Coverage for scripts/crypto_fee_research.py: 100%
114 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"""R-CRYPTO (V6.0.0, todo lead 3): what to do about the crypto exchange fee? Pre-registered rule.
3BT2 paid $1,131 of Coinbase fees on $775 of gross crypto P&L: limit fills (entries) pay 60 bps, market fills (every exit,
4every timeout fallback) 80 bps. Two levers are built: limit EXITS (`phase_v2.limit_orders.exit_asset_classes`) and fewer /
5smaller graduate pairs. On the Lean-calibrated simulator (`scripts/lean_calibration.py`), per split:
7 C0 current: limit entries, market exits (fee priced route-aware: entry maker, exit taker)
8 C1 + limit exits at the configured offset / timeout C3 graduates off (BTCUSD / LTCUSD only)
9 C2 + the best offset / timeout of the fill sweep C4 graduates at 0.5% per name / 2.5% class
10 C5 C2 + the better of C3 / C4 (by validation crypto net)
12The fill rates come from `evaluation.limit_fill_simulator` on the crypto rows (entry side measured in BT2: 109 of 112 limit
13orders filled). A resting order is not priced for price improvement (conservative). Crypto component P&L = the crypto names'
14weights x next-day returns minus per-side fees on their weight changes, from the simulator's weight log.
16R-CRYPTO: pick the variant with the best VALIDATION crypto-component net that (1) leaves the total-book backtest Sharpe not
17worse than C0 by more than 0.05, (2) has a simulated limit fill rate >= 85% on every limit side it routes, and (3) keeps
18BTCUSD / LTCUSD tradable; if no variant beats C0's validation crypto net, C0 stays. The Lean check is BT1's realised fee per
19fill by route (`aq evaluate --attribute-lean`).
21 python scripts/crypto_fee_research.py --dataset ml/datasets/full_dataset.csv -> ml/evaluation/v600/crypto_research.json
22"""
24from __future__ import annotations
26import argparse
27import json
28import sys
29from pathlib import Path
31import numpy as np
33ROOT_DIR = Path(__file__).resolve().parents[1]
34sys.path.insert(0, str(ROOT_DIR))
35sys.path.insert(0, str(Path(__file__).resolve().parent))
37MAKER_BPS, TAKER_BPS = 60.0, 80.0
38ENTRY_FILL_RATE_BT2 = 109 / 112 # limit crypto orders that filled in BT2 (3 timed out)
39MIN_FILL_RATE = 0.85
40MAX_TOTAL_BOOK_LOSS = 0.05
41OFFSETS = (0.0, 0.5, 1.0)
42TIMEOUTS = (3, 5)
43CORE = ("BTCUSD", "LTCUSD")
46def component_net(result, frame, tickers: set[str], fee_bps: float) -> dict:
47 """Net return (fraction of NAV) of `tickers`' positions inside a simulated book: gross P&L from the previous date's
48 weights (one-bar entry lag) x the date's return, fees on every weight change at `fee_bps` per side."""
49 dates = list(result.per_date)
50 returns = frame.set_index(["date", "ticker"])["target_return_1d"].to_dict()
51 gross = fees = 0.0
52 previous: dict[str, float] = {}
53 for index, date in enumerate(dates):
54 current = {ticker: weight for ticker, weight in result.weights_log[index].items() if ticker in tickers}
55 if index > 0:
56 gross += sum(weight * float(returns.get((date, ticker), 0.0) or 0.0) for ticker, weight in previous.items())
57 fees += sum(abs(current.get(ticker, 0.0) - previous.get(ticker, 0.0)) for ticker in set(current) | set(previous)) * fee_bps / 1e4
58 previous = current
59 return {"gross": gross, "fees": fees, "net": gross - fees}
62def fill_rates(frame, offset: float, timeout: int) -> dict:
63 from evaluation.limit_fill_simulator import simulate_limit_fills
65 crypto = frame[frame["ticker"].isin(frame.attrs["crypto_tickers"])]
66 sim = simulate_limit_fills(crypto, unfilled_timeout_bars=timeout, offset_multiplier=offset)
67 return {"overall": sim["overall"]["fill_rate"], "buy": sim["by_side"]["buy"]["fill_rate"], "sell": sim["by_side"]["sell"]["fill_rate"],
68 "mean_bars_to_fill": sim["overall"]["mean_bars_to_fill"]}
71def fee_per_side(entry_limit: bool, exit_limit: bool, entry_rate: float, exit_rate: float) -> float:
72 from execution.cost_model import route_aware_per_side_fee_bps
74 return route_aware_per_side_fee_bps({"maker_bps": MAKER_BPS, "taker_bps": TAKER_BPS, "entry_limit": entry_limit,
75 "exit_limit": exit_limit, "fill_rate": entry_rate, "exit_fill_rate": exit_rate})
78def decide(results: dict, fill: dict) -> dict:
79 """R-CRYPTO on {variant: {split: {"crypto_net", "total_sharpe"}}} and {variant: min fill rate of the sides it routes}."""
80 base = results["C0"]
81 eligible = []
82 for name, row in results.items():
83 if name == "C0":
84 continue
85 checks = {
86 "total_book_backtest_not_worse_than_0.05": row["backtest"]["total_sharpe"] - base["backtest"]["total_sharpe"] >= -MAX_TOTAL_BOOK_LOSS,
87 "fill_rate_ge_85": fill.get(name, 1.0) >= MIN_FILL_RATE,
88 "core_tradable": True,
89 "beats_C0_validation_crypto_net": row["validation"]["crypto_net"] > base["validation"]["crypto_net"],
90 }
91 if all(checks.values()):
92 eligible.append((row["validation"]["crypto_net"], name))
93 if not eligible:
94 return {"winner": "C0", "reason": "no variant beats C0's validation crypto net inside the constraints"}
95 return {"winner": max(eligible)[1], "eligible": sorted(name for _, name in eligible)}
98def main() -> int:
99 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
100 parser.add_argument("--dataset", default=str(ROOT_DIR / "ml" / "datasets" / "full_dataset.csv"))
101 parser.add_argument("--out", default=str(ROOT_DIR / "ml" / "evaluation" / "v600" / "crypto_research.json"))
102 args = parser.parse_args()
104 from as_live_levers import AsLiveHarness, summarize
105 from lean_calibration import calibrated_overrides, topology_inputs_fn_for, use_topology
107 from execution.cost_model import commission_bps_by_ticker
108 from portfolio.book_construction import resolve_class_weight_caps
109 from risk.asset_class_router import load_venue_listing_dates
111 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
112 security_types = {str(a["ticker"]): str(a["security_type"]) for a in config["phase1"]["universe"]["assets"]}
113 listing = load_venue_listing_dates(ROOT_DIR / "data" / "reference" / "crypto_listing_dates.json")
114 harnesses = {}
115 for split in ("validation", "backtest"):
116 harness = AsLiveHarness(split, dataset_path=Path(args.dataset))
117 harness.venue_listing_dates = listing or None
118 harnesses[split] = (harness, topology_inputs_fn_for(harness, harness.config))
119 crypto_all = sorted(t for t, kind in harnesses["backtest"][0].asset_class_by_ticker.items() if kind == "crypto")
120 for harness, _ in harnesses.values():
121 harness.frame.attrs["crypto_tickers"] = crypto_all
123 sweep = {}
124 for timeout in TIMEOUTS:
125 for offset in OFFSETS:
126 sweep[f"offset{offset}_timeout{timeout}"] = {
127 split: fill_rates(harnesses[split][0].frame, offset, timeout) for split in harnesses
128 }
129 row = sweep[f"offset{offset}_timeout{timeout}"]
130 print(f"fill sweep offset {offset} timeout {timeout}: " + " | ".join(f"{s} buy {v['buy']:.3f} sell {v['sell']:.3f}" for s, v in row.items()), flush=True)
132 def mean_side(name: str, side: str) -> float:
133 return float(np.mean([sweep[name][split][side] for split in harnesses]))
135 current_key = f"offset{float(config['phase_v2']['limit_orders']['offset_multiplier'])}_timeout{int(config['phase_v2']['limit_orders']['unfilled_timeout_bars'])}"
136 best_key = max((k for k in sweep if mean_side(k, "sell") >= MIN_FILL_RATE), key=lambda k: mean_side(k, "sell"), default=current_key)
137 graduates = sorted(set(crypto_all) - set(CORE))
139 def variant(name: str, *, exit_limit: bool, sweep_key: str, graduates_on: bool = True, caps=(0.01, 0.05)) -> dict:
140 exit_rate = mean_side(sweep_key, "sell")
141 fee = fee_per_side(True, exit_limit, ENTRY_FILL_RATE_BT2, exit_rate)
142 fee_map = dict.fromkeys(crypto_all, fee)
143 out = {}
144 for split, (harness, topology_fn) in harnesses.items():
145 use_topology(harness, topology_fn)
146 metadata = {t: dict(v) for t, v in harness.metadata.items()}
147 if not graduates_on:
148 for ticker in graduates:
149 metadata[ticker]["trading_eligible"] = False
150 cap_config = resolve_class_weight_caps({"crypto": {"per_name_cap": caps[0], "class_gross_cap": caps[1], "exempt": list(CORE)}})
151 base_fees = commission_bps_by_ticker(harness.config["phase_v2"].get("costs", {}), security_types)
152 fees = {**base_fees, **fee_map}
153 result = harness.as_live(
154 log_weights=True, candidate_metadata_by_ticker=metadata, class_weight_caps=cap_config,
155 commission_bps_by_ticker=fees, **calibrated_overrides(harness),
156 )
157 summary = summarize(result)
158 crypto = component_net(result, harness.frame, set(crypto_all), fee)
159 out[split] = {"total_sharpe": summary["net_sharpe"], "total_return": summary["net_total_return"], "crypto_net": crypto["net"],
160 "crypto_gross": crypto["gross"], "crypto_fees": crypto["fees"]}
161 out["fee_per_side_bps"] = fee
162 print(f"{name}: fee/side {fee:.1f} bps | " + " | ".join(
163 f"{s} crypto net {out[s]['crypto_net']:+.4f} (gross {out[s]['crypto_gross']:+.4f}, fees {out[s]['crypto_fees']:.4f}) total sharpe {out[s]['total_sharpe']:+.3f}"
164 for s in harnesses), flush=True)
165 return out
167 results = {
168 "C0": variant("C0", exit_limit=False, sweep_key=current_key),
169 "C1": variant("C1", exit_limit=True, sweep_key=current_key),
170 "C2": variant("C2", exit_limit=True, sweep_key=best_key),
171 "C3": variant("C3", exit_limit=False, sweep_key=current_key, graduates_on=False),
172 "C4": variant("C4", exit_limit=False, sweep_key=current_key, caps=(0.005, 0.025)),
173 }
174 better = "C3" if results["C3"]["validation"]["crypto_net"] >= results["C4"]["validation"]["crypto_net"] else "C4"
175 results["C5"] = variant("C5", exit_limit=True, sweep_key=best_key, graduates_on=(better != "C3"),
176 caps=(0.005, 0.025) if better == "C4" else (0.01, 0.05))
177 fill = {"C1": mean_side(current_key, "sell"), "C2": mean_side(best_key, "sell"), "C5": mean_side(best_key, "sell")}
178 decision = decide(results, fill)
179 decision.update(best_sweep=best_key, current_sweep=current_key, combined_with=better)
180 print("R-CRYPTO:", json.dumps(decision))
181 Path(args.out).parent.mkdir(parents=True, exist_ok=True)
182 Path(args.out).write_text(json.dumps({"sweep": sweep, "results": results, "fill_rates_routed": fill, "decision": decision},
183 indent=1, default=float), encoding="utf-8")
184 print(f"written {args.out}")
185 return 0
188if __name__ == "__main__":
189 raise SystemExit(main())