How to use the quantstats.utils._prepare_benchmark function in QuantStats

To help you get started, we’ve selected a few QuantStats examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github ranaroussi / quantstats / quantstats / stats.py View on Github external
def greeks(returns, benchmark, periods=252.):
    """ calculates alpha and beta of the portfolio """

    # ----------------------------
    # data cleanup
    returns = _utils._prepare_returns(returns)
    benchmark = _utils._prepare_benchmark(benchmark, returns.index)
    # ----------------------------

    # find covariance
    matrix = _np.cov(returns, benchmark)
    beta = matrix[0, 1] / matrix[1, 1]

    # calculates measures now
    alpha = returns.mean() - beta * benchmark.mean()
    alpha = alpha * periods

    return _pd.Series({
        "beta":  beta,
        "alpha": alpha,
        # "vol": _np.sqrt(matrix[0, 0]) * _np.sqrt(periods)
    }).fillna(0)
github ranaroussi / quantstats / quantstats / _plotting / wrappers.py View on Github external
def rolling_sortino(returns, benchmark=None, rf=0.,
                    period=126, period_label="6-Months",
                    lw=1.25, fontname='Arial', grayscale=False,
                    figsize=(10, 3), ylabel="Sortino",
                    subtitle=True, savefig=None, show=True):

    returns = _utils._prepare_returns(returns, rf)
    returns = returns.rolling(period).mean() / \
        returns[returns < 0].rolling(period).std()
    returns = returns * _np.sqrt(1 if period is None else period)

    if benchmark is not None:
        benchmark = _utils._prepare_benchmark(benchmark, returns.index, rf)
        benchmark = benchmark.rolling(period).mean() / benchmark[
            benchmark < 0].rolling(period).std()
        benchmark = benchmark * _np.sqrt(1 if period is None else period)

    _core.plot_rolling_stats(returns, benchmark,
                             hline=returns.mean(),
                             hlw=1.5,
                             ylabel=ylabel,
                             title='Rolling Sortino (%s)' % period_label,
                             fontname=fontname,
                             grayscale=grayscale,
                             lw=lw,
                             figsize=figsize,
                             subtitle=subtitle, savefig=savefig, show=show)
github ranaroussi / quantstats / quantstats / stats.py View on Github external
def compare(returns, benchmark, aggregate=None, compounded=True,
            round_vals=None):
    """
    compare returns to benchmark on a
    day/week/month/quarter/year basis
    """
    returns = _utils._prepare_returns(returns)
    benchmark = _utils._prepare_benchmark(benchmark, returns.index)

    data = _pd.DataFrame(data={
        'Benchmark': _utils.aggregate_returns(
            benchmark, aggregate, compounded) * 100,
        'Returns': _utils.aggregate_returns(
            returns, aggregate, compounded) * 100
    })

    data['Multiplier'] = data['Returns'] / data['Benchmark']
    data['Won'] = _np.where(data['Returns'] >= data['Benchmark'], '+', '-')

    if round_vals is not None:
        return _np.round(data, round_vals)

    return data
github ranaroussi / quantstats / quantstats / _plotting / wrappers.py View on Github external
def yearly_returns(returns, benchmark=None,
                   fontname='Arial', grayscale=False,
                   hlw=1.5, hlcolor="red", hllabel="",
                   match_volatility=False,
                   log_scale=False, figsize=(10, 5), ylabel=True,
                   subtitle=True, compounded=True,
                   savefig=None, show=True):

    title = 'EOY Returns'
    if benchmark is not None:
        title += '  vs Benchmark'
        benchmark = _utils._prepare_benchmark(
            benchmark, returns.index).resample('A').apply(
                _stats.compsum).resample('A').last()

    returns = _utils._prepare_returns(returns).resample('A')
    if compounded:
        returns = returns.apply(_stats.compsum)
    else:
        returns = returns.apply(_df.cumsum)
    returns = returns.resample('A').last()

    _core.plot_returns_bars(returns, benchmark,
                            fontname=fontname,
                            hline=returns.mean(),
                            hlw=hlw,
                            hllabel=hllabel,
                            hlcolor=hlcolor,
github ranaroussi / quantstats / quantstats / _plotting / wrappers.py View on Github external
subtitle=True, savefig=None, show=True):

    title = 'Cumulative Returns' if compound else 'Returns'
    if benchmark is not None:
        if isinstance(benchmark, str):
            title += ' vs %s (Log Scaled' % benchmark.upper()
        else:
            title += ' vs Benchmark (Log Scaled'
        if match_volatility:
            title += ', Volatility Matched'
    else:
        title += ' (Log Scaled'
    title += ')'

    returns = _utils._prepare_returns(returns)
    benchmark = _utils._prepare_benchmark(benchmark, returns.index)

    _core.plot_timeseries(returns, benchmark, title,
                          ylabel=ylabel,
                          match_volatility=match_volatility,
                          log_scale=True,
                          resample=resample,
                          compound=compound,
                          cumulative=cumulative,
                          lw=lw,
                          figsize=figsize,
                          fontname=fontname,
                          grayscale=grayscale,
                          subtitle=subtitle, savefig=savefig, show=show)
github ranaroussi / quantstats / quantstats / _plotting / wrappers.py View on Github external
fontname='Arial', lw=1.5,
            match_volatility=False, compound=True, cumulative=True,
            resample=None, ylabel="Cumulative Returns",
            subtitle=True, savefig=None, show=True):

    title = 'Cumulative Returns' if compound else 'Returns'
    if benchmark is not None:
        if isinstance(benchmark, str):
            title += ' vs %s' % benchmark.upper()
        else:
            title += ' vs Benchmark'
        if match_volatility:
            title += ' (Volatility Matched)'

    returns = _utils._prepare_returns(returns)
    benchmark = _utils._prepare_benchmark(benchmark, returns.index)

    _core.plot_timeseries(returns, benchmark, title,
                          ylabel=ylabel,
                          match_volatility=match_volatility,
                          log_scale=False,
                          resample=resample,
                          compound=compound,
                          cumulative=cumulative,
                          lw=lw,
                          figsize=figsize,
                          fontname=fontname,
                          grayscale=grayscale,
                          subtitle=subtitle, savefig=savefig, show=show)
github ranaroussi / quantstats / quantstats / stats.py View on Github external
def information_ratio(returns, benchmark):
    """
    calculates the information ratio
    (basically the risk return ratio of the net profits)
    """
    diff_rets = _utils._prepare_returns(returns) - \
        _utils._prepare_benchmark(benchmark, returns.index)

    return diff_rets.mean() / diff_rets.std()
github ranaroussi / quantstats / quantstats / reports.py View on Github external
mode='basic', sep=False, compounded=True, **kwargs):

    if isinstance(returns, _pd.DataFrame) and len(returns.columns) > 1:
        raise ValueError("`returns` must be a pandas Series, "
                         "but a multi-column DataFrame was passed")

    if benchmark is not None:
        if isinstance(returns, _pd.DataFrame) and len(returns.columns) > 1:
            raise ValueError("`benchmark` must be a pandas Series, "
                             "but a multi-column DataFrame was passed")

    blank = ['']
    df = _pd.DataFrame({"returns": _utils._prepare_returns(returns, rf)})
    if benchmark is not None:
        blank = ['', '']
        df["benchmark"] = _utils._prepare_benchmark(
            benchmark, returns.index, rf)

    df = df.fillna(0)

    # pct multiplier
    pct = 100 if display or "internal" in kwargs else 1

    # return df
    dd = _calc_dd(df, display=(display or "internal" in kwargs))

    metrics = _pd.DataFrame()

    s_start = {'returns': df['returns'].index.strftime('%Y-%m-%d')[0]}
    s_end = {'returns': df['returns'].index.strftime('%Y-%m-%d')[-1]}
    s_rf = {'returns': rf}
github ranaroussi / quantstats / quantstats / _plotting / wrappers.py View on Github external
def rolling_sharpe(returns, benchmark=None, rf=0.,
                   period=126, period_label="6-Months",
                   lw=1.25, fontname='Arial', grayscale=False,
                   figsize=(10, 3), ylabel="Sharpe",
                   subtitle=True, savefig=None, show=True):

    returns = _utils._prepare_returns(returns, rf)
    returns = returns.rolling(period).mean() / returns.rolling(period).std()
    returns = returns * _np.sqrt(1 if period is None else period)

    if benchmark is not None:
        benchmark = _utils._prepare_benchmark(benchmark, returns.index, rf)
        benchmark = benchmark.rolling(
            period).mean() / benchmark.rolling(period).std()
        benchmark = benchmark * _np.sqrt(1 if period is None else period)

    _core.plot_rolling_stats(returns, benchmark,
                             hline=returns.mean(),
                             hlw=1.5,
                             ylabel=ylabel,
                             title='Rolling Sharpe (%s)' % period_label,
                             fontname=fontname,
                             grayscale=grayscale,
                             lw=lw,
                             figsize=figsize,
                             subtitle=subtitle, savefig=savefig, show=show)