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
16 changes: 16 additions & 0 deletions src/quant_platform_kit/risk/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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",
]
287 changes: 287 additions & 0 deletions src/quant_platform_kit/risk/benchmark_dca_and_regime.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,287 @@
"""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
from datetime import date
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_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 = 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 _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,
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 = _validate_chronological_sessions(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,
)
Loading
Loading