Coverage for scripts/v661_glide.py: 100%

87 statements  

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

1"""R-GLIDE1 on the PC: its rule hashed before any run, then the policies over fixed-seed worlds; the winner goes to ml/generations/glide_policy.json and the policy file. Also the decay detector's run lengths. 

2 

3 python scripts/v661_glide.py rules 

4 python scripts/v661_glide.py run [--paths 2000] 

5 python scripts/v661_glide.py decay 

6""" 

7 

8from __future__ import annotations 

9 

10import argparse 

11import hashlib 

12import json 

13import sys 

14from pathlib import Path 

15 

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

17sys.path.insert(0, str(ROOT)) 

18 

19from evaluation.alpha_decay import average_run_lengths # noqa: E402 

20from evaluation.glide_calibration import ( # noqa: E402 

21 default_configs, 

22 default_policies, 

23 evaluate_policies, 

24 glide2_policies, 

25 pick_glide2, 

26 pick_policy, 

27) 

28 

29OUT = ROOT / "ml" / "generations" 

30RULES = OUT / "rules_glide1.json" 

31R_GLIDE1 = ( 

32 "Monte Carlo, 2,000 fixed-seed paths: a new generation each year, Sharpe {0.5, 1.0}, alpha half-life {1, 2, 3} years, return correlation {0, 0.3, 0.6}, probability a new generation has zero alpha {0.5, 0.8}, " 

33 "costs and the 0.002 deadband on. Policies: instant switch, equal weight, fixed glide {126, 252, 504}, ladder with evidence multiplier {none, hold on watch, accelerate on decaying}. Pick the lowest median regret " 

34 "against the oracle among policies whose time above 50% of capital on a zero-alpha generation is <= 20%. Ties go to fewer parameters. Replay on real score files is report-only, because ml/versions holds no real " 

35 "vintages. No policy qualifying: fixed 252." 

36) 

37 

38 

39def stage_rules() -> int: 

40 if RULES.exists(): 

41 raise SystemExit("the rule is written once") 

42 payload = {"rule": "R-GLIDE1", "text": R_GLIDE1, "configs": default_configs(), "policies": default_policies(), "seed": 1, "paths": 2000, "years": 8, "tie": 0.005, "max_zero_alpha_share": 0.20} 

43 OUT.mkdir(parents=True, exist_ok=True) 

44 RULES.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8", newline="\n") 

45 RULES.with_suffix(".sha256").write_text(hashlib.sha256(RULES.read_bytes()).hexdigest() + "\n", encoding="utf-8", newline="\n") 

46 print(RULES.with_suffix(".sha256").read_text(encoding="utf-8").strip()) 

47 return 0 

48 

49 

50def stage_run(paths: int) -> int: 

51 payload = json.loads(RULES.read_text(encoding="utf-8")) 

52 if hashlib.sha256(RULES.read_bytes()).hexdigest() != RULES.with_suffix(".sha256").read_text(encoding="utf-8").strip(): 

53 raise SystemExit("rules_glide1.json is not the recorded hash") 

54 results = evaluate_policies(payload["configs"], payload["policies"], paths=paths, seed=int(payload["seed"]), years=int(payload["years"])) 

55 chosen = pick_policy(results, max_zero_alpha_share=float(payload["max_zero_alpha_share"]), tie=float(payload["tie"])) 

56 chosen["paths_requested"] = paths 

57 out = OUT / "glide_policy.json" 

58 out.write_text(json.dumps(chosen, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

59 picked = next(policy for policy in payload["policies"] if policy["name"] == chosen["policy"]) if any(policy["name"] == chosen["policy"] for policy in payload["policies"]) else {} 

60 policy_file = OUT / "policy.json" 

61 policy = json.loads(policy_file.read_text(encoding="utf-8")) 

62 for key in ("glide_sessions", "hold_on_watch", "accelerate_on_decaying"): 

63 if key in picked: 

64 policy["glide"][key] = picked[key] 

65 policy["glide_policy"] = chosen["policy"] 

66 policy_file.write_text(json.dumps(policy, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

67 for name, row in sorted(results.items(), key=lambda item: item[1]["median_regret"]): 

68 print(f"{name:32s} regret {row['median_regret']:.3f} on a zero-alpha generation {row['zero_alpha_majority_share']:.3f}") 

69 print("chosen:", chosen["policy"]) 

70 return 0 

71 

72 

73RULES2 = OUT / "rules_glide2.json" 

74R_GLIDE2 = ( 

75 "The worlds, seeds, costs and deadband of R-GLIDE1. Policies: fixed_252 (the installed result of R-GLIDE1), equal weight, and the dynamic mode over half life {63, 126}, prior sessions {126, 252, 504}, score floor {0, 0.2}, " 

76 "blend row every {5, 21} sessions, at most 4 generations holding capital. Among dynamic policies no worse than fixed_252 on time above 50% of capital on a zero-alpha generation, take the lowest median regret, ties within 0.005 " 

77 "to less turnover. It replaces fixed_252 if its regret is no worse than fixed_252's, within 0.005: the owner asked for this form on 2026-11-06, so no worse is enough. Otherwise fixed_252 stays and the dynamic mode remains an " 

78 "option the owner can select, with these numbers. R-GLIDE1's limit of 20% is reported, not moved. Every generation is judged against the same claim, its selection Sharpe halved." 

79) 

80 

81 

82def stage_rules2() -> int: 

83 if RULES2.exists(): 

84 raise SystemExit("the rule is written once") 

85 payload = {"rule": "R-GLIDE2", "text": R_GLIDE2, "configs": default_configs(), "policies": glide2_policies(), "seed": 2, "paths": 2000, "years": 8, "tie": 0.005} 

86 RULES2.write_text(json.dumps(payload, indent=1) + "\n", encoding="utf-8", newline="\n") 

87 RULES2.with_suffix(".sha256").write_text(hashlib.sha256(RULES2.read_bytes()).hexdigest() + "\n", encoding="utf-8", newline="\n") 

88 print(RULES2.with_suffix(".sha256").read_text(encoding="utf-8").strip()) 

89 return 0 

90 

91 

92def stage_run2(paths: int, workers: int) -> int: 

93 if hashlib.sha256(RULES2.read_bytes()).hexdigest() != RULES2.with_suffix(".sha256").read_text(encoding="utf-8").strip(): 

94 raise SystemExit("rules_glide2.json is not the recorded hash") 

95 payload = json.loads(RULES2.read_text(encoding="utf-8")) 

96 results = evaluate_policies(payload["configs"], payload["policies"], paths=paths, seed=int(payload["seed"]), years=int(payload["years"]), workers=workers) 

97 chosen = pick_glide2(results, tie=float(payload["tie"])) 

98 (OUT / "glide2_policy.json").write_text(json.dumps({**chosen, "results": results}, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

99 policy_file = OUT / "policy.json" 

100 policy = json.loads(policy_file.read_text(encoding="utf-8")) 

101 picked = next((entry for entry in payload["policies"] if entry["name"] == chosen["policy"]), {}) 

102 if chosen["adopted"]: 

103 policy["glide"].update({"mode": "dynamic", **{key: picked[key] for key in ("half_life_sessions", "prior_sessions", "score_floor", "blend_every", "max_generations")}}) 

104 policy["glide_policy"] = chosen["policy"] 

105 policy_file.write_text(json.dumps(policy, indent=1, sort_keys=True) + "\n", encoding="utf-8", newline="\n") 

106 for name, row in sorted(results.items(), key=lambda item: item[1]["median_regret"]): 

107 print(f"{name:32s} regret {row['median_regret']:.3f} zero-alpha time {row['zero_alpha_majority_share']:.3f} holders {row['mean_holders']:.2f} turnover/yr {row['turnover_per_year']:.2f}") 

108 print("chosen:", chosen["policy"], "| adopted:", chosen["adopted"], "|", chosen["reason"]) 

109 return 0 

110 

111 

112def stage_decay() -> int: 

113 reports = { 

114 "1_to_0": average_run_lengths(expected_sharpe=1.0, decayed_sharpe=0.0, paths=500), 

115 "0.5_to_0": average_run_lengths(expected_sharpe=0.5, decayed_sharpe=0.0, paths=500), 

116 "0_to_-1": average_run_lengths(expected_sharpe=0.0, decayed_sharpe=-1.0, paths=500), 

117 } 

118 out = ROOT / "ml" / "evaluation" / "v661" / "decay_run_lengths.json" 

119 out.parent.mkdir(parents=True, exist_ok=True) 

120 out.write_text(json.dumps(reports, indent=1), encoding="utf-8", newline="\n") 

121 print(json.dumps(reports, indent=1)) 

122 return 0 

123 

124 

125def main() -> int: 

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

127 parser.add_argument("stage", choices=["rules", "run", "decay", "rules2", "run2"]) 

128 parser.add_argument("--paths", type=int, default=2000) 

129 parser.add_argument("--workers", type=int, default=1) 

130 args = parser.parse_args() 

131 return { 

132 "rules": stage_rules, "run": lambda: stage_run(args.paths), "decay": stage_decay, "rules2": stage_rules2, "run2": lambda: stage_run2(args.paths, args.workers), 

133 }[args.stage]() 

134 

135 

136if __name__ == "__main__": 

137 raise SystemExit(main())