Coverage for scripts/predict_sweep_bt1.py: 100%
130 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Predict a Lean run WITH the T-bill cash sweep from a finished run WITHOUT it (V6.2.0, written before BT1).
3The sweep stays outside the strategy's risk controls (the kill switch and the drawdown lock read the strategy value
4without it), so the book's decisions do not change and the run's own daily holdings and rebalance calendar decide the
5sweep exactly as main.py would (portfolio/cash_sweep.py):
7 * holdings after day D's orders = the positions at the end of the next equity session (orders fill at its open);
8 * a rebalance attempt next session = the next session is a book-history date (live logs every attempt, engaged or
9 vetoed); the formed book = the last attempt's target weights (empty after a veto, as live's _book_target_weights);
10 * the sweep decided on D is bought at D+1 and earns BIL's close-to-close moves from then on; IB's per-share fee
11 ($0.005, $1 minimum) and the configured slippage are charged on every trade.
13The counterfactual daily performance (Lean's own list plus the sweep's P&L over the previous day's equity) is priced
14with evaluation/lean_statistics.py on the refreshed risk-free file at 252 and 365 days a year.
16 python scripts/predict_sweep_bt1.py [--backtest-dir backtests/2026-10-16_18-23-01] [--out ml/evaluation/v620/bt1_prediction.json]
17"""
19from __future__ import annotations
21import argparse
22import json
23import sys
24from pathlib import Path
26ROOT_DIR = Path(__file__).resolve().parents[1]
27sys.path.insert(0, str(ROOT_DIR))
29IB_FEE_PER_SHARE = 0.005
30IB_MIN_FEE = 1.0
33def main() -> int:
34 from evaluation.backtest_audit import daily_equity_from_chart, load_backtest_run
35 from evaluation.lean_attribution import (
36 LEAN_EQUITY_PRICE_SCALE,
37 closes_for_universe,
38 daily_ticker_pnl,
39 fills_from_order_events,
40 find_book_history_for_run,
41 read_daily_closes,
42 run_config_path,
43 )
44 from evaluation.lean_statistics import (
45 lean_statistics,
46 load_backtest_series,
47 load_interest_rate_changes,
48 with_extra_daily_returns,
49 )
50 from json_safety import atomic_write_json, sanitize_json_finite
51 from portfolio.cash_sweep import cash_sweep_target_weight, margin_fraction, resolve_cash_sweep_config, strategy_reserve
53 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
54 parser.add_argument("--backtest-dir", default=str(ROOT_DIR / "backtests" / "2026-10-16_18-23-01"))
55 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v620" / "bt1_prediction.json"))
56 args = parser.parse_args()
58 run_dir = Path(args.backtest_dir)
59 config = json.loads(Path(run_config_path(run_dir, ROOT_DIR)).read_text(encoding="utf-8"))
60 shipped = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
61 sweep_config = dict(resolve_cash_sweep_config(shipped["phase_v2"].get("cash_sweep")), enabled=True)
62 history_path = find_book_history_for_run(run_dir, ROOT_DIR / "visualization" / "book_history")
63 history = [json.loads(line) for line in history_path.read_text(encoding="utf-8").splitlines() if line.strip()]
64 attempts = {record["date"]: {key: float(value.get("target_weight", 0.0)) for key, value in (record.get("allocations") or {}).items()}
65 for record in history}
67 run = load_backtest_run(run_dir)
68 fills = fills_from_order_events(run["order_events"])
69 daily_equity = daily_equity_from_chart(run["result"])
70 equity_by_date = dict(daily_equity)
71 dates = [date for date, _ in daily_equity]
72 closes = closes_for_universe(config, ROOT_DIR, {fill.ticker for fill in fills})
73 forex = {str(a["ticker"]).upper() for a in config["phase1"]["universe"]["assets"] if a.get("security_type") == "forex"}
74 ticker_pnl = daily_ticker_pnl(fills, closes, dates, forex)
75 types = {str(a["ticker"]).upper(): str(a.get("security_type", "equity")) for a in config["phase1"]["universe"]["assets"]}
76 bil = read_daily_closes(ROOT_DIR / sweep_config["data_path"], LEAN_EQUITY_PRICE_SCALE)
77 spy = read_daily_closes(ROOT_DIR / "data" / "equity" / "usa" / "daily" / "spy.zip", LEAN_EQUITY_PRICE_SCALE)
78 sessions = [date for date in sorted(spy) if dates[0] <= date <= dates[-1]]
80 phase_v2 = config["phase_v2"]
81 legacy, bond = phase_v2.get("legacy_sleeve", {}), phase_v2.get("bond_sleeve", {})
82 other = float(legacy.get("max_gross_exposure", 0.0)) if legacy.get("enabled") else 0.0
83 neutral = float(bond.get("gross_budget", 0.0)) if bond.get("enabled") else 0.0
84 cap = float(phase_v2["portfolio_book"]["neutrality"]["gross_exposure_cap"])
85 max_short = float(config.get("phase9", {}).get("portfolio", {}).get("max_short_exposure", 0.30))
87 positions_by_date: dict[str, dict[str, float]] = {}
88 running: dict[str, float] = {}
89 for date in sorted(ticker_pnl):
90 for ticker, entry in ticker_pnl[date].items():
91 running[ticker] = float(entry["position"])
92 positions_by_date[date] = dict(running)
94 shares, pnl_by_date, weights, cash_floor, trades, fees = 0, {}, [], [], 0, 0.0
95 formed: dict[str, float] = {}
96 pending_shares = None
97 previous_bil = None
98 for date in dates:
99 price = bil.get(date)
100 if price is not None:
101 if previous_bil is not None and shares:
102 pnl_by_date[date] = pnl_by_date.get(date, 0.0) + shares * (price - previous_bil)
103 previous_bil = price
104 if pending_shares is not None and date in bil: # the order placed on the previous session fills today
105 traded = abs(pending_shares - shares)
106 if traded:
107 cost = max(IB_MIN_FEE, IB_FEE_PER_SHARE * traded) + traded * price * sweep_config["cost_bps_per_side"] / 1e4
108 pnl_by_date[date] = pnl_by_date.get(date, 0.0) - cost
109 fees += cost
110 trades += 1
111 shares, pending_shares = pending_shares, None
112 if date not in spy:
113 continue
114 if date in attempts:
115 formed = attempts[date]
116 position = sessions.index(date)
117 next_session = sessions[position + 1] if position + 1 < len(sessions) else None
118 if next_session is None or date not in bil:
119 continue
120 equity = equity_by_date.get(next_session) or equity_by_date.get(date)
121 holdings = positions_by_date.get(next_session, {})
122 long_weight = short_weight = book_long = book_short = 0.0
123 margin_inputs = []
124 for ticker, quantity in holdings.items():
125 close = closes.get(ticker, {}).get(next_session)
126 if not quantity or close is None or not equity:
127 continue
128 weight = quantity * close / equity
129 margin_inputs.append((types.get(ticker, "equity"), weight))
130 if weight > 0:
131 long_weight += weight
132 book_long += weight if ticker in formed else 0.0
133 else:
134 short_weight -= weight
135 book_short -= weight if ticker in formed else 0.0
136 reserve = strategy_reserve(
137 rebalance_next=next_session in attempts, book_gross_cap=cap, max_short_exposure=max_short,
138 formed_long=sum(w for w in formed.values() if w > 0), formed_short=-sum(w for w in formed.values() if w < 0),
139 book_long=book_long, book_short=book_short, other_budget_remaining=other, neutral_budget=neutral,
140 )
141 target = cash_sweep_target_weight(long_weight=long_weight, short_weight=short_weight,
142 margin_used=margin_fraction(margin_inputs), reserve=reserve, config=sweep_config)
143 current = shares * price / equity_by_date.get(date, equity)
144 weights.append(target)
145 cash_floor.append(1.0 - long_weight + short_weight - target)
146 if current > target + 1e-9 or abs(target - current) >= sweep_config["min_trade_weight"]:
147 pending_shares = int(target * equity_by_date.get(date, equity) / price)
149 series = load_backtest_series(next(path for path in run_dir.glob("*.json") if path.stem.isdigit()))
150 previous_equity = dict(zip(dates[1:], [v for _, v in daily_equity[:-1]], strict=False))
151 extra = {}
152 from datetime import date as _date
154 for day in series["performance_dates"]:
155 key = day.isoformat()
156 if key in pnl_by_date and previous_equity.get(key):
157 extra[_date.fromisoformat(key)] = pnl_by_date[key] / previous_equity[key]
158 counterfactual = with_extra_daily_returns(series["performance"], series["performance_dates"], extra)
159 refreshed = load_interest_rate_changes(ROOT_DIR / "data" / "alternative" / "interest-rate" / "usa" / "interest-rate.csv")
160 old_file = ROOT_DIR / "ml" / "evaluation" / "v620" / "interest-rate_pre_v620.csv"
161 stats = {}
162 for label, changes in (("refreshed", refreshed), ("pre_v620", load_interest_rate_changes(old_file) if old_file.exists() else refreshed)):
163 for days in (252, 365):
164 stats[f"with_sweep/{label}/{days}"] = lean_statistics(counterfactual, series["equity_dates"], trading_days_per_year=days, rate_changes=changes)
165 stats[f"without_sweep/{label}/{days}"] = lean_statistics(series["performance"], series["equity_dates"], trading_days_per_year=days, rate_changes=changes)
167 cumulative, peak, drawdown, equity_with = 0.0, 0.0, 0.0, []
168 for date, value in daily_equity:
169 cumulative += pnl_by_date.get(date, 0.0)
170 total = value + cumulative
171 peak = max(peak, total)
172 drawdown = min(drawdown, total / peak - 1.0)
173 equity_with.append(total)
174 report = {
175 "run": run_dir.name, "book_history": history_path.name, "written_before_bt1": True,
176 "sweep_config": sweep_config,
177 "sweep_net_pnl_usd": sum(pnl_by_date.values()), "sweep_fees_usd": fees, "sweep_trades": trades,
178 "mean_target_weight": sum(weights) / len(weights) if weights else 0.0, "max_target_weight": max(weights or [0.0]),
179 "min_cash_fraction_after_sweep": min(cash_floor or [1.0]),
180 "end_equity_without": daily_equity[-1][1], "end_equity_with": equity_with[-1] if equity_with else None,
181 "max_drawdown_with_sweep": drawdown,
182 "lean_statistics": stats,
183 }
184 atomic_write_json(Path(args.out), sanitize_json_finite(report), indent=2)
185 print(f"{run_dir.name} + sweep: P&L ${report['sweep_net_pnl_usd']:,.0f} (fees ${fees:,.0f}, {trades} trades), mean weight "
186 f"{report['mean_target_weight']:.2f}, max {report['max_target_weight']:.2f}, min cash {report['min_cash_fraction_after_sweep']:.3f}, "
187 f"drawdown {drawdown:.2%}")
188 for key in ("without_sweep/pre_v620/252", "without_sweep/refreshed/365", "with_sweep/refreshed/252", "with_sweep/refreshed/365"):
189 print(f" {key:30s} Sharpe {stats[key]['sharpe_ratio']:+.3f} annual {stats[key]['annual_return']:+.2%} "
190 f"std {stats[key]['annual_standard_deviation']:.4f}")
191 print(f"written {args.out}")
192 return 0
195if __name__ == "__main__":
196 raise SystemExit(main())