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.
Files changed (43) hide show
  1. quantstats/__init__.py +163 -0
  2. quantstats/_compat.py +431 -0
  3. quantstats/_montecarlo.py +296 -0
  4. quantstats/_numpy_compat.py +289 -0
  5. quantstats/_plotting/__init__.py +0 -0
  6. quantstats/_plotting/core.py +2173 -0
  7. quantstats/_plotting/wrappers.py +2109 -0
  8. quantstats/_reporting/__init__.py +12 -0
  9. quantstats/_reporting/engine.py +37 -0
  10. quantstats/_reporting/sections.py +223 -0
  11. quantstats/alphadecay/__init__.py +25 -0
  12. quantstats/alphadecay/core.py +712 -0
  13. quantstats/alphadecay/plotting.py +206 -0
  14. quantstats/montecarlo/__init__.py +34 -0
  15. quantstats/montecarlo/analytics.py +291 -0
  16. quantstats/montecarlo/base.py +92 -0
  17. quantstats/montecarlo/core.py +175 -0
  18. quantstats/montecarlo/models/__init__.py +15 -0
  19. quantstats/montecarlo/models/bayesian.py +88 -0
  20. quantstats/montecarlo/models/block_bootstrap.py +108 -0
  21. quantstats/montecarlo/models/bootstrap.py +38 -0
  22. quantstats/montecarlo/models/garch.py +83 -0
  23. quantstats/montecarlo/models/gbm.py +44 -0
  24. quantstats/montecarlo/models/heston.py +103 -0
  25. quantstats/montecarlo/models/jump_diffusion.py +86 -0
  26. quantstats/montecarlo/models/shuffle.py +49 -0
  27. quantstats/montecarlo/models/trimmed.py +50 -0
  28. quantstats/montecarlo/plotting.py +324 -0
  29. quantstats/montecarlo/registry.py +34 -0
  30. quantstats/plots.py +27 -0
  31. quantstats/py.typed +0 -0
  32. quantstats/report.html +64 -0
  33. quantstats/report_alpha_decay.html +43 -0
  34. quantstats/report_montecarlo.html +62 -0
  35. quantstats/report_simple.html +58 -0
  36. quantstats/reports.py +3502 -0
  37. quantstats/stats.py +3321 -0
  38. quantstats/utils.py +1011 -0
  39. quantstats/version.py +1 -0
  40. quantstats_pro-0.4.1.dist-info/METADATA +509 -0
  41. quantstats_pro-0.4.1.dist-info/RECORD +43 -0
  42. quantstats_pro-0.4.1.dist-info/WHEEL +4 -0
  43. quantstats_pro-0.4.1.dist-info/licenses/LICENSE.txt +202 -0
@@ -0,0 +1,175 @@
1
+ """
2
+ Orchestration: calibrate and simulate multiple models, collect results.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from dataclasses import dataclass, field
8
+
9
+ import numpy as np
10
+ import pandas as pd
11
+
12
+ from . import analytics
13
+ from .base import SimulationModel
14
+ from .registry import available_models, get_model
15
+
16
+ _DRIFT_MODES = ("historical", "zero", "rf")
17
+
18
+
19
+ def infer_periods_per_year(returns: pd.Series) -> float:
20
+ """Infer trading days per year from the return index.
21
+
22
+ DatetimeIndex with >5% weekend observations → 365 (crypto / 24-7).
23
+ Otherwise → 252 (US equities).
24
+ """
25
+ idx = returns.index
26
+ if isinstance(idx, pd.DatetimeIndex) and len(idx) > 0:
27
+ weekend = idx.dayofweek >= 5
28
+ if float(weekend.mean()) > 0.05:
29
+ return 365.0
30
+ return 252.0
31
+
32
+
33
+ def _apply_drift(
34
+ returns: pd.Series,
35
+ drift: str,
36
+ rf: float = 0.0,
37
+ periods: float = 252.0,
38
+ ) -> pd.Series:
39
+ """Re-center the return series' drift before calibration.
40
+
41
+ ``historical`` keeps the estimated drift; ``zero`` removes it (isolating
42
+ risk/structure); ``rf`` sets the per-period mean to the risk-free rate.
43
+ Adjustment is done on log returns so it is consistent across models.
44
+ """
45
+ if drift not in _DRIFT_MODES:
46
+ raise ValueError(f"drift must be one of {_DRIFT_MODES}, got {drift!r}")
47
+ if drift == "historical":
48
+ return returns
49
+
50
+ simple = returns.to_numpy(dtype=float)
51
+ log_r = np.log1p(np.clip(simple, -0.999999, None))
52
+ target = 0.0 if drift == "zero" else np.log1p(rf) / periods
53
+ log_adj = log_r - np.mean(log_r) + target
54
+ return pd.Series(np.expm1(log_adj), index=returns.index, name=returns.name)
55
+
56
+
57
+ @dataclass
58
+ class ModelResult:
59
+ """Container for one model's simulated paths and derived analytics."""
60
+
61
+ name: str
62
+ label: str
63
+ sim_returns: np.ndarray # shape (horizon, sims), simple periodic returns
64
+ category: str = "montecarlo"
65
+ periods: float = 252.0
66
+ bust: float | None = None
67
+ goal: float | None = None
68
+ fitted_model: SimulationModel | None = field(default=None, repr=False)
69
+
70
+ @property
71
+ def horizon(self) -> int:
72
+ return int(self.sim_returns.shape[0])
73
+
74
+ @property
75
+ def sims(self) -> int:
76
+ return int(self.sim_returns.shape[1])
77
+
78
+ @property
79
+ def summary(self) -> dict[str, float]:
80
+ return analytics.summarize(
81
+ self.sim_returns, periods=self.periods, bust=self.bust, goal=self.goal
82
+ )
83
+
84
+ def terminal_values(self) -> np.ndarray:
85
+ return analytics.terminal_values(self.sim_returns)
86
+
87
+ def fan_chart(self, level: float = 0.95):
88
+ return analytics.fan_chart(self.sim_returns, level=level)
89
+
90
+ def calibration_summary(self) -> dict[str, str]:
91
+ if self.fitted_model is None:
92
+ return {}
93
+ return self.fitted_model.calibration_summary(periods=self.periods)
94
+
95
+
96
+ def run_models(
97
+ returns: pd.Series,
98
+ models: list[str] | None = None,
99
+ horizon: int | None = None,
100
+ sims: int = 1000,
101
+ bust: float | None = None,
102
+ goal: float | None = None,
103
+ seed: int | None = None,
104
+ periods: float | None = None,
105
+ drift: str = "historical",
106
+ rf: float = 0.0,
107
+ ) -> dict[str, ModelResult]:
108
+ """
109
+ Calibrate and simulate one or more models on a single asset's returns.
110
+
111
+ Parameters
112
+ ----------
113
+ returns : pd.Series
114
+ Daily (periodic) simple returns of a single asset.
115
+ models : list[str], optional
116
+ Model names to run. Defaults to all registered models.
117
+ horizon : int, optional
118
+ Number of periods per path. Defaults to one year
119
+ (``periods_per_year`` trading days).
120
+ sims : int, default 1000
121
+ Number of simulated paths per model.
122
+ bust : float, optional
123
+ Drawdown threshold for bust probability (e.g. ``-0.25``).
124
+ goal : float, optional
125
+ Terminal-return threshold for goal probability (e.g. ``0.5``).
126
+ seed : int, optional
127
+ Base seed; each model receives an independent child stream so results
128
+ are reproducible yet not artificially correlated across models.
129
+ periods : float, optional
130
+ Periods per year for annualisation. When ``None``, inferred from the
131
+ return index (252 for weekdays-only, 365 for 24/7 data).
132
+ drift : {"historical", "zero", "rf"}, default "historical"
133
+ How to treat the estimated drift before calibration. ``historical``
134
+ keeps it; ``zero`` removes it to compare pure risk/structure; ``rf``
135
+ sets the per-period mean to the risk-free rate.
136
+ rf : float, default 0.0
137
+ Annual risk-free rate, used only when ``drift="rf"``.
138
+
139
+ Returns
140
+ -------
141
+ dict[str, ModelResult]
142
+ Mapping of model name to its :class:`ModelResult`, in the requested
143
+ order.
144
+ """
145
+ returns = pd.Series(returns).dropna()
146
+ if periods is None:
147
+ periods = infer_periods_per_year(returns)
148
+ if horizon is None:
149
+ horizon = int(round(periods))
150
+ if horizon <= 0:
151
+ raise ValueError("horizon must be a positive integer")
152
+
153
+ returns = _apply_drift(returns, drift, rf=rf, periods=periods)
154
+
155
+ names = list(models) if models else available_models()
156
+ seed_seq = np.random.SeedSequence(seed)
157
+ children = seed_seq.spawn(len(names))
158
+
159
+ results: dict[str, ModelResult] = {}
160
+ for name, child in zip(names, children, strict=True):
161
+ model = get_model(name)
162
+ model.calibrate(returns)
163
+ rng = np.random.default_rng(child)
164
+ sim_returns = model.simulate(horizon, sims, rng)
165
+ results[name] = ModelResult(
166
+ name=name,
167
+ label=getattr(model, "label", name),
168
+ category=getattr(model, "category", "montecarlo"),
169
+ sim_returns=np.asarray(sim_returns, dtype=float),
170
+ periods=periods,
171
+ bust=bust,
172
+ goal=goal,
173
+ fitted_model=model,
174
+ )
175
+ return results
@@ -0,0 +1,15 @@
1
+ """
2
+ Built-in simulation models. Importing this package registers them all.
3
+ """
4
+
5
+ from . import ( # noqa: F401 (side-effect: registration)
6
+ bayesian,
7
+ block_bootstrap,
8
+ bootstrap,
9
+ garch,
10
+ gbm,
11
+ heston,
12
+ jump_diffusion,
13
+ shuffle,
14
+ trimmed,
15
+ )
@@ -0,0 +1,88 @@
1
+ """
2
+ Bayesian models.
3
+
4
+ ``bayesian`` -- conjugate Normal-Inverse-Gamma posterior for the mean and
5
+ variance of log returns under a non-informative (Jeffreys) prior. Parameter
6
+ uncertainty is propagated by drawing ``(mu, sigma^2)`` from the posterior once
7
+ per path and then generating i.i.d. Gaussian log returns. The per-period
8
+ predictive is Student-t, but drawing per path correctly inflates path-to-path
9
+ dispersion to reflect estimation uncertainty.
10
+
11
+ ``bayesian_bootstrap`` -- Rubin's Bayesian bootstrap: each path draws Dirichlet
12
+ weights over the observed returns and resamples accordingly, a smooth
13
+ nonparametric posterior over the empirical distribution.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+
21
+ from ..base import SimulationModel
22
+ from ..registry import register
23
+
24
+
25
+ @register
26
+ class BayesianNIG(SimulationModel):
27
+ name = "bayesian"
28
+ label = "Bayesian (NIG)"
29
+
30
+ def calibrate(self, returns: pd.Series) -> BayesianNIG:
31
+ log_r = self._to_log(self._clean(returns))
32
+ self.n_ = int(log_r.size)
33
+ if self.n_ < 2:
34
+ raise ValueError("Bayesian model needs at least two returns.")
35
+ self.xbar_ = float(np.mean(log_r))
36
+ self.s2_ = float(np.var(log_r, ddof=1))
37
+ self._fitted = True
38
+ return self
39
+
40
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
41
+ ann_mu = self.xbar_ * periods
42
+ ann_sigma = float(np.sqrt(self.s2_) * np.sqrt(periods))
43
+ return {
44
+ "Drift (ann.)": f"{ann_mu:.2%}",
45
+ "Volatility (ann.)": f"{ann_sigma:.2%}",
46
+ "Sample size": f"{self.n_:,}",
47
+ }
48
+
49
+ def simulate(
50
+ self, horizon: int, sims: int, rng: np.random.Generator
51
+ ) -> np.ndarray:
52
+ self._check_fitted()
53
+ n = self.n_
54
+ chi2 = rng.chisquare(df=n - 1, size=sims)
55
+ sigma2 = (n - 1) * self.s2_ / np.maximum(chi2, 1e-12)
56
+ mu = self.xbar_ + rng.standard_normal(sims) * np.sqrt(sigma2 / n)
57
+ sigma = np.sqrt(sigma2)
58
+ shocks = rng.standard_normal((horizon, sims))
59
+ log_paths = mu[np.newaxis, :] + shocks * sigma[np.newaxis, :]
60
+ return self._from_log(log_paths)
61
+
62
+
63
+ @register
64
+ class BayesianBootstrap(SimulationModel):
65
+ name = "bayesian_bootstrap"
66
+ label = "Bayesian Bootstrap (Rubin)"
67
+
68
+ def calibrate(self, returns: pd.Series) -> BayesianBootstrap:
69
+ self.returns_ = self._clean(returns)
70
+ if self.returns_.size == 0:
71
+ raise ValueError("Bayesian bootstrap needs at least one return.")
72
+ self._fitted = True
73
+ return self
74
+
75
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
76
+ return {"Resampled observations": f"{self.returns_.size:,}"}
77
+
78
+ def simulate(
79
+ self, horizon: int, sims: int, rng: np.random.Generator
80
+ ) -> np.ndarray:
81
+ self._check_fitted()
82
+ n = self.returns_.size
83
+ out = np.empty((horizon, sims), dtype=float)
84
+ for j in range(sims):
85
+ w = rng.dirichlet(np.ones(n))
86
+ idx = rng.choice(n, size=horizon, p=w)
87
+ out[:, j] = self.returns_[idx]
88
+ return out
@@ -0,0 +1,108 @@
1
+ """
2
+ Moving-block bootstrap model.
3
+
4
+ Resamples contiguous blocks of returns with replacement, preserving short-range
5
+ dependence such as volatility clustering. The default block length uses the
6
+ Politis-White (2004, 2009) automatic optimal block length (via ``arch``), which
7
+ balances bias and variance from the data's dependence structure. A simpler
8
+ volatility-cluster proxy is kept available as a fallback / alternative.
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
+ def politis_white_block_length(returns: np.ndarray) -> int:
21
+ """Politis-White automatic optimal block length (stationary bootstrap).
22
+
23
+ Uses ``arch.bootstrap.optimal_block_length``; falls back to the
24
+ volatility-cluster estimate if it cannot be computed.
25
+ """
26
+ try:
27
+ from arch.bootstrap import optimal_block_length
28
+
29
+ result = optimal_block_length(returns)
30
+ value = float(result["stationary"].iloc[0])
31
+ if np.isfinite(value) and value >= 1:
32
+ return max(1, int(round(value)))
33
+ except Exception:
34
+ pass
35
+ return volatility_cluster_block_length(returns)
36
+
37
+
38
+ def volatility_cluster_block_length(returns: np.ndarray) -> int:
39
+ """Average volatility-cluster length (>=1).
40
+
41
+ A 'cluster' is a maximal run of periods whose squared return is above the
42
+ median squared return. The mean run length is a simple, data-driven proxy
43
+ for the persistence of volatility.
44
+ """
45
+ if returns.size < 4:
46
+ return 1
47
+ sq = returns**2
48
+ above = sq > np.median(sq)
49
+ runs = []
50
+ count = 0
51
+ for flag in above:
52
+ if flag:
53
+ count += 1
54
+ elif count > 0:
55
+ runs.append(count)
56
+ count = 0
57
+ if count > 0:
58
+ runs.append(count)
59
+ if not runs:
60
+ return 1
61
+ return max(1, int(round(float(np.mean(runs)))))
62
+
63
+
64
+ @register
65
+ class BlockBootstrap(SimulationModel):
66
+ name = "block_bootstrap"
67
+ label = "Block Bootstrap"
68
+
69
+ def __init__(
70
+ self, block_length: int | None = None, method: str = "politis_white"
71
+ ) -> None:
72
+ super().__init__()
73
+ self._user_block_length = block_length
74
+ self._method = method
75
+
76
+ def calibrate(self, returns: pd.Series) -> BlockBootstrap:
77
+ self.returns_ = self._clean(returns)
78
+ if self.returns_.size == 0:
79
+ raise ValueError("Block bootstrap model needs at least one return.")
80
+ if self._user_block_length is not None:
81
+ self.block_length_ = self._user_block_length
82
+ elif self._method == "vol_cluster":
83
+ self.block_length_ = volatility_cluster_block_length(self.returns_)
84
+ else:
85
+ self.block_length_ = politis_white_block_length(self.returns_)
86
+ self._fitted = True
87
+ return self
88
+
89
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
90
+ return {
91
+ "Block length": f"{self.block_length_}",
92
+ "Resampled observations": f"{self.returns_.size:,}",
93
+ }
94
+
95
+ def simulate(
96
+ self, horizon: int, sims: int, rng: np.random.Generator
97
+ ) -> np.ndarray:
98
+ self._check_fitted()
99
+ n = self.returns_.size
100
+ b = max(1, min(self.block_length_, n))
101
+ n_blocks = -(-horizon // b) # ceil
102
+ out = np.empty((horizon, sims), dtype=float)
103
+ max_start = n - b
104
+ for j in range(sims):
105
+ starts = rng.integers(0, max_start + 1, size=n_blocks)
106
+ path = np.concatenate([self.returns_[s : s + b] for s in starts])
107
+ out[:, j] = path[:horizon]
108
+ return out
@@ -0,0 +1,38 @@
1
+ """
2
+ IID bootstrap model.
3
+
4
+ Resamples historical simple returns *with replacement*, one draw per period.
5
+ Preserves the empirical marginal distribution (including fat tails and skew)
6
+ but assumes independence across time.
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
+ @register
19
+ class Bootstrap(SimulationModel):
20
+ name = "bootstrap"
21
+ label = "Bootstrap"
22
+
23
+ def calibrate(self, returns: pd.Series) -> Bootstrap:
24
+ self.returns_ = self._clean(returns)
25
+ if self.returns_.size == 0:
26
+ raise ValueError("Bootstrap model needs at least one return.")
27
+ self._fitted = True
28
+ return self
29
+
30
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
31
+ return {"Resampled observations": f"{self.returns_.size:,}"}
32
+
33
+ def simulate(
34
+ self, horizon: int, sims: int, rng: np.random.Generator
35
+ ) -> np.ndarray:
36
+ self._check_fitted()
37
+ idx = rng.integers(0, self.returns_.size, size=(horizon, sims))
38
+ return self.returns_[idx]
@@ -0,0 +1,83 @@
1
+ """
2
+ GARCH(1,1) model with Student-t innovations.
3
+
4
+ Calibrates a constant-mean GARCH(1,1) on log returns using the ``arch`` package
5
+ (maximum likelihood, fat-tailed innovations) and simulates forward paths by
6
+ running the GARCH recursion with standardized-t shocks. Volatility clustering
7
+ and fat tails are captured natively.
8
+
9
+ Drift is anchored to the sample mean of log returns so simulated CAGR aligns
10
+ with history; GARCH MLE ``mu`` can overweight low-volatility (bull) regimes.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import numpy as np
16
+ import pandas as pd
17
+
18
+ # arch is a required dependency of quantstats-pro (see pyproject).
19
+ from arch import arch_model
20
+
21
+ from ..base import SimulationModel
22
+ from ..registry import register
23
+
24
+ # arch fits best when data are scaled to roughly unit magnitude.
25
+ _SCALE = 100.0
26
+
27
+
28
+ @register
29
+ class GARCH(SimulationModel):
30
+ name = "garch"
31
+ label = "GARCH(1,1)-t"
32
+
33
+ def calibrate(self, returns: pd.Series) -> GARCH:
34
+ raw_log = self._to_log(self._clean(returns))
35
+ self.log_mean_ = float(np.mean(raw_log))
36
+ log_r = raw_log * _SCALE
37
+ am = arch_model(log_r, mean="Constant", vol="GARCH", p=1, q=1, dist="t")
38
+ res = am.fit(disp="off")
39
+ p = res.params
40
+ self.mu_mle_ = float(p["mu"])
41
+ # Anchor simulated drift to sample mean (scaled space).
42
+ self.mu_ = self.log_mean_ * _SCALE
43
+ self.omega_ = float(p["omega"])
44
+ self.alpha_ = float(p["alpha[1]"])
45
+ self.beta_ = float(p["beta[1]"])
46
+ self.nu_ = float(p.get("nu", 8.0))
47
+ cv = res.conditional_volatility
48
+ last_vol = float(cv.iloc[-1] if hasattr(cv, "iloc") else cv[-1])
49
+ self.h0_ = last_vol**2
50
+ denom = 1.0 - self.alpha_ - self.beta_
51
+ self.uncond_var_ = self.omega_ / denom if denom > 1e-6 else self.h0_
52
+ self._fitted = True
53
+ return self
54
+
55
+ def _standardized_t(self, rng, shape):
56
+ """Student-t with unit variance (scaled by sqrt((nu-2)/nu))."""
57
+ nu = max(self.nu_, 2.1)
58
+ raw = rng.standard_t(nu, size=shape)
59
+ return raw * np.sqrt((nu - 2.0) / nu)
60
+
61
+ def simulate(
62
+ self, horizon: int, sims: int, rng: np.random.Generator
63
+ ) -> np.ndarray:
64
+ self._check_fitted()
65
+ z = self._standardized_t(rng, (horizon, sims))
66
+ log_paths = np.empty((horizon, sims), dtype=float)
67
+ h = np.full(sims, max(self.h0_, 1e-12), dtype=float)
68
+ for t in range(horizon):
69
+ eps = z[t] * np.sqrt(h)
70
+ log_paths[t] = (self.mu_ + eps) / _SCALE
71
+ h = self.omega_ + self.alpha_ * eps**2 + self.beta_ * h
72
+ return self._from_log(log_paths)
73
+
74
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
75
+ ann_mu = self.log_mean_ * periods
76
+ ann_vol = float(np.sqrt(self.uncond_var_ / _SCALE**2) * np.sqrt(periods))
77
+ return {
78
+ "Drift (ann.)": f"{ann_mu:.2%}",
79
+ "Volatility (ann.)": f"{ann_vol:.2%}",
80
+ "Student-t nu": f"{self.nu_:.1f}",
81
+ "GARCH alpha": f"{self.alpha_:.3f}",
82
+ "GARCH beta": f"{self.beta_:.3f}",
83
+ }
@@ -0,0 +1,44 @@
1
+ """
2
+ Geometric Brownian Motion model.
3
+
4
+ Calibrates the drift and volatility of log returns by maximum likelihood
5
+ (sample mean and standard deviation) and simulates i.i.d. Gaussian log returns,
6
+ converting them back to simple returns. This preserves the historical drift
7
+ (see the Monte Carlo challenge notes on drift handling).
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+
15
+ from ..base import SimulationModel
16
+ from ..registry import register
17
+
18
+
19
+ @register
20
+ class GBM(SimulationModel):
21
+ name = "gbm"
22
+ label = "GBM"
23
+
24
+ def calibrate(self, returns: pd.Series) -> GBM:
25
+ log_r = self._to_log(self._clean(returns))
26
+ self.mu_ = float(np.mean(log_r))
27
+ self.sigma_ = float(np.std(log_r, ddof=1))
28
+ self._fitted = True
29
+ return self
30
+
31
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
32
+ ann_mu = self.mu_ * periods
33
+ ann_sigma = self.sigma_ * np.sqrt(periods)
34
+ return {
35
+ "Drift (ann.)": f"{ann_mu:.2%}",
36
+ "Volatility (ann.)": f"{ann_sigma:.2%}",
37
+ }
38
+
39
+ def simulate(
40
+ self, horizon: int, sims: int, rng: np.random.Generator
41
+ ) -> np.ndarray:
42
+ self._check_fitted()
43
+ log_paths = rng.normal(self.mu_, self.sigma_, size=(horizon, sims))
44
+ return self._from_log(log_paths)
@@ -0,0 +1,103 @@
1
+ """
2
+ Heston stochastic-volatility model (first-cut, returns-only calibration).
3
+
4
+ Heston is usually calibrated to option surfaces; from a return series alone its
5
+ five parameters (kappa, theta, xi, rho, v0) are only weakly identified. This
6
+ implementation uses a pragmatic method-of-moments calibration on the realised
7
+ variance proxy (squared log returns) and simulates with a full-truncation Euler
8
+ scheme. It is intended as a reasonable first approximation -- see the Monte
9
+ Carlo challenge notes for the identifiability caveats.
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 Heston(SimulationModel):
23
+ name = "heston"
24
+ label = "Heston (SV)"
25
+
26
+ def calibrate(self, returns: pd.Series) -> Heston:
27
+ log_r = self._to_log(self._clean(returns))
28
+ n = log_r.size
29
+ if n < 8:
30
+ self.mu_ = float(np.mean(log_r)) if n else 0.0
31
+ self.theta_ = float(np.var(log_r)) if n > 1 else 1e-4
32
+ self.v0_ = self.theta_
33
+ self.kappa_ = 0.05
34
+ self.xi_ = 0.1 * np.sqrt(self.theta_)
35
+ self.rho_ = -0.5
36
+ self._fitted = True
37
+ return self
38
+
39
+ self.mu_ = float(np.mean(log_r))
40
+ self.theta_ = float(np.var(log_r))
41
+ self.v0_ = self.theta_
42
+
43
+ # Variance proxy and its persistence -> kappa.
44
+ v_proxy = (log_r - self.mu_) ** 2
45
+ v_demean = v_proxy - v_proxy.mean()
46
+ denom = float(np.sum(v_demean[:-1] ** 2))
47
+ phi = float(np.sum(v_demean[1:] * v_demean[:-1]) / denom) if denom > 0 else 0.0
48
+ phi = min(max(phi, 1e-3), 0.999)
49
+ self.kappa_ = float(-np.log(phi))
50
+
51
+ # Vol-of-vol from stationary variance of the variance proxy:
52
+ # Var(v) ~ xi^2 * theta / (2 kappa) => xi = sqrt(2 kappa Var(v)/theta).
53
+ var_v = float(np.var(v_proxy))
54
+ if self.theta_ > 0 and self.kappa_ > 0:
55
+ self.xi_ = float(np.sqrt(max(2.0 * self.kappa_ * var_v / self.theta_, 0.0)))
56
+ else:
57
+ self.xi_ = float(0.1 * np.sqrt(self.theta_))
58
+
59
+ # Leverage: correlation between return and variance innovation.
60
+ dv = np.diff(v_proxy)
61
+ r_lead = log_r[:-1]
62
+ if np.std(dv) > 0 and np.std(r_lead) > 0:
63
+ self.rho_ = float(np.clip(np.corrcoef(r_lead, dv)[0, 1], -0.95, 0.95))
64
+ else:
65
+ self.rho_ = -0.5
66
+ self._fitted = True
67
+ return self
68
+
69
+ def calibration_summary(self, periods: float = 252.0) -> dict[str, str]:
70
+ ann_mu = self.mu_ * periods
71
+ ann_vol = float(np.sqrt(self.theta_) * np.sqrt(periods))
72
+ return {
73
+ "Drift (ann.)": f"{ann_mu:.2%}",
74
+ "Volatility (ann.)": f"{ann_vol:.2%}",
75
+ "Mean reversion kappa": f"{self.kappa_:.3f}",
76
+ "Vol-of-vol xi": f"{self.xi_:.4f}",
77
+ "Leverage rho": f"{self.rho_:.2f}",
78
+ }
79
+
80
+ def simulate(
81
+ self, horizon: int, sims: int, rng: np.random.Generator
82
+ ) -> np.ndarray:
83
+ self._check_fitted()
84
+ z1 = rng.standard_normal((horizon, sims))
85
+ z2 = rng.standard_normal((horizon, sims))
86
+ # Correlate the two Brownian shocks.
87
+ w_v = z1
88
+ w_s = self.rho_ * z1 + np.sqrt(1.0 - self.rho_**2) * z2
89
+
90
+ log_paths = np.empty((horizon, sims), dtype=float)
91
+ v = np.full(sims, max(self.v0_, 1e-12), dtype=float)
92
+ for t in range(horizon):
93
+ v_pos = np.maximum(v, 0.0)
94
+ sqrt_v = np.sqrt(v_pos)
95
+ # mu_ is the mean of log returns; do not subtract variance drag again.
96
+ log_paths[t] = self.mu_ + sqrt_v * w_s[t]
97
+ v = (
98
+ v
99
+ + self.kappa_ * (self.theta_ - v_pos)
100
+ + self.xi_ * sqrt_v * w_v[t]
101
+ )
102
+ v = np.maximum(v, 0.0)
103
+ return self._from_log(log_paths)