From ed03133d6a4d25a60b17f59121fc0a1787c09116 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:15:20 +0800 Subject: [PATCH 1/2] feat: add matched-cashflow DCA benchmark and SMA regime evaluator --- src/quant_platform_kit/risk/__init__.py | 16 ++ .../risk/benchmark_dca_and_regime.py | 262 ++++++++++++++++++ tests/test_benchmark_dca_and_regime.py | 127 +++++++++ 3 files changed, 405 insertions(+) create mode 100644 src/quant_platform_kit/risk/benchmark_dca_and_regime.py create mode 100644 tests/test_benchmark_dca_and_regime.py diff --git a/src/quant_platform_kit/risk/__init__.py b/src/quant_platform_kit/risk/__init__.py index ce2317ce..6d46a383 100644 --- a/src/quant_platform_kit/risk/__init__.py +++ b/src/quant_platform_kit/risk/__init__.py @@ -92,6 +92,15 @@ evaluate_twr_and_capital_ladder, resolve_capital_ladder_tier, ) +from quant_platform_kit.risk.benchmark_dca_and_regime import ( + BenchmarkDcaResult, + DcaCashFlowPoint, + MatchedCashflowDcaReport, + SmaHysteresisRegimeConfig, + SmaHysteresisRegimeDecision, + evaluate_matched_cashflow_dca_benchmark, + evaluate_sma_hysteresis_regime, +) from quant_platform_kit.risk.policy_v0_sizing import ( BETA_SOXL, DEFAULT_SLEEVE_BETA_SHARES, @@ -279,4 +288,11 @@ "TwrCapitalLadderReport", "evaluate_twr_and_capital_ladder", "resolve_capital_ladder_tier", + "BenchmarkDcaResult", + "DcaCashFlowPoint", + "MatchedCashflowDcaReport", + "SmaHysteresisRegimeConfig", + "SmaHysteresisRegimeDecision", + "evaluate_matched_cashflow_dca_benchmark", + "evaluate_sma_hysteresis_regime", ] diff --git a/src/quant_platform_kit/risk/benchmark_dca_and_regime.py b/src/quant_platform_kit/risk/benchmark_dca_and_regime.py new file mode 100644 index 00000000..3c740766 --- /dev/null +++ b/src/quant_platform_kit/risk/benchmark_dca_and_regime.py @@ -0,0 +1,262 @@ +"""Offline matched-cashflow DCA benchmark comparator and causal SMA hysteresis gate. + +Pure research/reporting risk module (zero broker I/O, zero order side effects). +Designed to pair with ``twr_capital_ladder.py`` so every pilot or paper report +explicitly measures realized ending equity against matched-cashflow passive DCA +benchmarks (e.g. ``SPY`` / ``QQQ``), and provides a bounded ``<= 1.0`` L4 +exposure multiplier for slow ``SMA ± band`` regime de-leveraging. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass +import math + + +@dataclass(frozen=True) +class DcaCashFlowPoint: + """Single session external cash flow paired with benchmark close prices.""" + + session_date: str + net_cash_flow_usd: float + benchmark_prices_usd: Mapping[str, float] + + +@dataclass(frozen=True) +class BenchmarkDcaResult: + """Matched-cashflow passive DCA comparison for one benchmark symbol.""" + + symbol: str + total_invested_usd: float + ending_value_usd: float + ending_multiple: float + alpha_vs_benchmark_usd: float + alpha_vs_benchmark_pct: float + + +@dataclass(frozen=True) +class MatchedCashflowDcaReport: + """Portfolio ending equity compared against one or more DCA benchmarks.""" + + actual_ending_equity_usd: float + total_invested_usd: float + cost_bps_oneway: float + benchmarks: dict[str, BenchmarkDcaResult] + beats_all_benchmarks: bool + + +@dataclass(frozen=True) +class SmaHysteresisRegimeConfig: + """Configuration for slow SMA ± hysteresis-band regime scaling (factor <= 1.0).""" + + sma_window: int = 200 + hysteresis_band: float = 0.02 + risk_on_multiplier: float = 1.0 + risk_off_multiplier: float = 0.0 + + def __post_init__(self) -> None: + if isinstance(self.sma_window, bool) or self.sma_window < 2: + raise ValueError("sma_window must be an integer >= 2") + for field_name, val in ( + ("hysteresis_band", self.hysteresis_band), + ("risk_on_multiplier", self.risk_on_multiplier), + ("risk_off_multiplier", self.risk_off_multiplier), + ): + if isinstance(val, bool) or not math.isfinite(float(val)): + raise ValueError(f"{field_name} must be finite") + if not 0.0 <= float(self.hysteresis_band) < 0.50: + raise ValueError("hysteresis_band must lie in [0.0, 0.50)") + if not 0.0 <= float(self.risk_off_multiplier) <= float(self.risk_on_multiplier) <= 1.0: + raise ValueError("regime multipliers must satisfy 0 <= risk_off <= risk_on <= 1.0") + + +@dataclass(frozen=True) +class SmaHysteresisRegimeDecision: + """Causal SMA hysteresis regime evaluation output.""" + + risk_on: bool + exposure_multiplier: float + last_close: float | None + sma_value: float | None + upper_threshold: float | None + lower_threshold: float | None + reason_code: str + + +def _finite_number(value: object, label: str, *, allow_zero: bool = True, allow_negative: bool = False) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{label} must be a finite number") + num = float(value) + if not math.isfinite(num): + raise ValueError(f"{label} must be finite") + if not allow_negative and num < 0.0: + raise ValueError(f"{label} must be non-negative") + if not allow_zero and num <= 0.0: + raise ValueError(f"{label} must be strictly positive") + return num + + +def _simulate_single_benchmark_dca( + *, + symbol: str, + observations: Sequence[DcaCashFlowPoint], + actual_ending_equity_usd: float, + total_invested_usd: float, + cost_rate: float, +) -> BenchmarkDcaResult: + shares = 0.0 + last_price = 0.0 + for obs in observations: + if symbol not in obs.benchmark_prices_usd: + raise ValueError(f"missing benchmark price for {symbol!r} on {obs.session_date!r}") + price = _finite_number( + obs.benchmark_prices_usd[symbol], + f"price[{symbol}]@{obs.session_date}", + allow_zero=False, + ) + flow = _finite_number( + obs.net_cash_flow_usd, + f"net_cash_flow_usd@{obs.session_date}", + allow_negative=True, + ) + if flow > 0.0: + shares += flow / (price * (1.0 + cost_rate)) + elif flow < 0.0: + shares -= (-flow) / (price * (1.0 - cost_rate)) + last_price = price + + ending_value = max(0.0, shares * last_price) + multiple = ending_value / total_invested_usd if total_invested_usd > 0.0 else 0.0 + alpha_usd = actual_ending_equity_usd - ending_value + alpha_pct = (actual_ending_equity_usd / ending_value - 1.0) if ending_value > 0.0 else 0.0 + return BenchmarkDcaResult( + symbol=symbol, + total_invested_usd=total_invested_usd, + ending_value_usd=ending_value, + ending_multiple=multiple, + alpha_vs_benchmark_usd=alpha_usd, + alpha_vs_benchmark_pct=alpha_pct, + ) + + +def evaluate_matched_cashflow_dca_benchmark( + *, + actual_ending_equity_usd: float, + observations: Sequence[DcaCashFlowPoint], + benchmark_symbols: Sequence[str] = ("SPY", "QQQ"), + cost_bps_oneway: float = 15.0, +) -> MatchedCashflowDcaReport: + """Compare realized portfolio equity against matched-cashflow passive DCA benchmarks.""" + if not observations: + raise ValueError("observations must not be empty") + if not benchmark_symbols: + raise ValueError("benchmark_symbols must not be empty") + actual_eq = _finite_number(actual_ending_equity_usd, "actual_ending_equity_usd") + cost_bps = _finite_number(cost_bps_oneway, "cost_bps_oneway") + if cost_bps >= 5_000.0: + raise ValueError("cost_bps_oneway must be < 5000 bps") + cost_rate = cost_bps / 10_000.0 + + total_invested = math.fsum( + _finite_number(obs.net_cash_flow_usd, f"net_cash_flow_usd@{obs.session_date}", allow_negative=True) + for obs in observations + ) + + benchmarks: dict[str, BenchmarkDcaResult] = {} + for raw_sym in benchmark_symbols: + sym = str(raw_sym).strip().upper() + if not sym: + raise ValueError("benchmark_symbols must not contain empty values") + if sym in benchmarks: + continue + benchmarks[sym] = _simulate_single_benchmark_dca( + symbol=sym, + observations=observations, + actual_ending_equity_usd=actual_eq, + total_invested_usd=total_invested, + cost_rate=cost_rate, + ) + + beats_all = all(res.alpha_vs_benchmark_usd > 0.0 for res in benchmarks.values()) + return MatchedCashflowDcaReport( + actual_ending_equity_usd=actual_eq, + total_invested_usd=total_invested, + cost_bps_oneway=cost_bps, + benchmarks=benchmarks, + beats_all_benchmarks=beats_all, + ) + + +def evaluate_sma_hysteresis_regime( + *, + closes: Sequence[float], + prior_risk_on: bool = True, + config: SmaHysteresisRegimeConfig | None = None, +) -> SmaHysteresisRegimeDecision: + """Evaluate causal ``SMA ± hysteresis_band`` regime switch, failing closed on bad/short inputs.""" + cfg = config or SmaHysteresisRegimeConfig() + if not isinstance(prior_risk_on, bool): + raise ValueError("prior_risk_on must be a boolean") + + if len(closes) < cfg.sma_window: + return SmaHysteresisRegimeDecision( + risk_on=False, + exposure_multiplier=float(cfg.risk_off_multiplier), + last_close=None, + sma_value=None, + upper_threshold=None, + lower_threshold=None, + reason_code="INSUFFICIENT_HISTORY_FAIL_CLOSED", + ) + + window_vals: list[float] = [] + for raw_px in closes[-cfg.sma_window :]: + if isinstance(raw_px, bool) or not isinstance(raw_px, (int, float)): + return SmaHysteresisRegimeDecision( + risk_on=False, + exposure_multiplier=float(cfg.risk_off_multiplier), + last_close=None, + sma_value=None, + upper_threshold=None, + lower_threshold=None, + reason_code="INVALID_PRICE_FAIL_CLOSED", + ) + px = float(raw_px) + if not math.isfinite(px) or px <= 0.0: + return SmaHysteresisRegimeDecision( + risk_on=False, + exposure_multiplier=float(cfg.risk_off_multiplier), + last_close=None, + sma_value=None, + upper_threshold=None, + lower_threshold=None, + reason_code="INVALID_PRICE_FAIL_CLOSED", + ) + window_vals.append(px) + + sma_val = math.fsum(window_vals) / float(cfg.sma_window) + last_close = window_vals[-1] + lower = (1.0 - float(cfg.hysteresis_band)) * sma_val + upper = (1.0 + float(cfg.hysteresis_band)) * sma_val + + if last_close < lower: + next_risk_on = False + reason = "BELOW_LOWER_SMA_BAND" + elif last_close > upper: + next_risk_on = True + reason = "ABOVE_UPPER_SMA_BAND" + else: + next_risk_on = prior_risk_on + reason = "INSIDE_HYSTERESIS_HOLD_PRIOR" + + mult = float(cfg.risk_on_multiplier if next_risk_on else cfg.risk_off_multiplier) + return SmaHysteresisRegimeDecision( + risk_on=next_risk_on, + exposure_multiplier=mult, + last_close=last_close, + sma_value=sma_val, + upper_threshold=upper, + lower_threshold=lower, + reason_code=reason, + ) diff --git a/tests/test_benchmark_dca_and_regime.py b/tests/test_benchmark_dca_and_regime.py new file mode 100644 index 00000000..55e95e4f --- /dev/null +++ b/tests/test_benchmark_dca_and_regime.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +import pytest + +from quant_platform_kit.risk import ( + BenchmarkDcaResult, + DcaCashFlowPoint, + MatchedCashflowDcaReport, + SmaHysteresisRegimeConfig, + evaluate_matched_cashflow_dca_benchmark, + evaluate_sma_hysteresis_regime, +) + + +def test_matched_cashflow_dca_computes_exact_alpha_and_cost() -> None: + observations = [ + DcaCashFlowPoint("2026-01-02", 1000.0, {"SPY": 100.0, "QQQ": 200.0}), + DcaCashFlowPoint("2026-02-02", 500.0, {"SPY": 110.0, "QQQ": 250.0}), + DcaCashFlowPoint("2026-03-02", 0.0, {"SPY": 121.0, "QQQ": 250.0}), + ] + report = evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=1900.0, + observations=observations, + benchmark_symbols=("SPY", "QQQ"), + cost_bps_oneway=0.0, + ) + assert isinstance(report, MatchedCashflowDcaReport) + assert report.total_invested_usd == pytest.approx(1500.0) + # SPY shares: 1000/100 + 500/110 = 14.54545... -> *121 = 1760.0 + spy = report.benchmarks["SPY"] + assert isinstance(spy, BenchmarkDcaResult) + assert spy.ending_value_usd == pytest.approx(1760.0) + assert spy.alpha_vs_benchmark_usd == pytest.approx(140.0) + assert spy.alpha_vs_benchmark_pct == pytest.approx(140.0 / 1760.0) + # QQQ shares: 1000/200 + 500/250 = 7.0 -> *250 = 1750.0 + qqq = report.benchmarks["QQQ"] + assert qqq.ending_value_usd == pytest.approx(1750.0) + assert report.beats_all_benchmarks is True + + +def test_matched_cashflow_dca_applies_oneway_cost_and_withdrawals() -> None: + observations = [ + DcaCashFlowPoint("2026-01-02", 1000.0, {"SPY": 100.0}), + DcaCashFlowPoint("2026-02-02", -200.0, {"SPY": 100.0}), + ] + report = evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=790.0, + observations=observations, + benchmark_symbols=("SPY",), + cost_bps_oneway=100.0, # 1% + ) + # Buy 1000 / 101 = 9.90099 shares; sell 200 / 99 = 2.020202 shares -> 7.880788 shares * 100 + assert report.total_invested_usd == pytest.approx(800.0) + assert report.benchmarks["SPY"].ending_value_usd == pytest.approx((1000.0 / 101.0 - 200.0 / 99.0) * 100.0) + assert report.beats_all_benchmarks is True + + +def test_matched_cashflow_dca_fails_closed_on_bad_inputs() -> None: + with pytest.raises(ValueError, match="observations must not be empty"): + evaluate_matched_cashflow_dca_benchmark(actual_ending_equity_usd=1000.0, observations=[]) + + with pytest.raises(ValueError, match="missing benchmark price"): + evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=1000.0, + observations=[DcaCashFlowPoint("2026-01-02", 1000.0, {"SPY": 100.0})], + benchmark_symbols=("SPY", "QQQ"), + ) + + with pytest.raises(ValueError, match="strictly positive"): + evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=1000.0, + observations=[DcaCashFlowPoint("2026-01-02", 1000.0, {"SPY": 0.0})], + benchmark_symbols=("SPY",), + ) + + +def test_sma_hysteresis_regime_state_transitions() -> None: + cfg = SmaHysteresisRegimeConfig( + sma_window=5, + hysteresis_band=0.02, + risk_on_multiplier=1.0, + risk_off_multiplier=0.0, + ) + # 4 values of 100 + last close 99 -> SMA = 99.8, lower = 97.804 -> holds prior state + inside_closes = [100.0, 100.0, 100.0, 100.0, 99.0] + hold_on = evaluate_sma_hysteresis_regime(closes=inside_closes, prior_risk_on=True, config=cfg) + assert hold_on.risk_on is True + assert hold_on.exposure_multiplier == pytest.approx(1.0) + assert hold_on.reason_code == "INSIDE_HYSTERESIS_HOLD_PRIOR" + + hold_off = evaluate_sma_hysteresis_regime(closes=inside_closes, prior_risk_on=False, config=cfg) + assert hold_off.risk_on is False + assert hold_off.exposure_multiplier == pytest.approx(0.0) + assert hold_off.reason_code == "INSIDE_HYSTERESIS_HOLD_PRIOR" + + # Break below -2% band -> switches risk_on to False + bear_closes = [100.0, 100.0, 100.0, 100.0, 95.0] + switched_off = evaluate_sma_hysteresis_regime(closes=bear_closes, prior_risk_on=True, config=cfg) + assert switched_off.risk_on is False + assert switched_off.exposure_multiplier == pytest.approx(0.0) + assert switched_off.reason_code == "BELOW_LOWER_SMA_BAND" + + # Break above +2% band -> restores risk_on to True + bull_closes = [100.0, 100.0, 100.0, 100.0, 105.0] + switched_on = evaluate_sma_hysteresis_regime(closes=bull_closes, prior_risk_on=False, config=cfg) + assert switched_on.risk_on is True + assert switched_on.exposure_multiplier == pytest.approx(1.0) + assert switched_on.reason_code == "ABOVE_UPPER_SMA_BAND" + + +def test_sma_hysteresis_regime_enforces_multiplier_cap_and_fail_closed() -> None: + with pytest.raises(ValueError, match="<= 1.0"): + SmaHysteresisRegimeConfig(risk_on_multiplier=1.25) + + short_dec = evaluate_sma_hysteresis_regime(closes=[100.0, 101.0], prior_risk_on=True) + assert short_dec.risk_on is False + assert short_dec.exposure_multiplier == pytest.approx(0.0) + assert short_dec.reason_code == "INSUFFICIENT_HISTORY_FAIL_CLOSED" + + bad_dec = evaluate_sma_hysteresis_regime( + closes=[100.0, 100.0, float("nan"), 100.0, 100.0], + prior_risk_on=True, + config=SmaHysteresisRegimeConfig(sma_window=5, risk_off_multiplier=0.25), + ) + assert bad_dec.risk_on is False + assert bad_dec.exposure_multiplier == pytest.approx(0.25) + assert bad_dec.reason_code == "INVALID_PRICE_FAIL_CLOSED" From 30b02977f1137682e6a150d58c587e9e9046b54a Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 04:23:10 +0800 Subject: [PATCH 2/2] fix: validate session order and withdrawal cap in DCA evaluator --- .../risk/benchmark_dca_and_regime.py | 37 ++++++++++++++++--- tests/test_benchmark_dca_and_regime.py | 20 ++++++++++ 2 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/quant_platform_kit/risk/benchmark_dca_and_regime.py b/src/quant_platform_kit/risk/benchmark_dca_and_regime.py index 3c740766..ae1bce36 100644 --- a/src/quant_platform_kit/risk/benchmark_dca_and_regime.py +++ b/src/quant_platform_kit/risk/benchmark_dca_and_regime.py @@ -11,6 +11,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass +from datetime import date import math @@ -123,10 +124,15 @@ def _simulate_single_benchmark_dca( if flow > 0.0: shares += flow / (price * (1.0 + cost_rate)) elif flow < 0.0: - shares -= (-flow) / (price * (1.0 - cost_rate)) + shares_to_sell = (-flow) / (price * (1.0 - cost_rate)) + if shares_to_sell > shares + 1e-12: + raise ValueError( + f"withdrawal on {obs.session_date!r} exceeds available {symbol!r} benchmark value" + ) + shares = max(0.0, shares - shares_to_sell) last_price = price - ending_value = max(0.0, shares * last_price) + ending_value = shares * last_price multiple = ending_value / total_invested_usd if total_invested_usd > 0.0 else 0.0 alpha_usd = actual_ending_equity_usd - ending_value alpha_pct = (actual_ending_equity_usd / ending_value - 1.0) if ending_value > 0.0 else 0.0 @@ -140,6 +146,28 @@ def _simulate_single_benchmark_dca( ) +def _validate_chronological_sessions(observations: Sequence[DcaCashFlowPoint]) -> float: + prev_day: date | None = None + total_invested = 0.0 + for obs in observations: + try: + parsed_day = date.fromisoformat(obs.session_date) + except (TypeError, ValueError) as exc: + raise ValueError(f"invalid ISO session_date: {obs.session_date!r}") from exc + if prev_day is not None and parsed_day <= prev_day: + raise ValueError( + f"observations must be strictly increasing by session_date: " + f"{prev_day.isoformat()} >= {parsed_day.isoformat()}" + ) + prev_day = parsed_day + total_invested += _finite_number( + obs.net_cash_flow_usd, + f"net_cash_flow_usd@{obs.session_date}", + allow_negative=True, + ) + return total_invested + + def evaluate_matched_cashflow_dca_benchmark( *, actual_ending_equity_usd: float, @@ -158,10 +186,7 @@ def evaluate_matched_cashflow_dca_benchmark( raise ValueError("cost_bps_oneway must be < 5000 bps") cost_rate = cost_bps / 10_000.0 - total_invested = math.fsum( - _finite_number(obs.net_cash_flow_usd, f"net_cash_flow_usd@{obs.session_date}", allow_negative=True) - for obs in observations - ) + total_invested = _validate_chronological_sessions(observations) benchmarks: dict[str, BenchmarkDcaResult] = {} for raw_sym in benchmark_symbols: diff --git a/tests/test_benchmark_dca_and_regime.py b/tests/test_benchmark_dca_and_regime.py index 55e95e4f..e2c9c59f 100644 --- a/tests/test_benchmark_dca_and_regime.py +++ b/tests/test_benchmark_dca_and_regime.py @@ -73,6 +73,26 @@ def test_matched_cashflow_dca_fails_closed_on_bad_inputs() -> None: benchmark_symbols=("SPY",), ) + with pytest.raises(ValueError, match="strictly increasing by session_date"): + evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=1000.0, + observations=[ + DcaCashFlowPoint("2026-02-02", 0.0, {"SPY": 200.0}), + DcaCashFlowPoint("2026-01-02", 100.0, {"SPY": 100.0}), + ], + benchmark_symbols=("SPY",), + ) + + with pytest.raises(ValueError, match="exceeds available"): + evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=0.0, + observations=[ + DcaCashFlowPoint("2026-01-02", 100.0, {"SPY": 100.0}), + DcaCashFlowPoint("2026-02-02", -200.0, {"SPY": 100.0}), + ], + benchmark_symbols=("SPY",), + ) + def test_sma_hysteresis_regime_state_transitions() -> None: cfg = SmaHysteresisRegimeConfig(