Coverage for evaluation/target_weights_engine.py: 100%

291 statements  

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

1"""Offline engine of the target-weights path (V6.5.0): the same orders as `main.py::_target_weights_tick`, in seconds. 

2 

3Timeline of one decision dated D, as Lean runs it at daily resolution: 

4 * the equity bar of D arrives at 16:00 D; the row is read; crypto and forex closes known then are the bars dated D-1; 

5 * equity orders (including the T-bill sweep) fill at the next session's open; 

6 * crypto and forex orders wait for the bar dated D, which closes at the following midnight, and fill at its close. 

7 

8A row labelled D is what Lean's daily sample of D shows: equities at the close of D, crypto and forex at the close of the bar 

9dated before D (the one that ended at midnight, as D began). That is the timing `known_closes` gives the signals too. 

10 

11Cash is kept per currency, as Lean's cash book does, so a USD-base pair such as USDJPY earns its P&L in the quote currency. 

12Calls the pure functions main.py calls (`portfolio.target_weights`, `portfolio.financing`, `portfolio.cash_sweep`). 

13""" 

14 

15from __future__ import annotations 

16 

17from collections.abc import Callable, Mapping 

18from dataclasses import dataclass, field 

19from pathlib import Path 

20from typing import Any 

21 

22import numpy as np 

23import pandas as pd 

24 

25from features.fx_carry import split_forex_ticker 

26from portfolio.cash_sweep import ( 

27 cash_sweep_target_weight, 

28 margin_fraction, 

29 resolve_cash_sweep_config, 

30 sweep_order_needed, 

31) 

32from portfolio.financing import daily_financing_usd, rate_asof 

33from portfolio.target_weights import ( 

34 NEXT_BAR_CLASSES, 

35 TargetWeightsConfig, 

36 drop_class_weights, 

37 equity_fee_usd, 

38 names_to_exit_without_bars, 

39 no_bar_exit_cost_usd, 

40 rebalance_deltas, 

41 slippage_bps_for, 

42 sweep_reserve, 

43 update_missing_bars, 

44 weights_at_tick, 

45) 

46 

47SWEEP_CLASS = "cash_sweep" 

48CRYPTO_LOT = 1e-6 

49 

50 

51def coinbase_taker_bps(date: str) -> float: 

52 """Taker fee of Lean's date-effective CoinbaseFeeModel for a market order on a USD pair, in bps, as its fills show.""" 

53 if date < "2019-10-08": 

54 return 30.0 if date < "2019-03-23" else 25.0 

55 return 80.0 

56 

57 

58def default_fee_usd(asset_class: str, notional: float, date: str, config: TargetWeightsConfig) -> float: 

59 """The fee the target-weights simulator charges one fill: Coinbase taker on crypto, 0.2 bps (min $2) on forex, the equity terms otherwise.""" 

60 if asset_class == "crypto": 

61 return abs(notional) * coinbase_taker_bps(date) / 1e4 

62 if asset_class == "forex": 

63 return 0.0 if notional == 0.0 else max(abs(notional) * 0.2 / 1e4, 2.0) 

64 return equity_fee_usd(notional, config.equity_fee_bps, config.equity_min_fee_usd) 

65 

66 

67@dataclass 

68class MarketPanel: 

69 """Bars by calendar date (a NaN where the ticker has no bar that day). `sessions` are the equity sessions.""" 

70 

71 dates: list[str] 

72 tickers: list[str] 

73 opens: np.ndarray 

74 closes: np.ndarray 

75 asset_class: dict[str, str] 

76 sessions: set[str] = field(default_factory=set) 

77 

78 def index(self) -> dict[str, int]: 

79 return {ticker: i for i, ticker in enumerate(self.tickers)} 

80 

81 

82def load_market_panel(root: Path, config: dict[str, Any], *, extra_equity: tuple[str, ...] = ("BIL",), data_dir: str = "data") -> MarketPanel: 

83 """Every universe asset plus the sweep ticker, from the Lean zips under `root/data_dir`.""" 

84 from data_pipeline.data_audit import asset_zip_paths, read_lean_daily_zip 

85 

86 frames: dict[str, pd.DataFrame] = {} 

87 classes: dict[str, str] = {} 

88 assets = list(config["phase1"]["universe"]["assets"]) 

89 for ticker in extra_equity: 

90 if ticker not in {str(asset["ticker"]) for asset in assets}: 

91 assets.append({"ticker": ticker, "security_type": "equity", "asset_class": SWEEP_CLASS, 

92 "data_path": f"data/equity/usa/daily/{ticker.lower()}.zip"}) 

93 for asset in assets: 

94 path = asset_zip_paths(asset, Path(root) / data_dir)["trade"] 

95 if not path.exists(): 

96 continue 

97 frame = read_lean_daily_zip(path, str(asset.get("security_type"))) 

98 if frame.empty: 

99 continue 

100 ticker = str(asset["ticker"]) 

101 frames[ticker] = frame.set_index(frame["date"].dt.strftime("%Y-%m-%d"))[["open", "close"]] 

102 classes[ticker] = str(asset.get("asset_class") or asset.get("security_type")) 

103 dates = sorted({date for frame in frames.values() for date in frame.index}) 

104 tickers = sorted(frames) 

105 opens = np.full((len(dates), len(tickers)), np.nan) 

106 closes = np.full((len(dates), len(tickers)), np.nan) 

107 position = {date: i for i, date in enumerate(dates)} 

108 sessions: set[str] = set() 

109 for column, ticker in enumerate(tickers): 

110 frame = frames[ticker] 

111 rows = [position[date] for date in frame.index] 

112 opens[rows, column] = frame["open"].to_numpy(float) 

113 closes[rows, column] = frame["close"].to_numpy(float) 

114 if classes[ticker] in ("equity", "bond", SWEEP_CLASS): 

115 sessions.update(frame.index) 

116 return MarketPanel(dates, tickers, opens, closes, classes, sessions) 

117 

118 

119def _usd_rates(closes_ff: np.ndarray, index: Mapping[str, int]) -> dict[str, np.ndarray]: 

120 """USD per one unit of each currency, by date, from the USD pairs in the panel.""" 

121 rates = {"USD": np.ones(closes_ff.shape[0])} 

122 for ticker, column in index.items(): 

123 pair = split_forex_ticker(ticker) 

124 if pair is None: 

125 continue 

126 base, quote = pair 

127 if quote == "USD": 

128 rates[base] = closes_ff[:, column] 

129 elif base == "USD": 

130 with np.errstate(divide="ignore", invalid="ignore"): 

131 rates[quote] = 1.0 / closes_ff[:, column] 

132 return rates 

133 

134 

135def simulate_target_weights( 

136 weights_by_date: Mapping[str, Mapping[str, float]], 

137 panel: MarketPanel, 

138 config: TargetWeightsConfig, 

139 *, 

140 start: str, 

141 end: str, 

142 nav: float = 100_000.0, 

143 sweep_config: dict[str, Any] | None = None, 

144 sweep_ticker: str = "BIL", 

145 rf_dates: list[str] | None = None, 

146 rf_rates: list[float] | None = None, 

147 carry_fn: Callable[[str, str], float] | None = None, 

148 max_total_drawdown: float | None = None, 

149 max_drawdown_velocity: float | None = None, 

150 fee_fn: Callable[[str, float, str, TargetWeightsConfig], float] = default_fee_usd, 

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

152 disabled_classes: frozenset[str] = frozenset(), 

153) -> dict[str, Any]: 

154 """One path over [start, end]. Returns {"nav", "strategy" (ex-sweep daily return), "strategy_excess" (that, less the 

155 risk-free return on the net capital invested), "total" (daily return), "gross", "fees", "financing", "turnover", "fills", 

156 "locked_on"}, the series indexed by calendar date. 

157 

158 "strategy" is what Lean reports. Ex-sweep, a long book pays nothing for the cash it ties up, which the sweep would have 

159 earned, so a long sleeve's Sharpe is raw and not excess unless it is scored on "strategy_excess". A forex position is 

160 self-financed and has no such cost. 

161 

162 A drawdown lock (on the strategy, ex sweep, as main.py reads it) closes everything at the next fills and stops trading.""" 

163 index = panel.index() 

164 classes = {ticker: panel.asset_class.get(ticker, "equity") for ticker in panel.tickers} 

165 if disabled_classes: 

166 weights_by_date = drop_class_weights(weights_by_date, classes, disabled_classes) 

167 next_bar_columns = [index[ticker] for ticker in panel.tickers if classes[ticker] in NEXT_BAR_CLASSES] 

168 closes_ff = pd.DataFrame(panel.closes).ffill().to_numpy(copy=True) # pandas 3 hands out read-only views 

169 # a crypto or forex bar reaches this row's label when it ended, at the midnight that began this row 

170 if next_bar_columns: 

171 closes_ff[1:, next_bar_columns] = closes_ff[:-1, next_bar_columns].copy() 

172 closes_ff[0, next_bar_columns] = np.nan 

173 rates = _usd_rates(closes_ff, index) 

174 sweep = resolve_cash_sweep_config(sweep_config) if sweep_config else None 

175 sweep_column = index.get(sweep_ticker) if sweep and sweep.get("enabled") else None 

176 columns = [(ticker, column) for ticker, column in index.items() if column != sweep_column or sweep_column is None] 

177 pairs = {ticker: split_forex_ticker(ticker) if classes[ticker] == "forex" else None for ticker in panel.tickers} 

178 if lot_size is None: 

179 lot_size = {ticker: CRYPTO_LOT for ticker in panel.tickers if classes[ticker] == "crypto"} 

180 

181 units = np.zeros(len(panel.tickers)) 

182 cash: dict[str, float] = {"USD": float(nav)} 

183 pending_open: dict[str, float] = {} 

184 pending_target: dict[str, float] | None = None 

185 positions = [i for i, date in enumerate(panel.dates) if start <= date <= end] 

186 

187 nav_series, strategy_series, excess_series, total_series, gross_series = {}, {}, {}, {}, {} 

188 net_invested_previous = 0.0 

189 previous_date = None 

190 missing_bars: dict[str, int] = {} 

191 no_bar_exits: list[str] = [] 

192 fees = financing_total = traded = 0.0 

193 fills = 0 

194 previous_nav = None 

195 strategy_value = None 

196 sweep_pnl_previous = 0.0 

197 sweep_cost = 0.0 

198 sweep_units = 0.0 

199 peak = None 

200 previous_drawdown = 0.0 

201 locked_on = None 

202 last_financing_date = None 

203 

204 def usd_rate(currency: str, row: int) -> float: 

205 series = rates.get(currency) 

206 value = float(series[row]) if series is not None else float("nan") 

207 return value if np.isfinite(value) and value > 0.0 else 0.0 

208 

209 def unit_value(ticker: str, row: int) -> float: 

210 price = float(closes_ff[row, index[ticker]]) 

211 if not np.isfinite(price) or price <= 0.0: 

212 return 0.0 

213 pair = pairs[ticker] 

214 return price * usd_rate(pair[1], row) if pair else price 

215 

216 def value_now(row: int) -> float: 

217 total = sum(amount * usd_rate(currency, row) for currency, amount in cash.items()) 

218 for ticker, column in index.items(): 

219 if units[column] != 0.0 and pairs[ticker] is None: 

220 price = closes_ff[row, column] 

221 if np.isfinite(price): 

222 total += units[column] * price 

223 return float(total) 

224 

225 def fill(ticker: str, delta: float, raw_price: float, row: int, date: str) -> None: 

226 nonlocal fees, traded, fills, sweep_cost, sweep_units 

227 column = index[ticker] 

228 asset_class = classes[ticker] 

229 bps = 1.0 if column == sweep_column else slippage_bps_for(asset_class, config) 

230 price = raw_price * (1.0 + bps / 1e4) if delta > 0 else raw_price * (1.0 - bps / 1e4) 

231 pair = pairs[ticker] 

232 if pair: 

233 cash[pair[0]] = cash.get(pair[0], 0.0) + delta 

234 cash[pair[1]] = cash.get(pair[1], 0.0) - delta * price 

235 notional = abs(delta) * price * usd_rate(pair[1], row) 

236 else: 

237 cash["USD"] = cash["USD"] - delta * price 

238 notional = abs(delta) * price 

239 fee = fee_fn(asset_class if column != sweep_column else "equity", notional, date, config) 

240 cash["USD"] -= fee 

241 fees += fee 

242 traded += notional if column != sweep_column else 0.0 

243 fills += 1 

244 if column == sweep_column: 

245 sweep_cost += delta * price + fee 

246 sweep_units += delta 

247 units[column] += delta 

248 

249 for row in positions: 

250 date = panel.dates[row] 

251 is_session = date in panel.sessions 

252 

253 # a crypto or forex order fills as soon as its next bar has closed, at the midnight that begins this row 

254 if pending_target and row > 0: 

255 fresh = {ticker for ticker in pending_target if np.isfinite(panel.closes[row - 1, index[ticker]])} 

256 if fresh: 

257 held = {ticker: float(units[index[ticker]]) for ticker in fresh} 

258 values = {ticker: unit_value(ticker, row) for ticker in fresh} 

259 target = {ticker: weight for ticker, weight in pending_target.items() if ticker in fresh and weight != 0.0} 

260 deltas = rebalance_deltas(held, values, value_now(row), target, config, lot_size=lot_size, class_by_ticker=classes) 

261 for ticker, delta in deltas: 

262 fill(ticker, delta, float(closes_ff[row, index[ticker]]), row, date) 

263 pending_target = {t: w for t, w in pending_target.items() if t not in fresh} or None 

264 

265 if config.no_bar_exit: 

266 held_now = {ticker: float(units[column]) for ticker, column in columns if units[column] != 0.0} 

267 has_bar = {} 

268 for ticker in held_now: 

269 late = classes[ticker] in NEXT_BAR_CLASSES 

270 if not late and not is_session: 

271 has_bar[ticker] = True # an equity session did not happen: nothing went missing 

272 else: 

273 has_bar[ticker] = row > 0 and np.isfinite(panel.closes[row - 1 if late else row, index[ticker]]) 

274 missing_bars = update_missing_bars(missing_bars, held_now, has_bar) 

275 for ticker in names_to_exit_without_bars(missing_bars, config): 

276 column = index[ticker] 

277 price = unit_value(ticker, row) 

278 cash["USD"] += float(units[column]) * price - no_bar_exit_cost_usd(units[column], price, classes[ticker], config) 

279 units[column] = 0.0 

280 missing_bars.pop(ticker, None) 

281 pending_open.pop(ticker, None) 

282 if pending_target: 

283 pending_target = {name: weight for name, weight in pending_target.items() if name != ticker} or None 

284 no_bar_exits.append(f"{date}:{ticker}") 

285 

286 if is_session and pending_open: 

287 for ticker, delta in pending_open.items(): 

288 raw = panel.opens[row, index[ticker]] 

289 if np.isfinite(raw) and raw > 0.0: 

290 fill(ticker, delta, float(raw), row, date) 

291 pending_open = {} 

292 

293 nav_now = value_now(row) 

294 

295 if is_session and config.financing_enabled and last_financing_date is not None: 

296 days = (pd.Timestamp(date) - pd.Timestamp(last_financing_date)).days 

297 long_usd = short_usd = 0.0 

298 fx_positions = [] 

299 for ticker, column in index.items(): 

300 if units[column] == 0.0: 

301 continue 

302 value = units[column] * unit_value(ticker, row) 

303 if pairs[ticker]: 

304 fx_positions.append((value, carry_fn(ticker, date) if carry_fn else 0.0)) 

305 elif value > 0.0: 

306 long_usd += value 

307 else: 

308 short_usd -= value 

309 rf = rate_asof(rf_dates or [], rf_rates or [], date) 

310 amount = daily_financing_usd( 

311 long_usd=long_usd, short_usd=short_usd, nav=nav_now, rf_annual_pct=rf, fx_positions=fx_positions, 

312 days=days, margin_spread_bps=config.margin_spread_bps, borrow_bps=config.borrow_bps, 

313 fx_spread_bps=config.fx_spread_bps, 

314 ) 

315 cash["USD"] += amount 

316 financing_total += amount 

317 nav_now += amount 

318 if is_session: 

319 last_financing_date = date 

320 

321 # main.py evaluates the lock on the session's own tick, with that session's close already in the marks 

322 if is_session and locked_on is None and peak and previous_nav: 

323 sweep_now = 0.0 

324 if sweep_column is not None and (sweep_units != 0.0 or sweep_cost != 0.0): 

325 sweep_price = closes_ff[row, sweep_column] 

326 if np.isfinite(sweep_price): 

327 sweep_now = sweep_units * sweep_price - sweep_cost 

328 provisional = strategy_value * (1.0 + ((nav_now - previous_nav) - (sweep_now - sweep_pnl_previous)) / previous_nav) 

329 drawdown = 1.0 - provisional / max(peak, provisional) 

330 velocity = drawdown - previous_drawdown 

331 previous_drawdown = drawdown 

332 if (max_total_drawdown is not None and drawdown >= max_total_drawdown) or ( 

333 max_drawdown_velocity is not None and velocity >= max_drawdown_velocity 

334 ): 

335 locked_on = date 

336 weights_by_date = {} 

337 pending_target = { 

338 ticker: 0.0 for ticker in index 

339 if units[index[ticker]] != 0.0 and classes[ticker] in NEXT_BAR_CLASSES 

340 } or None 

341 pending_open = { 

342 ticker: -float(units[index[ticker]]) for ticker in index 

343 if units[index[ticker]] != 0.0 and classes[ticker] not in NEXT_BAR_CLASSES and index[ticker] != sweep_column 

344 } 

345 

346 if is_session: 

347 target_row = weights_at_tick(weights_by_date, date) 

348 if target_row is not None: 

349 target_row = { 

350 ticker: (max(0.0, weight) if classes[ticker] == "crypto" else weight) 

351 for ticker, weight in target_row.items() if ticker in index and index[ticker] != sweep_column 

352 } 

353 equity_like = { 

354 ticker for ticker, column in index.items() 

355 if classes[ticker] not in NEXT_BAR_CLASSES and column != sweep_column and (units[column] != 0.0 or ticker in target_row) 

356 } 

357 held = {ticker: float(units[index[ticker]]) for ticker in equity_like} 

358 values = {ticker: unit_value(ticker, row) for ticker in equity_like} 

359 target = {ticker: weight for ticker, weight in target_row.items() if ticker in equity_like} 

360 for ticker, delta in rebalance_deltas(held, values, nav_now, target, config, lot_size=lot_size, class_by_ticker=classes): 

361 pending_open[ticker] = delta 

362 pending_target = { 

363 ticker: target_row.get(ticker, 0.0) for ticker, column in index.items() 

364 if classes[ticker] in NEXT_BAR_CLASSES and (ticker in target_row or units[column] != 0.0) 

365 } or None 

366 

367 if sweep_column is not None: 

368 long_weight = short_weight = 0.0 

369 margin_inputs = [] 

370 for ticker, column in index.items(): 

371 if column == sweep_column: 

372 continue 

373 quantity = units[column] + pending_open.get(ticker, 0.0) 

374 if quantity == 0.0: 

375 continue 

376 weight = quantity * unit_value(ticker, row) / nav_now if nav_now > 0.0 else 0.0 

377 margin_inputs.append(({"crypto": "crypto", "forex": "forex"}.get(classes[ticker], "equity"), weight)) 

378 if weight > 0.0: 

379 long_weight += weight 

380 else: 

381 short_weight -= weight 

382 sweep_target = cash_sweep_target_weight( 

383 long_weight=long_weight, short_weight=short_weight, margin_used=margin_fraction(margin_inputs), 

384 reserve=sweep_reserve(config), config=sweep, 

385 ) 

386 price = float(closes_ff[row, sweep_column]) 

387 if np.isfinite(price) and price > 0.0 and nav_now > 0.0: 

388 current = units[sweep_column] * price / nav_now 

389 if sweep_order_needed(current, sweep_target, sweep["min_trade_weight"]): 

390 quantity = float(int((sweep_target - current) * nav_now / price)) 

391 if sweep_target <= 0.0: 

392 quantity = -float(units[sweep_column]) 

393 if quantity != 0.0: 

394 pending_open[sweep_ticker] = quantity 

395 

396 nav_now = value_now(row) 

397 sweep_pnl = 0.0 

398 if sweep_column is not None and (sweep_units != 0.0 or sweep_cost != 0.0): 

399 price = closes_ff[row, sweep_column] 

400 if np.isfinite(price): 

401 sweep_pnl = sweep_units * price - sweep_cost 

402 if previous_nav is not None and previous_nav > 0.0: 

403 total_series[date] = nav_now / previous_nav - 1.0 

404 strategy_series[date] = ((nav_now - previous_nav) - (sweep_pnl - sweep_pnl_previous)) / previous_nav 

405 days_held = (pd.Timestamp(date) - pd.Timestamp(previous_date)).days if previous_date else 1 

406 rf_annual = rate_asof(rf_dates or [], rf_rates or [], date) / 100.0 

407 excess_series[date] = strategy_series[date] - net_invested_previous * rf_annual * days_held / 365.0 

408 if nav_now > 0.0: 

409 net_invested_previous = sum( 

410 units[column] * unit_value(ticker, row) for ticker, column in columns if units[column] != 0.0 and pairs[ticker] is None 

411 ) / nav_now 

412 previous_date = date 

413 previous_nav = nav_now 

414 sweep_pnl_previous = sweep_pnl 

415 nav_series[date] = nav_now 

416 gross_series[date] = ( 

417 sum(abs(units[column]) * unit_value(ticker, row) for ticker, column in columns if units[column] != 0.0) / nav_now 

418 if nav_now > 0.0 else 0.0 

419 ) 

420 

421 if strategy_value is None: 

422 strategy_value = nav_now 

423 peak = nav_now 

424 elif date in strategy_series: 

425 strategy_value *= 1.0 + strategy_series[date] 

426 peak = max(peak, strategy_value) 

427 

428 years = max(len(positions) / 365.25, 1e-9) 

429 return { 

430 "nav": pd.Series(nav_series, dtype=float), 

431 "strategy": pd.Series(strategy_series, dtype=float), 

432 "strategy_excess": pd.Series(excess_series, dtype=float), 

433 "no_bar_exits": no_bar_exits, 

434 "total": pd.Series(total_series, dtype=float), 

435 "gross": pd.Series(gross_series, dtype=float), 

436 "fees": fees, 

437 "financing": financing_total, 

438 "turnover": traded / (sum(nav_series.values()) / len(nav_series) if nav_series else float(nav)) / years, 

439 "fills": fills, 

440 "locked_on": locked_on, 

441 }