Coverage for scripts/v643_sector_cap_frequency.py: 100%

55 statements  

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

1"""How often does the shipped book end a rebalance with a sector above `sector_max_net_weight`? (V6.4.3, the 

2`sector_cap_counterexample` of formal/AetherFormal/BookNeutrality.lean.) 

3 

4Replays `portfolio.book_neutrality.apply_book_neutrality` on every logged rebalance of a Lean run's book history: the raw 

5weights are rebuilt from the logged allocations with `build_book_raw_weights` (live's own pre-neutrality formula), then 

6neutralised with the run's config, once as shipped and once with `reapply_sector_cap_after_dollar_neutral`. 

7 

8 python scripts/v643_sector_cap_frequency.py [--run backtests/2026-10-22_10-56-13 ...] [--out ml/evaluation/v643/sector_cap_frequency.json] 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import json 

15import sys 

16from pathlib import Path 

17 

18ROOT_DIR = Path(__file__).resolve().parents[1] 

19sys.path.insert(0, str(ROOT_DIR)) 

20 

21DEFAULT_RUNS = ("backtests/2026-10-22_10-56-13", "backtests/2026-10-24_05-28-07", "backtests/2026-10-24_18-50-22") 

22 

23 

24def replay_run(run_dir: Path) -> dict: 

25 from evaluation.lean_attribution import find_book_history_for_run, run_config_path 

26 from features import load_sector_mapping 

27 from portfolio.book_construction import BookAllocation, build_book_raw_weights 

28 from portfolio.book_neutrality import apply_book_neutrality 

29 

30 config_path = run_config_path(run_dir, ROOT_DIR) or ROOT_DIR / "config.json" 

31 config = json.loads(Path(config_path).read_text(encoding="utf-8")) 

32 neutrality = config["phase_v2"]["portfolio_book"].get("neutrality", {}) 

33 max_position_weight = float(config.get("phase6", {}).get("risk", {}).get("max_position_weight", 0.25)) # main.py's read 

34 sectors = load_sector_mapping(config) 

35 history_path = find_book_history_for_run(run_dir, ROOT_DIR / "visualization" / "book_history") 

36 records = [json.loads(line) for line in history_path.read_text(encoding="utf-8").splitlines() if line.strip()] 

37 kwargs = dict(dollar_neutral=bool(neutrality.get("dollar_neutral", True)), sector_neutral=bool(neutrality.get("sector_neutral", True)), 

38 gross_exposure_cap=float(neutrality.get("gross_exposure_cap", 1.0)), 

39 max_weight_per_name=float(neutrality.get("max_weight_per_name", 0.12)), 

40 sector_max_net_weight=float(neutrality.get("sector_max_net_weight", 0.15))) 

41 cap = kwargs["sector_max_net_weight"] 

42 rebalances = breaches = 0 

43 worst, l1_change, net_after_reapply = 0.0, [], [] 

44 for record in records: 

45 allocations = record.get("allocations") or {} 

46 if not allocations: 

47 continue 

48 book = {symbol: BookAllocation(role=entry["role"], book_role_multiplier=float(entry["book_role_multiplier"]), 

49 predicted_rank_20d=float(entry["predicted_rank_20d"]), book_reason="replay") 

50 for symbol, entry in allocations.items()} 

51 raw = build_book_raw_weights(book, max_position_weight) 

52 sector_by_symbol = {symbol: allocations[symbol].get("sector") or sectors.get(symbol, "Unknown") for symbol in raw} 

53 shipped, diagnostics = apply_book_neutrality(raw, sector_by_symbol=sector_by_symbol, **kwargs) 

54 reapplied, reapplied_diagnostics = apply_book_neutrality(raw, sector_by_symbol=sector_by_symbol, 

55 reapply_sector_cap_after_dollar_neutral=True, **kwargs) 

56 rebalances += 1 

57 over = max((abs(net) - cap for net in diagnostics["per_sector_net"].values()), default=0.0) 

58 if over > 1e-12: 

59 breaches += 1 

60 worst = max(worst, over) 

61 l1_change.append(sum(abs(shipped[s] - reapplied[s]) for s in shipped)) 

62 net_after_reapply.append(abs(reapplied_diagnostics["net_after"])) 

63 return {"run": run_dir.name, "config": str(config_path), "rebalances": rebalances, "breaching_rebalances": breaches, 

64 "breach_share": breaches / rebalances if rebalances else None, "worst_excess_over_cap": worst, 

65 "sector_max_net_weight": cap, "mean_l1_change_with_reapply": sum(l1_change) / len(l1_change) if l1_change else None, 

66 "max_abs_net_with_reapply": max(net_after_reapply, default=0.0)} 

67 

68 

69def main() -> int: 

70 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

71 parser.add_argument("--run", action="append", default=None) 

72 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v643" / "sector_cap_frequency.json")) 

73 args = parser.parse_args() 

74 runs = [ROOT_DIR / run for run in (args.run or DEFAULT_RUNS)] 

75 report = {"runs": [replay_run(run) for run in runs]} 

76 for row in report["runs"]: 

77 print(json.dumps(row)) 

78 Path(args.out).parent.mkdir(parents=True, exist_ok=True) 

79 Path(args.out).write_text(json.dumps(report, indent=1), encoding="utf-8") 

80 return 0 

81 

82 

83if __name__ == "__main__": 

84 raise SystemExit(main())