Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 57 additions & 16 deletions src/quant_platform_kit/risk/benchmark_dca_and_regime.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from collections.abc import Mapping, Sequence
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
import math


Expand All @@ -31,19 +32,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


Expand All @@ -57,7 +63,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),
Expand All @@ -83,6 +89,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:
Expand All @@ -103,6 +110,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:
Expand All @@ -125,30 +133,37 @@ 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
multiple = ending_value / total_invested_usd if total_invested_usd > 0.0 else 0.0
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 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,
ending_value_usd=ending_value,
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 = Decimal("0")
total_withdrawals = Decimal("0")
for obs in observations:
try:
parsed_day = date.fromisoformat(obs.session_date)
Expand All @@ -160,12 +175,17 @@ 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
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(
Expand All @@ -174,6 +194,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:
Expand All @@ -186,7 +207,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:
Expand All @@ -199,16 +231,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,
)

Expand All @@ -227,36 +265,39 @@ 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] = []
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),
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)

Expand Down
89 changes: 87 additions & 2 deletions tests/test_benchmark_dca_and_regime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -50,11 +57,62 @@ 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

# 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"):
evaluate_matched_cashflow_dca_benchmark(actual_ending_equity_usd=1000.0, observations=[])
Expand Down Expand Up @@ -93,6 +151,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(
Expand Down Expand Up @@ -132,8 +198,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"

Expand All @@ -143,5 +217,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"
Loading