Giter VIP home page Giter VIP logo

Comments (2)

Snowhit3 avatar Snowhit3 commented on May 12, 2024

I have managed to fix the issue by changing yearly_returns() in wrappers.py as follows (replace returns.index with 'max'):

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, 'max').resample('A').apply(_stats.compsum).resample('A').last()

This fixes the EOY returns plot, but the remaining charts are still missing the benchmark (only the strategy is shown). The only error I get is:

/home/none/miniconda3/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:2023: RuntimeWarning: invalid value encountered in multiply
  lower_bound = _a * scale + loc
/home/none/miniconda3/lib/python3.6/site-packages/scipy/stats/_distn_infrastructure.py:2024: RuntimeWarning: invalid value encountered in multiply
  upper_bound = _b * scale + loc
/home/none/miniconda3/lib/python3.6/site-packages/quantstats/stats.py:633: RuntimeWarning: invalid value encountered in double_scalars
  beta = matrix[0, 1] / matrix[1, 1]
findfont: Font family ['Arial'] not found. Falling back to DejaVu Sans.
Report for /home/none/main.json generated

from quantstats.

Snowhit3 avatar Snowhit3 commented on May 12, 2024

To fix the cumulative return charts I've edited _prepare_benchmark() in utils.py as follows:

def _prepare_benchmark(benchmark=None, period="max", rf=0.):
    """
    fetch benchmark if ticker is provided, and pass through
    _prepare_returns()

    period can be options or (expected) _pd.DatetimeIndex range
    """
    if benchmark is None:
        return None

    if isinstance(benchmark, str):
        benchmark = download_returns(benchmark)

    elif isinstance(benchmark, _pd.DataFrame):
        benchmark = benchmark[benchmark.columns[0]].copy()

    if isinstance(period, _pd.DatetimeIndex):
        benchmark = benchmark[~benchmark.index.duplicated()]
        condition = [x and y for x,y in zip(benchmark.index >= min(period), benchmark.index <= max(period))]
        benchmark = benchmark[condition]
        
    return _prepare_returns(benchmark.dropna(), rf=rf)

To fix the rolling beta charts I edited rolling_greeks() in stats.py as follows:

def rolling_greeks(returns, benchmark, periods=252):
    """ calculates rolling alpha and beta of the portfolio """
    df = _pd.DataFrame(data={
        "returns": _utils._prepare_returns(returns),
        "benchmark": _utils._prepare_benchmark(benchmark, returns.index)
    })
    df = df.fillna(0)
    corr = df.rolling(int(periods)).corr().unstack()['returns']['benchmark']
    std = df.rolling(int(periods)).std()
    beta = corr * std['returns'] / std['benchmark']

    alpha = df['returns'].mean() - beta * df['benchmark'].mean()

    # alpha = alpha * periods
    return _pd.DataFrame(index=returns.index, data={
        "beta": beta,
        "alpha": alpha
    }).fillna(0)

I also experienced other error messages when using a benchmark. They all got fixed by resampling the input returns and benchmark pandas Series before passing them to quantstats as follows:

_returns = _returns.resample('D').last()
_benchmark = _benchmark.resample('D').last()

The major drawback with doing this is that the Time in market metric is not reliable anymore

from quantstats.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.