Coverage for data_pipeline/binance_archive.py: 100%
120 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"""Binance's public archive, data.binance.vision (V6.6.0, free, no account): every USDT spot pair, delisted ones included.
3The project's 12 coins are survivors, so nothing yet says what a crypto rule does on coins that later died. The archive keeps
4LUNA and FTT, so it can. Spot daily klines from 2017-08, perpetual funding rates from 2019-09.
6This is research data on a venue the book doesn't trade: blocking costs stay Coinbase's.
7"""
9from __future__ import annotations
11import csv
12import io
13import math
14import re
15import xml.etree.ElementTree as ElementTree
16import zipfile
17from collections.abc import Callable, Mapping
18from datetime import datetime, timezone
19from pathlib import Path
21import pandas as pd
23LISTING_URL = "https://s3-ap-northeast-1.amazonaws.com/data.binance.vision"
24ARCHIVE_URL = "https://data.binance.vision"
25KLINE_PREFIX = "data/spot/monthly/klines/"
26FUNDING_PREFIX = "data/futures/um/monthly/fundingRate/"
27STABLE_BASES = frozenset({
28 "USDC", "BUSD", "TUSD", "USDP", "PAX", "DAI", "FDUSD", "USDS", "USDSB", "SUSD", "GUSD", "EUR", "GBP", "AUD", "BRL", "TRY", "USDD",
29 "EURI", "AEUR", "UST", "USTC", "XUSD", "RLUSD", "PYUSD", "USD1", "BFUSD", "UUSD", "USDE", "IDRT", "BIDR", "BVND",
30})
31LEVERAGED_TOKEN = re.compile(r"(UP|DOWN|BULL|BEAR)$")
32S3_NAMESPACE = "{http://s3.amazonaws.com/doc/2006-03-01/}"
35def list_symbols(get_text: Callable[[str], str], prefix: str = KLINE_PREFIX) -> list[str]:
36 """Every folder under `prefix`, following the listing's pages: it returns 1,000 entries at a time, and stopping at the first
37 page would silently lose most of the alphabet."""
38 symbols: list[str] = []
39 marker = ""
40 while True:
41 url = f"{LISTING_URL}?delimiter=/&prefix={prefix}" + (f"&marker={marker}" if marker else "")
42 root = ElementTree.fromstring(get_text(url))
43 names = [
44 element.findtext(f"{S3_NAMESPACE}Prefix") or ""
45 for element in root.findall(f"{S3_NAMESPACE}CommonPrefixes")
46 ]
47 symbols.extend(name[len(prefix):].rstrip("/") for name in names if name != prefix)
48 truncated = (root.findtext(f"{S3_NAMESPACE}IsTruncated") or "false").lower() == "true"
49 if not truncated:
50 return sorted(set(symbols))
51 marker = root.findtext(f"{S3_NAMESPACE}NextMarker") or (names[-1] if names else "")
52 if not marker:
53 return sorted(set(symbols))
56def base_asset(symbol: str) -> str | None:
57 """LUNAUSDT -> LUNA. None for a pair this phase doesn't use: not quoted in USDT, a stablecoin, a leveraged token."""
58 if not symbol.endswith("USDT"):
59 return None
60 base = symbol[:-4]
61 if not base or base in STABLE_BASES or LEVERAGED_TOKEN.search(base):
62 return None
63 return base
66def _timestamp_date(value: str) -> str:
67 """Binance moved spot files from milliseconds to microseconds in 2025. Telling them apart by size keeps both right."""
68 number = int(value)
69 while number > 10**13:
70 number //= 1000
71 return datetime.fromtimestamp(number / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d")
74def parse_kline_zip(payload: bytes) -> list[dict]:
75 """{date, open, high, low, close, volume, quote_volume} from one monthly file. Some files have a header row and some don't."""
76 rows: list[dict] = []
77 with zipfile.ZipFile(io.BytesIO(payload)) as archive:
78 for name in archive.namelist():
79 with archive.open(name) as handle:
80 for record in csv.reader(io.TextIOWrapper(handle, encoding="utf-8")):
81 if not record or not record[0].strip().isdigit():
82 continue
83 close, volume, quote_volume = float(record[4]), float(record[5]), float(record[7])
84 if close <= 0.0:
85 continue
86 rows.append({
87 "date": _timestamp_date(record[0]), "open": float(record[1]), "high": float(record[2]), "low": float(record[3]),
88 "close": close, "volume": volume, "quote_volume": quote_volume,
89 })
90 return rows
93def parse_funding_zip(payload: bytes) -> list[tuple[str, float]]:
94 """(date, rate) per settlement from one monthly file: calc_time,funding_interval_hours,last_funding_rate."""
95 out: list[tuple[str, float]] = []
96 with zipfile.ZipFile(io.BytesIO(payload)) as archive:
97 for name in archive.namelist():
98 with archive.open(name) as handle:
99 for record in csv.reader(io.TextIOWrapper(handle, encoding="utf-8")):
100 if not record or not record[0].strip().isdigit():
101 continue
102 out.append((_timestamp_date(record[0]), float(record[-1])))
103 return out
106def daily_funding(settlements: list[tuple[str, float]]) -> dict[str, float]:
107 """A day's funding is the sum of its settlements: what a long position pays that day."""
108 totals: dict[str, float] = {}
109 for date, rate in settlements:
110 totals[date] = totals.get(date, 0.0) + rate
111 return totals
114def months_between(start: str, end: str) -> list[str]:
115 """YYYY-MM from `start` to `end`, inclusive."""
116 months = pd.period_range(start[:7], end[:7], freq="M")
117 return [str(month) for month in months]
120def kline_url(symbol: str, month: str) -> str:
121 """The data.binance.vision URL of one symbol's monthly daily-kline archive."""
122 return f"{ARCHIVE_URL}/{KLINE_PREFIX}{symbol}/1d/{symbol}-1d-{month}.zip"
125def funding_url(symbol: str, month: str) -> str:
126 """The data.binance.vision URL of one symbol's monthly funding-rate archive."""
127 return f"{ARCHIVE_URL}/{FUNDING_PREFIX}{symbol}/{symbol}-fundingRate-{month}.zip"
130def listed_months(get_text: Callable[[str], str], prefix: str) -> list[str] | None:
131 """The YYYY-MM of every file under `prefix`, or None if the listing holds none: then the caller tries every month. A pair has files only for
132 the months it traded, so asking first saves most of the requests."""
133 root = ElementTree.fromstring(get_text(f"{LISTING_URL}?prefix={prefix}&max-keys=1000"))
134 keys = [element.findtext(f"{S3_NAMESPACE}Key") or "" for element in root.findall(f"{S3_NAMESPACE}Contents")]
135 months = sorted({match.group(1) for key in keys if key.endswith(".zip") and (match := re.search(r"-(\d{4}-\d{2})\.zip$", key))})
136 return months or None
139def fetch_series(
140 url_for: Callable[[str, str], str], parse: Callable[[bytes], list], symbol: str, start: str, end: str,
141 get_bytes: Callable[[str], bytes | None], *, months: list[str] | None = None, workers: int = 8,
142) -> list:
143 """Every month's rows, in month order, fetched by a few threads: the archive is a static CDN, and one at a time takes hours. A missing month is
144 normal (a pair lists late, or has died), so `get_bytes` returns None for a 404."""
145 from concurrent.futures import ThreadPoolExecutor
147 wanted = [month for month in (months if months is not None else months_between(start, end)) if start[:7] <= month <= end[:7]]
148 with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
149 payloads = list(pool.map(lambda month: get_bytes(url_for(symbol, month)), wanted))
150 rows: list = []
151 for payload in payloads:
152 if payload:
153 rows.extend(parse(payload))
154 return rows
157def price_breaks(closes: Mapping[str, float], *, ratio: float = 10.0) -> list[dict]:
158 """Consecutive closes `ratio` times apart or more, across any gap in the dates: a redenomination or token swap spliced into one pair
159 (COCOS went from 0.0003 to 0.7 over a three-week gap in 2021), which reads as a return nobody could earn. A listing's first days can
160 do this honestly too, so a break is a thing to look at, not proof."""
161 found, previous_date, previous = [], None, None
162 for date in sorted(closes):
163 close = float(closes[date])
164 if not math.isfinite(close) or close <= 0.0:
165 continue
166 if previous is not None:
167 move = close / previous
168 if move >= ratio or move <= 1.0 / ratio:
169 found.append({"from": previous_date, "to": date, "ratio": move})
170 previous_date, previous = date, close
171 return found
174def truncate_at_swap(rows: list[dict], *, ratio: float = 10.0, min_gap_days: int = 2) -> tuple[list[dict], dict | None]:
175 """A pair's bars up to its first break across a gap of `min_gap_days` or more: what follows is another instrument under the same name. A collapse with
176 no gap (LUNA on 2022-05-11) is a real loss and stays."""
177 closes = {row["date"]: row["close"] for row in rows}
178 for found in price_breaks(closes, ratio=ratio):
179 gap = (datetime.fromisoformat(found["to"]) - datetime.fromisoformat(found["from"])).days
180 if gap >= min_gap_days:
181 return [row for row in rows if row["date"] <= found["from"]], found
182 return rows, None
185def liquid_universe(quote_volume: pd.DataFrame, *, top_n: int = 30, window: int = 60) -> pd.DataFrame:
186 """Date x coin, True where the coin is among the `top_n` by trailing dollar volume. Trailing and shifted a row: a day's own
187 volume isn't known until it ends. Only a coin with a full window qualifies."""
188 trailing = quote_volume.rolling(window, min_periods=window).mean().shift(1)
189 ranks = trailing.rank(axis=1, ascending=False, method="first")
190 return ranks.le(top_n) & trailing.notna()
193def write_frame(path: Path, frame: pd.DataFrame) -> None:
194 path.parent.mkdir(parents=True, exist_ok=True)
195 frame.astype("float64").to_parquet(path)