Coverage for scripts/v660_venue_study.py: 100%
70 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"""Evidence for the owner's live crypto venue decision (Problems.md #192). IB can't fill spot crypto, and the installed sleeve is crypto.
3Measures how closely spot ETFs a stock broker can fill track the coins, and writes one Lean run of the sleeve's BTC and ETH legs on those
4ETFs. It decides nothing. Fees and access in `ROUTES` come from each provider's public terms as of writing and are to be checked before use.
6 python scripts/v660_venue_study.py make # fetches the ETFs into data_wide, tracking, the run config
7"""
9from __future__ import annotations
11import argparse
12import json
13import sys
14from pathlib import Path
16import numpy as np
17import pandas as pd
19ROOT = Path(__file__).resolve().parents[1]
20sys.path.insert(0, str(ROOT))
21sys.path.insert(0, str(ROOT / "scripts"))
23from build_wide_root import fetch_adjusted_and_raw # noqa: E402
24from v650_instrument import target_path_config # noqa: E402
25from v660_lean import WEIGHTS, write_run # noqa: E402
27from data_pipeline.data_audit import read_lean_daily_zip # noqa: E402
28from data_pipeline.yfinance_backfill import sanitize_ohlc, scale_for_lean, write_lean_zip # noqa: E402
29from portfolio.target_weights import load_weight_file, write_weight_file # noqa: E402
31OUT = ROOT / "ml" / "evaluation" / "v660"
32PROXIES = {"BTCUSD": "IBIT", "ETHUSD": "ETHA"}
33FIRST_FULL_DATE = "2024-08-01" # ETHA listed in July 2024
34ROUTES = {
35 "coinbase_direct": {
36 "instruments": "all 12 coins of the sleeve", "account": "a Coinbase account: not one this project has", "fee_model": "the blocking cost of every run, up to 80 bps taker + 10 bps slippage",
37 "note": "Lean's Coinbase brokerage supports crypto on cash accounts, so the book is long-only there, which the sleeve already is.",
38 },
39 "ib_spot_etfs": {
40 "instruments": "IBIT and ETHA: BTC and ETH only, so the sleeve's other 10 coins have no route", "account": "the existing IB route", "fee_model": "equity commission and ETF spread, plus each fund's 0.25% a year expense ratio",
41 "note": "EU retail clients generally can't buy US-domiciled ETFs (PRIIPs): check the owner's account class before relying on this route. Equivalent UCITS or ETP listings were not studied.",
42 },
43 "ib_cme_micro_futures": {
44 "instruments": "CME micro bitcoin and micro ether futures", "account": "the existing IB route, with futures permissions", "fee_model": "exchange and IB fees per contract, plus the basis and roll",
45 "note": "A contract is 0.1 BTC or 0.1 ETH: at this sleeve's sizes on $100k, the position rounds to at most a contract or two, so it can't track. Not run.",
46 },
47}
50def fetch_proxies(root: Path) -> dict:
51 report = {}
52 for ticker in PROXIES.values():
53 path = root / "equity" / "usa" / "daily" / f"{ticker.lower()}.zip"
54 rows, _ = fetch_adjusted_and_raw(ticker, "2024-01-01", "2026-11-03")
55 rows, _ = sanitize_ohlc(rows)
56 if not rows:
57 report[ticker] = {"status": "no bars"}
58 continue
59 path.parent.mkdir(parents=True, exist_ok=True)
60 write_lean_zip(path, ticker, scale_for_lean(rows, "equity"), merge_with_existing=False)
61 report[ticker] = {"status": "ok", "first": rows[0]["date"].isoformat(), "last": rows[-1]["date"].isoformat(), "rows": len(rows)}
62 return report
65def tracking(root: Path) -> dict:
66 """ETF session return against its coin over the same span. A coin's bar closes at midnight UTC and the fund's at 4pm New York, so a daily
67 correlation understates the link: the weekly one is the fairer figure."""
68 report = {}
69 for coin, ticker in PROXIES.items():
70 etf = read_lean_daily_zip(root / "equity" / "usa" / "daily" / f"{ticker.lower()}.zip", "equity")
71 spot = read_lean_daily_zip(ROOT / "data" / "crypto" / "coinbase" / "daily" / f"{coin.lower()}_trade.zip", "crypto")
72 etf_close = etf.set_index(etf["date"].dt.strftime("%Y-%m-%d"))["close"]
73 spot_close = spot.set_index(spot["date"].dt.strftime("%Y-%m-%d"))["close"]
74 both = pd.concat({"etf": etf_close, "coin": spot_close.shift(1).reindex(etf_close.index)}, axis=1).dropna()
75 daily = both.pct_change().dropna()
76 weekly = both.iloc[::5].pct_change().dropna()
77 report[ticker] = {
78 "coin": coin, "sessions": len(daily), "daily_correlation": float(daily.corr().iloc[0, 1]), "weekly_correlation": float(weekly.corr().iloc[0, 1]),
79 "annual_return_gap": float(((1.0 + daily["etf"]).prod() ** (252.0 / len(daily)) - 1.0) - ((1.0 + daily["coin"]).prod() ** (252.0 / len(daily)) - 1.0)),
80 "weekly_tracking_error_annual": float((weekly["etf"] - weekly["coin"]).std(ddof=1) * np.sqrt(52.0)),
81 }
82 return report
85def proxy_rows(weights: dict[str, dict[str, float]]) -> dict[str, dict[str, float]]:
86 """The sleeve's rows with BTC and ETH on their ETFs, and nothing for coins with no route. A flat row stays flat."""
87 return {date: {PROXIES[ticker]: weight for ticker, weight in row.items() if ticker in PROXIES} for date, row in weights.items() if date >= FIRST_FULL_DATE}
90def make() -> dict:
91 root = ROOT / "data_wide"
92 fetched = fetch_proxies(root)
93 report = {"routes": ROUTES, "fetched": fetched, "tracking": tracking(root)}
94 base = json.loads((ROOT / "config.json").read_text(encoding="utf-8"))
95 target = base["phase_v2"]["target_weights"]
96 rows = proxy_rows(load_weight_file(ROOT / target["weights_path"], target["weights_sha256"]))
97 WEIGHTS.mkdir(parents=True, exist_ok=True)
98 sha = write_weight_file(rows, WEIGHTS / "v660_venue_etf.csv")
99 config = dict(base)
100 config["phase1"] = {**base["phase1"], "universe": {**base["phase1"]["universe"], "assets": [
101 {"ticker": ticker, "security_type": "equity", "market": "usa", "data_path": f"data/equity/usa/daily/{ticker.lower()}.zip"} for ticker in ("SPY", "AGG", *PROXIES.values())
102 ]}}
103 run = target_path_config(config, weights_path="ml/evaluation/v660/weights/v660_venue_etf.csv", weights_sha256=sha, window=(FIRST_FULL_DATE, "2026-11-02"))
104 report["run"] = {**write_run("v660_venue_etf", run, data_root="data_wide"), "weights_sha": sha, "role": "plumbing"}
105 (OUT / "venue_study.json").write_text(json.dumps(report, indent=1), encoding="utf-8", newline="\n")
106 return report
109def main() -> int:
110 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
111 parser.add_argument("stage", choices=["make"])
112 parser.parse_args()
113 print(json.dumps(make(), indent=1)[:3000])
114 return 0
117if __name__ == "__main__":
118 raise SystemExit(main())