Comments (2)
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.
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)
- positions versus return
- Problems with time dependent risk free rate
- Error - win_year / periods_per_year not passed to CAGR function HOT 2
- stats.py FutureWarning with DataFrame.prod HOT 1
- Futures Data (CME, EUREX, etc) HOT 1
- qs.reports.metrics() and qs.reports.full() give different results using same data HOT 1
- reports break
- NaN Handling HOT 1
- CAGR is not accurate - need to update to take the HOT 5
- Quantstats.reports.metrics would be nice to have last date stats for Drawdown HOT 1
- Plots don't display when using matplotlib backend qt HOT 1
- Is this project **ABANDONED** ? HOT 1
- Asset Wise Transaction List - Profit Loss Account
- Incompatibility with AWS Lambda
- TypeError: unsupported operand type(s) for +: 'float' and 'str' HOT 3
- Warings about pd.to_timedelta
- 'TypeError: super(type, obj): obj must be an instance or subtype of type' in the super() function of reports.html HOT 1
- stats.py: res = abs(total + 1.0) ** (1.0 / years) - 1 <-- ZeroDivisionErrorZeroDivisionError HOT 1
- Deprecated code in stats.py expected_return()
- Calculation of 3Y and 5Y annualized return date lag
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from quantstats.