Coverage for monitoring/evaluation_state.py: 100%

47 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Evaluation-dashboard state for Aether Quant's webui (V5.1 Phase 0). 

2 

3Reads the JSON reports `aq evaluate` writes (ml/evaluation/*.json) and 

4reshapes them into one payload for the /api/evaluation endpoint and the 

5webui's Evaluation tab. Pure, read-only - never runs a simulation itself 

6(that is `aq evaluate`'s job); this module only serves whatever `aq 

7evaluate` last wrote to disk. 

8 

9Each section degrades independently to {"status": "not_evaluated"} when 

10its source file is missing - never raises, mirroring 

11monitoring/neural_network_state.py::build_neural_network_state()'s own 

12per-network degrade-gracefully contract. A user who has never run `aq 

13evaluate` sees an honest "not evaluated yet" tab, not a 404/500. 

14""" 

15 

16from __future__ import annotations 

17 

18import json 

19from pathlib import Path 

20from typing import Any 

21 

22DEFAULT_ML_DIR = Path(__file__).resolve().parent.parent / "ml" 

23 

24 

25def _load_json(path: Path) -> dict[str, Any] | list[Any] | None: 

26 if not path.exists(): 

27 return None 

28 try: 

29 with path.open("r", encoding="utf-8") as f: 

30 return json.load(f) 

31 except (json.JSONDecodeError, OSError): 

32 return None 

33 

34 

35def build_generations_state(ml_dir: Path | None = None) -> dict[str, Any]: 

36 """V6.6.1 - what `aq cycle status` wrote: the generations, their shares and what is due. A fresh checkout has no status yet, which is not an error.""" 

37 payload = _load_json((ml_dir or DEFAULT_ML_DIR) / "generations" / "status.json") 

38 if not isinstance(payload, dict): 

39 return {"available": False, "generations": [], "due": [], "hint": "run `aq cycle status`"} 

40 return {"available": True, **payload} 

41 

42 

43def _not_evaluated(hint: str) -> dict[str, Any]: 

44 return {"status": "not_evaluated", "hint": hint} 

45 

46 

47def build_evaluation_state(ml_dir: Path | None = None) -> dict[str, Any]: 

48 """Reads ml/evaluation/{rank_book_simulation,capacity_report, 

49 cost_stress_report,ablation_report,book_spread_calibration, 

50 book_history_reconciliation,kill_switch_replay}.json plus the newest 

51 ml/versions/walk-forward-*/walk_forward_summary.json (Phase 4 - absent 

52 until that phase ships, degrades the same way). Every section is 

53 independently optional; a partial `aq evaluate` run (e.g. just 

54 --rank-book) still produces a fully-formed response with the 

55 unreported sections marked not_evaluated rather than omitted.""" 

56 ml_dir = ml_dir or DEFAULT_ML_DIR 

57 evaluation_dir = ml_dir / "evaluation" 

58 

59 rank_book = _load_json(evaluation_dir / "rank_book_simulation.json") 

60 capacity = _load_json(evaluation_dir / "capacity_report.json") 

61 stress_report = _load_json(evaluation_dir / "cost_stress_report.json") 

62 ablation = _load_json(evaluation_dir / "ablation_report.json") 

63 walk_forward = _latest_walk_forward_summary(ml_dir) 

64 # V5.1 report that was never wired in here until V5.2.3 - a pre- 

65 # existing gap, closed alongside book_history_reconciliation below 

66 # since this function already touches every other `aq evaluate` 

67 # report. 

68 book_spread_calibration = _load_json(evaluation_dir / "book_spread_calibration.json") 

69 # V5.2.2/V5.2.3 (development/Problems.md #91) - `aq evaluate 

70 # --reconcile-book-history`'s persisted payload (per-date diffs + 

71 # aggregate summary + universe_summary once V5.2.3's 

72 # include_full_universe toggle has been used for a run). 

73 book_history_reconciliation = _load_json(evaluation_dir / "book_history_reconciliation.json") 

74 # V5.2.8 (development/Problems.md #94) - `aq evaluate --replay-kill-switch`'s 

75 # persisted payload, never wired into this state builder until now - 

76 # same honest gap book_history_reconciliation had before V5.2.3. 

77 kill_switch_replay = _load_json(evaluation_dir / "kill_switch_replay.json") 

78 # V5.3.8 - Monte Carlo layer's persisted summary (avg curve + percentile 

79 # bands + config); the heavy runs matrix lives in the sibling .npz and is 

80 # intentionally NOT surfaced here. 

81 monte_carlo = _load_json(evaluation_dir / "monte_carlo.json") 

82 # V5.4.4 - benchmark comparison's persisted report (strategy + public 

83 # baselines over the rank book's own window); rendered by the 

84 # Evaluation tab's Benchmark Comparison panel. 

85 benchmarks = _load_json(evaluation_dir / "benchmark_comparison.json") 

86 

87 # Every section follows the same shape convention: the raw report dict 

88 # when present, or {"status": "not_evaluated", "hint": ...} when not - 

89 # "stress" is wrapped in {"entries": [...]} since its report is a bare 

90 # list (one entry per cost multiplier), which has no room for its own 

91 # "status"/"hint" keys. 

92 return { 

93 "rank_book": rank_book or _not_evaluated("run `aq evaluate --rank-book`"), 

94 "capacity": capacity or _not_evaluated("run `aq evaluate --capacity`"), 

95 "stress": ( 

96 {"entries": stress_report["stress"]} 

97 if stress_report and "stress" in stress_report 

98 else _not_evaluated("run `aq evaluate --stress`") 

99 ), 

100 "ablation": ablation or _not_evaluated("run `aq evaluate --ablation`"), 

101 "walk_forward": walk_forward or _not_evaluated("run `aq train --walk-forward --include-multitask --include-sequence`"), 

102 "book_spread_calibration": book_spread_calibration or _not_evaluated("run `aq evaluate --calibrate-book-spread`"), 

103 "book_history_reconciliation": book_history_reconciliation 

104 or _not_evaluated("run `aq evaluate --reconcile-book-history` (needs a backtest with phase_v2.diagnostics.book_history.enabled=true first)"), 

105 "kill_switch_replay": kill_switch_replay or _not_evaluated("run `aq evaluate --replay-kill-switch`"), 

106 "monte_carlo": monte_carlo or _not_evaluated("run `aq evaluate --rank-book --monte-carlo`"), 

107 "benchmarks": benchmarks or _not_evaluated("run `aq evaluate --benchmarks`"), 

108 } 

109 

110 

111def _latest_walk_forward_summary(ml_dir: Path) -> dict[str, Any] | None: 

112 """The most recently modified ml/versions/walk-forward-*/walk_forward_summary.json, 

113 if any - `_run_walk_forward()` (train.py) writes one such directory per 

114 run, each with its own uuid-suffixed name, so "latest" is by file 

115 mtime, not by name sort order.""" 

116 versions_dir = ml_dir / "versions" 

117 if not versions_dir.exists(): 

118 return None 

119 

120 def _mtime(path): 

121 # V5.4.7 (#120): a walk-forward dir deleted between glob() and 

122 # stat() (cleanup during retraining) previously FileNotFoundError'd 

123 # the whole /api/evaluation build. 

124 try: 

125 return path.stat().st_mtime 

126 except OSError: 

127 return 0.0 

128 

129 candidates = sorted( 

130 versions_dir.glob("walk-forward-*/walk_forward_summary.json"), 

131 key=_mtime, 

132 reverse=True, 

133 ) 

134 if not candidates: 

135 return None 

136 return _load_json(candidates[0])