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,206 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Plotting helpers for the alpha-decay tearsheet.
|
|
3
|
+
|
|
4
|
+
Rolling-metric histograms use the analysis (transformed) scale — same as the
|
|
5
|
+
z-score — with axis labels naming the transform. Time-underwater uses raw
|
|
6
|
+
days on the chart (easier to read); only its z-score is computed on log(days).
|
|
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
|
+
from scipy import stats as sp_stats
|
|
17
|
+
|
|
18
|
+
from .core import (
|
|
19
|
+
CusumResult,
|
|
20
|
+
MetricSpec,
|
|
21
|
+
TimeUnderwaterResult,
|
|
22
|
+
WindowResult,
|
|
23
|
+
format_value,
|
|
24
|
+
transform_axis_label,
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
_EXCELLENT = "#2e7d32"
|
|
28
|
+
_GOOD = "#689f38"
|
|
29
|
+
_WARNING = "#f9a825"
|
|
30
|
+
_CRITICAL = "#c62828"
|
|
31
|
+
_PRIMARY = "#348dc1"
|
|
32
|
+
_MEDIAN = "#c1431d"
|
|
33
|
+
_ACCENT = "#003366"
|
|
34
|
+
|
|
35
|
+
_STATUS_COLORS = {
|
|
36
|
+
"excellent": _EXCELLENT,
|
|
37
|
+
"good": _GOOD,
|
|
38
|
+
"warning": _WARNING,
|
|
39
|
+
"critical": _CRITICAL,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def _underwater_hist_bounds(
|
|
44
|
+
dist: np.ndarray,
|
|
45
|
+
mean: float,
|
|
46
|
+
current_days: int,
|
|
47
|
+
is_underwater: bool,
|
|
48
|
+
*,
|
|
49
|
+
percentile: float = 90.0,
|
|
50
|
+
) -> tuple[float, np.ndarray, int, float]:
|
|
51
|
+
"""
|
|
52
|
+
Pick a readable histogram x-range for completed spell lengths.
|
|
53
|
+
|
|
54
|
+
Completed spells are heavily right-skewed: a single 400-day episode
|
|
55
|
+
would stretch the axis to 400 even when mean ≈ 13 and current ≈ 12.
|
|
56
|
+
We cap the axis at roughly the p90 bulk, always including mean and the
|
|
57
|
+
current spell, and return outlier counts for an annotation.
|
|
58
|
+
"""
|
|
59
|
+
markers = max(mean, float(current_days) if is_underwater else 0.0)
|
|
60
|
+
if len(dist) == 0:
|
|
61
|
+
return max(markers * 1.25, 10.0), dist, 0, 0.0
|
|
62
|
+
|
|
63
|
+
p = float(np.percentile(dist, percentile))
|
|
64
|
+
upper = max(markers * 1.25, p * 1.05, 12.0)
|
|
65
|
+
mx = float(dist.max())
|
|
66
|
+
if mx <= upper:
|
|
67
|
+
return upper + 1, dist, 0, mx
|
|
68
|
+
|
|
69
|
+
in_range = dist[dist <= upper]
|
|
70
|
+
beyond = dist[dist > upper]
|
|
71
|
+
return upper, in_range, int(len(beyond)), float(beyond.max())
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def metric_distribution_figure(
|
|
75
|
+
result: WindowResult,
|
|
76
|
+
spec: MetricSpec,
|
|
77
|
+
figsize: tuple[float, float] = (4.2, 3.0),
|
|
78
|
+
title: str | None = None,
|
|
79
|
+
):
|
|
80
|
+
"""Histogram + KDE on the analysis (transformed) scale with raw-unit legend."""
|
|
81
|
+
dist = result.analysis_distribution
|
|
82
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
83
|
+
fig.set_facecolor("white")
|
|
84
|
+
ax.set_facecolor("white")
|
|
85
|
+
|
|
86
|
+
if len(dist) == 0:
|
|
87
|
+
ax.text(0.5, 0.5, "Insufficient data", ha="center", va="center")
|
|
88
|
+
ax.set_axis_off()
|
|
89
|
+
fig.tight_layout()
|
|
90
|
+
return fig
|
|
91
|
+
|
|
92
|
+
color = _STATUS_COLORS.get(result.status, _PRIMARY)
|
|
93
|
+
ax.hist(dist, bins=min(30, max(10, len(dist) // 8)), color=_PRIMARY, alpha=0.55, edgecolor="white")
|
|
94
|
+
|
|
95
|
+
if len(dist) > 5 and np.std(dist) > 0:
|
|
96
|
+
xs = np.linspace(dist.min(), dist.max(), 200)
|
|
97
|
+
try:
|
|
98
|
+
kde = sp_stats.gaussian_kde(dist)
|
|
99
|
+
ax.plot(xs, kde(xs) * len(dist) * (dist.max() - dist.min()) / 30, color=_ACCENT, lw=1.2, alpha=0.8)
|
|
100
|
+
except Exception:
|
|
101
|
+
pass
|
|
102
|
+
|
|
103
|
+
ax.axvline(
|
|
104
|
+
result.analysis_mean,
|
|
105
|
+
color=_MEDIAN,
|
|
106
|
+
lw=1.4,
|
|
107
|
+
ls="--",
|
|
108
|
+
label=f"Mean ({format_value(spec, result.mean)})",
|
|
109
|
+
)
|
|
110
|
+
ax.axvline(
|
|
111
|
+
result.analysis_observed,
|
|
112
|
+
color=color,
|
|
113
|
+
lw=2.0,
|
|
114
|
+
label=f"Current ({format_value(spec, result.observed)})",
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
ttl = title or f"{spec.label} — {result.window}d"
|
|
118
|
+
ax.set_title(ttl, fontweight="bold", color="black", fontsize=10, pad=8)
|
|
119
|
+
ax.set_xlabel(transform_axis_label(spec), fontsize=9)
|
|
120
|
+
ax.set_ylabel("Frequency", fontsize=9)
|
|
121
|
+
ax.spines["top"].set_visible(False)
|
|
122
|
+
ax.spines["right"].set_visible(False)
|
|
123
|
+
ax.legend(loc="upper right", frameon=False, fontsize=7)
|
|
124
|
+
fig.tight_layout()
|
|
125
|
+
return fig
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def cusum_figure(
|
|
129
|
+
cusum: CusumResult,
|
|
130
|
+
figsize: tuple[float, float] = (8, 2.8),
|
|
131
|
+
title: str = "CUSUM — Return Decay Detector",
|
|
132
|
+
):
|
|
133
|
+
"""CUSUM control chart with alarm threshold."""
|
|
134
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
135
|
+
fig.set_facecolor("white")
|
|
136
|
+
ax.set_facecolor("white")
|
|
137
|
+
|
|
138
|
+
x = np.arange(len(cusum.series))
|
|
139
|
+
ax.plot(x, cusum.series.to_numpy(), color=_PRIMARY, lw=1.4, label="CUSUM")
|
|
140
|
+
ax.axhline(cusum.threshold, color=_CRITICAL, lw=1.2, ls="--", label=f"Threshold ({cusum.threshold:.4f})")
|
|
141
|
+
ax.fill_between(x, 0, cusum.threshold, color="#ffebee", alpha=0.3)
|
|
142
|
+
|
|
143
|
+
status = "ALARM" if cusum.alarm else f"{cusum.pct_of_threshold:.0%} of threshold"
|
|
144
|
+
ax.set_title(f"{title} — {status}", fontweight="bold", color="black", pad=8)
|
|
145
|
+
ax.set_xlabel("Trading day (0 = start of sample)")
|
|
146
|
+
ax.set_ylabel("Cumulative sum of shortfalls")
|
|
147
|
+
ax.spines["top"].set_visible(False)
|
|
148
|
+
ax.spines["right"].set_visible(False)
|
|
149
|
+
ax.legend(loc="upper left", frameon=False, fontsize=9)
|
|
150
|
+
fig.tight_layout()
|
|
151
|
+
return fig
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def time_underwater_figure(
|
|
155
|
+
tuw: TimeUnderwaterResult,
|
|
156
|
+
figsize: tuple[float, float] = (8, 2.8),
|
|
157
|
+
title: str = "Time Underwater — Completed Spell Lengths",
|
|
158
|
+
):
|
|
159
|
+
"""Histogram of completed underwater spells (days); current spell marked separately."""
|
|
160
|
+
fig, ax = plt.subplots(figsize=figsize)
|
|
161
|
+
fig.set_facecolor("white")
|
|
162
|
+
ax.set_facecolor("white")
|
|
163
|
+
|
|
164
|
+
dist = tuw.distribution
|
|
165
|
+
if len(dist) == 0:
|
|
166
|
+
ax.text(0.5, 0.5, "No completed drawdown spells yet", ha="center", va="center")
|
|
167
|
+
ax.set_axis_off()
|
|
168
|
+
fig.tight_layout()
|
|
169
|
+
return fig
|
|
170
|
+
|
|
171
|
+
color = _STATUS_COLORS.get(tuw.status, _PRIMARY)
|
|
172
|
+
upper, hist_dist, n_beyond, longest_beyond = _underwater_hist_bounds(
|
|
173
|
+
dist, tuw.mean, tuw.current_days, tuw.is_underwater
|
|
174
|
+
)
|
|
175
|
+
width = max(1, int(np.ceil(upper / 30.0)))
|
|
176
|
+
edges = np.arange(0.5, upper + width + 0.5, width)
|
|
177
|
+
ax.hist(hist_dist, bins=edges, color=_PRIMARY, alpha=0.55, edgecolor="white")
|
|
178
|
+
ax.set_xlim(0, upper * 1.03 + 1)
|
|
179
|
+
if n_beyond > 0:
|
|
180
|
+
ax.text(
|
|
181
|
+
0.98,
|
|
182
|
+
0.97,
|
|
183
|
+
f"+{n_beyond} spell{'s' if n_beyond != 1 else ''} > {upper:.0f}d"
|
|
184
|
+
f"\n(longest {longest_beyond:.0f}d)",
|
|
185
|
+
transform=ax.transAxes,
|
|
186
|
+
ha="right",
|
|
187
|
+
va="top",
|
|
188
|
+
fontsize=7,
|
|
189
|
+
color="#666",
|
|
190
|
+
)
|
|
191
|
+
ax.axvline(tuw.mean, color=_MEDIAN, lw=1.4, ls="--", label=f"Mean ({tuw.mean:.0f}d)")
|
|
192
|
+
if tuw.is_underwater:
|
|
193
|
+
ax.axvline(
|
|
194
|
+
tuw.current_days,
|
|
195
|
+
color=color,
|
|
196
|
+
lw=2.0,
|
|
197
|
+
label=f"Current spell ({tuw.current_days}d)",
|
|
198
|
+
)
|
|
199
|
+
ax.set_title(title, fontweight="bold", color="black", pad=8)
|
|
200
|
+
ax.set_xlabel("Completed underwater spell (days)")
|
|
201
|
+
ax.set_ylabel("Frequency")
|
|
202
|
+
ax.spines["top"].set_visible(False)
|
|
203
|
+
ax.spines["right"].set_visible(False)
|
|
204
|
+
ax.legend(loc="upper right", frameon=False, fontsize=9)
|
|
205
|
+
fig.tight_layout()
|
|
206
|
+
return fig
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Multi-model Monte Carlo engine for QuantStats Pro.
|
|
3
|
+
|
|
4
|
+
This package characterises a single asset's return series with several models
|
|
5
|
+
(GBM, jump-diffusion, GARCH, stochastic volatility, bootstraps, Bayesian, ...)
|
|
6
|
+
and simulates forward paths from each, enabling a cross-model comparison of the
|
|
7
|
+
distribution of outcomes (terminal value, CAGR, max drawdown, bust/goal probs).
|
|
8
|
+
|
|
9
|
+
The legacy shuffle-based Monte Carlo (:mod:`quantstats._montecarlo`) remains the
|
|
10
|
+
default for ``qs.stats.montecarlo`` and is exposed here as the ``shuffle`` model.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
# Importing models registers them in the registry.
|
|
14
|
+
from . import (
|
|
15
|
+
analytics,
|
|
16
|
+
base,
|
|
17
|
+
models, # noqa: E402,F401 (side-effect: registration)
|
|
18
|
+
registry,
|
|
19
|
+
)
|
|
20
|
+
from .base import SimulationModel
|
|
21
|
+
from .core import ModelResult, infer_periods_per_year, run_models
|
|
22
|
+
from .registry import available_models, get_model
|
|
23
|
+
|
|
24
|
+
__all__ = [
|
|
25
|
+
"SimulationModel",
|
|
26
|
+
"ModelResult",
|
|
27
|
+
"run_models",
|
|
28
|
+
"infer_periods_per_year",
|
|
29
|
+
"get_model",
|
|
30
|
+
"available_models",
|
|
31
|
+
"analytics",
|
|
32
|
+
"base",
|
|
33
|
+
"registry",
|
|
34
|
+
]
|
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Analytics over simulated return paths.
|
|
3
|
+
|
|
4
|
+
All functions take ``sim_returns``: a 2-D array of shape ``(horizon, sims)`` of
|
|
5
|
+
simple periodic returns, and derive distributions of outcomes used by the
|
|
6
|
+
montecarlo tearsheet and the cross-model comparison table.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from .core import ModelResult
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def cumulative_paths(sim_returns: np.ndarray) -> np.ndarray:
|
|
21
|
+
"""Cumulative simple return per path: ``prod(1+r) - 1`` along time.
|
|
22
|
+
|
|
23
|
+
Returns an array of shape ``(horizon, sims)`` where each column is the
|
|
24
|
+
running cumulative return of that path.
|
|
25
|
+
"""
|
|
26
|
+
return np.cumprod(1.0 + sim_returns, axis=0) - 1.0
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def terminal_values(sim_returns: np.ndarray) -> np.ndarray:
|
|
30
|
+
"""Terminal cumulative simple return for each path (1-D, length ``sims``)."""
|
|
31
|
+
return np.prod(1.0 + sim_returns, axis=0) - 1.0
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def max_drawdowns(sim_returns: np.ndarray) -> np.ndarray:
|
|
35
|
+
"""Maximum drawdown (negative) of each path (1-D, length ``sims``)."""
|
|
36
|
+
growth = np.cumprod(1.0 + sim_returns, axis=0)
|
|
37
|
+
running_max = np.maximum.accumulate(growth, axis=0)
|
|
38
|
+
drawdowns = growth / running_max - 1.0
|
|
39
|
+
return drawdowns.min(axis=0)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def cagr_values(sim_returns: np.ndarray, periods: float = 252.0) -> np.ndarray:
|
|
43
|
+
"""Annualised compound growth rate for each path (1-D, length ``sims``)."""
|
|
44
|
+
horizon = sim_returns.shape[0]
|
|
45
|
+
years = horizon / periods
|
|
46
|
+
terminal = terminal_values(sim_returns)
|
|
47
|
+
# Guard against terminal <= -1 (total wipeout) which would be invalid.
|
|
48
|
+
safe = np.clip(terminal, -0.999999, None)
|
|
49
|
+
return (1.0 + safe) ** (1.0 / years) - 1.0
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def cvar(values: np.ndarray, q: float = 0.05) -> float:
|
|
53
|
+
"""Expected shortfall (CVaR) of the left tail at quantile ``q``."""
|
|
54
|
+
threshold = float(np.quantile(values, q))
|
|
55
|
+
tail = values[values <= threshold]
|
|
56
|
+
return float(np.mean(tail)) if tail.size > 0 else threshold
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def bust_probability(sim_returns: np.ndarray, bust: float) -> float:
|
|
60
|
+
"""Fraction of paths whose max drawdown is at or beyond ``bust`` (negative)."""
|
|
61
|
+
mdd = max_drawdowns(sim_returns)
|
|
62
|
+
return float(np.mean(mdd <= bust))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def goal_probability(sim_returns: np.ndarray, goal: float) -> float:
|
|
66
|
+
"""Fraction of paths whose terminal cumulative return reaches ``goal``."""
|
|
67
|
+
terminal = terminal_values(sim_returns)
|
|
68
|
+
return float(np.mean(terminal >= goal))
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def fan_chart(
|
|
72
|
+
sim_returns: np.ndarray, level: float = 0.95
|
|
73
|
+
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
|
|
74
|
+
"""Median path and a symmetric confidence band of cumulative returns.
|
|
75
|
+
|
|
76
|
+
Returns ``(median, lower, upper)``, each of length ``horizon``.
|
|
77
|
+
"""
|
|
78
|
+
paths = cumulative_paths(sim_returns)
|
|
79
|
+
alpha = (1.0 - level) / 2.0
|
|
80
|
+
median = np.median(paths, axis=1)
|
|
81
|
+
lower = np.quantile(paths, alpha, axis=1)
|
|
82
|
+
upper = np.quantile(paths, 1.0 - alpha, axis=1)
|
|
83
|
+
return median, lower, upper
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def historical_windows(returns: pd.Series, horizon: int) -> np.ndarray:
|
|
87
|
+
"""All overlapping ``horizon``-length return windows from full history.
|
|
88
|
+
|
|
89
|
+
Returns an array of shape ``(horizon, n_windows)`` — the same layout as
|
|
90
|
+
``sim_returns`` — so the empirical distribution of *realised* outcomes over
|
|
91
|
+
the entire history can be compared directly against simulated paths. If the
|
|
92
|
+
history is shorter than ``horizon``, a single truncated window is returned.
|
|
93
|
+
"""
|
|
94
|
+
arr = pd.Series(returns).dropna().to_numpy(dtype=float)
|
|
95
|
+
if arr.size == 0:
|
|
96
|
+
return np.empty((0, 0), dtype=float)
|
|
97
|
+
if arr.size <= horizon:
|
|
98
|
+
return arr.reshape(-1, 1)
|
|
99
|
+
windows = np.lib.stride_tricks.sliding_window_view(arr, horizon)
|
|
100
|
+
return np.ascontiguousarray(windows.T)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
def historical_window(returns: pd.Series, horizon: int) -> np.ndarray:
|
|
104
|
+
"""Trailing ``horizon`` simple returns from history (1-D)."""
|
|
105
|
+
arr = pd.Series(returns).dropna().to_numpy(dtype=float)
|
|
106
|
+
if arr.size == 0:
|
|
107
|
+
return np.array([], dtype=float)
|
|
108
|
+
return arr[-min(horizon, arr.size) :]
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def historical_cumulative(returns: pd.Series, horizon: int) -> np.ndarray:
|
|
112
|
+
"""Cumulative return path of the trailing historical window."""
|
|
113
|
+
window = historical_window(returns, horizon)
|
|
114
|
+
if window.size == 0:
|
|
115
|
+
return np.array([], dtype=float)
|
|
116
|
+
return cumulative_paths(window.reshape(-1, 1))[:, 0]
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def historical_summary(
|
|
120
|
+
returns: pd.Series,
|
|
121
|
+
horizon: int,
|
|
122
|
+
periods: float = 252.0,
|
|
123
|
+
bust: float | None = None,
|
|
124
|
+
goal: float | None = None,
|
|
125
|
+
) -> dict[str, float]:
|
|
126
|
+
"""Empirical distribution of realised metrics over all rolling windows.
|
|
127
|
+
|
|
128
|
+
Uses every overlapping ``horizon``-length window of the full history, so
|
|
129
|
+
quantiles (CAGR p5/median/p95, MaxDD, CVaR, probabilities) describe what
|
|
130
|
+
actually happened across the whole sample — directly comparable with each
|
|
131
|
+
model's simulated distribution.
|
|
132
|
+
"""
|
|
133
|
+
windows = historical_windows(returns, horizon)
|
|
134
|
+
if windows.size == 0:
|
|
135
|
+
return {}
|
|
136
|
+
return summarize(windows, periods=periods, bust=bust, goal=goal)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def realism_percentile(sim_returns: np.ndarray, historical_terminal: float) -> float:
|
|
140
|
+
"""Percentile rank of the historical terminal within simulated terminals."""
|
|
141
|
+
terminal = terminal_values(sim_returns)
|
|
142
|
+
if terminal.size == 0:
|
|
143
|
+
return float("nan")
|
|
144
|
+
return float(np.mean(terminal <= historical_terminal) * 100.0)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def summarize(
|
|
148
|
+
sim_returns: np.ndarray,
|
|
149
|
+
periods: float = 252.0,
|
|
150
|
+
bust: float | None = None,
|
|
151
|
+
goal: float | None = None,
|
|
152
|
+
) -> dict[str, float]:
|
|
153
|
+
"""Cross-model comparison row for a set of simulated paths."""
|
|
154
|
+
terminal = terminal_values(sim_returns)
|
|
155
|
+
mdd = max_drawdowns(sim_returns)
|
|
156
|
+
cagr = cagr_values(sim_returns, periods)
|
|
157
|
+
|
|
158
|
+
summary: dict[str, float] = {
|
|
159
|
+
"cagr_p5": float(np.quantile(cagr, 0.05)),
|
|
160
|
+
"cagr_median": float(np.median(cagr)),
|
|
161
|
+
"cagr_p95": float(np.quantile(cagr, 0.95)),
|
|
162
|
+
# 5th percentile of max drawdown: severity exceeded by ~5% of paths.
|
|
163
|
+
"maxdd_median": float(np.median(mdd)),
|
|
164
|
+
"maxdd_p95": float(np.quantile(mdd, 0.05)),
|
|
165
|
+
"terminal_median": float(np.median(terminal)),
|
|
166
|
+
"prob_loss": float(np.mean(terminal < 0)),
|
|
167
|
+
# CVaR on horizon terminal return (at 1y horizon = annual return tail).
|
|
168
|
+
"cvar_5": cvar(terminal, 0.05),
|
|
169
|
+
}
|
|
170
|
+
if bust is not None:
|
|
171
|
+
summary["bust_prob"] = bust_probability(sim_returns, bust)
|
|
172
|
+
if goal is not None:
|
|
173
|
+
summary["goal_prob"] = goal_probability(sim_returns, goal)
|
|
174
|
+
return summary
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def model_median_summary(
|
|
178
|
+
results: dict[str, ModelResult],
|
|
179
|
+
category: str = "montecarlo",
|
|
180
|
+
) -> dict[str, float]:
|
|
181
|
+
"""Median metrics across models in a category (robust consensus view)."""
|
|
182
|
+
summaries = [
|
|
183
|
+
res.summary for res in results.values() if res.category == category
|
|
184
|
+
]
|
|
185
|
+
if not summaries:
|
|
186
|
+
return {}
|
|
187
|
+
|
|
188
|
+
keys = (
|
|
189
|
+
"cagr_p5",
|
|
190
|
+
"cagr_median",
|
|
191
|
+
"cagr_p95",
|
|
192
|
+
"maxdd_median",
|
|
193
|
+
"maxdd_p95",
|
|
194
|
+
"terminal_median",
|
|
195
|
+
"prob_loss",
|
|
196
|
+
"cvar_5",
|
|
197
|
+
"bust_prob",
|
|
198
|
+
"goal_prob",
|
|
199
|
+
)
|
|
200
|
+
median: dict[str, float] = {}
|
|
201
|
+
for key in keys:
|
|
202
|
+
vals = [s[key] for s in summaries if key in s]
|
|
203
|
+
if vals:
|
|
204
|
+
median[key] = float(np.median(vals))
|
|
205
|
+
return median
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def conservative_envelope(
|
|
209
|
+
results: dict[str, ModelResult],
|
|
210
|
+
category: str = "montecarlo",
|
|
211
|
+
) -> dict[str, float]:
|
|
212
|
+
"""Worst-case metrics across models in a category (conservative envelope).
|
|
213
|
+
|
|
214
|
+
Takes the minimum of upside metrics, maximum of downside probabilities,
|
|
215
|
+
and the most severe drawdown tail across the selected models.
|
|
216
|
+
"""
|
|
217
|
+
summaries = [
|
|
218
|
+
(name, res.summary)
|
|
219
|
+
for name, res in results.items()
|
|
220
|
+
if res.category == category
|
|
221
|
+
]
|
|
222
|
+
if not summaries:
|
|
223
|
+
return {}
|
|
224
|
+
|
|
225
|
+
keys_min = (
|
|
226
|
+
"cagr_p5",
|
|
227
|
+
"cagr_median",
|
|
228
|
+
"cagr_p95",
|
|
229
|
+
"maxdd_median",
|
|
230
|
+
"maxdd_p95",
|
|
231
|
+
"terminal_median",
|
|
232
|
+
"cvar_5",
|
|
233
|
+
)
|
|
234
|
+
keys_max = ("prob_loss",)
|
|
235
|
+
|
|
236
|
+
envelope: dict[str, float] = {}
|
|
237
|
+
for key in keys_min:
|
|
238
|
+
envelope[key] = min(s[1][key] for s in summaries)
|
|
239
|
+
for key in keys_max:
|
|
240
|
+
envelope[key] = max(s[1][key] for s in summaries)
|
|
241
|
+
|
|
242
|
+
if all("bust_prob" in s[1] for s in summaries):
|
|
243
|
+
envelope["bust_prob"] = max(s[1]["bust_prob"] for s in summaries)
|
|
244
|
+
if all("goal_prob" in s[1] for s in summaries):
|
|
245
|
+
envelope["goal_prob"] = min(s[1]["goal_prob"] for s in summaries)
|
|
246
|
+
return envelope
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
def envelope_attribution(
|
|
250
|
+
results: dict[str, ModelResult],
|
|
251
|
+
envelope: dict[str, float],
|
|
252
|
+
category: str = "montecarlo",
|
|
253
|
+
) -> dict[str, str]:
|
|
254
|
+
"""Map each envelope metric to the model label that produced the extreme."""
|
|
255
|
+
summaries = [
|
|
256
|
+
(res.label, res.summary)
|
|
257
|
+
for res in results.values()
|
|
258
|
+
if res.category == category
|
|
259
|
+
]
|
|
260
|
+
if not summaries or not envelope:
|
|
261
|
+
return {}
|
|
262
|
+
|
|
263
|
+
keys_min = (
|
|
264
|
+
"cagr_p5",
|
|
265
|
+
"cagr_median",
|
|
266
|
+
"cagr_p95",
|
|
267
|
+
"maxdd_median",
|
|
268
|
+
"maxdd_p95",
|
|
269
|
+
"terminal_median",
|
|
270
|
+
"cvar_5",
|
|
271
|
+
"goal_prob",
|
|
272
|
+
)
|
|
273
|
+
keys_max = ("prob_loss", "bust_prob")
|
|
274
|
+
|
|
275
|
+
attr: dict[str, str] = {}
|
|
276
|
+
for key in keys_min:
|
|
277
|
+
if key not in envelope:
|
|
278
|
+
continue
|
|
279
|
+
if key == "goal_prob":
|
|
280
|
+
label = min(summaries, key=lambda s: s[1].get(key, float("inf")))[0]
|
|
281
|
+
else:
|
|
282
|
+
label = min(summaries, key=lambda s: s[1].get(key, float("inf")))[0]
|
|
283
|
+
attr[key] = label
|
|
284
|
+
|
|
285
|
+
for key in keys_max:
|
|
286
|
+
if key not in envelope:
|
|
287
|
+
continue
|
|
288
|
+
label = max(summaries, key=lambda s: s[1].get(key, float("-inf")))[0]
|
|
289
|
+
attr[key] = label
|
|
290
|
+
|
|
291
|
+
return attr
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Base interface for Monte Carlo simulation models.
|
|
3
|
+
|
|
4
|
+
A simulation model characterises an asset from its historical returns
|
|
5
|
+
(``calibrate``) and produces forward paths of *simple periodic returns*
|
|
6
|
+
(``simulate``). Keeping a single, narrow interface lets the engine treat every
|
|
7
|
+
characterisation method uniformly and compare them side by side.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
from abc import ABC, abstractmethod
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
import pandas as pd
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class SimulationModel(ABC):
|
|
19
|
+
"""
|
|
20
|
+
Abstract base class for Monte Carlo characterisation models.
|
|
21
|
+
|
|
22
|
+
Subclasses must define a unique ``name`` and implement :meth:`calibrate`
|
|
23
|
+
and :meth:`simulate`. ``simulate`` must return an array of shape
|
|
24
|
+
``(horizon, sims)`` of **simple** periodic returns (not log, not prices),
|
|
25
|
+
so downstream analytics are uniform across models.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
#: Short, unique identifier used by the registry and reports.
|
|
29
|
+
name: str = "base"
|
|
30
|
+
#: Human-readable label for tables and charts.
|
|
31
|
+
label: str = "Base"
|
|
32
|
+
#: Report grouping: ``"montecarlo"`` (neutral simulation) or ``"stress"``.
|
|
33
|
+
category: str = "montecarlo"
|
|
34
|
+
|
|
35
|
+
def __init__(self) -> None:
|
|
36
|
+
self._fitted: bool = False
|
|
37
|
+
|
|
38
|
+
@abstractmethod
|
|
39
|
+
def calibrate(self, returns: pd.Series) -> SimulationModel:
|
|
40
|
+
"""Estimate model parameters from a returns Series. Returns ``self``."""
|
|
41
|
+
raise NotImplementedError
|
|
42
|
+
|
|
43
|
+
@abstractmethod
|
|
44
|
+
def simulate(
|
|
45
|
+
self, horizon: int, sims: int, rng: np.random.Generator
|
|
46
|
+
) -> np.ndarray:
|
|
47
|
+
"""
|
|
48
|
+
Generate simulated simple periodic returns.
|
|
49
|
+
|
|
50
|
+
Parameters
|
|
51
|
+
----------
|
|
52
|
+
horizon : int
|
|
53
|
+
Number of periods (e.g. trading days) per simulated path.
|
|
54
|
+
sims : int
|
|
55
|
+
Number of independent simulated paths.
|
|
56
|
+
rng : numpy.random.Generator
|
|
57
|
+
Source of randomness (seeded by the caller for reproducibility).
|
|
58
|
+
|
|
59
|
+
Returns
|
|
60
|
+
-------
|
|
61
|
+
numpy.ndarray
|
|
62
|
+
Array of shape ``(horizon, sims)`` of simple periodic returns.
|
|
63
|
+
"""
|
|
64
|
+
raise NotImplementedError
|
|
65
|
+
|
|
66
|
+
# --- helpers shared by subclasses -------------------------------------
|
|
67
|
+
|
|
68
|
+
@staticmethod
|
|
69
|
+
def _clean(returns: pd.Series) -> np.ndarray:
|
|
70
|
+
"""Return finite simple returns as a 1-D float array."""
|
|
71
|
+
arr = pd.Series(returns).dropna().to_numpy(dtype=float)
|
|
72
|
+
return arr[np.isfinite(arr)]
|
|
73
|
+
|
|
74
|
+
@staticmethod
|
|
75
|
+
def _to_log(simple: np.ndarray) -> np.ndarray:
|
|
76
|
+
"""Convert simple returns to log returns (clipped to avoid -inf)."""
|
|
77
|
+
return np.log1p(np.clip(simple, -0.999999, None))
|
|
78
|
+
|
|
79
|
+
@staticmethod
|
|
80
|
+
def _from_log(log_returns: np.ndarray) -> np.ndarray:
|
|
81
|
+
"""Convert log returns back to simple returns."""
|
|
82
|
+
return np.expm1(log_returns)
|
|
83
|
+
|
|
84
|
+
def _check_fitted(self) -> None:
|
|
85
|
+
if not self._fitted:
|
|
86
|
+
raise RuntimeError(
|
|
87
|
+
f"Model '{self.name}' must be calibrated before simulate()."
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
|
|
91
|
+
"""Human-readable calibrated parameters for the tearsheet."""
|
|
92
|
+
return {}
|