cpz-quant 1.0.0__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.
- cpz_quant/__init__.py +27 -0
- cpz_quant/certification/__init__.py +50 -0
- cpz_quant/certification/analytics.py +294 -0
- cpz_quant/certification/factors.py +99 -0
- cpz_quant/certification/grade.py +341 -0
- cpz_quant/certification/overfitting.py +112 -0
- cpz_quant/certification/regime.py +147 -0
- cpz_quant/frames.py +72 -0
- cpz_quant/indicators/__init__.py +824 -0
- cpz_quant/indicators/_helpers.py +182 -0
- cpz_quant/indicators/_rust_accel.py +106 -0
- cpz_quant/indicators/momentum.py +285 -0
- cpz_quant/indicators/statistical.py +195 -0
- cpz_quant/indicators/trend.py +188 -0
- cpz_quant/indicators/volatility.py +236 -0
- cpz_quant/indicators/volume.py +107 -0
- cpz_quant/portfolio/__init__.py +186 -0
- cpz_quant/portfolio/attribution.py +335 -0
- cpz_quant/portfolio/convex.py +320 -0
- cpz_quant/portfolio/copula.py +245 -0
- cpz_quant/portfolio/costs.py +389 -0
- cpz_quant/portfolio/covariance.py +438 -0
- cpz_quant/portfolio/entropy_pooling.py +148 -0
- cpz_quant/portfolio/factors.py +306 -0
- cpz_quant/portfolio/model_selection.py +176 -0
- cpz_quant/portfolio/optimization.py +1457 -0
- cpz_quant/portfolio/preselection.py +140 -0
- cpz_quant/portfolio/quantum_backends.py +416 -0
- cpz_quant/portfolio/risk_measures.py +279 -0
- cpz_quant/portfolio/sklearn_estimators.py +149 -0
- cpz_quant/py.typed +0 -0
- cpz_quant/viz.py +155 -0
- cpz_quant-1.0.0.dist-info/METADATA +466 -0
- cpz_quant-1.0.0.dist-info/RECORD +37 -0
- cpz_quant-1.0.0.dist-info/WHEEL +5 -0
- cpz_quant-1.0.0.dist-info/licenses/LICENSE +202 -0
- cpz_quant-1.0.0.dist-info/top_level.txt +1 -0
cpz_quant/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"""cpz-quant — open-source quantitative portfolio construction, risk, and
|
|
2
|
+
strategy certification from CPZ Lab.
|
|
3
|
+
|
|
4
|
+
Three subpackages, all pure functions (data in, results out — no I/O):
|
|
5
|
+
|
|
6
|
+
- :mod:`cpz_quant.portfolio` — portfolio optimization (mean-variance, HRP,
|
|
7
|
+
HERC, NCO, Black-Litterman, entropy pooling, CVaR, robust, convex/cvxpy,
|
|
8
|
+
QUBO), covariance estimation, factor models, transaction costs,
|
|
9
|
+
attribution, pre-selection, and walk-forward / combinatorial purged
|
|
10
|
+
cross-validation.
|
|
11
|
+
- :mod:`cpz_quant.certification` — anti-overfitting strategy certification:
|
|
12
|
+
Probability of Backtest Overfitting (CSCV), Deflated Sharpe Ratio,
|
|
13
|
+
regime-conditional performance, and the CPZ Certification grade.
|
|
14
|
+
- :mod:`cpz_quant.indicators` — vectorised technical indicators (momentum,
|
|
15
|
+
trend, volatility, volume, statistical) with optional Rust acceleration.
|
|
16
|
+
|
|
17
|
+
The proprietary `cpz-ai` SDK builds on this package for live execution,
|
|
18
|
+
broker routing, and platform data access; cpz-quant itself is fully
|
|
19
|
+
standalone and Apache-2.0 licensed.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from cpz_quant import certification, indicators, portfolio
|
|
23
|
+
from cpz_quant.frames import as_returns
|
|
24
|
+
|
|
25
|
+
__version__ = "1.0.0"
|
|
26
|
+
|
|
27
|
+
__all__ = ["portfolio", "certification", "indicators", "as_returns", "__version__"]
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"""CPZAI Certification Standard — the SDK-side grading + institutional analytics.
|
|
2
|
+
|
|
3
|
+
Parity with the edge engine (``supabase/functions/_shared``) so the SDK, the
|
|
4
|
+
backtest engine, and the hosted certification all produce the same grade and the
|
|
5
|
+
same due-diligence analytics from an equity curve.
|
|
6
|
+
|
|
7
|
+
- :func:`compute_risk_analytics` — institutional analytics (Sortino, Calmar,
|
|
8
|
+
CVaR, tail ratio, MinTRL, up/down capture, crisis behavior). Rust-accelerated.
|
|
9
|
+
- :func:`certify` — the six-dimension letter grade with minimum gates.
|
|
10
|
+
- :func:`probability_of_backtest_overfitting` — PBO via CSCV.
|
|
11
|
+
- :func:`factor_attribution` — idiosyncratic alpha after neutralizing factors.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
from .analytics import RiskAnalytics, compute_risk_analytics, has_rust
|
|
17
|
+
from .factors import FactorAttribution, factor_attribution
|
|
18
|
+
from .grade import (
|
|
19
|
+
CERTIFICATION_ENGINE_VERSION,
|
|
20
|
+
CertificationResult,
|
|
21
|
+
CertLive,
|
|
22
|
+
CertMetrics,
|
|
23
|
+
CertRigor,
|
|
24
|
+
DimensionScore,
|
|
25
|
+
GateResult,
|
|
26
|
+
certify,
|
|
27
|
+
)
|
|
28
|
+
from .overfitting import PBOResult, probability_of_backtest_overfitting
|
|
29
|
+
from .regime import RegimeBreakdown, RegimeStats, regime_conditional_performance
|
|
30
|
+
|
|
31
|
+
__all__ = [
|
|
32
|
+
"RiskAnalytics",
|
|
33
|
+
"compute_risk_analytics",
|
|
34
|
+
"has_rust",
|
|
35
|
+
"certify",
|
|
36
|
+
"CertificationResult",
|
|
37
|
+
"CertMetrics",
|
|
38
|
+
"CertRigor",
|
|
39
|
+
"CertLive",
|
|
40
|
+
"DimensionScore",
|
|
41
|
+
"GateResult",
|
|
42
|
+
"CERTIFICATION_ENGINE_VERSION",
|
|
43
|
+
"probability_of_backtest_overfitting",
|
|
44
|
+
"PBOResult",
|
|
45
|
+
"factor_attribution",
|
|
46
|
+
"FactorAttribution",
|
|
47
|
+
"regime_conditional_performance",
|
|
48
|
+
"RegimeBreakdown",
|
|
49
|
+
"RegimeStats",
|
|
50
|
+
]
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
"""Institutional risk analytics for the CPZAI Certification Standard.
|
|
2
|
+
|
|
3
|
+
Bit-parity with the edge engine (`supabase/functions/_shared/risk-analytics.ts`)
|
|
4
|
+
and the Rust fast path (`rust/src/analytics.rs`): downside-aware ratios, tail
|
|
5
|
+
risk, drawdown geometry, statistical significance (Lopez de Prado MinTRL), and
|
|
6
|
+
benchmark-conditional behavior — computed deterministically from an equity curve.
|
|
7
|
+
|
|
8
|
+
Uses the compiled Rust extension `cpz_risk_rs.certification_analytics` when
|
|
9
|
+
available and falls back to a pure-NumPy implementation otherwise; both round
|
|
10
|
+
identically so the result is backend-independent.
|
|
11
|
+
|
|
12
|
+
Fail closed: too-short or degenerate series return ``None`` rather than
|
|
13
|
+
fabricated numbers.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from dataclasses import asdict, dataclass
|
|
19
|
+
from typing import Optional, Sequence
|
|
20
|
+
|
|
21
|
+
import numpy as np
|
|
22
|
+
|
|
23
|
+
try: # optional Rust acceleration (built via `cd rust && maturin develop --release`)
|
|
24
|
+
import cpz_risk_rs # type: ignore
|
|
25
|
+
|
|
26
|
+
# An older compiled extension may predate this symbol — verify it, don't
|
|
27
|
+
# assume it (mirrors cpz_quant.indicators._rust_accel).
|
|
28
|
+
_RUST = hasattr(cpz_risk_rs, "certification_analytics")
|
|
29
|
+
except ImportError: # pragma: no cover - depends on build
|
|
30
|
+
_RUST = False
|
|
31
|
+
|
|
32
|
+
TRADING_DAYS = 252.0
|
|
33
|
+
|
|
34
|
+
# Field -> decimal places, matching the TypeScript engine exactly.
|
|
35
|
+
_ROUND = {
|
|
36
|
+
"annualized_return": 4, "annualized_vol": 4, "max_drawdown": 4, "downside_deviation": 4,
|
|
37
|
+
"var95": 4, "cvar95": 4, "cvar99": 4, "crisis_return": 4, "crisis_benchmark_return": 4,
|
|
38
|
+
"worst_month": 4, "best_month": 4,
|
|
39
|
+
"sharpe": 3, "sortino": 3, "calmar": 3, "ulcer_index": 3, "tail_ratio": 3,
|
|
40
|
+
"skew": 3, "excess_kurtosis": 3, "beta": 3, "correlation": 3,
|
|
41
|
+
"up_capture": 3, "down_capture": 3,
|
|
42
|
+
"min_trl_years": 2, "track_years": 2,
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass
|
|
47
|
+
class RiskAnalytics:
|
|
48
|
+
"""Certification analytics block. Percentage-like fields are fractions."""
|
|
49
|
+
|
|
50
|
+
observations: int
|
|
51
|
+
annualized_return: Optional[float]
|
|
52
|
+
annualized_vol: Optional[float]
|
|
53
|
+
sharpe: Optional[float]
|
|
54
|
+
sortino: Optional[float]
|
|
55
|
+
calmar: Optional[float]
|
|
56
|
+
max_drawdown: Optional[float]
|
|
57
|
+
ulcer_index: Optional[float]
|
|
58
|
+
max_time_under_water_days: Optional[int]
|
|
59
|
+
downside_deviation: Optional[float]
|
|
60
|
+
var95: Optional[float]
|
|
61
|
+
cvar95: Optional[float]
|
|
62
|
+
cvar99: Optional[float]
|
|
63
|
+
tail_ratio: Optional[float]
|
|
64
|
+
skew: Optional[float]
|
|
65
|
+
excess_kurtosis: Optional[float]
|
|
66
|
+
min_trl_years: Optional[float]
|
|
67
|
+
track_years: Optional[float]
|
|
68
|
+
significant: Optional[bool]
|
|
69
|
+
beta: Optional[float]
|
|
70
|
+
correlation: Optional[float]
|
|
71
|
+
up_capture: Optional[float]
|
|
72
|
+
down_capture: Optional[float]
|
|
73
|
+
crisis_return: Optional[float]
|
|
74
|
+
crisis_benchmark_return: Optional[float]
|
|
75
|
+
worst_month: Optional[float] = None
|
|
76
|
+
best_month: Optional[float] = None
|
|
77
|
+
|
|
78
|
+
def to_dict(self) -> dict:
|
|
79
|
+
return asdict(self)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def has_rust() -> bool:
|
|
83
|
+
"""True when the Rust acceleration extension is importable."""
|
|
84
|
+
return _RUST
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# ── pure-NumPy core (parity with rust/src/analytics.rs) ──────────────────────
|
|
88
|
+
def _to_returns(eq: np.ndarray) -> np.ndarray:
|
|
89
|
+
prev = eq[:-1]
|
|
90
|
+
cur = eq[1:]
|
|
91
|
+
mask = (prev > 0) & np.isfinite(cur) & np.isfinite(prev)
|
|
92
|
+
return (cur[mask] / prev[mask]) - 1.0
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _percentile(xs: np.ndarray, p: float) -> float:
|
|
96
|
+
# numpy 'linear' == the (n-1)*p interpolation used by the TS/Rust engines.
|
|
97
|
+
return float(np.percentile(xs, p * 100.0, method="linear"))
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _compute_numpy(equity: Sequence[float], benchmark: Optional[Sequence[float]]) -> Optional[dict]:
|
|
101
|
+
eq_in = np.asarray(equity, dtype=float)
|
|
102
|
+
has_bench = benchmark is not None and len(benchmark) == len(eq_in)
|
|
103
|
+
bench_in = np.asarray(benchmark, dtype=float) if has_bench else None
|
|
104
|
+
|
|
105
|
+
keep = np.isfinite(eq_in) & (eq_in > 0)
|
|
106
|
+
eq = eq_in[keep]
|
|
107
|
+
bench = bench_in[keep] if has_bench else None # type: ignore[index]
|
|
108
|
+
if eq.size < 30:
|
|
109
|
+
return None
|
|
110
|
+
rets = _to_returns(eq)
|
|
111
|
+
n = rets.size
|
|
112
|
+
if n < 20:
|
|
113
|
+
return None
|
|
114
|
+
|
|
115
|
+
mu = float(rets.mean())
|
|
116
|
+
sd = float(rets.std(ddof=1))
|
|
117
|
+
ann_return = float((eq[-1] / eq[0]) ** (TRADING_DAYS / n) - 1.0)
|
|
118
|
+
ann_vol = sd * np.sqrt(TRADING_DAYS)
|
|
119
|
+
sharpe = (mu / sd) * np.sqrt(TRADING_DAYS) if sd > 0 else None
|
|
120
|
+
|
|
121
|
+
downs = np.where(rets < 0, rets, 0.0)
|
|
122
|
+
down_dev = float(np.sqrt(np.mean(downs * downs)))
|
|
123
|
+
sortino = (mu / down_dev) * np.sqrt(TRADING_DAYS) if down_dev > 0 else None
|
|
124
|
+
|
|
125
|
+
peak = eq[0]
|
|
126
|
+
max_dd = 0.0
|
|
127
|
+
sum_sq_dd = 0.0
|
|
128
|
+
cur_uw = 0
|
|
129
|
+
max_uw = 0
|
|
130
|
+
for e in eq:
|
|
131
|
+
if e > peak:
|
|
132
|
+
peak = e
|
|
133
|
+
cur_uw = 0
|
|
134
|
+
else:
|
|
135
|
+
cur_uw += 1
|
|
136
|
+
max_uw = max(max_uw, cur_uw)
|
|
137
|
+
dd = (e / peak - 1.0) if peak > 0 else 0.0
|
|
138
|
+
max_dd = min(max_dd, dd)
|
|
139
|
+
sum_sq_dd += (dd * 100.0) ** 2
|
|
140
|
+
ulcer = float(np.sqrt(sum_sq_dd / eq.size))
|
|
141
|
+
calmar = (ann_return / abs(max_dd)) if max_dd < 0 else None
|
|
142
|
+
|
|
143
|
+
var95 = _percentile(rets, 0.05)
|
|
144
|
+
below95 = rets[rets <= var95]
|
|
145
|
+
cvar95 = float(below95.mean()) if below95.size else var95
|
|
146
|
+
var99 = _percentile(rets, 0.01)
|
|
147
|
+
below99 = rets[rets <= var99]
|
|
148
|
+
cvar99 = float(below99.mean()) if below99.size else var99
|
|
149
|
+
p95 = _percentile(rets, 0.95)
|
|
150
|
+
tail_ratio = (abs(p95) / abs(var95)) if var95 != 0 else None
|
|
151
|
+
|
|
152
|
+
m3 = float(np.mean((rets - mu) ** 3))
|
|
153
|
+
m4 = float(np.mean((rets - mu) ** 4))
|
|
154
|
+
skew = (m3 / sd**3) if sd > 0 else None
|
|
155
|
+
kurt = (m4 / sd**4) if sd > 0 else None
|
|
156
|
+
excess_kurtosis = (kurt - 3.0) if kurt is not None else None
|
|
157
|
+
|
|
158
|
+
min_trl_years = None
|
|
159
|
+
srp = (mu / sd) if sd > 0 else None
|
|
160
|
+
if srp is not None and srp > 0 and skew is not None and kurt is not None:
|
|
161
|
+
z = 1.645
|
|
162
|
+
min_obs = 1.0 + (1.0 - skew * srp + ((kurt - 1.0) / 4.0) * srp * srp) * (z / srp) ** 2
|
|
163
|
+
if np.isfinite(min_obs) and min_obs > 0:
|
|
164
|
+
min_trl_years = min_obs / TRADING_DAYS
|
|
165
|
+
track_years = n / TRADING_DAYS
|
|
166
|
+
significant = (track_years >= min_trl_years) if min_trl_years is not None else None
|
|
167
|
+
|
|
168
|
+
beta = correlation = up_capture = down_capture = None
|
|
169
|
+
crisis_return = crisis_benchmark_return = None
|
|
170
|
+
if bench is not None and np.all(np.isfinite(bench)) and np.all(bench > 0):
|
|
171
|
+
b_rets = _to_returns(bench)
|
|
172
|
+
if b_rets.size == n:
|
|
173
|
+
b_mu = float(b_rets.mean())
|
|
174
|
+
b_sd = float(b_rets.std(ddof=1))
|
|
175
|
+
cov = float(np.sum((rets - mu) * (b_rets - b_mu)) / (n - 1))
|
|
176
|
+
beta = (cov / (b_sd * b_sd)) if b_sd > 0 else None
|
|
177
|
+
correlation = (cov / (sd * b_sd)) if sd > 0 and b_sd > 0 else None
|
|
178
|
+
|
|
179
|
+
up = b_rets > 0
|
|
180
|
+
dn = b_rets < 0
|
|
181
|
+
s_up = float(np.prod(1 + rets[up])) if up.any() else 1.0
|
|
182
|
+
b_up = float(np.prod(1 + b_rets[up])) if up.any() else 1.0
|
|
183
|
+
s_dn = float(np.prod(1 + rets[dn])) if dn.any() else 1.0
|
|
184
|
+
b_dn = float(np.prod(1 + b_rets[dn])) if dn.any() else 1.0
|
|
185
|
+
if up.any() and b_up != 1.0:
|
|
186
|
+
up_capture = (s_up - 1.0) / (b_up - 1.0)
|
|
187
|
+
if dn.any() and b_dn != 1.0:
|
|
188
|
+
down_capture = (s_dn - 1.0) / (b_dn - 1.0)
|
|
189
|
+
|
|
190
|
+
b_peak = bench[0]
|
|
191
|
+
b_peak_idx = 0
|
|
192
|
+
worst_dd = 0.0
|
|
193
|
+
t_idx = 0
|
|
194
|
+
p_for_t = 0
|
|
195
|
+
for i, b in enumerate(bench):
|
|
196
|
+
if b > b_peak:
|
|
197
|
+
b_peak = b
|
|
198
|
+
b_peak_idx = i
|
|
199
|
+
dd = b / b_peak - 1.0
|
|
200
|
+
if dd < worst_dd:
|
|
201
|
+
worst_dd = dd
|
|
202
|
+
t_idx = i
|
|
203
|
+
p_for_t = b_peak_idx
|
|
204
|
+
if worst_dd < 0 and t_idx > p_for_t:
|
|
205
|
+
crisis_benchmark_return = float(bench[t_idx] / bench[p_for_t] - 1.0)
|
|
206
|
+
crisis_return = float(eq[t_idx] / eq[p_for_t] - 1.0)
|
|
207
|
+
|
|
208
|
+
return {
|
|
209
|
+
"observations": int(n),
|
|
210
|
+
"annualized_return": ann_return,
|
|
211
|
+
"annualized_vol": ann_vol,
|
|
212
|
+
"sharpe": sharpe,
|
|
213
|
+
"sortino": sortino,
|
|
214
|
+
"calmar": calmar,
|
|
215
|
+
"max_drawdown": max_dd,
|
|
216
|
+
"ulcer_index": ulcer,
|
|
217
|
+
"max_time_under_water_days": int(max_uw),
|
|
218
|
+
"downside_deviation": down_dev * np.sqrt(TRADING_DAYS),
|
|
219
|
+
"var95": var95,
|
|
220
|
+
"cvar95": cvar95,
|
|
221
|
+
"cvar99": cvar99,
|
|
222
|
+
"tail_ratio": tail_ratio,
|
|
223
|
+
"skew": skew,
|
|
224
|
+
"excess_kurtosis": excess_kurtosis,
|
|
225
|
+
"min_trl_years": min_trl_years,
|
|
226
|
+
"track_years": track_years,
|
|
227
|
+
"significant": significant,
|
|
228
|
+
"beta": beta,
|
|
229
|
+
"correlation": correlation,
|
|
230
|
+
"up_capture": up_capture,
|
|
231
|
+
"down_capture": down_capture,
|
|
232
|
+
"crisis_return": crisis_return,
|
|
233
|
+
"crisis_benchmark_return": crisis_benchmark_return,
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def _round(raw: dict) -> dict:
|
|
238
|
+
out = dict(raw)
|
|
239
|
+
for k, dp in _ROUND.items():
|
|
240
|
+
v = out.get(k)
|
|
241
|
+
if v is not None and np.isfinite(v):
|
|
242
|
+
out[k] = round(float(v), dp)
|
|
243
|
+
elif v is not None and not np.isfinite(v):
|
|
244
|
+
out[k] = None
|
|
245
|
+
return out
|
|
246
|
+
|
|
247
|
+
|
|
248
|
+
def _worst_best_month(equity: Sequence[float], dates: Sequence[str]) -> tuple[Optional[float], Optional[float]]:
|
|
249
|
+
if not dates or len(dates) != len(equity):
|
|
250
|
+
return None, None
|
|
251
|
+
buckets: dict[str, list[float]] = {}
|
|
252
|
+
for d, p in zip(dates, equity):
|
|
253
|
+
if not isinstance(d, str):
|
|
254
|
+
return None, None
|
|
255
|
+
buckets.setdefault(d[:7], [None, None]) # type: ignore
|
|
256
|
+
b = buckets[d[:7]]
|
|
257
|
+
if b[0] is None:
|
|
258
|
+
b[0] = p
|
|
259
|
+
b[1] = p
|
|
260
|
+
monthlies = [b[1] / b[0] - 1.0 for b in buckets.values() if b[0]]
|
|
261
|
+
if not monthlies:
|
|
262
|
+
return None, None
|
|
263
|
+
return round(min(monthlies), 4), round(max(monthlies), 4)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def compute_risk_analytics(
|
|
267
|
+
equity: Sequence[float],
|
|
268
|
+
benchmark: Optional[Sequence[float]] = None,
|
|
269
|
+
dates: Optional[Sequence[str]] = None,
|
|
270
|
+
) -> Optional[RiskAnalytics]:
|
|
271
|
+
"""Compute the certification analytics block from a daily equity curve.
|
|
272
|
+
|
|
273
|
+
Args:
|
|
274
|
+
equity: daily portfolio equity values (>= 30 points).
|
|
275
|
+
benchmark: optional aligned benchmark equity series (same length).
|
|
276
|
+
dates: optional aligned ``YYYY-MM-DD`` strings (enables worst/best month).
|
|
277
|
+
|
|
278
|
+
Returns ``None`` when the series is too short to be meaningful.
|
|
279
|
+
"""
|
|
280
|
+
raw: Optional[dict]
|
|
281
|
+
if _RUST:
|
|
282
|
+
raw = cpz_risk_rs.certification_analytics(
|
|
283
|
+
[float(x) for x in equity],
|
|
284
|
+
[float(x) for x in benchmark] if benchmark is not None else None,
|
|
285
|
+
)
|
|
286
|
+
else:
|
|
287
|
+
raw = _compute_numpy(equity, benchmark)
|
|
288
|
+
if raw is None:
|
|
289
|
+
return None
|
|
290
|
+
rounded = _round(raw)
|
|
291
|
+
wm, bm = _worst_best_month(equity, dates) if dates is not None else (None, None)
|
|
292
|
+
rounded["worst_month"] = wm
|
|
293
|
+
rounded["best_month"] = bm
|
|
294
|
+
return RiskAnalytics(**rounded)
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
"""Factor attribution — isolate idiosyncratic alpha from repackaged risk premia.
|
|
2
|
+
|
|
3
|
+
A top quant risk desk never accepts a raw return: they neutralize it against a
|
|
4
|
+
factor model (market, size, value, momentum, quality, low-vol, ...) and ask what
|
|
5
|
+
alpha survives. This runs an OLS of strategy returns on the supplied factor
|
|
6
|
+
returns and reports the annualized alpha, per-factor betas, R^2, and the
|
|
7
|
+
idiosyncratic (residual) Sharpe — the part of the edge that is not explained by
|
|
8
|
+
known factors.
|
|
9
|
+
|
|
10
|
+
Needs a factor-returns dataset, so it lives in the SDK / backtest engine.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from dataclasses import dataclass, field
|
|
16
|
+
from typing import Dict, Mapping, Sequence
|
|
17
|
+
|
|
18
|
+
import numpy as np
|
|
19
|
+
|
|
20
|
+
TRADING_DAYS = 252.0
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
@dataclass
|
|
24
|
+
class FactorAttribution:
|
|
25
|
+
alpha_daily: float
|
|
26
|
+
alpha_annualized: float
|
|
27
|
+
alpha_tstat: float
|
|
28
|
+
betas: Dict[str, float]
|
|
29
|
+
beta_tstats: Dict[str, float]
|
|
30
|
+
r_squared: float
|
|
31
|
+
idiosyncratic_sharpe: float # annualized Sharpe of the residual (unexplained) return
|
|
32
|
+
explained_fraction: float # share of return variance explained by the factors
|
|
33
|
+
observations: int = field(default=0)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def factor_attribution(
|
|
37
|
+
strategy_returns: Sequence[float],
|
|
38
|
+
factor_returns: Mapping[str, Sequence[float]],
|
|
39
|
+
) -> FactorAttribution:
|
|
40
|
+
"""Attribute strategy returns to a set of factor return series via OLS.
|
|
41
|
+
|
|
42
|
+
Args:
|
|
43
|
+
strategy_returns: (T,) per-period strategy returns.
|
|
44
|
+
factor_returns: mapping of factor name -> (T,) per-period factor returns
|
|
45
|
+
(e.g. {"MKT": ..., "SMB": ..., "HML": ..., "MOM": ...}).
|
|
46
|
+
|
|
47
|
+
Returns a :class:`FactorAttribution` with annualized alpha and residual Sharpe.
|
|
48
|
+
"""
|
|
49
|
+
y = np.asarray(strategy_returns, dtype=float)
|
|
50
|
+
T = y.size
|
|
51
|
+
names = list(factor_returns.keys())
|
|
52
|
+
if not names:
|
|
53
|
+
raise ValueError("provide at least one factor series")
|
|
54
|
+
F = np.column_stack([np.asarray(factor_returns[n], dtype=float) for n in names])
|
|
55
|
+
if F.shape[0] != T:
|
|
56
|
+
raise ValueError("all factor series must align with strategy_returns length")
|
|
57
|
+
if T <= len(names) + 1:
|
|
58
|
+
raise ValueError("not enough observations for the number of factors")
|
|
59
|
+
|
|
60
|
+
# Design matrix with intercept.
|
|
61
|
+
X = np.column_stack([np.ones(T), F])
|
|
62
|
+
beta, _resid, _rank, _sv = np.linalg.lstsq(X, y, rcond=None)
|
|
63
|
+
fitted = X @ beta
|
|
64
|
+
residuals = y - fitted
|
|
65
|
+
|
|
66
|
+
# R^2.
|
|
67
|
+
ss_res = float(np.sum(residuals**2))
|
|
68
|
+
ss_tot = float(np.sum((y - y.mean()) ** 2))
|
|
69
|
+
r2 = 1.0 - ss_res / ss_tot if ss_tot > 0 else 0.0
|
|
70
|
+
|
|
71
|
+
# Standard errors -> t-stats (classical OLS).
|
|
72
|
+
dof = T - X.shape[1]
|
|
73
|
+
sigma2 = ss_res / dof if dof > 0 else float("nan")
|
|
74
|
+
try:
|
|
75
|
+
xtx_inv = np.linalg.inv(X.T @ X)
|
|
76
|
+
se = np.sqrt(np.diag(sigma2 * xtx_inv))
|
|
77
|
+
tstats = np.where(se > 0, beta / se, 0.0)
|
|
78
|
+
except np.linalg.LinAlgError:
|
|
79
|
+
tstats = np.zeros_like(beta)
|
|
80
|
+
|
|
81
|
+
alpha_daily = float(beta[0])
|
|
82
|
+
# Appraisal ratio (Treynor-Black): the idiosyncratic return each period is
|
|
83
|
+
# alpha (the intercept) plus mean-zero residual noise, so its risk-adjusted
|
|
84
|
+
# value is alpha / residual-vol, annualized. Using residuals.mean() here is
|
|
85
|
+
# wrong — OLS residuals are mean-zero by construction.
|
|
86
|
+
res_sd = float(residuals.std(ddof=1))
|
|
87
|
+
idio_sharpe = (alpha_daily / res_sd) * np.sqrt(TRADING_DAYS) if res_sd > 0 else 0.0
|
|
88
|
+
|
|
89
|
+
return FactorAttribution(
|
|
90
|
+
alpha_daily=round(alpha_daily, 6),
|
|
91
|
+
alpha_annualized=round(alpha_daily * TRADING_DAYS, 4),
|
|
92
|
+
alpha_tstat=round(float(tstats[0]), 3),
|
|
93
|
+
betas={n: round(float(b), 4) for n, b in zip(names, beta[1:])},
|
|
94
|
+
beta_tstats={n: round(float(t), 3) for n, t in zip(names, tstats[1:])},
|
|
95
|
+
r_squared=round(float(r2), 4),
|
|
96
|
+
idiosyncratic_sharpe=round(float(idio_sharpe), 3),
|
|
97
|
+
explained_fraction=round(float(max(0.0, min(1.0, r2))), 4),
|
|
98
|
+
observations=int(T),
|
|
99
|
+
)
|