Coverage for portfolio/target_weights.py: 100%

160 statements  

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

1"""Target-weights path (V6.5.0, `phase_v2.target_weights`, default off): a run that holds a file of target weights. 

2 

3The gated live path is too complex to replicate offline: the simulator tracks Lean at a daily correlation of about 0.73 and 

4has disagreed with it in sign. This path has no gates between a weight and its order, so an offline engine 

5(`evaluation/target_weights_engine.py`, same functions) can track Lean closely enough to select on. 

6 

7A row `date,ticker,weight` is a decision taken at the equity close of `date`. Equities fill at the next session's open. 

8Crypto and forex bars close at the following midnight, so their orders wait for that bar and fill at its close: sent 

9on the equity tick they would fill at a price 16 hours old, which flatters any signal with positive daily autocorrelation. 

10 

11Stdlib only at import; never raises on bad numbers except in `load_weight_file`, where a damaged file must stop the run. 

12""" 

13 

14from __future__ import annotations 

15 

16import csv 

17import hashlib 

18import math 

19from collections.abc import Iterable, Mapping 

20from dataclasses import dataclass, field 

21from pathlib import Path 

22from typing import Any 

23 

24from portfolio.cash_sweep import strategy_reserve 

25 

26DEFAULT_SLIPPAGE_BPS = {"equity": 3.0, "bond": 3.0, "forex": 1.0, "crypto": 10.0} 

27NEXT_BAR_CLASSES = frozenset({"crypto", "forex"}) 

28DEFAULT_NO_BAR_HAIRCUT = {"equity": 0.05, "bond": 0.05, "forex": 0.0, "crypto": 0.20} 

29 

30 

31@dataclass(frozen=True) 

32class TargetWeightsConfig: 

33 """Settings of the target-weights path: the weights file and its pin, deadbands, minimum trades, fees, slippage and financing.""" 

34 enabled: bool = False 

35 weights_path: str = "" 

36 weights_sha256: str = "" 

37 min_weight_change: float = 0.002 

38 min_trade_usd: float = 100.0 

39 forex_min_trade_usd: float = 5000.0 

40 reserve_gross: float = 0.3 

41 equity_fee_bps: float = 1.5 

42 equity_min_fee_usd: float = 1.0 

43 slippage_bps_by_class: Mapping[str, float] = field(default_factory=lambda: dict(DEFAULT_SLIPPAGE_BPS)) 

44 financing_enabled: bool = True 

45 margin_spread_bps: float = 150.0 

46 borrow_bps: float = 25.0 

47 fx_spread_bps: float = 50.0 

48 live_reload: bool = False 

49 uses_model: bool = False 

50 no_bar_exit: bool = False 

51 no_bar_exit_after: int = 2 

52 no_bar_haircut_by_class: Mapping[str, float] = field(default_factory=lambda: dict(DEFAULT_NO_BAR_HAIRCUT)) 

53 source: str = "file" # "file": rows from the weights file; "model_book": main.py computes each session's row (V6.6.9, default off) 

54 

55 

56TARGET_SOURCES = ("file", "model_book") 

57 

58 

59def _finite(value, default: float) -> float: 

60 try: 

61 number = float(value) 

62 except (TypeError, ValueError): 

63 return default 

64 return number if math.isfinite(number) else default 

65 

66 

67def resolve_target_weights_config(raw: Mapping[str, Any] | None) -> TargetWeightsConfig: 

68 """A `TargetWeightsConfig` from `phase_v2.target_weights`, every number finite and non-negative, defaults where missing.""" 

69 raw = raw or {} 

70 defaults = TargetWeightsConfig() 

71 numbers = { 

72 name: max(0.0, _finite(raw.get(name, getattr(defaults, name)), getattr(defaults, name))) 

73 for name in ( 

74 "min_weight_change", "min_trade_usd", "forex_min_trade_usd", "reserve_gross", "equity_fee_bps", 

75 "equity_min_fee_usd", "margin_spread_bps", "borrow_bps", "fx_spread_bps", 

76 ) 

77 } 

78 slippage = {**DEFAULT_SLIPPAGE_BPS} 

79 for name, value in (raw.get("slippage_bps_by_class") or {}).items(): 

80 slippage[str(name)] = max(0.0, _finite(value, slippage.get(str(name), 0.0))) 

81 haircut = {**DEFAULT_NO_BAR_HAIRCUT} 

82 for name, value in (raw.get("no_bar_haircut_by_class") or {}).items(): 

83 haircut[str(name)] = max(0.0, min(1.0, _finite(value, haircut.get(str(name), 0.0)))) 

84 return TargetWeightsConfig( 

85 live_reload=bool(raw.get("live_reload", False)), 

86 uses_model=bool(raw.get("uses_model", False)), 

87 no_bar_exit=bool(raw.get("no_bar_exit", False)), 

88 no_bar_exit_after=max(1, int(_finite(raw.get("no_bar_exit_after", defaults.no_bar_exit_after), defaults.no_bar_exit_after))), 

89 no_bar_haircut_by_class=haircut, 

90 enabled=bool(raw.get("enabled", False)), 

91 weights_path=str(raw.get("weights_path") or ""), 

92 weights_sha256=str(raw.get("weights_sha256") or ""), 

93 source=str(raw.get("source")) if raw.get("source") in TARGET_SOURCES else "file", 

94 slippage_bps_by_class=slippage, 

95 financing_enabled=bool(raw.get("financing_enabled", True)), 

96 **numbers, 

97 ) 

98 

99 

100def drop_class_weights( 

101 weights_by_date: Mapping[str, Mapping[str, float]], class_by_ticker: Mapping[str, str], dropped: Iterable[str] 

102) -> dict[str, dict[str, float]]: 

103 """The weight rows without the tickers of `dropped` asset classes (V6.6.9, #384): a name the per-bar disabled-class sweep 

104 would close each bar is never opened. Main.py and the offline engine call this one function, so both hold the same names.""" 

105 dropped = frozenset(dropped) 

106 if not dropped: 

107 return {date: dict(row) for date, row in weights_by_date.items()} 

108 return { 

109 date: {ticker: weight for ticker, weight in row.items() if class_by_ticker.get(ticker) not in dropped} 

110 for date, row in weights_by_date.items() 

111 } 

112 

113 

114def load_weight_file(path: Path | str, expected_sha256: str = "") -> dict[str, dict[str, float]]: 

115 """date -> ticker -> weight. Raises ValueError on a hash mismatch, a malformed row or a non-finite weight: a run 

116 must not trade a file other than the one its config froze.""" 

117 path = Path(path) 

118 payload = path.read_bytes() 

119 if expected_sha256: 

120 actual = hashlib.sha256(payload).hexdigest() 

121 if actual != expected_sha256: 

122 raise ValueError(f"{path.name}: sha256 {actual} is not the frozen {expected_sha256}") 

123 weights: dict[str, dict[str, float]] = {} 

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

125 reader = csv.DictReader(handle) 

126 if reader.fieldnames is None or not {"date", "ticker", "weight"} <= set(reader.fieldnames): 

127 raise ValueError(f"{path.name}: expected the columns date,ticker,weight") 

128 for row in reader: 

129 value = float(row["weight"]) 

130 if not math.isfinite(value): 

131 raise ValueError(f"{path.name}: non-finite weight for {row['ticker']} on {row['date']}") 

132 weights.setdefault(row["date"][:10], {})[row["ticker"]] = value 

133 return weights 

134 

135 

136def write_weight_file(weights_by_date: Mapping[str, Mapping[str, float]], path: Path | str) -> str: 

137 """Writes the file (LF, rows sorted, so one set of weights has one hash) and returns its sha256. A date with no 

138 positions gets a `__FLAT__` row with weight 0: without it, "go flat" would read as "no decision today".""" 

139 lines = ["date,ticker,weight"] 

140 for date in sorted(weights_by_date): 

141 row = {ticker: weight for ticker, weight in weights_by_date[date].items() if abs(_finite(weight, 0.0)) > 0.0} 

142 if not row: 

143 lines.append(f"{date},{FLAT_TICKER},0") 

144 for ticker in sorted(row): 

145 lines.append(f"{date},{ticker},{float(row[ticker]):.8f}") 

146 payload = ("\n".join(lines) + "\n").encode("utf-8") 

147 Path(path).write_bytes(payload) 

148 return hashlib.sha256(payload).hexdigest() 

149 

150 

151FLAT_TICKER = "__FLAT__" 

152 

153 

154def weights_at_tick(weights: Mapping[str, Mapping[str, float]], tick_date: str) -> dict[str, float] | None: 

155 """The decision taken at this date's equity close; None when the file has no row for it (hold what is held).""" 

156 row = weights.get(str(tick_date)[:10]) 

157 if row is None: 

158 return None 

159 return {ticker: float(weight) for ticker, weight in row.items() if ticker != FLAT_TICKER} 

160 

161 

162def next_unapplied_row( 

163 weights: Mapping[str, Mapping[str, float]], tick_date: str, applied_through: str | None, 

164) -> tuple[str, dict[str, float]] | None: 

165 """Paper and live (`live_reload`): the latest row dated at or before this tick and after the last one applied. Row D is 

166 written after D's close, so the exact-date lookup a backtest uses would miss every row.""" 

167 tick = str(tick_date)[:10] 

168 dates = [date for date in weights if date <= tick and (applied_through is None or date > applied_through)] 

169 if not dates: 

170 return None 

171 date = max(dates) 

172 return date, {ticker: float(weight) for ticker, weight in weights[date].items() if ticker != FLAT_TICKER} 

173 

174 

175def weights_sidecar(path: Path | str) -> Path: 

176 """`<weights>.sha256`: what a live run checks each reload against. The file grows daily, so no config can pin its hash.""" 

177 path = Path(path) 

178 return path.with_name(path.name + ".sha256") 

179 

180 

181def write_weights_sidecar(path: Path | str) -> str: 

182 """Records the file's current hash, atomically, so a reload never reads a half-written one.""" 

183 path = Path(path) 

184 digest = hashlib.sha256(path.read_bytes()).hexdigest() 

185 sidecar = weights_sidecar(path) 

186 temporary = sidecar.with_name(sidecar.name + ".tmp") 

187 temporary.write_text(digest + "\n", encoding="utf-8", newline="\n") 

188 temporary.replace(sidecar) 

189 return digest 

190 

191 

192def load_live_weight_file(path: Path | str) -> dict[str, dict[str, float]]: 

193 """A growing weight file, checked against its sidecar. Raises as `load_weight_file` does; the caller keeps what it has.""" 

194 return load_weight_file(path, weights_sidecar(path).read_text(encoding="utf-8").strip()) 

195 

196 

197def update_missing_bars( 

198 missing: Mapping[str, int], held_units: Mapping[str, float], has_bar: Mapping[str, bool], 

199) -> dict[str, int]: 

200 """Consecutive bars each held name has gone without one. A name not held, or with a bar, starts again from zero.""" 

201 return { 

202 ticker: int(missing.get(ticker, 0)) + 1 

203 for ticker, units in held_units.items() 

204 if _finite(units, 0.0) != 0.0 and not has_bar.get(ticker, False) 

205 } 

206 

207 

208def names_to_exit_without_bars(missing: Mapping[str, int], config: TargetWeightsConfig) -> list[str]: 

209 """Held names whose bars stopped, in a fixed order. This reacts only to bars already missing, so it reads no future: a 

210 delisted name can't be sold at any later price, and holding it at its last close forever would hide the loss.""" 

211 return sorted(ticker for ticker, count in missing.items() if count >= config.no_bar_exit_after) if config.no_bar_exit else [] 

212 

213 

214def no_bar_exit_cost_usd(units: float, last_close_usd: float, asset_class: str, config: TargetWeightsConfig) -> float: 

215 """What such an exit loses against the last close: Lean fills the order at that stale price, so this is charged on top.""" 

216 haircut = float(config.no_bar_haircut_by_class.get(str(asset_class), 0.0)) 

217 return abs(_finite(units, 0.0)) * max(0.0, _finite(last_close_usd, 0.0)) * haircut 

218 

219 

220def rebalance_deltas( 

221 held_units: Mapping[str, float], 

222 usd_per_unit: Mapping[str, float], 

223 nav: float, 

224 target: Mapping[str, float], 

225 config: TargetWeightsConfig, 

226 *, 

227 lot_size: Mapping[str, float] | None = None, 

228 class_by_ticker: Mapping[str, str] | None = None, 

229) -> list[tuple[str, float]]: 

230 """(ticker, signed units to trade), reductions first: Lean checks buying power when an order is submitted and does 

231 not net sells that have not filled. A ticker with no usable price is skipped, never traded on a guess. A ticker the 

232 target omits is closed in full; otherwise a change below the deadband or the minimum trade size is left alone.""" 

233 nav = _finite(nav, 0.0) 

234 if nav <= 0.0: 

235 return [] 

236 lots = lot_size or {} 

237 classes = class_by_ticker or {} 

238 orders: list[tuple[str, float, bool]] = [] 

239 for ticker in sorted(set(held_units) | set(target)): 

240 unit_value = _finite(usd_per_unit.get(ticker), 0.0) 

241 if unit_value <= 0.0: 

242 continue 

243 held = _finite(held_units.get(ticker, 0.0), 0.0) 

244 wanted = _finite(target.get(ticker, 0.0), 0.0) 

245 if wanted == 0.0: 

246 if held != 0.0: 

247 orders.append((ticker, -held, True)) 

248 continue 

249 current = held * unit_value / nav 

250 if abs(wanted - current) < config.min_weight_change: 

251 continue 

252 lot = _finite(lots.get(ticker, 1.0), 1.0) 

253 lot = lot if lot > 0.0 else 1.0 

254 lots_wanted = (wanted - current) * nav / unit_value / lot 

255 if not math.isfinite(lots_wanted): # an overflowing size is no order, never an OverflowError mid-bar (V6.6.7, #363) 

256 continue 

257 delta = math.trunc(lots_wanted) * lot 

258 notional = abs(delta) * unit_value 

259 minimum = config.forex_min_trade_usd if classes.get(ticker) == "forex" else config.min_trade_usd 

260 if delta == 0.0 or notional < minimum: 

261 continue 

262 # an order through zero (held +10, delta -30) opens exposure that needs buying power: it is not a reduction (#373) 

263 reduces = held != 0.0 and (delta < 0.0) == (held > 0.0) and abs(delta) <= abs(held) 

264 orders.append((ticker, delta, reduces)) 

265 orders.sort(key=lambda order: (not order[2], order[0])) 

266 return [(ticker, delta) for ticker, delta, _ in orders] 

267 

268 

269def equity_fee_usd(notional: float, bps: float, min_usd: float) -> float: 

270 """Commission in basis points with a dollar minimum. Used instead of Lean's per-share IB model on this path: the 

271 data is split- and dividend-adjusted, so an old adjusted price of $0.49 would make a per-share fee 1% of the trade.""" 

272 notional = abs(_finite(notional, 0.0)) 

273 return 0.0 if notional <= 0.0 else max(notional * bps / 1e4, min_usd) 

274 

275 

276def slippage_bps_for(asset_class: str, config: TargetWeightsConfig) -> float: 

277 """The slippage the simulator charges one asset class, in bps.""" 

278 return float(config.slippage_bps_by_class.get(str(asset_class), 0.0)) 

279 

280 

281def sweep_reserve(config: TargetWeightsConfig) -> dict[str, Any]: 

282 """What the T-bill sweep leaves free for the next session's orders on this path: a fixed share of gross, since the 

283 next row of the file must not be read before its date.""" 

284 return strategy_reserve( 

285 rebalance_next=True, book_gross_cap=config.reserve_gross, max_short_exposure=config.reserve_gross, 

286 formed_long=0.0, formed_short=0.0, book_long=0.0, book_short=0.0, other_budget_remaining=0.0, 

287 )