Coverage for scripts/forex_sleeve_research.py: 100%
54 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"""Forex sleeve research (V5.7.0, plan F4.1 / F4.2 / F4.5): does a concentrated forex book earn its way past IB's $2 minimum?
3Forex is switched off because at ~2% of NAV per leg the $2 minimum commission is ~8-10 bps per fill and the gross edge was
4~0. This asks the same question for a SLEEVE: its own pool (the forex pairs ranked among themselves), `k` longs and `k`
5shorts, a gross budget that makes each leg big enough for the minimum to be small, a 20-bar hold and a dollar deadband.
7Everything runs through the same `simulate_rank_book` the as-live book uses (selection, hysteresis, entry lag, per-order
8dollar-floor commission) on the forex rows only, on BOTH splits; the rule R-FX (offline half) is applied to the result:
10 ships to a Lean backtest only if the sleeve's net Sharpe is > 0 on validation AND on the backtest split AND the forex
11 rank IC (within the pairs) is > 0 on validation, and adding it does not lower the main book's backtest Sharpe by > 0.05.
13 python scripts/forex_sleeve_research.py [--no-cache] -> ml/evaluation/forex_sleeve_research.json
14"""
16from __future__ import annotations
18import argparse
19import json
20import sys
21from pathlib import Path
23ROOT_DIR = Path(__file__).resolve().parents[1]
24sys.path.insert(0, str(ROOT_DIR))
25sys.path.insert(0, str(Path(__file__).resolve().parent))
27from as_live_levers import AsLiveHarness # noqa: E402
29from evaluation import simulate_rank_book # noqa: E402
30from evaluation.rank_ic_core import newey_west_t_stat, rank_ic_from_arrays # noqa: E402
31from portfolio.forex_sleeve import build_forex_sleeve_weights # noqa: E402
33NAV = 100_000.0
36def forex_rank_ic(frame, score_column: str = "live_rank_score") -> dict:
37 """Daily rank IC of the score against the 20d forward return ranked AMONG THE PAIRS (the dataset's own rank target is
38 ranked in the full universe, which is the wrong cross-section for a sleeve that only ranks forex)."""
39 work = frame.dropna(subset=[score_column, "target_return_20d"]).copy()
40 work["own_rank"] = work.groupby("date")["target_return_20d"].rank(pct=True)
41 result = rank_ic_from_arrays(
42 work[score_column].to_numpy(), work["own_rank"].to_numpy(), work["date"].to_numpy(), min_names_per_date=8
43 )
44 return {
45 "daily_mean_ic": result["mean_ic"], "hac_t": newey_west_t_stat(result["ic_values"], 19), "num_dates": result["num_dates"],
46 }
49def sleeve_run(frame, base: dict, *, per_side: int, gross: float, rebalance: int, min_trade_usd: float, fee_bps: float, min_usd: float):
50 tickers = sorted(frame["ticker"].unique())
51 max_weight = gross / (2 * per_side)
53 def deadband(*, base_weight, held_weight, **_unused):
54 # a resize or entry smaller than the minimum trade is not worth a $2 minimum commission
55 if held_weight != 0.0 and abs(base_weight - held_weight) * NAV < min_trade_usd:
56 return held_weight
57 return base_weight
59 kwargs = dict(
60 base, prediction_column="live_rank_score", top_n=per_side, bottom_n=per_side, rebalance_every_bars=rebalance,
61 gross_exposure=gross, max_weight_per_name=max_weight, max_position_weight=max_weight, min_universe_size=8,
62 # the very function main.py's _update_forex_sleeve() calls, so the two cannot disagree on the weights
63 raw_weights_fn=lambda allocations, date: build_forex_sleeve_weights(allocations, gross),
64 normalize_to_percentile=True, live_weighting=False, sector_by_ticker={}, sector_neutral=False, dollar_neutral=True,
65 entry_lag_bars=1, cost_bps_per_side=1.0, commission_bps=fee_bps,
66 commission_bps_by_ticker=dict.fromkeys(tickers, fee_bps),
67 min_commission_usd_by_ticker=dict.fromkeys(tickers, min_usd),
68 assumed_portfolio_value_usd=NAV, member_weight_fn=deadband,
69 )
70 return simulate_rank_book(frame, **kwargs)
73def main() -> int:
74 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
75 parser.add_argument("--no-cache", action="store_true")
76 args = parser.parse_args()
78 results: dict = {}
79 for split in ("validation", "backtest"):
80 harness = AsLiveHarness(split, use_cache=not args.no_cache)
81 forex = {t for t, kind in harness.asset_class_by_ticker.items() if kind == "forex"}
82 frame = harness.lagged_frame[harness.lagged_frame["ticker"].isin(forex)].reset_index(drop=True)
83 results[split] = {"forex_rank_ic": forex_rank_ic(frame), "pairs": len(forex), "sleeves": {}}
84 print(f"[{split}] forex IC: {results[split]['forex_rank_ic']}")
85 for per_side in (2, 3):
86 for gross in (0.2, 0.3, 0.4):
87 for min_trade_usd in (1000.0, 2500.0):
88 name = f"k={per_side} gross={gross} deadband=${min_trade_usd:.0f}"
89 run = sleeve_run(
90 frame, harness.base, per_side=per_side, gross=gross, rebalance=20,
91 min_trade_usd=min_trade_usd, fee_bps=0.2, min_usd=2.0,
92 )
93 results[split]["sleeves"][name] = {
94 "net_sharpe": run.net_sharpe, "net_return": run.net_total_return, "max_dd": run.net_max_drawdown,
95 "cost_drag_bps": run.cost_drag_annual_bps, "turnover": run.annualized_turnover,
96 "gross_return": run.gross_total_return,
97 }
98 print(
99 f"[{split}] {name:36s} net sharpe {run.net_sharpe:+.3f} ret {100 * run.net_total_return:+.2f}% "
100 f"gross ret {100 * run.gross_total_return:+.2f}% cost {run.cost_drag_annual_bps:.0f}bps/yr"
101 )
102 qualifying = [
103 name
104 for name in results["validation"]["sleeves"]
105 if results["validation"]["sleeves"][name]["net_sharpe"] > 0.0
106 and results["backtest"]["sleeves"][name]["net_sharpe"] > 0.0
107 and results["validation"]["forex_rank_ic"]["daily_mean_ic"] > 0.0
108 ]
109 results["r_fx_offline_candidates"] = sorted(
110 qualifying, key=lambda name: -results["validation"]["sleeves"][name]["net_sharpe"]
111 )
112 print("R-FX offline candidates (best validation Sharpe first):", results["r_fx_offline_candidates"] or "none")
113 out = ROOT_DIR / "ml" / "evaluation" / "forex_sleeve_research.json"
114 out.write_text(json.dumps(results, indent=2, default=float), encoding="utf-8")
115 print(f"written {out}")
116 return 0
119if __name__ == "__main__":
120 raise SystemExit(main())