quantstats-pro 0.4.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- quantstats/__init__.py +163 -0
- quantstats/_compat.py +431 -0
- quantstats/_montecarlo.py +296 -0
- quantstats/_numpy_compat.py +289 -0
- quantstats/_plotting/__init__.py +0 -0
- quantstats/_plotting/core.py +2173 -0
- quantstats/_plotting/wrappers.py +2109 -0
- quantstats/_reporting/__init__.py +12 -0
- quantstats/_reporting/engine.py +37 -0
- quantstats/_reporting/sections.py +223 -0
- quantstats/alphadecay/__init__.py +25 -0
- quantstats/alphadecay/core.py +712 -0
- quantstats/alphadecay/plotting.py +206 -0
- quantstats/montecarlo/__init__.py +34 -0
- quantstats/montecarlo/analytics.py +291 -0
- quantstats/montecarlo/base.py +92 -0
- quantstats/montecarlo/core.py +175 -0
- quantstats/montecarlo/models/__init__.py +15 -0
- quantstats/montecarlo/models/bayesian.py +88 -0
- quantstats/montecarlo/models/block_bootstrap.py +108 -0
- quantstats/montecarlo/models/bootstrap.py +38 -0
- quantstats/montecarlo/models/garch.py +83 -0
- quantstats/montecarlo/models/gbm.py +44 -0
- quantstats/montecarlo/models/heston.py +103 -0
- quantstats/montecarlo/models/jump_diffusion.py +86 -0
- quantstats/montecarlo/models/shuffle.py +49 -0
- quantstats/montecarlo/models/trimmed.py +50 -0
- quantstats/montecarlo/plotting.py +324 -0
- quantstats/montecarlo/registry.py +34 -0
- quantstats/plots.py +27 -0
- quantstats/py.typed +0 -0
- quantstats/report.html +64 -0
- quantstats/report_alpha_decay.html +43 -0
- quantstats/report_montecarlo.html +62 -0
- quantstats/report_simple.html +58 -0
- quantstats/reports.py +3502 -0
- quantstats/stats.py +3321 -0
- quantstats/utils.py +1011 -0
- quantstats/version.py +1 -0
- quantstats_pro-0.4.1.dist-info/METADATA +509 -0
- quantstats_pro-0.4.1.dist-info/RECORD +43 -0
- quantstats_pro-0.4.1.dist-info/WHEEL +4 -0
- quantstats_pro-0.4.1.dist-info/licenses/LICENSE.txt +202 -0
|
@@ -0,0 +1,2109 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
#
|
|
3
|
+
# Quantreturns: Portfolio analytics for quants
|
|
4
|
+
# https://github.com/ranaroussi/quantreturns
|
|
5
|
+
#
|
|
6
|
+
# Copyright 2019-2025 Ran Aroussi
|
|
7
|
+
#
|
|
8
|
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
9
|
+
# you may not use this file except in compliance with the License.
|
|
10
|
+
# You may obtain a copy of the License at
|
|
11
|
+
#
|
|
12
|
+
# http://www.apache.org/licenses/LICENSE-2.0
|
|
13
|
+
#
|
|
14
|
+
# Unless required by applicable law or agreed to in writing, software
|
|
15
|
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
16
|
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
17
|
+
# See the License for the specific language governing permissions and
|
|
18
|
+
# limitations under the License.
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import warnings
|
|
23
|
+
from typing import TYPE_CHECKING, Any
|
|
24
|
+
|
|
25
|
+
import matplotlib.pyplot as _plt
|
|
26
|
+
import numpy as _np
|
|
27
|
+
import pandas as _pd
|
|
28
|
+
import seaborn as _sns
|
|
29
|
+
from matplotlib.ticker import (
|
|
30
|
+
FuncFormatter as _FuncFormatter,
|
|
31
|
+
)
|
|
32
|
+
from matplotlib.ticker import (
|
|
33
|
+
StrMethodFormatter as _StrMethodFormatter,
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
from .._compat import safe_resample
|
|
37
|
+
|
|
38
|
+
# Lazy imports to avoid circular dependency during package initialization
|
|
39
|
+
# These modules are imported when first accessed via _get_stats() and _get_utils()
|
|
40
|
+
_stats = None
|
|
41
|
+
_utils = None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _get_stats():
|
|
45
|
+
global _stats
|
|
46
|
+
if _stats is None:
|
|
47
|
+
from .. import stats
|
|
48
|
+
_stats = stats
|
|
49
|
+
return _stats
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _get_utils():
|
|
53
|
+
global _utils
|
|
54
|
+
if _utils is None:
|
|
55
|
+
from .. import utils
|
|
56
|
+
_utils = utils
|
|
57
|
+
return _utils
|
|
58
|
+
|
|
59
|
+
import contextlib
|
|
60
|
+
|
|
61
|
+
from . import core as _core
|
|
62
|
+
|
|
63
|
+
if TYPE_CHECKING:
|
|
64
|
+
from matplotlib.figure import Figure as _Figure
|
|
65
|
+
|
|
66
|
+
# Type alias for return data (Series or DataFrame)
|
|
67
|
+
Returns = _pd.Series | _pd.DataFrame
|
|
68
|
+
|
|
69
|
+
_FLATUI_COLORS = ["#5c5c5c", "#6b9e00", "#af4b64", "#4fa487", "#9b59b6", "#808080"]
|
|
70
|
+
_GRAYSCALE_COLORS = (len(_FLATUI_COLORS) * ["black"]) + ["white"]
|
|
71
|
+
|
|
72
|
+
# Check if plotly is available for optional conversion functionality
|
|
73
|
+
_HAS_PLOTLY = False
|
|
74
|
+
try:
|
|
75
|
+
import plotly
|
|
76
|
+
|
|
77
|
+
_HAS_PLOTLY = True
|
|
78
|
+
except ImportError:
|
|
79
|
+
pass
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def to_plotly(fig: _Figure) -> _Figure:
|
|
83
|
+
"""
|
|
84
|
+
Convert a matplotlib figure to a Plotly interactive plot.
|
|
85
|
+
|
|
86
|
+
Parameters
|
|
87
|
+
----------
|
|
88
|
+
fig : matplotlib.figure.Figure
|
|
89
|
+
The matplotlib figure to convert to Plotly format.
|
|
90
|
+
|
|
91
|
+
Returns
|
|
92
|
+
-------
|
|
93
|
+
plotly.graph_objects.Figure or matplotlib.figure.Figure
|
|
94
|
+
Interactive Plotly figure if plotly is available, otherwise original figure.
|
|
95
|
+
|
|
96
|
+
Notes
|
|
97
|
+
-----
|
|
98
|
+
This function requires the plotly library to be installed. If plotly is not
|
|
99
|
+
available, the original matplotlib figure is returned unchanged.
|
|
100
|
+
"""
|
|
101
|
+
# Return original figure if plotly not available
|
|
102
|
+
if not _HAS_PLOTLY:
|
|
103
|
+
return fig
|
|
104
|
+
|
|
105
|
+
# Suppress warnings during conversion to avoid noise
|
|
106
|
+
with warnings.catch_warnings():
|
|
107
|
+
warnings.simplefilter("ignore")
|
|
108
|
+
# Convert matplotlib figure to plotly format
|
|
109
|
+
fig = plotly.tools.mpl_to_plotly(fig)
|
|
110
|
+
# Upload and display the interactive plot
|
|
111
|
+
return plotly.plotly.iplot(fig, filename="quantstats-plot", overwrite=True) # type: ignore
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def snapshot(
|
|
115
|
+
returns: Returns,
|
|
116
|
+
grayscale: bool = False,
|
|
117
|
+
figsize: tuple[float, float] = (10, 8),
|
|
118
|
+
title: str = "Portfolio Summary",
|
|
119
|
+
fontname: str = "Arial",
|
|
120
|
+
lw: float = 1.5,
|
|
121
|
+
mode: str = "comp",
|
|
122
|
+
subtitle: bool = True,
|
|
123
|
+
savefig: str | dict | None = None,
|
|
124
|
+
show: bool = True,
|
|
125
|
+
log_scale: bool = False,
|
|
126
|
+
**kwargs,
|
|
127
|
+
) -> _Figure | None:
|
|
128
|
+
"""
|
|
129
|
+
Generate a comprehensive portfolio performance snapshot with multiple subplots.
|
|
130
|
+
|
|
131
|
+
Parameters
|
|
132
|
+
----------
|
|
133
|
+
returns : pandas.Series or pandas.DataFrame
|
|
134
|
+
Daily returns data. If DataFrame with multiple columns, uses mean or specific column.
|
|
135
|
+
grayscale : bool, optional
|
|
136
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
137
|
+
figsize : tuple, optional
|
|
138
|
+
Figure size as (width, height) in inches (default: (10, 8)).
|
|
139
|
+
title : str, optional
|
|
140
|
+
Main title for the plot (default: "Portfolio Summary").
|
|
141
|
+
fontname : str, optional
|
|
142
|
+
Font family for text elements (default: "Arial").
|
|
143
|
+
lw : float, optional
|
|
144
|
+
Line width for plots (default: 1.5).
|
|
145
|
+
mode : str, optional
|
|
146
|
+
Calculation mode: "comp" for compound returns or "sum" for simple sum.
|
|
147
|
+
subtitle : bool, optional
|
|
148
|
+
Whether to show subtitle with date range and Sharpe ratio (default: True).
|
|
149
|
+
savefig : str or dict, optional
|
|
150
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
151
|
+
show : bool, optional
|
|
152
|
+
Whether to display the plot (default: True).
|
|
153
|
+
log_scale : bool, optional
|
|
154
|
+
Whether to use logarithmic scale for y-axes (default: False).
|
|
155
|
+
**kwargs : dict
|
|
156
|
+
Additional keyword arguments, including strategy_col for column selection.
|
|
157
|
+
|
|
158
|
+
Returns
|
|
159
|
+
-------
|
|
160
|
+
matplotlib.figure.Figure or None
|
|
161
|
+
Figure object if show=False, otherwise None.
|
|
162
|
+
|
|
163
|
+
Notes
|
|
164
|
+
-----
|
|
165
|
+
Creates a three-panel plot showing:
|
|
166
|
+
1. Cumulative returns over time
|
|
167
|
+
2. Drawdown periods
|
|
168
|
+
3. Daily returns distribution
|
|
169
|
+
"""
|
|
170
|
+
# Extract strategy column name from kwargs
|
|
171
|
+
strategy_colname = kwargs.get("strategy_col", "Strategy")
|
|
172
|
+
|
|
173
|
+
# Handle multi-column DataFrame input
|
|
174
|
+
multi_column = False
|
|
175
|
+
if isinstance(returns, _pd.Series):
|
|
176
|
+
returns.name = strategy_colname
|
|
177
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
178
|
+
if len(returns.columns) > 1:
|
|
179
|
+
# Check if specific strategy column exists
|
|
180
|
+
if strategy_colname in returns.columns:
|
|
181
|
+
returns = returns[strategy_colname]
|
|
182
|
+
else:
|
|
183
|
+
# Use mean of all columns if no specific column found
|
|
184
|
+
multi_column = True
|
|
185
|
+
returns = returns.mean(axis=1)
|
|
186
|
+
title = title + " (daily equal-weighted*)"
|
|
187
|
+
returns.columns = strategy_colname
|
|
188
|
+
|
|
189
|
+
# Select color scheme based on grayscale preference
|
|
190
|
+
colors = _GRAYSCALE_COLORS if grayscale else _FLATUI_COLORS
|
|
191
|
+
# Convert to portfolio format and calculate percentage changes
|
|
192
|
+
returns = _get_utils().make_portfolio(returns.dropna(), 1, mode).pct_change(fill_method=None).fillna(0)
|
|
193
|
+
|
|
194
|
+
# Use current figure size if not specified
|
|
195
|
+
if figsize is None:
|
|
196
|
+
size = list(_plt.gcf().get_size_inches())
|
|
197
|
+
figsize = (size[0], size[0] * 0.75)
|
|
198
|
+
|
|
199
|
+
# Create figure with three subplots: cumulative returns, drawdown, daily returns
|
|
200
|
+
fig, axes = _plt.subplots(
|
|
201
|
+
3, 1, sharex=True, figsize=figsize, gridspec_kw={"height_ratios": [3, 1, 1]}
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
# Add footnote for multi-column DataFrame explanation
|
|
205
|
+
if multi_column:
|
|
206
|
+
_plt.figtext(
|
|
207
|
+
0,
|
|
208
|
+
-0.05,
|
|
209
|
+
" * When a multi-column DataFrame is passed, the mean of all columns will be used as returns.\n"
|
|
210
|
+
" To change this behavior, use a pandas Series or pass the column name in the "
|
|
211
|
+
"`strategy_col` parameter.",
|
|
212
|
+
ha="left",
|
|
213
|
+
fontsize=11,
|
|
214
|
+
color="black",
|
|
215
|
+
alpha=0.6,
|
|
216
|
+
linespacing=1.5,
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
# Remove spines from all axes for cleaner appearance
|
|
220
|
+
for ax in axes:
|
|
221
|
+
ax.spines["top"].set_visible(False)
|
|
222
|
+
ax.spines["right"].set_visible(False)
|
|
223
|
+
ax.spines["bottom"].set_visible(False)
|
|
224
|
+
ax.spines["left"].set_visible(False)
|
|
225
|
+
|
|
226
|
+
# Set main title
|
|
227
|
+
fig.suptitle(
|
|
228
|
+
title, fontsize=14, y=0.97, fontname=fontname, fontweight="bold", color="black"
|
|
229
|
+
)
|
|
230
|
+
|
|
231
|
+
fig.set_facecolor("white")
|
|
232
|
+
|
|
233
|
+
# Add subtitle with date range and Sharpe ratio
|
|
234
|
+
if subtitle:
|
|
235
|
+
if isinstance(returns, _pd.Series):
|
|
236
|
+
axes[0].set_title(
|
|
237
|
+
"{} - {} ; Sharpe: {:.2f} \n".format(
|
|
238
|
+
returns.index.date[:1][0].strftime("%e %b '%y"), # type: ignore
|
|
239
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"), # type: ignore
|
|
240
|
+
_get_stats().sharpe(returns),
|
|
241
|
+
),
|
|
242
|
+
fontsize=12,
|
|
243
|
+
color="gray",
|
|
244
|
+
)
|
|
245
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
246
|
+
axes[0].set_title(
|
|
247
|
+
"\n{} - {} ; ".format(
|
|
248
|
+
returns.index.date[:1][0].strftime("%e %b '%y"), # type: ignore
|
|
249
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"), # type: ignore
|
|
250
|
+
),
|
|
251
|
+
fontsize=12,
|
|
252
|
+
color="gray",
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
# Configure first subplot: Cumulative Returns
|
|
256
|
+
axes[0].set_ylabel(
|
|
257
|
+
"Cumulative Return", fontname=fontname, fontweight="bold", fontsize=12
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
# Plot cumulative returns for Series or DataFrame
|
|
261
|
+
if isinstance(returns, _pd.Series):
|
|
262
|
+
# Calculate cumulative returns based on mode
|
|
263
|
+
if mode.lower() in ["cumsum", "sum"]:
|
|
264
|
+
cum_ret = returns.cumsum() * 100
|
|
265
|
+
else:
|
|
266
|
+
cum_ret = _get_stats().compsum(returns) * 100
|
|
267
|
+
# Plot cumulative returns line
|
|
268
|
+
axes[0].plot(
|
|
269
|
+
cum_ret,
|
|
270
|
+
color=colors[1],
|
|
271
|
+
lw=1 if grayscale else lw,
|
|
272
|
+
zorder=1,
|
|
273
|
+
)
|
|
274
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
275
|
+
# Plot each column separately for DataFrame
|
|
276
|
+
for col in returns.columns:
|
|
277
|
+
if mode.lower() in ["cumsum", "sum"]:
|
|
278
|
+
cum_ret = returns[col].cumsum() * 100
|
|
279
|
+
else:
|
|
280
|
+
cum_ret = _get_stats().compsum(returns[col]) * 100
|
|
281
|
+
axes[0].plot(
|
|
282
|
+
cum_ret,
|
|
283
|
+
label=col,
|
|
284
|
+
lw=1 if grayscale else lw,
|
|
285
|
+
zorder=1,
|
|
286
|
+
)
|
|
287
|
+
# Add horizontal line at zero
|
|
288
|
+
axes[0].axhline(0, color="silver", lw=1, zorder=0)
|
|
289
|
+
|
|
290
|
+
# Set y-axis scale based on log_scale parameter
|
|
291
|
+
axes[0].set_yscale("symlog" if log_scale else "linear")
|
|
292
|
+
# axes[0].legend(fontsize=12)
|
|
293
|
+
|
|
294
|
+
# Configure second subplot: Drawdown
|
|
295
|
+
dd = _get_stats().to_drawdown_series(returns) * 100
|
|
296
|
+
# Calculate appropriate tick spacing for drawdown
|
|
297
|
+
ddmin = _get_utils()._round_to_closest(abs(dd.min()), 5)
|
|
298
|
+
ddmin_ticks = 5
|
|
299
|
+
if ddmin > 50:
|
|
300
|
+
ddmin_ticks = ddmin / 4
|
|
301
|
+
elif ddmin > 20:
|
|
302
|
+
ddmin_ticks = ddmin / 3
|
|
303
|
+
ddmin_ticks = int(_get_utils()._round_to_closest(ddmin_ticks, 5))
|
|
304
|
+
|
|
305
|
+
# ddmin_ticks = int(_get_utils()._round_to_closest(ddmin, 5))
|
|
306
|
+
axes[1].set_ylabel("Drawdown", fontname=fontname, fontweight="bold", fontsize=12)
|
|
307
|
+
axes[1].set_yticks(_np.arange(-ddmin, 0, step=ddmin_ticks))
|
|
308
|
+
|
|
309
|
+
# Plot drawdown series
|
|
310
|
+
if isinstance(dd, _pd.Series):
|
|
311
|
+
axes[1].plot(dd, color=colors[2], lw=1 if grayscale else lw, zorder=1)
|
|
312
|
+
elif isinstance(dd, _pd.DataFrame):
|
|
313
|
+
for col in dd.columns:
|
|
314
|
+
axes[1].plot(dd[col], label=col, lw=1 if grayscale else lw, zorder=1)
|
|
315
|
+
axes[1].axhline(0, color="silver", lw=1, zorder=0)
|
|
316
|
+
|
|
317
|
+
# Add filled area under drawdown curve if not grayscale
|
|
318
|
+
if not grayscale:
|
|
319
|
+
if isinstance(dd, _pd.Series):
|
|
320
|
+
axes[1].fill_between(dd.index, 0, dd, color=colors[2], alpha=0.25)
|
|
321
|
+
elif isinstance(dd, _pd.DataFrame):
|
|
322
|
+
for i, col in enumerate(dd.columns):
|
|
323
|
+
axes[1].fill_between(
|
|
324
|
+
dd[col].index, 0, dd[col], color=colors[i + 1], alpha=0.25
|
|
325
|
+
)
|
|
326
|
+
|
|
327
|
+
axes[1].set_yscale("symlog" if log_scale else "linear")
|
|
328
|
+
# axes[1].legend(fontsize=12)
|
|
329
|
+
|
|
330
|
+
# Configure third subplot: Daily Returns
|
|
331
|
+
axes[2].set_ylabel(
|
|
332
|
+
"Daily Return", fontname=fontname, fontweight="bold", fontsize=12
|
|
333
|
+
)
|
|
334
|
+
|
|
335
|
+
# Plot daily returns
|
|
336
|
+
if isinstance(returns, _pd.Series):
|
|
337
|
+
axes[2].plot(
|
|
338
|
+
returns * 100, color=colors[0], label=returns.name, lw=0.5, zorder=1
|
|
339
|
+
)
|
|
340
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
341
|
+
for i, col in enumerate(returns.columns):
|
|
342
|
+
axes[2].plot(
|
|
343
|
+
returns[col] * 100, color=colors[i], label=col, lw=0.5, zorder=1
|
|
344
|
+
)
|
|
345
|
+
# Add horizontal lines at zero
|
|
346
|
+
axes[2].axhline(0, color="silver", lw=1, zorder=0)
|
|
347
|
+
axes[2].axhline(0, color=colors[-1], linestyle="--", lw=1, zorder=2)
|
|
348
|
+
|
|
349
|
+
axes[2].set_yscale("symlog" if log_scale else "linear")
|
|
350
|
+
# axes[2].legend(fontsize=12)
|
|
351
|
+
|
|
352
|
+
# Calculate appropriate tick spacing for daily returns
|
|
353
|
+
retmax = _get_utils()._round_to_closest(returns.max() * 100, 5)
|
|
354
|
+
retmin = _get_utils()._round_to_closest(returns.min() * 100, 5)
|
|
355
|
+
retdiff = retmax - retmin
|
|
356
|
+
steps = 5
|
|
357
|
+
if retdiff > 50:
|
|
358
|
+
steps = retdiff / 5
|
|
359
|
+
elif retdiff > 30:
|
|
360
|
+
steps = retdiff / 4
|
|
361
|
+
steps = _get_utils()._round_to_closest(steps, 5)
|
|
362
|
+
axes[2].set_yticks(_np.arange(retmin, retmax, step=steps))
|
|
363
|
+
|
|
364
|
+
# Apply common formatting to all axes
|
|
365
|
+
for ax in axes:
|
|
366
|
+
ax.set_facecolor("white")
|
|
367
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
368
|
+
ax.yaxis.set_major_formatter(_StrMethodFormatter("{x:,.0f}%"))
|
|
369
|
+
|
|
370
|
+
# Adjust layout
|
|
371
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
372
|
+
fig.autofmt_xdate()
|
|
373
|
+
|
|
374
|
+
# Apply layout adjustments with error handling
|
|
375
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
376
|
+
_plt.subplots_adjust(hspace=0)
|
|
377
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
378
|
+
fig.tight_layout(w_pad=0, h_pad=0)
|
|
379
|
+
|
|
380
|
+
# Save figure if requested
|
|
381
|
+
if savefig:
|
|
382
|
+
if isinstance(savefig, dict):
|
|
383
|
+
_plt.savefig(**savefig)
|
|
384
|
+
else:
|
|
385
|
+
_plt.savefig(savefig)
|
|
386
|
+
|
|
387
|
+
# Show plot if requested
|
|
388
|
+
if show:
|
|
389
|
+
_plt.show(block=False)
|
|
390
|
+
|
|
391
|
+
_plt.close()
|
|
392
|
+
|
|
393
|
+
if not show:
|
|
394
|
+
return fig
|
|
395
|
+
|
|
396
|
+
return None
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def earnings(
|
|
400
|
+
returns: Returns,
|
|
401
|
+
start_balance: float = 1e5,
|
|
402
|
+
mode: str = "comp",
|
|
403
|
+
grayscale: bool = False,
|
|
404
|
+
figsize: tuple[float, float] = (10, 6),
|
|
405
|
+
title: str = "Portfolio Earnings",
|
|
406
|
+
fontname: str = "Arial",
|
|
407
|
+
lw: float = 1.5,
|
|
408
|
+
subtitle: bool = True,
|
|
409
|
+
savefig: str | dict | None = None,
|
|
410
|
+
show: bool = True,
|
|
411
|
+
) -> _Figure | None:
|
|
412
|
+
"""
|
|
413
|
+
Plot portfolio earnings over time showing absolute dollar value growth.
|
|
414
|
+
|
|
415
|
+
Parameters
|
|
416
|
+
----------
|
|
417
|
+
returns : pandas.Series or pandas.DataFrame
|
|
418
|
+
Daily returns data.
|
|
419
|
+
start_balance : float, optional
|
|
420
|
+
Starting portfolio balance in dollars (default: 100000).
|
|
421
|
+
mode : str, optional
|
|
422
|
+
Calculation mode: "comp" for compound returns or "sum" for simple sum.
|
|
423
|
+
grayscale : bool, optional
|
|
424
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
425
|
+
figsize : tuple, optional
|
|
426
|
+
Figure size as (width, height) in inches (default: (10, 6)).
|
|
427
|
+
title : str, optional
|
|
428
|
+
Main title for the plot (default: "Portfolio Earnings").
|
|
429
|
+
fontname : str, optional
|
|
430
|
+
Font family for text elements (default: "Arial").
|
|
431
|
+
lw : float, optional
|
|
432
|
+
Line width for the earnings line (default: 1.5).
|
|
433
|
+
subtitle : bool, optional
|
|
434
|
+
Whether to show subtitle with date range and P&L (default: True).
|
|
435
|
+
savefig : str or dict, optional
|
|
436
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
437
|
+
show : bool, optional
|
|
438
|
+
Whether to display the plot (default: True).
|
|
439
|
+
|
|
440
|
+
Returns
|
|
441
|
+
-------
|
|
442
|
+
matplotlib.figure.Figure or None
|
|
443
|
+
Figure object if show=False, otherwise None.
|
|
444
|
+
|
|
445
|
+
Notes
|
|
446
|
+
-----
|
|
447
|
+
Shows portfolio value over time starting from the specified balance.
|
|
448
|
+
Highlights the maximum portfolio value achieved during the period.
|
|
449
|
+
"""
|
|
450
|
+
# Select color scheme and transparency based on grayscale preference
|
|
451
|
+
colors = _GRAYSCALE_COLORS if grayscale else _FLATUI_COLORS
|
|
452
|
+
alpha = 0.5 if grayscale else 0.8
|
|
453
|
+
|
|
454
|
+
# Convert returns to portfolio dollar values
|
|
455
|
+
returns = _get_utils().make_portfolio(returns, start_balance, mode)
|
|
456
|
+
|
|
457
|
+
# Use current figure size if not specified
|
|
458
|
+
if figsize is None:
|
|
459
|
+
size = list(_plt.gcf().get_size_inches())
|
|
460
|
+
figsize = (size[0], size[0] * 0.55)
|
|
461
|
+
|
|
462
|
+
# Create single subplot figure
|
|
463
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
464
|
+
|
|
465
|
+
# Remove spines for cleaner appearance
|
|
466
|
+
ax.spines["top"].set_visible(False)
|
|
467
|
+
ax.spines["right"].set_visible(False)
|
|
468
|
+
ax.spines["bottom"].set_visible(False)
|
|
469
|
+
ax.spines["left"].set_visible(False)
|
|
470
|
+
|
|
471
|
+
# Set main title
|
|
472
|
+
fig.suptitle(
|
|
473
|
+
f" {title}",
|
|
474
|
+
fontsize=12,
|
|
475
|
+
y=0.95,
|
|
476
|
+
fontname=fontname,
|
|
477
|
+
fontweight="bold",
|
|
478
|
+
color="black",
|
|
479
|
+
)
|
|
480
|
+
|
|
481
|
+
# Add subtitle with date range and P&L information
|
|
482
|
+
if subtitle:
|
|
483
|
+
ax.set_title(
|
|
484
|
+
"\n{} - {} ; P&L: {} ({}) ".format(
|
|
485
|
+
returns.index.date[1:2][0].strftime("%e %b '%y"), # type: ignore
|
|
486
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"), # type: ignore
|
|
487
|
+
_get_utils()._score_str(
|
|
488
|
+
f"${round(returns.values[-1] - returns.values[0], 2):,}"
|
|
489
|
+
),
|
|
490
|
+
_get_utils()._score_str(
|
|
491
|
+
f"{round((returns.values[-1] / returns.values[0] - 1) * 100, 2):,}%"
|
|
492
|
+
),
|
|
493
|
+
),
|
|
494
|
+
fontsize=10,
|
|
495
|
+
color="gray",
|
|
496
|
+
)
|
|
497
|
+
|
|
498
|
+
# Find and highlight maximum portfolio value
|
|
499
|
+
mx = returns.max()
|
|
500
|
+
returns_max = returns[returns == mx]
|
|
501
|
+
ix = returns_max[~_np.isnan(returns_max)].index[0]
|
|
502
|
+
returns_max = _np.where(returns.index == ix, mx, _np.nan)
|
|
503
|
+
|
|
504
|
+
# Plot maximum value point as a marker
|
|
505
|
+
ax.plot(
|
|
506
|
+
returns.index,
|
|
507
|
+
returns_max,
|
|
508
|
+
marker="o",
|
|
509
|
+
lw=0,
|
|
510
|
+
alpha=alpha,
|
|
511
|
+
markersize=12,
|
|
512
|
+
color=colors[0],
|
|
513
|
+
)
|
|
514
|
+
|
|
515
|
+
# Plot main earnings line
|
|
516
|
+
ax.plot(returns.index, returns, color=colors[1], lw=1 if grayscale else lw)
|
|
517
|
+
|
|
518
|
+
# Set y-axis label showing starting balance
|
|
519
|
+
ax.set_ylabel(
|
|
520
|
+
f"Value of ${start_balance:,.0f}",
|
|
521
|
+
fontname=fontname,
|
|
522
|
+
fontweight="bold",
|
|
523
|
+
fontsize=11,
|
|
524
|
+
)
|
|
525
|
+
|
|
526
|
+
# Format y-axis as currency
|
|
527
|
+
ax.yaxis.set_major_formatter(_FuncFormatter(_core.format_cur_axis))
|
|
528
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
529
|
+
_plt.xticks(fontsize=11)
|
|
530
|
+
_plt.yticks(fontsize=11)
|
|
531
|
+
|
|
532
|
+
# Set background colors
|
|
533
|
+
fig.set_facecolor("white")
|
|
534
|
+
ax.set_facecolor("white")
|
|
535
|
+
fig.autofmt_xdate()
|
|
536
|
+
|
|
537
|
+
# Apply layout adjustments with error handling
|
|
538
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
539
|
+
_plt.subplots_adjust(hspace=0)
|
|
540
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
541
|
+
fig.tight_layout(w_pad=0, h_pad=0)
|
|
542
|
+
|
|
543
|
+
# Save figure if requested
|
|
544
|
+
if savefig:
|
|
545
|
+
if isinstance(savefig, dict):
|
|
546
|
+
_plt.savefig(**savefig)
|
|
547
|
+
else:
|
|
548
|
+
_plt.savefig(savefig)
|
|
549
|
+
|
|
550
|
+
# Show plot if requested
|
|
551
|
+
if show:
|
|
552
|
+
_plt.show(block=False)
|
|
553
|
+
|
|
554
|
+
_plt.close()
|
|
555
|
+
|
|
556
|
+
if not show:
|
|
557
|
+
return fig
|
|
558
|
+
|
|
559
|
+
return None
|
|
560
|
+
|
|
561
|
+
|
|
562
|
+
def returns(
|
|
563
|
+
returns: Returns,
|
|
564
|
+
benchmark: Returns | str | None = None,
|
|
565
|
+
grayscale: bool = False,
|
|
566
|
+
figsize: tuple[float, float] = (10, 6),
|
|
567
|
+
fontname: str = "Arial",
|
|
568
|
+
lw: float = 1.5,
|
|
569
|
+
match_volatility: bool = False,
|
|
570
|
+
compound: bool = True,
|
|
571
|
+
resample: str | None = None,
|
|
572
|
+
ylabel: str = "Cumulative Returns",
|
|
573
|
+
subtitle: bool = True,
|
|
574
|
+
savefig: str | dict | None = None,
|
|
575
|
+
show: bool = True,
|
|
576
|
+
prepare_returns: bool = True,
|
|
577
|
+
) -> _Figure | None:
|
|
578
|
+
"""
|
|
579
|
+
Plot cumulative returns over time, optionally compared to a benchmark.
|
|
580
|
+
|
|
581
|
+
Parameters
|
|
582
|
+
----------
|
|
583
|
+
returns : pandas.Series or pandas.DataFrame
|
|
584
|
+
Daily returns data.
|
|
585
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
586
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
587
|
+
grayscale : bool, optional
|
|
588
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
589
|
+
figsize : tuple, optional
|
|
590
|
+
Figure size as (width, height) in inches (default: (10, 6)).
|
|
591
|
+
fontname : str, optional
|
|
592
|
+
Font family for text elements (default: "Arial").
|
|
593
|
+
lw : float, optional
|
|
594
|
+
Line width for plots (default: 1.5).
|
|
595
|
+
match_volatility : bool, optional
|
|
596
|
+
If True, matches volatility between returns and benchmark (default: False).
|
|
597
|
+
compound : bool, optional
|
|
598
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
599
|
+
resample : str, optional
|
|
600
|
+
Resampling frequency (e.g., 'M' for monthly, 'Q' for quarterly).
|
|
601
|
+
ylabel : str, optional
|
|
602
|
+
Y-axis label (default: "Cumulative Returns").
|
|
603
|
+
subtitle : bool, optional
|
|
604
|
+
Whether to show subtitle with date range and statistics (default: True).
|
|
605
|
+
savefig : str or dict, optional
|
|
606
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
607
|
+
show : bool, optional
|
|
608
|
+
Whether to display the plot (default: True).
|
|
609
|
+
prepare_returns : bool, optional
|
|
610
|
+
Whether to prepare returns data (default: True).
|
|
611
|
+
|
|
612
|
+
Returns
|
|
613
|
+
-------
|
|
614
|
+
matplotlib.figure.Figure or None
|
|
615
|
+
Figure object if show=False, otherwise None.
|
|
616
|
+
|
|
617
|
+
Notes
|
|
618
|
+
-----
|
|
619
|
+
Creates a time series plot of cumulative returns. If benchmark is provided,
|
|
620
|
+
both series are plotted for comparison.
|
|
621
|
+
"""
|
|
622
|
+
# Build title based on parameters
|
|
623
|
+
title = "Cumulative Returns" if compound else "Returns"
|
|
624
|
+
if benchmark is not None:
|
|
625
|
+
if isinstance(benchmark, str):
|
|
626
|
+
title += f" vs {benchmark.upper()}"
|
|
627
|
+
else:
|
|
628
|
+
title += " vs Benchmark"
|
|
629
|
+
if match_volatility:
|
|
630
|
+
title += " (Volatility Matched)"
|
|
631
|
+
|
|
632
|
+
# Prepare benchmark data to match returns index
|
|
633
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index)
|
|
634
|
+
|
|
635
|
+
# Prepare returns data if requested
|
|
636
|
+
if prepare_returns:
|
|
637
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
638
|
+
|
|
639
|
+
# Use core plotting function for time series
|
|
640
|
+
fig = _core.plot_timeseries(
|
|
641
|
+
returns,
|
|
642
|
+
benchmark,
|
|
643
|
+
title,
|
|
644
|
+
ylabel=ylabel,
|
|
645
|
+
match_volatility=match_volatility,
|
|
646
|
+
log_scale=False,
|
|
647
|
+
resample=resample,
|
|
648
|
+
compound=compound,
|
|
649
|
+
lw=lw,
|
|
650
|
+
figsize=figsize,
|
|
651
|
+
fontname=fontname,
|
|
652
|
+
grayscale=grayscale,
|
|
653
|
+
subtitle=subtitle,
|
|
654
|
+
savefig=savefig,
|
|
655
|
+
show=show,
|
|
656
|
+
)
|
|
657
|
+
if not show:
|
|
658
|
+
return fig
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def log_returns(
|
|
662
|
+
returns: Returns,
|
|
663
|
+
benchmark: Returns | str | None = None,
|
|
664
|
+
grayscale: bool = False,
|
|
665
|
+
figsize: tuple[float, float] = (10, 5),
|
|
666
|
+
fontname: str = "Arial",
|
|
667
|
+
lw: float = 1.5,
|
|
668
|
+
match_volatility: bool = False,
|
|
669
|
+
compound: bool = True,
|
|
670
|
+
resample: str | None = None,
|
|
671
|
+
ylabel: str = "Cumulative Returns",
|
|
672
|
+
subtitle: bool = True,
|
|
673
|
+
savefig: str | dict | None = None,
|
|
674
|
+
show: bool = True,
|
|
675
|
+
prepare_returns: bool = True,
|
|
676
|
+
) -> _Figure | None:
|
|
677
|
+
"""
|
|
678
|
+
Plot cumulative returns on a logarithmic scale for better trend visualization.
|
|
679
|
+
|
|
680
|
+
Parameters
|
|
681
|
+
----------
|
|
682
|
+
returns : pandas.Series or pandas.DataFrame
|
|
683
|
+
Daily returns data.
|
|
684
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
685
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
686
|
+
grayscale : bool, optional
|
|
687
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
688
|
+
figsize : tuple, optional
|
|
689
|
+
Figure size as (width, height) in inches (default: (10, 5)).
|
|
690
|
+
fontname : str, optional
|
|
691
|
+
Font family for text elements (default: "Arial").
|
|
692
|
+
lw : float, optional
|
|
693
|
+
Line width for plots (default: 1.5).
|
|
694
|
+
match_volatility : bool, optional
|
|
695
|
+
If True, matches volatility between returns and benchmark (default: False).
|
|
696
|
+
compound : bool, optional
|
|
697
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
698
|
+
resample : str, optional
|
|
699
|
+
Resampling frequency (e.g., 'M' for monthly, 'Q' for quarterly).
|
|
700
|
+
ylabel : str, optional
|
|
701
|
+
Y-axis label (default: "Cumulative Returns").
|
|
702
|
+
subtitle : bool, optional
|
|
703
|
+
Whether to show subtitle with date range and statistics (default: True).
|
|
704
|
+
savefig : str or dict, optional
|
|
705
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
706
|
+
show : bool, optional
|
|
707
|
+
Whether to display the plot (default: True).
|
|
708
|
+
prepare_returns : bool, optional
|
|
709
|
+
Whether to prepare returns data (default: True).
|
|
710
|
+
|
|
711
|
+
Returns
|
|
712
|
+
-------
|
|
713
|
+
matplotlib.figure.Figure or None
|
|
714
|
+
Figure object if show=False, otherwise None.
|
|
715
|
+
|
|
716
|
+
Notes
|
|
717
|
+
-----
|
|
718
|
+
Similar to returns() but uses logarithmic scale which is better for visualizing
|
|
719
|
+
exponential growth and making percentage changes more comparable across time.
|
|
720
|
+
"""
|
|
721
|
+
# Build title with log scale indication
|
|
722
|
+
title = "Cumulative Returns" if compound else "Returns"
|
|
723
|
+
if benchmark is not None:
|
|
724
|
+
if isinstance(benchmark, str):
|
|
725
|
+
title += f" vs {benchmark.upper()} (Log Scaled"
|
|
726
|
+
else:
|
|
727
|
+
title += " vs Benchmark (Log Scaled"
|
|
728
|
+
if match_volatility:
|
|
729
|
+
title += ", Volatility Matched"
|
|
730
|
+
else:
|
|
731
|
+
title += " (Log Scaled"
|
|
732
|
+
title += ")"
|
|
733
|
+
|
|
734
|
+
# Prepare returns data if requested
|
|
735
|
+
if prepare_returns:
|
|
736
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
737
|
+
|
|
738
|
+
# Prepare benchmark data to match returns index
|
|
739
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index) # type: ignore
|
|
740
|
+
|
|
741
|
+
# Use core plotting function with log scale enabled
|
|
742
|
+
fig = _core.plot_timeseries(
|
|
743
|
+
returns,
|
|
744
|
+
benchmark,
|
|
745
|
+
title,
|
|
746
|
+
ylabel=ylabel,
|
|
747
|
+
match_volatility=match_volatility,
|
|
748
|
+
log_scale=True,
|
|
749
|
+
resample=resample,
|
|
750
|
+
compound=compound,
|
|
751
|
+
lw=lw,
|
|
752
|
+
figsize=figsize,
|
|
753
|
+
fontname=fontname,
|
|
754
|
+
grayscale=grayscale,
|
|
755
|
+
subtitle=subtitle,
|
|
756
|
+
savefig=savefig,
|
|
757
|
+
show=show,
|
|
758
|
+
)
|
|
759
|
+
if not show:
|
|
760
|
+
return fig
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def daily_returns(
|
|
764
|
+
returns: Returns,
|
|
765
|
+
benchmark: Returns | str | None,
|
|
766
|
+
grayscale: bool = False,
|
|
767
|
+
figsize: tuple[float, float] = (10, 4),
|
|
768
|
+
fontname: str = "Arial",
|
|
769
|
+
lw: float = 0.5,
|
|
770
|
+
log_scale: bool = False,
|
|
771
|
+
ylabel: str = "Returns",
|
|
772
|
+
subtitle: bool = True,
|
|
773
|
+
savefig: str | dict | None = None,
|
|
774
|
+
show: bool = True,
|
|
775
|
+
prepare_returns: bool = True,
|
|
776
|
+
active: bool = False,
|
|
777
|
+
) -> _Figure | None:
|
|
778
|
+
"""
|
|
779
|
+
Plot daily returns over time, optionally as active returns vs benchmark.
|
|
780
|
+
|
|
781
|
+
Parameters
|
|
782
|
+
----------
|
|
783
|
+
returns : pandas.Series or pandas.DataFrame
|
|
784
|
+
Daily returns data.
|
|
785
|
+
benchmark : pandas.Series, pandas.DataFrame, or str
|
|
786
|
+
Benchmark returns data or ticker symbol.
|
|
787
|
+
grayscale : bool, optional
|
|
788
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
789
|
+
figsize : tuple, optional
|
|
790
|
+
Figure size as (width, height) in inches (default: (10, 4)).
|
|
791
|
+
fontname : str, optional
|
|
792
|
+
Font family for text elements (default: "Arial").
|
|
793
|
+
lw : float, optional
|
|
794
|
+
Line width for plots (default: 0.5).
|
|
795
|
+
log_scale : bool, optional
|
|
796
|
+
Whether to use logarithmic scale for y-axis (default: False).
|
|
797
|
+
ylabel : str, optional
|
|
798
|
+
Y-axis label (default: "Returns").
|
|
799
|
+
subtitle : bool, optional
|
|
800
|
+
Whether to show subtitle with date range and statistics (default: True).
|
|
801
|
+
savefig : str or dict, optional
|
|
802
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
803
|
+
show : bool, optional
|
|
804
|
+
Whether to display the plot (default: True).
|
|
805
|
+
prepare_returns : bool, optional
|
|
806
|
+
Whether to prepare returns data (default: True).
|
|
807
|
+
active : bool, optional
|
|
808
|
+
If True, plots active returns (returns - benchmark) (default: False).
|
|
809
|
+
|
|
810
|
+
Returns
|
|
811
|
+
-------
|
|
812
|
+
matplotlib.figure.Figure or None
|
|
813
|
+
Figure object if show=False, otherwise None.
|
|
814
|
+
|
|
815
|
+
Notes
|
|
816
|
+
-----
|
|
817
|
+
Shows daily return variations over time. If active=True, displays the difference
|
|
818
|
+
between portfolio returns and benchmark returns.
|
|
819
|
+
"""
|
|
820
|
+
# Prepare returns data if requested
|
|
821
|
+
if prepare_returns:
|
|
822
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
823
|
+
# Calculate active returns if requested
|
|
824
|
+
if active and benchmark is not None:
|
|
825
|
+
benchmark = _get_utils()._prepare_returns(benchmark)
|
|
826
|
+
returns = returns - benchmark
|
|
827
|
+
|
|
828
|
+
# Set plot title based on active returns setting
|
|
829
|
+
plot_title = "Daily Active Returns" if active else "Daily Returns"
|
|
830
|
+
plot_title += " (Cumulative Sum)"
|
|
831
|
+
|
|
832
|
+
# Use core plotting function for daily time series
|
|
833
|
+
fig = _core.plot_timeseries(
|
|
834
|
+
returns,
|
|
835
|
+
None, # No benchmark for daily returns plot
|
|
836
|
+
plot_title,
|
|
837
|
+
ylabel=ylabel,
|
|
838
|
+
match_volatility=False,
|
|
839
|
+
log_scale=log_scale,
|
|
840
|
+
resample="D", # Daily resampling
|
|
841
|
+
compound=False, # No compounding for daily returns
|
|
842
|
+
lw=lw,
|
|
843
|
+
figsize=figsize,
|
|
844
|
+
fontname=fontname,
|
|
845
|
+
grayscale=grayscale,
|
|
846
|
+
subtitle=subtitle,
|
|
847
|
+
savefig=savefig,
|
|
848
|
+
show=show,
|
|
849
|
+
)
|
|
850
|
+
if not show:
|
|
851
|
+
return fig
|
|
852
|
+
|
|
853
|
+
|
|
854
|
+
def yearly_returns(
|
|
855
|
+
returns: Returns,
|
|
856
|
+
benchmark: Returns | str | None = None,
|
|
857
|
+
fontname: str = "Arial",
|
|
858
|
+
grayscale: bool = False,
|
|
859
|
+
hlw: float = 1.5,
|
|
860
|
+
hlcolor: str = "red",
|
|
861
|
+
hllabel: str = "",
|
|
862
|
+
match_volatility: bool = False,
|
|
863
|
+
log_scale: bool = False,
|
|
864
|
+
figsize: tuple[float, float] = (10, 5),
|
|
865
|
+
ylabel: bool = True,
|
|
866
|
+
subtitle: bool = True,
|
|
867
|
+
compounded: bool = True,
|
|
868
|
+
savefig: str | dict | None = None,
|
|
869
|
+
show: bool = True,
|
|
870
|
+
prepare_returns: bool = True,
|
|
871
|
+
) -> _Figure | None:
|
|
872
|
+
"""
|
|
873
|
+
Plot end-of-year returns as a bar chart, optionally compared to benchmark.
|
|
874
|
+
|
|
875
|
+
Parameters
|
|
876
|
+
----------
|
|
877
|
+
returns : pandas.Series or pandas.DataFrame
|
|
878
|
+
Daily returns data.
|
|
879
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
880
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
881
|
+
fontname : str, optional
|
|
882
|
+
Font family for text elements (default: "Arial").
|
|
883
|
+
grayscale : bool, optional
|
|
884
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
885
|
+
hlw : float, optional
|
|
886
|
+
Horizontal line width for mean line (default: 1.5).
|
|
887
|
+
hlcolor : str, optional
|
|
888
|
+
Color for horizontal mean line (default: "red").
|
|
889
|
+
hllabel : str, optional
|
|
890
|
+
Label for horizontal mean line (default: "").
|
|
891
|
+
match_volatility : bool, optional
|
|
892
|
+
If True, matches volatility between returns and benchmark (default: False).
|
|
893
|
+
log_scale : bool, optional
|
|
894
|
+
Whether to use logarithmic scale for y-axis (default: False).
|
|
895
|
+
figsize : tuple, optional
|
|
896
|
+
Figure size as (width, height) in inches (default: (10, 5)).
|
|
897
|
+
ylabel : bool, optional
|
|
898
|
+
Whether to show y-axis label (default: True).
|
|
899
|
+
subtitle : bool, optional
|
|
900
|
+
Whether to show subtitle with date range and statistics (default: True).
|
|
901
|
+
compounded : bool, optional
|
|
902
|
+
If True, uses compound returns; if False, uses simple sum (default: True).
|
|
903
|
+
savefig : str or dict, optional
|
|
904
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
905
|
+
show : bool, optional
|
|
906
|
+
Whether to display the plot (default: True).
|
|
907
|
+
prepare_returns : bool, optional
|
|
908
|
+
Whether to prepare returns data (default: True).
|
|
909
|
+
|
|
910
|
+
Returns
|
|
911
|
+
-------
|
|
912
|
+
matplotlib.figure.Figure or None
|
|
913
|
+
Figure object if show=False, otherwise None.
|
|
914
|
+
|
|
915
|
+
Notes
|
|
916
|
+
-----
|
|
917
|
+
Aggregates returns by year and displays as bars. Shows mean return as horizontal line.
|
|
918
|
+
"""
|
|
919
|
+
# Set plot title
|
|
920
|
+
title = "EOY Returns"
|
|
921
|
+
if benchmark is not None:
|
|
922
|
+
title += " vs Benchmark"
|
|
923
|
+
# Prepare and resample benchmark data
|
|
924
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index)
|
|
925
|
+
benchmark = safe_resample(benchmark, "YE", _get_stats().comp)
|
|
926
|
+
benchmark = safe_resample(benchmark, "YE", "last")
|
|
927
|
+
|
|
928
|
+
# Prepare returns data if requested
|
|
929
|
+
if prepare_returns:
|
|
930
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
931
|
+
|
|
932
|
+
# Resample returns to year-end based on compounding preference
|
|
933
|
+
if compounded:
|
|
934
|
+
returns = safe_resample(returns, "YE", _get_stats().comp)
|
|
935
|
+
else:
|
|
936
|
+
returns = safe_resample(returns, "YE", "sum")
|
|
937
|
+
returns = safe_resample(returns, "YE", "last")
|
|
938
|
+
|
|
939
|
+
# Use core plotting function for bar chart
|
|
940
|
+
fig = _core.plot_returns_bars(
|
|
941
|
+
returns,
|
|
942
|
+
benchmark,
|
|
943
|
+
fontname=fontname,
|
|
944
|
+
hline=returns.mean(), # Show mean as horizontal line
|
|
945
|
+
hlw=hlw,
|
|
946
|
+
hllabel=hllabel,
|
|
947
|
+
hlcolor=hlcolor,
|
|
948
|
+
match_volatility=match_volatility,
|
|
949
|
+
log_scale=log_scale,
|
|
950
|
+
resample="YE",
|
|
951
|
+
title=title,
|
|
952
|
+
figsize=figsize,
|
|
953
|
+
grayscale=grayscale,
|
|
954
|
+
ylabel=ylabel,
|
|
955
|
+
subtitle=subtitle,
|
|
956
|
+
savefig=savefig,
|
|
957
|
+
show=show,
|
|
958
|
+
)
|
|
959
|
+
if not show:
|
|
960
|
+
return fig
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
def distribution(
|
|
964
|
+
returns: Returns,
|
|
965
|
+
fontname: str = "Arial",
|
|
966
|
+
grayscale: bool = False,
|
|
967
|
+
ylabel: bool = True,
|
|
968
|
+
figsize: tuple[float, float] = (10, 6),
|
|
969
|
+
subtitle: bool = True,
|
|
970
|
+
compounded: bool = True,
|
|
971
|
+
savefig: str | dict | None = None,
|
|
972
|
+
show: bool = True,
|
|
973
|
+
title: str | None = None,
|
|
974
|
+
prepare_returns: bool = True,
|
|
975
|
+
) -> _Figure | None:
|
|
976
|
+
"""
|
|
977
|
+
Plot the distribution of returns using histogram and density curves.
|
|
978
|
+
|
|
979
|
+
Parameters
|
|
980
|
+
----------
|
|
981
|
+
returns : pandas.Series or pandas.DataFrame
|
|
982
|
+
Daily returns data.
|
|
983
|
+
fontname : str, optional
|
|
984
|
+
Font family for text elements (default: "Arial").
|
|
985
|
+
grayscale : bool, optional
|
|
986
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
987
|
+
ylabel : bool, optional
|
|
988
|
+
Whether to show y-axis label (default: True).
|
|
989
|
+
figsize : tuple, optional
|
|
990
|
+
Figure size as (width, height) in inches (default: (10, 6)).
|
|
991
|
+
subtitle : bool, optional
|
|
992
|
+
Whether to show subtitle with distribution statistics (default: True).
|
|
993
|
+
compounded : bool, optional
|
|
994
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
995
|
+
savefig : str or dict, optional
|
|
996
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
997
|
+
show : bool, optional
|
|
998
|
+
Whether to display the plot (default: True).
|
|
999
|
+
title : str, optional
|
|
1000
|
+
Custom title for the plot (default: None).
|
|
1001
|
+
prepare_returns : bool, optional
|
|
1002
|
+
Whether to prepare returns data (default: True).
|
|
1003
|
+
|
|
1004
|
+
Returns
|
|
1005
|
+
-------
|
|
1006
|
+
matplotlib.figure.Figure or None
|
|
1007
|
+
Figure object if show=False, otherwise None.
|
|
1008
|
+
|
|
1009
|
+
Notes
|
|
1010
|
+
-----
|
|
1011
|
+
Shows the distribution of returns with histogram bars and overlaid density curve.
|
|
1012
|
+
Helpful for understanding return characteristics and identifying outliers.
|
|
1013
|
+
"""
|
|
1014
|
+
# Prepare returns data if requested
|
|
1015
|
+
if prepare_returns:
|
|
1016
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
1017
|
+
|
|
1018
|
+
# Use core plotting function for distribution
|
|
1019
|
+
fig = _core.plot_distribution(
|
|
1020
|
+
returns,
|
|
1021
|
+
fontname=fontname,
|
|
1022
|
+
grayscale=grayscale,
|
|
1023
|
+
figsize=figsize,
|
|
1024
|
+
ylabel=ylabel,
|
|
1025
|
+
subtitle=subtitle,
|
|
1026
|
+
title=title,
|
|
1027
|
+
compounded=compounded,
|
|
1028
|
+
savefig=savefig,
|
|
1029
|
+
show=show,
|
|
1030
|
+
)
|
|
1031
|
+
if not show:
|
|
1032
|
+
return fig
|
|
1033
|
+
|
|
1034
|
+
|
|
1035
|
+
def histogram(
|
|
1036
|
+
returns: Returns,
|
|
1037
|
+
benchmark: Returns | str | None = None,
|
|
1038
|
+
resample: str = "ME",
|
|
1039
|
+
fontname: str = "Arial",
|
|
1040
|
+
grayscale: bool = False,
|
|
1041
|
+
figsize: tuple[float, float] = (10, 5),
|
|
1042
|
+
ylabel: bool = True,
|
|
1043
|
+
subtitle: bool = True,
|
|
1044
|
+
compounded: bool = True,
|
|
1045
|
+
xlim_quantile: float | None = None,
|
|
1046
|
+
binwidth: float | None = None,
|
|
1047
|
+
adaptive_bins: int | None = None,
|
|
1048
|
+
savefig: str | dict | None = None,
|
|
1049
|
+
show: bool = True,
|
|
1050
|
+
prepare_returns: bool = True,
|
|
1051
|
+
) -> _Figure | None:
|
|
1052
|
+
"""
|
|
1053
|
+
Plot histogram of returns resampled to specified frequency.
|
|
1054
|
+
|
|
1055
|
+
Parameters
|
|
1056
|
+
----------
|
|
1057
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1058
|
+
Daily returns data.
|
|
1059
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
1060
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
1061
|
+
resample : str, optional
|
|
1062
|
+
Resampling frequency: 'W' for weekly, 'ME' for monthly, 'QE' for quarterly,
|
|
1063
|
+
'YE' for yearly (default: 'ME').
|
|
1064
|
+
fontname : str, optional
|
|
1065
|
+
Font family for text elements (default: "Arial").
|
|
1066
|
+
grayscale : bool, optional
|
|
1067
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1068
|
+
figsize : tuple, optional
|
|
1069
|
+
Figure size as (width, height) in inches (default: (10, 5)).
|
|
1070
|
+
ylabel : bool, optional
|
|
1071
|
+
Whether to show y-axis label (default: True).
|
|
1072
|
+
subtitle : bool, optional
|
|
1073
|
+
Whether to show subtitle with distribution statistics (default: True).
|
|
1074
|
+
compounded : bool, optional
|
|
1075
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
1076
|
+
savefig : str or dict, optional
|
|
1077
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1078
|
+
show : bool, optional
|
|
1079
|
+
Whether to display the plot (default: True).
|
|
1080
|
+
prepare_returns : bool, optional
|
|
1081
|
+
Whether to prepare returns data (default: True).
|
|
1082
|
+
|
|
1083
|
+
Returns
|
|
1084
|
+
-------
|
|
1085
|
+
matplotlib.figure.Figure or None
|
|
1086
|
+
Figure object if show=False, otherwise None.
|
|
1087
|
+
|
|
1088
|
+
Notes
|
|
1089
|
+
-----
|
|
1090
|
+
Resamples returns to specified frequency and plots distribution histogram.
|
|
1091
|
+
Useful for analyzing return patterns at different time horizons.
|
|
1092
|
+
"""
|
|
1093
|
+
# Prepare returns data if requested
|
|
1094
|
+
if prepare_returns:
|
|
1095
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
1096
|
+
if benchmark is not None:
|
|
1097
|
+
benchmark = _get_utils()._prepare_returns(benchmark)
|
|
1098
|
+
|
|
1099
|
+
# Determine title based on resampling frequency
|
|
1100
|
+
if resample in ("D", "B"):
|
|
1101
|
+
title = "Daily "
|
|
1102
|
+
elif resample == "W":
|
|
1103
|
+
title = "Weekly "
|
|
1104
|
+
elif resample == "ME":
|
|
1105
|
+
title = "Monthly "
|
|
1106
|
+
elif resample == "QE":
|
|
1107
|
+
title = "Quarterly "
|
|
1108
|
+
elif resample == "YE":
|
|
1109
|
+
title = "Annual "
|
|
1110
|
+
else:
|
|
1111
|
+
title = ""
|
|
1112
|
+
|
|
1113
|
+
# Use core plotting function for histogram
|
|
1114
|
+
return _core.plot_histogram(
|
|
1115
|
+
returns,
|
|
1116
|
+
benchmark,
|
|
1117
|
+
resample=resample,
|
|
1118
|
+
grayscale=grayscale,
|
|
1119
|
+
fontname=fontname,
|
|
1120
|
+
title=f"Distribution of {title}Returns",
|
|
1121
|
+
figsize=figsize,
|
|
1122
|
+
ylabel=ylabel,
|
|
1123
|
+
subtitle=subtitle,
|
|
1124
|
+
compounded=compounded,
|
|
1125
|
+
xlim_quantile=xlim_quantile,
|
|
1126
|
+
binwidth=binwidth,
|
|
1127
|
+
adaptive_bins=adaptive_bins,
|
|
1128
|
+
savefig=savefig,
|
|
1129
|
+
show=show,
|
|
1130
|
+
)
|
|
1131
|
+
|
|
1132
|
+
|
|
1133
|
+
def drawdown(
|
|
1134
|
+
returns: Returns,
|
|
1135
|
+
grayscale: bool = False,
|
|
1136
|
+
figsize: tuple[float, float] = (10, 5),
|
|
1137
|
+
fontname: str = "Arial",
|
|
1138
|
+
lw: float = 1,
|
|
1139
|
+
log_scale: bool = False,
|
|
1140
|
+
match_volatility: bool = False,
|
|
1141
|
+
compound: bool = False,
|
|
1142
|
+
ylabel: str = "Drawdown",
|
|
1143
|
+
resample: str | None = None,
|
|
1144
|
+
subtitle: bool = True,
|
|
1145
|
+
savefig: str | dict | None = None,
|
|
1146
|
+
show: bool = True,
|
|
1147
|
+
) -> _Figure | None:
|
|
1148
|
+
"""
|
|
1149
|
+
Plot drawdown series over time showing periods of loss from peak values.
|
|
1150
|
+
|
|
1151
|
+
Parameters
|
|
1152
|
+
----------
|
|
1153
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1154
|
+
Daily returns data.
|
|
1155
|
+
grayscale : bool, optional
|
|
1156
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1157
|
+
figsize : tuple, optional
|
|
1158
|
+
Figure size as (width, height) in inches (default: (10, 5)).
|
|
1159
|
+
fontname : str, optional
|
|
1160
|
+
Font family for text elements (default: "Arial").
|
|
1161
|
+
lw : float, optional
|
|
1162
|
+
Line width for drawdown plot (default: 1).
|
|
1163
|
+
log_scale : bool, optional
|
|
1164
|
+
Whether to use logarithmic scale for y-axis (default: False).
|
|
1165
|
+
match_volatility : bool, optional
|
|
1166
|
+
Not used in drawdown plot (default: False).
|
|
1167
|
+
compound : bool, optional
|
|
1168
|
+
Not used in drawdown plot (default: False).
|
|
1169
|
+
ylabel : str, optional
|
|
1170
|
+
Y-axis label (default: "Drawdown").
|
|
1171
|
+
resample : str, optional
|
|
1172
|
+
Resampling frequency for data aggregation.
|
|
1173
|
+
subtitle : bool, optional
|
|
1174
|
+
Whether to show subtitle with drawdown statistics (default: True).
|
|
1175
|
+
savefig : str or dict, optional
|
|
1176
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1177
|
+
show : bool, optional
|
|
1178
|
+
Whether to display the plot (default: True).
|
|
1179
|
+
|
|
1180
|
+
Returns
|
|
1181
|
+
-------
|
|
1182
|
+
matplotlib.figure.Figure or None
|
|
1183
|
+
Figure object if show=False, otherwise None.
|
|
1184
|
+
|
|
1185
|
+
Notes
|
|
1186
|
+
-----
|
|
1187
|
+
Shows underwater plot of drawdowns with filled area. Includes average drawdown
|
|
1188
|
+
line as reference. Useful for understanding portfolio risk and recovery periods.
|
|
1189
|
+
"""
|
|
1190
|
+
# Convert returns to drawdown series
|
|
1191
|
+
dd = _get_stats().to_drawdown_series(returns)
|
|
1192
|
+
|
|
1193
|
+
# Use core plotting function for drawdown time series
|
|
1194
|
+
fig = _core.plot_timeseries(
|
|
1195
|
+
dd,
|
|
1196
|
+
title="Underwater Plot",
|
|
1197
|
+
hline=dd.mean(), # Show average drawdown as horizontal line
|
|
1198
|
+
hlw=2,
|
|
1199
|
+
hllabel="Average",
|
|
1200
|
+
returns_label="Drawdown",
|
|
1201
|
+
compound=compound,
|
|
1202
|
+
match_volatility=match_volatility,
|
|
1203
|
+
log_scale=log_scale,
|
|
1204
|
+
resample=resample,
|
|
1205
|
+
fill=True, # Fill area under drawdown curve
|
|
1206
|
+
lw=lw,
|
|
1207
|
+
figsize=figsize,
|
|
1208
|
+
ylabel=ylabel,
|
|
1209
|
+
fontname=fontname,
|
|
1210
|
+
grayscale=grayscale,
|
|
1211
|
+
subtitle=subtitle,
|
|
1212
|
+
savefig=savefig,
|
|
1213
|
+
show=show,
|
|
1214
|
+
raw_data=True, # Skip cumulative transformation for drawdown data
|
|
1215
|
+
)
|
|
1216
|
+
if not show:
|
|
1217
|
+
return fig
|
|
1218
|
+
|
|
1219
|
+
|
|
1220
|
+
def drawdowns_periods(
|
|
1221
|
+
returns: Returns,
|
|
1222
|
+
periods: int = 5,
|
|
1223
|
+
lw: float = 1.5,
|
|
1224
|
+
log_scale: bool = False,
|
|
1225
|
+
fontname: str = "Arial",
|
|
1226
|
+
grayscale: bool = False,
|
|
1227
|
+
title: str | None = None,
|
|
1228
|
+
figsize: tuple[float, float] = (10, 5),
|
|
1229
|
+
ylabel: bool = True,
|
|
1230
|
+
subtitle: bool = True,
|
|
1231
|
+
compounded: bool = True,
|
|
1232
|
+
savefig: str | dict | None = None,
|
|
1233
|
+
show: bool = True,
|
|
1234
|
+
prepare_returns: bool = True,
|
|
1235
|
+
) -> _Figure | None:
|
|
1236
|
+
"""
|
|
1237
|
+
Plot the longest drawdown periods as separate lines for detailed analysis.
|
|
1238
|
+
|
|
1239
|
+
Parameters
|
|
1240
|
+
----------
|
|
1241
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1242
|
+
Daily returns data.
|
|
1243
|
+
periods : int, optional
|
|
1244
|
+
Number of longest drawdown periods to display (default: 5).
|
|
1245
|
+
lw : float, optional
|
|
1246
|
+
Line width for drawdown lines (default: 1.5).
|
|
1247
|
+
log_scale : bool, optional
|
|
1248
|
+
Whether to use logarithmic scale for y-axis (default: False).
|
|
1249
|
+
fontname : str, optional
|
|
1250
|
+
Font family for text elements (default: "Arial").
|
|
1251
|
+
grayscale : bool, optional
|
|
1252
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1253
|
+
title : str, optional
|
|
1254
|
+
Custom title for the plot (default: None).
|
|
1255
|
+
figsize : tuple, optional
|
|
1256
|
+
Figure size as (width, height) in inches (default: (10, 5)).
|
|
1257
|
+
ylabel : bool, optional
|
|
1258
|
+
Whether to show y-axis label (default: True).
|
|
1259
|
+
subtitle : bool, optional
|
|
1260
|
+
Whether to show subtitle with drawdown statistics (default: True).
|
|
1261
|
+
compounded : bool, optional
|
|
1262
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
1263
|
+
savefig : str or dict, optional
|
|
1264
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1265
|
+
show : bool, optional
|
|
1266
|
+
Whether to display the plot (default: True).
|
|
1267
|
+
prepare_returns : bool, optional
|
|
1268
|
+
Whether to prepare returns data (default: True).
|
|
1269
|
+
|
|
1270
|
+
Returns
|
|
1271
|
+
-------
|
|
1272
|
+
matplotlib.figure.Figure or None
|
|
1273
|
+
Figure object if show=False, otherwise None.
|
|
1274
|
+
|
|
1275
|
+
Notes
|
|
1276
|
+
-----
|
|
1277
|
+
Identifies and plots the longest drawdown periods separately. Each period is
|
|
1278
|
+
shown as a different colored line for easy comparison of severity and duration.
|
|
1279
|
+
"""
|
|
1280
|
+
# Prepare returns data if requested
|
|
1281
|
+
if prepare_returns:
|
|
1282
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
1283
|
+
|
|
1284
|
+
# Use core plotting function for longest drawdown periods
|
|
1285
|
+
fig = _core.plot_longest_drawdowns(
|
|
1286
|
+
returns,
|
|
1287
|
+
periods=periods,
|
|
1288
|
+
lw=lw,
|
|
1289
|
+
log_scale=log_scale,
|
|
1290
|
+
fontname=fontname,
|
|
1291
|
+
grayscale=grayscale,
|
|
1292
|
+
title=title,
|
|
1293
|
+
figsize=figsize,
|
|
1294
|
+
ylabel=ylabel,
|
|
1295
|
+
subtitle=subtitle,
|
|
1296
|
+
compounded=compounded,
|
|
1297
|
+
savefig=savefig,
|
|
1298
|
+
show=show,
|
|
1299
|
+
)
|
|
1300
|
+
if not show:
|
|
1301
|
+
return fig
|
|
1302
|
+
|
|
1303
|
+
|
|
1304
|
+
def rolling_beta(
|
|
1305
|
+
returns: Returns,
|
|
1306
|
+
benchmark: Returns | str,
|
|
1307
|
+
window1: int = 126,
|
|
1308
|
+
window1_label: str = "6-Months",
|
|
1309
|
+
window2: int = 252,
|
|
1310
|
+
window2_label: str = "12-Months",
|
|
1311
|
+
lw: float = 1.5,
|
|
1312
|
+
fontname: str = "Arial",
|
|
1313
|
+
grayscale: bool = False,
|
|
1314
|
+
figsize: tuple[float, float] = (10, 3),
|
|
1315
|
+
ylabel: bool = True,
|
|
1316
|
+
subtitle: bool = True,
|
|
1317
|
+
savefig: str | dict | None = None,
|
|
1318
|
+
show: bool = True,
|
|
1319
|
+
prepare_returns: bool = True,
|
|
1320
|
+
) -> _Figure | None:
|
|
1321
|
+
"""
|
|
1322
|
+
Plot rolling beta coefficients over time using multiple window sizes.
|
|
1323
|
+
|
|
1324
|
+
Parameters
|
|
1325
|
+
----------
|
|
1326
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1327
|
+
Daily returns data.
|
|
1328
|
+
benchmark : pandas.Series, pandas.DataFrame, or str
|
|
1329
|
+
Benchmark returns data or ticker symbol.
|
|
1330
|
+
window1 : int, optional
|
|
1331
|
+
First rolling window size in days (default: 126).
|
|
1332
|
+
window1_label : str, optional
|
|
1333
|
+
Label for first window (default: "6-Months").
|
|
1334
|
+
window2 : int, optional
|
|
1335
|
+
Second rolling window size in days (default: 252).
|
|
1336
|
+
window2_label : str, optional
|
|
1337
|
+
Label for second window (default: "12-Months").
|
|
1338
|
+
lw : float, optional
|
|
1339
|
+
Line width for beta lines (default: 1.5).
|
|
1340
|
+
fontname : str, optional
|
|
1341
|
+
Font family for text elements (default: "Arial").
|
|
1342
|
+
grayscale : bool, optional
|
|
1343
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1344
|
+
figsize : tuple, optional
|
|
1345
|
+
Figure size as (width, height) in inches (default: (10, 3)).
|
|
1346
|
+
ylabel : bool, optional
|
|
1347
|
+
Whether to show y-axis label (default: True).
|
|
1348
|
+
subtitle : bool, optional
|
|
1349
|
+
Whether to show subtitle with beta statistics (default: True).
|
|
1350
|
+
savefig : str or dict, optional
|
|
1351
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1352
|
+
show : bool, optional
|
|
1353
|
+
Whether to display the plot (default: True).
|
|
1354
|
+
prepare_returns : bool, optional
|
|
1355
|
+
Whether to prepare returns data (default: True).
|
|
1356
|
+
|
|
1357
|
+
Returns
|
|
1358
|
+
-------
|
|
1359
|
+
matplotlib.figure.Figure or None
|
|
1360
|
+
Figure object if show=False, otherwise None.
|
|
1361
|
+
|
|
1362
|
+
Notes
|
|
1363
|
+
-----
|
|
1364
|
+
Shows how portfolio beta (systematic risk) changes over time relative to benchmark.
|
|
1365
|
+
Uses two different window sizes to show short-term and long-term beta trends.
|
|
1366
|
+
"""
|
|
1367
|
+
# Prepare returns data if requested
|
|
1368
|
+
if prepare_returns:
|
|
1369
|
+
returns = _get_utils()._prepare_returns(returns)
|
|
1370
|
+
|
|
1371
|
+
# Prepare benchmark data to match returns index
|
|
1372
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index) # type: ignore
|
|
1373
|
+
|
|
1374
|
+
# Use core plotting function for rolling beta
|
|
1375
|
+
fig = _core.plot_rolling_beta(
|
|
1376
|
+
returns,
|
|
1377
|
+
benchmark,
|
|
1378
|
+
window1=window1,
|
|
1379
|
+
window1_label=window1_label,
|
|
1380
|
+
window2=window2,
|
|
1381
|
+
window2_label=window2_label,
|
|
1382
|
+
title="Rolling Beta to Benchmark",
|
|
1383
|
+
fontname=fontname,
|
|
1384
|
+
grayscale=grayscale,
|
|
1385
|
+
lw=lw,
|
|
1386
|
+
figsize=figsize,
|
|
1387
|
+
ylabel=ylabel,
|
|
1388
|
+
subtitle=subtitle,
|
|
1389
|
+
savefig=savefig,
|
|
1390
|
+
show=show,
|
|
1391
|
+
)
|
|
1392
|
+
if not show:
|
|
1393
|
+
return fig
|
|
1394
|
+
|
|
1395
|
+
|
|
1396
|
+
def rolling_volatility(
|
|
1397
|
+
returns: Returns,
|
|
1398
|
+
benchmark: Returns | str | None = None,
|
|
1399
|
+
period: int = 126,
|
|
1400
|
+
period_label: str = "6-Months",
|
|
1401
|
+
periods_per_year: int = 252,
|
|
1402
|
+
lw: float = 1.5,
|
|
1403
|
+
fontname: str = "Arial",
|
|
1404
|
+
grayscale: bool = False,
|
|
1405
|
+
figsize: tuple[float, float] = (10, 3),
|
|
1406
|
+
ylabel: str = "Volatility",
|
|
1407
|
+
subtitle: bool = True,
|
|
1408
|
+
savefig: str | dict | None = None,
|
|
1409
|
+
show: bool = True,
|
|
1410
|
+
) -> _Figure | None:
|
|
1411
|
+
"""
|
|
1412
|
+
Plot rolling volatility over time, optionally compared to benchmark.
|
|
1413
|
+
|
|
1414
|
+
Parameters
|
|
1415
|
+
----------
|
|
1416
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1417
|
+
Daily returns data.
|
|
1418
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
1419
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
1420
|
+
period : int, optional
|
|
1421
|
+
Rolling window size in days (default: 126).
|
|
1422
|
+
period_label : str, optional
|
|
1423
|
+
Label for the rolling period (default: "6-Months").
|
|
1424
|
+
periods_per_year : int, optional
|
|
1425
|
+
Number of periods per year for annualization (default: 252).
|
|
1426
|
+
lw : float, optional
|
|
1427
|
+
Line width for volatility lines (default: 1.5).
|
|
1428
|
+
fontname : str, optional
|
|
1429
|
+
Font family for text elements (default: "Arial").
|
|
1430
|
+
grayscale : bool, optional
|
|
1431
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1432
|
+
figsize : tuple, optional
|
|
1433
|
+
Figure size as (width, height) in inches (default: (10, 3)).
|
|
1434
|
+
ylabel : str, optional
|
|
1435
|
+
Y-axis label (default: "Volatility").
|
|
1436
|
+
subtitle : bool, optional
|
|
1437
|
+
Whether to show subtitle with volatility statistics (default: True).
|
|
1438
|
+
savefig : str or dict, optional
|
|
1439
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1440
|
+
show : bool, optional
|
|
1441
|
+
Whether to display the plot (default: True).
|
|
1442
|
+
|
|
1443
|
+
Returns
|
|
1444
|
+
-------
|
|
1445
|
+
matplotlib.figure.Figure or None
|
|
1446
|
+
Figure object if show=False, otherwise None.
|
|
1447
|
+
|
|
1448
|
+
Notes
|
|
1449
|
+
-----
|
|
1450
|
+
Shows rolling volatility (standard deviation) over time. Includes mean volatility
|
|
1451
|
+
as horizontal reference line. Useful for understanding risk patterns over time.
|
|
1452
|
+
"""
|
|
1453
|
+
# Calculate rolling volatility for returns
|
|
1454
|
+
returns = _get_stats().rolling_volatility(returns, period, periods_per_year)
|
|
1455
|
+
|
|
1456
|
+
# Calculate rolling volatility for benchmark if provided
|
|
1457
|
+
if benchmark is not None:
|
|
1458
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index)
|
|
1459
|
+
benchmark = _get_stats().rolling_volatility(
|
|
1460
|
+
benchmark, period, periods_per_year, prepare_returns=False
|
|
1461
|
+
)
|
|
1462
|
+
|
|
1463
|
+
# Use core plotting function for rolling statistics
|
|
1464
|
+
fig = _core.plot_rolling_stats(
|
|
1465
|
+
returns,
|
|
1466
|
+
benchmark,
|
|
1467
|
+
hline=returns.mean(), # Show mean volatility as horizontal line
|
|
1468
|
+
hlw=1.5,
|
|
1469
|
+
ylabel=ylabel,
|
|
1470
|
+
title=f"Rolling Volatility ({period_label})",
|
|
1471
|
+
fontname=fontname,
|
|
1472
|
+
grayscale=grayscale,
|
|
1473
|
+
lw=lw,
|
|
1474
|
+
figsize=figsize,
|
|
1475
|
+
subtitle=subtitle,
|
|
1476
|
+
savefig=savefig,
|
|
1477
|
+
show=show,
|
|
1478
|
+
)
|
|
1479
|
+
if not show:
|
|
1480
|
+
return fig
|
|
1481
|
+
|
|
1482
|
+
|
|
1483
|
+
def rolling_sharpe(
|
|
1484
|
+
returns: Returns,
|
|
1485
|
+
benchmark: Returns | str | None = None,
|
|
1486
|
+
rf: float = 0.0,
|
|
1487
|
+
period: int = 126,
|
|
1488
|
+
period_label: str = "6-Months",
|
|
1489
|
+
periods_per_year: int = 252,
|
|
1490
|
+
lw: float = 1.25,
|
|
1491
|
+
fontname: str = "Arial",
|
|
1492
|
+
grayscale: bool = False,
|
|
1493
|
+
figsize: tuple[float, float] = (10, 3),
|
|
1494
|
+
ylabel: str = "Sharpe",
|
|
1495
|
+
subtitle: bool = True,
|
|
1496
|
+
savefig: str | dict | None = None,
|
|
1497
|
+
show: bool = True,
|
|
1498
|
+
) -> _Figure | None:
|
|
1499
|
+
"""
|
|
1500
|
+
Plot rolling Sharpe ratio over time, optionally compared to benchmark.
|
|
1501
|
+
|
|
1502
|
+
Parameters
|
|
1503
|
+
----------
|
|
1504
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1505
|
+
Daily returns data.
|
|
1506
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
1507
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
1508
|
+
rf : float, optional
|
|
1509
|
+
Risk-free rate for Sharpe calculation (default: 0.0).
|
|
1510
|
+
period : int, optional
|
|
1511
|
+
Rolling window size in days (default: 126).
|
|
1512
|
+
period_label : str, optional
|
|
1513
|
+
Label for the rolling period (default: "6-Months").
|
|
1514
|
+
periods_per_year : int, optional
|
|
1515
|
+
Number of periods per year for annualization (default: 252).
|
|
1516
|
+
lw : float, optional
|
|
1517
|
+
Line width for Sharpe lines (default: 1.25).
|
|
1518
|
+
fontname : str, optional
|
|
1519
|
+
Font family for text elements (default: "Arial").
|
|
1520
|
+
grayscale : bool, optional
|
|
1521
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1522
|
+
figsize : tuple, optional
|
|
1523
|
+
Figure size as (width, height) in inches (default: (10, 3)).
|
|
1524
|
+
ylabel : str, optional
|
|
1525
|
+
Y-axis label (default: "Sharpe").
|
|
1526
|
+
subtitle : bool, optional
|
|
1527
|
+
Whether to show subtitle with Sharpe statistics (default: True).
|
|
1528
|
+
savefig : str or dict, optional
|
|
1529
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1530
|
+
show : bool, optional
|
|
1531
|
+
Whether to display the plot (default: True).
|
|
1532
|
+
|
|
1533
|
+
Returns
|
|
1534
|
+
-------
|
|
1535
|
+
matplotlib.figure.Figure or None
|
|
1536
|
+
Figure object if show=False, otherwise None.
|
|
1537
|
+
|
|
1538
|
+
Notes
|
|
1539
|
+
-----
|
|
1540
|
+
Shows rolling Sharpe ratio (risk-adjusted returns) over time. Higher values
|
|
1541
|
+
indicate better risk-adjusted performance. Includes mean Sharpe as reference.
|
|
1542
|
+
"""
|
|
1543
|
+
# Calculate rolling Sharpe ratio for returns
|
|
1544
|
+
returns = _get_stats().rolling_sharpe(
|
|
1545
|
+
returns,
|
|
1546
|
+
rf,
|
|
1547
|
+
period,
|
|
1548
|
+
True, # prepare_returns
|
|
1549
|
+
periods_per_year,
|
|
1550
|
+
)
|
|
1551
|
+
|
|
1552
|
+
# Calculate rolling Sharpe ratio for benchmark if provided
|
|
1553
|
+
if benchmark is not None:
|
|
1554
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
|
|
1555
|
+
benchmark = _get_stats().rolling_sharpe(
|
|
1556
|
+
benchmark, rf, period, True, periods_per_year, prepare_returns=False
|
|
1557
|
+
)
|
|
1558
|
+
|
|
1559
|
+
# Use core plotting function for rolling statistics
|
|
1560
|
+
fig = _core.plot_rolling_stats(
|
|
1561
|
+
returns,
|
|
1562
|
+
benchmark,
|
|
1563
|
+
hline=returns.mean(), # Show mean Sharpe as horizontal line
|
|
1564
|
+
hlw=1.5,
|
|
1565
|
+
ylabel=ylabel,
|
|
1566
|
+
title=f"Rolling Sharpe ({period_label})",
|
|
1567
|
+
fontname=fontname,
|
|
1568
|
+
grayscale=grayscale,
|
|
1569
|
+
lw=lw,
|
|
1570
|
+
figsize=figsize,
|
|
1571
|
+
subtitle=subtitle,
|
|
1572
|
+
savefig=savefig,
|
|
1573
|
+
show=show,
|
|
1574
|
+
)
|
|
1575
|
+
if not show:
|
|
1576
|
+
return fig
|
|
1577
|
+
|
|
1578
|
+
|
|
1579
|
+
def rolling_sortino(
|
|
1580
|
+
returns: Returns,
|
|
1581
|
+
benchmark: Returns | str | None = None,
|
|
1582
|
+
rf: float = 0.0,
|
|
1583
|
+
period: int = 126,
|
|
1584
|
+
period_label: str = "6-Months",
|
|
1585
|
+
periods_per_year: int = 252,
|
|
1586
|
+
lw: float = 1.25,
|
|
1587
|
+
fontname: str = "Arial",
|
|
1588
|
+
grayscale: bool = False,
|
|
1589
|
+
figsize: tuple[float, float] = (10, 3),
|
|
1590
|
+
ylabel: str = "Sortino",
|
|
1591
|
+
subtitle: bool = True,
|
|
1592
|
+
savefig: str | dict | None = None,
|
|
1593
|
+
show: bool = True,
|
|
1594
|
+
) -> _Figure | None:
|
|
1595
|
+
"""
|
|
1596
|
+
Plot rolling Sortino ratio over time, optionally compared to benchmark.
|
|
1597
|
+
|
|
1598
|
+
Parameters
|
|
1599
|
+
----------
|
|
1600
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1601
|
+
Daily returns data.
|
|
1602
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
1603
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
1604
|
+
rf : float, optional
|
|
1605
|
+
Risk-free rate for Sortino calculation (default: 0.0).
|
|
1606
|
+
period : int, optional
|
|
1607
|
+
Rolling window size in days (default: 126).
|
|
1608
|
+
period_label : str, optional
|
|
1609
|
+
Label for the rolling period (default: "6-Months").
|
|
1610
|
+
periods_per_year : int, optional
|
|
1611
|
+
Number of periods per year for annualization (default: 252).
|
|
1612
|
+
lw : float, optional
|
|
1613
|
+
Line width for Sortino lines (default: 1.25).
|
|
1614
|
+
fontname : str, optional
|
|
1615
|
+
Font family for text elements (default: "Arial").
|
|
1616
|
+
grayscale : bool, optional
|
|
1617
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1618
|
+
figsize : tuple, optional
|
|
1619
|
+
Figure size as (width, height) in inches (default: (10, 3)).
|
|
1620
|
+
ylabel : str, optional
|
|
1621
|
+
Y-axis label (default: "Sortino").
|
|
1622
|
+
subtitle : bool, optional
|
|
1623
|
+
Whether to show subtitle with Sortino statistics (default: True).
|
|
1624
|
+
savefig : str or dict, optional
|
|
1625
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1626
|
+
show : bool, optional
|
|
1627
|
+
Whether to display the plot (default: True).
|
|
1628
|
+
|
|
1629
|
+
Returns
|
|
1630
|
+
-------
|
|
1631
|
+
matplotlib.figure.Figure or None
|
|
1632
|
+
Figure object if show=False, otherwise None.
|
|
1633
|
+
|
|
1634
|
+
Notes
|
|
1635
|
+
-----
|
|
1636
|
+
Shows rolling Sortino ratio (downside deviation adjusted returns) over time.
|
|
1637
|
+
Similar to Sharpe but only considers downside volatility. Higher values indicate
|
|
1638
|
+
better downside-adjusted performance.
|
|
1639
|
+
"""
|
|
1640
|
+
# Calculate rolling Sortino ratio for returns
|
|
1641
|
+
returns = _get_stats().rolling_sortino(returns, rf, period, True, periods_per_year)
|
|
1642
|
+
|
|
1643
|
+
# Calculate rolling Sortino ratio for benchmark if provided
|
|
1644
|
+
if benchmark is not None:
|
|
1645
|
+
benchmark = _get_utils()._prepare_benchmark(benchmark, returns.index, rf)
|
|
1646
|
+
benchmark = _get_stats().rolling_sortino(
|
|
1647
|
+
benchmark, rf, period, True, periods_per_year, prepare_returns=False
|
|
1648
|
+
)
|
|
1649
|
+
|
|
1650
|
+
# Use core plotting function for rolling statistics
|
|
1651
|
+
fig = _core.plot_rolling_stats(
|
|
1652
|
+
returns,
|
|
1653
|
+
benchmark,
|
|
1654
|
+
hline=returns.mean(), # Show mean Sortino as horizontal line
|
|
1655
|
+
hlw=1.5,
|
|
1656
|
+
ylabel=ylabel,
|
|
1657
|
+
title=f"Rolling Sortino ({period_label})",
|
|
1658
|
+
fontname=fontname,
|
|
1659
|
+
grayscale=grayscale,
|
|
1660
|
+
lw=lw,
|
|
1661
|
+
figsize=figsize,
|
|
1662
|
+
subtitle=subtitle,
|
|
1663
|
+
savefig=savefig,
|
|
1664
|
+
show=show,
|
|
1665
|
+
)
|
|
1666
|
+
if not show:
|
|
1667
|
+
return fig
|
|
1668
|
+
|
|
1669
|
+
|
|
1670
|
+
def monthly_heatmap(
|
|
1671
|
+
returns: Returns,
|
|
1672
|
+
benchmark: Returns | str | None = None,
|
|
1673
|
+
annot_size: int = 10,
|
|
1674
|
+
figsize: tuple[float, float] = (8, 5),
|
|
1675
|
+
cbar: bool = True,
|
|
1676
|
+
square: bool = False,
|
|
1677
|
+
returns_label: str = "Strategy",
|
|
1678
|
+
compounded: bool = True,
|
|
1679
|
+
eoy: bool = False,
|
|
1680
|
+
grayscale: bool = False,
|
|
1681
|
+
fontname: str = "Arial",
|
|
1682
|
+
ylabel: bool = True,
|
|
1683
|
+
savefig: str | dict | None = None,
|
|
1684
|
+
show: bool = True,
|
|
1685
|
+
active: bool = False,
|
|
1686
|
+
) -> _Figure | None:
|
|
1687
|
+
"""
|
|
1688
|
+
Create a heatmap of monthly returns showing performance across years and months.
|
|
1689
|
+
|
|
1690
|
+
Parameters
|
|
1691
|
+
----------
|
|
1692
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1693
|
+
Daily returns data.
|
|
1694
|
+
benchmark : pandas.Series, pandas.DataFrame, or str, optional
|
|
1695
|
+
Benchmark returns data or ticker symbol (default: None).
|
|
1696
|
+
annot_size : int, optional
|
|
1697
|
+
Font size for annotations in heatmap cells (default: 10).
|
|
1698
|
+
figsize : tuple, optional
|
|
1699
|
+
Figure size as (width, height) in inches (default: (8, 5)).
|
|
1700
|
+
cbar : bool, optional
|
|
1701
|
+
Whether to show color bar (default: True).
|
|
1702
|
+
square : bool, optional
|
|
1703
|
+
Whether to make heatmap cells square (default: False).
|
|
1704
|
+
returns_label : str, optional
|
|
1705
|
+
Label for the returns series (default: "Strategy").
|
|
1706
|
+
compounded : bool, optional
|
|
1707
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
1708
|
+
eoy : bool, optional
|
|
1709
|
+
Whether to include end-of-year column (default: False).
|
|
1710
|
+
grayscale : bool, optional
|
|
1711
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1712
|
+
fontname : str, optional
|
|
1713
|
+
Font family for text elements (default: "Arial").
|
|
1714
|
+
ylabel : bool, optional
|
|
1715
|
+
Whether to show y-axis label (default: True).
|
|
1716
|
+
savefig : str or dict, optional
|
|
1717
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1718
|
+
show : bool, optional
|
|
1719
|
+
Whether to display the plot (default: True).
|
|
1720
|
+
active : bool, optional
|
|
1721
|
+
If True, shows active returns (returns - benchmark) (default: False).
|
|
1722
|
+
|
|
1723
|
+
Returns
|
|
1724
|
+
-------
|
|
1725
|
+
matplotlib.figure.Figure or None
|
|
1726
|
+
Figure object if show=False, otherwise None.
|
|
1727
|
+
|
|
1728
|
+
Notes
|
|
1729
|
+
-----
|
|
1730
|
+
Creates a color-coded heatmap where each cell represents a month's performance.
|
|
1731
|
+
Green indicates positive returns, red indicates negative returns. Useful for
|
|
1732
|
+
identifying seasonal patterns and performance consistency.
|
|
1733
|
+
"""
|
|
1734
|
+
# colors, ls, alpha = _core._get_colors(grayscale)
|
|
1735
|
+
# Select color map based on grayscale preference
|
|
1736
|
+
cmap = "gray" if grayscale else "RdYlGn"
|
|
1737
|
+
|
|
1738
|
+
# Convert to monthly returns and convert to percentage
|
|
1739
|
+
returns = _get_stats().monthly_returns(returns, eoy=eoy, compounded=compounded) * 100
|
|
1740
|
+
|
|
1741
|
+
# Calculate figure height based on number of years
|
|
1742
|
+
fig_height = len(returns) / 2.5
|
|
1743
|
+
|
|
1744
|
+
# Use current figure size if not specified
|
|
1745
|
+
if figsize is None:
|
|
1746
|
+
size = list(_plt.gcf().get_size_inches())
|
|
1747
|
+
figsize = (size[0], size[1])
|
|
1748
|
+
|
|
1749
|
+
# Adjust figure size based on data and color bar
|
|
1750
|
+
figsize = (figsize[0], max([fig_height, figsize[1]]))
|
|
1751
|
+
|
|
1752
|
+
if cbar:
|
|
1753
|
+
figsize = (figsize[0] * 1.051, max([fig_height, figsize[1]]))
|
|
1754
|
+
|
|
1755
|
+
# Create figure and axis
|
|
1756
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
1757
|
+
|
|
1758
|
+
# Remove spines for cleaner appearance
|
|
1759
|
+
ax.spines["top"].set_visible(False)
|
|
1760
|
+
ax.spines["right"].set_visible(False)
|
|
1761
|
+
ax.spines["bottom"].set_visible(False)
|
|
1762
|
+
ax.spines["left"].set_visible(False)
|
|
1763
|
+
|
|
1764
|
+
# Set background colors
|
|
1765
|
+
fig.set_facecolor("white")
|
|
1766
|
+
ax.set_facecolor("white")
|
|
1767
|
+
|
|
1768
|
+
# _sns.set(font_scale=.9)
|
|
1769
|
+
# Create heatmap for active returns vs benchmark
|
|
1770
|
+
if active and benchmark is not None:
|
|
1771
|
+
ax.set_title(
|
|
1772
|
+
f"{returns_label} - Monthly Active Returns (%)\n",
|
|
1773
|
+
fontsize=14,
|
|
1774
|
+
y=0.995,
|
|
1775
|
+
fontname=fontname,
|
|
1776
|
+
fontweight="bold",
|
|
1777
|
+
color="black",
|
|
1778
|
+
)
|
|
1779
|
+
# Calculate benchmark monthly returns
|
|
1780
|
+
benchmark = (
|
|
1781
|
+
_get_stats().monthly_returns(benchmark, eoy=eoy, compounded=compounded) * 100
|
|
1782
|
+
)
|
|
1783
|
+
# Calculate active returns (strategy - benchmark)
|
|
1784
|
+
active_returns = returns - benchmark
|
|
1785
|
+
|
|
1786
|
+
# Create heatmap with active returns
|
|
1787
|
+
ax = _sns.heatmap(
|
|
1788
|
+
active_returns,
|
|
1789
|
+
ax=ax,
|
|
1790
|
+
annot=True,
|
|
1791
|
+
center=0, # Center colormap at zero
|
|
1792
|
+
annot_kws={"size": annot_size},
|
|
1793
|
+
fmt="0.2f",
|
|
1794
|
+
linewidths=0.5,
|
|
1795
|
+
square=square,
|
|
1796
|
+
cbar=cbar,
|
|
1797
|
+
cmap=cmap,
|
|
1798
|
+
cbar_kws={"format": "%.0f%%"},
|
|
1799
|
+
)
|
|
1800
|
+
else:
|
|
1801
|
+
# Create standard monthly returns heatmap
|
|
1802
|
+
ax.set_title(
|
|
1803
|
+
f"{returns_label} - Monthly Returns (%)\n",
|
|
1804
|
+
fontsize=12,
|
|
1805
|
+
y=0.995,
|
|
1806
|
+
fontname=fontname,
|
|
1807
|
+
fontweight="bold",
|
|
1808
|
+
color="black",
|
|
1809
|
+
)
|
|
1810
|
+
|
|
1811
|
+
# Create heatmap with monthly returns
|
|
1812
|
+
ax = _sns.heatmap(
|
|
1813
|
+
returns,
|
|
1814
|
+
ax=ax,
|
|
1815
|
+
annot=True,
|
|
1816
|
+
center=0, # Center colormap at zero
|
|
1817
|
+
annot_kws={"size": annot_size},
|
|
1818
|
+
fmt="0.2f",
|
|
1819
|
+
linewidths=0.5,
|
|
1820
|
+
square=square,
|
|
1821
|
+
cbar=cbar,
|
|
1822
|
+
cmap=cmap,
|
|
1823
|
+
cbar_kws={"format": "%.0f%%"},
|
|
1824
|
+
)
|
|
1825
|
+
|
|
1826
|
+
# Format color bar if present
|
|
1827
|
+
if cbar:
|
|
1828
|
+
cbar = ax.collections[0].colorbar
|
|
1829
|
+
cbar.ax.tick_params(labelsize=annot_size)
|
|
1830
|
+
|
|
1831
|
+
# Set y-axis label
|
|
1832
|
+
if ylabel:
|
|
1833
|
+
ax.set_ylabel("Years", fontname=fontname, fontweight="bold", fontsize=12)
|
|
1834
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
1835
|
+
|
|
1836
|
+
# Format tick labels
|
|
1837
|
+
ax.tick_params(colors="#808080")
|
|
1838
|
+
_plt.xticks(rotation=0, fontsize=annot_size * 1.2)
|
|
1839
|
+
_plt.yticks(rotation=0, fontsize=annot_size * 1.2)
|
|
1840
|
+
|
|
1841
|
+
# Apply layout adjustments with error handling
|
|
1842
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1843
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
1844
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1845
|
+
fig.tight_layout(w_pad=0, h_pad=0)
|
|
1846
|
+
|
|
1847
|
+
# Save figure if requested
|
|
1848
|
+
if savefig:
|
|
1849
|
+
if isinstance(savefig, dict):
|
|
1850
|
+
_plt.savefig(**savefig)
|
|
1851
|
+
else:
|
|
1852
|
+
_plt.savefig(savefig)
|
|
1853
|
+
|
|
1854
|
+
# Show plot if requested
|
|
1855
|
+
if show:
|
|
1856
|
+
_plt.show(block=False)
|
|
1857
|
+
|
|
1858
|
+
_plt.close()
|
|
1859
|
+
|
|
1860
|
+
if not show:
|
|
1861
|
+
return fig
|
|
1862
|
+
|
|
1863
|
+
return None
|
|
1864
|
+
|
|
1865
|
+
|
|
1866
|
+
def monthly_returns(
|
|
1867
|
+
returns: Returns,
|
|
1868
|
+
annot_size: int = 9,
|
|
1869
|
+
figsize: tuple[float, float] = (10, 5),
|
|
1870
|
+
cbar: bool = True,
|
|
1871
|
+
square: bool = False,
|
|
1872
|
+
compounded: bool = True,
|
|
1873
|
+
eoy: bool = False,
|
|
1874
|
+
grayscale: bool = False,
|
|
1875
|
+
fontname: str = "Arial",
|
|
1876
|
+
ylabel: bool = True,
|
|
1877
|
+
savefig: str | dict | None = None,
|
|
1878
|
+
show: bool = True,
|
|
1879
|
+
) -> _Figure | None:
|
|
1880
|
+
"""
|
|
1881
|
+
Create a heatmap of monthly returns (wrapper function for monthly_heatmap).
|
|
1882
|
+
|
|
1883
|
+
Parameters
|
|
1884
|
+
----------
|
|
1885
|
+
returns : pandas.Series or pandas.DataFrame
|
|
1886
|
+
Daily returns data.
|
|
1887
|
+
annot_size : int, optional
|
|
1888
|
+
Font size for annotations in heatmap cells (default: 9).
|
|
1889
|
+
figsize : tuple, optional
|
|
1890
|
+
Figure size as (width, height) in inches (default: (10, 5)).
|
|
1891
|
+
cbar : bool, optional
|
|
1892
|
+
Whether to show color bar (default: True).
|
|
1893
|
+
square : bool, optional
|
|
1894
|
+
Whether to make heatmap cells square (default: False).
|
|
1895
|
+
compounded : bool, optional
|
|
1896
|
+
If True, uses compound returns; if False, uses simple returns (default: True).
|
|
1897
|
+
eoy : bool, optional
|
|
1898
|
+
Whether to include end-of-year column (default: False).
|
|
1899
|
+
grayscale : bool, optional
|
|
1900
|
+
If True, uses grayscale colors instead of default color scheme (default: False).
|
|
1901
|
+
fontname : str, optional
|
|
1902
|
+
Font family for text elements (default: "Arial").
|
|
1903
|
+
ylabel : bool, optional
|
|
1904
|
+
Whether to show y-axis label (default: True).
|
|
1905
|
+
savefig : str or dict, optional
|
|
1906
|
+
Path to save figure or dict with matplotlib savefig parameters.
|
|
1907
|
+
show : bool, optional
|
|
1908
|
+
Whether to display the plot (default: True).
|
|
1909
|
+
|
|
1910
|
+
Returns
|
|
1911
|
+
-------
|
|
1912
|
+
matplotlib.figure.Figure or None
|
|
1913
|
+
Figure object if show=False, otherwise None.
|
|
1914
|
+
|
|
1915
|
+
Notes
|
|
1916
|
+
-----
|
|
1917
|
+
This is a convenience wrapper around monthly_heatmap() with commonly used
|
|
1918
|
+
default parameters for displaying monthly returns.
|
|
1919
|
+
"""
|
|
1920
|
+
# Call monthly_heatmap with provided parameters
|
|
1921
|
+
return monthly_heatmap(
|
|
1922
|
+
returns=returns,
|
|
1923
|
+
annot_size=annot_size,
|
|
1924
|
+
figsize=figsize,
|
|
1925
|
+
cbar=cbar,
|
|
1926
|
+
square=square,
|
|
1927
|
+
compounded=compounded,
|
|
1928
|
+
eoy=eoy,
|
|
1929
|
+
grayscale=grayscale,
|
|
1930
|
+
fontname=fontname,
|
|
1931
|
+
ylabel=ylabel,
|
|
1932
|
+
savefig=savefig,
|
|
1933
|
+
show=show,
|
|
1934
|
+
)
|
|
1935
|
+
|
|
1936
|
+
|
|
1937
|
+
# ======== MONTE CARLO PLOTS ========
|
|
1938
|
+
|
|
1939
|
+
|
|
1940
|
+
def montecarlo(
|
|
1941
|
+
mc_result_or_returns: Returns | Any,
|
|
1942
|
+
sims: int = 1000,
|
|
1943
|
+
bust: float | None = None,
|
|
1944
|
+
goal: float | None = None,
|
|
1945
|
+
seed: int | None = None,
|
|
1946
|
+
title: str = "Monte Carlo Simulation",
|
|
1947
|
+
figsize: tuple[float, float] = (10, 6),
|
|
1948
|
+
grayscale: bool = False,
|
|
1949
|
+
fontname: str = "Arial",
|
|
1950
|
+
ylabel: bool = True,
|
|
1951
|
+
subtitle: bool = True,
|
|
1952
|
+
savefig: str | dict | None = None,
|
|
1953
|
+
show: bool = True,
|
|
1954
|
+
confidence_level: float = 0.95,
|
|
1955
|
+
) -> _Figure | None:
|
|
1956
|
+
"""
|
|
1957
|
+
Plot Monte Carlo simulation results.
|
|
1958
|
+
|
|
1959
|
+
This function can accept either a MonteCarloResult object (from qs.stats.montecarlo)
|
|
1960
|
+
or a returns Series to run a new simulation.
|
|
1961
|
+
|
|
1962
|
+
Parameters
|
|
1963
|
+
----------
|
|
1964
|
+
mc_result_or_returns : MonteCarloResult or pd.Series
|
|
1965
|
+
Either a MonteCarloResult object or a returns Series to simulate.
|
|
1966
|
+
sims : int, optional
|
|
1967
|
+
Number of simulations (only used if returns Series provided, default: 1000).
|
|
1968
|
+
bust : float, optional
|
|
1969
|
+
Drawdown threshold for "bust" probability (e.g., -0.1 for -10%).
|
|
1970
|
+
goal : float, optional
|
|
1971
|
+
Return threshold for "goal" probability (e.g., 1.0 for +100%).
|
|
1972
|
+
seed : int, optional
|
|
1973
|
+
Random seed for reproducibility.
|
|
1974
|
+
title : str, optional
|
|
1975
|
+
Chart title (default: "Monte Carlo Simulation").
|
|
1976
|
+
figsize : tuple, optional
|
|
1977
|
+
Figure size (default: (10, 6)).
|
|
1978
|
+
grayscale : bool, optional
|
|
1979
|
+
Whether to use grayscale colors (default: False).
|
|
1980
|
+
fontname : str, optional
|
|
1981
|
+
Font name for labels (default: "Arial").
|
|
1982
|
+
ylabel : bool, optional
|
|
1983
|
+
Whether to show y-axis label (default: True).
|
|
1984
|
+
subtitle : bool, optional
|
|
1985
|
+
Whether to show subtitle with statistics (default: True).
|
|
1986
|
+
savefig : str or dict, optional
|
|
1987
|
+
Save figure parameters.
|
|
1988
|
+
show : bool, optional
|
|
1989
|
+
Whether to display the plot (default: True).
|
|
1990
|
+
confidence_level : float, optional
|
|
1991
|
+
Confidence level for shaded band (default: 0.95).
|
|
1992
|
+
|
|
1993
|
+
Returns
|
|
1994
|
+
-------
|
|
1995
|
+
matplotlib.figure.Figure or None
|
|
1996
|
+
Figure object if show=False, otherwise None.
|
|
1997
|
+
|
|
1998
|
+
Examples
|
|
1999
|
+
--------
|
|
2000
|
+
>>> import quantstats as qs
|
|
2001
|
+
>>> returns = qs.utils.download_returns("SPY")
|
|
2002
|
+
>>> # Run simulation and plot
|
|
2003
|
+
>>> qs.plots.montecarlo(returns, sims=1000, bust=-0.2, goal=0.5)
|
|
2004
|
+
>>> # Or use pre-computed result
|
|
2005
|
+
>>> mc = qs.stats.montecarlo(returns, sims=1000)
|
|
2006
|
+
>>> mc.plot()
|
|
2007
|
+
"""
|
|
2008
|
+
from .._montecarlo import MonteCarloResult
|
|
2009
|
+
|
|
2010
|
+
# Check if we received a MonteCarloResult or returns data
|
|
2011
|
+
if isinstance(mc_result_or_returns, MonteCarloResult):
|
|
2012
|
+
mc_result = mc_result_or_returns
|
|
2013
|
+
else:
|
|
2014
|
+
# Run Monte Carlo simulation
|
|
2015
|
+
mc_result = _get_stats().montecarlo(
|
|
2016
|
+
mc_result_or_returns,
|
|
2017
|
+
sims=sims,
|
|
2018
|
+
bust=bust,
|
|
2019
|
+
goal=goal,
|
|
2020
|
+
seed=seed,
|
|
2021
|
+
)
|
|
2022
|
+
|
|
2023
|
+
return _core.plot_montecarlo(
|
|
2024
|
+
mc_result,
|
|
2025
|
+
title=title,
|
|
2026
|
+
figsize=figsize,
|
|
2027
|
+
grayscale=grayscale,
|
|
2028
|
+
fontname=fontname,
|
|
2029
|
+
ylabel=ylabel,
|
|
2030
|
+
subtitle=subtitle,
|
|
2031
|
+
savefig=savefig,
|
|
2032
|
+
show=show,
|
|
2033
|
+
confidence_level=confidence_level,
|
|
2034
|
+
)
|
|
2035
|
+
|
|
2036
|
+
|
|
2037
|
+
def montecarlo_distribution(
|
|
2038
|
+
mc_result_or_returns: Returns | Any,
|
|
2039
|
+
sims: int = 1000,
|
|
2040
|
+
seed: int | None = None,
|
|
2041
|
+
title: str = "Terminal Value Distribution",
|
|
2042
|
+
figsize: tuple[float, float] = (10, 6),
|
|
2043
|
+
grayscale: bool = False,
|
|
2044
|
+
fontname: str = "Arial",
|
|
2045
|
+
ylabel: bool = True,
|
|
2046
|
+
subtitle: bool = True,
|
|
2047
|
+
savefig: str | dict | None = None,
|
|
2048
|
+
show: bool = True,
|
|
2049
|
+
bins: int = 50,
|
|
2050
|
+
) -> _Figure | None:
|
|
2051
|
+
"""
|
|
2052
|
+
Plot histogram of terminal values from Monte Carlo simulation.
|
|
2053
|
+
|
|
2054
|
+
This function can accept either a MonteCarloResult object (from qs.stats.montecarlo)
|
|
2055
|
+
or a returns Series to run a new simulation.
|
|
2056
|
+
|
|
2057
|
+
Parameters
|
|
2058
|
+
----------
|
|
2059
|
+
mc_result_or_returns : MonteCarloResult or pd.Series
|
|
2060
|
+
Either a MonteCarloResult object or a returns Series to simulate.
|
|
2061
|
+
sims : int, optional
|
|
2062
|
+
Number of simulations (only used if returns Series provided, default: 1000).
|
|
2063
|
+
seed : int, optional
|
|
2064
|
+
Random seed for reproducibility.
|
|
2065
|
+
title : str, optional
|
|
2066
|
+
Chart title (default: "Terminal Value Distribution").
|
|
2067
|
+
figsize : tuple, optional
|
|
2068
|
+
Figure size (default: (10, 6)).
|
|
2069
|
+
grayscale : bool, optional
|
|
2070
|
+
Whether to use grayscale colors (default: False).
|
|
2071
|
+
fontname : str, optional
|
|
2072
|
+
Font name for labels (default: "Arial").
|
|
2073
|
+
ylabel : bool, optional
|
|
2074
|
+
Whether to show y-axis label (default: True).
|
|
2075
|
+
subtitle : bool, optional
|
|
2076
|
+
Whether to show subtitle with statistics (default: True).
|
|
2077
|
+
savefig : str or dict, optional
|
|
2078
|
+
Save figure parameters.
|
|
2079
|
+
show : bool, optional
|
|
2080
|
+
Whether to display the plot (default: True).
|
|
2081
|
+
bins : int, optional
|
|
2082
|
+
Number of histogram bins (default: 50).
|
|
2083
|
+
|
|
2084
|
+
Returns
|
|
2085
|
+
-------
|
|
2086
|
+
matplotlib.figure.Figure or None
|
|
2087
|
+
Figure object if show=False, otherwise None.
|
|
2088
|
+
"""
|
|
2089
|
+
from .._montecarlo import MonteCarloResult
|
|
2090
|
+
|
|
2091
|
+
# Check if we received a MonteCarloResult or returns data
|
|
2092
|
+
if isinstance(mc_result_or_returns, MonteCarloResult):
|
|
2093
|
+
mc_result = mc_result_or_returns
|
|
2094
|
+
else:
|
|
2095
|
+
# Run Monte Carlo simulation
|
|
2096
|
+
mc_result = _get_stats().montecarlo(mc_result_or_returns, sims=sims, seed=seed)
|
|
2097
|
+
|
|
2098
|
+
return _core.plot_montecarlo_distribution(
|
|
2099
|
+
mc_result,
|
|
2100
|
+
title=title,
|
|
2101
|
+
figsize=figsize,
|
|
2102
|
+
grayscale=grayscale,
|
|
2103
|
+
fontname=fontname,
|
|
2104
|
+
ylabel=ylabel,
|
|
2105
|
+
subtitle=subtitle,
|
|
2106
|
+
savefig=savefig,
|
|
2107
|
+
show=show,
|
|
2108
|
+
bins=bins,
|
|
2109
|
+
)
|