Coverage for scripts/daily_target_weights.py: 100%

110 statements  

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

1"""The next row of a target-weights run (V6.5.0), for paper or live: what the research file holds, computed from today's data. 

2 

3A Lean backtest reads a whole weight file. Paper or live needs the same row written before each open, from the same functions, 

4so this appends one row to the file `phase_v2.target_weights.weights_path` names, and rewrites its `.sha256` sidecar, which a run 

5with `live_reload` checks at each reload. A date is written once, and the row must be finite. A date with no data, or a class 

6whose last bar is too old, exits non-zero: "not a rebalance day" must never hide a broken data feed. 

7 

8 python scripts/daily_target_weights.py --candidate ml/evaluation/v650/installed_candidate.json --out ml/evaluation/v650/weights/live.csv [--date 2026-11-04] 

9""" 

10 

11from __future__ import annotations 

12 

13import argparse 

14import csv 

15import json 

16import math 

17import sys 

18from pathlib import Path 

19 

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

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

22sys.path.insert(0, str(ROOT / "scripts")) 

23 

24 

25def row_for_date(definition: dict, context, date: str, *, candidate_rows, history_start: str = "2014-12-01") -> dict[str, float] | None: 

26 """The candidate's row dated `date`, or None when `date` is not one of its rebalance days. Computed on data cut at `date`, 

27 so it cannot depend on anything later, and rebalance days counted from the same `history_start` as the research file.""" 

28 cut = context.panel.truncated(date) 

29 original = context.panel 

30 context.panel = cut 

31 try: 

32 rows = candidate_rows(definition, context, start=history_start, end=date, phase_index=int(definition.get("phase_index", 0))) 

33 finally: 

34 context.panel = original 

35 return rows.get(date) 

36 

37 

38def append_row(path: Path, date: str, row: dict[str, float]) -> bool: 

39 """Appends the row; False when the file already holds this date. Raises ValueError on a non-finite weight, so a damaged 

40 row never reaches an order.""" 

41 for ticker, weight in row.items(): 

42 if not math.isfinite(float(weight)): 

43 raise ValueError(f"non-finite weight for {ticker} on {date}") 

44 exists = path.exists() 

45 if exists: 

46 with path.open(newline="", encoding="utf-8") as handle: 

47 if any(existing["date"][:10] == date for existing in csv.DictReader(handle)): 

48 return False 

49 from portfolio.target_weights import FLAT_TICKER 

50 

51 with path.open("a", newline="\n", encoding="utf-8") as handle: 

52 if not exists: 

53 handle.write("date,ticker,weight\n") 

54 if not row: 

55 handle.write(f"{date},{FLAT_TICKER},0\n") 

56 for ticker in sorted(row): 

57 handle.write(f"{date},{ticker},{float(row[ticker]):.8f}\n") 

58 from portfolio.target_weights import write_weights_sidecar 

59 

60 write_weights_sidecar(path) 

61 return True 

62 

63 

64# The oldest a class's last bar may be, in calendar days before the decision: a weekend plus a holiday for equities' sessions, and 

65# crypto trades daily and its bar is read a day late. 

66MAX_STALE_DAYS = {"equity": 5, "bond": 5, "forex": 5, "crypto": 2} 

67 

68 

69def data_problems(context, date: str) -> list[str]: 

70 """Why `date` can't be decided: no such session, or a class holding this candidate's names has stopped updating.""" 

71 import pandas as pd 

72 

73 known = context.panel.known 

74 if date not in known.index: 

75 return [f"{date} is not a session in the data (last is {known.index[-1]})"] 

76 problems = [] 

77 closes = pd.DataFrame(context.market.closes, index=context.market.dates, columns=context.market.tickers) 

78 closes = closes[closes.index <= date] 

79 today = pd.Timestamp(date) 

80 for asset_class, limit in MAX_STALE_DAYS.items(): 

81 members = [ticker for ticker, name in context.market.asset_class.items() if name == asset_class and ticker in closes.columns] 

82 rows = closes[members].dropna(how="all") if members else None 

83 if rows is None or rows.empty: 

84 continue 

85 age = (today - pd.Timestamp(rows.index[-1])).days 

86 if age > limit: 

87 problems.append(f"{asset_class} data is {age} days old on {date} (limit {limit})") 

88 return problems 

89 

90 

91def blended_rows(ledger: Path) -> dict[str, dict[str, float]]: 

92 """{session: blended row} from the generations' ledger (`scripts/cycle_daily.py`). Stops at a broken chain: a row that can't be trusted must not reach an order.""" 

93 from evaluation.forward_ledger import read_ledger 

94 from evaluation.generation_ledger import ALLOCATION_ID, judge_generations 

95 

96 rows = read_ledger(ledger) 

97 if not judge_generations(rows)["chain_valid"]: 

98 raise ValueError(f"{ledger.name}: the chain is broken") 

99 return { 

100 row["payload"]["session"]: dict(row["payload"]["blended"]) 

101 for row in rows 

102 if row["payload"].get("candidate") == ALLOCATION_ID and row["payload"].get("blended") is not None 

103 } 

104 

105 

106def write_blended(ledger: Path, out: Path) -> list[str]: 

107 """Appends each blended row the file doesn't hold yet, in order, and returns their dates. A paper run with `live_reload` trades this file.""" 

108 written = [] 

109 for date, row in sorted(blended_rows(ledger).items()): 

110 if append_row(out, date, row): 

111 written.append(date) 

112 return written 

113 

114 

115def main() -> int: 

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

117 parser.add_argument("--candidate", default=None, help="one frozen rule's definition") 

118 parser.add_argument("--generations", default=None, help="instead of --candidate: the generations' ledger, forward/generations.jsonl") 

119 parser.add_argument("--out", required=True) 

120 parser.add_argument("--date", default=None, help="the session to decide for (default: the last session in the data)") 

121 args = parser.parse_args() 

122 if bool(args.candidate) == bool(args.generations): 

123 parser.error("name exactly one of --candidate and --generations") 

124 if args.generations: 

125 for date in write_blended(Path(args.generations), Path(args.out)): 

126 print(f"{date}: wrote the blended row") 

127 return 0 

128 

129 definition = json.loads(Path(args.candidate).read_text(encoding="utf-8")) 

130 if definition.get("kind") == "blend": 

131 # V6.6.9: the installed book is a blend of the crypto sleeve and the model book; its rows need the installed models' scores up to the session 

132 from evaluation import model_book_round as rnd 

133 

134 out_dir = ROOT / "ml" / "evaluation" / "v669" 

135 context = rnd.load_round_context(ROOT, {name: out_dir / "scores" / f"long_{name[-2:]}.csv" for name in ("ml_a1", "ml_a2", "ml_a3")}) 

136 date = args.date or str(context.panel.known.index[-1]) 

137 problems = [*data_problems(context, date), *filter(None, [rnd.score_problem(context, date)])] 

138 row_of = lambda: rnd.blend_row(definition, context, date) # noqa: E731 

139 else: 

140 from v650_lean import candidate_rows 

141 from v650_research import load_context 

142 

143 context = load_context() 

144 date = args.date or str(context.panel.known.index[-1]) 

145 problems = data_problems(context, date) 

146 row_of = lambda: row_for_date(definition, context, date, candidate_rows=candidate_rows, history_start=str(definition.get("history_start", "2014-12-01"))) # noqa: E731 

147 if problems: 

148 for problem in problems: 

149 print(f"refusing to decide: {problem}", file=sys.stderr) 

150 return 1 

151 row = row_of() 

152 if row is None: 

153 print(f"{date}: not a rebalance day, nothing to write") 

154 return 0 

155 written = append_row(Path(args.out), date, row) 

156 print(f"{date}: {'wrote' if written else 'already held'} {len(row)} weights") 

157 return 0 

158 

159 

160if __name__ == "__main__": 

161 raise SystemExit(main())