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,712 @@
1
+ """
2
+ Core alpha-decay analysis: rolling metrics, z-scores, traffic lights, CUSUM.
3
+
4
+ Statistical design
5
+ ------------------
6
+ Each rolling metric is compared to its own historical distribution of past
7
+ windows. Raw rolling values are often skewed (volatility is ~lognormal,
8
+ drawdowns/VaR are severity metrics with heavy tails, CAGR is bounded below
9
+ at −100%). A plain z-score on raw values mis-calibrates the ±2σ / ±3σ
10
+ traffic lights because the sample mean and std are pulled by those tails.
11
+
12
+ We therefore map each metric to an *analysis scale* where the distribution is
13
+ approximately normal, compute z-scores and percentiles there, and plot
14
+ histograms on that same scale. Summary lines (Obs / Mean above each chart)
15
+ stay in the original units so the numbers remain interpretable.
16
+
17
+ See ``MetricSpec.transform``, ``TRANSFORM_RATIONALE``, and ``_transform_values``.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from dataclasses import dataclass, field
23
+ from typing import Literal
24
+
25
+ import numpy as np
26
+ import pandas as pd
27
+
28
+ TrafficLight = Literal["excellent", "good", "warning", "critical"]
29
+
30
+ _STATUS_LABELS = {
31
+ "excellent": "Excellent",
32
+ "good": "Good",
33
+ "warning": "Warning",
34
+ "critical": "Critical",
35
+ }
36
+
37
+
38
+ def _stats():
39
+ from quantstats import stats
40
+
41
+ return stats
42
+
43
+
44
+ Transform = Literal["none", "log1p", "log", "log_neg"]
45
+
46
+ # Per-transform rationale (referenced from MetricSpec and plotting axis labels).
47
+ TRANSFORM_RATIONALE: dict[Transform, str] = {
48
+ "none": (
49
+ "No transform — the quantity is already roughly symmetric on the "
50
+ "rolling window, or too discrete for a continuous map (win rate over "
51
+ "7–30 days)."
52
+ ),
53
+ "log1p": (
54
+ "log(1 + x) — CAGR is a growth rate bounded below at −100%. This is "
55
+ "the continuously-compounded rate; if daily log-returns are "
56
+ "~normal, log(1+CAGR) is ~normal and z-scores are well calibrated."
57
+ ),
58
+ "log": (
59
+ "log(x) — strictly positive, right-skewed quantities (realized vol, "
60
+ "downside vol, payoff ratio). Realized volatility is empirically "
61
+ "~lognormal (Andersen, Bollerslev, Diebold & Ebens, 2001); the log "
62
+ "map turns multiplicative shocks into additive ones."
63
+ ),
64
+ "log_neg": (
65
+ "log(−x) — negative severity metrics (drawdowns, VaR, Expected "
66
+ "Shortfall). Values are ≤ 0 with heavier left tails; mapping to "
67
+ "log-severity (positive, higher = worse) stabilises variance and fixes "
68
+ "the traffic-light direction (more severe → higher z)."
69
+ ),
70
+ }
71
+
72
+ # Per-metric notes (why this transform for this key).
73
+ METRIC_TRANSFORM_NOTES: dict[str, str] = {
74
+ "cagr": "Growth rate with −100% floor → log(1+CAGR).",
75
+ "volatility": "Annualised std of returns; positive and right-skewed → log(vol).",
76
+ "downside_vol": "Same family as volatility (dispersion of losses) → log.",
77
+ "max_drawdown": "Peak-to-trough loss (≤ 0); severity is multiplicative → log(−DD).",
78
+ "mean_drawdown": "Average underwater depth (≤ 0) → log(−mean DD).",
79
+ "win_rate": "Share of winning days in the window; kept raw (discrete, bounded).",
80
+ "var_95": "Left-tail loss quantile (≤ 0) → log-severity.",
81
+ "cvar_95": "Mean loss beyond VaR (≤ 0) → log-severity.",
82
+ "payoff_ratio": "Ratio of two positive means; ratios are log-symmetric → log.",
83
+ "skew": "Third moment; already centred and unbounded → raw.",
84
+ }
85
+
86
+
87
+ @dataclass(frozen=True)
88
+ class MetricSpec:
89
+ """
90
+ Metric definition for alpha-decay monitoring.
91
+
92
+ ``transform`` selects the analysis-scale map (see ``TRANSFORM_RATIONALE``).
93
+ ``higher_is_better`` is evaluated on that *transformed* scale.
94
+ """
95
+
96
+ key: str
97
+ label: str
98
+ higher_is_better: bool
99
+ is_pct: bool
100
+ decimals: int = 2
101
+ transform: Transform = "none"
102
+
103
+
104
+ METRIC_SPECS: tuple[MetricSpec, ...] = (
105
+ MetricSpec("cagr", "CAGR", True, True, 2, "log1p"),
106
+ MetricSpec("volatility", "Volatility", False, True, 2, "log"),
107
+ MetricSpec("downside_vol", "Downside Vol", False, True, 2, "log"),
108
+ MetricSpec("max_drawdown", "Max Drawdown", False, True, 2, "log_neg"),
109
+ MetricSpec("mean_drawdown", "Mean Drawdown", False, True, 2, "log_neg"),
110
+ MetricSpec("win_rate", "Win Rate", True, True, 1, "none"),
111
+ MetricSpec("var_95", "VaR 95%", False, True, 2, "log_neg"),
112
+ MetricSpec("cvar_95", "Expected Shortfall 95%", False, True, 2, "log_neg"),
113
+ MetricSpec("payoff_ratio", "Payoff Ratio", True, False, 2, "log"),
114
+ MetricSpec("skew", "Skew", True, False, 2, "none"),
115
+ )
116
+
117
+
118
+ def _transform_values(values: np.ndarray, transform: Transform) -> np.ndarray:
119
+ """
120
+ Map raw rolling metric values to the analysis (approximately normal) scale.
121
+
122
+ Used for z-scores, percentiles, traffic lights, and histograms.
123
+
124
+ Zero-handling (log / log_neg only)
125
+ ----------------------------------
126
+ Some windows produce exact zeros (no losing days → downside vol = 0;
127
+ monotonic-up window → max drawdown = 0). Zeros are floored to the
128
+ smallest *positive* observation in the sample so they remain the best
129
+ (lowest-severity) values without −inf or distorted moments.
130
+ """
131
+ if transform == "none":
132
+ return values
133
+ if transform == "log1p":
134
+ return np.log1p(np.maximum(values, -1.0 + 1e-12))
135
+ x = values if transform == "log" else -values
136
+ positive = x[x > 0]
137
+ floor = float(positive.min()) if len(positive) else 1e-12
138
+ return np.log(np.clip(x, floor, None))
139
+
140
+
141
+ def transform_axis_label(spec: MetricSpec) -> str:
142
+ """X-axis label for distribution charts (analysis scale)."""
143
+ labels = {
144
+ "none": spec.label,
145
+ "log1p": f"log(1 + {spec.label})",
146
+ "log": f"log({spec.label})",
147
+ "log_neg": f"log(−{spec.label}) [severity]",
148
+ }
149
+ return labels[spec.transform]
150
+
151
+
152
+ def transform_chart_subtitle(spec: MetricSpec) -> str:
153
+ """One-line transform note shown under chart titles (empty if none)."""
154
+ if spec.transform == "none":
155
+ return ""
156
+ return METRIC_TRANSFORM_NOTES.get(spec.key, TRANSFORM_RATIONALE[spec.transform])
157
+
158
+
159
+ def available_metrics() -> list[str]:
160
+ return [spec.key for spec in METRIC_SPECS]
161
+
162
+
163
+ def _downside_volatility(window: pd.Series, periods: float) -> float:
164
+ arr = window.to_numpy(dtype=float)
165
+ if len(arr) == 0:
166
+ return np.nan
167
+ downside = arr[arr < 0]
168
+ if len(downside) == 0:
169
+ return 0.0
170
+ dd = np.sqrt((downside**2).sum() / len(arr))
171
+ return float(dd * np.sqrt(periods))
172
+
173
+
174
+ def _compute_metric(
175
+ window: pd.Series,
176
+ key: str,
177
+ rf: float,
178
+ periods: float,
179
+ ) -> float:
180
+ """
181
+ Reference (non-vectorised) implementation of one metric on one window.
182
+
183
+ Kept as ground truth for the vectorised fast path in
184
+ ``_rolling_metrics_matrix`` — the parity test in tests/test_alphadecay.py
185
+ asserts both produce identical values.
186
+ """
187
+ stats = _stats()
188
+ w = window.dropna()
189
+ if len(w) < 2:
190
+ return np.nan
191
+
192
+ if key == "cagr":
193
+ return float(stats.cagr(w, rf=rf, periods=periods))
194
+ if key == "volatility":
195
+ return float(stats.volatility(w, periods=periods, prepare_returns=False))
196
+ if key == "downside_vol":
197
+ return _downside_volatility(w, periods)
198
+ if key == "max_drawdown":
199
+ return float(stats.to_drawdown_series(w).min())
200
+ if key == "mean_drawdown":
201
+ return float(stats.to_drawdown_series(w).mean())
202
+ if key == "win_rate":
203
+ return float(stats.win_rate(w, prepare_returns=False))
204
+ if key == "var_95":
205
+ return float(stats.value_at_risk(w, confidence=0.95, prepare_returns=False))
206
+ if key == "cvar_95":
207
+ return float(stats.cvar(w, confidence=0.95, prepare_returns=False))
208
+ if key == "payoff_ratio":
209
+ return float(stats.payoff_ratio(w, prepare_returns=False))
210
+ if key == "skew":
211
+ return float(stats.skew(w, prepare_returns=False))
212
+ raise KeyError(f"Unknown metric key: {key}")
213
+
214
+
215
+ def _classify_underwater_status(z: float, is_underwater: bool) -> TrafficLight:
216
+ """
217
+ Traffic light for an *ongoing* underwater spell vs completed historical spells.
218
+
219
+ Z is on log(duration). Thresholds match the metric traffic lights
220
+ (lower-is-better convention): being longer than the log-mean spell is
221
+ normal — spell lengths are right-skewed, so under a ~lognormal model
222
+ z ≤ 2 covers ~98% of typical spells. Only clearly abnormal durations
223
+ escalate: z > 2 → warning, z > 3 → critical.
224
+ """
225
+ if not is_underwater:
226
+ return "excellent"
227
+ if np.isnan(z):
228
+ return "good"
229
+ if z < 0:
230
+ return "excellent"
231
+ if z <= 2:
232
+ return "good"
233
+ if z <= 3:
234
+ return "warning"
235
+ return "critical"
236
+
237
+
238
+ def _classify_status(z: float, higher_is_better: bool) -> TrafficLight:
239
+ if np.isnan(z):
240
+ return "good"
241
+ if higher_is_better:
242
+ if z > 0:
243
+ return "excellent"
244
+ if z >= -2:
245
+ return "good"
246
+ if z >= -3:
247
+ return "warning"
248
+ return "critical"
249
+ if z < 0:
250
+ return "excellent"
251
+ if z <= 2:
252
+ return "good"
253
+ if z <= 3:
254
+ return "warning"
255
+ return "critical"
256
+
257
+
258
+ def _format_metric_value(spec: MetricSpec, value: float) -> str:
259
+ if value is None or np.isnan(value):
260
+ return "—"
261
+ if spec.is_pct:
262
+ return f"{value * 100:.{spec.decimals}f}%"
263
+ return f"{value:.{spec.decimals}f}"
264
+
265
+
266
+ @dataclass
267
+ class WindowResult:
268
+ window: int
269
+ distribution: np.ndarray # raw rolling values (for Obs/Mean labels)
270
+ mean: float
271
+ std: float
272
+ observed: float
273
+ analysis_distribution: np.ndarray # transformed — used for z-score & charts
274
+ analysis_mean: float
275
+ analysis_observed: float
276
+ z_score: float
277
+ status: TrafficLight
278
+ percentile: float
279
+
280
+
281
+ @dataclass
282
+ class MetricResult:
283
+ spec: MetricSpec
284
+ windows: dict[int, WindowResult] = field(default_factory=dict)
285
+
286
+
287
+ @dataclass
288
+ class CusumResult:
289
+ series: pd.Series
290
+ threshold: float
291
+ current: float
292
+ alarm: bool
293
+ pct_of_threshold: float
294
+ target_mean: float
295
+ sigma: float
296
+
297
+
298
+ @dataclass
299
+ class TimeUnderwaterResult:
300
+ current_days: int
301
+ distribution: np.ndarray # raw spell lengths in days
302
+ mean: float
303
+ std: float
304
+ analysis_distribution: np.ndarray # log(duration) — z-score & chart scale
305
+ analysis_mean: float
306
+ analysis_current: float
307
+ z_score: float
308
+ status: TrafficLight
309
+ percentile: float
310
+ is_underwater: bool
311
+
312
+
313
+ @dataclass
314
+ class DecayResult:
315
+ returns: pd.Series
316
+ windows: tuple[int, ...]
317
+ metrics: list[MetricResult]
318
+ score: int
319
+ total: int
320
+ cusum: CusumResult
321
+ time_underwater: TimeUnderwaterResult
322
+ asset_label: str = "Asset"
323
+
324
+ @property
325
+ def score_pct(self) -> float:
326
+ return 100.0 * self.score / self.total if self.total else 0.0
327
+
328
+
329
+ def _rolling_metrics_matrix(
330
+ returns: pd.Series,
331
+ window: int,
332
+ periods: float,
333
+ ) -> dict[str, np.ndarray]:
334
+ """
335
+ Compute every metric for all rolling windows of one size in a single
336
+ vectorised pass.
337
+
338
+ ``sliding_window_view`` builds an (n−w+1, w) view of the return array (no
339
+ copy), and each metric is evaluated column-wise with numpy. This replaces
340
+ ``rolling().apply(python_callback)``, which invoked the full quantstats
341
+ metric stack ~n times per metric per window (~12k Python calls per
342
+ ``analyze()``) and dominated runtime.
343
+
344
+ Formulas replicate quantstats.stats exactly (see ``_compute_metric``, the
345
+ reference implementation, and the parity test):
346
+
347
+ - cagr: compounded total return annualised by w/periods. Note that
348
+ ``stats.cagr`` ignores ``rf`` internally (it is in the
349
+ ``unnecessary_function_calls`` list of ``_prepare_returns``), so the
350
+ vectorised version takes no rf either.
351
+ - volatility: sample std (ddof=1) × √periods.
352
+ - downside_vol: √(Σ min(r,0)² / w) × √periods (full-window denominator).
353
+ - max/mean drawdown: equity = cumprod(1+r) with a baseline of 1.0
354
+ (matching ``to_drawdown_series``'s phantom start), running max, min/mean.
355
+ - var_95: Gaussian VaR — norm.ppf(0.05, μ, σ) with sample moments.
356
+ - cvar_95: mean of returns strictly below VaR; falls back to VaR when no
357
+ return is below it (this also removes the "Mean of empty slice"
358
+ RuntimeWarning the old path emitted thousands of times).
359
+ - win_rate: wins / non-zero returns (0.0 when no non-zero returns).
360
+ - payoff_ratio: mean(wins) / |mean(losses)|; NaN when there are no losses.
361
+ - skew: pandas' adjusted Fisher–Pearson estimator
362
+ g1 · √(w(w−1))/(w−2).
363
+ """
364
+ from scipy.stats import norm as _norm
365
+
366
+ arr = returns.to_numpy(dtype=float)
367
+ w = window
368
+ mat = np.lib.stride_tricks.sliding_window_view(arr, w)
369
+ m = mat.shape[0]
370
+ out: dict[str, np.ndarray] = {}
371
+
372
+ if m == 0 or w < 2:
373
+ empty = np.full(max(m, 0), np.nan)
374
+ return {spec.key: empty.copy() for spec in METRIC_SPECS}
375
+
376
+ sqrt_periods = np.sqrt(periods)
377
+ mu = mat.mean(axis=1)
378
+ std = mat.std(axis=1, ddof=1)
379
+
380
+ total = np.prod(1.0 + mat, axis=1) - 1.0
381
+ years = w / periods
382
+ out["cagr"] = np.abs(total + 1.0) ** (1.0 / years) - 1.0
383
+
384
+ out["volatility"] = std * sqrt_periods
385
+
386
+ downside = np.where(mat < 0, mat, 0.0)
387
+ out["downside_vol"] = np.sqrt((downside**2).sum(axis=1) / w) * sqrt_periods
388
+
389
+ equity = np.cumprod(1.0 + mat, axis=1)
390
+ running_max = np.maximum(np.maximum.accumulate(equity, axis=1), 1.0)
391
+ dd = equity / running_max - 1.0
392
+ out["max_drawdown"] = dd.min(axis=1)
393
+ out["mean_drawdown"] = dd.mean(axis=1)
394
+
395
+ nonzero = (mat != 0).sum(axis=1)
396
+ wins = (mat > 0).sum(axis=1)
397
+ out["win_rate"] = np.where(nonzero > 0, wins / np.maximum(nonzero, 1), 0.0)
398
+
399
+ var = _norm.ppf(0.05, mu, std)
400
+ below = mat < var[:, None]
401
+ below_cnt = below.sum(axis=1)
402
+ below_sum = np.where(below, mat, 0.0).sum(axis=1)
403
+ out["var_95"] = var
404
+ out["cvar_95"] = np.where(
405
+ below_cnt > 0, below_sum / np.maximum(below_cnt, 1), var
406
+ )
407
+
408
+ pos_cnt = wins
409
+ neg_cnt = (mat < 0).sum(axis=1)
410
+ pos_sum = np.where(mat > 0, mat, 0.0).sum(axis=1)
411
+ neg_sum = np.where(mat < 0, mat, 0.0).sum(axis=1)
412
+ with np.errstate(invalid="ignore", divide="ignore"):
413
+ avg_win = np.where(pos_cnt > 0, pos_sum / np.maximum(pos_cnt, 1), np.nan)
414
+ avg_loss = np.where(neg_cnt > 0, neg_sum / np.maximum(neg_cnt, 1), np.nan)
415
+ out["payoff_ratio"] = avg_win / np.abs(avg_loss)
416
+
417
+ dev = mat - mu[:, None]
418
+ m2 = (dev**2).mean(axis=1)
419
+ m3 = (dev**3).mean(axis=1)
420
+ with np.errstate(invalid="ignore", divide="ignore"):
421
+ g1 = m3 / m2**1.5
422
+ out["skew"] = g1 * np.sqrt(w * (w - 1.0)) / (w - 2.0)
423
+
424
+ return out
425
+
426
+
427
+ def _rolling_metric_series(
428
+ returns: pd.Series,
429
+ window: int,
430
+ key: str,
431
+ rf: float,
432
+ periods: float,
433
+ ) -> pd.Series:
434
+ """Single-metric rolling series via the reference implementation (slow path).
435
+
436
+ Retained for API compatibility and the vectorisation parity test;
437
+ ``analyze()`` uses ``_rolling_metrics_matrix`` instead.
438
+ """
439
+
440
+ def _apply(window_series: pd.Series) -> float:
441
+ return _compute_metric(window_series, key, rf, periods)
442
+
443
+ return returns.rolling(window).apply(_apply, raw=False)
444
+
445
+
446
+ def _window_result(
447
+ values: np.ndarray | pd.Series,
448
+ window: int,
449
+ spec: MetricSpec,
450
+ ) -> WindowResult:
451
+ if isinstance(values, pd.Series):
452
+ values = values.to_numpy(dtype=float)
453
+ clean = values[~np.isnan(values)]
454
+ if len(clean) == 0:
455
+ return WindowResult(
456
+ window=window,
457
+ distribution=np.array([]),
458
+ mean=np.nan,
459
+ std=np.nan,
460
+ observed=np.nan,
461
+ analysis_distribution=np.array([]),
462
+ analysis_mean=np.nan,
463
+ analysis_observed=np.nan,
464
+ z_score=np.nan,
465
+ status="good",
466
+ percentile=np.nan,
467
+ )
468
+
469
+ observed = float(clean[-1])
470
+ dist = clean
471
+ mean = float(np.mean(dist))
472
+ std = float(np.std(dist, ddof=1)) if len(dist) > 1 else 0.0
473
+
474
+ tdist = _transform_values(dist, spec.transform)
475
+ tobs = float(tdist[-1])
476
+ tmean = float(np.mean(tdist))
477
+ tstd = float(np.std(tdist, ddof=1)) if len(tdist) > 1 else 0.0
478
+ z = (tobs - tmean) / tstd if tstd > 0 else 0.0
479
+ status = _classify_status(z, spec.higher_is_better)
480
+ pct = float((tdist <= tobs).mean() * 100.0)
481
+ if not spec.higher_is_better:
482
+ pct = 100.0 - pct
483
+ return WindowResult(
484
+ window=window,
485
+ distribution=dist,
486
+ mean=mean,
487
+ std=std,
488
+ observed=observed,
489
+ analysis_distribution=tdist,
490
+ analysis_mean=tmean,
491
+ analysis_observed=tobs,
492
+ z_score=z,
493
+ status=status,
494
+ percentile=pct,
495
+ )
496
+
497
+
498
+ def _compute_cusum(
499
+ returns: pd.Series,
500
+ k: float = 0.5,
501
+ h: float = 4.0,
502
+ ) -> CusumResult:
503
+ """
504
+ One-sided CUSUM for detecting sustained *negative* shifts in daily returns.
505
+
506
+ For each trading day t (x-axis index 0 … N−1):
507
+
508
+ μ = mean(all daily returns)
509
+ σ = std(all daily returns, ddof=1)
510
+ k_abs = k · σ # slack — ignore small daily shortfalls
511
+ threshold = h · σ # alarm line on the chart
512
+
513
+ S_t = max(0, S_{t−1} + (μ − r_t) − k_abs)
514
+
515
+ Interpretation
516
+ --------------
517
+ - ``μ − r_t`` is how much today's return fell *below* the historical average.
518
+ - ``S_t`` accumulates those shortfalls; it resets to 0 whenever performance
519
+ is on target (the inner term would drive it negative).
520
+ - When ``S_t ≥ threshold`` → alarm (possible alpha decay / regime shift).
521
+
522
+ The chart x-axis is the trading-day index in the return series (same order
523
+ as the sample period), not calendar time.
524
+ """
525
+ arr = returns.to_numpy(dtype=float)
526
+ mu = float(np.mean(arr))
527
+ sigma = float(np.std(arr, ddof=1))
528
+ if sigma == 0:
529
+ sigma = 1e-12
530
+ k_abs = k * sigma
531
+ threshold = h * sigma
532
+
533
+ values = []
534
+ s = 0.0
535
+ for x in arr:
536
+ s = max(0.0, s + (mu - x) - k_abs)
537
+ values.append(s)
538
+
539
+ series = pd.Series(values, index=returns.index, name="cusum")
540
+ current = float(values[-1]) if values else 0.0
541
+ pct = current / threshold if threshold > 0 else 0.0
542
+ return CusumResult(
543
+ series=series,
544
+ threshold=threshold,
545
+ current=current,
546
+ alarm=current >= threshold,
547
+ pct_of_threshold=pct,
548
+ target_mean=mu,
549
+ sigma=sigma,
550
+ )
551
+
552
+
553
+ def _underwater_durations(drawdown: pd.Series) -> list[int]:
554
+ """Length (days) of every underwater spell, including an ongoing spell at the end."""
555
+ durations: list[int] = []
556
+ current = 0
557
+ for val in drawdown.to_numpy(dtype=float):
558
+ if val < 0:
559
+ current += 1
560
+ elif current > 0:
561
+ durations.append(current)
562
+ current = 0
563
+ if current > 0:
564
+ durations.append(current)
565
+ return durations
566
+
567
+
568
+ def _completed_underwater_durations(
569
+ drawdown: pd.Series,
570
+ ) -> tuple[list[int], int, bool]:
571
+ """
572
+ Split drawdown spells into completed history vs the ongoing spell.
573
+
574
+ The ongoing spell must be excluded from the reference distribution —
575
+ otherwise a 102-day streak contaminates its own benchmark and the z-score
576
+ is artificially muted.
577
+ """
578
+ all_spells = _underwater_durations(drawdown)
579
+ current, is_uw = _current_underwater_days(drawdown)
580
+ if is_uw and all_spells and all_spells[-1] == current:
581
+ return all_spells[:-1], current, is_uw
582
+ return all_spells, current, is_uw
583
+
584
+
585
+ def _current_underwater_days(drawdown: pd.Series) -> tuple[int, bool]:
586
+ if len(drawdown) == 0:
587
+ return 0, False
588
+ arr = drawdown.to_numpy(dtype=float)
589
+ if arr[-1] >= 0:
590
+ return 0, False
591
+ days = 0
592
+ for val in arr[::-1]:
593
+ if val < 0:
594
+ days += 1
595
+ else:
596
+ break
597
+ return days, True
598
+
599
+
600
+ def _compute_time_underwater(returns: pd.Series) -> TimeUnderwaterResult:
601
+ stats = _stats()
602
+ dd = stats.to_drawdown_series(returns)
603
+ completed, current, is_uw = _completed_underwater_durations(dd)
604
+
605
+ if not completed:
606
+ return TimeUnderwaterResult(
607
+ current_days=current,
608
+ distribution=np.array([]),
609
+ mean=0.0,
610
+ std=0.0,
611
+ analysis_distribution=np.array([]),
612
+ analysis_mean=0.0,
613
+ analysis_current=float(np.log(max(current, 1))),
614
+ z_score=np.nan,
615
+ status=_classify_underwater_status(np.nan, is_uw),
616
+ percentile=50.0,
617
+ is_underwater=is_uw,
618
+ )
619
+
620
+ dist = np.array(completed, dtype=float)
621
+ mean = float(np.mean(dist))
622
+ std = float(np.std(dist, ddof=1)) if len(dist) > 1 else 0.0
623
+ ldist = np.log(dist)
624
+ lmean = float(np.mean(ldist))
625
+ lcurrent = float(np.log(max(current, 1)))
626
+ lstd = float(np.std(ldist, ddof=1)) if len(ldist) > 1 else 0.0
627
+ z = (lcurrent - lmean) / lstd if is_uw and lstd > 0 else (0.0 if not is_uw else np.nan)
628
+ status = _classify_underwater_status(z, is_uw)
629
+ if is_uw:
630
+ pct = float((dist <= current).mean() * 100.0)
631
+ pct = 100.0 - pct
632
+ else:
633
+ pct = 50.0
634
+ return TimeUnderwaterResult(
635
+ current_days=current,
636
+ distribution=dist,
637
+ mean=mean,
638
+ std=std,
639
+ analysis_distribution=ldist,
640
+ analysis_mean=lmean,
641
+ analysis_current=lcurrent,
642
+ z_score=z,
643
+ status=status,
644
+ percentile=pct,
645
+ is_underwater=is_uw,
646
+ )
647
+
648
+
649
+ def analyze(
650
+ returns: pd.Series,
651
+ windows: tuple[int, ...] = (7, 15, 30),
652
+ rf: float = 0.0,
653
+ periods: float = 252.0,
654
+ cusum_k: float = 0.5,
655
+ cusum_h: float = 4.0,
656
+ asset_label: str | None = None,
657
+ ) -> DecayResult:
658
+ """
659
+ Run alpha-decay analysis on a return series.
660
+
661
+ Computes rolling risk metrics for each window size, compares the latest
662
+ observation against the historical distribution (z-score / traffic light),
663
+ and adds CUSUM + time-underwater diagnostics.
664
+ """
665
+ if isinstance(returns, pd.DataFrame):
666
+ returns = returns.iloc[:, 0]
667
+ returns = returns.dropna()
668
+ if len(returns) < max(windows) + 5:
669
+ raise ValueError(
670
+ f"Need at least {max(windows) + 5} return observations, got {len(returns)}"
671
+ )
672
+
673
+ label = asset_label or (returns.name if returns.name else "Asset")
674
+ metrics: list[MetricResult] = []
675
+ score = 0
676
+ total = 0
677
+
678
+ # One vectorised pass per window size covers all metrics (rf is unused by
679
+ # the metric formulas — see _rolling_metrics_matrix).
680
+ per_window = {w: _rolling_metrics_matrix(returns, w, periods) for w in windows}
681
+
682
+ for spec in METRIC_SPECS:
683
+ mr = MetricResult(spec=spec)
684
+ for window in windows:
685
+ wr = _window_result(per_window[window][spec.key], window, spec)
686
+ mr.windows[window] = wr
687
+ total += 1
688
+ if wr.status in ("excellent", "good"):
689
+ score += 1
690
+ metrics.append(mr)
691
+
692
+ cusum = _compute_cusum(returns, k=cusum_k, h=cusum_h)
693
+ tuw = _compute_time_underwater(returns)
694
+
695
+ return DecayResult(
696
+ returns=returns,
697
+ windows=windows,
698
+ metrics=metrics,
699
+ score=score,
700
+ total=total,
701
+ cusum=cusum,
702
+ time_underwater=tuw,
703
+ asset_label=str(label),
704
+ )
705
+
706
+
707
+ def status_label(status: TrafficLight) -> str:
708
+ return _STATUS_LABELS[status]
709
+
710
+
711
+ def format_value(spec: MetricSpec, value: float) -> str:
712
+ return _format_metric_value(spec, value)