From 1b497d22d44eb70098e1562a3c1e2ec8d0e5cf83 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:01:02 +0800 Subject: [PATCH 1/2] fix(risk): harden DCA comparator and SMA regime guards --- .../risk/benchmark_dca_and_regime.py | 63 ++++++++++++++----- tests/test_benchmark_dca_and_regime.py | 56 ++++++++++++++++- 2 files changed, 103 insertions(+), 16 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 ae1bce36..c8707a89 100644 --- a/src/quant_platform_kit/risk/benchmark_dca_and_regime.py +++ b/src/quant_platform_kit/risk/benchmark_dca_and_regime.py @@ -31,19 +31,24 @@ class BenchmarkDcaResult: symbol: str total_invested_usd: float ending_value_usd: float - ending_multiple: float + ending_multiple: float | None alpha_vs_benchmark_usd: float - alpha_vs_benchmark_pct: float + alpha_vs_benchmark_pct: float | None + comparable: bool @dataclass(frozen=True) class MatchedCashflowDcaReport: """Portfolio ending equity compared against one or more DCA benchmarks.""" + valuation_session_date: str actual_ending_equity_usd: float + total_deposits_usd: float + total_withdrawals_usd: float total_invested_usd: float cost_bps_oneway: float benchmarks: dict[str, BenchmarkDcaResult] + comparable: bool beats_all_benchmarks: bool @@ -57,7 +62,7 @@ class SmaHysteresisRegimeConfig: risk_off_multiplier: float = 0.0 def __post_init__(self) -> None: - if isinstance(self.sma_window, bool) or self.sma_window < 2: + if isinstance(self.sma_window, bool) or not isinstance(self.sma_window, int) or self.sma_window < 2: raise ValueError("sma_window must be an integer >= 2") for field_name, val in ( ("hysteresis_band", self.hysteresis_band), @@ -83,6 +88,7 @@ class SmaHysteresisRegimeDecision: upper_threshold: float | None lower_threshold: float | None reason_code: str + is_valid: bool = True def _finite_number(value: object, label: str, *, allow_zero: bool = True, allow_negative: bool = False) -> float: @@ -103,6 +109,7 @@ def _simulate_single_benchmark_dca( symbol: str, observations: Sequence[DcaCashFlowPoint], actual_ending_equity_usd: float, + total_deposits_usd: float, total_invested_usd: float, cost_rate: float, ) -> BenchmarkDcaResult: @@ -133,9 +140,10 @@ def _simulate_single_benchmark_dca( last_price = price ending_value = shares * last_price - multiple = ending_value / total_invested_usd if total_invested_usd > 0.0 else 0.0 + multiple = ending_value / total_invested_usd if total_invested_usd > 0.0 else None 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 + alpha_pct = (actual_ending_equity_usd / ending_value - 1.0) if ending_value > 0.0 else None + comparable = total_deposits_usd > 0.0 and ending_value > 0.0 return BenchmarkDcaResult( symbol=symbol, total_invested_usd=total_invested_usd, @@ -143,12 +151,14 @@ def _simulate_single_benchmark_dca( ending_multiple=multiple, alpha_vs_benchmark_usd=alpha_usd, alpha_vs_benchmark_pct=alpha_pct, + comparable=comparable, ) -def _validate_chronological_sessions(observations: Sequence[DcaCashFlowPoint]) -> float: +def _validate_chronological_sessions(observations: Sequence[DcaCashFlowPoint]) -> tuple[float, float, float]: prev_day: date | None = None - total_invested = 0.0 + total_deposits = 0.0 + total_withdrawals = 0.0 for obs in observations: try: parsed_day = date.fromisoformat(obs.session_date) @@ -160,12 +170,16 @@ def _validate_chronological_sessions(observations: Sequence[DcaCashFlowPoint]) - f"{prev_day.isoformat()} >= {parsed_day.isoformat()}" ) prev_day = parsed_day - total_invested += _finite_number( + flow = _finite_number( obs.net_cash_flow_usd, f"net_cash_flow_usd@{obs.session_date}", allow_negative=True, ) - return total_invested + if flow > 0.0: + total_deposits += flow + elif flow < 0.0: + total_withdrawals += -flow + return total_deposits, total_withdrawals, total_deposits - total_withdrawals def evaluate_matched_cashflow_dca_benchmark( @@ -174,6 +188,7 @@ def evaluate_matched_cashflow_dca_benchmark( observations: Sequence[DcaCashFlowPoint], benchmark_symbols: Sequence[str] = ("SPY", "QQQ"), cost_bps_oneway: float = 15.0, + valuation_session_date: str | None = None, ) -> MatchedCashflowDcaReport: """Compare realized portfolio equity against matched-cashflow passive DCA benchmarks.""" if not observations: @@ -186,7 +201,18 @@ def evaluate_matched_cashflow_dca_benchmark( raise ValueError("cost_bps_oneway must be < 5000 bps") cost_rate = cost_bps / 10_000.0 - total_invested = _validate_chronological_sessions(observations) + total_deposits, total_withdrawals, total_invested = _validate_chronological_sessions(observations) + terminal_session = observations[-1].session_date + if valuation_session_date is not None: + try: + val_day = date.fromisoformat(valuation_session_date) + except (TypeError, ValueError) as exc: + raise ValueError(f"invalid ISO valuation_session_date: {valuation_session_date!r}") from exc + if val_day != date.fromisoformat(terminal_session): + raise ValueError( + f"valuation_session_date ({valuation_session_date!r}) must match final observation date " + f"({terminal_session!r})" + ) benchmarks: dict[str, BenchmarkDcaResult] = {} for raw_sym in benchmark_symbols: @@ -199,16 +225,22 @@ def evaluate_matched_cashflow_dca_benchmark( symbol=sym, observations=observations, actual_ending_equity_usd=actual_eq, + total_deposits_usd=total_deposits, total_invested_usd=total_invested, cost_rate=cost_rate, ) - beats_all = all(res.alpha_vs_benchmark_usd > 0.0 for res in benchmarks.values()) + comparable = all(res.comparable for res in benchmarks.values()) + beats_all = comparable and all(res.alpha_vs_benchmark_usd > 0.0 for res in benchmarks.values()) return MatchedCashflowDcaReport( + valuation_session_date=terminal_session, actual_ending_equity_usd=actual_eq, + total_deposits_usd=total_deposits, + total_withdrawals_usd=total_withdrawals, total_invested_usd=total_invested, cost_bps_oneway=cost_bps, benchmarks=benchmarks, + comparable=comparable, beats_all_benchmarks=beats_all, ) @@ -227,12 +259,13 @@ def evaluate_sma_hysteresis_regime( if len(closes) < cfg.sma_window: return SmaHysteresisRegimeDecision( risk_on=False, - exposure_multiplier=float(cfg.risk_off_multiplier), + exposure_multiplier=0.0, last_close=None, sma_value=None, upper_threshold=None, lower_threshold=None, reason_code="INSUFFICIENT_HISTORY_FAIL_CLOSED", + is_valid=False, ) window_vals: list[float] = [] @@ -240,23 +273,25 @@ def evaluate_sma_hysteresis_regime( if isinstance(raw_px, bool) or not isinstance(raw_px, (int, float)): return SmaHysteresisRegimeDecision( risk_on=False, - exposure_multiplier=float(cfg.risk_off_multiplier), + exposure_multiplier=0.0, last_close=None, sma_value=None, upper_threshold=None, lower_threshold=None, reason_code="INVALID_PRICE_FAIL_CLOSED", + is_valid=False, ) 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), + exposure_multiplier=0.0, last_close=None, sma_value=None, upper_threshold=None, lower_threshold=None, reason_code="INVALID_PRICE_FAIL_CLOSED", + is_valid=False, ) window_vals.append(px) diff --git a/tests/test_benchmark_dca_and_regime.py b/tests/test_benchmark_dca_and_regime.py index e2c9c59f..9681e3bf 100644 --- a/tests/test_benchmark_dca_and_regime.py +++ b/tests/test_benchmark_dca_and_regime.py @@ -23,15 +23,22 @@ def test_matched_cashflow_dca_computes_exact_alpha_and_cost() -> None: observations=observations, benchmark_symbols=("SPY", "QQQ"), cost_bps_oneway=0.0, + valuation_session_date="2026-03-02", ) assert isinstance(report, MatchedCashflowDcaReport) + assert report.valuation_session_date == "2026-03-02" + assert report.total_deposits_usd == pytest.approx(1500.0) + assert report.total_withdrawals_usd == pytest.approx(0.0) assert report.total_invested_usd == pytest.approx(1500.0) + assert report.comparable is True # 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.ending_multiple == pytest.approx(1760.0 / 1500.0) assert spy.alpha_vs_benchmark_usd == pytest.approx(140.0) assert spy.alpha_vs_benchmark_pct == pytest.approx(140.0 / 1760.0) + assert spy.comparable is True # QQQ shares: 1000/200 + 500/250 = 7.0 -> *250 = 1750.0 qqq = report.benchmarks["QQQ"] assert qqq.ending_value_usd == pytest.approx(1750.0) @@ -50,11 +57,29 @@ def test_matched_cashflow_dca_applies_oneway_cost_and_withdrawals() -> None: 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_deposits_usd == pytest.approx(1000.0) + assert report.total_withdrawals_usd == pytest.approx(200.0) 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.comparable is True assert report.beats_all_benchmarks is True +def test_matched_cashflow_dca_zero_cashflow_is_not_comparable_or_false_win() -> None: + zero_report = evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=100.0, + observations=[DcaCashFlowPoint("2026-01-02", 0.0, {"SPY": 100.0})], + benchmark_symbols=("SPY",), + ) + assert zero_report.comparable is False + assert zero_report.beats_all_benchmarks is False + spy = zero_report.benchmarks["SPY"] + assert spy.ending_value_usd == pytest.approx(0.0) + assert spy.ending_multiple is None + assert spy.alpha_vs_benchmark_pct is None + assert spy.comparable is False + + 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=[]) @@ -93,6 +118,14 @@ def test_matched_cashflow_dca_fails_closed_on_bad_inputs() -> None: benchmark_symbols=("SPY",), ) + with pytest.raises(ValueError, match="must match final observation date"): + evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=100.0, + observations=[DcaCashFlowPoint("2026-01-02", 100.0, {"SPY": 100.0})], + benchmark_symbols=("SPY",), + valuation_session_date="2026-01-05", + ) + def test_sma_hysteresis_regime_state_transitions() -> None: cfg = SmaHysteresisRegimeConfig( @@ -132,8 +165,16 @@ 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) + with pytest.raises(ValueError, match="integer >= 2"): + SmaHysteresisRegimeConfig(sma_window=200.0) # type: ignore[arg-type] + + short_dec = evaluate_sma_hysteresis_regime( + closes=[100.0, 101.0], + prior_risk_on=True, + config=SmaHysteresisRegimeConfig(sma_window=5, risk_off_multiplier=0.25), + ) assert short_dec.risk_on is False + assert short_dec.is_valid is False assert short_dec.exposure_multiplier == pytest.approx(0.0) assert short_dec.reason_code == "INSUFFICIENT_HISTORY_FAIL_CLOSED" @@ -143,5 +184,16 @@ def test_sma_hysteresis_regime_enforces_multiplier_cap_and_fail_closed() -> None 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.is_valid is False + assert bad_dec.exposure_multiplier == pytest.approx(0.0) assert bad_dec.reason_code == "INVALID_PRICE_FAIL_CLOSED" + + valid_bear = evaluate_sma_hysteresis_regime( + closes=[100.0, 100.0, 100.0, 100.0, 95.0], + prior_risk_on=True, + config=SmaHysteresisRegimeConfig(sma_window=5, risk_off_multiplier=0.25), + ) + assert valid_bear.risk_on is False + assert valid_bear.is_valid is True + assert valid_bear.exposure_multiplier == pytest.approx(0.25) + assert valid_bear.reason_code == "BELOW_LOWER_SMA_BAND" From a2488755d0a5c211bd00dca82e163369dbcc9715 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 05:13:42 +0800 Subject: [PATCH 2/2] fix(risk): guard full-withdrawal dust and decimal net cashflow --- .../risk/benchmark_dca_and_regime.py | 24 +++++++++----- tests/test_benchmark_dca_and_regime.py | 33 +++++++++++++++++++ 2 files changed, 48 insertions(+), 9 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 c8707a89..b9316772 100644 --- a/src/quant_platform_kit/risk/benchmark_dca_and_regime.py +++ b/src/quant_platform_kit/risk/benchmark_dca_and_regime.py @@ -12,6 +12,7 @@ from collections.abc import Mapping, Sequence from dataclasses import dataclass from datetime import date +from decimal import Decimal import math @@ -132,14 +133,18 @@ def _simulate_single_benchmark_dca( shares += flow / (price * (1.0 + cost_rate)) elif flow < 0.0: shares_to_sell = (-flow) / (price * (1.0 - cost_rate)) - if shares_to_sell > shares + 1e-12: + tol = 1e-12 * max(1.0, shares) + if shares_to_sell > shares + tol: raise ValueError( f"withdrawal on {obs.session_date!r} exceeds available {symbol!r} benchmark value" ) - shares = max(0.0, shares - shares_to_sell) + remaining = shares - shares_to_sell + shares = 0.0 if remaining <= tol else remaining last_price = price ending_value = shares * last_price + if ending_value <= 1e-12: + ending_value = 0.0 multiple = ending_value / total_invested_usd if total_invested_usd > 0.0 else None alpha_usd = actual_ending_equity_usd - ending_value alpha_pct = (actual_ending_equity_usd / ending_value - 1.0) if ending_value > 0.0 else None @@ -157,8 +162,8 @@ def _simulate_single_benchmark_dca( def _validate_chronological_sessions(observations: Sequence[DcaCashFlowPoint]) -> tuple[float, float, float]: prev_day: date | None = None - total_deposits = 0.0 - total_withdrawals = 0.0 + total_deposits = Decimal("0") + total_withdrawals = Decimal("0") for obs in observations: try: parsed_day = date.fromisoformat(obs.session_date) @@ -175,11 +180,12 @@ def _validate_chronological_sessions(observations: Sequence[DcaCashFlowPoint]) - f"net_cash_flow_usd@{obs.session_date}", allow_negative=True, ) - if flow > 0.0: - total_deposits += flow - elif flow < 0.0: - total_withdrawals += -flow - return total_deposits, total_withdrawals, total_deposits - total_withdrawals + flow_dec = Decimal(str(flow)) + if flow_dec > 0: + total_deposits += flow_dec + elif flow_dec < 0: + total_withdrawals += -flow_dec + return float(total_deposits), float(total_withdrawals), float(total_deposits - total_withdrawals) def evaluate_matched_cashflow_dca_benchmark( diff --git a/tests/test_benchmark_dca_and_regime.py b/tests/test_benchmark_dca_and_regime.py index 9681e3bf..def5f003 100644 --- a/tests/test_benchmark_dca_and_regime.py +++ b/tests/test_benchmark_dca_and_regime.py @@ -79,6 +79,39 @@ def test_matched_cashflow_dca_zero_cashflow_is_not_comparable_or_false_win() -> assert spy.alpha_vs_benchmark_pct is None assert spy.comparable is False + # Full withdrawal with floating-point rounding dust must zero out and not report a false win + full_wd = evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=1.0, + observations=[ + DcaCashFlowPoint("2026-01-02", 103.0, {"SPY": 100.0}), + DcaCashFlowPoint("2026-01-05", 200.0, {"SPY": 100.0}), + DcaCashFlowPoint("2026-01-06", -303.0, {"SPY": 100.0}), + ], + benchmark_symbols=("SPY",), + cost_bps_oneway=0.0, + ) + assert full_wd.comparable is False + assert full_wd.beats_all_benchmarks is False + assert full_wd.benchmarks["SPY"].ending_value_usd == pytest.approx(0.0) + assert full_wd.benchmarks["SPY"].alpha_vs_benchmark_pct is None + + # Zero net invested (0.10 + 0.20 - 0.30) after price doubling: ending_multiple is None, still comparable + zero_net = evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=0.35, + observations=[ + DcaCashFlowPoint("2026-01-02", 0.10, {"SPY": 100.0}), + DcaCashFlowPoint("2026-01-05", 0.20, {"SPY": 100.0}), + DcaCashFlowPoint("2026-01-06", -0.30, {"SPY": 200.0}), + ], + benchmark_symbols=("SPY",), + cost_bps_oneway=0.0, + ) + assert zero_net.total_invested_usd == pytest.approx(0.0) + assert zero_net.comparable is True + assert zero_net.benchmarks["SPY"].ending_multiple is None + assert zero_net.benchmarks["SPY"].ending_value_usd == pytest.approx(0.30) + assert zero_net.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"):