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,2173 @@
|
|
|
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 contextlib
|
|
23
|
+
from typing import TYPE_CHECKING
|
|
24
|
+
|
|
25
|
+
import matplotlib.pyplot as _plt
|
|
26
|
+
|
|
27
|
+
# Set default font to Arial, fall back gracefully if not available
|
|
28
|
+
with contextlib.suppress(KeyError, ValueError, OSError):
|
|
29
|
+
_plt.rcParams["font.family"] = "Arial"
|
|
30
|
+
|
|
31
|
+
import matplotlib.dates as _mdates
|
|
32
|
+
import numpy as _np
|
|
33
|
+
import pandas as _pd
|
|
34
|
+
import seaborn as _sns
|
|
35
|
+
from matplotlib.ticker import (
|
|
36
|
+
FormatStrFormatter as _FormatStrFormatter,
|
|
37
|
+
)
|
|
38
|
+
from matplotlib.ticker import (
|
|
39
|
+
FuncFormatter as _FuncFormatter,
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
# Lazy import to avoid circular dependency during package initialization
|
|
43
|
+
_stats = None
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _get_stats():
|
|
47
|
+
global _stats
|
|
48
|
+
if _stats is None:
|
|
49
|
+
from .. import stats
|
|
50
|
+
_stats = stats
|
|
51
|
+
return _stats
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
import contextlib
|
|
55
|
+
|
|
56
|
+
from .._compat import safe_resample
|
|
57
|
+
|
|
58
|
+
if TYPE_CHECKING:
|
|
59
|
+
pass
|
|
60
|
+
|
|
61
|
+
# Type alias for return data
|
|
62
|
+
Returns = _pd.Series | _pd.DataFrame
|
|
63
|
+
|
|
64
|
+
# Configure seaborn theme with custom styling
|
|
65
|
+
_sns.set_theme(
|
|
66
|
+
font_scale=1.1,
|
|
67
|
+
rc={
|
|
68
|
+
"figure.figsize": (10, 6),
|
|
69
|
+
"axes.facecolor": "white",
|
|
70
|
+
"figure.facecolor": "white",
|
|
71
|
+
"grid.color": "#dddddd",
|
|
72
|
+
"grid.linewidth": 0.5,
|
|
73
|
+
"lines.linewidth": 1.5,
|
|
74
|
+
"text.color": "#333333",
|
|
75
|
+
"xtick.color": "#666666",
|
|
76
|
+
"ytick.color": "#666666",
|
|
77
|
+
},
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
# Color palettes for different chart styles
|
|
81
|
+
_FLATUI_COLORS = [
|
|
82
|
+
"#5C5C5C", # benchmark — medium dark gray
|
|
83
|
+
"#6B9E00", # strategy — medium dark lime
|
|
84
|
+
"#BA516B",
|
|
85
|
+
"#4FA487",
|
|
86
|
+
"#9B59B6",
|
|
87
|
+
"#613F66",
|
|
88
|
+
"#84B082",
|
|
89
|
+
"#DC136C",
|
|
90
|
+
"#559CAD",
|
|
91
|
+
"#4A5899",
|
|
92
|
+
]
|
|
93
|
+
_GRAYSCALE_COLORS = [
|
|
94
|
+
"#000000",
|
|
95
|
+
"#222222",
|
|
96
|
+
"#555555",
|
|
97
|
+
"#888888",
|
|
98
|
+
"#AAAAAA",
|
|
99
|
+
"#CCCCCC",
|
|
100
|
+
"#EEEEEE",
|
|
101
|
+
"#333333",
|
|
102
|
+
"#666666",
|
|
103
|
+
"#999999",
|
|
104
|
+
]
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _get_colors(grayscale):
|
|
108
|
+
"""
|
|
109
|
+
Get color palette, line style, and alpha values based on grayscale setting
|
|
110
|
+
|
|
111
|
+
Parameters
|
|
112
|
+
----------
|
|
113
|
+
grayscale : bool
|
|
114
|
+
Whether to use grayscale colors
|
|
115
|
+
|
|
116
|
+
Returns
|
|
117
|
+
-------
|
|
118
|
+
tuple
|
|
119
|
+
(colors, line_style, alpha) - Color palette, line style, and alpha value
|
|
120
|
+
"""
|
|
121
|
+
colors = _FLATUI_COLORS
|
|
122
|
+
ls = "-"
|
|
123
|
+
alpha = 0.8
|
|
124
|
+
if grayscale:
|
|
125
|
+
colors = _GRAYSCALE_COLORS
|
|
126
|
+
ls = "-"
|
|
127
|
+
alpha = 0.5
|
|
128
|
+
return colors, ls, alpha
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def plot_returns_bars(
|
|
132
|
+
returns,
|
|
133
|
+
benchmark=None,
|
|
134
|
+
returns_label="Strategy",
|
|
135
|
+
hline=None,
|
|
136
|
+
hlw=None,
|
|
137
|
+
hlcolor="red",
|
|
138
|
+
hllabel="",
|
|
139
|
+
resample="YE",
|
|
140
|
+
title="Returns",
|
|
141
|
+
match_volatility=False,
|
|
142
|
+
log_scale=False,
|
|
143
|
+
figsize=(10, 6),
|
|
144
|
+
grayscale=False,
|
|
145
|
+
fontname="Arial",
|
|
146
|
+
ylabel=True,
|
|
147
|
+
subtitle=True,
|
|
148
|
+
savefig=None,
|
|
149
|
+
show=True,
|
|
150
|
+
):
|
|
151
|
+
"""
|
|
152
|
+
Plot returns as a bar chart with optional benchmark comparison
|
|
153
|
+
|
|
154
|
+
Parameters
|
|
155
|
+
----------
|
|
156
|
+
returns : pd.Series or pd.DataFrame
|
|
157
|
+
Returns data to plot
|
|
158
|
+
benchmark : pd.Series, optional
|
|
159
|
+
Benchmark returns for comparison
|
|
160
|
+
returns_label : str, default "Strategy"
|
|
161
|
+
Label for returns data
|
|
162
|
+
hline : float, optional
|
|
163
|
+
Horizontal line value
|
|
164
|
+
hlw : float, optional
|
|
165
|
+
Horizontal line width
|
|
166
|
+
hlcolor : str, default "red"
|
|
167
|
+
Horizontal line color
|
|
168
|
+
hllabel : str, default ""
|
|
169
|
+
Horizontal line label
|
|
170
|
+
resample : str, default "YE"
|
|
171
|
+
Resampling frequency
|
|
172
|
+
title : str, default "Returns"
|
|
173
|
+
Chart title
|
|
174
|
+
match_volatility : bool, default False
|
|
175
|
+
Whether to match volatility with benchmark
|
|
176
|
+
log_scale : bool, default False
|
|
177
|
+
Whether to use log scale for y-axis
|
|
178
|
+
figsize : tuple, default (10, 6)
|
|
179
|
+
Figure size
|
|
180
|
+
grayscale : bool, default False
|
|
181
|
+
Whether to use grayscale colors
|
|
182
|
+
fontname : str, default "Arial"
|
|
183
|
+
Font name for labels
|
|
184
|
+
ylabel : bool, default True
|
|
185
|
+
Whether to show y-axis label
|
|
186
|
+
subtitle : bool, default True
|
|
187
|
+
Whether to show subtitle with date range
|
|
188
|
+
savefig : str or dict, optional
|
|
189
|
+
Save figure parameters
|
|
190
|
+
show : bool, default True
|
|
191
|
+
Whether to display the plot
|
|
192
|
+
|
|
193
|
+
Returns
|
|
194
|
+
-------
|
|
195
|
+
matplotlib.figure.Figure or None
|
|
196
|
+
Figure object if show=False, otherwise None
|
|
197
|
+
"""
|
|
198
|
+
# Validate volatility matching requirements
|
|
199
|
+
if match_volatility and benchmark is None:
|
|
200
|
+
raise ValueError("match_volatility requires passing of " "benchmark.")
|
|
201
|
+
if match_volatility and benchmark is not None:
|
|
202
|
+
bmark_vol = benchmark.loc[returns.index].std()
|
|
203
|
+
returns = (returns / returns.std()) * bmark_vol
|
|
204
|
+
|
|
205
|
+
# ---------------
|
|
206
|
+
# Prepare data and colors
|
|
207
|
+
colors, _, _ = _get_colors(grayscale)
|
|
208
|
+
if isinstance(returns, _pd.Series):
|
|
209
|
+
df = _pd.DataFrame(index=returns.index, data={returns.name: returns})
|
|
210
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
211
|
+
df = _pd.DataFrame(
|
|
212
|
+
index=returns.index, data={col: returns[col] for col in returns.columns}
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
# Add benchmark data if provided
|
|
216
|
+
if isinstance(benchmark, _pd.Series):
|
|
217
|
+
df[benchmark.name] = benchmark[benchmark.index.isin(returns.index)]
|
|
218
|
+
if isinstance(returns, _pd.Series):
|
|
219
|
+
df = df[[benchmark.name, returns.name]]
|
|
220
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
221
|
+
col_names = [benchmark.name, returns.columns]
|
|
222
|
+
df = df[list(_pd.core.common.flatten(col_names))]
|
|
223
|
+
|
|
224
|
+
# Clean data and apply resampling
|
|
225
|
+
df = df.dropna()
|
|
226
|
+
if resample is not None:
|
|
227
|
+
df = safe_resample(df, resample, _get_stats().comp)
|
|
228
|
+
df = safe_resample(df, resample, "last")
|
|
229
|
+
# Use integer years on the x-axis so bar positions and tick labels stay aligned
|
|
230
|
+
if isinstance(df.index, _pd.DatetimeIndex):
|
|
231
|
+
df = df.copy()
|
|
232
|
+
df.index = df.index.year
|
|
233
|
+
# ---------------
|
|
234
|
+
|
|
235
|
+
# Create figure and axis
|
|
236
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
237
|
+
ax.spines["top"].set_visible(False)
|
|
238
|
+
ax.spines["right"].set_visible(False)
|
|
239
|
+
ax.spines["bottom"].set_visible(False)
|
|
240
|
+
ax.spines["left"].set_visible(False)
|
|
241
|
+
|
|
242
|
+
# use a more precise date string for the x axis locations in the toolbar
|
|
243
|
+
fig.suptitle(
|
|
244
|
+
title, y=0.94, fontweight="bold", fontname=fontname, fontsize=14, color="black"
|
|
245
|
+
)
|
|
246
|
+
|
|
247
|
+
# Add subtitle with date range if enabled
|
|
248
|
+
if subtitle:
|
|
249
|
+
ax.set_title(
|
|
250
|
+
f"{df.index[0]} - {df.index[-1]} \n",
|
|
251
|
+
fontsize=12,
|
|
252
|
+
color="gray",
|
|
253
|
+
)
|
|
254
|
+
|
|
255
|
+
# Adjust colors if no benchmark
|
|
256
|
+
if benchmark is None:
|
|
257
|
+
colors = colors[1:]
|
|
258
|
+
df.plot(kind="bar", ax=ax, color=colors)
|
|
259
|
+
|
|
260
|
+
# Set background colors
|
|
261
|
+
fig.set_facecolor("white")
|
|
262
|
+
ax.set_facecolor("white")
|
|
263
|
+
|
|
264
|
+
# Format x-axis labels (keep tick positions from the bar plot)
|
|
265
|
+
tick_labels = [str(year) for year in df.index]
|
|
266
|
+
if len(tick_labels) > 10:
|
|
267
|
+
mod = max(1, len(tick_labels) // 10)
|
|
268
|
+
tick_labels = [
|
|
269
|
+
label if i % mod == 0 else "" for i, label in enumerate(tick_labels)
|
|
270
|
+
]
|
|
271
|
+
ax.set_xticks(ax.get_xticks())
|
|
272
|
+
ax.set_xticklabels(tick_labels)
|
|
273
|
+
|
|
274
|
+
# Add horizontal line if specified
|
|
275
|
+
if hline is not None and not isinstance(hline, _pd.Series):
|
|
276
|
+
if grayscale:
|
|
277
|
+
hlcolor = "gray"
|
|
278
|
+
ax.axhline(hline, ls="--", lw=hlw, color=hlcolor, label=hllabel, zorder=2)
|
|
279
|
+
|
|
280
|
+
# Add zero line for reference
|
|
281
|
+
ax.axhline(0, ls="--", lw=1, color="#000000", zorder=2)
|
|
282
|
+
|
|
283
|
+
# Only show legend if there are labeled elements
|
|
284
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
285
|
+
if handles:
|
|
286
|
+
ax.legend(fontsize=11)
|
|
287
|
+
|
|
288
|
+
# Set y-axis scale
|
|
289
|
+
_plt.yscale("symlog" if log_scale else "linear")
|
|
290
|
+
|
|
291
|
+
# Configure axis labels
|
|
292
|
+
ax.set_xlabel("")
|
|
293
|
+
if ylabel:
|
|
294
|
+
ax.set_ylabel(
|
|
295
|
+
"Returns", fontname=fontname, fontweight="bold", fontsize=12, color="black"
|
|
296
|
+
)
|
|
297
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
298
|
+
|
|
299
|
+
# Format y-axis as percentage
|
|
300
|
+
ax.yaxis.set_major_formatter(_FuncFormatter(format_pct_axis))
|
|
301
|
+
|
|
302
|
+
# Remove legend for single series without benchmark
|
|
303
|
+
if benchmark is None and len(_pd.DataFrame(returns).columns) == 1:
|
|
304
|
+
try:
|
|
305
|
+
legend = ax.get_legend()
|
|
306
|
+
if legend:
|
|
307
|
+
legend.remove()
|
|
308
|
+
except (ValueError, AttributeError, TypeError, RuntimeError):
|
|
309
|
+
pass
|
|
310
|
+
|
|
311
|
+
# Adjust layout
|
|
312
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
313
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
314
|
+
|
|
315
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
316
|
+
fig.tight_layout()
|
|
317
|
+
|
|
318
|
+
# Handle saving and displaying
|
|
319
|
+
if savefig:
|
|
320
|
+
if isinstance(savefig, dict):
|
|
321
|
+
_plt.savefig(**savefig)
|
|
322
|
+
else:
|
|
323
|
+
_plt.savefig(savefig)
|
|
324
|
+
|
|
325
|
+
if show:
|
|
326
|
+
_plt.show(block=False)
|
|
327
|
+
|
|
328
|
+
_plt.close()
|
|
329
|
+
|
|
330
|
+
if not show:
|
|
331
|
+
return fig
|
|
332
|
+
|
|
333
|
+
return None
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def plot_timeseries(
|
|
337
|
+
returns,
|
|
338
|
+
benchmark=None,
|
|
339
|
+
title="Returns",
|
|
340
|
+
compound=False,
|
|
341
|
+
fill=False,
|
|
342
|
+
returns_label="Strategy",
|
|
343
|
+
hline=None,
|
|
344
|
+
hlw=None,
|
|
345
|
+
hlcolor="red",
|
|
346
|
+
hllabel="",
|
|
347
|
+
percent=True,
|
|
348
|
+
match_volatility=False,
|
|
349
|
+
log_scale=False,
|
|
350
|
+
resample=None,
|
|
351
|
+
lw=1.5,
|
|
352
|
+
figsize=(10, 6),
|
|
353
|
+
ylabel="",
|
|
354
|
+
grayscale=False,
|
|
355
|
+
fontname="Arial",
|
|
356
|
+
subtitle=True,
|
|
357
|
+
savefig=None,
|
|
358
|
+
show=True,
|
|
359
|
+
raw_data=False,
|
|
360
|
+
):
|
|
361
|
+
"""
|
|
362
|
+
Plot returns as a time series line chart
|
|
363
|
+
|
|
364
|
+
Parameters
|
|
365
|
+
----------
|
|
366
|
+
returns : pd.Series or pd.DataFrame
|
|
367
|
+
Returns data to plot
|
|
368
|
+
benchmark : pd.Series, optional
|
|
369
|
+
Benchmark returns for comparison
|
|
370
|
+
title : str, default "Returns"
|
|
371
|
+
Chart title
|
|
372
|
+
compound : bool, default False
|
|
373
|
+
Whether to compound returns
|
|
374
|
+
fill : bool, default False
|
|
375
|
+
Whether to fill area under the line
|
|
376
|
+
returns_label : str, default "Strategy"
|
|
377
|
+
Label for returns data
|
|
378
|
+
hline : float, optional
|
|
379
|
+
Horizontal line value
|
|
380
|
+
hlw : float, optional
|
|
381
|
+
Horizontal line width
|
|
382
|
+
hlcolor : str, default "red"
|
|
383
|
+
Horizontal line color
|
|
384
|
+
hllabel : str, default ""
|
|
385
|
+
Horizontal line label
|
|
386
|
+
percent : bool, default True
|
|
387
|
+
Whether to format y-axis as percentage
|
|
388
|
+
match_volatility : bool, default False
|
|
389
|
+
Whether to match volatility with benchmark
|
|
390
|
+
log_scale : bool, default False
|
|
391
|
+
Whether to use log scale for y-axis
|
|
392
|
+
resample : str, optional
|
|
393
|
+
Resampling frequency
|
|
394
|
+
lw : float, default 1.5
|
|
395
|
+
Line width
|
|
396
|
+
figsize : tuple, default (10, 6)
|
|
397
|
+
Figure size
|
|
398
|
+
ylabel : str, default ""
|
|
399
|
+
Y-axis label
|
|
400
|
+
grayscale : bool, default False
|
|
401
|
+
Whether to use grayscale colors
|
|
402
|
+
fontname : str, default "Arial"
|
|
403
|
+
Font name for labels
|
|
404
|
+
subtitle : bool, default True
|
|
405
|
+
Whether to show subtitle with date range
|
|
406
|
+
savefig : str or dict, optional
|
|
407
|
+
Save figure parameters
|
|
408
|
+
show : bool, default True
|
|
409
|
+
Whether to display the plot
|
|
410
|
+
|
|
411
|
+
Returns
|
|
412
|
+
-------
|
|
413
|
+
matplotlib.figure.Figure or None
|
|
414
|
+
Figure object if show=False, otherwise None
|
|
415
|
+
"""
|
|
416
|
+
|
|
417
|
+
colors, ls, alpha = _get_colors(grayscale)
|
|
418
|
+
|
|
419
|
+
# Fill NaN values with zeros
|
|
420
|
+
returns = returns.fillna(0)
|
|
421
|
+
if isinstance(benchmark, _pd.Series):
|
|
422
|
+
benchmark = benchmark.fillna(0)
|
|
423
|
+
|
|
424
|
+
# Validate volatility matching requirements
|
|
425
|
+
if match_volatility and benchmark is None:
|
|
426
|
+
raise ValueError("match_volatility requires passing of " "benchmark.")
|
|
427
|
+
if match_volatility and benchmark is not None:
|
|
428
|
+
bmark_vol = benchmark.std()
|
|
429
|
+
returns = (returns / returns.std()) * bmark_vol
|
|
430
|
+
|
|
431
|
+
# ---------------
|
|
432
|
+
# Transform data based on compound setting (skip for raw data like drawdowns)
|
|
433
|
+
if not raw_data:
|
|
434
|
+
if compound:
|
|
435
|
+
returns = _get_stats().compsum(returns)
|
|
436
|
+
if isinstance(benchmark, _pd.Series):
|
|
437
|
+
benchmark = _get_stats().compsum(benchmark)
|
|
438
|
+
else:
|
|
439
|
+
returns = returns.cumsum()
|
|
440
|
+
if isinstance(benchmark, _pd.Series):
|
|
441
|
+
benchmark = benchmark.cumsum()
|
|
442
|
+
|
|
443
|
+
# Apply resampling if specified
|
|
444
|
+
if resample:
|
|
445
|
+
from .._compat import safe_resample
|
|
446
|
+
|
|
447
|
+
returns = safe_resample(
|
|
448
|
+
returns, resample, "last" if compound is True else "sum"
|
|
449
|
+
)
|
|
450
|
+
if isinstance(benchmark, _pd.Series):
|
|
451
|
+
benchmark = safe_resample(
|
|
452
|
+
benchmark, resample, "last" if compound is True else "sum"
|
|
453
|
+
)
|
|
454
|
+
# ---------------
|
|
455
|
+
|
|
456
|
+
# Create figure and axis
|
|
457
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
458
|
+
ax.spines["top"].set_visible(False)
|
|
459
|
+
ax.spines["right"].set_visible(False)
|
|
460
|
+
ax.spines["bottom"].set_visible(False)
|
|
461
|
+
ax.spines["left"].set_visible(False)
|
|
462
|
+
|
|
463
|
+
# Set main title
|
|
464
|
+
fig.suptitle(
|
|
465
|
+
title, y=0.94, fontweight="bold", fontname=fontname, fontsize=14, color="black"
|
|
466
|
+
)
|
|
467
|
+
|
|
468
|
+
# Add subtitle with date range if enabled
|
|
469
|
+
if subtitle:
|
|
470
|
+
ax.set_title(
|
|
471
|
+
"{} - {} \n".format(
|
|
472
|
+
returns.index.date[:1][0].strftime("%e %b '%y"),
|
|
473
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"),
|
|
474
|
+
),
|
|
475
|
+
fontsize=12,
|
|
476
|
+
color="gray",
|
|
477
|
+
)
|
|
478
|
+
|
|
479
|
+
# Set background colors
|
|
480
|
+
fig.set_facecolor("white")
|
|
481
|
+
ax.set_facecolor("white")
|
|
482
|
+
|
|
483
|
+
# Plot benchmark first if provided
|
|
484
|
+
if isinstance(benchmark, _pd.Series):
|
|
485
|
+
ax.plot(benchmark, lw=lw, ls=ls, label=benchmark.name, color=colors[0])
|
|
486
|
+
|
|
487
|
+
# Adjust alpha for grayscale
|
|
488
|
+
alpha = 0.25 if grayscale else 1
|
|
489
|
+
|
|
490
|
+
# Plot returns data
|
|
491
|
+
if isinstance(returns, _pd.Series):
|
|
492
|
+
ax.plot(returns, lw=lw, label=returns.name, color=colors[1], alpha=alpha)
|
|
493
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
494
|
+
# Plot each column in the DataFrame
|
|
495
|
+
for i, col in enumerate(returns.columns):
|
|
496
|
+
ax.plot(returns[col], lw=lw, label=col, alpha=alpha, color=colors[i + 1])
|
|
497
|
+
|
|
498
|
+
# Add fill under the line if requested
|
|
499
|
+
if fill:
|
|
500
|
+
if isinstance(returns, _pd.Series):
|
|
501
|
+
ax.fill_between(returns.index, 0, returns, color=colors[1], alpha=0.25)
|
|
502
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
503
|
+
for i, col in enumerate(returns.columns):
|
|
504
|
+
ax.fill_between(
|
|
505
|
+
returns[col].index, 0, returns[col], color=colors[i + 1], alpha=0.25
|
|
506
|
+
)
|
|
507
|
+
|
|
508
|
+
# rotate and align the tick labels so they look better
|
|
509
|
+
fig.autofmt_xdate()
|
|
510
|
+
|
|
511
|
+
# use a more precise date string for the x axis locations in the toolbar
|
|
512
|
+
# ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')
|
|
513
|
+
|
|
514
|
+
# Add horizontal line if specified
|
|
515
|
+
if hline is not None and not isinstance(hline, _pd.Series):
|
|
516
|
+
if grayscale:
|
|
517
|
+
hlcolor = "black"
|
|
518
|
+
ax.axhline(hline, ls="--", lw=hlw, color=hlcolor, label=hllabel, zorder=2)
|
|
519
|
+
|
|
520
|
+
# Add reference lines at zero
|
|
521
|
+
ax.axhline(0, ls="-", lw=1, color="gray", zorder=1)
|
|
522
|
+
ax.axhline(0, ls="--", lw=1, color="white" if grayscale else "black", zorder=2)
|
|
523
|
+
|
|
524
|
+
# Only show legend if there are labeled elements
|
|
525
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
526
|
+
if handles:
|
|
527
|
+
ax.legend(fontsize=11)
|
|
528
|
+
|
|
529
|
+
# Set y-axis scale
|
|
530
|
+
_plt.yscale("symlog" if log_scale else "linear")
|
|
531
|
+
|
|
532
|
+
# Format y-axis as percentage if requested
|
|
533
|
+
if percent:
|
|
534
|
+
ax.yaxis.set_major_formatter(_FuncFormatter(format_pct_axis))
|
|
535
|
+
# ax.yaxis.set_major_formatter(_plt.FuncFormatter(
|
|
536
|
+
# lambda x, loc: "{:,}%".format(int(x*100))))
|
|
537
|
+
|
|
538
|
+
# Configure axis labels
|
|
539
|
+
ax.set_xlabel("")
|
|
540
|
+
if ylabel:
|
|
541
|
+
ax.set_ylabel(
|
|
542
|
+
ylabel, fontname=fontname, fontweight="bold", fontsize=12, color="black"
|
|
543
|
+
)
|
|
544
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
545
|
+
|
|
546
|
+
# Remove legend for single series without benchmark
|
|
547
|
+
if benchmark is None and len(_pd.DataFrame(returns).columns) == 1:
|
|
548
|
+
try:
|
|
549
|
+
legend = ax.get_legend()
|
|
550
|
+
if legend:
|
|
551
|
+
legend.remove()
|
|
552
|
+
except (ValueError, AttributeError, TypeError, RuntimeError):
|
|
553
|
+
pass
|
|
554
|
+
|
|
555
|
+
# Adjust layout
|
|
556
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
557
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
558
|
+
|
|
559
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
560
|
+
fig.tight_layout()
|
|
561
|
+
|
|
562
|
+
# Handle saving and displaying
|
|
563
|
+
if savefig:
|
|
564
|
+
if isinstance(savefig, dict):
|
|
565
|
+
_plt.savefig(**savefig)
|
|
566
|
+
else:
|
|
567
|
+
_plt.savefig(savefig)
|
|
568
|
+
|
|
569
|
+
if show:
|
|
570
|
+
_plt.show(block=False)
|
|
571
|
+
|
|
572
|
+
_plt.close()
|
|
573
|
+
|
|
574
|
+
if not show:
|
|
575
|
+
return fig
|
|
576
|
+
|
|
577
|
+
return None
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def _pooled_returns_array(returns, benchmark) -> _np.ndarray:
|
|
581
|
+
"""Concatenate finite return observations from strategy and benchmark."""
|
|
582
|
+
chunks = []
|
|
583
|
+
for series in (returns, benchmark):
|
|
584
|
+
if series is None:
|
|
585
|
+
continue
|
|
586
|
+
arr = _np.asarray(series).ravel()
|
|
587
|
+
arr = arr[_np.isfinite(arr)]
|
|
588
|
+
if arr.size:
|
|
589
|
+
chunks.append(arr)
|
|
590
|
+
return _np.concatenate(chunks) if chunks else _np.array([])
|
|
591
|
+
|
|
592
|
+
|
|
593
|
+
def _histogram_visible_range(pooled: _np.ndarray, xlim_quantile: float | None):
|
|
594
|
+
"""Return (lo, hi) for the histogram view, with light padding."""
|
|
595
|
+
if pooled.size == 0:
|
|
596
|
+
return None
|
|
597
|
+
if xlim_quantile:
|
|
598
|
+
q = float(xlim_quantile)
|
|
599
|
+
lo = _np.quantile(pooled, q)
|
|
600
|
+
hi = _np.quantile(pooled, 1.0 - q)
|
|
601
|
+
else:
|
|
602
|
+
lo = float(_np.min(pooled))
|
|
603
|
+
hi = float(_np.max(pooled))
|
|
604
|
+
if not (_np.isfinite(lo) and _np.isfinite(hi) and hi > lo):
|
|
605
|
+
return None
|
|
606
|
+
pad = 0.05 * (hi - lo)
|
|
607
|
+
return lo - pad, hi + pad
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _resolve_histogram_bins(
|
|
611
|
+
pooled: _np.ndarray,
|
|
612
|
+
xlim_quantile: float | None,
|
|
613
|
+
binwidth: float | None,
|
|
614
|
+
adaptive_bins: int | None,
|
|
615
|
+
bins: int,
|
|
616
|
+
):
|
|
617
|
+
"""
|
|
618
|
+
Choose histogram bin kwargs and optional x-axis limits.
|
|
619
|
+
|
|
620
|
+
When ``adaptive_bins`` is set, bin width is ``span / adaptive_bins`` over
|
|
621
|
+
the visible range (quantile-clipped when ``xlim_quantile`` is set). Using
|
|
622
|
+
``binrange`` keeps every bar inside the plotted window instead of spreading
|
|
623
|
+
bins across the full historical min/max.
|
|
624
|
+
"""
|
|
625
|
+
visible = _histogram_visible_range(pooled, xlim_quantile)
|
|
626
|
+
if visible is None:
|
|
627
|
+
return {"bins": bins}, None
|
|
628
|
+
|
|
629
|
+
lo, hi = visible
|
|
630
|
+
span = hi - lo
|
|
631
|
+
|
|
632
|
+
if adaptive_bins:
|
|
633
|
+
bw = span / int(adaptive_bins)
|
|
634
|
+
return {"binwidth": bw, "binrange": (lo, hi)}, (lo, hi)
|
|
635
|
+
if binwidth:
|
|
636
|
+
kw = {"binwidth": binwidth}
|
|
637
|
+
if xlim_quantile:
|
|
638
|
+
kw["binrange"] = (lo, hi)
|
|
639
|
+
return kw, (lo, hi) if xlim_quantile else None
|
|
640
|
+
return {"bins": bins}, (lo, hi) if xlim_quantile else None
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
def plot_histogram(
|
|
644
|
+
returns,
|
|
645
|
+
benchmark,
|
|
646
|
+
resample="ME",
|
|
647
|
+
bins=20,
|
|
648
|
+
fontname="Arial",
|
|
649
|
+
grayscale=False,
|
|
650
|
+
title="Returns",
|
|
651
|
+
kde=True,
|
|
652
|
+
figsize=(10, 6),
|
|
653
|
+
ylabel=True,
|
|
654
|
+
subtitle=True,
|
|
655
|
+
compounded=True,
|
|
656
|
+
xlim_quantile=None,
|
|
657
|
+
binwidth=None,
|
|
658
|
+
adaptive_bins: int | None = None,
|
|
659
|
+
savefig=None,
|
|
660
|
+
show=True,
|
|
661
|
+
):
|
|
662
|
+
"""
|
|
663
|
+
Plot histogram of returns with optional KDE and benchmark comparison
|
|
664
|
+
|
|
665
|
+
Parameters
|
|
666
|
+
----------
|
|
667
|
+
returns : pd.Series or pd.DataFrame
|
|
668
|
+
Returns data to plot
|
|
669
|
+
benchmark : pd.Series
|
|
670
|
+
Benchmark returns for comparison
|
|
671
|
+
resample : str, default "ME"
|
|
672
|
+
Resampling frequency
|
|
673
|
+
bins : int, default 20
|
|
674
|
+
Number of histogram bins
|
|
675
|
+
fontname : str, default "Arial"
|
|
676
|
+
Font name for labels
|
|
677
|
+
grayscale : bool, default False
|
|
678
|
+
Whether to use grayscale colors
|
|
679
|
+
title : str, default "Returns"
|
|
680
|
+
Chart title
|
|
681
|
+
kde : bool, default True
|
|
682
|
+
Whether to show kernel density estimate
|
|
683
|
+
figsize : tuple, default (10, 6)
|
|
684
|
+
Figure size
|
|
685
|
+
ylabel : bool, default True
|
|
686
|
+
Whether to show y-axis label
|
|
687
|
+
subtitle : bool, default True
|
|
688
|
+
Whether to show subtitle with date range
|
|
689
|
+
compounded : bool, default True
|
|
690
|
+
Whether to use compounded returns
|
|
691
|
+
savefig : str or dict, optional
|
|
692
|
+
Save figure parameters
|
|
693
|
+
show : bool, default True
|
|
694
|
+
Whether to display the plot
|
|
695
|
+
|
|
696
|
+
Returns
|
|
697
|
+
-------
|
|
698
|
+
matplotlib.figure.Figure or None
|
|
699
|
+
Figure object if show=False, otherwise None
|
|
700
|
+
"""
|
|
701
|
+
|
|
702
|
+
# colors = ['#348dc1', '#003366', 'red']
|
|
703
|
+
# if grayscale:
|
|
704
|
+
# colors = ['silver', 'gray', 'black']
|
|
705
|
+
|
|
706
|
+
colors, _, _ = _get_colors(grayscale)
|
|
707
|
+
|
|
708
|
+
# Daily histograms: input is already daily returns. Calendar-day resample
|
|
709
|
+
# with comp() turns empty weekend/holiday buckets into 0% returns
|
|
710
|
+
# (comp([]) == 0), which piles up in the centre bin.
|
|
711
|
+
if resample in ("D", "B"):
|
|
712
|
+
returns = returns.dropna()
|
|
713
|
+
if benchmark is not None:
|
|
714
|
+
benchmark = benchmark.dropna()
|
|
715
|
+
else:
|
|
716
|
+
# Choose aggregation function based on compounded setting
|
|
717
|
+
apply_fnc = _get_stats().comp if compounded else _np.sum
|
|
718
|
+
|
|
719
|
+
# Process benchmark data
|
|
720
|
+
if benchmark is not None:
|
|
721
|
+
benchmark = benchmark.fillna(0)
|
|
722
|
+
benchmark = safe_resample(benchmark, resample, apply_fnc)
|
|
723
|
+
benchmark = safe_resample(benchmark, resample, "last")
|
|
724
|
+
|
|
725
|
+
# Process returns data
|
|
726
|
+
returns = returns.fillna(0)
|
|
727
|
+
returns = safe_resample(returns, resample, apply_fnc)
|
|
728
|
+
returns = safe_resample(returns, resample, "last")
|
|
729
|
+
|
|
730
|
+
# Adjust figure size slightly
|
|
731
|
+
figsize = (0.995 * figsize[0], figsize[1])
|
|
732
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
733
|
+
|
|
734
|
+
# Convert single-column DataFrame to Series for easier handling
|
|
735
|
+
if isinstance(returns, _pd.DataFrame) and len(returns.columns) == 1:
|
|
736
|
+
returns = returns[returns.columns[0]]
|
|
737
|
+
|
|
738
|
+
pooled = _pooled_returns_array(returns, benchmark)
|
|
739
|
+
_bin_kw, xlim = _resolve_histogram_bins(
|
|
740
|
+
pooled, xlim_quantile, binwidth, adaptive_bins, bins
|
|
741
|
+
)
|
|
742
|
+
|
|
743
|
+
# Configure axis appearance
|
|
744
|
+
ax.spines["top"].set_visible(False)
|
|
745
|
+
ax.spines["right"].set_visible(False)
|
|
746
|
+
ax.spines["bottom"].set_visible(False)
|
|
747
|
+
ax.spines["left"].set_visible(False)
|
|
748
|
+
|
|
749
|
+
# Set main title
|
|
750
|
+
fig.suptitle(
|
|
751
|
+
title, y=0.94, fontweight="bold", fontname=fontname, fontsize=14, color="black"
|
|
752
|
+
)
|
|
753
|
+
|
|
754
|
+
# Add subtitle with date range if enabled
|
|
755
|
+
if subtitle:
|
|
756
|
+
ax.set_title(
|
|
757
|
+
"{} - {} \n".format(
|
|
758
|
+
returns.index.date[:1][0].strftime("%Y"),
|
|
759
|
+
returns.index.date[-1:][0].strftime("%Y"),
|
|
760
|
+
),
|
|
761
|
+
fontsize=12,
|
|
762
|
+
color="gray",
|
|
763
|
+
)
|
|
764
|
+
|
|
765
|
+
# Set background colors
|
|
766
|
+
fig.set_facecolor("white")
|
|
767
|
+
ax.set_facecolor("white")
|
|
768
|
+
|
|
769
|
+
# Set up color palette and alpha based on data structure
|
|
770
|
+
pallete = colors[1:2] if benchmark is None else colors[:2]
|
|
771
|
+
alpha = 0.7
|
|
772
|
+
if isinstance(returns, _pd.DataFrame):
|
|
773
|
+
pallete = (
|
|
774
|
+
colors[1:(len(returns.columns) + 1)]
|
|
775
|
+
if benchmark is None
|
|
776
|
+
else colors[:(len(returns.columns) + 1)]
|
|
777
|
+
)
|
|
778
|
+
if len(returns.columns) > 1:
|
|
779
|
+
alpha = 0.5
|
|
780
|
+
|
|
781
|
+
# Plot histogram with benchmark comparison
|
|
782
|
+
if benchmark is not None:
|
|
783
|
+
if isinstance(returns, _pd.Series):
|
|
784
|
+
combined_returns = (
|
|
785
|
+
benchmark.to_frame()
|
|
786
|
+
.join(returns.to_frame())
|
|
787
|
+
.stack()
|
|
788
|
+
.reset_index()
|
|
789
|
+
.rename(columns={"level_1": "", 0: "Returns"})
|
|
790
|
+
)
|
|
791
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
792
|
+
combined_returns = (
|
|
793
|
+
benchmark.to_frame()
|
|
794
|
+
.join(returns)
|
|
795
|
+
.stack()
|
|
796
|
+
.reset_index()
|
|
797
|
+
.rename(columns={"level_1": "", 0: "Returns"})
|
|
798
|
+
)
|
|
799
|
+
_sns.histplot(
|
|
800
|
+
data=combined_returns,
|
|
801
|
+
x="Returns",
|
|
802
|
+
**_bin_kw,
|
|
803
|
+
alpha=alpha,
|
|
804
|
+
kde=kde,
|
|
805
|
+
stat="density",
|
|
806
|
+
hue="",
|
|
807
|
+
palette=pallete,
|
|
808
|
+
ax=ax,
|
|
809
|
+
)
|
|
810
|
+
|
|
811
|
+
else:
|
|
812
|
+
# Plot histogram without benchmark
|
|
813
|
+
if isinstance(returns, _pd.Series):
|
|
814
|
+
combined_returns = returns.copy()
|
|
815
|
+
if kde:
|
|
816
|
+
_sns.kdeplot(data=combined_returns, color="black", ax=ax, warn_singular=False)
|
|
817
|
+
|
|
818
|
+
_sns.histplot(
|
|
819
|
+
data=combined_returns,
|
|
820
|
+
**_bin_kw,
|
|
821
|
+
alpha=alpha,
|
|
822
|
+
kde=False,
|
|
823
|
+
stat="density",
|
|
824
|
+
color=colors[1],
|
|
825
|
+
ax=ax,
|
|
826
|
+
)
|
|
827
|
+
|
|
828
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
829
|
+
combined_returns = (
|
|
830
|
+
returns.stack()
|
|
831
|
+
.reset_index()
|
|
832
|
+
.rename(columns={"level_1": "", 0: "Returns"})
|
|
833
|
+
)
|
|
834
|
+
# _sns.kdeplot(data=combined_returns, color='black', ax=ax)
|
|
835
|
+
_sns.histplot(
|
|
836
|
+
data=combined_returns,
|
|
837
|
+
x="Returns",
|
|
838
|
+
**_bin_kw,
|
|
839
|
+
alpha=alpha,
|
|
840
|
+
kde=kde,
|
|
841
|
+
stat="density",
|
|
842
|
+
hue="",
|
|
843
|
+
palette=pallete,
|
|
844
|
+
ax=ax,
|
|
845
|
+
)
|
|
846
|
+
|
|
847
|
+
# Add average line for single series
|
|
848
|
+
if isinstance(combined_returns, _pd.Series) or len(combined_returns.columns) == 1:
|
|
849
|
+
ax.axvline(
|
|
850
|
+
combined_returns.mean(),
|
|
851
|
+
ls="--",
|
|
852
|
+
lw=1.5,
|
|
853
|
+
zorder=2,
|
|
854
|
+
label="Average",
|
|
855
|
+
color="red",
|
|
856
|
+
)
|
|
857
|
+
|
|
858
|
+
# Format x-axis as percentage (finer ticks when the visible span is narrow)
|
|
859
|
+
span = xlim[1] - xlim[0] if xlim else None
|
|
860
|
+
if span is not None and span < 0.12:
|
|
861
|
+
ax.xaxis.set_major_formatter(
|
|
862
|
+
_plt.FuncFormatter(lambda x, loc: f"{x * 100:.1f}%")
|
|
863
|
+
)
|
|
864
|
+
else:
|
|
865
|
+
ax.xaxis.set_major_formatter(
|
|
866
|
+
_plt.FuncFormatter(lambda x, loc: f"{int(x * 100):,}%")
|
|
867
|
+
)
|
|
868
|
+
|
|
869
|
+
if xlim:
|
|
870
|
+
ax.set_xlim(xlim)
|
|
871
|
+
|
|
872
|
+
# Removed static lines for clarity
|
|
873
|
+
# ax.axhline(0.01, lw=1, color="#000000", zorder=2)
|
|
874
|
+
# ax.axvline(0, lw=1, color="#000000", zorder=2)
|
|
875
|
+
|
|
876
|
+
# Configure axis labels
|
|
877
|
+
ax.set_xlabel("")
|
|
878
|
+
if ylabel:
|
|
879
|
+
ax.set_ylabel(
|
|
880
|
+
"Occurrences",
|
|
881
|
+
fontname=fontname,
|
|
882
|
+
fontweight="bold",
|
|
883
|
+
fontsize=12,
|
|
884
|
+
color="black",
|
|
885
|
+
)
|
|
886
|
+
else:
|
|
887
|
+
ax.set_ylabel("")
|
|
888
|
+
|
|
889
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
890
|
+
|
|
891
|
+
# fig.autofmt_xdate()
|
|
892
|
+
|
|
893
|
+
# Adjust layout
|
|
894
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
895
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
896
|
+
|
|
897
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
898
|
+
fig.tight_layout()
|
|
899
|
+
|
|
900
|
+
# Handle saving and displaying
|
|
901
|
+
if savefig:
|
|
902
|
+
if isinstance(savefig, dict):
|
|
903
|
+
_plt.savefig(**savefig)
|
|
904
|
+
else:
|
|
905
|
+
_plt.savefig(savefig)
|
|
906
|
+
|
|
907
|
+
if show:
|
|
908
|
+
_plt.show(block=False)
|
|
909
|
+
|
|
910
|
+
_plt.close()
|
|
911
|
+
|
|
912
|
+
if not show:
|
|
913
|
+
return fig
|
|
914
|
+
|
|
915
|
+
return None
|
|
916
|
+
|
|
917
|
+
|
|
918
|
+
def plot_rolling_stats(
|
|
919
|
+
returns,
|
|
920
|
+
benchmark=None,
|
|
921
|
+
title="",
|
|
922
|
+
returns_label="Strategy",
|
|
923
|
+
hline=None,
|
|
924
|
+
hlw=None,
|
|
925
|
+
hlcolor="red",
|
|
926
|
+
hllabel="",
|
|
927
|
+
lw=1.5,
|
|
928
|
+
figsize=(10, 6),
|
|
929
|
+
ylabel="",
|
|
930
|
+
grayscale=False,
|
|
931
|
+
fontname="Arial",
|
|
932
|
+
subtitle=True,
|
|
933
|
+
savefig=None,
|
|
934
|
+
show=True,
|
|
935
|
+
):
|
|
936
|
+
"""
|
|
937
|
+
Plot rolling statistics time series
|
|
938
|
+
|
|
939
|
+
Parameters
|
|
940
|
+
----------
|
|
941
|
+
returns : pd.Series or pd.DataFrame
|
|
942
|
+
Returns data to plot
|
|
943
|
+
benchmark : pd.Series, optional
|
|
944
|
+
Benchmark returns for comparison
|
|
945
|
+
title : str, default ""
|
|
946
|
+
Chart title
|
|
947
|
+
returns_label : str, default "Strategy"
|
|
948
|
+
Label for returns data
|
|
949
|
+
hline : float, optional
|
|
950
|
+
Horizontal line value
|
|
951
|
+
hlw : float, optional
|
|
952
|
+
Horizontal line width
|
|
953
|
+
hlcolor : str, default "red"
|
|
954
|
+
Horizontal line color
|
|
955
|
+
hllabel : str, default ""
|
|
956
|
+
Horizontal line label
|
|
957
|
+
lw : float, default 1.5
|
|
958
|
+
Line width
|
|
959
|
+
figsize : tuple, default (10, 6)
|
|
960
|
+
Figure size
|
|
961
|
+
ylabel : str, default ""
|
|
962
|
+
Y-axis label
|
|
963
|
+
grayscale : bool, default False
|
|
964
|
+
Whether to use grayscale colors
|
|
965
|
+
fontname : str, default "Arial"
|
|
966
|
+
Font name for labels
|
|
967
|
+
subtitle : bool, default True
|
|
968
|
+
Whether to show subtitle with date range
|
|
969
|
+
savefig : str or dict, optional
|
|
970
|
+
Save figure parameters
|
|
971
|
+
show : bool, default True
|
|
972
|
+
Whether to display the plot
|
|
973
|
+
|
|
974
|
+
Returns
|
|
975
|
+
-------
|
|
976
|
+
matplotlib.figure.Figure or None
|
|
977
|
+
Figure object if show=False, otherwise None
|
|
978
|
+
"""
|
|
979
|
+
|
|
980
|
+
colors, _, _ = _get_colors(grayscale)
|
|
981
|
+
|
|
982
|
+
# Create figure and axis
|
|
983
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
984
|
+
ax.spines["top"].set_visible(False)
|
|
985
|
+
ax.spines["right"].set_visible(False)
|
|
986
|
+
ax.spines["bottom"].set_visible(False)
|
|
987
|
+
ax.spines["left"].set_visible(False)
|
|
988
|
+
|
|
989
|
+
# Handle DataFrame case for returns_label
|
|
990
|
+
if isinstance(returns, _pd.DataFrame):
|
|
991
|
+
returns_label = list(returns.columns)
|
|
992
|
+
|
|
993
|
+
# Prepare data structure
|
|
994
|
+
if isinstance(returns, _pd.Series):
|
|
995
|
+
df = _pd.DataFrame(index=returns.index, data={returns_label: returns})
|
|
996
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
997
|
+
df = _pd.DataFrame(
|
|
998
|
+
index=returns.index, data={col: returns[col] for col in returns.columns}
|
|
999
|
+
)
|
|
1000
|
+
|
|
1001
|
+
# Add benchmark data if provided
|
|
1002
|
+
if isinstance(benchmark, _pd.Series):
|
|
1003
|
+
df["Benchmark"] = benchmark[benchmark.index.isin(returns.index)]
|
|
1004
|
+
if isinstance(returns, _pd.Series):
|
|
1005
|
+
df = df[["Benchmark", returns_label]].dropna()
|
|
1006
|
+
ax.plot(
|
|
1007
|
+
df[returns_label].dropna(), lw=lw, label=returns.name, color=colors[1]
|
|
1008
|
+
)
|
|
1009
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
1010
|
+
col_names = ["Benchmark", returns_label]
|
|
1011
|
+
df = df[list(_pd.core.common.flatten(col_names))].dropna()
|
|
1012
|
+
for i, col in enumerate(returns_label):
|
|
1013
|
+
ax.plot(df[col], lw=lw, label=col, color=colors[i + 1])
|
|
1014
|
+
# Plot benchmark line
|
|
1015
|
+
ax.plot(
|
|
1016
|
+
df["Benchmark"], lw=lw, label=benchmark.name, color=colors[0], alpha=0.8
|
|
1017
|
+
)
|
|
1018
|
+
else:
|
|
1019
|
+
# Plot without benchmark
|
|
1020
|
+
if isinstance(returns, _pd.Series):
|
|
1021
|
+
df = df[[returns_label]].dropna()
|
|
1022
|
+
ax.plot(
|
|
1023
|
+
df[returns_label].dropna(), lw=lw, label=returns.name, color=colors[1]
|
|
1024
|
+
)
|
|
1025
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
1026
|
+
df = df[returns_label].dropna()
|
|
1027
|
+
for i, col in enumerate(returns_label):
|
|
1028
|
+
ax.plot(df[col], lw=lw, label=col, color=colors[i + 1])
|
|
1029
|
+
|
|
1030
|
+
# rotate and align the tick labels so they look better
|
|
1031
|
+
fig.autofmt_xdate()
|
|
1032
|
+
|
|
1033
|
+
# use a more precise date string for the x axis locations in the toolbar
|
|
1034
|
+
# ax.fmt_xdata = _mdates.DateFormatter('%Y-%m-%d')\
|
|
1035
|
+
|
|
1036
|
+
# Set main title
|
|
1037
|
+
fig.suptitle(
|
|
1038
|
+
title, y=0.94, fontweight="bold", fontname=fontname, fontsize=14, color="black"
|
|
1039
|
+
)
|
|
1040
|
+
|
|
1041
|
+
# Add subtitle with date range if enabled
|
|
1042
|
+
if subtitle:
|
|
1043
|
+
ax.set_title(
|
|
1044
|
+
"{} - {} \n".format(
|
|
1045
|
+
df.index.date[:1][0].strftime("%e %b '%y"),
|
|
1046
|
+
df.index.date[-1:][0].strftime("%e %b '%y"),
|
|
1047
|
+
),
|
|
1048
|
+
fontsize=12,
|
|
1049
|
+
color="gray",
|
|
1050
|
+
)
|
|
1051
|
+
|
|
1052
|
+
# Add horizontal line if specified
|
|
1053
|
+
if hline is not None and not isinstance(hline, _pd.Series):
|
|
1054
|
+
if grayscale:
|
|
1055
|
+
hlcolor = "black"
|
|
1056
|
+
ax.axhline(hline, ls="--", lw=hlw, color=hlcolor, label=hllabel, zorder=2)
|
|
1057
|
+
|
|
1058
|
+
# Add zero reference line
|
|
1059
|
+
ax.axhline(0, ls="--", lw=1, color="#000000", zorder=2)
|
|
1060
|
+
|
|
1061
|
+
# Configure y-axis label
|
|
1062
|
+
if ylabel:
|
|
1063
|
+
ax.set_ylabel(
|
|
1064
|
+
ylabel, fontname=fontname, fontweight="bold", fontsize=12, color="black"
|
|
1065
|
+
)
|
|
1066
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
1067
|
+
|
|
1068
|
+
# Format y-axis with fixed decimals
|
|
1069
|
+
ax.yaxis.set_major_formatter(_FormatStrFormatter("%.2f"))
|
|
1070
|
+
|
|
1071
|
+
# Only show legend if there are labeled elements
|
|
1072
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
1073
|
+
if handles:
|
|
1074
|
+
ax.legend(fontsize=11)
|
|
1075
|
+
|
|
1076
|
+
# Remove legend for single series without benchmark
|
|
1077
|
+
if benchmark is None and len(_pd.DataFrame(returns).columns) == 1:
|
|
1078
|
+
try:
|
|
1079
|
+
legend = ax.get_legend()
|
|
1080
|
+
if legend:
|
|
1081
|
+
legend.remove()
|
|
1082
|
+
except (ValueError, AttributeError, TypeError, RuntimeError):
|
|
1083
|
+
pass
|
|
1084
|
+
|
|
1085
|
+
# Adjust layout
|
|
1086
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1087
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
1088
|
+
|
|
1089
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1090
|
+
fig.tight_layout()
|
|
1091
|
+
|
|
1092
|
+
# Handle saving and displaying
|
|
1093
|
+
if savefig:
|
|
1094
|
+
if isinstance(savefig, dict):
|
|
1095
|
+
_plt.savefig(**savefig)
|
|
1096
|
+
else:
|
|
1097
|
+
_plt.savefig(savefig)
|
|
1098
|
+
if show:
|
|
1099
|
+
_plt.show(block=False)
|
|
1100
|
+
|
|
1101
|
+
_plt.close()
|
|
1102
|
+
|
|
1103
|
+
if not show:
|
|
1104
|
+
return fig
|
|
1105
|
+
|
|
1106
|
+
return None
|
|
1107
|
+
|
|
1108
|
+
|
|
1109
|
+
def plot_rolling_beta(
|
|
1110
|
+
returns,
|
|
1111
|
+
benchmark,
|
|
1112
|
+
window1=126,
|
|
1113
|
+
window1_label="",
|
|
1114
|
+
window2=None,
|
|
1115
|
+
window2_label="",
|
|
1116
|
+
title="",
|
|
1117
|
+
hlcolor="red",
|
|
1118
|
+
figsize=(10, 6),
|
|
1119
|
+
grayscale=False,
|
|
1120
|
+
fontname="Arial",
|
|
1121
|
+
lw=1.5,
|
|
1122
|
+
ylabel=True,
|
|
1123
|
+
subtitle=True,
|
|
1124
|
+
savefig=None,
|
|
1125
|
+
show=True,
|
|
1126
|
+
):
|
|
1127
|
+
"""
|
|
1128
|
+
Plot rolling beta calculation over time
|
|
1129
|
+
|
|
1130
|
+
Parameters
|
|
1131
|
+
----------
|
|
1132
|
+
returns : pd.Series or pd.DataFrame
|
|
1133
|
+
Returns data to calculate beta for
|
|
1134
|
+
benchmark : pd.Series
|
|
1135
|
+
Benchmark returns for beta calculation
|
|
1136
|
+
window1 : int, default 126
|
|
1137
|
+
Primary rolling window size
|
|
1138
|
+
window1_label : str, default ""
|
|
1139
|
+
Label for primary window
|
|
1140
|
+
window2 : int, optional
|
|
1141
|
+
Secondary rolling window size
|
|
1142
|
+
window2_label : str, default ""
|
|
1143
|
+
Label for secondary window
|
|
1144
|
+
title : str, default ""
|
|
1145
|
+
Chart title
|
|
1146
|
+
hlcolor : str, default "red"
|
|
1147
|
+
Horizontal line color
|
|
1148
|
+
figsize : tuple, default (10, 6)
|
|
1149
|
+
Figure size
|
|
1150
|
+
grayscale : bool, default False
|
|
1151
|
+
Whether to use grayscale colors
|
|
1152
|
+
fontname : str, default "Arial"
|
|
1153
|
+
Font name for labels
|
|
1154
|
+
lw : float, default 1.5
|
|
1155
|
+
Line width
|
|
1156
|
+
ylabel : bool, default True
|
|
1157
|
+
Whether to show y-axis label
|
|
1158
|
+
subtitle : bool, default True
|
|
1159
|
+
Whether to show subtitle with date range
|
|
1160
|
+
savefig : str or dict, optional
|
|
1161
|
+
Save figure parameters
|
|
1162
|
+
show : bool, default True
|
|
1163
|
+
Whether to display the plot
|
|
1164
|
+
|
|
1165
|
+
Returns
|
|
1166
|
+
-------
|
|
1167
|
+
matplotlib.figure.Figure or None
|
|
1168
|
+
Figure object if show=False, otherwise None
|
|
1169
|
+
"""
|
|
1170
|
+
|
|
1171
|
+
colors, _, _ = _get_colors(grayscale)
|
|
1172
|
+
|
|
1173
|
+
# Create figure and axis
|
|
1174
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
1175
|
+
ax.spines["top"].set_visible(False)
|
|
1176
|
+
ax.spines["right"].set_visible(False)
|
|
1177
|
+
ax.spines["bottom"].set_visible(False)
|
|
1178
|
+
ax.spines["left"].set_visible(False)
|
|
1179
|
+
|
|
1180
|
+
# Set main title
|
|
1181
|
+
fig.suptitle(
|
|
1182
|
+
title, y=0.94, fontweight="bold", fontname=fontname, fontsize=14, color="black"
|
|
1183
|
+
)
|
|
1184
|
+
|
|
1185
|
+
# Add subtitle with date range if enabled
|
|
1186
|
+
if subtitle:
|
|
1187
|
+
ax.set_title(
|
|
1188
|
+
"{} - {} \n".format(
|
|
1189
|
+
returns.index.date[:1][0].strftime("%e %b '%y"),
|
|
1190
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"),
|
|
1191
|
+
),
|
|
1192
|
+
fontsize=12,
|
|
1193
|
+
color="gray",
|
|
1194
|
+
)
|
|
1195
|
+
|
|
1196
|
+
# Calculate and plot primary beta window
|
|
1197
|
+
i = 1
|
|
1198
|
+
if isinstance(returns, _pd.Series):
|
|
1199
|
+
beta = _get_stats().rolling_greeks(returns, benchmark, window1)["beta"].fillna(0)
|
|
1200
|
+
ax.plot(beta, lw=lw, label=window1_label, color=colors[1])
|
|
1201
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
1202
|
+
beta = {
|
|
1203
|
+
col: _get_stats().rolling_greeks(returns[col], benchmark, window1)["beta"].fillna(
|
|
1204
|
+
0
|
|
1205
|
+
)
|
|
1206
|
+
for col in returns.columns
|
|
1207
|
+
}
|
|
1208
|
+
for name, b in beta.items():
|
|
1209
|
+
ax.plot(b, lw=lw, label=name + " " + f"({window1_label})", color=colors[i])
|
|
1210
|
+
i += 1
|
|
1211
|
+
|
|
1212
|
+
# Calculate and plot secondary beta window if provided
|
|
1213
|
+
i = 1
|
|
1214
|
+
if window2:
|
|
1215
|
+
lw = lw - 0.5 # Thinner line for secondary window
|
|
1216
|
+
if isinstance(returns, _pd.Series):
|
|
1217
|
+
ax.plot(
|
|
1218
|
+
_get_stats().rolling_greeks(returns, benchmark, window2)["beta"],
|
|
1219
|
+
lw=lw,
|
|
1220
|
+
label=window2_label,
|
|
1221
|
+
color="gray",
|
|
1222
|
+
alpha=0.8,
|
|
1223
|
+
)
|
|
1224
|
+
elif isinstance(returns, _pd.DataFrame):
|
|
1225
|
+
betas_w2 = {
|
|
1226
|
+
col: _get_stats().rolling_greeks(returns[col], benchmark, window2)["beta"]
|
|
1227
|
+
for col in returns.columns
|
|
1228
|
+
}
|
|
1229
|
+
for name, beta_w2 in betas_w2.items():
|
|
1230
|
+
ax.plot(
|
|
1231
|
+
beta_w2,
|
|
1232
|
+
lw=lw,
|
|
1233
|
+
ls="--",
|
|
1234
|
+
label=name + " " + f"({window2_label})",
|
|
1235
|
+
alpha=0.5,
|
|
1236
|
+
color=colors[i],
|
|
1237
|
+
)
|
|
1238
|
+
i += 1
|
|
1239
|
+
|
|
1240
|
+
# Calculate beta range for y-axis ticks
|
|
1241
|
+
beta_min = (
|
|
1242
|
+
beta.min()
|
|
1243
|
+
if isinstance(returns, _pd.Series)
|
|
1244
|
+
else min([b.min() for b in beta.values()])
|
|
1245
|
+
)
|
|
1246
|
+
beta_max = (
|
|
1247
|
+
beta.max()
|
|
1248
|
+
if isinstance(returns, _pd.Series)
|
|
1249
|
+
else max([b.max() for b in beta.values()])
|
|
1250
|
+
)
|
|
1251
|
+
mmin = min([-100, int(beta_min * 100)])
|
|
1252
|
+
mmax = max([100, int(beta_max * 100)])
|
|
1253
|
+
step = 50 if (mmax - mmin) >= 200 else 100
|
|
1254
|
+
ax.set_yticks([x / 100 for x in list(range(mmin, mmax, step))])
|
|
1255
|
+
|
|
1256
|
+
# Add mean line for single series
|
|
1257
|
+
if isinstance(returns, _pd.Series):
|
|
1258
|
+
hlcolor = "black" if grayscale else hlcolor
|
|
1259
|
+
ax.axhline(beta.mean(), ls="--", lw=1.5, color=hlcolor, zorder=2)
|
|
1260
|
+
|
|
1261
|
+
# Add zero reference line
|
|
1262
|
+
ax.axhline(0, ls="--", lw=1, color="#000000", zorder=2)
|
|
1263
|
+
|
|
1264
|
+
# Format dates on x-axis
|
|
1265
|
+
fig.autofmt_xdate()
|
|
1266
|
+
|
|
1267
|
+
# use a more precise date string for the x axis locations in the toolbar
|
|
1268
|
+
ax.fmt_xdata = _mdates.DateFormatter("%Y-%m-%d")
|
|
1269
|
+
|
|
1270
|
+
# Configure y-axis label
|
|
1271
|
+
if ylabel:
|
|
1272
|
+
ax.set_ylabel(
|
|
1273
|
+
"Beta", fontname=fontname, fontweight="bold", fontsize=12, color="black"
|
|
1274
|
+
)
|
|
1275
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
1276
|
+
|
|
1277
|
+
# Only show legend if there are labeled elements
|
|
1278
|
+
handles, labels = ax.get_legend_handles_labels()
|
|
1279
|
+
if handles:
|
|
1280
|
+
ax.legend(fontsize=11)
|
|
1281
|
+
|
|
1282
|
+
# Remove legend for single series without benchmark
|
|
1283
|
+
if benchmark is None and len(_pd.DataFrame(returns).columns) == 1:
|
|
1284
|
+
try:
|
|
1285
|
+
legend = ax.get_legend()
|
|
1286
|
+
if legend:
|
|
1287
|
+
legend.remove()
|
|
1288
|
+
except (ValueError, AttributeError, TypeError, RuntimeError):
|
|
1289
|
+
pass
|
|
1290
|
+
|
|
1291
|
+
# Adjust layout
|
|
1292
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1293
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
1294
|
+
|
|
1295
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1296
|
+
fig.tight_layout()
|
|
1297
|
+
|
|
1298
|
+
# Handle saving and displaying
|
|
1299
|
+
if savefig:
|
|
1300
|
+
if isinstance(savefig, dict):
|
|
1301
|
+
_plt.savefig(**savefig)
|
|
1302
|
+
else:
|
|
1303
|
+
_plt.savefig(savefig)
|
|
1304
|
+
|
|
1305
|
+
if show:
|
|
1306
|
+
_plt.show(block=False)
|
|
1307
|
+
|
|
1308
|
+
_plt.close()
|
|
1309
|
+
|
|
1310
|
+
if not show:
|
|
1311
|
+
return fig
|
|
1312
|
+
|
|
1313
|
+
return None
|
|
1314
|
+
|
|
1315
|
+
|
|
1316
|
+
def plot_longest_drawdowns(
|
|
1317
|
+
returns,
|
|
1318
|
+
periods=5,
|
|
1319
|
+
lw=1.5,
|
|
1320
|
+
fontname="Arial",
|
|
1321
|
+
grayscale=False,
|
|
1322
|
+
title=None,
|
|
1323
|
+
log_scale=False,
|
|
1324
|
+
figsize=(10, 6),
|
|
1325
|
+
ylabel=True,
|
|
1326
|
+
subtitle=True,
|
|
1327
|
+
compounded=True,
|
|
1328
|
+
savefig=None,
|
|
1329
|
+
show=True,
|
|
1330
|
+
):
|
|
1331
|
+
"""
|
|
1332
|
+
Plot cumulative returns with longest drawdown periods highlighted
|
|
1333
|
+
|
|
1334
|
+
Parameters
|
|
1335
|
+
----------
|
|
1336
|
+
returns : pd.Series
|
|
1337
|
+
Returns data to analyze
|
|
1338
|
+
periods : int, default 5
|
|
1339
|
+
Number of longest drawdown periods to highlight
|
|
1340
|
+
lw : float, default 1.5
|
|
1341
|
+
Line width
|
|
1342
|
+
fontname : str, default "Arial"
|
|
1343
|
+
Font name for labels
|
|
1344
|
+
grayscale : bool, default False
|
|
1345
|
+
Whether to use grayscale colors
|
|
1346
|
+
title : str, optional
|
|
1347
|
+
Chart title
|
|
1348
|
+
log_scale : bool, default False
|
|
1349
|
+
Whether to use log scale for y-axis
|
|
1350
|
+
figsize : tuple, default (10, 6)
|
|
1351
|
+
Figure size
|
|
1352
|
+
ylabel : bool, default True
|
|
1353
|
+
Whether to show y-axis label
|
|
1354
|
+
subtitle : bool, default True
|
|
1355
|
+
Whether to show subtitle with date range
|
|
1356
|
+
compounded : bool, default True
|
|
1357
|
+
Whether to use compounded returns
|
|
1358
|
+
savefig : str or dict, optional
|
|
1359
|
+
Save figure parameters
|
|
1360
|
+
show : bool, default True
|
|
1361
|
+
Whether to display the plot
|
|
1362
|
+
|
|
1363
|
+
Returns
|
|
1364
|
+
-------
|
|
1365
|
+
matplotlib.figure.Figure or None
|
|
1366
|
+
Figure object if show=False, otherwise None
|
|
1367
|
+
"""
|
|
1368
|
+
|
|
1369
|
+
colors = ["#6B9E00", "#5C5C5C", "red"]
|
|
1370
|
+
if grayscale:
|
|
1371
|
+
colors = ["#000000"] * 3
|
|
1372
|
+
|
|
1373
|
+
# Calculate drawdown statistics
|
|
1374
|
+
dd = _get_stats().to_drawdown_series(returns.fillna(0))
|
|
1375
|
+
dddf = _get_stats().drawdown_details(dd)
|
|
1376
|
+
longest_dd = dddf.sort_values(by="days", ascending=False, kind="mergesort")[
|
|
1377
|
+
:periods
|
|
1378
|
+
]
|
|
1379
|
+
|
|
1380
|
+
# Create figure and axis
|
|
1381
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
1382
|
+
ax.spines["top"].set_visible(False)
|
|
1383
|
+
ax.spines["right"].set_visible(False)
|
|
1384
|
+
ax.spines["bottom"].set_visible(False)
|
|
1385
|
+
ax.spines["left"].set_visible(False)
|
|
1386
|
+
|
|
1387
|
+
# Set main title with period count
|
|
1388
|
+
fig.suptitle(
|
|
1389
|
+
f"{title} - Worst %.0f Drawdown Periods" % periods,
|
|
1390
|
+
y=0.94,
|
|
1391
|
+
fontweight="bold",
|
|
1392
|
+
fontname=fontname,
|
|
1393
|
+
fontsize=14,
|
|
1394
|
+
color="black",
|
|
1395
|
+
)
|
|
1396
|
+
|
|
1397
|
+
# Add subtitle with date range if enabled
|
|
1398
|
+
if subtitle:
|
|
1399
|
+
ax.set_title(
|
|
1400
|
+
"{} - {} \n".format(
|
|
1401
|
+
returns.index.date[:1][0].strftime("%e %b '%y"),
|
|
1402
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"),
|
|
1403
|
+
),
|
|
1404
|
+
fontsize=12,
|
|
1405
|
+
color="gray",
|
|
1406
|
+
)
|
|
1407
|
+
|
|
1408
|
+
# Set background colors
|
|
1409
|
+
fig.set_facecolor("white")
|
|
1410
|
+
ax.set_facecolor("white")
|
|
1411
|
+
|
|
1412
|
+
# Calculate cumulative returns
|
|
1413
|
+
series = _get_stats().compsum(returns) if compounded else returns.cumsum()
|
|
1414
|
+
ax.plot(series, lw=lw, label="Backtest", color=colors[0])
|
|
1415
|
+
|
|
1416
|
+
# Highlight drawdown periods
|
|
1417
|
+
highlight = "black" if grayscale else "red"
|
|
1418
|
+
# Vectorized approach instead of iterrows
|
|
1419
|
+
for start, end in zip(longest_dd["start"], longest_dd["end"], strict=False):
|
|
1420
|
+
ax.axvspan(
|
|
1421
|
+
*_mdates.datestr2num([str(start), str(end)]),
|
|
1422
|
+
color=highlight,
|
|
1423
|
+
alpha=0.1,
|
|
1424
|
+
)
|
|
1425
|
+
|
|
1426
|
+
# rotate and align the tick labels so they look better
|
|
1427
|
+
fig.autofmt_xdate()
|
|
1428
|
+
|
|
1429
|
+
# use a more precise date string for the x axis locations in the toolbar
|
|
1430
|
+
ax.fmt_xdata = _mdates.DateFormatter("%Y-%m-%d")
|
|
1431
|
+
|
|
1432
|
+
# Add zero reference line
|
|
1433
|
+
ax.axhline(0, ls="--", lw=1, color="#000000", zorder=2)
|
|
1434
|
+
|
|
1435
|
+
# Set y-axis scale
|
|
1436
|
+
_plt.yscale("symlog" if log_scale else "linear")
|
|
1437
|
+
|
|
1438
|
+
# Configure y-axis label
|
|
1439
|
+
if ylabel:
|
|
1440
|
+
ax.set_ylabel(
|
|
1441
|
+
"Cumulative Returns",
|
|
1442
|
+
fontname=fontname,
|
|
1443
|
+
fontweight="bold",
|
|
1444
|
+
fontsize=12,
|
|
1445
|
+
color="black",
|
|
1446
|
+
)
|
|
1447
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
1448
|
+
|
|
1449
|
+
# Format y-axis as percentage
|
|
1450
|
+
ax.yaxis.set_major_formatter(_FuncFormatter(format_pct_axis))
|
|
1451
|
+
# ax.yaxis.set_major_formatter(_plt.FuncFormatter(
|
|
1452
|
+
# lambda x, loc: "{:,}%".format(int(x*100))))
|
|
1453
|
+
|
|
1454
|
+
# Format dates on x-axis
|
|
1455
|
+
fig.autofmt_xdate()
|
|
1456
|
+
|
|
1457
|
+
# Adjust layout
|
|
1458
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1459
|
+
_plt.subplots_adjust(hspace=0, bottom=0, top=1)
|
|
1460
|
+
|
|
1461
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1462
|
+
fig.tight_layout()
|
|
1463
|
+
|
|
1464
|
+
# Handle saving and displaying
|
|
1465
|
+
if savefig:
|
|
1466
|
+
if isinstance(savefig, dict):
|
|
1467
|
+
_plt.savefig(**savefig)
|
|
1468
|
+
else:
|
|
1469
|
+
_plt.savefig(savefig)
|
|
1470
|
+
|
|
1471
|
+
if show:
|
|
1472
|
+
_plt.show(block=False)
|
|
1473
|
+
|
|
1474
|
+
_plt.close()
|
|
1475
|
+
|
|
1476
|
+
if not show:
|
|
1477
|
+
return fig
|
|
1478
|
+
|
|
1479
|
+
return None
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
def plot_distribution(
|
|
1483
|
+
returns,
|
|
1484
|
+
figsize=(10, 6),
|
|
1485
|
+
fontname="Arial",
|
|
1486
|
+
grayscale=False,
|
|
1487
|
+
ylabel=True,
|
|
1488
|
+
subtitle=True,
|
|
1489
|
+
compounded=True,
|
|
1490
|
+
title=None,
|
|
1491
|
+
savefig=None,
|
|
1492
|
+
show=True,
|
|
1493
|
+
):
|
|
1494
|
+
"""
|
|
1495
|
+
Plot box plot showing return distribution across different time periods
|
|
1496
|
+
|
|
1497
|
+
Parameters
|
|
1498
|
+
----------
|
|
1499
|
+
returns : pd.Series
|
|
1500
|
+
Returns data to analyze
|
|
1501
|
+
figsize : tuple, default (10, 6)
|
|
1502
|
+
Figure size
|
|
1503
|
+
fontname : str, default "Arial"
|
|
1504
|
+
Font name for labels
|
|
1505
|
+
grayscale : bool, default False
|
|
1506
|
+
Whether to use grayscale colors
|
|
1507
|
+
ylabel : bool, default True
|
|
1508
|
+
Whether to show y-axis label
|
|
1509
|
+
subtitle : bool, default True
|
|
1510
|
+
Whether to show subtitle with date range
|
|
1511
|
+
compounded : bool, default True
|
|
1512
|
+
Whether to use compounded returns
|
|
1513
|
+
title : str, optional
|
|
1514
|
+
Chart title
|
|
1515
|
+
savefig : str or dict, optional
|
|
1516
|
+
Save figure parameters
|
|
1517
|
+
show : bool, default True
|
|
1518
|
+
Whether to display the plot
|
|
1519
|
+
|
|
1520
|
+
Returns
|
|
1521
|
+
-------
|
|
1522
|
+
matplotlib.figure.Figure or None
|
|
1523
|
+
Figure object if show=False, otherwise None
|
|
1524
|
+
"""
|
|
1525
|
+
|
|
1526
|
+
colors = _FLATUI_COLORS
|
|
1527
|
+
if grayscale:
|
|
1528
|
+
colors = ["#f9f9f9", "#dddddd", "#bbbbbb", "#999999", "#808080"]
|
|
1529
|
+
# colors, ls, alpha = _get_colors(grayscale)
|
|
1530
|
+
|
|
1531
|
+
# Create portfolio data structure
|
|
1532
|
+
port = _pd.DataFrame(returns.fillna(0))
|
|
1533
|
+
port.columns = ["Daily"]
|
|
1534
|
+
|
|
1535
|
+
# Calculate returns for different time periods
|
|
1536
|
+
if compounded:
|
|
1537
|
+
port["Weekly"] = safe_resample(port["Daily"], "W-MON", _get_stats().comp)
|
|
1538
|
+
port["Monthly"] = safe_resample(port["Daily"], "ME", _get_stats().comp)
|
|
1539
|
+
port["Quarterly"] = safe_resample(port["Daily"], "QE", _get_stats().comp)
|
|
1540
|
+
port["Yearly"] = safe_resample(port["Daily"], "YE", _get_stats().comp)
|
|
1541
|
+
else:
|
|
1542
|
+
port["Weekly"] = safe_resample(port["Daily"], "W-MON", "sum")
|
|
1543
|
+
port["Monthly"] = safe_resample(port["Daily"], "ME", "sum")
|
|
1544
|
+
port["Quarterly"] = safe_resample(port["Daily"], "QE", "sum")
|
|
1545
|
+
port["Yearly"] = safe_resample(port["Daily"], "YE", "sum")
|
|
1546
|
+
|
|
1547
|
+
# Forward fill missing values
|
|
1548
|
+
port["Weekly"] = port["Weekly"].ffill()
|
|
1549
|
+
port["Monthly"] = port["Monthly"].ffill()
|
|
1550
|
+
port["Quarterly"] = port["Quarterly"].ffill()
|
|
1551
|
+
port["Yearly"] = port["Yearly"].ffill()
|
|
1552
|
+
|
|
1553
|
+
# Create figure and axis
|
|
1554
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
1555
|
+
ax.spines["top"].set_visible(False)
|
|
1556
|
+
ax.spines["right"].set_visible(False)
|
|
1557
|
+
ax.spines["bottom"].set_visible(False)
|
|
1558
|
+
ax.spines["left"].set_visible(False)
|
|
1559
|
+
|
|
1560
|
+
# Set main title
|
|
1561
|
+
if title:
|
|
1562
|
+
title = f"{title} - Return Quantiles"
|
|
1563
|
+
else:
|
|
1564
|
+
title = "Return Quantiles"
|
|
1565
|
+
fig.suptitle(
|
|
1566
|
+
title, y=0.94, fontweight="bold", fontname=fontname, fontsize=14, color="black"
|
|
1567
|
+
)
|
|
1568
|
+
|
|
1569
|
+
# Add subtitle with date range if enabled
|
|
1570
|
+
if subtitle:
|
|
1571
|
+
ax.set_title(
|
|
1572
|
+
"{} - {} \n".format(
|
|
1573
|
+
returns.index.date[:1][0].strftime("%e %b '%y"),
|
|
1574
|
+
returns.index.date[-1:][0].strftime("%e %b '%y"),
|
|
1575
|
+
),
|
|
1576
|
+
fontsize=12,
|
|
1577
|
+
color="gray",
|
|
1578
|
+
)
|
|
1579
|
+
|
|
1580
|
+
# Set background colors
|
|
1581
|
+
fig.set_facecolor("white")
|
|
1582
|
+
ax.set_facecolor("white")
|
|
1583
|
+
|
|
1584
|
+
# Create box plot with custom color palette
|
|
1585
|
+
_sns.boxplot(
|
|
1586
|
+
data=port,
|
|
1587
|
+
ax=ax,
|
|
1588
|
+
palette={
|
|
1589
|
+
"Daily": colors[0],
|
|
1590
|
+
"Weekly": colors[1],
|
|
1591
|
+
"Monthly": colors[2],
|
|
1592
|
+
"Quarterly": colors[3],
|
|
1593
|
+
"Yearly": colors[4],
|
|
1594
|
+
},
|
|
1595
|
+
)
|
|
1596
|
+
|
|
1597
|
+
# Format y-axis as percentage
|
|
1598
|
+
ax.yaxis.set_major_formatter(
|
|
1599
|
+
_plt.FuncFormatter(lambda x, loc: f"{int(x * 100):,}%")
|
|
1600
|
+
)
|
|
1601
|
+
|
|
1602
|
+
# Configure y-axis label
|
|
1603
|
+
if ylabel:
|
|
1604
|
+
ax.set_ylabel(
|
|
1605
|
+
"Returns", fontname=fontname, fontweight="bold", fontsize=12, color="black"
|
|
1606
|
+
)
|
|
1607
|
+
ax.yaxis.set_label_coords(-0.1, 0.5)
|
|
1608
|
+
|
|
1609
|
+
# Format dates on x-axis
|
|
1610
|
+
fig.autofmt_xdate()
|
|
1611
|
+
|
|
1612
|
+
# Adjust layout
|
|
1613
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1614
|
+
_plt.subplots_adjust(hspace=0)
|
|
1615
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1616
|
+
fig.tight_layout(w_pad=0, h_pad=0)
|
|
1617
|
+
|
|
1618
|
+
# Handle saving and displaying
|
|
1619
|
+
if savefig:
|
|
1620
|
+
if isinstance(savefig, dict):
|
|
1621
|
+
_plt.savefig(**savefig)
|
|
1622
|
+
else:
|
|
1623
|
+
_plt.savefig(savefig)
|
|
1624
|
+
|
|
1625
|
+
if show:
|
|
1626
|
+
_plt.show(block=False)
|
|
1627
|
+
|
|
1628
|
+
_plt.close()
|
|
1629
|
+
|
|
1630
|
+
if not show:
|
|
1631
|
+
return fig
|
|
1632
|
+
|
|
1633
|
+
return None
|
|
1634
|
+
|
|
1635
|
+
|
|
1636
|
+
def plot_table(
|
|
1637
|
+
tbl,
|
|
1638
|
+
columns=None,
|
|
1639
|
+
title="",
|
|
1640
|
+
title_loc="left",
|
|
1641
|
+
header=True,
|
|
1642
|
+
colWidths=None,
|
|
1643
|
+
rowLoc="right",
|
|
1644
|
+
colLoc="right",
|
|
1645
|
+
colLabels=None,
|
|
1646
|
+
edges="horizontal",
|
|
1647
|
+
orient="horizontal",
|
|
1648
|
+
figsize=(5.5, 6),
|
|
1649
|
+
savefig=None,
|
|
1650
|
+
show=False,
|
|
1651
|
+
):
|
|
1652
|
+
"""
|
|
1653
|
+
Plot a data table as a matplotlib figure
|
|
1654
|
+
|
|
1655
|
+
Parameters
|
|
1656
|
+
----------
|
|
1657
|
+
tbl : pd.DataFrame
|
|
1658
|
+
Data table to plot
|
|
1659
|
+
columns : list, optional
|
|
1660
|
+
Column names to use
|
|
1661
|
+
title : str, default ""
|
|
1662
|
+
Table title
|
|
1663
|
+
title_loc : str, default "left"
|
|
1664
|
+
Title location
|
|
1665
|
+
header : bool, default True
|
|
1666
|
+
Whether to show header row
|
|
1667
|
+
colWidths : list, optional
|
|
1668
|
+
Column widths
|
|
1669
|
+
rowLoc : str, default "right"
|
|
1670
|
+
Row alignment
|
|
1671
|
+
colLoc : str, default "right"
|
|
1672
|
+
Column alignment
|
|
1673
|
+
colLabels : list, optional
|
|
1674
|
+
Column labels
|
|
1675
|
+
edges : str, default "horizontal"
|
|
1676
|
+
Table edge style
|
|
1677
|
+
orient : str, default "horizontal"
|
|
1678
|
+
Table orientation
|
|
1679
|
+
figsize : tuple, default (5.5, 6)
|
|
1680
|
+
Figure size
|
|
1681
|
+
savefig : str or dict, optional
|
|
1682
|
+
Save figure parameters
|
|
1683
|
+
show : bool, default False
|
|
1684
|
+
Whether to display the plot
|
|
1685
|
+
|
|
1686
|
+
Returns
|
|
1687
|
+
-------
|
|
1688
|
+
matplotlib.figure.Figure or None
|
|
1689
|
+
Figure object if show=False, otherwise None
|
|
1690
|
+
"""
|
|
1691
|
+
|
|
1692
|
+
# Set column names if provided
|
|
1693
|
+
if columns is not None:
|
|
1694
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1695
|
+
tbl.columns = columns
|
|
1696
|
+
|
|
1697
|
+
# Create figure and axis
|
|
1698
|
+
fig = _plt.figure(figsize=figsize)
|
|
1699
|
+
ax = _plt.subplot(111, frame_on=False)
|
|
1700
|
+
|
|
1701
|
+
# Set title if provided
|
|
1702
|
+
if title != "":
|
|
1703
|
+
ax.set_title(
|
|
1704
|
+
title, fontweight="bold", fontsize=14, color="black", loc=title_loc
|
|
1705
|
+
)
|
|
1706
|
+
|
|
1707
|
+
# Create table
|
|
1708
|
+
the_table = ax.table(
|
|
1709
|
+
cellText=tbl.values,
|
|
1710
|
+
colWidths=colWidths,
|
|
1711
|
+
rowLoc=rowLoc,
|
|
1712
|
+
colLoc=colLoc,
|
|
1713
|
+
edges=edges,
|
|
1714
|
+
colLabels=(tbl.columns if header else colLabels),
|
|
1715
|
+
loc="center",
|
|
1716
|
+
zorder=2,
|
|
1717
|
+
)
|
|
1718
|
+
|
|
1719
|
+
# Configure table appearance
|
|
1720
|
+
the_table.auto_set_font_size(False)
|
|
1721
|
+
the_table.set_fontsize(12)
|
|
1722
|
+
the_table.scale(1, 1)
|
|
1723
|
+
|
|
1724
|
+
# Style individual cells
|
|
1725
|
+
for (row, col), cell in the_table.get_celld().items():
|
|
1726
|
+
cell.set_height(0.08)
|
|
1727
|
+
cell.set_text_props(color="black")
|
|
1728
|
+
cell.set_edgecolor("#dddddd")
|
|
1729
|
+
# Header row styling
|
|
1730
|
+
if row == 0 and header:
|
|
1731
|
+
cell.set_edgecolor("black")
|
|
1732
|
+
cell.set_facecolor("black")
|
|
1733
|
+
cell.set_linewidth(2)
|
|
1734
|
+
cell.set_text_props(weight="bold", color="black")
|
|
1735
|
+
# First column styling for vertical orientation
|
|
1736
|
+
elif col == 0 and "vertical" in orient:
|
|
1737
|
+
cell.set_edgecolor("#dddddd")
|
|
1738
|
+
cell.set_linewidth(1)
|
|
1739
|
+
cell.set_text_props(weight="bold", color="black")
|
|
1740
|
+
# Data row styling
|
|
1741
|
+
elif row > 1:
|
|
1742
|
+
cell.set_linewidth(1)
|
|
1743
|
+
|
|
1744
|
+
# Remove axis elements
|
|
1745
|
+
ax.grid(False)
|
|
1746
|
+
ax.set_xticks([])
|
|
1747
|
+
ax.set_yticks([])
|
|
1748
|
+
|
|
1749
|
+
# Adjust layout
|
|
1750
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1751
|
+
_plt.subplots_adjust(hspace=0)
|
|
1752
|
+
with contextlib.suppress(ValueError, AttributeError, TypeError, RuntimeError):
|
|
1753
|
+
fig.tight_layout(w_pad=0, h_pad=0)
|
|
1754
|
+
|
|
1755
|
+
# Handle saving and displaying
|
|
1756
|
+
if savefig:
|
|
1757
|
+
if isinstance(savefig, dict):
|
|
1758
|
+
_plt.savefig(**savefig)
|
|
1759
|
+
else:
|
|
1760
|
+
_plt.savefig(savefig)
|
|
1761
|
+
|
|
1762
|
+
if show:
|
|
1763
|
+
_plt.show(block=False)
|
|
1764
|
+
|
|
1765
|
+
_plt.close()
|
|
1766
|
+
|
|
1767
|
+
if not show:
|
|
1768
|
+
return fig
|
|
1769
|
+
|
|
1770
|
+
return None
|
|
1771
|
+
|
|
1772
|
+
|
|
1773
|
+
def format_cur_axis(x, _):
|
|
1774
|
+
"""
|
|
1775
|
+
Format currency values for axis labels with appropriate units
|
|
1776
|
+
|
|
1777
|
+
Parameters
|
|
1778
|
+
----------
|
|
1779
|
+
x : float
|
|
1780
|
+
Value to format
|
|
1781
|
+
_ : unused
|
|
1782
|
+
Matplotlib formatter parameter (not used)
|
|
1783
|
+
|
|
1784
|
+
Returns
|
|
1785
|
+
-------
|
|
1786
|
+
str
|
|
1787
|
+
Formatted currency string with appropriate unit suffix
|
|
1788
|
+
"""
|
|
1789
|
+
# Format large values with appropriate suffixes
|
|
1790
|
+
if x >= 1e12:
|
|
1791
|
+
res = "$%1.1fT" % (x * 1e-12)
|
|
1792
|
+
return res.replace(".0T", "T")
|
|
1793
|
+
if x >= 1e9:
|
|
1794
|
+
res = "$%1.1fB" % (x * 1e-9)
|
|
1795
|
+
return res.replace(".0B", "B")
|
|
1796
|
+
if x >= 1e6:
|
|
1797
|
+
res = "$%1.1fM" % (x * 1e-6)
|
|
1798
|
+
return res.replace(".0M", "ME")
|
|
1799
|
+
if x >= 1e3:
|
|
1800
|
+
res = "$%1.0fK" % (x * 1e-3)
|
|
1801
|
+
return res.replace(".0K", "K")
|
|
1802
|
+
# Format small values without suffix
|
|
1803
|
+
res = f"${x:1.0f}"
|
|
1804
|
+
return res.replace(".0", "")
|
|
1805
|
+
|
|
1806
|
+
|
|
1807
|
+
def format_pct_axis(x, _):
|
|
1808
|
+
"""
|
|
1809
|
+
Format percentage values for axis labels with appropriate units
|
|
1810
|
+
|
|
1811
|
+
Parameters
|
|
1812
|
+
----------
|
|
1813
|
+
x : float
|
|
1814
|
+
Value to format (as decimal, e.g., 0.01 for 1%)
|
|
1815
|
+
_ : unused
|
|
1816
|
+
Matplotlib formatter parameter (not used)
|
|
1817
|
+
|
|
1818
|
+
Returns
|
|
1819
|
+
-------
|
|
1820
|
+
str
|
|
1821
|
+
Formatted percentage string with appropriate unit suffix
|
|
1822
|
+
"""
|
|
1823
|
+
# Convert to percentage
|
|
1824
|
+
x *= 100 # lambda x, loc: "{:,}%".format(int(x * 100))
|
|
1825
|
+
|
|
1826
|
+
# Format large percentage values with appropriate suffixes
|
|
1827
|
+
if x >= 1e12:
|
|
1828
|
+
res = "%1.1fT%%" % (x * 1e-12)
|
|
1829
|
+
return res.replace(".0T%", "T%")
|
|
1830
|
+
if x >= 1e9:
|
|
1831
|
+
res = "%1.1fB%%" % (x * 1e-9)
|
|
1832
|
+
return res.replace(".0B%", "B%")
|
|
1833
|
+
if x >= 1e6:
|
|
1834
|
+
res = "%1.1fM%%" % (x * 1e-6)
|
|
1835
|
+
return res.replace(".0M%", "M%")
|
|
1836
|
+
if x >= 1e3:
|
|
1837
|
+
res = "%1.1fK%%" % (x * 1e-3)
|
|
1838
|
+
return res.replace(".0K%", "K%")
|
|
1839
|
+
# Format small percentage values without suffix
|
|
1840
|
+
res = f"{x:1.0f}%"
|
|
1841
|
+
return res.replace(".0%", "%")
|
|
1842
|
+
|
|
1843
|
+
|
|
1844
|
+
# ======== MONTE CARLO PLOTS ========
|
|
1845
|
+
|
|
1846
|
+
|
|
1847
|
+
def plot_montecarlo(
|
|
1848
|
+
mc_result,
|
|
1849
|
+
title="Monte Carlo Simulation",
|
|
1850
|
+
figsize=(10, 6),
|
|
1851
|
+
grayscale=False,
|
|
1852
|
+
fontname="Arial",
|
|
1853
|
+
ylabel=True,
|
|
1854
|
+
subtitle=True,
|
|
1855
|
+
savefig=None,
|
|
1856
|
+
show=True,
|
|
1857
|
+
confidence_level=0.95,
|
|
1858
|
+
):
|
|
1859
|
+
"""
|
|
1860
|
+
Plot Monte Carlo simulation results showing all paths with original highlighted.
|
|
1861
|
+
|
|
1862
|
+
Parameters
|
|
1863
|
+
----------
|
|
1864
|
+
mc_result : MonteCarloResult
|
|
1865
|
+
Monte Carlo simulation result object
|
|
1866
|
+
title : str, default "Monte Carlo Simulation"
|
|
1867
|
+
Chart title
|
|
1868
|
+
figsize : tuple, default (10, 6)
|
|
1869
|
+
Figure size
|
|
1870
|
+
grayscale : bool, default False
|
|
1871
|
+
Whether to use grayscale colors
|
|
1872
|
+
fontname : str, default "Arial"
|
|
1873
|
+
Font name for labels
|
|
1874
|
+
ylabel : bool, default True
|
|
1875
|
+
Whether to show y-axis label
|
|
1876
|
+
subtitle : bool, default True
|
|
1877
|
+
Whether to show subtitle with statistics
|
|
1878
|
+
savefig : str or dict, optional
|
|
1879
|
+
Save figure parameters
|
|
1880
|
+
show : bool, default True
|
|
1881
|
+
Whether to display the plot
|
|
1882
|
+
confidence_level : float, default 0.95
|
|
1883
|
+
Confidence level for shaded band (e.g., 0.95 for 95%)
|
|
1884
|
+
|
|
1885
|
+
Returns
|
|
1886
|
+
-------
|
|
1887
|
+
matplotlib.figure.Figure or None
|
|
1888
|
+
Figure object if show=False, otherwise None
|
|
1889
|
+
"""
|
|
1890
|
+
colors, _, _ = _get_colors(grayscale)
|
|
1891
|
+
|
|
1892
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
1893
|
+
|
|
1894
|
+
# Get simulation data
|
|
1895
|
+
data = mc_result.data
|
|
1896
|
+
|
|
1897
|
+
# Plot all simulation paths with low alpha
|
|
1898
|
+
sim_color = colors[1] if not grayscale else "#888888"
|
|
1899
|
+
for col in data.columns[1:]: # Skip first (original) path
|
|
1900
|
+
ax.plot(
|
|
1901
|
+
data.index,
|
|
1902
|
+
data[col] * 100, # Convert to percentage
|
|
1903
|
+
color=sim_color,
|
|
1904
|
+
alpha=0.03,
|
|
1905
|
+
linewidth=0.5,
|
|
1906
|
+
)
|
|
1907
|
+
|
|
1908
|
+
# Plot confidence bands
|
|
1909
|
+
lower, upper = mc_result.confidence_band(confidence_level)
|
|
1910
|
+
ax.fill_between(
|
|
1911
|
+
data.index,
|
|
1912
|
+
lower * 100,
|
|
1913
|
+
upper * 100,
|
|
1914
|
+
alpha=0.2,
|
|
1915
|
+
color=colors[1] if not grayscale else "#666666",
|
|
1916
|
+
label=f"{int(confidence_level * 100)}% Confidence Band",
|
|
1917
|
+
)
|
|
1918
|
+
|
|
1919
|
+
# Plot median path
|
|
1920
|
+
median_path = mc_result.percentile(50)
|
|
1921
|
+
ax.plot(
|
|
1922
|
+
data.index,
|
|
1923
|
+
median_path * 100,
|
|
1924
|
+
color=colors[0] if not grayscale else "#444444",
|
|
1925
|
+
linewidth=1.5,
|
|
1926
|
+
linestyle="--",
|
|
1927
|
+
label="Median",
|
|
1928
|
+
)
|
|
1929
|
+
|
|
1930
|
+
# Plot original path (highlighted)
|
|
1931
|
+
ax.plot(
|
|
1932
|
+
data.index,
|
|
1933
|
+
mc_result.original * 100,
|
|
1934
|
+
color="red" if not grayscale else "#000000",
|
|
1935
|
+
linewidth=2,
|
|
1936
|
+
label="Original",
|
|
1937
|
+
)
|
|
1938
|
+
|
|
1939
|
+
# Add bust/goal threshold lines if set
|
|
1940
|
+
if mc_result.bust_threshold is not None:
|
|
1941
|
+
ax.axhline(
|
|
1942
|
+
mc_result.bust_threshold * 100,
|
|
1943
|
+
color="darkred",
|
|
1944
|
+
linestyle="--",
|
|
1945
|
+
linewidth=1,
|
|
1946
|
+
label=f"Bust ({mc_result.bust_threshold:.0%})",
|
|
1947
|
+
)
|
|
1948
|
+
|
|
1949
|
+
if mc_result.goal_threshold is not None:
|
|
1950
|
+
ax.axhline(
|
|
1951
|
+
mc_result.goal_threshold * 100,
|
|
1952
|
+
color="darkgreen",
|
|
1953
|
+
linestyle="--",
|
|
1954
|
+
linewidth=1,
|
|
1955
|
+
label=f"Goal ({mc_result.goal_threshold:.0%})",
|
|
1956
|
+
)
|
|
1957
|
+
|
|
1958
|
+
# Configure axes
|
|
1959
|
+
ax.set_xlabel("Trading Days", fontname=fontname)
|
|
1960
|
+
if ylabel:
|
|
1961
|
+
ax.set_ylabel(
|
|
1962
|
+
"Cumulative Return (%)",
|
|
1963
|
+
fontname=fontname,
|
|
1964
|
+
fontweight="bold",
|
|
1965
|
+
fontsize=12,
|
|
1966
|
+
)
|
|
1967
|
+
|
|
1968
|
+
# Add title
|
|
1969
|
+
ax.set_title(
|
|
1970
|
+
title,
|
|
1971
|
+
fontname=fontname,
|
|
1972
|
+
fontweight="bold",
|
|
1973
|
+
fontsize=14,
|
|
1974
|
+
color="black",
|
|
1975
|
+
)
|
|
1976
|
+
|
|
1977
|
+
# Add subtitle with stats
|
|
1978
|
+
if subtitle:
|
|
1979
|
+
stats = mc_result.stats
|
|
1980
|
+
subtitle_text = (
|
|
1981
|
+
f"Sims: {len(data.columns)} | "
|
|
1982
|
+
f"Mean: {stats['mean']:.1%} | "
|
|
1983
|
+
f"Median: {stats['median']:.1%} | "
|
|
1984
|
+
f"5th-95th: {stats['percentile_5']:.1%} to {stats['percentile_95']:.1%}"
|
|
1985
|
+
)
|
|
1986
|
+
if mc_result.bust_probability is not None:
|
|
1987
|
+
subtitle_text += f" | Bust: {mc_result.bust_probability:.1%}"
|
|
1988
|
+
if mc_result.goal_probability is not None:
|
|
1989
|
+
subtitle_text += f" | Goal: {mc_result.goal_probability:.1%}"
|
|
1990
|
+
|
|
1991
|
+
ax.set_title(
|
|
1992
|
+
f"{title}\n{subtitle_text}",
|
|
1993
|
+
fontname=fontname,
|
|
1994
|
+
fontweight="bold",
|
|
1995
|
+
fontsize=12,
|
|
1996
|
+
)
|
|
1997
|
+
|
|
1998
|
+
# Add legend
|
|
1999
|
+
ax.legend(loc="upper left", fontsize=9)
|
|
2000
|
+
|
|
2001
|
+
# Add horizontal line at 0
|
|
2002
|
+
ax.axhline(0, color="black", linewidth=0.5, linestyle="-")
|
|
2003
|
+
|
|
2004
|
+
# Configure grid
|
|
2005
|
+
ax.grid(True, alpha=0.3)
|
|
2006
|
+
|
|
2007
|
+
# Tight layout
|
|
2008
|
+
fig.tight_layout()
|
|
2009
|
+
|
|
2010
|
+
# Save figure if requested
|
|
2011
|
+
if savefig:
|
|
2012
|
+
if isinstance(savefig, dict):
|
|
2013
|
+
_plt.savefig(**savefig)
|
|
2014
|
+
else:
|
|
2015
|
+
_plt.savefig(savefig)
|
|
2016
|
+
|
|
2017
|
+
if show:
|
|
2018
|
+
_plt.show()
|
|
2019
|
+
|
|
2020
|
+
_plt.close()
|
|
2021
|
+
|
|
2022
|
+
if not show:
|
|
2023
|
+
return fig
|
|
2024
|
+
|
|
2025
|
+
return None
|
|
2026
|
+
|
|
2027
|
+
|
|
2028
|
+
def plot_montecarlo_distribution(
|
|
2029
|
+
mc_result,
|
|
2030
|
+
title="Terminal Value Distribution",
|
|
2031
|
+
figsize=(10, 6),
|
|
2032
|
+
grayscale=False,
|
|
2033
|
+
fontname="Arial",
|
|
2034
|
+
ylabel=True,
|
|
2035
|
+
subtitle=True,
|
|
2036
|
+
savefig=None,
|
|
2037
|
+
show=True,
|
|
2038
|
+
bins=50,
|
|
2039
|
+
):
|
|
2040
|
+
"""
|
|
2041
|
+
Plot histogram of terminal values from Monte Carlo simulation.
|
|
2042
|
+
|
|
2043
|
+
Parameters
|
|
2044
|
+
----------
|
|
2045
|
+
mc_result : MonteCarloResult
|
|
2046
|
+
Monte Carlo simulation result object
|
|
2047
|
+
title : str, default "Terminal Value Distribution"
|
|
2048
|
+
Chart title
|
|
2049
|
+
figsize : tuple, default (10, 6)
|
|
2050
|
+
Figure size
|
|
2051
|
+
grayscale : bool, default False
|
|
2052
|
+
Whether to use grayscale colors
|
|
2053
|
+
fontname : str, default "Arial"
|
|
2054
|
+
Font name for labels
|
|
2055
|
+
ylabel : bool, default True
|
|
2056
|
+
Whether to show y-axis label
|
|
2057
|
+
subtitle : bool, default True
|
|
2058
|
+
Whether to show subtitle with statistics
|
|
2059
|
+
savefig : str or dict, optional
|
|
2060
|
+
Save figure parameters
|
|
2061
|
+
show : bool, default True
|
|
2062
|
+
Whether to display the plot
|
|
2063
|
+
bins : int, default 50
|
|
2064
|
+
Number of histogram bins
|
|
2065
|
+
|
|
2066
|
+
Returns
|
|
2067
|
+
-------
|
|
2068
|
+
matplotlib.figure.Figure or None
|
|
2069
|
+
Figure object if show=False, otherwise None
|
|
2070
|
+
"""
|
|
2071
|
+
colors, _, _ = _get_colors(grayscale)
|
|
2072
|
+
|
|
2073
|
+
fig, ax = _plt.subplots(figsize=figsize)
|
|
2074
|
+
|
|
2075
|
+
# Get terminal values
|
|
2076
|
+
terminal = mc_result.data.iloc[-1] * 100 # Convert to percentage
|
|
2077
|
+
|
|
2078
|
+
# Plot histogram
|
|
2079
|
+
hist_color = colors[1] if not grayscale else "#666666"
|
|
2080
|
+
ax.hist(terminal, bins=bins, alpha=0.7, color=hist_color, edgecolor="white")
|
|
2081
|
+
|
|
2082
|
+
# Add vertical lines for key percentiles
|
|
2083
|
+
stats = mc_result.stats
|
|
2084
|
+
ax.axvline(
|
|
2085
|
+
stats["mean"] * 100,
|
|
2086
|
+
color="red",
|
|
2087
|
+
linewidth=2,
|
|
2088
|
+
linestyle="-",
|
|
2089
|
+
label=f"Mean: {stats['mean']:.1%}",
|
|
2090
|
+
)
|
|
2091
|
+
ax.axvline(
|
|
2092
|
+
stats["median"] * 100,
|
|
2093
|
+
color="blue",
|
|
2094
|
+
linewidth=2,
|
|
2095
|
+
linestyle="--",
|
|
2096
|
+
label=f"Median: {stats['median']:.1%}",
|
|
2097
|
+
)
|
|
2098
|
+
ax.axvline(
|
|
2099
|
+
stats["percentile_5"] * 100,
|
|
2100
|
+
color="darkred",
|
|
2101
|
+
linewidth=1.5,
|
|
2102
|
+
linestyle=":",
|
|
2103
|
+
label=f"5th pct: {stats['percentile_5']:.1%}",
|
|
2104
|
+
)
|
|
2105
|
+
ax.axvline(
|
|
2106
|
+
stats["percentile_95"] * 100,
|
|
2107
|
+
color="darkgreen",
|
|
2108
|
+
linewidth=1.5,
|
|
2109
|
+
linestyle=":",
|
|
2110
|
+
label=f"95th pct: {stats['percentile_95']:.1%}",
|
|
2111
|
+
)
|
|
2112
|
+
|
|
2113
|
+
# Mark original terminal value
|
|
2114
|
+
original_terminal = mc_result.original.iloc[-1] * 100
|
|
2115
|
+
ax.axvline(
|
|
2116
|
+
original_terminal,
|
|
2117
|
+
color="black",
|
|
2118
|
+
linewidth=2,
|
|
2119
|
+
linestyle="-",
|
|
2120
|
+
label=f"Original: {original_terminal:.1f}%",
|
|
2121
|
+
)
|
|
2122
|
+
|
|
2123
|
+
# Configure axes
|
|
2124
|
+
ax.set_xlabel("Terminal Return (%)", fontname=fontname)
|
|
2125
|
+
if ylabel:
|
|
2126
|
+
ax.set_ylabel(
|
|
2127
|
+
"Frequency",
|
|
2128
|
+
fontname=fontname,
|
|
2129
|
+
fontweight="bold",
|
|
2130
|
+
fontsize=12,
|
|
2131
|
+
)
|
|
2132
|
+
|
|
2133
|
+
# Add title
|
|
2134
|
+
title_text = title
|
|
2135
|
+
if subtitle:
|
|
2136
|
+
title_text = (
|
|
2137
|
+
f"{title}\n"
|
|
2138
|
+
f"Min: {stats['min']:.1%} | Max: {stats['max']:.1%} | "
|
|
2139
|
+
f"Std: {stats['std']:.1%}"
|
|
2140
|
+
)
|
|
2141
|
+
|
|
2142
|
+
ax.set_title(
|
|
2143
|
+
title_text,
|
|
2144
|
+
fontname=fontname,
|
|
2145
|
+
fontweight="bold",
|
|
2146
|
+
fontsize=12,
|
|
2147
|
+
)
|
|
2148
|
+
|
|
2149
|
+
# Add legend
|
|
2150
|
+
ax.legend(loc="upper right", fontsize=9)
|
|
2151
|
+
|
|
2152
|
+
# Configure grid
|
|
2153
|
+
ax.grid(True, alpha=0.3, axis="y")
|
|
2154
|
+
|
|
2155
|
+
# Tight layout
|
|
2156
|
+
fig.tight_layout()
|
|
2157
|
+
|
|
2158
|
+
# Save figure if requested
|
|
2159
|
+
if savefig:
|
|
2160
|
+
if isinstance(savefig, dict):
|
|
2161
|
+
_plt.savefig(**savefig)
|
|
2162
|
+
else:
|
|
2163
|
+
_plt.savefig(savefig)
|
|
2164
|
+
|
|
2165
|
+
if show:
|
|
2166
|
+
_plt.show()
|
|
2167
|
+
|
|
2168
|
+
_plt.close()
|
|
2169
|
+
|
|
2170
|
+
if not show:
|
|
2171
|
+
return fig
|
|
2172
|
+
|
|
2173
|
+
return None
|