Coverage for retraining/backtest_gate.py: 100%

48 statements  

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

1"""Pure active/candidate/buy-and-hold backtest comparison (Phase V2-17). 

2 

3Builds the comparison table directly from the strategy/buy_and_hold blocks 

4train.py's compute_strategy_metrics() already produces in every 

5strategy_report.json - no re-computation needed, buy-and-hold is already 

6built in. See retraining/lean_backtest.py for the optional, best-effort 

7Lean-backtest IO wrapper this module's caller may also want to run first. 

8""" 

9 

10from __future__ import annotations 

11 

12import math 

13from typing import Any 

14 

15 

16def _strategy_block(report: dict[str, Any], key: str) -> dict[str, Any]: 

17 return report.get("backtest", {}).get(key, {}) 

18 

19 

20def _finite_or_default(value, default: float = 0.0) -> float: 

21 # V5.4.7 (development/Problems.md #122): a NaN total_return previously 

22 # produced a NaN excess return whose `nan < threshold` comparison is 

23 # False - the gate passed vacuously. Non-finite degrades to the 

24 # no-edge default (conservative direction here). 

25 try: 

26 as_float = float(value) 

27 except (TypeError, ValueError): 

28 return default 

29 return as_float if math.isfinite(as_float) else default 

30 

31 

32def _finite_or_none(value) -> float | None: 

33 if isinstance(value, bool): 

34 return None 

35 try: 

36 as_float = float(value) 

37 except (TypeError, ValueError): 

38 return None 

39 return as_float if math.isfinite(as_float) else None 

40 

41 

42def compare_backtests(active_report: dict[str, Any], candidate_report: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]: 

43 """3-way (active / candidate / buy-and-hold) comparison, plus an optional 

44 4th risk-adjusted-benchmark row. 

45 

46 A benchmark row is included only if config["benchmark_ticker"] names an 

47 asset present in candidate_report["backtest_per_asset"] - reuses the 

48 per-asset breakdown build_strategy_report() already computes. 

49 

50 Returns {passed, comparison: {active, candidate, buy_and_hold, benchmark|None}, reasons: [...]}. 

51 """ 

52 active_strategy = _strategy_block(active_report, "strategy") 

53 candidate_strategy = _strategy_block(candidate_report, "strategy") 

54 candidate_buy_and_hold = _strategy_block(candidate_report, "buy_and_hold") 

55 

56 benchmark_ticker = config.get("benchmark_ticker") 

57 benchmark = None 

58 if benchmark_ticker: 

59 per_asset = candidate_report.get("backtest_per_asset", {}) 

60 asset_report = per_asset.get(benchmark_ticker) 

61 if isinstance(asset_report, dict): 

62 benchmark = asset_report.get("strategy") 

63 

64 # V6.6.7 (#370, formal/AetherFormal/BacktestGate.lean): a candidate without a finite return, or a threshold that is 

65 # not a finite number, fails. Before, a missing candidate return read 0.0 (which beats a losing active model) and a 

66 # NaN threshold made `excess < nan` False, so the gate passed vacuously (the class of #122). 

67 threshold = _finite_or_none(config.get("min_excess_return_vs_active", -0.02)) 

68 candidate_value = _finite_or_none(candidate_strategy.get("total_return")) 

69 candidate_return = 0.0 if candidate_value is None else candidate_value 

70 active_return = _finite_or_default(active_strategy.get("total_return")) 

71 excess_return_vs_active = candidate_return - active_return 

72 min_excess_return_vs_active = threshold if threshold is not None else math.nan 

73 

74 reasons: list[str] = [] 

75 passed = True 

76 if threshold is None: 

77 passed = False 

78 reasons.append(f"min_excess_return_vs_active_invalid ({config.get('min_excess_return_vs_active')!r})") 

79 elif candidate_value is None: 

80 passed = False 

81 reasons.append("candidate_return_missing") 

82 elif excess_return_vs_active < min_excess_return_vs_active: 

83 passed = False 

84 reasons.append( 

85 f"candidate_excess_return_vs_active_below_threshold " 

86 f"({excess_return_vs_active:.4f} < {min_excess_return_vs_active:.4f})" 

87 ) 

88 

89 return { 

90 "passed": passed, 

91 "comparison": { 

92 "active": active_strategy, 

93 "candidate": candidate_strategy, 

94 "buy_and_hold": candidate_buy_and_hold, 

95 "benchmark": benchmark, 

96 }, 

97 "excess_return_vs_active": excess_return_vs_active, 

98 "reasons": reasons, 

99 }