Coverage for scripts/build_crypto_wide_root.py: 100%

148 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""The wide crypto root of V6.6.0: every USDT spot pair Binance's archive holds, delisted ones included, as a Lean data root. 

2 

3Pairs are written under Lean's Coinbase market so a run uses the project's fee model (the blocking cost) and symbol properties are 

4added for coins Lean doesn't know. The root also holds SPY, AGG, BIL and BTCUSD: with no equity bars the target path has no sessions, 

5and nothing trades. A rerun resumes. The script records only row counts, spans and hashes. 

6 

7 python scripts/build_crypto_wide_root.py --out data_crypto_wide 

8""" 

9 

10from __future__ import annotations 

11 

12import argparse 

13import csv 

14import hashlib 

15import io 

16import json 

17import shutil 

18import sys 

19import time as _time 

20import zipfile 

21from collections.abc import Callable 

22from pathlib import Path 

23 

24import pandas as pd 

25 

26ROOT = Path(__file__).resolve().parents[1] 

27sys.path.insert(0, str(ROOT)) 

28 

29from data_pipeline import net_retry # noqa: E402 

30from data_pipeline.binance_archive import ( # noqa: E402 

31 FUNDING_PREFIX, 

32 KLINE_PREFIX, 

33 base_asset, 

34 daily_funding, 

35 fetch_series, 

36 funding_url, 

37 kline_url, 

38 list_symbols, 

39 listed_months, 

40 parse_funding_zip, 

41 parse_kline_zip, 

42 truncate_at_swap, 

43 write_frame, 

44) 

45from data_pipeline.yfinance_backfill import write_lean_crypto_quote_zip, write_lean_zip # noqa: E402 

46 

47MANIFEST = "crypto_wide_manifest.json" 

48PROJECT_COINS_FIRST = ("BTC", "ETH") 

49START, END = "2017-08-01", "2026-11-02" 

50COPIED_DIRS = ("market-hours", "symbol-properties", Path("alternative") / "interest-rate") 

51FROM_WIDE = ("spy", "agg", "bil") 

52 

53 

54def add_symbol_properties(database: Path, coins: list[str]) -> list[str]: 

55 """Rows for coins Lean's table lacks under Coinbase. Returns those added. Lot and tick follow Lean's Coinbase rows: an order is 

56 sized to these, and no real order ever uses them.""" 

57 lines = database.read_text(encoding="utf-8").splitlines() 

58 existing = {line.split(",")[1].upper() for line in lines if line.startswith("coinbase,")} 

59 added = [coin for coin in coins if f"{coin}USD" not in existing] 

60 rows = [f"coinbase,{coin}USD,crypto,{coin}-US Dollar,USD,1,0.00000001,0.00000001,{coin}-USD,0.00000001" for coin in added] 

61 database.write_text("\n".join(lines + rows) + "\n", encoding="utf-8", newline="\n") 

62 return added 

63 

64 

65def cut_swaps(out: Path) -> dict: 

66 """The same cut on a root built before `truncate_at_swap` existed. Bars only: volume and funding past a cut are never reached.""" 

67 manifest_path = out / "crypto_wide_manifest.json" 

68 manifest = json.loads(manifest_path.read_text(encoding="utf-8")) 

69 daily = out / "crypto" / "coinbase" / "daily" 

70 for coin, entry in manifest["coins"].items(): 

71 ticker = entry["ticker"] 

72 trade = daily / f"{ticker.lower()}_trade.zip" 

73 with zipfile.ZipFile(trade) as archive, archive.open(archive.namelist()[0]) as handle: 

74 lines = list(csv.reader(io.TextIOWrapper(handle, encoding="utf-8"))) 

75 rows = [{ 

76 "date": f"{line[0][:4]}-{line[0][4:6]}-{line[0][6:8]}", "open": float(line[1]), "high": float(line[2]), "low": float(line[3]), 

77 "close": float(line[4]), "volume": float(line[5]), 

78 } for line in lines] 

79 kept, swap = truncate_at_swap(rows) 

80 if not swap: 

81 continue 

82 bars = lean_rows(kept) 

83 write_lean_zip(trade, ticker, bars, merge_with_existing=False) 

84 write_lean_crypto_quote_zip(trade, trade.with_name(f"{ticker.lower()}_quote.zip"), ticker, merge_with_existing=False) 

85 entry.update({"rows": len(bars), "last": bars[-1]["date"].isoformat(), "sha256": hashlib.sha256(trade.read_bytes()).hexdigest()}) 

86 manifest.setdefault("cut_at_a_swap", {})[coin] = swap 

87 manifest_path.write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n") 

88 return manifest.get("cut_at_a_swap", {}) 

89 

90 

91def lean_rows(rows: list[dict]) -> list[dict]: 

92 """Bars as `write_lean_zip` takes them, one per date, the last file's row winning. Crypto isn't price-scaled.""" 

93 import datetime 

94 

95 by_date = {row["date"]: row for row in rows} 

96 return [{ 

97 "date": datetime.date.fromisoformat(date), "open": row["open"], "high": row["high"], "low": row["low"], "close": row["close"], 

98 "volume": row["volume"], 

99 } for date, row in sorted(by_date.items())] 

100 

101 

102def build_root( 

103 out: Path, *, get_text: Callable[[str], str], get_bytes: Callable[[str], bytes | None], source: Path = ROOT / "data", 

104 wide_root: Path = ROOT / "data_wide", start: str = START, end: str = END, pause_seconds: float = 0.2, 

105) -> dict: 

106 out = Path(out) 

107 for relative in COPIED_DIRS: 

108 if (source / relative).exists(): 

109 (out / relative).parent.mkdir(parents=True, exist_ok=True) 

110 shutil.copytree(source / relative, out / relative, dirs_exist_ok=True) 

111 (out / "equity" / "usa" / "daily").mkdir(parents=True, exist_ok=True) 

112 for name in FROM_WIDE: 

113 shutil.copy2(Path(wide_root) / "equity" / "usa" / "daily" / f"{name}.zip", out / "equity" / "usa" / "daily" / f"{name}.zip") 

114 (out / "equity" / "usa" / "map_files").mkdir(parents=True, exist_ok=True) 

115 (out / "equity" / "usa" / "factor_files").mkdir(parents=True, exist_ok=True) 

116 

117 manifest_path = out / MANIFEST 

118 manifest = json.loads(manifest_path.read_text(encoding="utf-8")) if manifest_path.exists() else {"start": start, "end": end, "coins": {}, "left_out": {}} 

119 symbols = [symbol for symbol in list_symbols(get_text) if base_asset(symbol)] 

120 manifest["pairs_listed"] = len(symbols) 

121 quote_volume: dict[str, dict[str, float]] = {} 

122 funding: dict[str, dict[str, float]] = {} 

123 volume_path, funding_path = out / "reference" / "quote_volume.parquet", out / "reference" / "funding.parquet" 

124 if volume_path.exists(): 

125 quote_volume = {column: series.dropna().to_dict() for column, series in pd.read_parquet(volume_path).items()} 

126 if funding_path.exists(): 

127 funding = {column: series.dropna().to_dict() for column, series in pd.read_parquet(funding_path).items()} 

128 

129 for count, symbol in enumerate(symbols, start=1): 

130 coin = base_asset(symbol) 

131 if coin in manifest["coins"] or coin in manifest["left_out"]: 

132 continue 

133 rows = fetch_series(kline_url, parse_kline_zip, symbol, start, end, get_bytes, months=listed_months(get_text, f"{KLINE_PREFIX}{symbol}/1d/")) 

134 if not rows: 

135 manifest["left_out"][coin] = "no bars" 

136 continue 

137 rows, swap = truncate_at_swap(rows) 

138 if swap: 

139 manifest.setdefault("cut_at_a_swap", {})[coin] = swap 

140 bars = lean_rows(rows) 

141 ticker = f"{coin}USD" 

142 trade = out / "crypto" / "coinbase" / "daily" / f"{ticker.lower()}_trade.zip" 

143 trade.parent.mkdir(parents=True, exist_ok=True) 

144 write_lean_zip(trade, ticker, bars, merge_with_existing=False) 

145 write_lean_crypto_quote_zip(trade, trade.with_name(f"{ticker.lower()}_quote.zip"), ticker, merge_with_existing=False) 

146 quote_volume[ticker] = {row["date"]: row["quote_volume"] for row in rows} 

147 settlements = fetch_series( 

148 funding_url, parse_funding_zip, symbol, "2019-09-01", end, get_bytes, months=listed_months(get_text, f"{FUNDING_PREFIX}{symbol}/") or [], 

149 ) 

150 if settlements: 

151 funding[ticker] = daily_funding(settlements) 

152 manifest["coins"][coin] = { 

153 "ticker": ticker, "rows": len(bars), "first": bars[0]["date"].isoformat(), "last": bars[-1]["date"].isoformat(), 

154 "sha256": hashlib.sha256(trade.read_bytes()).hexdigest(), "funding": bool(settlements), 

155 } 

156 if count % 5 == 0: 

157 _save(manifest_path, manifest, volume_path, quote_volume, funding_path, funding) 

158 print(f"{count} of {len(symbols)}: {len(manifest['coins'])} coins", flush=True) 

159 if pause_seconds: 

160 _time.sleep(pause_seconds) 

161 _save(manifest_path, manifest, volume_path, quote_volume, funding_path, funding) 

162 database = out / "symbol-properties" / "symbol-properties-database.csv" 

163 if database.exists(): 

164 manifest["symbol_properties_added"] = len(add_symbol_properties(database, sorted(manifest["coins"]))) 

165 manifest_path.write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n") 

166 return manifest 

167 

168 

169def _save(manifest_path, manifest, volume_path, quote_volume, funding_path, funding) -> None: 

170 manifest_path.write_text(json.dumps(manifest, indent=1), encoding="utf-8", newline="\n") 

171 write_frame(volume_path, pd.DataFrame(quote_volume).sort_index()) 

172 write_frame(funding_path, pd.DataFrame(funding).sort_index()) 

173 

174 

175def write_coverage(path: Path, manifest: dict, *, delisted_after: str = "2026-09-01") -> dict: 

176 """Coins whose bars stopped before the end: how the root differs from today's survivors. Holds no price or return.""" 

177 stopped = {coin: entry["last"] for coin, entry in manifest["coins"].items() if entry["last"] < delisted_after} 

178 report = {"coins": len(manifest["coins"]), "stopped_before_the_end": len(stopped), "last_bar": dict(sorted(stopped.items())), "left_out": manifest["left_out"]} 

179 Path(path).parent.mkdir(parents=True, exist_ok=True) 

180 Path(path).write_text(json.dumps(report, indent=1), encoding="utf-8", newline="\n") 

181 return report 

182 

183 

184def main() -> int: 

185 import requests 

186 

187 session = requests.Session() 

188 session.headers["User-Agent"] = "AetherQuantResearch/6.6 (github.com/leon1706-lol/Aether-quant)" 

189 

190 def get_text(url: str) -> str: 

191 response = net_retry.fetch(url, get=session.get, timeout=60.0) 

192 if response is None: 

193 raise SystemExit(f"{url}: the listing itself is gone") 

194 return response.text 

195 

196 def get_bytes(url: str) -> bytes | None: 

197 response = net_retry.fetch(url, get=session.get, timeout=60.0) 

198 return None if response is None else response.content 

199 

200 parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) 

201 parser.add_argument("--out", default="data_crypto_wide") 

202 parser.add_argument("--cut-swaps", action="store_true", help="cut the pairs of an existing root at a token swap; downloads nothing") 

203 args = parser.parse_args() 

204 if args.cut_swaps: 

205 print(json.dumps(cut_swaps(ROOT / args.out), indent=1)) 

206 return 0 

207 try: 

208 manifest = build_root(ROOT / args.out, get_text=get_text, get_bytes=get_bytes) 

209 except net_retry.NetworkOutage as error: 

210 print(f"stopped by a network outage, rerun to resume: {error}", file=sys.stderr, flush=True) 

211 return 3 

212 report = write_coverage(ROOT / "ml" / "evaluation" / "v660" / "crypto_wide_coverage.json", manifest) 

213 print(f"{report['coins']} coins, {report['stopped_before_the_end']} stopped before the end") 

214 return 0 

215 

216 

217if __name__ == "__main__": 

218 raise SystemExit(main())