Coverage for execution/paper_readiness_report.py: 100%
64 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"""Offline paper-trading readiness report (Phase V2-21).
3main.py cannot compute this itself - it never opens its own Postgres
4connection (same invariant retraining/status_export.py's docstring
5describes). This module is the sole writer of
6visualization/grafana/paper_readiness_report.json; monitoring/api_server.py
7merges that file into /api/state server-side, and `aq paper-readiness`
8(aq_cli.py) runs this as a human-invoked gate before flipping
9phase_v2.runtime.mode to "paper".
10"""
12from __future__ import annotations
14import json
15import logging
16import sys
17from datetime import datetime, timezone
18from pathlib import Path
20from execution.paper_readiness import evaluate_observation_readiness, evaluate_paper_broker_config, evaluate_velocity_decision
21from execution.paper_readiness_io import fetch_observation_mode_events
22from execution.secrets_io import secret_env
23from experience.observation_metrics import compute_observation_summary
24from json_safety import atomic_write_json
26logger = logging.getLogger(__name__)
28ROOT_DIR = Path(__file__).resolve().parent.parent
29DEFAULT_CONFIG_PATH = ROOT_DIR / "config.json"
30DEFAULT_REPORT_PATH = ROOT_DIR / "visualization" / "grafana" / "paper_readiness_report.json"
33def live_broker_view(config: dict) -> tuple[bool, str]:
34 """`evaluate_live_broker_config` with the inputs main.py passes it: the paper flags, whether live credentials are present,
35 the phase6 risk posture, phase_v2.live and the runtime Postgres DSN."""
36 from execution.live_credentials import credentials_present
37 from execution.live_credentials_io import load_live_credentials, load_postgres_dsn
38 from execution.paper_readiness import evaluate_live_broker_config
40 phase_v2 = config.get("phase_v2", {})
41 risk = config.get("phase6", {}).get("risk", {})
42 return evaluate_live_broker_config(
43 phase_v2.get("paper_trading", {}),
44 credentials_present(load_live_credentials()),
45 risk_config={
46 "max_daily_drawdown_pct": float(risk.get("max_daily_drawdown_pct", 0.03)),
47 "max_total_drawdown_pct": float(risk.get("max_total_drawdown_pct", 0.12)),
48 "liquidate_on_risk_breach": bool(risk.get("liquidate_on_risk_breach", True)),
49 },
50 live_config=phase_v2.get("live", {}),
51 postgres_dsn=load_postgres_dsn(),
52 )
55def build_paper_readiness_view(conn, config: dict) -> dict:
56 """Returns the full paper_readiness_report.json payload.
58 {generated_at, ready, checks, blocking_reasons, broker_config_present,
59 broker_config_reason, observation_summary}
60 """
61 paper_trading_config = config.get("phase_v2", {}).get("paper_trading", {})
62 thresholds = paper_trading_config.get("readiness_thresholds", {})
64 events = fetch_observation_mode_events(conn)
65 summary = compute_observation_summary(events)
66 observation_readiness = evaluate_observation_readiness(summary, thresholds)
67 broker_config_present, broker_config_reason = evaluate_paper_broker_config(paper_trading_config)
69 blocking_reasons = list(observation_readiness["blocking_reasons"])
70 if not broker_config_present:
71 blocking_reasons.append(broker_config_reason)
72 velocity_decided, velocity_reason = evaluate_velocity_decision(config)
73 if not velocity_decided:
74 blocking_reasons.append(velocity_reason)
76 live_present, live_reason = live_broker_view(config)
78 return {
79 "generated_at": datetime.now(timezone.utc).isoformat(),
80 "ready": observation_readiness["ready"] and broker_config_present and velocity_decided,
81 # V6.6.5 (#352): main.py's live gate, computed offline too (it was only ever seen at runtime). Reported, not
82 # part of `ready`, which is the paper gate; `aq live-readiness` is the scorecard for live capital.
83 "live_broker_config_present": live_present,
84 "live_broker_config_reason": live_reason,
85 "velocity_decision": velocity_reason,
86 "checks": observation_readiness["checks"],
87 "blocking_reasons": blocking_reasons,
88 "broker_config_present": broker_config_present,
89 "broker_config_reason": broker_config_reason,
90 "observation_summary": summary,
91 }
94def write_paper_readiness_file(view: dict, path: Path = DEFAULT_REPORT_PATH) -> None:
95 # V5.4.7 (Problems.md #120): atomic + finite-safe.
96 atomic_write_json(path, view, indent=2)
99def _print_summary(view: dict) -> None:
100 status = "READY" if view["ready"] else "NOT READY"
101 print(f"Paper trading readiness: {status}")
102 for name, check in view["checks"].items():
103 mark = "PASS" if check["pass"] else "FAIL"
104 print(f" [{mark}] {name}: value={check['value']} threshold={check['threshold']}")
105 broker_mark = "PASS" if view["broker_config_present"] else "FAIL"
106 print(f" [{broker_mark}] broker_config: {view['broker_config_reason']}")
107 if view["blocking_reasons"]:
108 print("Blocking reasons: " + ", ".join(view["blocking_reasons"]))
111def main() -> int:
112 logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s — %(message)s")
114 with DEFAULT_CONFIG_PATH.open("r", encoding="utf-8") as f:
115 config = json.load(f)
117 import psycopg
119 dsn = secret_env("POSTGRES_DSN", "")
120 conn = psycopg.connect(dsn, autocommit=False)
121 try:
122 view = build_paper_readiness_view(conn, config)
123 finally:
124 conn.close()
126 write_paper_readiness_file(view)
127 _print_summary(view)
128 return 0 if view["ready"] else 1
131if __name__ == "__main__":
132 sys.exit(main())