Coverage for scripts/coinbase_listing_dates.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"""Derive each crypto pair's Coinbase listing date and trading suspensions from the exchange's own daily candles (V5.8.0).
3A backtest that trades a pair before the exchange listed it (or while trading was suspended - Coinbase halted XRP from
4January 2021 to July 2023) books returns no live account could have earned. Search engines carry no reliable listing
5history, so this reads the public Coinbase Exchange candles endpoint (no key needed): the first daily candle is the
6first traded day, and a run of missing days longer than `--min-gap-days` is a suspension. The result feeds
7`risk/asset_class_router.py::asset_listed_on_venue` via `data/reference/crypto_listing_dates.json`.
9 python scripts/coinbase_listing_dates.py [--start 2014-01-01] [--end 2026-10-01] [--apply]
11Dry run by default (prints the table, writes nothing).
12"""
14from __future__ import annotations
16import argparse
17import itertools
18import json
19import sys
20import time as _time
21import urllib.request
22from datetime import date, datetime, timedelta, timezone
23from pathlib import Path
25ROOT_DIR = Path(__file__).resolve().parents[1]
26API = "https://api.exchange.coinbase.com/products/{product}/candles?granularity=86400&start={start}&end={end}"
27MAX_CANDLES = 300
30def product_id(ticker: str) -> str:
31 return f"{ticker[:-3]}-{ticker[-3:]}"
34def fetch_candle_days(product: str, start: date, end: date, *, pause: float = 0.35) -> list[date]:
35 """Every UTC day with a daily candle in [start, end)."""
36 days: set[date] = set()
37 cursor = start
38 while cursor < end:
39 chunk_end = min(cursor + timedelta(days=MAX_CANDLES - 1), end)
40 url = API.format(product=product, start=cursor.isoformat(), end=chunk_end.isoformat())
41 request = urllib.request.Request(url, headers={"User-Agent": "aether-quant-listing-audit"})
42 for attempt in range(4):
43 try:
44 with urllib.request.urlopen(request, timeout=30) as response:
45 payload = json.loads(response.read().decode("utf-8"))
46 break
47 except Exception:
48 if attempt == 3:
49 raise
50 _time.sleep(2.0 * (attempt + 1))
51 if isinstance(payload, list):
52 for candle in payload:
53 days.add(datetime.fromtimestamp(int(candle[0]), tz=timezone.utc).date())
54 cursor = chunk_end + timedelta(days=1)
55 _time.sleep(pause)
56 return sorted(days)
59def listing_entry(days: list[date], *, min_gap_days: int, end: date | None = None) -> dict:
60 """{"listed", "last", "suspended": [[gap_start, gap_end_exclusive], ...], "delisted"} from the traded days. A pair
61 whose last candle is more than `min_gap_days` before `end` is delisted from the day after it."""
62 if not days:
63 return {"listed": None, "last": None, "suspended": [], "delisted": None}
64 gaps = []
65 for previous, current in itertools.pairwise(days):
66 if (current - previous).days > min_gap_days:
67 gaps.append([(previous + timedelta(days=1)).isoformat(), current.isoformat()])
68 delisted = None
69 if end is not None and (end - days[-1]).days > min_gap_days:
70 delisted = (days[-1] + timedelta(days=1)).isoformat()
71 return {"listed": days[0].isoformat(), "last": days[-1].isoformat(), "suspended": gaps, "delisted": delisted}
74def main() -> int:
75 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
76 parser.add_argument("--start", default="2014-01-01")
77 parser.add_argument("--end", default="2026-10-01")
78 parser.add_argument("--min-gap-days", type=int, default=7)
79 parser.add_argument("--output", default=str(ROOT_DIR / "data" / "reference" / "crypto_listing_dates.json"))
80 parser.add_argument("--apply", action="store_true")
81 args = parser.parse_args()
82 config = json.loads((ROOT_DIR / "config.json").read_text(encoding="utf-8"))
83 tickers = [a["ticker"] for a in config["phase1"]["universe"]["assets"] if a.get("security_type") == "crypto"]
84 start, end = date.fromisoformat(args.start), date.fromisoformat(args.end)
85 assets = {}
86 for ticker in tickers:
87 days = fetch_candle_days(product_id(ticker), start, end)
88 assets[ticker] = listing_entry(days, min_gap_days=args.min_gap_days, end=end)
89 print(f"{ticker:8s} listed {assets[ticker]['listed']} last {assets[ticker]['last']} suspended {assets[ticker]['suspended']} delisted {assets[ticker]['delisted']}")
90 if args.apply:
91 payload = {
92 "source": "Coinbase Exchange public daily candles (api.exchange.coinbase.com/products/<pair>/candles), "
93 f"first candle = listing, gaps > {args.min_gap_days} days = suspension; built by scripts/coinbase_listing_dates.py",
94 "built_on": date.today().isoformat(),
95 "assets": assets,
96 }
97 Path(args.output).write_text(json.dumps(payload, indent=2), encoding="utf-8")
98 print(f"written {args.output}")
99 return 0
102if __name__ == "__main__":
103 sys.exit(main())