pyalloq-simulation 0.1.20__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.
- pyalloq_simulation/__init__.py +38 -0
- pyalloq_simulation/core/__init__.py +6 -0
- pyalloq_simulation/core/evaluator.py +107 -0
- pyalloq_simulation/generators/__init__.py +13 -0
- pyalloq_simulation/generators/copulas.py +342 -0
- pyalloq_simulation/generators/factors.py +108 -0
- pyalloq_simulation/generators/fhs.py +165 -0
- pyalloq_simulation/generators/gaussian.py +106 -0
- pyalloq_simulation/generators/regimes.py +147 -0
- pyalloq_simulation/utils/__init__.py +3 -0
- pyalloq_simulation/utils/imputation.py +147 -0
- pyalloq_simulation/views/__init__.py +20 -0
- pyalloq_simulation/views/builder.py +179 -0
- pyalloq_simulation/views/pooler.py +121 -0
- pyalloq_simulation-0.1.20.dist-info/METADATA +31 -0
- pyalloq_simulation-0.1.20.dist-info/RECORD +17 -0
- pyalloq_simulation-0.1.20.dist-info/WHEEL +4 -0
|
@@ -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,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
|
+
)
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
from typing import Any
|
|
2
|
+
import numpy as np
|
|
3
|
+
from sklearn.decomposition import PCA
|
|
4
|
+
|
|
5
|
+
from pyalloq_core.interfaces import BaseScenarioGenerator
|
|
6
|
+
from pyalloq_core.data import MarketData, ScenarioMarketData
|
|
7
|
+
from pyalloq_simulation.utils.imputation import FactorBackcastImputer
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class PCAFactorGenerator(BaseScenarioGenerator):
|
|
11
|
+
"""
|
|
12
|
+
Factor-Based Monte Carlo Generator.
|
|
13
|
+
Decomposes historical returns via PCA, simulates K latent factors,
|
|
14
|
+
and reconstitutes N asset returns via static factor loadings.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
n_components: int = 5,
|
|
20
|
+
dtype: Any = np.float32,
|
|
21
|
+
impute_missing: bool = True,
|
|
22
|
+
) -> None:
|
|
23
|
+
self.K = n_components
|
|
24
|
+
self.dtype = np.dtype(dtype)
|
|
25
|
+
self.impute_missing = impute_missing
|
|
26
|
+
|
|
27
|
+
self.is_fitted = False
|
|
28
|
+
self.log_returns: bool = False
|
|
29
|
+
self.factor_means: np.ndarray | None = None
|
|
30
|
+
self.factor_stds: np.ndarray | None = None
|
|
31
|
+
self.loadings: np.ndarray | None = None
|
|
32
|
+
self.asset_means: np.ndarray | None = None
|
|
33
|
+
self.resid_stds: np.ndarray | None = None
|
|
34
|
+
self.initial_prices: np.ndarray | None = None
|
|
35
|
+
|
|
36
|
+
def fit(self, data: MarketData, log_returns: bool = False) -> None:
|
|
37
|
+
clean_data = (
|
|
38
|
+
FactorBackcastImputer().fit_transform(data) if self.impute_missing else data
|
|
39
|
+
)
|
|
40
|
+
self.assets = list(clean_data.assets)
|
|
41
|
+
self.N = len(self.assets)
|
|
42
|
+
self.log_returns = log_returns
|
|
43
|
+
self._record_index_metadata(clean_data.prices.index)
|
|
44
|
+
self.initial_prices = clean_data.prices.iloc[-1].to_numpy(dtype=self.dtype)
|
|
45
|
+
returns = clean_data.get_returns(log_returns)
|
|
46
|
+
self._fit_exogenous_features(clean_data, returns)
|
|
47
|
+
|
|
48
|
+
k_eff = min(self.K, self.N, len(returns))
|
|
49
|
+
self.k_eff = k_eff
|
|
50
|
+
self.pca = PCA(n_components=k_eff)
|
|
51
|
+
|
|
52
|
+
ret_np = returns.to_numpy(dtype=np.float64)
|
|
53
|
+
F_hist = self.pca.fit_transform(ret_np)
|
|
54
|
+
self.loadings = self.pca.components_.astype(self.dtype)
|
|
55
|
+
self.asset_means = self.pca.mean_.astype(self.dtype)
|
|
56
|
+
|
|
57
|
+
R_reconstructed = self.pca.inverse_transform(F_hist)
|
|
58
|
+
E_hist = ret_np - R_reconstructed
|
|
59
|
+
|
|
60
|
+
self.factor_means = np.mean(F_hist, axis=0).astype(self.dtype)
|
|
61
|
+
self.factor_stds = np.std(F_hist, axis=0).astype(self.dtype)
|
|
62
|
+
self.resid_stds = np.std(E_hist, axis=0).astype(self.dtype)
|
|
63
|
+
|
|
64
|
+
self.is_fitted = True
|
|
65
|
+
|
|
66
|
+
def generate(self, n_paths: int, horizon: int) -> ScenarioMarketData:
|
|
67
|
+
if (
|
|
68
|
+
not self.is_fitted
|
|
69
|
+
or self.factor_means is None
|
|
70
|
+
or self.factor_stds is None
|
|
71
|
+
or self.loadings is None
|
|
72
|
+
or self.asset_means is None
|
|
73
|
+
or self.resid_stds is None
|
|
74
|
+
or self.initial_prices is None
|
|
75
|
+
):
|
|
76
|
+
raise ValueError("PCAFactorGenerator needs to be fitted. Call .fit() first")
|
|
77
|
+
|
|
78
|
+
Z_factors = np.random.standard_normal(
|
|
79
|
+
size=(n_paths, horizon, self.k_eff)
|
|
80
|
+
).astype(self.dtype)
|
|
81
|
+
F_sim = self.factor_means + Z_factors * self.factor_stds
|
|
82
|
+
|
|
83
|
+
Z_noise = np.random.standard_normal(size=(n_paths, horizon, self.N)).astype(
|
|
84
|
+
self.dtype
|
|
85
|
+
)
|
|
86
|
+
E_sim = Z_noise * self.resid_stds
|
|
87
|
+
|
|
88
|
+
R_sim = (self.asset_means + np.matmul(F_sim, self.loadings) + E_sim).astype(
|
|
89
|
+
self.dtype, copy=False
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
if self.log_returns:
|
|
93
|
+
synthetic_prices = self.initial_prices * np.exp(np.cumsum(R_sim, axis=1))
|
|
94
|
+
else:
|
|
95
|
+
synthetic_prices = self.initial_prices * np.cumprod(1.0 + R_sim, axis=1)
|
|
96
|
+
|
|
97
|
+
synthetic_prices = synthetic_prices.astype(self.dtype, copy=False)
|
|
98
|
+
sim_features, feat_cols = self._simulate_exogenous_features(R_sim)
|
|
99
|
+
|
|
100
|
+
return ScenarioMarketData(
|
|
101
|
+
prices=synthetic_prices,
|
|
102
|
+
returns=R_sim,
|
|
103
|
+
asset_names=self.assets,
|
|
104
|
+
initial_prices=self.initial_prices.copy(),
|
|
105
|
+
timestamps=self._build_future_timestamps(horizon),
|
|
106
|
+
features=sim_features,
|
|
107
|
+
feature_columns=feat_cols,
|
|
108
|
+
)
|