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,86 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Merton jump-diffusion model.
|
|
3
|
+
|
|
4
|
+
Log returns are modelled as a Gaussian diffusion plus a compound-Poisson jump
|
|
5
|
+
component. Parameters are estimated with a simple, robust threshold method:
|
|
6
|
+
periods whose log return deviates from the mean by more than ``k`` robust
|
|
7
|
+
standard deviations are flagged as jumps; the diffusion is fit on the remainder
|
|
8
|
+
and the jump size distribution on the flagged set. See the Monte Carlo challenge
|
|
9
|
+
notes on jump identification (threshold vs EM).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
from ..base import SimulationModel
|
|
18
|
+
from ..registry import register
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@register
|
|
22
|
+
class JumpDiffusion(SimulationModel):
|
|
23
|
+
name = "jump_diffusion"
|
|
24
|
+
label = "Jump Diffusion"
|
|
25
|
+
|
|
26
|
+
def __init__(self, threshold: float = 3.0) -> None:
|
|
27
|
+
super().__init__()
|
|
28
|
+
self.threshold = threshold
|
|
29
|
+
|
|
30
|
+
def calibrate(self, returns: pd.Series) -> JumpDiffusion:
|
|
31
|
+
log_r = self._to_log(self._clean(returns))
|
|
32
|
+
if log_r.size < 4:
|
|
33
|
+
# Degenerate: no jumps, pure diffusion.
|
|
34
|
+
self.mu_ = float(np.mean(log_r)) if log_r.size else 0.0
|
|
35
|
+
self.sigma_ = float(np.std(log_r, ddof=1)) if log_r.size > 1 else 0.0
|
|
36
|
+
self.lambda_ = 0.0
|
|
37
|
+
self.jump_mean_ = 0.0
|
|
38
|
+
self.jump_std_ = 0.0
|
|
39
|
+
self._fitted = True
|
|
40
|
+
return self
|
|
41
|
+
|
|
42
|
+
med = np.median(log_r)
|
|
43
|
+
mad = np.median(np.abs(log_r - med))
|
|
44
|
+
robust_std = 1.4826 * mad if mad > 0 else np.std(log_r, ddof=1)
|
|
45
|
+
is_jump = np.abs(log_r - med) > self.threshold * robust_std
|
|
46
|
+
|
|
47
|
+
diffusion = log_r[~is_jump]
|
|
48
|
+
jumps = log_r[is_jump]
|
|
49
|
+
|
|
50
|
+
self.mu_ = float(np.mean(diffusion)) if diffusion.size else float(med)
|
|
51
|
+
self.sigma_ = (
|
|
52
|
+
float(np.std(diffusion, ddof=1)) if diffusion.size > 1 else float(robust_std)
|
|
53
|
+
)
|
|
54
|
+
self.lambda_ = float(jumps.size / log_r.size)
|
|
55
|
+
self.jump_mean_ = float(np.mean(jumps)) if jumps.size else 0.0
|
|
56
|
+
self.jump_std_ = float(np.std(jumps, ddof=1)) if jumps.size > 1 else 0.0
|
|
57
|
+
self._fitted = True
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
|
|
61
|
+
ann_mu = self.mu_ * periods
|
|
62
|
+
ann_sigma = self.sigma_ * np.sqrt(periods)
|
|
63
|
+
ann_lambda = self.lambda_ * periods
|
|
64
|
+
return {
|
|
65
|
+
"Drift (ann.)": f"{ann_mu:.2%}",
|
|
66
|
+
"Diffusion vol (ann.)": f"{ann_sigma:.2%}",
|
|
67
|
+
"Jump intensity (ann.)": f"{ann_lambda:.2f}",
|
|
68
|
+
"Jump mean": f"{self.jump_mean_:.4f}",
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
def simulate(
|
|
72
|
+
self, horizon: int, sims: int, rng: np.random.Generator
|
|
73
|
+
) -> np.ndarray:
|
|
74
|
+
self._check_fitted()
|
|
75
|
+
shape = (horizon, sims)
|
|
76
|
+
diffusion = rng.normal(self.mu_, self.sigma_, size=shape)
|
|
77
|
+
if self.lambda_ > 0:
|
|
78
|
+
n_jumps = rng.poisson(self.lambda_, size=shape)
|
|
79
|
+
# Sum of n_jumps gaussian jumps == Normal(n*mean, sqrt(n)*std).
|
|
80
|
+
jump_component = rng.normal(
|
|
81
|
+
n_jumps * self.jump_mean_,
|
|
82
|
+
np.sqrt(np.maximum(n_jumps, 0)) * self.jump_std_,
|
|
83
|
+
)
|
|
84
|
+
else:
|
|
85
|
+
jump_component = 0.0
|
|
86
|
+
return self._from_log(diffusion + jump_component)
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Shuffle (permutation bootstrap) model.
|
|
3
|
+
|
|
4
|
+
Resamples the historical returns *without replacement* per path, preserving the
|
|
5
|
+
empirical distribution exactly while breaking time ordering. This mirrors the
|
|
6
|
+
legacy ``qs.stats.montecarlo`` behaviour, exposed here as a registered model.
|
|
7
|
+
When ``horizon`` differs from the history length, it samples with replacement
|
|
8
|
+
of full permutations / truncation as needed.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
from ..base import SimulationModel
|
|
17
|
+
from ..registry import register
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@register
|
|
21
|
+
class Shuffle(SimulationModel):
|
|
22
|
+
name = "shuffle"
|
|
23
|
+
label = "Shuffle"
|
|
24
|
+
|
|
25
|
+
def calibrate(self, returns: pd.Series) -> Shuffle:
|
|
26
|
+
self.returns_ = self._clean(returns)
|
|
27
|
+
if self.returns_.size == 0:
|
|
28
|
+
raise ValueError("Shuffle model needs at least one return.")
|
|
29
|
+
self._fitted = True
|
|
30
|
+
return self
|
|
31
|
+
|
|
32
|
+
def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
|
|
33
|
+
return {"Permuted observations": f"{self.returns_.size:,}"}
|
|
34
|
+
|
|
35
|
+
def simulate(
|
|
36
|
+
self, horizon: int, sims: int, rng: np.random.Generator
|
|
37
|
+
) -> np.ndarray:
|
|
38
|
+
self._check_fitted()
|
|
39
|
+
n = self.returns_.size
|
|
40
|
+
out = np.empty((horizon, sims), dtype=float)
|
|
41
|
+
for j in range(sims):
|
|
42
|
+
if horizon <= n:
|
|
43
|
+
out[:, j] = rng.permutation(self.returns_)[:horizon]
|
|
44
|
+
else:
|
|
45
|
+
# Tile permutations to fill a longer horizon.
|
|
46
|
+
reps = -(-horizon // n) # ceil division
|
|
47
|
+
chunks = [rng.permutation(self.returns_) for _ in range(reps)]
|
|
48
|
+
out[:, j] = np.concatenate(chunks)[:horizon]
|
|
49
|
+
return out
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Trimmed bootstrap models.
|
|
3
|
+
|
|
4
|
+
Removes the *best* returns from the sample before bootstrapping, producing a
|
|
5
|
+
deliberately pessimistic view of outcomes (it strips the luckiest upside while
|
|
6
|
+
keeping the downside intact). Only the top 1% variant is registered by default.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
from ..base import SimulationModel
|
|
15
|
+
from ..registry import register
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class _TrimmedBase(SimulationModel):
|
|
19
|
+
category = "stress"
|
|
20
|
+
trim_fraction: float = 0.01
|
|
21
|
+
|
|
22
|
+
def calibrate(self, returns: pd.Series) -> _TrimmedBase:
|
|
23
|
+
arr = self._clean(returns)
|
|
24
|
+
if arr.size == 0:
|
|
25
|
+
raise ValueError("Trimmed model needs at least one return.")
|
|
26
|
+
cutoff = np.quantile(arr, 1.0 - self.trim_fraction)
|
|
27
|
+
trimmed = arr[arr <= cutoff]
|
|
28
|
+
self.returns_ = trimmed if trimmed.size > 0 else arr
|
|
29
|
+
self._fitted = True
|
|
30
|
+
return self
|
|
31
|
+
|
|
32
|
+
def simulate(
|
|
33
|
+
self, horizon: int, sims: int, rng: np.random.Generator
|
|
34
|
+
) -> np.ndarray:
|
|
35
|
+
self._check_fitted()
|
|
36
|
+
idx = rng.integers(0, self.returns_.size, size=(horizon, sims))
|
|
37
|
+
return self.returns_[idx]
|
|
38
|
+
|
|
39
|
+
def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
|
|
40
|
+
return {
|
|
41
|
+
"Trim fraction (top)": f"{self.trim_fraction:.1%}",
|
|
42
|
+
"Sample size (after trim)": f"{self.returns_.size:,}",
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@register
|
|
47
|
+
class TrimmedTop1(_TrimmedBase):
|
|
48
|
+
name = "trimmed_1pct"
|
|
49
|
+
label = "Trimmed (top 1%)"
|
|
50
|
+
trim_fraction = 0.01
|
|
@@ -0,0 +1,324 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Plotting helpers for the Monte Carlo tearsheet.
|
|
3
|
+
|
|
4
|
+
These produce matplotlib figures from :class:`ModelResult` objects: overlay fan
|
|
5
|
+
charts, drawdown distributions, CAGR quantile strips, and per-model detail
|
|
6
|
+
charts for the collapsible appendix.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import matplotlib
|
|
12
|
+
|
|
13
|
+
matplotlib.use("Agg", force=False)
|
|
14
|
+
import matplotlib.pyplot as plt
|
|
15
|
+
import numpy as np
|
|
16
|
+
|
|
17
|
+
from . import analytics
|
|
18
|
+
|
|
19
|
+
_PRIMARY = "#348dc1"
|
|
20
|
+
_BAND = "#9bc4e2"
|
|
21
|
+
_ACCENT = "#003366"
|
|
22
|
+
_MEDIAN = "#c1431d"
|
|
23
|
+
_HIST = "#1a1a1a"
|
|
24
|
+
_PALETTE = [
|
|
25
|
+
"#348dc1",
|
|
26
|
+
"#c1431d",
|
|
27
|
+
"#6B9E00",
|
|
28
|
+
"#7b68ee",
|
|
29
|
+
"#e67e22",
|
|
30
|
+
"#16a085",
|
|
31
|
+
"#8e44ad",
|
|
32
|
+
"#2c3e50",
|
|
33
|
+
"#d35400",
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _historical_band(historical_windows: np.ndarray):
|
|
38
|
+
"""Median and p5–p95 band of cumulative paths across rolling windows."""
|
|
39
|
+
cum = analytics.cumulative_paths(historical_windows)
|
|
40
|
+
median = np.median(cum, axis=1)
|
|
41
|
+
lower = np.quantile(cum, 0.05, axis=1)
|
|
42
|
+
upper = np.quantile(cum, 0.95, axis=1)
|
|
43
|
+
return median, lower, upper
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def fan_chart_figure(
|
|
47
|
+
result,
|
|
48
|
+
level: float = 0.95,
|
|
49
|
+
n_paths: int = 100,
|
|
50
|
+
figsize: tuple[float, float] = (8, 4),
|
|
51
|
+
title: str | None = None,
|
|
52
|
+
historical_windows: np.ndarray | None = None,
|
|
53
|
+
):
|
|
54
|
+
"""Fan chart: sample paths (faint), confidence band, median, optional history."""
|
|
55
|
+
paths = analytics.cumulative_paths(result.sim_returns) * 100.0
|
|
56
|
+
median, lower, upper = analytics.fan_chart(result.sim_returns, level=level)
|
|
57
|
+
x = np.arange(paths.shape[0])
|
|
58
|
+
|
|
59
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
60
|
+
fig.set_facecolor("white")
|
|
61
|
+
ax.set_facecolor("white")
|
|
62
|
+
|
|
63
|
+
sample = min(n_paths, paths.shape[1])
|
|
64
|
+
if sample > 0:
|
|
65
|
+
step = max(1, paths.shape[1] // sample)
|
|
66
|
+
for j in range(0, paths.shape[1], step):
|
|
67
|
+
ax.plot(x, paths[:, j], color=_PRIMARY, alpha=0.05, lw=0.6)
|
|
68
|
+
|
|
69
|
+
ax.fill_between(
|
|
70
|
+
x,
|
|
71
|
+
lower * 100.0,
|
|
72
|
+
upper * 100.0,
|
|
73
|
+
color=_BAND,
|
|
74
|
+
alpha=0.5,
|
|
75
|
+
label=f"{int(level * 100)}% band",
|
|
76
|
+
)
|
|
77
|
+
ax.plot(x, median * 100.0, color=_MEDIAN, lw=1.6, label="Median")
|
|
78
|
+
|
|
79
|
+
if historical_windows is not None and historical_windows.size:
|
|
80
|
+
h_med, _, _ = _historical_band(historical_windows)
|
|
81
|
+
hx = np.arange(h_med.size)
|
|
82
|
+
ax.plot(
|
|
83
|
+
hx,
|
|
84
|
+
h_med * 100.0,
|
|
85
|
+
color=_HIST,
|
|
86
|
+
lw=2.0,
|
|
87
|
+
ls="--",
|
|
88
|
+
label="Historical median (rolling)",
|
|
89
|
+
zorder=5,
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
ax.axhline(0, color="gray", lw=0.8, ls="--")
|
|
93
|
+
ax.set_title(title or result.label, fontweight="bold", color="black")
|
|
94
|
+
ax.set_xlabel("Periods")
|
|
95
|
+
ax.set_ylabel("Cumulative Return (%)")
|
|
96
|
+
ax.spines["top"].set_visible(False)
|
|
97
|
+
ax.spines["right"].set_visible(False)
|
|
98
|
+
ax.legend(loc="upper left", frameon=False, fontsize=9)
|
|
99
|
+
fig.tight_layout()
|
|
100
|
+
return fig
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def terminal_hist_figure(
|
|
104
|
+
result,
|
|
105
|
+
figsize: tuple[float, float] = (8, 3),
|
|
106
|
+
title: str | None = None,
|
|
107
|
+
historical_terminal: float | None = None,
|
|
108
|
+
):
|
|
109
|
+
"""Histogram of terminal cumulative returns across simulations."""
|
|
110
|
+
terminal = result.terminal_values() * 100.0
|
|
111
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
112
|
+
fig.set_facecolor("white")
|
|
113
|
+
ax.set_facecolor("white")
|
|
114
|
+
|
|
115
|
+
ax.hist(terminal, bins=40, color=_PRIMARY, alpha=0.75, edgecolor="white")
|
|
116
|
+
ax.axvline(
|
|
117
|
+
float(np.median(terminal)), color=_MEDIAN, lw=1.5, label="Median"
|
|
118
|
+
)
|
|
119
|
+
if historical_terminal is not None:
|
|
120
|
+
ax.axvline(
|
|
121
|
+
historical_terminal * 100.0,
|
|
122
|
+
color=_HIST,
|
|
123
|
+
lw=2.0,
|
|
124
|
+
label="Historical",
|
|
125
|
+
)
|
|
126
|
+
ax.axvline(0, color="gray", lw=0.8, ls="--")
|
|
127
|
+
|
|
128
|
+
ax.set_title(
|
|
129
|
+
title or f"{result.label} - Terminal Return Distribution",
|
|
130
|
+
fontweight="bold",
|
|
131
|
+
color="black",
|
|
132
|
+
)
|
|
133
|
+
ax.set_xlabel("Terminal Cumulative Return (%)")
|
|
134
|
+
ax.set_ylabel("Frequency")
|
|
135
|
+
ax.spines["top"].set_visible(False)
|
|
136
|
+
ax.spines["right"].set_visible(False)
|
|
137
|
+
ax.legend(loc="upper right", frameon=False, fontsize=9)
|
|
138
|
+
fig.tight_layout()
|
|
139
|
+
return fig
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def overlay_fan_figure(
|
|
143
|
+
results: list,
|
|
144
|
+
level: float = 0.95,
|
|
145
|
+
figsize: tuple[float, float] = (10, 5),
|
|
146
|
+
title: str = "Model Medians & Envelope",
|
|
147
|
+
historical_windows: np.ndarray | None = None,
|
|
148
|
+
):
|
|
149
|
+
"""Overlay median paths per model with a pooled confidence envelope."""
|
|
150
|
+
if not results:
|
|
151
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
152
|
+
ax.text(0.5, 0.5, "No models", ha="center", va="center")
|
|
153
|
+
return fig
|
|
154
|
+
|
|
155
|
+
horizon = results[0].horizon
|
|
156
|
+
x = np.arange(horizon)
|
|
157
|
+
pooled = np.concatenate(
|
|
158
|
+
[analytics.cumulative_paths(r.sim_returns) for r in results], axis=1
|
|
159
|
+
)
|
|
160
|
+
median_env = np.median(pooled, axis=1)
|
|
161
|
+
alpha = (1.0 - level) / 2.0
|
|
162
|
+
lower = np.quantile(pooled, alpha, axis=1)
|
|
163
|
+
upper = np.quantile(pooled, 1.0 - alpha, axis=1)
|
|
164
|
+
|
|
165
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
166
|
+
fig.set_facecolor("white")
|
|
167
|
+
ax.set_facecolor("white")
|
|
168
|
+
|
|
169
|
+
ax.fill_between(
|
|
170
|
+
x,
|
|
171
|
+
lower * 100.0,
|
|
172
|
+
upper * 100.0,
|
|
173
|
+
color=_BAND,
|
|
174
|
+
alpha=0.35,
|
|
175
|
+
label=f"Pooled {int(level * 100)}% band",
|
|
176
|
+
)
|
|
177
|
+
ax.plot(
|
|
178
|
+
x,
|
|
179
|
+
median_env * 100.0,
|
|
180
|
+
color=_ACCENT,
|
|
181
|
+
lw=2.0,
|
|
182
|
+
ls="--",
|
|
183
|
+
label="Pooled median",
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
for i, res in enumerate(results):
|
|
187
|
+
med, _, _ = analytics.fan_chart(res.sim_returns, level=level)
|
|
188
|
+
color = _PALETTE[i % len(_PALETTE)]
|
|
189
|
+
ax.plot(x, med * 100.0, color=color, lw=1.4, label=res.label)
|
|
190
|
+
|
|
191
|
+
if historical_windows is not None and historical_windows.size:
|
|
192
|
+
h_med, h_lo, h_hi = _historical_band(historical_windows)
|
|
193
|
+
hx = np.arange(h_med.size)
|
|
194
|
+
ax.fill_between(
|
|
195
|
+
hx,
|
|
196
|
+
h_lo * 100.0,
|
|
197
|
+
h_hi * 100.0,
|
|
198
|
+
color=_HIST,
|
|
199
|
+
alpha=0.08,
|
|
200
|
+
label="Historical 5–95% (rolling windows)",
|
|
201
|
+
zorder=1,
|
|
202
|
+
)
|
|
203
|
+
ax.plot(
|
|
204
|
+
hx,
|
|
205
|
+
h_med * 100.0,
|
|
206
|
+
color=_HIST,
|
|
207
|
+
lw=2.2,
|
|
208
|
+
ls="--",
|
|
209
|
+
label="Historical median (rolling windows)",
|
|
210
|
+
zorder=6,
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
ax.axhline(0, color="gray", lw=0.8, ls="--")
|
|
214
|
+
ax.set_title(title, fontweight="bold", color="black")
|
|
215
|
+
ax.set_xlabel("Periods")
|
|
216
|
+
ax.set_ylabel("Cumulative Return (%)")
|
|
217
|
+
ax.spines["top"].set_visible(False)
|
|
218
|
+
ax.spines["right"].set_visible(False)
|
|
219
|
+
ax.legend(loc="upper left", frameon=False, fontsize=8, ncol=2)
|
|
220
|
+
fig.tight_layout()
|
|
221
|
+
return fig
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def maxdd_distribution_figure(
|
|
225
|
+
results: list,
|
|
226
|
+
figsize: tuple[float, float] = (10, 5),
|
|
227
|
+
title: str = "Max Drawdown Distribution by Model",
|
|
228
|
+
historical_windows: np.ndarray | None = None,
|
|
229
|
+
):
|
|
230
|
+
"""Horizontal boxplot of max drawdown distributions (plus historical)."""
|
|
231
|
+
if not results:
|
|
232
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
233
|
+
ax.text(0.5, 0.5, "No models", ha="center", va="center")
|
|
234
|
+
return fig
|
|
235
|
+
|
|
236
|
+
data = [analytics.max_drawdowns(r.sim_returns) * 100.0 for r in results]
|
|
237
|
+
labels = [r.label for r in results]
|
|
238
|
+
n_hist = 0
|
|
239
|
+
if historical_windows is not None and historical_windows.size:
|
|
240
|
+
data.insert(0, analytics.max_drawdowns(historical_windows) * 100.0)
|
|
241
|
+
labels.insert(0, "Historical (rolling)")
|
|
242
|
+
n_hist = 1
|
|
243
|
+
|
|
244
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
245
|
+
fig.set_facecolor("white")
|
|
246
|
+
ax.set_facecolor("white")
|
|
247
|
+
|
|
248
|
+
bp = ax.boxplot(
|
|
249
|
+
data,
|
|
250
|
+
orientation="horizontal",
|
|
251
|
+
tick_labels=labels,
|
|
252
|
+
patch_artist=True,
|
|
253
|
+
showfliers=False,
|
|
254
|
+
medianprops={"color": _MEDIAN, "linewidth": 1.5},
|
|
255
|
+
)
|
|
256
|
+
for i, patch in enumerate(bp["boxes"]):
|
|
257
|
+
if i < n_hist:
|
|
258
|
+
patch.set_facecolor(_HIST)
|
|
259
|
+
patch.set_alpha(0.45)
|
|
260
|
+
else:
|
|
261
|
+
patch.set_facecolor(_PRIMARY)
|
|
262
|
+
patch.set_alpha(0.55)
|
|
263
|
+
|
|
264
|
+
ax.set_xlabel("Max Drawdown (%)")
|
|
265
|
+
ax.set_title(title, fontweight="bold", color="black")
|
|
266
|
+
ax.spines["top"].set_visible(False)
|
|
267
|
+
ax.spines["right"].set_visible(False)
|
|
268
|
+
fig.tight_layout()
|
|
269
|
+
return fig
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def cagr_quantiles_figure(
|
|
273
|
+
results: list,
|
|
274
|
+
figsize: tuple[float, float] = (10, 5),
|
|
275
|
+
title: str = "CAGR Quantiles by Model",
|
|
276
|
+
historical_windows: np.ndarray | None = None,
|
|
277
|
+
):
|
|
278
|
+
"""Horizontal range plot of CAGR p5–median–p95 per model (plus historical)."""
|
|
279
|
+
if not results:
|
|
280
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
281
|
+
ax.text(0.5, 0.5, "No models", ha="center", va="center")
|
|
282
|
+
return fig
|
|
283
|
+
|
|
284
|
+
labels = []
|
|
285
|
+
p5s, medians, p95s = [], [], []
|
|
286
|
+
hist_flags = []
|
|
287
|
+
if historical_windows is not None and historical_windows.size:
|
|
288
|
+
periods = results[0].periods
|
|
289
|
+
h_cagr = analytics.cagr_values(historical_windows, periods) * 100.0
|
|
290
|
+
labels.append("Historical (rolling)")
|
|
291
|
+
p5s.append(float(np.quantile(h_cagr, 0.05)))
|
|
292
|
+
medians.append(float(np.median(h_cagr)))
|
|
293
|
+
p95s.append(float(np.quantile(h_cagr, 0.95)))
|
|
294
|
+
hist_flags.append(True)
|
|
295
|
+
for res in results:
|
|
296
|
+
cagr = analytics.cagr_values(res.sim_returns, res.periods) * 100.0
|
|
297
|
+
labels.append(res.label)
|
|
298
|
+
p5s.append(float(np.quantile(cagr, 0.05)))
|
|
299
|
+
medians.append(float(np.median(cagr)))
|
|
300
|
+
p95s.append(float(np.quantile(cagr, 0.95)))
|
|
301
|
+
hist_flags.append(False)
|
|
302
|
+
|
|
303
|
+
y = np.arange(len(labels))
|
|
304
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
305
|
+
fig.set_facecolor("white")
|
|
306
|
+
ax.set_facecolor("white")
|
|
307
|
+
|
|
308
|
+
for i, (lo, mid, hi, is_hist) in enumerate(
|
|
309
|
+
zip(p5s, medians, p95s, hist_flags, strict=True)
|
|
310
|
+
):
|
|
311
|
+
color = _HIST if is_hist else _PALETTE[i % len(_PALETTE)]
|
|
312
|
+
ax.plot([lo, hi], [i, i], color=color, lw=2.0, solid_capstyle="round")
|
|
313
|
+
ax.scatter([lo, hi], [i, i], color=color, s=28, zorder=3)
|
|
314
|
+
ax.scatter([mid], [i], color=_MEDIAN, s=48, zorder=4, marker="D")
|
|
315
|
+
|
|
316
|
+
ax.axvline(0, color="gray", lw=0.8, ls="--")
|
|
317
|
+
ax.set_yticks(y)
|
|
318
|
+
ax.set_yticklabels(labels)
|
|
319
|
+
ax.set_xlabel("CAGR (%)")
|
|
320
|
+
ax.set_title(title, fontweight="bold", color="black")
|
|
321
|
+
ax.spines["top"].set_visible(False)
|
|
322
|
+
ax.spines["right"].set_visible(False)
|
|
323
|
+
fig.tight_layout()
|
|
324
|
+
return fig
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Registry of Monte Carlo simulation models, keyed by name.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from .base import SimulationModel
|
|
8
|
+
|
|
9
|
+
_REGISTRY: dict[str, type[SimulationModel]] = {}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def register(model_cls: type[SimulationModel]) -> type[SimulationModel]:
|
|
13
|
+
"""Class decorator that registers a :class:`SimulationModel` by ``name``."""
|
|
14
|
+
name = model_cls.name
|
|
15
|
+
if not name or name == "base":
|
|
16
|
+
raise ValueError(f"Model {model_cls!r} must define a unique 'name'.")
|
|
17
|
+
_REGISTRY[name] = model_cls
|
|
18
|
+
return model_cls
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def get_model(name: str) -> SimulationModel:
|
|
22
|
+
"""Instantiate a registered model by name."""
|
|
23
|
+
try:
|
|
24
|
+
return _REGISTRY[name]()
|
|
25
|
+
except KeyError as exc:
|
|
26
|
+
raise KeyError(
|
|
27
|
+
f"Unknown Monte Carlo model '{name}'. "
|
|
28
|
+
f"Available: {', '.join(available_models())}"
|
|
29
|
+
) from exc
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def available_models() -> list[str]:
|
|
33
|
+
"""Return the registered model names, in registration order."""
|
|
34
|
+
return list(_REGISTRY.keys())
|
quantstats/plots.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
#!/usr/bin/env python
|
|
2
|
+
#
|
|
3
|
+
# QuantStats: Portfolio analytics for quants
|
|
4
|
+
# https://github.com/ranaroussi/quantstats
|
|
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
|
+
try:
|
|
21
|
+
from pandas.plotting import register_matplotlib_converters as _rmc
|
|
22
|
+
|
|
23
|
+
_rmc()
|
|
24
|
+
except ImportError:
|
|
25
|
+
pass
|
|
26
|
+
|
|
27
|
+
from quantstats._plotting.wrappers import *
|
quantstats/py.typed
ADDED
|
File without changes
|
quantstats/report.html
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
<!-- generated by QuantStats Pro -->
|
|
2
|
+
<!DOCTYPE html>
|
|
3
|
+
<html lang="en">
|
|
4
|
+
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8">
|
|
7
|
+
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
|
9
|
+
<title>Tearsheet (generated by QuantStats Pro)</title>
|
|
10
|
+
<meta name="robots" content="noindex, nofollow">
|
|
11
|
+
<style>
|
|
12
|
+
body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;margin:30px;background:#fff;color:#000}body,p,table,td,th{font:13px/1.4 Arial,sans-serif}.container{max-width:960px;margin:auto}img,svg{width:100%}h1,h2,h3,h4{font-weight:400;margin:0}h1 dt{display:inline;margin-left:10px;font-size:14px}h3{margin-bottom:10px;font-weight:700}h4{color:grey}h4 a{color:#09c;text-decoration:none}h4 a:hover{color:#069;text-decoration:underline}hr{margin:25px 0 40px;height:0;border:0;border-top:1px solid #ccc}#left{width:620px;margin-right:18px;margin-top:-1.2rem;float:left}#right{width:320px;float:right}#left svg{margin:-1.5rem 0}#monthly_heatmap{overflow:hidden}#monthly_heatmap svg{margin:-1.5rem 0}table{margin:0 0 40px;border:0;border-spacing:0;width:100%}table td,table th{text-align:right;padding:4px 5px 3px 5px}table th{text-align:right;padding:6px 5px 5px 5px}table td:first-of-type,table th:first-of-type{text-align:left;padding-left:2px}table td:last-of-type,table th:last-of-type{text-align:right;padding-right:2px}td hr{margin:5px 0}table th{font-weight:400}table thead th{font-weight:700;background:#2d2d2d;color:#fff}#eoy table td:after{content:"%"}#eoy table td:first-of-type:after,#eoy table td:last-of-type:after,#eoy table td:nth-of-type(4):after{content:""}#eoy table th{text-align:right}#eoy table th:first-of-type{text-align:left}#eoy table td:after{content:"%"}#eoy table td:first-of-type:after,#eoy table td:last-of-type:after{content:""}#ddinfo table td:nth-of-type(3):after{content:"%"}#ddinfo table th{text-align:right}#ddinfo table td:first-of-type,#ddinfo table td:nth-of-type(2),#ddinfo table th:first-of-type,#ddinfo table th:nth-of-type(2){text-align:left}#ddinfo table td:nth-of-type(3):after{content:"%"}
|
|
13
|
+
|
|
14
|
+
@media print{hr{margin:25px 0}body{margin:0}.container{max-width:100%;margin:0}#left{width:55%;margin:0}#left svg{margin:0 0 -10%}#left svg:first-of-type{margin-top:-30%}#right{margin:0;width:45%}}
|
|
15
|
+
</style>
|
|
16
|
+
</head>
|
|
17
|
+
|
|
18
|
+
<body onload="save()">
|
|
19
|
+
|
|
20
|
+
<div class="container">
|
|
21
|
+
|
|
22
|
+
<h1>{{title}} <dt>{{date_range}}{{matched_dates}}</dt></h1>
|
|
23
|
+
<h4>{{params}} Generated by <a href="https://github.com/diegoalvarezmgl/quantstats-pro/" target="quantstats">QuantStats Pro</a> (v. {{v}}) at {{generated_at}}</h4>
|
|
24
|
+
<hr>
|
|
25
|
+
|
|
26
|
+
<div id="left">
|
|
27
|
+
|
|
28
|
+
<div>
|
|
29
|
+
{{returns}}
|
|
30
|
+
</div>
|
|
31
|
+
|
|
32
|
+
<div id="log_returns">{{log_returns}}</div>
|
|
33
|
+
<div id="vol_returns">{{vol_returns}}</div>
|
|
34
|
+
<div id="eoy_returns">{{eoy_returns}}</div>
|
|
35
|
+
<div id="monthly_dist">{{monthly_dist}}</div>
|
|
36
|
+
<div id="daily_returns">{{daily_returns}}</div>
|
|
37
|
+
<div id="rolling_beta">{{rolling_beta}}</div>
|
|
38
|
+
<div id="rolling_vol">{{rolling_vol}}</div>
|
|
39
|
+
<div id="rolling_sharpe">{{rolling_sharpe}}</div>
|
|
40
|
+
<div id="rolling_sortino">{{rolling_sortino}}</div>
|
|
41
|
+
<div id="dd_periods">{{dd_periods}}</div>
|
|
42
|
+
<div id="dd_plot">{{dd_plot}}</div>
|
|
43
|
+
<div id="monthly_heatmap">{{monthly_heatmap}}</div>
|
|
44
|
+
<div id="returns_dist">{{returns_dist}}</div>
|
|
45
|
+
|
|
46
|
+
</div>
|
|
47
|
+
|
|
48
|
+
<div id="right">
|
|
49
|
+
<h3>Key Performance Metrics</h3>
|
|
50
|
+
{{metrics}}
|
|
51
|
+
|
|
52
|
+
<div id="eoy">{{eoy_title}}
|
|
53
|
+
{{eoy_table}}</div>
|
|
54
|
+
|
|
55
|
+
<div id="ddinfo">
|
|
56
|
+
<h3>Worst 10 Drawdowns</h3>
|
|
57
|
+
{{dd_info}}
|
|
58
|
+
</div>
|
|
59
|
+
</div>
|
|
60
|
+
|
|
61
|
+
</div>
|
|
62
|
+
<style>*{white-space:auto !important;}</style>
|
|
63
|
+
</body>
|
|
64
|
+
</html>
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
<!-- generated by QuantStats Pro (alpha_decay) -->
|
|
2
|
+
<!DOCTYPE html>
|
|
3
|
+
<html lang="en">
|
|
4
|
+
|
|
5
|
+
<head>
|
|
6
|
+
<meta charset="utf-8">
|
|
7
|
+
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
|
|
8
|
+
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
|
9
|
+
<title>Alpha Decay Tearsheet (generated by QuantStats Pro)</title>
|
|
10
|
+
<meta name="robots" content="noindex, nofollow">
|
|
11
|
+
<style>
|
|
12
|
+
body{-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;margin:30px;background:#fff;color:#000}body,p,table,td,th{font:13px/1.4 Arial,sans-serif}.container{max-width:1200px;margin:auto}img,svg{width:100%}h1,h2,h3,h4{font-weight:400;margin:0}h1 dt{display:inline;margin-left:10px;font-size:14px}h3{margin:30px 0 10px;font-weight:700}h4{color:grey;margin:20px 0 8px;font-weight:700}h4 a{color:#09c;text-decoration:none}h4 a:hover{color:#069;text-decoration:underline}hr{margin:25px 0 30px;height:0;border:0;border-top:1px solid #ccc}table{margin:0 0 30px;border:0;border-spacing:0;width:100%}table td,table th{text-align:center;padding:4px 6px 3px 6px}table th{text-align:center;padding:6px;font-weight:700;background:#2d2d2d;color:#fff}table td:first-of-type,table th:first-of-type{text-align:left}table tbody tr:nth-child(even){background:#f6f6f6}.grid{display:flex;flex-wrap:wrap;gap:10px}.cell{width:32%}.cell.full{width:100%;max-width:850px;margin:0 auto 10px}.note{color:#666;font-size:12px;margin:0 0 15px;line-height:1.5}.kpi-grid{display:grid;grid-template-columns:repeat(4,1fr);gap:12px;margin:15px 0 25px}@media(max-width:768px){.kpi-grid{grid-template-columns:repeat(2,1fr)}}.kpi-grid.score-grid{margin-bottom:10px}.kpi-grid.score-grid .kpi{grid-column:1/-1}.kpi{border:1px solid #e3e3e3;border-radius:6px;padding:12px 14px;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.04)}.kpi-grid .kpi{border-left:3px solid #9e9e9e}.kpi-grid .kpi.excellent{border-left-color:#2e7d32}.kpi-grid .kpi.good{border-left-color:#689f38}.kpi-grid .kpi.warning{border-left-color:#f57f17}.kpi-grid .kpi.critical{border-left-color:#c62828}.kpi-grid .kpi.excellent .value{color:#2e7d32}.kpi-grid .kpi.good .value{color:#558b2f}.kpi-grid .kpi.warning .value{color:#f57f17}.kpi-grid .kpi.critical .value{color:#c62828}.kpi .label{font-size:11px;color:#666;text-transform:uppercase;letter-spacing:.03em}.kpi .value{font-size:22px;font-weight:700;margin-top:4px}.kpi .hint{font-size:11px;color:#999;margin-top:4px}.badge{display:inline-block;padding:2px 8px;border-radius:3px;font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.02em}.badge.excellent{background:#e8f5e9;color:#2e7d32}.badge.good{background:#f1f8e9;color:#558b2f}.badge.warning{background:#fff8e1;color:#f57f17}.badge.critical{background:#ffebee;color:#c62828}.metric-row{margin:25px 0 35px;padding-bottom:20px;border-bottom:1px solid #eee}.metric-meta{font-size:11px;color:#888;margin:4px 0 10px}.sota-note{background:#e3f2fd;border-left:3px solid #348dc1;padding:10px 14px;margin:0 0 15px;font-size:12px;color:#555}footer{margin-top:30px;padding-top:15px;border-top:1px solid #ccc;font-size:11px;color:#888;line-height:1.6}
|
|
13
|
+
</style>
|
|
14
|
+
</head>
|
|
15
|
+
|
|
16
|
+
<body>
|
|
17
|
+
|
|
18
|
+
<div class="container">
|
|
19
|
+
|
|
20
|
+
<h1>{{title}} <dt>{{date_range}}</dt></h1>
|
|
21
|
+
<h4>{{params}} Generated by <a href="https://github.com/diegoalvarezmgl/quantstats-pro/" target="quantstats">QuantStats Pro</a> (v. {{v}}) at {{generated_at}}</h4>
|
|
22
|
+
<hr>
|
|
23
|
+
|
|
24
|
+
<h3>Health Summary</h3>
|
|
25
|
+
<p class="note">Rolling risk metrics compared to their historical distributions. Each cell flags the latest {{windows_label}}-day window against all prior windows of the same length.</p>
|
|
26
|
+
{{score_summary}}
|
|
27
|
+
{{status_counts}}
|
|
28
|
+
<div id="summary_table">{{summary_table}}</div>
|
|
29
|
+
|
|
30
|
+
<h3>Metric Distributions</h3>
|
|
31
|
+
<p class="note">One row per metric. Each panel shows the historical rolling distribution on the <em>analysis scale</em> (log / log-severity transforms where needed — same scale as the z-score). The mean (dashed) and current observation (solid) are marked on that scale; Obs/Mean above each chart stay in original units.</p>
|
|
32
|
+
<div id="metric_rows">{{metric_rows}}</div>
|
|
33
|
+
|
|
34
|
+
<h3>Structural Decay Diagnostics</h3>
|
|
35
|
+
<div id="cusum_chart" class="cell full">{{cusum_chart}}</div>
|
|
36
|
+
<div id="time_underwater" class="cell full">{{time_underwater}}</div>
|
|
37
|
+
{{sota_stats}}
|
|
38
|
+
|
|
39
|
+
<footer>{{assumptions}}</footer>
|
|
40
|
+
|
|
41
|
+
</div>
|
|
42
|
+
</body>
|
|
43
|
+
</html>
|