Coverage for execution/paper_readiness.py: 100%
71 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Pure, Lean-free paper/live broker-readiness gating (Phase V2-21/V2-22).
3`execution/order_gate.py::resolve_order_permission()` already implements the
4correct mode -> real-vs-simulated decision table, but the `broker_config_present`
5flag it depends on used to be `bool(self.paper_brokerage)` in `main.py` - a
6string that is never empty by construction, so the check was a no-op. This
7module is what actually decides whether that flag should be True, for both
8`paper` mode (Lean's built-in PaperBrokerage, no real credentials needed) and
9`live` mode (V2-22, real broker credentials).
11No imports from AlgorithmImports/QCAlgorithm/psycopg live here on purpose -
12see execution/paper_readiness_io.py for the IO layer that feeds these
13functions, and execution/paper_readiness_report.py for the offline report
14that additionally evaluates observation-mode readiness.
15"""
17from __future__ import annotations
19from typing import Any
21_PAPER_REASON_ALL_CONFIRMED = "paper_broker_config_confirmed"
22_PAPER_REASON_MISSING_BROKERAGE = "paper_broker_config_missing_brokerage"
23_PAPER_REASON_MISSING_DATA_PROVIDER = "paper_broker_config_missing_live_data_provider"
24_PAPER_REASON_MISSING_MANUAL_REVIEW = "paper_broker_config_missing_manual_review"
26_LIVE_REASON_ALL_CONFIRMED = "live_broker_config_confirmed"
27_LIVE_REASON_PAPER_NOT_READY = "live_broker_config_paper_corridor_not_ready"
28_LIVE_REASON_MISSING_CREDENTIALS = "live_broker_config_missing_credentials"
29_LIVE_REASON_RISK_POSTURE_UNSAFE = "live_broker_config_risk_posture_unsafe"
30_LIVE_REASON_UNSAFE_DB_PASSWORD = "live_broker_config_unsafe_db_password"
33def evaluate_paper_broker_config(paper_trading_config: dict[str, Any]) -> tuple[bool, str]:
34 """mode='paper' gate. All three must be true:
35 - brokerage is a non-empty known value
36 - live_data_provider_configured (human-set attestation - a live market
37 data feed is required for Lean's live-paper environment even though
38 PaperBrokerage itself needs no broker credentials)
39 - manual_review_confirmed (human-set attestation, replaces the old
40 phase6.paper_trading.ready_for_live_paper stub)
41 """
42 if not str(paper_trading_config.get("brokerage", "")).strip():
43 return False, _PAPER_REASON_MISSING_BROKERAGE
44 if not bool(paper_trading_config.get("live_data_provider_configured", False)):
45 return False, _PAPER_REASON_MISSING_DATA_PROVIDER
46 if not bool(paper_trading_config.get("manual_review_confirmed", False)):
47 return False, _PAPER_REASON_MISSING_MANUAL_REVIEW
48 return True, _PAPER_REASON_ALL_CONFIRMED
51def evaluate_live_risk_posture(risk_config: dict[str, Any], live_config: dict[str, Any]) -> tuple[bool, str]:
52 """Sanity ceiling for mode='live' - not a redesign of the drawdown
53 circuit breaker, just a guard against live mode running with an
54 accidentally-loose (or disabled) risk config that was fine for
55 paper/observation but is unacceptable once real capital is at risk."""
56 max_daily_drawdown_pct = float(risk_config.get("max_daily_drawdown_pct", 1.0))
57 max_total_drawdown_pct = float(risk_config.get("max_total_drawdown_pct", 1.0))
58 liquidate_on_risk_breach = bool(risk_config.get("liquidate_on_risk_breach", False))
60 allowed_daily = float(live_config.get("max_allowed_daily_drawdown_pct", 0.0))
61 allowed_total = float(live_config.get("max_allowed_total_drawdown_pct", 0.0))
63 if not liquidate_on_risk_breach:
64 return False, _LIVE_REASON_RISK_POSTURE_UNSAFE
65 if max_daily_drawdown_pct > allowed_daily:
66 return False, _LIVE_REASON_RISK_POSTURE_UNSAFE
67 if max_total_drawdown_pct > allowed_total:
68 return False, _LIVE_REASON_RISK_POSTURE_UNSAFE
69 return True, _LIVE_REASON_ALL_CONFIRMED
72def evaluate_live_broker_config(
73 paper_trading_config: dict[str, Any],
74 live_credentials_present: bool,
75 risk_config: dict[str, Any] | None = None,
76 live_config: dict[str, Any] | None = None,
77 postgres_dsn: str | None = None,
78) -> tuple[bool, str]:
79 """mode='live' gate (V2-22). You cannot go straight to live without a
80 validated paper corridor - the paper check must also pass - AND real
81 broker credentials must be present AND (if risk/live config supplied)
82 the live risk posture must be safe AND (if a Postgres DSN is supplied) it
83 must not still use the published dev-default password.
85 `postgres_dsn` is optional and defaults to None (unchecked) so existing
86 callers/tests are unaffected; main.py threads the real DSN through so a
87 live run against the public default password fails closed."""
88 paper_ready, _paper_reason = evaluate_paper_broker_config(paper_trading_config)
89 if not paper_ready:
90 return False, _LIVE_REASON_PAPER_NOT_READY
92 if not live_credentials_present:
93 return False, _LIVE_REASON_MISSING_CREDENTIALS
95 if postgres_dsn is not None:
96 from execution.live_credentials import postgres_dsn_is_live_safe
98 if not postgres_dsn_is_live_safe(postgres_dsn):
99 return False, _LIVE_REASON_UNSAFE_DB_PASSWORD
101 if risk_config is not None and live_config is not None:
102 risk_ok, _ = evaluate_live_risk_posture(risk_config, live_config)
103 if not risk_ok:
104 return False, _LIVE_REASON_RISK_POSTURE_UNSAFE
106 return True, _LIVE_REASON_ALL_CONFIRMED
109def evaluate_broker_config(
110 mode: str,
111 paper_trading_config: dict[str, Any],
112 live_credentials_present: bool = False,
113 risk_config: dict[str, Any] | None = None,
114 live_config: dict[str, Any] | None = None,
115 postgres_dsn: str | None = None,
116) -> tuple[bool, str]:
117 """Single entrypoint main.py._order_permission() calls regardless of
118 mode - dispatches to the two functions above. Any mode other than
119 'live' (including 'backtest'/'observation', where the result is unused
120 since resolve_order_permission() never consults broker_config_present
121 for those modes) goes through the paper path."""
122 if mode == "live":
123 return evaluate_live_broker_config(
124 paper_trading_config,
125 live_credentials_present,
126 risk_config,
127 live_config,
128 postgres_dsn,
129 )
130 return evaluate_paper_broker_config(paper_trading_config)
133def evaluate_velocity_decision(config: dict[str, Any]) -> tuple[bool, str]:
134 """A target-weights run must not reach a broker on a velocity setting nobody decided (Problems.md #278). `R-VEL1` records it in
135 `phase_v2.target_weights.velocity_decision`, whichever way it went. Any other path has its own gates."""
136 target = ((config or {}).get("phase_v2") or {}).get("target_weights") or {}
137 if not target.get("enabled"):
138 return True, "not_on_the_target_path"
139 decision = str(target.get("velocity_decision") or "").strip()
140 return (True, f"velocity_decision: {decision}") if decision else (False, "target_weights_velocity_decision_missing")
143def evaluate_observation_readiness(summary: dict[str, Any], thresholds: dict[str, Any]) -> dict[str, Any]:
144 """Turns 4 of the 5 bullets in development/infrastructure.md's "Paper"
145 checklist into code, given an already-computed
146 observation summary (experience.observation_metrics.compute_observation_summary()
147 output) and threshold config. The 5th bullet (manual review of trade
148 history for plausible entry/exit prices) is deliberately NOT automated -
149 it stays a human judgment call, surfaced via paper_trading_config's
150 manual_review_confirmed flag (see evaluate_paper_broker_config above).
151 """
152 min_observations = int(thresholds.get("min_observations", 500))
153 min_simulated_sharpe = float(thresholds.get("min_simulated_sharpe", 0.3))
154 max_simulated_drawdown_floor = float(thresholds.get("max_simulated_drawdown_floor", -0.15))
155 max_single_rejection_reason_share = float(thresholds.get("max_single_rejection_reason_share", 0.5))
157 count_observations = int(summary.get("count_observations", 0))
158 simulated_sharpe = float(summary.get("simulated_sharpe", 0.0))
159 simulated_max_drawdown = float(summary.get("simulated_max_drawdown", 0.0))
160 rejected_by_reason = summary.get("rejected_by_reason") or {}
161 total_rejections = sum(rejected_by_reason.values())
162 top_rejection_share = (max(rejected_by_reason.values()) / total_rejections) if total_rejections > 0 else 0.0
164 checks = {
165 "observation_count": {
166 "pass": count_observations >= min_observations,
167 "value": count_observations,
168 "threshold": min_observations,
169 },
170 "simulated_sharpe": {
171 "pass": simulated_sharpe >= min_simulated_sharpe,
172 "value": simulated_sharpe,
173 "threshold": min_simulated_sharpe,
174 },
175 "simulated_max_drawdown": {
176 "pass": simulated_max_drawdown >= max_simulated_drawdown_floor,
177 "value": simulated_max_drawdown,
178 "threshold": max_simulated_drawdown_floor,
179 },
180 "dominant_rejection_reason": {
181 "pass": top_rejection_share <= max_single_rejection_reason_share,
182 "value": top_rejection_share,
183 "threshold": max_single_rejection_reason_share,
184 },
185 }
187 blocking_reasons = [name for name, check in checks.items() if not check["pass"]]
189 return {
190 "ready": len(blocking_reasons) == 0,
191 "checks": checks,
192 "blocking_reasons": blocking_reasons,
193 }