pyfolio
pyfolio copied to clipboard
Returns with zeros, NAs, etc
Problem Description
Trying to determine how to deal with returns series that contain 0s and/or missing values. Transforming dollar returns to decimal returns creates NAs, and sometimes +/- infinities, if your dollar returns have 0s. The documentation specifies that returns should be a pandas series of decimal returns, but I haven't been able to find guidance on what to do when 0s, NAs, or infinities are present.
Please provide a minimal, self-contained, and reproducible example:
import pandas as pd
import numpy as np
import pyfolio as py
# retrieve and prepare returns data
url_algo = 'https://raw.githubusercontent.com/JoeOD/pyfolio-example-data/master/returns_amzn_with_zeros.csv'
backtest_load = pd.read_csv(url_algo, header=0, parse_dates=[0], index_col=0, squeeze=True)
backtest_cash_returns = backtest_load.to_frame()
backtest_dec_returns = backtest_cash_returns.pct_change(1)
backtest_dec_returns.index = backtest_dec_returns.index.tz_localize('utc')
# retrieve and prepare benchmark data
url_bench = 'https://raw.githubusercontent.com/JoeOD/pyfolio-example-data/master/rets_ind.csv'
benchmark_load = pd.read_csv(url_bench, header=0, parse_dates=[0], index_col=0, squeeze=True)
benchmark_cash_returns = benchmark_load.to_frame()
benchmark_dec_returns = benchmark_cash_returns.pct_change(1)
benchmark_dec_returns.index = benchmark_dec_returns.index.tz_localize('utc')
py.create_full_tear_sheet(returns=backtest_dec_returns['adjusted_close'].divide(100), benchmark_rets=benchmark_dec_returns['adjusted_close'].divide(100), live_start_date='2015-01-01')
Please provide the full traceback:
ValueError Traceback (most recent call last)
<ipython-input-100-654c2a90efb8> in <module>
15 benchmark_dec_returns.index = benchmark_dec_returns.index.tz_localize('utc')
16
---> 17 py.create_full_tear_sheet(returns=backtest_dec_returns['adjusted_close'].divide(100), benchmark_rets=benchmark_dec_returns['adjusted_close'].divide(100), live_start_date='2015-01-01')
~/anaconda3/lib/python3.7/site-packages/pyfolio/tears.py in create_full_tear_sheet(returns, positions, transactions, market_data, benchmark_rets, slippage, live_start_date, sector_mappings, bayesian, round_trips, estimate_intraday, hide_positions, cone_std, bootstrap, unadjusted_returns, style_factor_panel, sectors, caps, shares_held, volumes, percentile, turnover_denom, set_context, factor_returns, factor_loadings, pos_in_dollars, header_rows, factor_partitions)
220 turnover_denom=turnover_denom,
221 header_rows=header_rows,
--> 222 set_context=set_context)
223
224 create_interesting_times_tear_sheet(returns,
~/anaconda3/lib/python3.7/site-packages/pyfolio/plotting.py in call_w_context(*args, **kwargs)
50 if set_context:
51 with plotting_context(), axes_style():
---> 52 return func(*args, **kwargs)
53 else:
54 return func(*args, **kwargs)
~/anaconda3/lib/python3.7/site-packages/pyfolio/tears.py in create_returns_tear_sheet(returns, positions, transactions, live_start_date, cone_std, benchmark_rets, bootstrap, turnover_denom, header_rows, return_fig)
618
619 plotting.plot_rolling_volatility(
--> 620 returns, factor_returns=benchmark_rets, ax=ax_rolling_volatility)
621
622 plotting.plot_rolling_sharpe(
~/anaconda3/lib/python3.7/site-packages/pyfolio/plotting.py in plot_rolling_volatility(returns, factor_returns, rolling_window, legend_loc, ax, **kwargs)
928 returns, rolling_window)
929 rolling_vol_ts.plot(alpha=.7, lw=3, color='orangered', ax=ax,
--> 930 **kwargs)
931 if factor_returns is not None:
932 rolling_vol_ts_factor = timeseries.rolling_volatility(
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in __call__(self, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
2739 colormap=colormap, table=table, yerr=yerr,
2740 xerr=xerr, label=label, secondary_y=secondary_y,
-> 2741 **kwds)
2742 __call__.__doc__ = plot_series.__doc__
2743
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in plot_series(data, kind, ax, figsize, use_index, title, grid, legend, style, logx, logy, loglog, xticks, yticks, xlim, ylim, rot, fontsize, colormap, table, yerr, xerr, label, secondary_y, **kwds)
2000 yerr=yerr, xerr=xerr,
2001 label=label, secondary_y=secondary_y,
-> 2002 **kwds)
2003
2004
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in _plot(data, x, y, subplots, ax, kind, **kwds)
1802 plot_obj = klass(data, subplots=subplots, ax=ax, kind=kind, **kwds)
1803
-> 1804 plot_obj.generate()
1805 plot_obj.draw()
1806 return plot_obj.result
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in generate(self)
261 self._add_table()
262 self._make_legend()
--> 263 self._adorn_subplots()
264
265 for ax in self.axes:
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_core.py in _adorn_subplots(self)
435 naxes=nrows * ncols, nrows=nrows,
436 ncols=ncols, sharex=self.sharex,
--> 437 sharey=self.sharey)
438
439 for ax in self.axes:
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_tools.py in _handle_shared_axes(axarr, nplots, naxes, nrows, ncols, sharex, sharey)
316 if sharex or len(ax.get_shared_x_axes()
317 .get_siblings(ax)) > 1:
--> 318 _remove_labels_from_axis(ax.xaxis)
319
320 except IndexError:
~/anaconda3/lib/python3.7/site-packages/pandas/plotting/_tools.py in _remove_labels_from_axis(axis)
279
280 def _remove_labels_from_axis(axis):
--> 281 for t in axis.get_majorticklabels():
282 t.set_visible(False)
283
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in get_majorticklabels(self)
1238 def get_majorticklabels(self):
1239 'Return a list of Text instances for the major ticklabels'
-> 1240 ticks = self.get_major_ticks()
1241 labels1 = [tick.label1 for tick in ticks if tick.label1On]
1242 labels2 = [tick.label2 for tick in ticks if tick.label2On]
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in get_major_ticks(self, numticks)
1389 'get the tick instances; grow as necessary'
1390 if numticks is None:
-> 1391 numticks = len(self.get_major_locator()())
1392
1393 while len(self.majorTicks) < numticks:
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in __call__(self)
1228 def __call__(self):
1229 'Return the locations of the ticks'
-> 1230 self.refresh()
1231 return self._locator()
1232
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in refresh(self)
1248 def refresh(self):
1249 'Refresh internal information based on current limits.'
-> 1250 dmin, dmax = self.viewlim_to_dt()
1251 self._locator = self.get_locator(dmin, dmax)
1252
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
999 'often happens if you pass a non-datetime '
1000 'value to an axis that has datetime units'
-> 1001 .format(vmin))
1002 return num2date(vmin, self.tz), num2date(vmax, self.tz)
1003
ValueError: view limit minimum -0.001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
Error in callback <function install_repl_displayhook.<locals>.post_execute at 0x7febeab43488> (for post_execute):
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/matplotlib/pyplot.py in post_execute()
107 def post_execute():
108 if matplotlib.is_interactive():
--> 109 draw_all()
110
111 # IPython >= 2
~/anaconda3/lib/python3.7/site-packages/matplotlib/_pylab_helpers.py in draw_all(cls, force)
130 for f_mgr in cls.get_all_fig_managers():
131 if force or f_mgr.canvas.figure.stale:
--> 132 f_mgr.canvas.draw_idle()
133
134 atexit.register(Gcf.destroy_all)
~/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in draw_idle(self, *args, **kwargs)
1897 if not self._is_idle_drawing:
1898 with self._idle_draw_cntx():
-> 1899 self.draw(*args, **kwargs)
1900
1901 def draw_cursor(self, event):
~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
400 toolbar = self.toolbar
401 try:
--> 402 self.figure.draw(self.renderer)
403 # A GUI class may be need to update a window using this draw, so
404 # don't forget to call the superclass.
~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
48 renderer.start_filter()
49
---> 50 return draw(artist, renderer, *args, **kwargs)
51 finally:
52 if artist.get_agg_filter() is not None:
~/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
1647
1648 mimage._draw_list_compositing_images(
-> 1649 renderer, self, artists, self.suppressComposite)
1650
1651 renderer.close_group('figure')
~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
136 if not_composite or not has_images:
137 for a in artists:
--> 138 a.draw(renderer)
139 else:
140 # Composite any adjacent images together
~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
48 renderer.start_filter()
49
---> 50 return draw(artist, renderer, *args, **kwargs)
51 finally:
52 if artist.get_agg_filter() is not None:
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2626 renderer.stop_rasterizing()
2627
-> 2628 mimage._draw_list_compositing_images(renderer, self, artists)
2629
2630 renderer.close_group('axes')
~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
136 if not_composite or not has_images:
137 for a in artists:
--> 138 a.draw(renderer)
139 else:
140 # Composite any adjacent images together
~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
48 renderer.start_filter()
49
---> 50 return draw(artist, renderer, *args, **kwargs)
51 finally:
52 if artist.get_agg_filter() is not None:
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
1183 renderer.open_group(__name__)
1184
-> 1185 ticks_to_draw = self._update_ticks(renderer)
1186 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1187 renderer)
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
1021
1022 interval = self.get_view_interval()
-> 1023 tick_tups = list(self.iter_ticks()) # iter_ticks calls the locator
1024 if self._smart_bounds and tick_tups:
1025 # handle inverted limits
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in iter_ticks(self)
965 Iterate through all of the major and minor ticks.
966 """
--> 967 majorLocs = self.major.locator()
968 majorTicks = self.get_major_ticks(len(majorLocs))
969 self.major.formatter.set_locs(majorLocs)
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in __call__(self)
1228 def __call__(self):
1229 'Return the locations of the ticks'
-> 1230 self.refresh()
1231 return self._locator()
1232
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in refresh(self)
1248 def refresh(self):
1249 'Refresh internal information based on current limits.'
-> 1250 dmin, dmax = self.viewlim_to_dt()
1251 self._locator = self.get_locator(dmin, dmax)
1252
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
999 'often happens if you pass a non-datetime '
1000 'value to an axis that has datetime units'
-> 1001 .format(vmin))
1002 return num2date(vmin, self.tz), num2date(vmax, self.tz)
1003
ValueError: view limit minimum -0.001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
~/anaconda3/lib/python3.7/site-packages/IPython/core/formatters.py in __call__(self, obj)
339 pass
340 else:
--> 341 return printer(obj)
342 # Finally look for special method names
343 method = get_real_method(obj, self.print_method)
~/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in <lambda>(fig)
242
243 if 'png' in formats:
--> 244 png_formatter.for_type(Figure, lambda fig: print_figure(fig, 'png', **kwargs))
245 if 'retina' in formats or 'png2x' in formats:
246 png_formatter.for_type(Figure, lambda fig: retina_figure(fig, **kwargs))
~/anaconda3/lib/python3.7/site-packages/IPython/core/pylabtools.py in print_figure(fig, fmt, bbox_inches, **kwargs)
126
127 bytes_io = BytesIO()
--> 128 fig.canvas.print_figure(bytes_io, **kw)
129 data = bytes_io.getvalue()
130 if fmt == 'svg':
~/anaconda3/lib/python3.7/site-packages/matplotlib/backend_bases.py in print_figure(self, filename, dpi, facecolor, edgecolor, orientation, format, bbox_inches, **kwargs)
2047 orientation=orientation,
2048 dryrun=True,
-> 2049 **kwargs)
2050 renderer = self.figure._cachedRenderer
2051 bbox_artists = kwargs.pop("bbox_extra_artists", None)
~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in print_png(self, filename_or_obj, *args, **kwargs)
508
509 """
--> 510 FigureCanvasAgg.draw(self)
511 renderer = self.get_renderer()
512
~/anaconda3/lib/python3.7/site-packages/matplotlib/backends/backend_agg.py in draw(self)
400 toolbar = self.toolbar
401 try:
--> 402 self.figure.draw(self.renderer)
403 # A GUI class may be need to update a window using this draw, so
404 # don't forget to call the superclass.
~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
48 renderer.start_filter()
49
---> 50 return draw(artist, renderer, *args, **kwargs)
51 finally:
52 if artist.get_agg_filter() is not None:
~/anaconda3/lib/python3.7/site-packages/matplotlib/figure.py in draw(self, renderer)
1647
1648 mimage._draw_list_compositing_images(
-> 1649 renderer, self, artists, self.suppressComposite)
1650
1651 renderer.close_group('figure')
~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
136 if not_composite or not has_images:
137 for a in artists:
--> 138 a.draw(renderer)
139 else:
140 # Composite any adjacent images together
~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
48 renderer.start_filter()
49
---> 50 return draw(artist, renderer, *args, **kwargs)
51 finally:
52 if artist.get_agg_filter() is not None:
~/anaconda3/lib/python3.7/site-packages/matplotlib/axes/_base.py in draw(self, renderer, inframe)
2626 renderer.stop_rasterizing()
2627
-> 2628 mimage._draw_list_compositing_images(renderer, self, artists)
2629
2630 renderer.close_group('axes')
~/anaconda3/lib/python3.7/site-packages/matplotlib/image.py in _draw_list_compositing_images(renderer, parent, artists, suppress_composite)
136 if not_composite or not has_images:
137 for a in artists:
--> 138 a.draw(renderer)
139 else:
140 # Composite any adjacent images together
~/anaconda3/lib/python3.7/site-packages/matplotlib/artist.py in draw_wrapper(artist, renderer, *args, **kwargs)
48 renderer.start_filter()
49
---> 50 return draw(artist, renderer, *args, **kwargs)
51 finally:
52 if artist.get_agg_filter() is not None:
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in draw(self, renderer, *args, **kwargs)
1183 renderer.open_group(__name__)
1184
-> 1185 ticks_to_draw = self._update_ticks(renderer)
1186 ticklabelBoxes, ticklabelBoxes2 = self._get_tick_bboxes(ticks_to_draw,
1187 renderer)
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in _update_ticks(self, renderer)
1021
1022 interval = self.get_view_interval()
-> 1023 tick_tups = list(self.iter_ticks()) # iter_ticks calls the locator
1024 if self._smart_bounds and tick_tups:
1025 # handle inverted limits
~/anaconda3/lib/python3.7/site-packages/matplotlib/axis.py in iter_ticks(self)
965 Iterate through all of the major and minor ticks.
966 """
--> 967 majorLocs = self.major.locator()
968 majorTicks = self.get_major_ticks(len(majorLocs))
969 self.major.formatter.set_locs(majorLocs)
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in __call__(self)
1228 def __call__(self):
1229 'Return the locations of the ticks'
-> 1230 self.refresh()
1231 return self._locator()
1232
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in refresh(self)
1248 def refresh(self):
1249 'Refresh internal information based on current limits.'
-> 1250 dmin, dmax = self.viewlim_to_dt()
1251 self._locator = self.get_locator(dmin, dmax)
1252
~/anaconda3/lib/python3.7/site-packages/matplotlib/dates.py in viewlim_to_dt(self)
999 'often happens if you pass a non-datetime '
1000 'value to an axis that has datetime units'
-> 1001 .format(vmin))
1002 return num2date(vmin, self.tz), num2date(vmax, self.tz)
1003
ValueError: view limit minimum -0.001 is less than 1 and is an invalid Matplotlib date value. This often happens if you pass a non-datetime value to an axis that has datetime units
<Figure size 1008x5616 with 13 Axes>
Please provide any additional information below:
When I try to run the code with returns that have had the zeros removed, it runs, but it produces an output that doesn't make sense. Here's code for that:
import pandas as pd
import numpy as np
import pyfolio as py
url_algo = 'https://raw.githubusercontent.com/JoeOD/pyfolio-example-data/master/returns_amzn_without_zeros.csv'
backtest_load = pd.read_csv(url_algo, header=0, parse_dates=[0], index_col=0, squeeze=True)
backtest_cash_returns = backtest_load.to_frame()
backtest_dec_returns = backtest_cash_returns.pct_change(1)
backtest_dec_returns.index = backtest_dec_returns.index.tz_localize('utc')
url_bench = 'https://raw.githubusercontent.com/JoeOD/pyfolio-example-data/master/rets_ind.csv'
benchmark_load = pd.read_csv(url_bench, header=0, parse_dates=[0], index_col=0, squeeze=True)
benchmark_cash_returns = benchmark_load.to_frame()
benchmark_dec_returns = benchmark_cash_returns.pct_change(1)
benchmark_dec_returns.index = benchmark_dec_returns.index.tz_localize('utc')
py.create_full_tear_sheet(returns=backtest_dec_returns['adjusted_close'].divide(100), benchmark_rets=benchmark_dec_returns['adjusted_close'].divide(100), live_start_date='2015-01-01')
Versions
- Pyfolio version: pyfolio==0.9.0
- Python version: 3.7.1
- Pandas version: pandas==0.23.4 pandas-datareader==0.7.0
- Matplotlib version: matplotlib==3.0.2
Thanks