pyalloq-simulation 0.1.20__tar.gz

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.
@@ -0,0 +1,31 @@
1
+ Metadata-Version: 2.3
2
+ Name: pyalloq-simulation
3
+ Version: 0.1.20
4
+ Summary: Core simulation engine for PyAlloq.
5
+ Author: Siddeshkanth
6
+ Author-email: Siddeshkanth <pyalloq-info@alloq-alpha.com>
7
+ Requires-Dist: numpy>=1.24
8
+ Requires-Dist: pandas>=2.0
9
+ Requires-Dist: scipy>=1.11
10
+ Requires-Dist: scikit-learn>=1.3
11
+ Requires-Dist: pyalloq-core
12
+ Requires-Dist: arch>=5.2.0
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+
16
+ # `pyalloq-simulation`
17
+
18
+ Institutional Monte Carlo scenario generation, missing-history imputation, and Meucci Entropy Pooling for the PyAlloq SDK.
19
+
20
+ ## Capabilities
21
+
22
+ - **Missing Data Imputation (`FactorBackcastImputer`)**: Back-casts missing history for recent IPOs and fills interior gaps in return space via PCA factor regression and idiosyncratic volatility matching.
23
+ - **Scenario Generators (`BaseScenarioGenerator`)**:
24
+ - `GaussianGenerator`: Multivariate Normal baseline with Ledoit-Wolf shrinkage and Cholesky factorization.
25
+ - `PCAFactorGenerator`: Latent PCA factor simulation for high-dimensional universes.
26
+ - `FHSGenerator`: Filtered Historical Simulation (GARCH(1,1) de-volatization + synchronous residual bootstrapping).
27
+ - `GARCHEVTCopulaGenerator`: AR(1)-GARCH(1,1) filtration + Extreme Value Theory (Generalized Pareto Distribution tails) + Student-$t$ Copula.
28
+ - `GMMRegimeGenerator`: $K$-regime Gaussian Mixture Model with empirical Markov transition matrix.
29
+ - **Memory & Batching**: Default `float32` tensor precision and `generate_batches(n_paths, horizon, batch_size)` streaming.
30
+ - **Meucci Entropy Pooling (`ViewBuilder`, `EntropyPooler`)**: First-moment (`AbsoluteView`, `RelativeView`) and second-moment (`VolatilityView`, `CovarianceView`) market views solved via Lagrange dual optimization.
31
+ - **Path-Dependent Risk Evaluation (`ScenarioEvaluator`)**: Posterior probability-weighted Expected Return, Volatility, Sharpe Ratio, 95% CVaR, View-Adjusted Maximum Drawdown (`view_adjusted_mdd`), and Probability of Ruin (`probability_of_ruin`).
@@ -0,0 +1,16 @@
1
+ # `pyalloq-simulation`
2
+
3
+ Institutional Monte Carlo scenario generation, missing-history imputation, and Meucci Entropy Pooling for the PyAlloq SDK.
4
+
5
+ ## Capabilities
6
+
7
+ - **Missing Data Imputation (`FactorBackcastImputer`)**: Back-casts missing history for recent IPOs and fills interior gaps in return space via PCA factor regression and idiosyncratic volatility matching.
8
+ - **Scenario Generators (`BaseScenarioGenerator`)**:
9
+ - `GaussianGenerator`: Multivariate Normal baseline with Ledoit-Wolf shrinkage and Cholesky factorization.
10
+ - `PCAFactorGenerator`: Latent PCA factor simulation for high-dimensional universes.
11
+ - `FHSGenerator`: Filtered Historical Simulation (GARCH(1,1) de-volatization + synchronous residual bootstrapping).
12
+ - `GARCHEVTCopulaGenerator`: AR(1)-GARCH(1,1) filtration + Extreme Value Theory (Generalized Pareto Distribution tails) + Student-$t$ Copula.
13
+ - `GMMRegimeGenerator`: $K$-regime Gaussian Mixture Model with empirical Markov transition matrix.
14
+ - **Memory & Batching**: Default `float32` tensor precision and `generate_batches(n_paths, horizon, batch_size)` streaming.
15
+ - **Meucci Entropy Pooling (`ViewBuilder`, `EntropyPooler`)**: First-moment (`AbsoluteView`, `RelativeView`) and second-moment (`VolatilityView`, `CovarianceView`) market views solved via Lagrange dual optimization.
16
+ - **Path-Dependent Risk Evaluation (`ScenarioEvaluator`)**: Posterior probability-weighted Expected Return, Volatility, Sharpe Ratio, 95% CVaR, View-Adjusted Maximum Drawdown (`view_adjusted_mdd`), and Probability of Ruin (`probability_of_ruin`).
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.10.9,<0.11.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "pyalloq-simulation"
7
+ version = "0.1.20"
8
+ description = "Core simulation engine for PyAlloq."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ dependencies = [
12
+ "numpy>=1.24",
13
+ "pandas>=2.0",
14
+ "scipy>=1.11",
15
+ "scikit-learn>=1.3",
16
+ "pyalloq-core",
17
+ "arch>=5.2.0",
18
+ ]
19
+
20
+ [[project.authors]]
21
+ name = "Siddeshkanth"
22
+ email = "pyalloq-info@alloq-alpha.com"
23
+
24
+ [dependency-groups]
25
+ dev = [
26
+ "pytest>=8",
27
+ "ruff>=0.6",
28
+ "mypy>=1.11",
29
+ ]
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src/"]
@@ -0,0 +1,26 @@
1
+ [build-system]
2
+ requires = ["uv_build>=0.10.9,<0.11.0"]
3
+ build-backend = "uv_build"
4
+
5
+ [project]
6
+ name = "pyalloq-simulation"
7
+ version = "0.1.20"
8
+ description = "Core simulation engine for PyAlloq."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ authors = [{ name = "Siddeshkanth", email = "pyalloq-info@alloq-alpha.com" }]
12
+
13
+ dependencies = [
14
+ "numpy>=1.24",
15
+ "pandas>=2.0",
16
+ "scipy>=1.11",
17
+ "scikit-learn>=1.3",
18
+ "pyalloq-core",
19
+ "arch>=5.2.0",
20
+ ]
21
+
22
+ [dependency-groups]
23
+ dev = ["pytest>=8", "ruff>=0.6", "mypy>=1.11"]
24
+
25
+ [tool.setuptools.packages.find]
26
+ where = ["src/"]
@@ -0,0 +1,38 @@
1
+ from pyalloq_simulation.core.evaluator import EvaluationMetrics, ScenarioEvaluator
2
+ from pyalloq_simulation.generators import (
3
+ FHSGenerator,
4
+ PCAFactorGenerator,
5
+ GaussianGenerator,
6
+ GARCHEVTCopulaGenerator,
7
+ GMMRegimeGenerator,
8
+ )
9
+ from pyalloq_simulation.utils import FactorBackcastImputer
10
+ from pyalloq_simulation.views import (
11
+ EntropyPooler,
12
+ EntropyResult,
13
+ AbsoluteView,
14
+ RelativeView,
15
+ VolatilityView,
16
+ CovarianceView,
17
+ ViewType,
18
+ ViewBuilder,
19
+ )
20
+
21
+ __all__ = [
22
+ "EvaluationMetrics",
23
+ "ScenarioEvaluator",
24
+ "FHSGenerator",
25
+ "PCAFactorGenerator",
26
+ "GaussianGenerator",
27
+ "GARCHEVTCopulaGenerator",
28
+ "GMMRegimeGenerator",
29
+ "FactorBackcastImputer",
30
+ "EntropyPooler",
31
+ "EntropyResult",
32
+ "AbsoluteView",
33
+ "RelativeView",
34
+ "VolatilityView",
35
+ "CovarianceView",
36
+ "ViewType",
37
+ "ViewBuilder",
38
+ ]
@@ -0,0 +1,6 @@
1
+ from pyalloq_simulation.core.evaluator import EvaluationMetrics, ScenarioEvaluator
2
+
3
+ __all__ = [
4
+ "EvaluationMetrics",
5
+ "ScenarioEvaluator",
6
+ ]
@@ -0,0 +1,107 @@
1
+ import numpy as np
2
+ from dataclasses import dataclass
3
+
4
+ from pyalloq_core.data import ScenarioMarketData
5
+ from pyalloq_simulation.views.pooler import EntropyResult
6
+
7
+
8
+ @dataclass
9
+ class EvaluationMetrics:
10
+ expected_return: float
11
+ volatility: float
12
+ sharpe_ratio: float
13
+ cvar_95: float
14
+ view_adjusted_mdd: float = 0.0
15
+ probability_of_ruin: float = 0.0
16
+
17
+
18
+ class ScenarioEvaluator:
19
+ def __init__(
20
+ self, risk_free_rate: float = 0.0, ruin_threshold: float = -0.30
21
+ ) -> None:
22
+ self.rf = risk_free_rate
23
+ # Normalize ruin threshold to a negative drawdown fraction (e.g., -0.30 for a 30% drop)
24
+ self.ruin_threshold = -abs(ruin_threshold)
25
+
26
+ def evaluate(
27
+ self,
28
+ scenario_data: ScenarioMarketData,
29
+ asset_weights: np.ndarray,
30
+ entropy_result: EntropyResult,
31
+ ruin_threshold: float | None = None,
32
+ ) -> EvaluationMetrics:
33
+ """
34
+ Calculates probability-weighted terminal and path-dependent portfolio metrics
35
+ across the simulation horizon T.
36
+ """
37
+ weights = np.asarray(asset_weights, dtype=np.float64)
38
+ probs = np.asarray(entropy_result.weights, dtype=np.float64) # Shape: (M,)
39
+
40
+ cumulative_asset_returns = scenario_data.get_cumulative_returns().astype(
41
+ np.float64
42
+ ) # Shape: (M, N)
43
+ portfolio_returns = np.dot(cumulative_asset_returns, weights)
44
+
45
+ expected_return = float(np.dot(portfolio_returns, probs))
46
+
47
+ variance = float(np.dot(probs, (portfolio_returns - expected_return) ** 2))
48
+ volatility = float(np.sqrt(max(variance, 0.0)))
49
+ sharpe = (expected_return - self.rf) / volatility if volatility > 0 else 0.0
50
+
51
+ sort_idx = np.argsort(portfolio_returns)
52
+ sorted_rets = portfolio_returns[sort_idx]
53
+ sorted_probs = probs[sort_idx]
54
+
55
+ cum_probs = np.cumsum(sorted_probs)
56
+ alpha = 0.05
57
+ tail_idx = np.where(cum_probs <= alpha)[0]
58
+
59
+ if len(tail_idx) == 0:
60
+ # Fallback if the very first scenario carries > 5% probability mass
61
+ cvar_95 = float(sorted_rets[0])
62
+ else:
63
+ # Normalize the tail probabilities so they sum to 1.0
64
+ tail_probs = sorted_probs[tail_idx] / np.sum(sorted_probs[tail_idx])
65
+ cvar_95 = float(np.dot(sorted_rets[tail_idx], tail_probs))
66
+
67
+ # Path-dependent intra-horizon metrics along axis=1 (time steps 0..T)
68
+ M = scenario_data.prices.shape[0]
69
+ if scenario_data.initial_prices is not None:
70
+ init_p = np.asarray(scenario_data.initial_prices, dtype=np.float64)[
71
+ None, None, :
72
+ ]
73
+ rel_prices = scenario_data.prices.astype(np.float64) / init_p
74
+ # Portfolio wealth at each step t=1..T: (M, T)
75
+ step_wealth: np.ndarray = np.tensordot(rel_prices, weights, axes=([2], [0]))
76
+ else:
77
+ step_port_rets = np.tensordot(
78
+ scenario_data.returns.astype(np.float64), weights, axes=([2], [0])
79
+ )
80
+ step_wealth = np.cumprod(1.0 + step_port_rets, axis=1).astype(np.float64)
81
+
82
+ # Prepend t=0 initial portfolio equity = 1.0 -> shape (M, T + 1)
83
+ wealth_curve = np.concatenate(
84
+ [np.ones((M, 1), dtype=np.float64), step_wealth], axis=1
85
+ )
86
+ running_peaks = np.maximum.accumulate(wealth_curve, axis=1)
87
+ drawdowns = (wealth_curve - running_peaks) / np.maximum(running_peaks, 1e-12)
88
+ path_mdds = np.min(drawdowns, axis=1) # Shape: (M,), values <= 0.0
89
+
90
+ view_adjusted_mdd = float(np.dot(probs, path_mdds))
91
+
92
+ eff_threshold = (
93
+ -abs(ruin_threshold) if ruin_threshold is not None else self.ruin_threshold
94
+ )
95
+ # Ruin occurs if intra-horizon drawdown or equity drop breaches threshold
96
+ min_equity_return = np.min(wealth_curve - 1.0, axis=1)
97
+ ruin_mask = (path_mdds <= eff_threshold) | (min_equity_return <= eff_threshold)
98
+ probability_of_ruin = float(np.dot(probs, ruin_mask.astype(np.float64)))
99
+
100
+ return EvaluationMetrics(
101
+ expected_return=expected_return,
102
+ volatility=volatility,
103
+ sharpe_ratio=sharpe,
104
+ cvar_95=cvar_95,
105
+ view_adjusted_mdd=view_adjusted_mdd,
106
+ probability_of_ruin=probability_of_ruin,
107
+ )
@@ -0,0 +1,13 @@
1
+ from pyalloq_simulation.generators.fhs import FHSGenerator
2
+ from pyalloq_simulation.generators.factors import PCAFactorGenerator
3
+ from pyalloq_simulation.generators.gaussian import GaussianGenerator
4
+ from pyalloq_simulation.generators.copulas import GARCHEVTCopulaGenerator
5
+ from pyalloq_simulation.generators.regimes import GMMRegimeGenerator
6
+
7
+ __all__ = [
8
+ "FHSGenerator",
9
+ "PCAFactorGenerator",
10
+ "GaussianGenerator",
11
+ "GARCHEVTCopulaGenerator",
12
+ "GMMRegimeGenerator",
13
+ ]
@@ -0,0 +1,342 @@
1
+ from typing import Any
2
+ import warnings
3
+ import numpy as np
4
+ import pandas as pd
5
+ from arch import arch_model
6
+ from scipy import stats
7
+
8
+ from pyalloq_core.interfaces import BaseScenarioGenerator
9
+ from pyalloq_core.data import MarketData, ScenarioMarketData
10
+ from pyalloq_simulation.utils.imputation import FactorBackcastImputer
11
+
12
+
13
+ class GARCHEVTCopulaGenerator(BaseScenarioGenerator):
14
+ """
15
+ GARCH-EVT-Student-t Copula Monte Carlo Generator.
16
+
17
+ 1. Filters univariate marginals via AR(1)-GARCH(1,1) to extract i.i.d. standardized residuals.
18
+ 2. Models marginal tails with Extreme Value Theory (Peaks-Over-Threshold Generalized Pareto
19
+ Distribution) and the interior with the empirical distribution.
20
+ 3. Binds marginals via a Student-t Copula with correlation matrix R and degrees of freedom nu
21
+ to capture asymmetric tail risk and lower-tail dependence (lambda_L > 0).
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ nu: float = 5.0,
27
+ lower_quantile: float = 0.10,
28
+ upper_quantile: float = 0.90,
29
+ mean_model: str = "AR",
30
+ dtype: Any = np.float32,
31
+ impute_missing: bool = True,
32
+ ) -> None:
33
+ if nu <= 2.0:
34
+ raise ValueError("Student-t degrees of freedom `nu` must be > 2.0.")
35
+ if not (0.01 <= lower_quantile < upper_quantile <= 0.99):
36
+ raise ValueError(
37
+ "Quantile thresholds must satisfy 0.01 <= lower_quantile < upper_quantile <= 0.99."
38
+ )
39
+ self.nu = float(nu)
40
+ self.q_lower = float(lower_quantile)
41
+ self.q_upper = float(upper_quantile)
42
+ self.mean_model = mean_model
43
+ self.dtype = np.dtype(dtype)
44
+ self.impute_missing = impute_missing
45
+
46
+ self.is_fitted = False
47
+ self.log_returns: bool = False
48
+ self.assets: list[str] = []
49
+ self.N: int = 0
50
+ self.garch_params: dict[str, dict[str, float]] = {}
51
+ self.evt_params: dict[str, dict[str, Any]] = {}
52
+ self.copula_chol: np.ndarray | None = None
53
+ self.initial_prices: np.ndarray | None = None
54
+
55
+ def _fit_evt_marginal(self, z: np.ndarray) -> dict[str, Any]:
56
+ z_clean = np.sort(z[~np.isnan(z)])
57
+ u_l = float(np.quantile(z_clean, self.q_lower))
58
+ u_u = float(np.quantile(z_clean, self.q_upper))
59
+
60
+ lower_exceed = u_l - z_clean[z_clean < u_l]
61
+ if len(lower_exceed) >= 5:
62
+ xi_l, _, scale_l = stats.genpareto.fit(lower_exceed, floc=0.0)
63
+ xi_l = float(np.clip(xi_l, -0.4, 0.45))
64
+ scale_l = float(max(scale_l, 1e-4))
65
+ else:
66
+ xi_l, scale_l = 0.1, float(max(np.std(z_clean) * 0.5, 0.1))
67
+
68
+ upper_exceed = z_clean[z_clean > u_u] - u_u
69
+ if len(upper_exceed) >= 5:
70
+ xi_u, _, scale_u = stats.genpareto.fit(upper_exceed, floc=0.0)
71
+ xi_u = float(np.clip(xi_u, -0.4, 0.45))
72
+ scale_u = float(max(scale_u, 1e-4))
73
+ else:
74
+ xi_u, scale_u = 0.1, float(max(np.std(z_clean) * 0.5, 0.1))
75
+
76
+ return {
77
+ "sorted_z": z_clean,
78
+ "u_l": u_l,
79
+ "u_u": u_u,
80
+ "xi_l": xi_l,
81
+ "scale_l": scale_l,
82
+ "xi_u": xi_u,
83
+ "scale_u": scale_u,
84
+ }
85
+
86
+ def _evt_cdf(self, z: np.ndarray, meta: dict[str, Any]) -> np.ndarray:
87
+ u = np.empty_like(z, dtype=np.float64)
88
+ u_l = meta["u_l"]
89
+ u_u = meta["u_u"]
90
+ sorted_z = meta["sorted_z"]
91
+ n = len(sorted_z)
92
+
93
+ mask_l = z < u_l
94
+ mask_u = z > u_u
95
+ mask_mid = ~(mask_l | mask_u)
96
+
97
+ if np.any(mask_l):
98
+ exceed_l = u_l - z[mask_l]
99
+ gpd_cdf_l = stats.genpareto.cdf(
100
+ exceed_l, c=meta["xi_l"], loc=0.0, scale=meta["scale_l"]
101
+ )
102
+ u[mask_l] = self.q_lower * (1.0 - gpd_cdf_l)
103
+
104
+ if np.any(mask_u):
105
+ exceed_u = z[mask_u] - u_u
106
+ gpd_cdf_u = stats.genpareto.cdf(
107
+ exceed_u, c=meta["xi_u"], loc=0.0, scale=meta["scale_u"]
108
+ )
109
+ u[mask_u] = self.q_upper + (1.0 - self.q_upper) * gpd_cdf_u
110
+
111
+ if np.any(mask_mid):
112
+ ranks = np.searchsorted(sorted_z, z[mask_mid], side="right")
113
+ u[mask_mid] = np.clip(ranks / (n + 1.0), self.q_lower, self.q_upper)
114
+
115
+ return np.clip(u, 1e-5, 1.0 - 1e-5)
116
+
117
+ def _evt_ppf(self, u: np.ndarray, meta: dict[str, Any]) -> np.ndarray:
118
+ u_clipped = np.clip(u, 1e-5, 1.0 - 1e-5)
119
+ z_out = np.empty_like(u_clipped, dtype=np.float64)
120
+ u_l = meta["u_l"]
121
+ u_u = meta["u_u"]
122
+ sorted_z = meta["sorted_z"]
123
+
124
+ mask_l = u_clipped < self.q_lower
125
+ mask_u = u_clipped > self.q_upper
126
+ mask_mid = ~(mask_l | mask_u)
127
+
128
+ if np.any(mask_l):
129
+ tail_prob_l = np.clip(
130
+ 1.0 - (u_clipped[mask_l] / self.q_lower), 1e-6, 1.0 - 1e-6
131
+ )
132
+ exceed_l = stats.genpareto.ppf(
133
+ tail_prob_l, c=meta["xi_l"], loc=0.0, scale=meta["scale_l"]
134
+ )
135
+ z_out[mask_l] = u_l - exceed_l
136
+
137
+ if np.any(mask_u):
138
+ tail_prob_u = np.clip(
139
+ (u_clipped[mask_u] - self.q_upper) / (1.0 - self.q_upper),
140
+ 1e-6,
141
+ 1.0 - 1e-6,
142
+ )
143
+ exceed_u = stats.genpareto.ppf(
144
+ tail_prob_u, c=meta["xi_u"], loc=0.0, scale=meta["scale_u"]
145
+ )
146
+ z_out[mask_u] = u_u + exceed_u
147
+
148
+ if np.any(mask_mid):
149
+ interior_z = sorted_z[(sorted_z >= u_l) & (sorted_z <= u_u)]
150
+ if len(interior_z) >= 2:
151
+ rel_q = (u_clipped[mask_mid] - self.q_lower) / (
152
+ self.q_upper - self.q_lower
153
+ )
154
+ z_out[mask_mid] = np.quantile(interior_z, np.clip(rel_q, 0.0, 1.0))
155
+ else:
156
+ z_out[mask_mid] = np.quantile(sorted_z, u_clipped[mask_mid])
157
+
158
+ # Standardize and bound extreme tail draws for multi-step GARCH stability
159
+ return np.clip(z_out, -12.0, 12.0)
160
+
161
+ def fit(self, data: MarketData, log_returns: bool = False) -> None:
162
+ clean_data = (
163
+ FactorBackcastImputer().fit_transform(data) if self.impute_missing else data
164
+ )
165
+ self.assets = list(clean_data.assets)
166
+ self.N = len(self.assets)
167
+ self.log_returns = log_returns
168
+ self._record_index_metadata(clean_data.prices.index)
169
+ self.initial_prices = clean_data.prices.iloc[-1].to_numpy(dtype=self.dtype)
170
+
171
+ returns = clean_data.get_returns(log_returns)
172
+ self._fit_exogenous_features(clean_data, returns)
173
+
174
+ warnings.filterwarnings("ignore", category=FutureWarning)
175
+ scale = 100.0
176
+ std_residuals_df = pd.DataFrame(
177
+ index=returns.index, columns=self.assets, dtype=np.float64
178
+ )
179
+
180
+ use_ar = self.mean_model.upper() == "AR" and len(returns) > 30
181
+ for asset in self.assets:
182
+ series = returns[asset].dropna() * scale
183
+ am = arch_model(
184
+ series,
185
+ mean="AR" if use_ar else "Constant",
186
+ lags=1 if use_ar else 0,
187
+ vol="GARCH",
188
+ p=1,
189
+ q=1,
190
+ dist="t",
191
+ rescale=False,
192
+ )
193
+ res = am.fit(disp="off")
194
+ params = res.params
195
+
196
+ mu_val = float(params.get("Const", params.get("mu", 0.0))) / scale
197
+ ar1_val = float(params.get(f"{asset}[1]", 0.0)) if use_ar else 0.0
198
+ # Fallback lookup if arch named the AR lag differently
199
+ if use_ar and ar1_val == 0.0:
200
+ for k_param in params.index:
201
+ if "[1]" in str(k_param) and k_param not in ("alpha[1]", "beta[1]"):
202
+ ar1_val = float(params[k_param])
203
+ break
204
+
205
+ omega_val = float(params["omega"]) / (scale**2)
206
+ alpha_val = float(params["alpha[1]"])
207
+ beta_val = float(params["beta[1]"])
208
+
209
+ cond_vol = pd.Series(res.conditional_volatility, index=series.index)
210
+ resid_s = pd.Series(res.resid, index=series.index)
211
+ z_series = (resid_s / cond_vol).dropna()
212
+ std_residuals_df.loc[z_series.index, asset] = z_series.to_numpy(
213
+ dtype=np.float64
214
+ )
215
+
216
+ self.garch_params[asset] = {
217
+ "mu": mu_val,
218
+ "ar1": float(np.clip(ar1_val, -0.95, 0.95)),
219
+ "omega": omega_val,
220
+ "alpha": alpha_val,
221
+ "beta": beta_val,
222
+ "last_vol": float(cond_vol.iloc[-1]) / scale,
223
+ "last_ret": float(returns[asset].iloc[-1]),
224
+ }
225
+ self.evt_params[asset] = self._fit_evt_marginal(
226
+ z_series.to_numpy(dtype=np.float64)
227
+ )
228
+
229
+ std_residuals_df.dropna(inplace=True)
230
+ Z_mat = std_residuals_df.to_numpy(dtype=np.float64)
231
+
232
+ # Transform marginals to Uniform via EVT CDF, then to Student-t quantiles
233
+ U_mat = np.zeros_like(Z_mat)
234
+ for j, asset in enumerate(self.assets):
235
+ U_mat[:, j] = self._evt_cdf(Z_mat[:, j], self.evt_params[asset])
236
+
237
+ T_mat = stats.t.ppf(U_mat, df=self.nu)
238
+ corr = np.corrcoef(T_mat, rowvar=False)
239
+ if corr.ndim == 0:
240
+ corr = np.ones((1, 1), dtype=np.float64)
241
+ corr = np.nan_to_num(corr, nan=0.0)
242
+ np.fill_diagonal(corr, 1.0)
243
+
244
+ # Positive-definite repair via eigenvalue flooring if needed
245
+ eigvals, eigvecs = np.linalg.eigh(corr)
246
+ eigvals = np.maximum(eigvals, 1e-4)
247
+ corr_pd = eigvecs @ np.diag(eigvals) @ eigvecs.T
248
+ d_inv = np.diag(1.0 / np.sqrt(np.diag(corr_pd)))
249
+ corr_pd = d_inv @ corr_pd @ d_inv
250
+
251
+ self.copula_chol = np.linalg.cholesky(corr_pd)
252
+ self.is_fitted = True
253
+
254
+ def generate(self, n_paths: int, horizon: int) -> ScenarioMarketData:
255
+ if (
256
+ not self.is_fitted
257
+ or self.copula_chol is None
258
+ or self.initial_prices is None
259
+ ):
260
+ raise ValueError(
261
+ "GARCHEVTCopulaGenerator needs to be fitted. Call .fit() first."
262
+ )
263
+
264
+ # 1. Sample multivariate Student-t Copula across (n_paths, horizon, N)
265
+ Z_norm = np.random.standard_normal(size=(n_paths, horizon, self.N))
266
+ correlated_norm = np.matmul(Z_norm, self.copula_chol.T)
267
+ chi2_draws = np.random.chisquare(df=self.nu, size=(n_paths, horizon, 1))
268
+ t_draws = correlated_norm / np.sqrt(chi2_draws / self.nu)
269
+ U_sim = stats.t.cdf(t_draws, df=self.nu)
270
+
271
+ # 2. Invert through semi-parametric EVT-GPD marginal quantiles
272
+ Z_shocks = np.empty((n_paths, horizon, self.N), dtype=self.dtype)
273
+ for j, asset in enumerate(self.assets):
274
+ Z_shocks[:, :, j] = self._evt_ppf(
275
+ U_sim[:, :, j], self.evt_params[asset]
276
+ ).astype(self.dtype)
277
+
278
+ # 3. Step AR(1)-GARCH(1,1) dynamics forward
279
+ mu = np.array(
280
+ [self.garch_params[a]["mu"] for a in self.assets], dtype=self.dtype
281
+ )
282
+ ar1 = np.array(
283
+ [self.garch_params[a]["ar1"] for a in self.assets], dtype=self.dtype
284
+ )
285
+ omega = np.array(
286
+ [self.garch_params[a]["omega"] for a in self.assets], dtype=self.dtype
287
+ )
288
+ alpha = np.array(
289
+ [self.garch_params[a]["alpha"] for a in self.assets], dtype=self.dtype
290
+ )
291
+ beta = np.array(
292
+ [self.garch_params[a]["beta"] for a in self.assets], dtype=self.dtype
293
+ )
294
+
295
+ current_vol = np.tile(
296
+ np.array(
297
+ [self.garch_params[a]["last_vol"] for a in self.assets],
298
+ dtype=self.dtype,
299
+ ),
300
+ (n_paths, 1),
301
+ )
302
+ prev_ret = np.tile(
303
+ np.array(
304
+ [self.garch_params[a]["last_ret"] for a in self.assets],
305
+ dtype=self.dtype,
306
+ ),
307
+ (n_paths, 1),
308
+ )
309
+
310
+ synthetic_returns = np.zeros((n_paths, horizon, self.N), dtype=self.dtype)
311
+ for t in range(horizon):
312
+ z_t = Z_shocks[:, t, :]
313
+ eps_t = current_vol * z_t
314
+ r_t = mu + ar1 * prev_ret + eps_t
315
+ synthetic_returns[:, t, :] = r_t
316
+ prev_ret = r_t
317
+ next_var = omega + alpha * (eps_t**2) + beta * (current_vol**2)
318
+ current_vol = np.sqrt(np.maximum(next_var, 1e-12)).astype(
319
+ self.dtype, copy=False
320
+ )
321
+
322
+ if self.log_returns:
323
+ synthetic_prices = self.initial_prices * np.exp(
324
+ np.cumsum(synthetic_returns, axis=1)
325
+ )
326
+ else:
327
+ synthetic_prices = self.initial_prices * np.cumprod(
328
+ 1.0 + synthetic_returns, axis=1
329
+ )
330
+
331
+ synthetic_prices = synthetic_prices.astype(self.dtype, copy=False)
332
+ sim_features, feat_cols = self._simulate_exogenous_features(synthetic_returns)
333
+
334
+ return ScenarioMarketData(
335
+ prices=synthetic_prices,
336
+ returns=synthetic_returns,
337
+ asset_names=self.assets,
338
+ initial_prices=self.initial_prices.copy(),
339
+ timestamps=self._build_future_timestamps(horizon),
340
+ features=sim_features,
341
+ feature_columns=feat_cols,
342
+ )