Coverage for scripts/readme_freshness.py: 100%

62 statements  

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

1"""Is every block of the README's Backtest Statistics current (V6.3.0, the end-of-phase recapture check)? 

2 

3Each `AQ:*` block between "## Backtest Statistics" and "## Test Suite" is dated by the timestamp it prints ("computed ...", 

4"Last updated | ...") or, when it prints none, by the newest mtime of the files it is rendered from. A block is stale when 

5that date is before `--since`, unless it is named with `--allow`. The walk-forward blocks are model-bound: they describe the 

6installed models, so they are stale only when dated before those models were written (a retrain refreshes them, nothing 

7else can). Lean-reading blocks must name the pinned run (`ml/evaluation/readme_lean_run.json`). 

8 

9 python scripts/readme_freshness.py --since 2026-10-18 [--allow BLOCK ...] 

10""" 

11 

12from __future__ import annotations 

13 

14import argparse 

15import json 

16import re 

17from datetime import datetime, timezone 

18from pathlib import Path 

19 

20ROOT = Path(__file__).resolve().parents[1] 

21EVALUATION = ROOT / "ml" / "evaluation" 

22BLOCK_RE = re.compile(r"<!-- AQ:([A-Z0-9_]+)_START -->(.*?)<!-- AQ:\1_END -->", re.DOTALL) 

23STAMP_RE = re.compile(r"(?:computed|Last updated \|)\s+(\d{4}-\d{2}-\d{2})") 

24RUN_RE = re.compile(r"`?(\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2})`?") 

25# blocks that print no timestamp: the files they are rendered from 

26SOURCES = { 

27 "ASLIVE": ["rank_book_simulation_as_live_validation.json", "rank_book_simulation_as_live_backtest.json"], 

28 "LEANCMP": ["backtest_audit.json"], 

29 "RESEARCH": ["v630/research.json", "v630/calibration.json", "head_audit.json", "holdout_report.json", 

30 "v640/research.json", "v640/r_lean13.json", "v642/r_lean14_bt7.json", "v642/r_lean14_bt8.json"], 

31 "BACKTEST_HISTORY": [], 

32 "MONTECARLO_FULL_STATS": ["monte_carlo_lean.json"], 

33 "EVAL_FULL_STATS": ["rank_book_simulation_sequence.json", "rank_book_simulation_multitask.json"], 

34 "WALKFORWARD_FULL_STATS": [], 

35} 

36LEAN_BLOCKS = ("BTSTATS_GENERAL", "BTSTATS_PERFORMANCE", "BTSTATS_RUNS", "BTSTATS_SHORTFALL", "BTSTATS_EFFICIENCY", 

37 "BTSTATS_ATTRIBUTION", "BTSTATS_BENCHMARKS", "ALPHA", "MONTECARLO") 

38MODEL_BOUND = ("WALKFORWARD", "WALKFORWARD_FULL_STATS") 

39# the installed models the model-bound blocks describe (ml/, written by a retrain) 

40MODEL_FILES = ("model_weights.json", "multitask_model.json", "sequence_model.json") 

41 

42 

43def models_written(ml_dir: Path = ROOT / "ml") -> str | None: 

44 """UTC date the newest installed model artifact was written, None when none exists.""" 

45 stamps = [(ml_dir / name).stat().st_mtime for name in MODEL_FILES if (ml_dir / name).exists()] 

46 return datetime.fromtimestamp(max(stamps), tz=timezone.utc).date().isoformat() if stamps else None 

47 

48 

49def section(text: str) -> str: 

50 start = text.find("## Backtest Statistics") 

51 end = text.find("## Test Suite", start) 

52 return text[start:end] if start >= 0 else "" 

53 

54 

55def block_dates(text: str, evaluation_dir: Path = EVALUATION) -> dict[str, dict]: 

56 """{block: {"date": newest date or None, "source": "printed" | "files" | "none", "runs": runs named}}.""" 

57 out = {} 

58 for name, body in BLOCK_RE.findall(section(text)): 

59 printed = STAMP_RE.findall(body) 

60 if printed: 

61 out[name] = {"date": max(printed), "source": "printed", "runs": sorted(set(RUN_RE.findall(body)))} 

62 continue 

63 mtimes = [ 

64 datetime.fromtimestamp((evaluation_dir / rel).stat().st_mtime, tz=timezone.utc).date().isoformat() 

65 for rel in SOURCES.get(name, []) if (evaluation_dir / rel).exists() 

66 ] 

67 out[name] = {"date": max(mtimes) if mtimes else None, "source": "files" if mtimes else "none", 

68 "runs": sorted(set(RUN_RE.findall(body)))} 

69 return out 

70 

71 

72def stale_blocks(dates: dict[str, dict], since: str, allow: set[str], pinned_run: str | None, 

73 models_date: str | None = None) -> list[str]: 

74 problems = [] 

75 for name, info in sorted(dates.items()): 

76 if name in allow: 

77 continue 

78 bound = models_date if name in MODEL_BOUND and models_date else since 

79 if info["date"] is None or info["date"] < bound: 

80 what = f"the installed models ({bound})" if bound != since else since 

81 problems.append(f"{name}: dated {info['date'] or 'nowhere'} ({info['source']}), before {what}") 

82 if pinned_run and name in LEAN_BLOCKS and pinned_run not in info["runs"]: 

83 problems.append(f"{name}: does not name the pinned run {pinned_run}") 

84 return problems 

85 

86 

87def main() -> int: 

88 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) 

89 parser.add_argument("--since", required=True, help="ISO date: every block must be dated on or after it") 

90 parser.add_argument("--allow", action="append", default=[], help="a block name exempt from the date check") 

91 parser.add_argument("--readme", type=Path, default=ROOT / "README.md") 

92 args = parser.parse_args() 

93 dates = block_dates(args.readme.read_text(encoding="utf-8")) 

94 pin = EVALUATION / "readme_lean_run.json" 

95 pinned = json.loads(pin.read_text(encoding="utf-8")).get("run") if pin.exists() else None 

96 for name, info in sorted(dates.items()): 

97 print(f"{name:28s} {info['date'] or '-':10s} {info['source']:8s} {', '.join(info['runs'][:2])}") 

98 problems = stale_blocks(dates, args.since, set(args.allow), pinned, models_written()) 

99 for problem in problems: 

100 print("STALE:", problem) 

101 print(f"{len(dates)} blocks, {len(problems)} problem(s); pinned run {pinned or 'none'}") 

102 return 1 if problems else 0 

103 

104 

105if __name__ == "__main__": 

106 raise SystemExit(main())