From fe71dcfa219f015d32d191867321241bfc6c2ef3 Mon Sep 17 00:00:00 2001 From: Pigbibi <20649888+Pigbibi@users.noreply.github.com> Date: Sun, 29 Nov 2026 08:17:46 +0800 Subject: [PATCH] feat(risk): add Bayesian monitor, shadow ledger, and decision cards --- src/quant_platform_kit/risk/__init__.py | 68 +++ .../risk/bayesian_confidence_monitor.py | 463 ++++++++++++++++++ .../risk/multi_tier_shadow_ledger.py | 430 ++++++++++++++++ .../risk/sentinel_decision_cards.py | 441 +++++++++++++++++ tests/test_bayesian_confidence_monitor.py | 132 +++++ tests/test_multi_tier_shadow_ledger.py | 146 ++++++ tests/test_sentinel_decision_cards.py | 146 ++++++ 7 files changed, 1826 insertions(+) create mode 100644 src/quant_platform_kit/risk/bayesian_confidence_monitor.py create mode 100644 src/quant_platform_kit/risk/multi_tier_shadow_ledger.py create mode 100644 src/quant_platform_kit/risk/sentinel_decision_cards.py create mode 100644 tests/test_bayesian_confidence_monitor.py create mode 100644 tests/test_multi_tier_shadow_ledger.py create mode 100644 tests/test_sentinel_decision_cards.py diff --git a/src/quant_platform_kit/risk/__init__.py b/src/quant_platform_kit/risk/__init__.py index ed0bcd00..edb45bf7 100644 --- a/src/quant_platform_kit/risk/__init__.py +++ b/src/quant_platform_kit/risk/__init__.py @@ -114,6 +114,43 @@ evaluate_bucket_allocation, modeled_ibkr_tiered_fee, ) +from quant_platform_kit.risk.bayesian_confidence_monitor import ( + ACTION_HOLD_CONFIG, + ACTION_PAUSE_CONTRIBUTIONS, + ACTION_REVIEW_REDUCE_WEIGHT, + ACTION_SUSPEND_BUCKET, + OBSERVATION_SOURCES, + STATUS_GREEN, + STATUS_RED, + STATUS_YELLOW, + BayesianConfidenceReport, + BayesianMonitorConfig, + QuarterlyBucketObservation, + SourcePosteriorReport, + evaluate_bucket_bayesian_confidence, + evaluate_source_posterior, +) +from quant_platform_kit.risk.multi_tier_shadow_ledger import ( + DEFAULT_SHADOW_TIERS, + MultiTierShadowReport, + ShadowRebalanceStep, + ShadowTierSpec, + ShadowTierSummary, + run_multi_tier_shadow_ledger, +) +from quant_platform_kit.risk.sentinel_decision_cards import ( + CARD_SEVERITY_CRITICAL, + CARD_SEVERITY_INFO, + CARD_SEVERITY_WARNING, + CARD_TYPE_BAYESIAN_DECAY, + CARD_TYPE_BUCKET_D_REVIEW, + CARD_TYPE_COST_DRIFT, + CARD_TYPE_FUSE_OR_ISOLATION, + CARD_TYPE_TIER_CROSSING, + OwnerDecisionCard, + SentinelDecisionBundle, + build_sentinel_decision_cards, +) from quant_platform_kit.risk.policy_v0_sizing import ( BETA_SOXL, DEFAULT_SLEEVE_BETA_SHARES, @@ -319,4 +356,35 @@ "compute_merged_whole_share_orders", "evaluate_bucket_allocation", "modeled_ibkr_tiered_fee", + "OBSERVATION_SOURCES", + "STATUS_GREEN", + "STATUS_YELLOW", + "STATUS_RED", + "ACTION_HOLD_CONFIG", + "ACTION_REVIEW_REDUCE_WEIGHT", + "ACTION_PAUSE_CONTRIBUTIONS", + "ACTION_SUSPEND_BUCKET", + "QuarterlyBucketObservation", + "BayesianMonitorConfig", + "SourcePosteriorReport", + "BayesianConfidenceReport", + "evaluate_source_posterior", + "evaluate_bucket_bayesian_confidence", + "DEFAULT_SHADOW_TIERS", + "ShadowTierSpec", + "ShadowRebalanceStep", + "ShadowTierSummary", + "MultiTierShadowReport", + "run_multi_tier_shadow_ledger", + "CARD_SEVERITY_INFO", + "CARD_SEVERITY_WARNING", + "CARD_SEVERITY_CRITICAL", + "CARD_TYPE_FUSE_OR_ISOLATION", + "CARD_TYPE_COST_DRIFT", + "CARD_TYPE_BAYESIAN_DECAY", + "CARD_TYPE_TIER_CROSSING", + "CARD_TYPE_BUCKET_D_REVIEW", + "OwnerDecisionCard", + "SentinelDecisionBundle", + "build_sentinel_decision_cards", ] diff --git a/src/quant_platform_kit/risk/bayesian_confidence_monitor.py b/src/quant_platform_kit/risk/bayesian_confidence_monitor.py new file mode 100644 index 00000000..0673ddde --- /dev/null +++ b/src/quant_platform_kit/risk/bayesian_confidence_monitor.py @@ -0,0 +1,463 @@ +"""Pure-offline Layer 2 quarterly source-separated Bayesian confidence monitor. + +Tracks per-bucket quarterly forward excess return and drawdown/slippage breach +rates using conjugate Normal-Normal and Beta-Binomial posteriors. Observations +are strictly partitioned by source (``SHADOW``, ``PAPER``, ``LIVE``) and never +pooled across channels. Inactive channels contribute zero samples. + +Governance invariants: +- Never mutates strategy signal parameters online (``parameter_mutation_allowed=False``). +- Never auto-executes weight changes or suspensions (``auto_execution_allowed=False``). +- Zero broker, cloud, or network I/O. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping +from dataclasses import dataclass, field +from datetime import date, datetime +import math +import re +from types import MappingProxyType + +OBSERVATION_SOURCES: frozenset[str] = frozenset({"SHADOW", "PAPER", "LIVE"}) +SOURCE_FIDELITY_ORDER: tuple[str, ...] = ("LIVE", "PAPER", "SHADOW") + +STATUS_GREEN = "GREEN" +STATUS_YELLOW = "YELLOW" +STATUS_RED = "RED" +VALID_STATUSES: frozenset[str] = frozenset({STATUS_GREEN, STATUS_YELLOW, STATUS_RED}) +_STATUS_RANK: dict[str, int] = {STATUS_GREEN: 0, STATUS_YELLOW: 1, STATUS_RED: 2} + +ACTION_HOLD_CONFIG = "HOLD_CONFIG" +ACTION_REVIEW_REDUCE_WEIGHT = "REVIEW_REDUCE_WEIGHT" +ACTION_PAUSE_CONTRIBUTIONS = "PAUSE_CONTRIBUTIONS" +ACTION_SUSPEND_BUCKET = "SUSPEND_BUCKET" +VALID_ACTIONS: frozenset[str] = frozenset( + { + ACTION_HOLD_CONFIG, + ACTION_REVIEW_REDUCE_WEIGHT, + ACTION_PAUSE_CONTRIBUTIONS, + ACTION_SUSPEND_BUCKET, + } +) +_ACTION_RANK: dict[str, int] = { + ACTION_HOLD_CONFIG: 0, + ACTION_REVIEW_REDUCE_WEIGHT: 1, + ACTION_PAUSE_CONTRIBUTIONS: 2, + ACTION_SUSPEND_BUCKET: 3, +} + +_BUCKET_ID_RE = re.compile(r"^[A-Z0-9][A-Z0-9_-]{0,31}$") +_MIN_PARAM_SCALE = 1e-6 +_MAX_PARAM_SCALE = 1e6 + + +def _finite_float(value: object, name: str) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{name} must be a finite number") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{name} must be finite") + return result + + +def _strict_int(value: object, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise ValueError(f"{name} must be an integer") + return value + + +def _strict_bool(value: object, name: str) -> bool: + if not isinstance(value, bool): + raise ValueError(f"{name} must be a bool") + return value + + +def _strict_date(value: object, name: str) -> date: + if isinstance(value, datetime) or not isinstance(value, date): + raise ValueError(f"{name} must be a datetime.date (not datetime)") + return value + + +def _normalize_bucket_id(value: object) -> str: + if not isinstance(value, str) or not value.strip(): + raise ValueError("bucket_id must be a non-empty string") + norm = value.strip().upper() + if not _BUCKET_ID_RE.match(norm): + raise ValueError("bucket_id must match ^[A-Z0-9][A-Z0-9_-]{0,31}$") + return norm + + +def _normalize_source(value: object) -> str: + if not isinstance(value, str): + raise ValueError("source must be a string in {'SHADOW', 'PAPER', 'LIVE'}") + norm = value.strip().upper() + if norm not in OBSERVATION_SOURCES: + raise ValueError(f"unsupported observation source: {value!r}") + return norm + + +def _calendar_quarter(day: date) -> tuple[int, int]: + return (day.year, (day.month - 1) // 3 + 1) + + +def _normal_cdf(x: float) -> float: + return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0))) + + +def _resolve_config(config: BayesianMonitorConfig | None) -> BayesianMonitorConfig: + if config is None: + return BayesianMonitorConfig() + if not isinstance(config, BayesianMonitorConfig): + raise ValueError("config must be a BayesianMonitorConfig or None") + return config + + +def _materialize_observations(observations: Iterable[QuarterlyBucketObservation]) -> tuple[QuarterlyBucketObservation, ...]: + if isinstance(observations, (str, bytes)): + raise ValueError("observations must be an iterable of QuarterlyBucketObservation, not a string") + return tuple(observations) + + +@dataclass(frozen=True) +class QuarterlyBucketObservation: + """Single quarterly forward observation for one bucket and one source.""" + + bucket_id: str + source: str + period_end: date + excess_return: float + drawdown_breached: bool + slippage_breached: bool = False + is_active_channel: bool = True + + def __post_init__(self) -> None: + object.__setattr__(self, "bucket_id", _normalize_bucket_id(self.bucket_id)) + object.__setattr__(self, "source", _normalize_source(self.source)) + _strict_date(self.period_end, "period_end") + excess = _finite_float(self.excess_return, "excess_return") + object.__setattr__(self, "excess_return", excess) + _strict_bool(self.drawdown_breached, "drawdown_breached") + _strict_bool(self.slippage_breached, "slippage_breached") + _strict_bool(self.is_active_channel, "is_active_channel") + + +@dataclass(frozen=True) +class BayesianMonitorConfig: + """Conjugate priors and governance alert thresholds for Layer 2 decay monitoring.""" + + prior_mean_quarterly: float = 0.0 + prior_std_quarterly: float = 0.04 + observation_std_quarterly: float = 0.06 + prior_breach_alpha: float = 0.5 + prior_breach_beta: float = 4.5 + min_quarters_for_action: int = 4 + yellow_prob_negative_threshold: float = 0.70 + red_prob_negative_threshold: float = 0.85 + yellow_breach_prob_threshold: float = 0.25 + red_breach_prob_threshold: float = 0.40 + + def __post_init__(self) -> None: + _finite_float(self.prior_mean_quarterly, "prior_mean_quarterly") + p_std = _finite_float(self.prior_std_quarterly, "prior_std_quarterly") + o_std = _finite_float(self.observation_std_quarterly, "observation_std_quarterly") + alpha = _finite_float(self.prior_breach_alpha, "prior_breach_alpha") + beta = _finite_float(self.prior_breach_beta, "prior_breach_beta") + min_q = _strict_int(self.min_quarters_for_action, "min_quarters_for_action") + y_neg = _finite_float(self.yellow_prob_negative_threshold, "yellow_prob_negative_threshold") + r_neg = _finite_float(self.red_prob_negative_threshold, "red_prob_negative_threshold") + y_br = _finite_float(self.yellow_breach_prob_threshold, "yellow_breach_prob_threshold") + r_br = _finite_float(self.red_breach_prob_threshold, "red_breach_prob_threshold") + + for name, val in ( + ("prior_std_quarterly", p_std), + ("observation_std_quarterly", o_std), + ("prior_breach_alpha", alpha), + ("prior_breach_beta", beta), + ): + if not (_MIN_PARAM_SCALE <= val <= _MAX_PARAM_SCALE): + raise ValueError(f"{name} must be within [{_MIN_PARAM_SCALE}, {_MAX_PARAM_SCALE}]") + if min_q < 1: + raise ValueError("min_quarters_for_action must be >= 1") + if not (0.0 < y_neg < r_neg < 1.0): + raise ValueError("require 0 < yellow_prob_negative_threshold < red_prob_negative_threshold < 1") + if not (0.0 < y_br < r_br < 1.0): + raise ValueError("require 0 < yellow_breach_prob_threshold < red_breach_prob_threshold < 1") + + +@dataclass(frozen=True) +class SourcePosteriorReport: + """Posterior confidence and governance recommendation for one source.""" + + bucket_id: str + source: str + sample_count: int + ignored_inactive_count: int + sufficient_samples: bool + latest_period_end: date | None + posterior_mean_quarterly: float + posterior_std_quarterly: float + prob_negative_excess: float + drawdown_breach_count: int + posterior_drawdown_breach_prob: float + slippage_breach_count: int + posterior_slippage_breach_prob: float + status: str + recommended_action: str + reason_codes: tuple[str, ...] + parameter_mutation_allowed: bool = field(default=False, init=False) + auto_execution_allowed: bool = field(default=False, init=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "bucket_id", _normalize_bucket_id(self.bucket_id)) + object.__setattr__(self, "source", _normalize_source(self.source)) + if self.latest_period_end is not None: + _strict_date(self.latest_period_end, "latest_period_end") + if self.status not in VALID_STATUSES: + raise ValueError(f"unsupported status: {self.status!r}") + if self.recommended_action not in VALID_ACTIONS: + raise ValueError(f"unsupported recommended_action: {self.recommended_action!r}") + + +@dataclass(frozen=True) +class BayesianConfidenceReport: + """Source-separated Bayesian confidence report for a single bucket.""" + + bucket_id: str + by_source: Mapping[str, SourcePosteriorReport] + primary_source: str | None + latest_period_end: date | None + overall_status: str + recommended_action: str + reason_codes: tuple[str, ...] + parameter_mutation_allowed: bool = field(default=False, init=False) + auto_execution_allowed: bool = field(default=False, init=False) + + def __post_init__(self) -> None: + object.__setattr__(self, "bucket_id", _normalize_bucket_id(self.bucket_id)) + if self.primary_source is not None: + object.__setattr__(self, "primary_source", _normalize_source(self.primary_source)) + if self.latest_period_end is not None: + _strict_date(self.latest_period_end, "latest_period_end") + if self.overall_status not in VALID_STATUSES: + raise ValueError(f"unsupported overall_status: {self.overall_status!r}") + if self.recommended_action not in VALID_ACTIONS: + raise ValueError(f"unsupported recommended_action: {self.recommended_action!r}") + object.__setattr__(self, "by_source", MappingProxyType(dict(self.by_source))) + + +def _filter_and_validate_source_observations( + bucket_id: str, + source: str, + observations: tuple[QuarterlyBucketObservation, ...], +) -> tuple[list[QuarterlyBucketObservation], int]: + active: list[QuarterlyBucketObservation] = [] + ignored_inactive = 0 + last_period: date | None = None + seen_quarters: set[tuple[int, int]] = set() + + for obs in observations: + if not isinstance(obs, QuarterlyBucketObservation): + raise ValueError("observations must contain QuarterlyBucketObservation instances") + if obs.bucket_id != bucket_id: + raise ValueError(f"observation bucket_id {obs.bucket_id!r} != expected {bucket_id!r}") + if obs.source != source: + raise ValueError(f"observation source {obs.source!r} != expected {source!r}") + if not obs.is_active_channel: + ignored_inactive += 1 + continue + if last_period is not None and obs.period_end <= last_period: + raise ValueError("active observations within a source must have strictly increasing period_end") + qtr = _calendar_quarter(obs.period_end) + if qtr in seen_quarters: + raise ValueError(f"duplicate calendar quarter {qtr[0]}-Q{qtr[1]} in source {source}") + seen_quarters.add(qtr) + last_period = obs.period_end + active.append(obs) + + return active, ignored_inactive + + +def _classify_posterior_governance( + *, + sample_count: int, + dd_count: int, + slip_count: int, + prob_negative_excess: float, + posterior_dd_prob: float, + posterior_slip_prob: float, + cfg: BayesianMonitorConfig, +) -> tuple[str, str, tuple[str, ...]]: + if sample_count == 0: + return STATUS_GREEN, ACTION_HOLD_CONFIG, ("INSUFFICIENT_SAMPLES",) + + reasons: list[str] = [] + neg_red = prob_negative_excess >= cfg.red_prob_negative_threshold + neg_yellow = prob_negative_excess >= cfg.yellow_prob_negative_threshold + dd_red = posterior_dd_prob >= cfg.red_breach_prob_threshold + dd_yellow = posterior_dd_prob >= cfg.yellow_breach_prob_threshold + slip_red = posterior_slip_prob >= cfg.red_breach_prob_threshold + slip_yellow = posterior_slip_prob >= cfg.yellow_breach_prob_threshold + + if sample_count >= cfg.min_quarters_for_action: + if neg_red: + reasons.append("EXCESS_RETURN_DECAY_RED") + if dd_red: + reasons.append("DRAWDOWN_BREACH_RATE_RED") + if slip_red: + reasons.append("SLIPPAGE_BREACH_RATE_RED") + if neg_red and dd_red: + return STATUS_RED, ACTION_SUSPEND_BUCKET, tuple(reasons) + if neg_red or dd_red or slip_red: + return STATUS_RED, ACTION_PAUSE_CONTRIBUTIONS, tuple(reasons) + + if neg_yellow: + reasons.append("EXCESS_RETURN_DECAY_YELLOW") + if dd_yellow: + reasons.append("DRAWDOWN_BREACH_RATE_YELLOW") + if slip_yellow: + reasons.append("SLIPPAGE_BREACH_RATE_YELLOW") + if reasons: + return STATUS_YELLOW, ACTION_REVIEW_REDUCE_WEIGHT, tuple(reasons) + return STATUS_GREEN, ACTION_HOLD_CONFIG, ("CONFIDENCE_HEALTHY",) + + # Below min_quarters_for_action: require >=2 actual breaches of the flagged type + if dd_count >= 2 and dd_red: + reasons.append("EARLY_DRAWDOWN_BREACH_WARNING") + if slip_count >= 2 and slip_red: + reasons.append("EARLY_SLIPPAGE_BREACH_WARNING") + if reasons: + return STATUS_YELLOW, ACTION_REVIEW_REDUCE_WEIGHT, tuple(reasons) + + return STATUS_GREEN, ACTION_HOLD_CONFIG, ("INSUFFICIENT_SAMPLES",) + + +def evaluate_source_posterior( + bucket_id: str, + source: str, + observations: Iterable[QuarterlyBucketObservation], + *, + config: BayesianMonitorConfig | None = None, +) -> SourcePosteriorReport: + """Compute conjugate Normal-Normal + Beta-Binomial posteriors for one source.""" + norm_bucket = _normalize_bucket_id(bucket_id) + norm_source = _normalize_source(source) + cfg = _resolve_config(config) + obs_tuple = _materialize_observations(observations) + + active, ignored_inactive = _filter_and_validate_source_observations(norm_bucket, norm_source, obs_tuple) + n = len(active) + + prior_prec = 1.0 / (cfg.prior_std_quarterly**2) + obs_prec = 1.0 / (cfg.observation_std_quarterly**2) + post_prec = prior_prec + n * obs_prec + excess_sum = sum(obs.excess_return for obs in active) + post_mean = (prior_prec * cfg.prior_mean_quarterly + obs_prec * excess_sum) / post_prec + post_std = math.sqrt(1.0 / post_prec) + prob_neg = _normal_cdf(-post_mean / post_std) + + dd_count = sum(1 for obs in active if obs.drawdown_breached) + slip_count = sum(1 for obs in active if obs.slippage_breached) + denom = cfg.prior_breach_alpha + cfg.prior_breach_beta + n + post_dd_prob = (cfg.prior_breach_alpha + dd_count) / denom + post_slip_prob = (cfg.prior_breach_alpha + slip_count) / denom + + for name, val in ( + ("posterior_mean_quarterly", post_mean), + ("posterior_std_quarterly", post_std), + ("prob_negative_excess", prob_neg), + ("posterior_drawdown_breach_prob", post_dd_prob), + ("posterior_slippage_breach_prob", post_slip_prob), + ): + _finite_float(val, name) + + status, action, reasons = _classify_posterior_governance( + sample_count=n, + dd_count=dd_count, + slip_count=slip_count, + prob_negative_excess=prob_neg, + posterior_dd_prob=post_dd_prob, + posterior_slip_prob=post_slip_prob, + cfg=cfg, + ) + + return SourcePosteriorReport( + bucket_id=norm_bucket, + source=norm_source, + sample_count=n, + ignored_inactive_count=ignored_inactive, + sufficient_samples=n >= cfg.min_quarters_for_action, + latest_period_end=active[-1].period_end if active else None, + posterior_mean_quarterly=post_mean, + posterior_std_quarterly=post_std, + prob_negative_excess=prob_neg, + drawdown_breach_count=dd_count, + posterior_drawdown_breach_prob=post_dd_prob, + slippage_breach_count=slip_count, + posterior_slippage_breach_prob=post_slip_prob, + status=status, + recommended_action=action, + reason_codes=reasons, + ) + + +def evaluate_bucket_bayesian_confidence( + bucket_id: str, + observations: Iterable[QuarterlyBucketObservation], + *, + config: BayesianMonitorConfig | None = None, +) -> BayesianConfidenceReport: + """Evaluate a bucket's quarterly Bayesian confidence with strict source separation.""" + norm_bucket = _normalize_bucket_id(bucket_id) + cfg = _resolve_config(config) + obs_tuple = _materialize_observations(observations) + + grouped: dict[str, list[QuarterlyBucketObservation]] = {src: [] for src in SOURCE_FIDELITY_ORDER} + for obs in obs_tuple: + if not isinstance(obs, QuarterlyBucketObservation): + raise ValueError("observations must contain QuarterlyBucketObservation instances") + if obs.bucket_id != norm_bucket: + raise ValueError(f"observation bucket_id {obs.bucket_id!r} != expected {norm_bucket!r}") + grouped[obs.source].append(obs) + + by_source: dict[str, SourcePosteriorReport] = {} + for src in SOURCE_FIDELITY_ORDER: + if grouped[src]: + by_source[src] = evaluate_source_posterior(norm_bucket, src, grouped[src], config=cfg) + + active_reports = [by_source[src] for src in SOURCE_FIDELITY_ORDER if src in by_source and by_source[src].sample_count > 0] + if not active_reports: + return BayesianConfidenceReport( + bucket_id=norm_bucket, + by_source=by_source, + primary_source=None, + latest_period_end=None, + overall_status=STATUS_GREEN, + recommended_action=ACTION_HOLD_CONFIG, + reason_codes=("NO_ACTIVE_SAMPLES",), + ) + + primary_report = active_reports[0] + latest_end = max(rep.latest_period_end for rep in active_reports if rep.latest_period_end is not None) + + # Preserve highest-fidelity primary_source, but never let an insufficient-sample + # higher-fidelity channel mask an active YELLOW/RED alert from another channel. + governing = primary_report + if not primary_report.sufficient_samples: + worst = max( + active_reports, + key=lambda r: (_STATUS_RANK[r.status], _ACTION_RANK[r.recommended_action]), + ) + if _STATUS_RANK[worst.status] > _STATUS_RANK[primary_report.status]: + governing = worst + + return BayesianConfidenceReport( + bucket_id=norm_bucket, + by_source=by_source, + primary_source=primary_report.source, + latest_period_end=latest_end, + overall_status=governing.status, + recommended_action=governing.recommended_action, + reason_codes=governing.reason_codes, + ) diff --git a/src/quant_platform_kit/risk/multi_tier_shadow_ledger.py b/src/quant_platform_kit/risk/multi_tier_shadow_ledger.py new file mode 100644 index 00000000..08ac2118 --- /dev/null +++ b/src/quant_platform_kit/risk/multi_tier_shadow_ledger.py @@ -0,0 +1,430 @@ +"""Pure-offline multi-tier simultaneous read-only shadow ledger. + +Simulates multiple capital tiers (default ``$1.5k``, ``$15k``, ``$50k`` plus +modeled ``$300/month`` contributions) over the exact same sequence of signals, +timestamps, and quotes using ``bucket_capital_ladder`` whole-share order +merging and ``benchmark_dca_and_regime`` matched-cashflow DCA benchmarking. + +Zero broker, cloud, or network I/O. Strictly read-only shadow accounting. +""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date, datetime +from decimal import Decimal +import math +from types import MappingProxyType + +from quant_platform_kit.risk.benchmark_dca_and_regime import ( + DcaCashFlowPoint, + MatchedCashflowDcaReport, + evaluate_matched_cashflow_dca_benchmark, +) +from quant_platform_kit.risk.bucket_capital_ladder import ( + BucketAllocationPlan, + BucketLadderConfig, + classify_capital_tier, + compute_merged_whole_share_orders, + evaluate_bucket_allocation, +) + + +def _finite_number(value: object, name: str, *, allow_zero: bool = True) -> float: + if isinstance(value, bool) or not isinstance(value, (int, float)): + raise ValueError(f"{name} must be a finite number") + result = float(value) + if not math.isfinite(result): + raise ValueError(f"{name} must be finite") + if allow_zero and result < 0.0: + raise ValueError(f"{name} must be >= 0") + if not allow_zero and result <= 0.0: + raise ValueError(f"{name} must be > 0") + return result + + +def _strict_date(value: object, name: str) -> date: + if isinstance(value, datetime) or not isinstance(value, date): + raise ValueError(f"{name} must be a datetime.date (not datetime)") + return value + + +def _normalize_weights(weights: Mapping[str, float], name: str) -> dict[str, float]: + out: dict[str, float] = {} + total = Decimal("0") + for raw_sym, raw_w in weights.items(): + if not isinstance(raw_sym, str) or not raw_sym.strip(): + raise ValueError(f"{name} contains an empty symbol") + sym = raw_sym.strip().upper() + if sym in out: + raise ValueError(f"{name} contains duplicate normalized symbol {sym!r}") + w = _finite_number(raw_w, f"{name}[{sym}]", allow_zero=True) + if w > 1.0: + raise ValueError(f"{name}[{sym}] must be <= 1.0") + out[sym] = w + total += Decimal(str(w)) + if total > Decimal("1.000001"): + raise ValueError(f"{name} sum must be <= 1.0 (got {total})") + return out + + +def _normalize_prices(prices: Mapping[str, float]) -> dict[str, float]: + out: dict[str, float] = {} + for raw_sym, raw_px in prices.items(): + if not isinstance(raw_sym, str) or not raw_sym.strip(): + raise ValueError("prices_usd contains an empty symbol") + sym = raw_sym.strip().upper() + if sym in out: + raise ValueError(f"prices_usd contains duplicate normalized symbol {sym!r}") + out[sym] = _finite_number(raw_px, f"prices_usd[{sym}]", allow_zero=False) + return out + + +def _normalize_halted(halted: Sequence[str]) -> tuple[str, ...]: + if isinstance(halted, (str, bytes)): + raise ValueError("halted_symbols must be a sequence of symbols, not a bare string") + out: set[str] = set() + for raw in halted: + if not isinstance(raw, str) or not raw.strip(): + raise ValueError("halted_symbols contains an empty symbol") + out.add(raw.strip().upper()) + return tuple(sorted(out)) + + +@dataclass(frozen=True) +class ShadowTierSpec: + """Initial capital and modeled recurring contribution for one shadow tier.""" + + tier_name: str + initial_capital_usd: float + monthly_contribution_usd: float = 300.0 + + def __post_init__(self) -> None: + if not isinstance(self.tier_name, str) or not self.tier_name.strip(): + raise ValueError("tier_name must be a non-empty string") + object.__setattr__(self, "tier_name", self.tier_name.strip()) + _finite_number(self.initial_capital_usd, "initial_capital_usd", allow_zero=False) + _finite_number(self.monthly_contribution_usd, "monthly_contribution_usd", allow_zero=True) + + +DEFAULT_SHADOW_TIERS: tuple[ShadowTierSpec, ...] = ( + ShadowTierSpec("TIER1_1500", 1_500.0, 300.0), + ShadowTierSpec("TIER2_15000", 15_000.0, 300.0), + ShadowTierSpec("TIER3_50000", 50_000.0, 300.0), +) + + +@dataclass(frozen=True) +class ShadowRebalanceStep: + """One shared market/signal snapshot consumed identically by all shadow tiers.""" + + session_date: date + prices_usd: Mapping[str, float] + bucket_a_weights: Mapping[str, float] + bucket_b_weights: Mapping[str, float] + bucket_d_weights: Mapping[str, float] = field(default_factory=dict) + apply_monthly_contribution: bool = False + halted_symbols: tuple[str, ...] = () + bucket_d_forward_oos_passed: bool = False + bucket_d_owner_approved: bool = False + fuse_halted: bool = False + expansion_paused: bool = False + + def __post_init__(self) -> None: + _strict_date(self.session_date, "session_date") + object.__setattr__(self, "prices_usd", MappingProxyType(_normalize_prices(self.prices_usd))) + object.__setattr__(self, "bucket_a_weights", MappingProxyType(_normalize_weights(self.bucket_a_weights, "bucket_a_weights"))) + object.__setattr__(self, "bucket_b_weights", MappingProxyType(_normalize_weights(self.bucket_b_weights, "bucket_b_weights"))) + object.__setattr__(self, "bucket_d_weights", MappingProxyType(_normalize_weights(self.bucket_d_weights, "bucket_d_weights"))) + object.__setattr__(self, "halted_symbols", _normalize_halted(self.halted_symbols)) + for flag in ( + "apply_monthly_contribution", + "bucket_d_forward_oos_passed", + "bucket_d_owner_approved", + "fuse_halted", + "expansion_paused", + ): + if not isinstance(getattr(self, flag), bool): + raise ValueError(f"{flag} must be a bool") + + +@dataclass(frozen=True) +class ShadowTierSummary: + """End-of-run read-only shadow ledger summary for one capital tier.""" + + tier_name: str + initial_capital_usd: float + total_contributions_usd: float + ending_nav_usd: float + ending_cash_usd: float + ending_holdings: Mapping[str, int] + total_fees_usd: float + mean_idle_cash_ratio: float + zero_share_event_count: int + rebalance_count: int + final_capital_tier: str + net_return_on_invested: float + benchmark_comparison: MatchedCashflowDcaReport | None = None + + +@dataclass(frozen=True) +class MultiTierShadowReport: + """Simultaneous multi-tier shadow ledger evaluation across shared market steps.""" + + tiers: Mapping[str, ShadowTierSummary] + step_count: int + start_date: date | None + end_date: date | None + read_only_shadow: bool = field(default=True, init=False) + + +def _validate_steps_and_tiers( + steps: tuple[ShadowRebalanceStep, ...], + tiers: tuple[ShadowTierSpec, ...], + benchmark_symbols: tuple[str, ...], +) -> None: + if not tiers: + raise ValueError("tiers must not be empty") + seen_tiers: set[str] = set() + for tier in tiers: + if not isinstance(tier, ShadowTierSpec): + raise ValueError("tiers must contain ShadowTierSpec instances") + if tier.tier_name in seen_tiers: + raise ValueError(f"duplicate tier_name: {tier.tier_name!r}") + seen_tiers.add(tier.tier_name) + + prev_date: date | None = None + contribution_months: dict[tuple[int, int], date] = {} + for step in steps: + if not isinstance(step, ShadowRebalanceStep): + raise ValueError("steps must contain ShadowRebalanceStep instances") + if prev_date is not None and step.session_date <= prev_date: + raise ValueError("steps must have strictly increasing session_date") + prev_date = step.session_date + + if step.apply_monthly_contribution: + ym = (step.session_date.year, step.session_date.month) + if ym in contribution_months: + raise ValueError( + f"duplicate monthly contribution in {ym[0]}-{ym[1]:02d}: " + f"{contribution_months[ym]} and {step.session_date}" + ) + contribution_months[ym] = step.session_date + + missing_bench = [sym for sym in benchmark_symbols if sym not in step.prices_usd] + if missing_bench: + raise ValueError( + f"missing benchmark price(s) on {step.session_date.isoformat()}: {', '.join(missing_bench)}" + ) + + +def _build_sleeve_targets_and_caps( + step: ShadowRebalanceStep, + alloc: BucketAllocationPlan, + holdings: Mapping[str, int], + *, + expansion_paused: bool, +) -> tuple[list[tuple[str, float]], dict[str, float]]: + merged_targets: dict[str, float] = {} + budget_a = alloc.bucket_budgets_usd.get("A", 0.0) + budget_b = alloc.bucket_budgets_usd.get("B", 0.0) + budget_d = alloc.bucket_budgets_usd.get("D", 0.0) + + positive_ab_syms: set[str] = set() + for sym, w in step.bucket_a_weights.items(): + if budget_a > 0.0 and w > 0.0: + merged_targets[sym] = merged_targets.get(sym, 0.0) + budget_a * w + positive_ab_syms.add(sym) + for sym, w in step.bucket_b_weights.items(): + if budget_b > 0.0 and w > 0.0: + merged_targets[sym] = merged_targets.get(sym, 0.0) + budget_b * w + positive_ab_syms.add(sym) + + caps: dict[str, float] = {} + if alloc.bucket_d_active and budget_d > 0.0: + d_cap = alloc.bucket_d_single_stock_max_usd + for sym, w in step.bucket_d_weights.items(): + if w > 0.0: + raw_d_usd = budget_d * w + capped_d_usd = min(raw_d_usd, d_cap) if d_cap > 0.0 else raw_d_usd + merged_targets[sym] = merged_targets.get(sym, 0.0) + capped_d_usd + if sym not in positive_ab_syms and d_cap > 0.0: + caps[sym] = d_cap + + if expansion_paused: + # Block all new buys across every sleeve while keeping existing holdings + # and still permitting explicit trims/exits. + for sym in set(merged_targets) | set(holdings): + held_val = holdings.get(sym, 0) * step.prices_usd[sym] + if sym in merged_targets: + merged_targets[sym] = min(merged_targets[sym], held_val) + elif holdings.get(sym, 0) > 0: + merged_targets[sym] = held_val + + target_pairs = [(sym, usd) for sym, usd in merged_targets.items() if usd > 0.0] + return target_pairs, caps + + +def _simulate_single_tier( + tier: ShadowTierSpec, + steps: tuple[ShadowRebalanceStep, ...], + *, + ladder_config: BucketLadderConfig, + slippage_bps: float, + benchmark_symbols: tuple[str, ...], +) -> ShadowTierSummary: + cash = float(tier.initial_capital_usd) + total_contributions = float(tier.initial_capital_usd) + holdings: dict[str, int] = {} + total_fees = 0.0 + idle_ratios: list[float] = [] + zero_share_events = 0 + rebalance_count = 0 + dca_points: list[DcaCashFlowPoint] = [] + + prev_tier: str | None = None + for idx, step in enumerate(steps): + flow_usd = float(tier.initial_capital_usd) if idx == 0 else 0.0 + if step.apply_monthly_contribution and tier.monthly_contribution_usd > 0.0: + cash += tier.monthly_contribution_usd + total_contributions += tier.monthly_contribution_usd + flow_usd += tier.monthly_contribution_usd + + if benchmark_symbols: + bench_px = {sym: step.prices_usd[sym] for sym in benchmark_symbols} + dca_points.append( + DcaCashFlowPoint( + session_date=step.session_date.isoformat(), + net_cash_flow_usd=flow_usd, + benchmark_prices_usd=bench_px, + ) + ) + + missing_held = [s for s, q in holdings.items() if q > 0 and s not in step.prices_usd] + if missing_held: + raise ValueError(f"missing price for held symbols on {step.session_date}: {sorted(missing_held)}") + held_val = sum(q * step.prices_usd[s] for s, q in holdings.items() if q > 0) + nav_usd = cash + held_val + + if step.fuse_halted: + idle_ratios.append((cash / nav_usd) if nav_usd > 0 else 1.0) + continue + + d_approved = step.bucket_d_forward_oos_passed and step.bucket_d_owner_approved + alloc = evaluate_bucket_allocation( + investable_nav_usd=nav_usd, + bucket_d_approved=d_approved, + prior_tier=prev_tier, + config=ladder_config, + ) + prev_tier = alloc.capital_tier + paused = step.expansion_paused or alloc.expansion_paused + + target_pairs, caps = _build_sleeve_targets_and_caps( + step, + alloc, + holdings, + expansion_paused=paused, + ) + + order_plan = compute_merged_whole_share_orders( + target_dollar_allocations=target_pairs, + total_available_nav_usd=nav_usd, + prices_usd=step.prices_usd, + current_shares=holdings, + halted_symbols=step.halted_symbols, + single_symbol_max_usd=caps or None, + slippage_bps=slippage_bps, + ) + + holdings = {s: q for s, q in order_plan.target_shares.items() if q > 0} + cash = order_plan.idle_cash_usd + total_fees += order_plan.estimated_fees_usd + idle_ratios.append(order_plan.idle_cash_ratio) + rebalance_count += 1 + if order_plan.zero_share_target_symbols: + zero_share_events += 1 + + last_prices = steps[-1].prices_usd if steps else {} + ending_nav = cash + sum(q * last_prices[s] for s, q in holdings.items()) + mean_idle = sum(idle_ratios) / len(idle_ratios) if idle_ratios else 1.0 + net_ret = (ending_nav - total_contributions) / total_contributions if total_contributions > 0 else 0.0 + + bench_report: MatchedCashflowDcaReport | None = None + if benchmark_symbols and dca_points: + bench_report = evaluate_matched_cashflow_dca_benchmark( + actual_ending_equity_usd=ending_nav, + observations=dca_points, + benchmark_symbols=benchmark_symbols, + cost_bps_oneway=slippage_bps, + valuation_session_date=steps[-1].session_date.isoformat(), + ) + + return ShadowTierSummary( + tier_name=tier.tier_name, + initial_capital_usd=tier.initial_capital_usd, + total_contributions_usd=total_contributions, + ending_nav_usd=ending_nav, + ending_cash_usd=cash, + ending_holdings=MappingProxyType(dict(sorted(holdings.items()))), + total_fees_usd=total_fees, + mean_idle_cash_ratio=mean_idle, + zero_share_event_count=zero_share_events, + rebalance_count=rebalance_count, + final_capital_tier=classify_capital_tier(ending_nav, ladder_config), + net_return_on_invested=net_ret, + benchmark_comparison=bench_report, + ) + + +def run_multi_tier_shadow_ledger( + steps: Iterable[ShadowRebalanceStep], + *, + tiers: Iterable[ShadowTierSpec] = DEFAULT_SHADOW_TIERS, + ladder_config: BucketLadderConfig | None = None, + slippage_bps: float = 10.0, + benchmark_symbols: Sequence[str] = (), +) -> MultiTierShadowReport: + """Run all configured shadow capital tiers over identical market/signal steps.""" + if isinstance(steps, (str, bytes)): + raise ValueError("steps must be an iterable of ShadowRebalanceStep, not a string") + if isinstance(tiers, (str, bytes)): + raise ValueError("tiers must be an iterable of ShadowTierSpec, not a string") + if ladder_config is None: + cfg = BucketLadderConfig() + elif isinstance(ladder_config, BucketLadderConfig): + cfg = ladder_config + else: + raise ValueError("ladder_config must be a BucketLadderConfig or None") + + slip = _finite_number(slippage_bps, "slippage_bps", allow_zero=True) + if slip >= 5_000.0: + raise ValueError("slippage_bps must be < 5000") + if isinstance(benchmark_symbols, (str, bytes)): + raise ValueError("benchmark_symbols must be a sequence of symbols, not a bare string") + norm_bench = tuple(dict.fromkeys(s.strip().upper() for s in benchmark_symbols if isinstance(s, str) and s.strip())) + if len(norm_bench) != len(benchmark_symbols): + raise ValueError("benchmark_symbols must contain unique non-empty strings") + + steps_tuple = tuple(steps) + tiers_tuple = tuple(tiers) + _validate_steps_and_tiers(steps_tuple, tiers_tuple, norm_bench) + + results = { + tier.tier_name: _simulate_single_tier( + tier, + steps_tuple, + ladder_config=cfg, + slippage_bps=slip, + benchmark_symbols=norm_bench, + ) + for tier in tiers_tuple + } + + return MultiTierShadowReport( + tiers=MappingProxyType(results), + step_count=len(steps_tuple), + start_date=steps_tuple[0].session_date if steps_tuple else None, + end_date=steps_tuple[-1].session_date if steps_tuple else None, + ) diff --git a/src/quant_platform_kit/risk/sentinel_decision_cards.py b/src/quant_platform_kit/risk/sentinel_decision_cards.py new file mode 100644 index 00000000..1337ddb9 --- /dev/null +++ b/src/quant_platform_kit/risk/sentinel_decision_cards.py @@ -0,0 +1,441 @@ +"""Pure-offline Layer 3 AI Sentinel & Web-Console Decision-Card payload builder. + +Aggregates pure-offline governance reports (capital tier allocation, Layer 2 +Bayesian decay status, execution cost drift, Bucket D 12-month OOS readiness, +and FUSE/isolation health) into redacted, JSON-serializable ``OwnerDecisionCard`` +items for web-console approval. + +Governance invariants: +- Strictly read-only sentinel (``read_only_sentinel=True``). +- Never auto-executes orders, tier switches, or bucket toggles (``auto_execute=False``). +- Never includes raw account IDs, credentials, hostnames, or cloud resource IDs. +""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field +from datetime import date, datetime +import math +from types import MappingProxyType + +from quant_platform_kit.risk.bayesian_confidence_monitor import ( + STATUS_GREEN, + STATUS_RED, + VALID_ACTIONS, + VALID_STATUSES, + BayesianConfidenceReport, +) +from quant_platform_kit.risk.bucket_capital_ladder import ( + TIER_1, + TIER_2, + TIER_3, + TIER_BELOW, + BucketAllocationPlan, +) +from quant_platform_kit.risk.execution_cost_drift import ExecutionCostDriftReport + +CARD_SEVERITY_INFO = "INFO" +CARD_SEVERITY_WARNING = "WARNING" +CARD_SEVERITY_CRITICAL = "CRITICAL" + +_SEVERITY_RANK: dict[str, int] = { + CARD_SEVERITY_CRITICAL: 0, + CARD_SEVERITY_WARNING: 1, + CARD_SEVERITY_INFO: 2, +} + +CARD_TYPE_FUSE_OR_ISOLATION = "FUSE_OR_ISOLATION_STATUS" +CARD_TYPE_COST_DRIFT = "EXECUTION_COST_DRIFT" +CARD_TYPE_BAYESIAN_DECAY = "BAYESIAN_CONFIDENCE_ALERT" +CARD_TYPE_TIER_CROSSING = "TIER_CROSSING" +CARD_TYPE_BUCKET_D_REVIEW = "BUCKET_D_12M_REVIEW" + +_TIER_RANK: dict[str, int] = { + TIER_BELOW: 0, + TIER_1: 1, + TIER_2: 2, + TIER_3: 3, +} + +_PUBLIC_ISOLATION_CODES: frozenset[str] = frozenset( + { + "ISOLATION_UNHEALTHY", + "PAPER_LIVE_HOST_MISMATCH", + "GATEWAY_READBACK_UNHEALTHY", + "CONFIG_DRIFT_DETECTED", + } +) +_PUBLIC_BAYESIAN_REASONS: frozenset[str] = frozenset( + { + "INSUFFICIENT_SAMPLES", + "NO_ACTIVE_SAMPLES", + "CONFIDENCE_HEALTHY", + "EXCESS_RETURN_DECAY_YELLOW", + "EXCESS_RETURN_DECAY_RED", + "DRAWDOWN_BREACH_RATE_YELLOW", + "DRAWDOWN_BREACH_RATE_RED", + "SLIPPAGE_BREACH_RATE_YELLOW", + "SLIPPAGE_BREACH_RATE_RED", + "EARLY_DRAWDOWN_BREACH_WARNING", + "EARLY_SLIPPAGE_BREACH_WARNING", + } +) + + +def _strict_date(value: object, name: str) -> date: + if isinstance(value, datetime) or not isinstance(value, date): + raise ValueError(f"{name} must be a datetime.date (not datetime)") + return value + + +def _strict_bool(value: object, name: str) -> bool: + if not isinstance(value, bool): + raise ValueError(f"{name} must be a bool") + return value + + +def _strict_non_neg_int(value: object, name: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"{name} must be a non-negative integer") + return value + + +def _validate_evidence(evidence: Mapping[str, str | int | float | bool]) -> Mapping[str, str | int | float | bool]: + if not isinstance(evidence, Mapping): + raise ValueError("evidence must be a mapping") + clean: dict[str, str | int | float | bool] = {} + for key, val in evidence.items(): + if not isinstance(key, str) or not key.strip(): + raise ValueError("evidence keys must be non-empty strings") + if isinstance(val, (str, bool, int)): + clean[key] = val + elif isinstance(val, float): + if not math.isfinite(val): + raise ValueError(f"evidence[{key!r}] must be a finite float") + clean[key] = val + else: + raise ValueError(f"evidence[{key!r}] must be a JSON-safe scalar (str, bool, int, finite float)") + return MappingProxyType(clean) + + +def _sanitize_isolation_code(raw_reason: str) -> str: + norm = raw_reason.strip().upper() + if norm in _PUBLIC_ISOLATION_CODES: + return norm + return "ISOLATION_UNHEALTHY" + + +def _sanitize_bayesian_reasons(reasons: Sequence[str]) -> str: + safe = [r if r in _PUBLIC_BAYESIAN_REASONS else "GOVERNANCE_ALERT" for r in reasons] + return ",".join(safe) + + +@dataclass(frozen=True) +class OwnerDecisionCard: + """Single redacted decision card for the web console approval queue.""" + + card_id: str + card_type: str + severity: str + title: str + summary: str + recommended_action: str + evidence: Mapping[str, str | int | float | bool] + requires_owner_signoff: bool = field(default=True, init=False) + auto_execute: bool = field(default=False, init=False) + + def __post_init__(self) -> None: + if not isinstance(self.card_id, str) or not self.card_id.strip(): + raise ValueError("card_id must be a non-empty string") + if self.severity not in _SEVERITY_RANK: + raise ValueError(f"unsupported severity: {self.severity!r}") + object.__setattr__(self, "evidence", _validate_evidence(self.evidence)) + + def to_dict(self) -> dict[str, object]: + return { + "card_id": self.card_id, + "card_type": self.card_type, + "severity": self.severity, + "title": self.title, + "summary": self.summary, + "recommended_action": self.recommended_action, + "evidence": dict(self.evidence), + "requires_owner_signoff": self.requires_owner_signoff, + "auto_execute": self.auto_execute, + } + + +@dataclass(frozen=True) +class SentinelDecisionBundle: + """Deterministic collection of pending owner decision cards.""" + + as_of_date: date + cards: tuple[OwnerDecisionCard, ...] + highest_severity: str = field(init=False) + pending_signoff_count: int = field(init=False) + read_only_sentinel: bool = field(default=True, init=False) + auto_execute_allowed: bool = field(default=False, init=False) + + def __post_init__(self) -> None: + _strict_date(self.as_of_date, "as_of_date") + cards_tuple = tuple(self.cards) + seen_ids: set[str] = set() + for card in cards_tuple: + if not isinstance(card, OwnerDecisionCard): + raise ValueError("cards must contain OwnerDecisionCard instances") + if card.card_id in seen_ids: + raise ValueError(f"duplicate card_id in bundle: {card.card_id!r}") + seen_ids.add(card.card_id) + sorted_cards = tuple(sorted(cards_tuple, key=lambda c: (_SEVERITY_RANK[c.severity], c.card_type, c.card_id))) + object.__setattr__(self, "cards", sorted_cards) + object.__setattr__(self, "highest_severity", sorted_cards[0].severity if sorted_cards else CARD_SEVERITY_INFO) + object.__setattr__(self, "pending_signoff_count", len(sorted_cards)) + + def to_dict(self) -> dict[str, object]: + return { + "as_of_date": self.as_of_date.isoformat(), + "cards": [card.to_dict() for card in self.cards], + "highest_severity": self.highest_severity, + "pending_signoff_count": self.pending_signoff_count, + "read_only_sentinel": self.read_only_sentinel, + "auto_execute_allowed": self.auto_execute_allowed, + } + + +def _append_safety_cards( + cards: list[OwnerDecisionCard], + *, + as_of_iso: str, + fuse_halted: bool, + isolation_healthy: bool, + isolation_reason: str, + cost_drift_report: ExecutionCostDriftReport | None, +) -> None: + if fuse_halted or not isolation_healthy: + reasons = [] + if fuse_halted: + reasons.append("FUSE_HALTED") + if not isolation_healthy: + reasons.append(_sanitize_isolation_code(isolation_reason)) + cards.append( + OwnerDecisionCard( + card_id=f"fuse-isolation-{as_of_iso}", + card_type=CARD_TYPE_FUSE_OR_ISOLATION, + severity=CARD_SEVERITY_CRITICAL, + title="Safety halt active — new buys paused", + summary="FUSE or environment isolation tripped. Existing holdings stay put until you inspect and clear it.", + recommended_action="HOLD_HALT_AND_INSPECT", + evidence={ + "fuse_halted": fuse_halted, + "isolation_healthy": isolation_healthy, + "reasons": ",".join(reasons), + }, + ) + ) + + if cost_drift_report is not None and cost_drift_report.pause_promotion: + cards.append( + OwnerDecisionCard( + card_id=f"cost-drift-{as_of_iso}", + card_type=CARD_TYPE_COST_DRIFT, + severity=CARD_SEVERITY_WARNING, + title="Trading costs ran above model — promotion paused", + summary="Realized slippage or commissions crossed the safety cap. Capital upgrades are on hold until costs settle.", + recommended_action="PAUSE_CAPITAL_PROMOTION", + evidence={ + "sample_count": cost_drift_report.sample_count, + "median_slippage_bps": round(cost_drift_report.median_slippage_bps, 2), + "p95_slippage_bps": round(cost_drift_report.p95_slippage_bps, 2), + "breach_reasons": ",".join(cost_drift_report.breach_reasons), + }, + ) + ) + + +def _append_bayesian_cards( + cards: list[OwnerDecisionCard], + *, + as_of_date: date, + as_of_iso: str, + bayesian_reports: Sequence[BayesianConfidenceReport], +) -> None: + seen_buckets: set[str] = set() + for rep in bayesian_reports: + if not isinstance(rep, BayesianConfidenceReport): + raise ValueError("bayesian_reports must contain BayesianConfidenceReport instances") + if rep.bucket_id in seen_buckets: + raise ValueError(f"duplicate bayesian report for bucket {rep.bucket_id!r}") + seen_buckets.add(rep.bucket_id) + if rep.overall_status not in VALID_STATUSES: + raise ValueError(f"unsupported bayesian status: {rep.overall_status!r}") + if rep.recommended_action not in VALID_ACTIONS: + raise ValueError(f"unsupported bayesian action: {rep.recommended_action!r}") + if rep.latest_period_end is not None and rep.latest_period_end > as_of_date: + raise ValueError( + f"bayesian report for {rep.bucket_id} has period_end {rep.latest_period_end} after as_of_date {as_of_date}" + ) + if rep.overall_status == STATUS_GREEN: + continue + + sev = CARD_SEVERITY_CRITICAL if rep.overall_status == STATUS_RED else CARD_SEVERITY_WARNING + primary = rep.primary_source or "NONE" + action_hint = ( + "Consider pausing new deposits or suspending this bucket." + if rep.overall_status == STATUS_RED + else "Review whether to trim this bucket's target weight." + ) + cards.append( + OwnerDecisionCard( + card_id=f"bayesian-{rep.bucket_id.lower()}-{primary.lower()}-{as_of_iso}", + card_type=CARD_TYPE_BAYESIAN_DECAY, + severity=sev, + title=f"{rep.bucket_id} performance check: {rep.overall_status}", + summary=f"Recent {primary} quarters weakened. {action_hint} Strategy rules stay unchanged.", + recommended_action=rep.recommended_action, + evidence={ + "bucket_id": rep.bucket_id, + "primary_source": primary, + "status": rep.overall_status, + "reason_codes": _sanitize_bayesian_reasons(rep.reason_codes), + "parameter_mutation_allowed": False, + }, + ) + ) + + +def _append_tier_and_bucket_d_cards( + cards: list[OwnerDecisionCard], + *, + as_of_iso: str, + current_allocation: BucketAllocationPlan, + previous_tier: str | None, + bucket_d_forward_oos_months: int, + bucket_d_forward_oos_passed: bool, + expansion_allowed: bool, +) -> None: + if previous_tier is not None and current_allocation.capital_tier != previous_tier: + is_upgrade = _TIER_RANK[current_allocation.capital_tier] > _TIER_RANK[previous_tier] + if is_upgrade and expansion_allowed: + cards.append( + OwnerDecisionCard( + card_id=f"tier-crossing-{current_allocation.capital_tier.lower()}-{as_of_iso}", + card_type=CARD_TYPE_TIER_CROSSING, + severity=CARD_SEVERITY_INFO, + title=f"Capital crossed into {current_allocation.capital_tier}", + summary=f"Account moved from {previous_tier} to {current_allocation.capital_tier}. Review the updated bucket split and broker routing before turning it on.", + recommended_action="REVIEW_AND_APPROVE_TIER_CONFIG", + evidence={ + "previous_tier": previous_tier, + "new_tier": current_allocation.capital_tier, + "broker_route_count": len(current_allocation.broker_routes), + "bucket_d_eligible": current_allocation.bucket_d_eligible, + }, + ) + ) + elif not is_upgrade: + cards.append( + OwnerDecisionCard( + card_id=f"tier-regression-{current_allocation.capital_tier.lower()}-{as_of_iso}", + card_type=CARD_TYPE_TIER_CROSSING, + severity=CARD_SEVERITY_WARNING, + title=f"Capital stepped down to {current_allocation.capital_tier}", + summary=f"Account moved from {previous_tier} to {current_allocation.capital_tier}. New expansion is paused while existing positions stay intact.", + recommended_action="HOLD_EXISTING_AND_PAUSE_EXPANSION", + evidence={ + "previous_tier": previous_tier, + "new_tier": current_allocation.capital_tier, + "expansion_paused": True, + }, + ) + ) + + if ( + expansion_allowed + and current_allocation.capital_tier == TIER_3 + and current_allocation.bucket_d_eligible + and bucket_d_forward_oos_months >= 12 + and bucket_d_forward_oos_passed + and not current_allocation.bucket_d_active + ): + cards.append( + OwnerDecisionCard( + card_id=f"bucket-d-12m-review-{as_of_iso}", + card_type=CARD_TYPE_BUCKET_D_REVIEW, + severity=CARD_SEVERITY_INFO, + title="Bucket D passed 12-month forward check", + summary="Capital is above the $50k floor and 12 months of forward tracking passed. Decide whether to enable Bucket D.", + recommended_action="REVIEW_BUCKET_D_ACTIVATION", + evidence={ + "tier": current_allocation.capital_tier, + "forward_oos_months": bucket_d_forward_oos_months, + "forward_oos_passed": bucket_d_forward_oos_passed, + }, + ) + ) + + +def build_sentinel_decision_cards( + *, + as_of_date: date, + current_allocation: BucketAllocationPlan, + previous_tier: str | None = None, + bayesian_reports: Sequence[BayesianConfidenceReport] = (), + cost_drift_report: ExecutionCostDriftReport | None = None, + bucket_d_forward_oos_months: int = 0, + bucket_d_forward_oos_passed: bool = False, + fuse_halted: bool = False, + isolation_healthy: bool = True, + isolation_reason: str = "", +) -> SentinelDecisionBundle: + """Build deterministic, redacted web-console decision cards from offline reports.""" + _strict_date(as_of_date, "as_of_date") + if not isinstance(current_allocation, BucketAllocationPlan): + raise ValueError("current_allocation must be a BucketAllocationPlan") + if previous_tier is not None and previous_tier not in _TIER_RANK: + raise ValueError(f"unsupported previous_tier: {previous_tier!r}") + if cost_drift_report is not None and not isinstance(cost_drift_report, ExecutionCostDriftReport): + raise ValueError("cost_drift_report must be an ExecutionCostDriftReport or None") + _strict_non_neg_int(bucket_d_forward_oos_months, "bucket_d_forward_oos_months") + _strict_bool(bucket_d_forward_oos_passed, "bucket_d_forward_oos_passed") + _strict_bool(fuse_halted, "fuse_halted") + _strict_bool(isolation_healthy, "isolation_healthy") + if not isinstance(isolation_reason, str): + raise ValueError("isolation_reason must be a string") + + as_of_iso = as_of_date.isoformat() + cards: list[OwnerDecisionCard] = [] + + _append_safety_cards( + cards, + as_of_iso=as_of_iso, + fuse_halted=fuse_halted, + isolation_healthy=isolation_healthy, + isolation_reason=isolation_reason, + cost_drift_report=cost_drift_report, + ) + _append_bayesian_cards( + cards, + as_of_date=as_of_date, + as_of_iso=as_of_iso, + bayesian_reports=bayesian_reports, + ) + + cost_paused = cost_drift_report is not None and cost_drift_report.pause_promotion + expansion_allowed = ( + not fuse_halted + and isolation_healthy + and not current_allocation.expansion_paused + and not cost_paused + ) + _append_tier_and_bucket_d_cards( + cards, + as_of_iso=as_of_iso, + current_allocation=current_allocation, + previous_tier=previous_tier, + bucket_d_forward_oos_months=bucket_d_forward_oos_months, + bucket_d_forward_oos_passed=bucket_d_forward_oos_passed, + expansion_allowed=expansion_allowed, + ) + + return SentinelDecisionBundle(as_of_date=as_of_date, cards=tuple(cards)) diff --git a/tests/test_bayesian_confidence_monitor.py b/tests/test_bayesian_confidence_monitor.py new file mode 100644 index 00000000..ae5bdae6 --- /dev/null +++ b/tests/test_bayesian_confidence_monitor.py @@ -0,0 +1,132 @@ +from dataclasses import replace +from datetime import date, datetime + +import pytest + +from quant_platform_kit.risk.bayesian_confidence_monitor import ( + ACTION_HOLD_CONFIG, + ACTION_PAUSE_CONTRIBUTIONS, + ACTION_REVIEW_REDUCE_WEIGHT, + ACTION_SUSPEND_BUCKET, + STATUS_GREEN, + STATUS_RED, + STATUS_YELLOW, + BayesianMonitorConfig, + QuarterlyBucketObservation, + evaluate_bucket_bayesian_confidence, + evaluate_source_posterior, +) + + +def test_source_separation_never_pools_shadow_paper_live() -> None: + obs = [ + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 3, 31), 0.04, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 6, 30), 0.03, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 9, 30), 0.05, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 12, 31), 0.04, False), + QuarterlyBucketObservation("BUCKET_B", "LIVE", date(2027, 3, 31), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "LIVE", date(2027, 6, 30), -0.04, True), + QuarterlyBucketObservation("BUCKET_B", "LIVE", date(2027, 9, 30), -0.06, True), + QuarterlyBucketObservation("BUCKET_B", "LIVE", date(2027, 12, 31), -0.05, True), + ] + report = evaluate_bucket_bayesian_confidence("BUCKET_B", obs) + assert report.primary_source == "LIVE" + assert report.latest_period_end == date(2027, 12, 31) + assert report.by_source["SHADOW"].status == STATUS_GREEN + assert report.by_source["LIVE"].status == STATUS_RED + assert report.overall_status == STATUS_RED + assert report.recommended_action == ACTION_SUSPEND_BUCKET + assert report.parameter_mutation_allowed is False + assert report.auto_execution_allowed is False + with pytest.raises(ValueError, match="init=False"): + replace(report, parameter_mutation_allowed=True) # type: ignore[misc] + + +def test_insufficient_live_sample_does_not_mask_paper_red_alert() -> None: + obs = [ + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 3, 31), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 6, 30), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 9, 30), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 12, 31), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "LIVE", date(2027, 3, 31), 0.01, False), + ] + report = evaluate_bucket_bayesian_confidence("BUCKET_B", obs) + assert report.primary_source == "LIVE" + assert report.by_source["LIVE"].sufficient_samples is False + assert report.by_source["PAPER"].status == STATUS_RED + assert report.overall_status == STATUS_RED + assert report.recommended_action == ACTION_SUSPEND_BUCKET + + +def test_inactive_channels_and_arithmetic_excess_below_minus_one() -> None: + inactive_obs = [ + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 3, 31), -1.10, True, is_active_channel=False), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 6, 30), -0.10, True, is_active_channel=False), + ] + report = evaluate_bucket_bayesian_confidence("BUCKET_B", inactive_obs) + assert report.primary_source is None + assert report.latest_period_end is None + assert report.by_source["PAPER"].sample_count == 0 + assert report.by_source["PAPER"].ignored_inactive_count == 2 + assert report.overall_status == STATUS_GREEN + assert report.recommended_action == ACTION_HOLD_CONFIG + + +def test_yellow_red_and_early_breach_requires_actual_breaches() -> None: + yellow_obs = [ + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 3, 31), -0.025, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 6, 30), -0.020, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 9, 30), -0.025, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 12, 31), -0.020, False), + ] + y_rep = evaluate_source_posterior("BUCKET_B", "SHADOW", yellow_obs) + assert y_rep.status == STATUS_YELLOW + assert y_rep.recommended_action == ACTION_REVIEW_REDUCE_WEIGHT + + red_obs = [ + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 3, 31), -0.05, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 6, 30), -0.05, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 9, 30), -0.05, False), + QuarterlyBucketObservation("BUCKET_B", "SHADOW", date(2026, 12, 31), -0.05, False), + ] + r_rep = evaluate_source_posterior("BUCKET_B", "SHADOW", red_obs) + assert r_rep.status == STATUS_RED + assert r_rep.recommended_action == ACTION_PAUSE_CONTRIBUTIONS + + # Pessimistic prior with ZERO actual breaches must NOT fire early warning + pessimistic_cfg = BayesianMonitorConfig(prior_breach_alpha=8.0, prior_breach_beta=1.0, min_quarters_for_action=4) + zero_breach = [ + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 3, 31), 0.0, False), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 6, 30), 0.0, False), + ] + zb_rep = evaluate_source_posterior("BUCKET_B", "PAPER", zero_breach, config=pessimistic_cfg) + assert zb_rep.status == STATUS_GREEN + + # 2 actual drawdown breaches fire early YELLOW (never RED before min_quarters) + two_breach = [ + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 3, 31), 0.0, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 6, 30), 0.0, True), + ] + tb_rep = evaluate_source_posterior("BUCKET_B", "PAPER", two_breach, config=pessimistic_cfg) + assert tb_rep.status == STATUS_YELLOW + assert "EARLY_DRAWDOWN_BREACH_WARNING" in tb_rep.reason_codes + + +def test_bayesian_monitor_rejects_same_quarter_and_invalid_inputs() -> None: + with pytest.raises(ValueError, match="datetime.date"): + QuarterlyBucketObservation("BUCKET_B", "SHADOW", datetime(2026, 3, 31), 0.01, False) # type: ignore[arg-type] + with pytest.raises(ValueError, match="duplicate calendar quarter"): + evaluate_source_posterior( + "BUCKET_B", + "PAPER", + [ + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 1, 1), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 1, 2), -0.05, True), + ], + ) + with pytest.raises(ValueError, match="within"): + BayesianMonitorConfig(prior_breach_alpha=1e308, prior_breach_beta=1e308) + with pytest.raises(ValueError, match="BayesianMonitorConfig"): + evaluate_source_posterior("BUCKET_B", "SHADOW", [], config=False) # type: ignore[arg-type] + with pytest.raises(ValueError, match="not a string"): + evaluate_bucket_bayesian_confidence("BUCKET_B", "") # type: ignore[arg-type] diff --git a/tests/test_multi_tier_shadow_ledger.py b/tests/test_multi_tier_shadow_ledger.py new file mode 100644 index 00000000..e52baf4b --- /dev/null +++ b/tests/test_multi_tier_shadow_ledger.py @@ -0,0 +1,146 @@ +from dataclasses import replace +from datetime import date + +import pytest + +from quant_platform_kit.risk.bucket_capital_ladder import TIER_1, TIER_2, TIER_3, BucketLadderConfig +from quant_platform_kit.risk.multi_tier_shadow_ledger import ( + DEFAULT_SHADOW_TIERS, + ShadowRebalanceStep, + ShadowTierSpec, + run_multi_tier_shadow_ledger, +) + + +def test_default_three_tiers_run_simultaneously_with_contributions_and_benchmarks() -> None: + steps = [ + ShadowRebalanceStep( + session_date=date(2026, 12, 1), + prices_usd={"VTI": 280.0, "QLD": 100.0, "SGOV": 100.0, "SPY": 590.0, "QQQ": 500.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={"QLD": 1.0}, + apply_monthly_contribution=False, + ), + ShadowRebalanceStep( + session_date=date(2027, 1, 4), + prices_usd={"VTI": 294.0, "QLD": 110.0, "SGOV": 100.4, "SPY": 605.0, "QQQ": 520.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={"QLD": 1.0}, + apply_monthly_contribution=True, + ), + ShadowRebalanceStep( + session_date=date(2027, 2, 1), + prices_usd={"VTI": 300.0, "QLD": 95.0, "SGOV": 100.8, "SPY": 610.0, "QQQ": 505.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={"SGOV": 1.0}, + apply_monthly_contribution=True, + ), + ] + report = run_multi_tier_shadow_ledger( + iter(steps), + tiers=iter(DEFAULT_SHADOW_TIERS), + slippage_bps=10.0, + benchmark_symbols=("SPY", "QQQ"), + ) + assert report.read_only_shadow is True + assert report.step_count == 3 + with pytest.raises(ValueError, match="init=False"): + replace(report, read_only_shadow=False) # type: ignore[misc] + + t1 = report.tiers["TIER1_1500"] + t2 = report.tiers["TIER2_15000"] + t3 = report.tiers["TIER3_50000"] + assert t1.total_contributions_usd == pytest.approx(2_100.0) + assert t2.total_contributions_usd == pytest.approx(15_600.0) + assert t3.total_contributions_usd == pytest.approx(50_600.0) + assert t1.final_capital_tier == TIER_1 + assert t2.final_capital_tier == TIER_2 + assert t3.final_capital_tier == TIER_3 + assert t3.mean_idle_cash_ratio < t1.mean_idle_cash_ratio + assert t1.benchmark_comparison is not None + assert "SPY" in t1.benchmark_comparison.benchmarks + + +def test_bucket_d_cap_holds_with_zero_and_positive_ab_overlap() -> None: + # Zero weight in Bucket A for NVDA must NOT disable Bucket D 2% cap ($1,000 -> 10 shares) + zero_overlap = ShadowRebalanceStep( + session_date=date(2027, 1, 4), + prices_usd={"VTI": 250.0, "QLD": 100.0, "NVDA": 100.0}, + bucket_a_weights={"VTI": 1.0, "NVDA": 0.0}, + bucket_b_weights={"QLD": 1.0}, + bucket_d_weights={"NVDA": 1.0}, + bucket_d_forward_oos_passed=True, + bucket_d_owner_approved=True, + ) + rep_zero = run_multi_tier_shadow_ledger( + [zero_overlap], + ladder_config=BucketLadderConfig(bucket_d_weight=0.10), + slippage_bps=0.0, + ) + assert "NVDA" not in rep_zero.tiers["TIER1_1500"].ending_holdings + assert rep_zero.tiers["TIER3_50000"].ending_holdings["NVDA"] == 10 + + # Positive weight overlap: Bucket A (60% * 10% = $3,000) + capped Bucket D ($1,000) = $4,000 -> 40 shares + pos_overlap = ShadowRebalanceStep( + session_date=date(2027, 1, 4), + prices_usd={"VTI": 250.0, "QLD": 100.0, "NVDA": 100.0}, + bucket_a_weights={"VTI": 0.9, "NVDA": 0.1}, + bucket_b_weights={"QLD": 1.0}, + bucket_d_weights={"NVDA": 1.0}, + bucket_d_forward_oos_passed=True, + bucket_d_owner_approved=True, + ) + rep_pos = run_multi_tier_shadow_ledger( + [pos_overlap], + ladder_config=BucketLadderConfig(bucket_d_weight=0.10), + slippage_bps=0.0, + ) + assert rep_pos.tiers["TIER3_50000"].ending_holdings["NVDA"] == 40 + + +def test_expansion_paused_and_fuse_halted_block_new_buys() -> None: + paused_step = ShadowRebalanceStep( + session_date=date(2027, 1, 4), + prices_usd={"VTI": 100.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={}, + expansion_paused=True, + ) + rep_paused = run_multi_tier_shadow_ledger([paused_step], tiers=(ShadowTierSpec("T", 50_000.0),), slippage_bps=0.0) + assert rep_paused.tiers["T"].ending_holdings == {} + + halted_step = ShadowRebalanceStep( + session_date=date(2027, 1, 4), + prices_usd={"VTI": 100.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={}, + fuse_halted=True, + ) + rep_halted = run_multi_tier_shadow_ledger([halted_step], tiers=(ShadowTierSpec("T", 50_000.0),), slippage_bps=0.0) + assert rep_halted.tiers["T"].rebalance_count == 0 + assert rep_halted.step_count == 1 + + +def test_shadow_ledger_rejects_invalid_inputs() -> None: + s1 = ShadowRebalanceStep( + session_date=date(2027, 1, 4), + prices_usd={"VTI": 250.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={}, + apply_monthly_contribution=True, + ) + s2 = ShadowRebalanceStep( + session_date=date(2027, 1, 15), + prices_usd={"VTI": 250.0}, + bucket_a_weights={"VTI": 1.0}, + bucket_b_weights={}, + apply_monthly_contribution=True, + ) + with pytest.raises(ValueError, match="duplicate monthly contribution"): + run_multi_tier_shadow_ledger([s1, s2]) + with pytest.raises(ValueError, match="missing benchmark price"): + run_multi_tier_shadow_ledger([s1], benchmark_symbols=("SPY",)) + with pytest.raises(ValueError, match="slippage_bps must be < 5000"): + run_multi_tier_shadow_ledger([replace(s1, fuse_halted=True)], slippage_bps=5000.0) + with pytest.raises(ValueError, match="BucketLadderConfig"): + run_multi_tier_shadow_ledger([s1], ladder_config={}) # type: ignore[arg-type] diff --git a/tests/test_sentinel_decision_cards.py b/tests/test_sentinel_decision_cards.py new file mode 100644 index 00000000..c2352bf8 --- /dev/null +++ b/tests/test_sentinel_decision_cards.py @@ -0,0 +1,146 @@ +from dataclasses import replace +from datetime import date +import json + +import pytest + +from quant_platform_kit.risk.bayesian_confidence_monitor import ( + QuarterlyBucketObservation, + evaluate_bucket_bayesian_confidence, +) +from quant_platform_kit.risk.bucket_capital_ladder import ( + TIER_1, + TIER_2, + BucketLadderConfig, + evaluate_bucket_allocation, +) +from quant_platform_kit.risk.execution_cost_drift import ( + ExecutionCostDriftConfig, + FillCostObservation, + evaluate_execution_cost_drift, +) +from quant_platform_kit.risk.sentinel_decision_cards import ( + CARD_SEVERITY_CRITICAL, + CARD_SEVERITY_INFO, + CARD_SEVERITY_WARNING, + CARD_TYPE_BAYESIAN_DECAY, + CARD_TYPE_BUCKET_D_REVIEW, + CARD_TYPE_COST_DRIFT, + CARD_TYPE_FUSE_OR_ISOLATION, + CARD_TYPE_TIER_CROSSING, + OwnerDecisionCard, + build_sentinel_decision_cards, +) + + +def test_healthy_upgrade_emits_tier_and_bucket_d_cards_and_strict_json() -> None: + alloc = evaluate_bucket_allocation(investable_nav_usd=55_000.0, bucket_d_approved=False) + bayes_red = evaluate_bucket_bayesian_confidence( + "BUCKET_B", + [ + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 3, 31), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 6, 30), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 9, 30), -0.05, True), + QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2026, 12, 31), -0.05, True), + ], + ) + bundle = build_sentinel_decision_cards( + as_of_date=date(2026, 12, 31), + current_allocation=alloc, + previous_tier=TIER_2, + bayesian_reports=(bayes_red,), + bucket_d_forward_oos_months=12, + bucket_d_forward_oos_passed=True, + ) + assert bundle.read_only_sentinel is True + assert bundle.auto_execute_allowed is False + assert bundle.highest_severity == CARD_SEVERITY_CRITICAL + assert bundle.pending_signoff_count == 3 + assert [c.card_type for c in bundle.cards] == [ + CARD_TYPE_BAYESIAN_DECAY, + CARD_TYPE_BUCKET_D_REVIEW, + CARD_TYPE_TIER_CROSSING, + ] + payload = json.dumps(bundle.to_dict(), allow_nan=False) + assert '"auto_execute": false' in payload + with pytest.raises(ValueError, match="init=False"): + replace(bundle, auto_execute_allowed=True) # type: ignore[misc] + + +def test_cost_drift_and_isolation_suppress_expansion_and_sanitize_reasons() -> None: + alloc = evaluate_bucket_allocation(investable_nav_usd=55_000.0, bucket_d_approved=False) + drift = evaluate_execution_cost_drift( + [ + FillCostObservation(date(2026, 12, d), "QLD", "BUY", 10.0, 100.0, 100.30, 0.35, 0.35) + for d in range(1, 6) + ], + config=ExecutionCostDriftConfig(max_median_slippage_bps=15.0, min_sample_count=5), + ) + bundle = build_sentinel_decision_cards( + as_of_date=date(2026, 12, 31), + current_allocation=alloc, + previous_tier=TIER_2, + cost_drift_report=drift, + bucket_d_forward_oos_months=12, + bucket_d_forward_oos_passed=True, + isolation_healthy=False, + isolation_reason="private-host.internal.example", + ) + assert [c.card_type for c in bundle.cards] == [CARD_TYPE_FUSE_OR_ISOLATION, CARD_TYPE_COST_DRIFT] + assert bundle.cards[0].evidence["reasons"] == "ISOLATION_UNHEALTHY" + + +def test_bucket_d_hard_50k_floor_respected_even_with_custom_tier3_min() -> None: + alloc = evaluate_bucket_allocation( + investable_nav_usd=30_000.0, + config=BucketLadderConfig(tier3_min_usd=25_000.0), + ) + assert alloc.bucket_d_eligible is False + bundle = build_sentinel_decision_cards( + as_of_date=date(2026, 12, 31), + current_allocation=alloc, + previous_tier=TIER_1, + bucket_d_forward_oos_months=12, + bucket_d_forward_oos_passed=True, + ) + assert [c.card_type for c in bundle.cards] == [CARD_TYPE_TIER_CROSSING] + + +def test_rejects_future_reports_duplicate_buckets_and_non_scalar_evidence() -> None: + alloc = evaluate_bucket_allocation(investable_nav_usd=1_500.0) + bayes = evaluate_bucket_bayesian_confidence( + "BUCKET_B", + [QuarterlyBucketObservation("BUCKET_B", "PAPER", date(2027, 3, 31), -0.05, True)], + ) + with pytest.raises(ValueError, match="after as_of_date"): + build_sentinel_decision_cards( + as_of_date=date(2026, 12, 31), + current_allocation=alloc, + bayesian_reports=(bayes,), + ) + with pytest.raises(ValueError, match="duplicate bayesian report"): + build_sentinel_decision_cards( + as_of_date=date(2027, 3, 31), + current_allocation=alloc, + bayesian_reports=(bayes, bayes), + ) + with pytest.raises(ValueError, match="JSON-safe scalar"): + OwnerDecisionCard( + card_id="bad", + card_type=CARD_TYPE_TIER_CROSSING, + severity=CARD_SEVERITY_WARNING, + title="Bad", + summary="Bad", + recommended_action="NOOP", + evidence={"bad": []}, # type: ignore[dict-item] + ) + with pytest.raises(ValueError, match="finite float"): + OwnerDecisionCard( + card_id="bad-nan", + card_type=CARD_TYPE_TIER_CROSSING, + severity=CARD_SEVERITY_INFO, + title="Bad", + summary="Bad", + recommended_action="NOOP", + evidence={"x": float("nan")}, + )