Coverage for monitoring/assets_status.py: 100%
45 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"""Multi-asset-class (IB/futures/options/FRED) readiness report.
3Pure, read-only report builder shared by two consumers so the readiness
4logic is defined exactly once: `aq_cli.py::cmd_assets()` (prints it to the
5terminal) and `monitoring/api_server.py`'s `/api/assets-status` endpoint
6(serves it to the webui). Computed live on every call - matches
7`monitoring/neural_network_state.py::build_neural_network_state()`'s
8"compute on read" precedent rather than the paper-readiness/retraining-
9status pattern of a periodic worker writing a cached JSON file, since every
10input here (config.json, lean.json, the local FRED cache file, the static
11futures contract specs file) is a cheap local read, not a heavy computation
12worth caching.
13"""
15from __future__ import annotations
17from pathlib import Path
19from data_pipeline.fred_backfill import load_cached_fred_series
20from data_pipeline.ib_backfill import ib_readiness_status, load_futures_contract_specs
21from risk.forex_risk import load_forex_pair_specs
23ROOT_DIR = Path(__file__).resolve().parent.parent
24CONFIG_PATH = ROOT_DIR / "config.json"
25LEAN_JSON_PATH = ROOT_DIR / "lean.json"
28def build_sleeve_status(config: dict, runtime_guards: dict | None = None) -> dict:
29 """V5.8.0 - what each class sleeve / overlay is set to (from config.json) and, when the algorithm has written one,
30 each guard's live state (`visualization/state.json` -> `sleeve_guards`). Pure; a missing block reads as disabled."""
31 phase_v2 = config.get("phase_v2", {})
32 guards = phase_v2.get("sleeve_guards", {})
33 runtime_guards = runtime_guards or {}
35 def _guard(name: str) -> dict:
36 settings = guards.get(name, {}) or {}
37 return {
38 "enabled": bool(settings.get("enabled", False)),
39 "max_loss_fraction_nav": settings.get("max_loss_fraction_nav"),
40 "lookback_bars": settings.get("lookback_bars"),
41 "cooldown_bars": settings.get("cooldown_bars"),
42 "runtime": runtime_guards.get(name),
43 }
45 forex, bond = phase_v2.get("forex_sleeve", {}) or {}, phase_v2.get("bond_sleeve", {}) or {}
46 crypto_caps = (phase_v2.get("class_weight_caps", {}) or {}).get("crypto", {}) or {}
47 dynamic_risk = phase_v2.get("dynamic_risk", {}) or {}
48 sweep = phase_v2.get("cash_sweep", {}) or {}
49 return {
50 # V6.2.0's T-bill sweep (V6.3.0: shown here, the engine deploy check reads it)
51 "cash_sweep": {"enabled": bool(sweep.get("enabled", False)), "ticker": sweep.get("ticker"),
52 "max_weight": sweep.get("max_weight"), "margin_leverage": sweep.get("margin_leverage"),
53 "exclude_from_risk_controls": bool(sweep.get("exclude_from_risk_controls", False))},
54 "forex_sleeve": {"enabled": bool(forex.get("enabled", False)) and bool(phase_v2.get("forex_risk", {}).get("enabled", False)),
55 "signal": forex.get("signal", "model_rank"), "gross_budget": forex.get("gross_budget"), "guard": _guard("forex")},
56 "bond_sleeve": {"enabled": bool(bond.get("enabled", False)), "signal": bond.get("signal", "model_rank"),
57 "gross_budget": bond.get("gross_budget"), "guard": _guard("bond")},
58 "crypto_graduates": {"enabled": bool(crypto_caps.get("enabled", False)), "per_name_cap": crypto_caps.get("per_name_cap"),
59 "class_gross_cap": crypto_caps.get("class_gross_cap"), "guard": _guard("crypto_graduates")},
60 "rl_sizing": {"enabled": bool(dynamic_risk.get("rl_sizing_enabled", False)),
61 "range": [dynamic_risk.get("min_rl_multiplier"), dynamic_risk.get("max_rl_multiplier")],
62 "shadow_guard": bool((dynamic_risk.get("rl_shadow_guard", {}) or {}).get("enabled", False))},
63 "venue_listing_guard": bool((phase_v2.get("venue_listing_guard", {}) or {}).get("enabled", False)),
64 "learned_topology": bool((phase_v2.get("topology_learning", {}) or {}).get("enabled", False)),
65 }
68def build_assets_status(config: dict, lean_config: dict, runtime_guards: dict | None = None) -> dict:
69 """Returns the same facts `aq assets status` prints, as a JSON-safe
70 dict: IB readiness tri-state, futures/options feature flags, futures
71 contract specs loaded, FRED yield-curve cache freshness, and how many
72 futures/options assets are configured in the universe."""
73 phase_v2 = config.get("phase_v2", {})
74 specs = load_futures_contract_specs()
75 forex_specs = load_forex_pair_specs()
76 fred_series = load_cached_fred_series()
77 all_dates = [row["date"] for rows in fred_series.values() for row in rows]
78 assets = config.get("phase1", {}).get("universe", {}).get("assets", [])
80 return {
81 "ib_status": ib_readiness_status(config, lean_config),
82 "futures_risk_enabled": bool(phase_v2.get("futures_risk", {}).get("enabled", False)),
83 "options_risk_enabled": bool(phase_v2.get("options_risk", {}).get("enabled", False)),
84 # V4.6 - Forex/FX, same reporting shape as futures above.
85 "forex_risk_enabled": bool(phase_v2.get("forex_risk", {}).get("enabled", False)),
86 "futures_contract_specs_loaded": len(specs),
87 "futures_contract_specs_tickers": sorted(specs),
88 "forex_pair_specs_loaded": len(forex_specs),
89 "forex_pair_specs_tickers": sorted(forex_specs),
90 "fred_cache_series_count": len(fred_series),
91 "fred_cache_most_recent_date": max(all_dates).isoformat() if all_dates else None,
92 "configured_futures_assets": sum(
93 1 for asset in assets if (asset.get("asset_class") or asset.get("security_type")) == "future"
94 ),
95 "configured_options_assets": sum(
96 1 for asset in assets if (asset.get("asset_class") or asset.get("security_type")) == "option"
97 ),
98 "configured_forex_assets": sum(
99 1 for asset in assets if (asset.get("asset_class") or asset.get("security_type")) == "forex"
100 ),
101 "sleeves": build_sleeve_status(config, runtime_guards),
102 }
105def build_assets_status_from_disk(root: Path | None = None) -> dict:
106 """Convenience wrapper reading config.json/lean.json from their
107 canonical repo-root paths - used by callers (the API server) that don't
108 already have both loaded, mirroring aq_cli.py::cmd_assets()'s own
109 CONFIG_PATH/LEAN_JSON_PATH read pattern.
111 lean.json is deliberately excluded from the published Docker image
112 itself (development/Problems.md #42) and only reaches a running
113 container via an explicit volume mount (docker-compose.yml's `engine`
114 service) - a misconfigured or stripped-down deployment could still be
115 missing it, so a missing file degrades to an empty lean_config (every
116 ib_readiness_status() field it drives already has a graceful
117 "not configured" reading for that case) rather than a 500.
118 """
119 import json
121 config_path, lean_path, state_path = (CONFIG_PATH, LEAN_JSON_PATH, ROOT_DIR / "visualization" / "state.json") if root is None else (
122 Path(root) / "config.json", Path(root) / "lean.json", Path(root) / "visualization" / "state.json")
123 try:
124 config = json.loads(config_path.read_text(encoding="utf-8"))
125 except (OSError, ValueError):
126 # V5.4.7 (#120): a missing/mid-write config.json previously 500'd
127 # the endpoint; degrade to an empty universe view instead.
128 config = {}
129 try:
130 lean_config = json.loads(lean_path.read_text(encoding="utf-8"))
131 except (OSError, ValueError):
132 lean_config = {}
133 try:
134 runtime_state = json.loads(state_path.read_text(encoding="utf-8"))
135 runtime_guards = runtime_state.get("sleeve_guards") if isinstance(runtime_state, dict) else None
136 except (OSError, ValueError):
137 runtime_guards = None
138 return build_assets_status(config, lean_config, runtime_guards)