Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
zwd163 opened this issue Jan 16, 2024 · 1 comment

Comments

@zwd163
Copy link

zwd163 commented Jan 16, 2024

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_x64__qbz5n2kfra8p0\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

  • Pyfolio version: pyfolio-reloaded==0.9.5
  • Python version: Python 3.11.7
  • Pandas version: pandas==2.1.4
  • Matplotlib version: matplotlib==3.8.2
@vinicius-vargas
Copy link

Same problem here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants