stefan-jansen / pyfolio-reloaded

Portfolio and risk analytics in Python
https://pyfolio.ml4trading.io/
Apache License 2.0
321 stars 103 forks source link

the axis.py report "matplotlib.units.ConversionError:" when call pf.create_full_tear_sheet #41

Open zwd163 opened 6 months ago

zwd163 commented 6 months ago

Problem Description

always raise exception when create_full_tear_sheet called. Please provide a minimal, self-contained, and reproducible example:

[Paste code here]

import backtrader as bt import pyfolio as pf .... results = cb.run(runonce=True, preload=True, oldsync=True) st0 = results[0]

pyfoliozer = st0.analyzers.getbyname('pyfolio') returns, positions, transactions, _ = pyfoliozer.get_pf_items() pf.create_full_tear_sheet( returns, positions=positions, transactions=transactions, live_start_date=live_start_date # This date is used to determine the

periods included in plotting

    )

..env\Lib\site-packages\pyfolio\plotting.py:

def plot_drawdown_periods(returns, top=10, ax=None, **kwargs): """ Plots cumulative returns highlighting top drawdown periods.

Parameters
----------
returns : pd.Series
    Daily returns of the strategy, noncumulative.
     - See full explanation in tears.create_full_tear_sheet.
top : int, optional
    Amount of top drawdowns periods to plot (default 10).
ax : matplotlib.Axes, optional
    Axes upon which to plot.
**kwargs, optional
    Passed to plotting function.

Returns
-------
ax : matplotlib.Axes
    The axes that were plotted on.
"""

if ax is None:
    ax = plt.gca()

y_axis_formatter = FuncFormatter(utils.two_dec_places)
ax.yaxis.set_major_formatter(FuncFormatter(y_axis_formatter))

df_cum_rets = ep.cum_returns(returns, starting_value=1.0)
df_drawdowns = timeseries.gen_drawdown_table(returns, top=top)

df_cum_rets.plot(ax=ax, **kwargs)

lim = ax.get_ylim()
colors = sns.cubehelix_palette(len(df_drawdowns))[::-1]
for i, (peak, recovery) in df_drawdowns[["Peak date", "Recovery date"]].iterrows():
    if pd.isnull(recovery):
        recovery = returns.index[-1]
    #fix bug when peak is the last day of the series 
    if pd.isnull(peak): #<=== fixed
        continue
    ax.fill_between((peak, recovery), lim[0], lim[1], alpha=0.4, color=colors[i])
ax.set_ylim(lim)
ax.set_title("Top %i drawdown periods" % top)
ax.set_ylabel("Cumulative returns")
ax.legend(["Portfolio"], loc="upper left", frameon=True, framealpha=0.5)
ax.set_xlabel("")
return ax

Please provide the full traceback:

[Paste traceback here]

Exception has occurred: ConversionError (note: full exception trace is shown but execution is paused at: _run_module_as_main) Failed to convert value(s) to axis units: (NaT, Timestamp('2022-04-30 00:00:00+0000', tz='UTC')) File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib\axis.py", line 1769, in convert_units ret = self.converter.convert(x, self.units, self) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\pandas\plotting_matplotlib\converter.py", line 239, in convert values = PeriodConverter._convert_1d(values, units, axis) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\pandas\plotting_matplotlib\converter.py", line 269, in _convert_1d return [get_datevalue(x, axis.freq) for x in values] ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\pandas\plotting_matplotlib\converter.py", line 269, in return [get_datevalue(x, axis.freq) for x in values] ^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\pandas\plotting_matplotlib\converter.py", line 277, in get_datevalue return Period(date, freq).ordinal ^^^^^^^^^^^^^^^^^^^^^^^^^^ AttributeError: 'NaTType' object has no attribute 'ordinal'

The above exception was the direct cause of the following exception:

File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib\axis.py", line 1771, in convert_units raise munits.ConversionError('Failed to convert value(s) to axis ' File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib\axes_base.py", line 2573, in return [axis_map[axis_name].convert_units(data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib\axes_base.py", line 2573, in _process_unit_info return [axis_map[axis_name].convert_units(data) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib\axes_axes.py", line 5410, in _fill_between_x_or_y ma.masked_invalid, self._process_unit_info( ^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib\axes_axes.py", line 5509, in fill_between return self._fill_between_x_or_y( ^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\matplotlib__init.py", line 1478, in inner return func(ax, *map(sanitize_sequence, args), *kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\pyfolio\plotting.py", line 450, in plot_drawdown_periods ax.fill_between((peak, recovery), lim[0], lim[1], alpha=0.4, color=colors[i]) File "D:\work\github\backtrader.env\Lib\site-packages\pyfolio\tears.py", line 630, in create_returns_tear_sheet plotting.plot_drawdown_periods(returns, top=5, ax=ax_drawdown) File "D:\work\github\backtrader.env\Lib\site-packages\pyfolio\plotting.py", line 51, in call_w_context return func(args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^ File "D:\work\github\backtrader.env\Lib\site-packages\pyfolio\tears.py", line 199, in create_full_tear_sheet create_returns_tear_sheet( File "D:\work\github\backtrader\mystrategy\bot_main.py", line 197, in pf.create_full_tear_sheet( File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64qbz5n2kfra8p0\Lib\runpy.py", line 88, in _run_code exec(code, run_globals) File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.11_3.11.2032.0_x64__qbz5n2kfra8p0\Lib\runpy.py", line 198, in _run_module_as_main (Current frame) return _run_code(code, main_globals, None, ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ matplotlib.units.ConversionError: Failed to convert value(s) to axis units: (NaT, Timestamp('2022-04-30 00:00:00+0000', tz='UTC'))

Please provide any additional information below:

Versions

vinicius-vargas commented 5 months ago

Same problem here.