Download sim/fetch_data.py from dejanb/hrt: direct link, hf CLI and curl.
- Browser
- Download file 2.62 kB
-
https://huggingface.co/datasets/dejanb/hrt/resolve/main/sim/fetch_data.py
- Command line
-
hf download hf://datasets/dejanb/hrt/sim/fetch_data.py
-
curl -L -o fetch_data.py https://huggingface.co/datasets/dejanb/hrt/resolve/main/sim/fetch_data.py
2.62 kB
| """Download daily close prices into hrt/data/: Binance public API for crypto, Yahoo Finance | |
| chart API (dividend-adjusted close) for ETFs.""" | |
| import csv | |
| import json | |
| import sys | |
| import time | |
| import urllib.request | |
| from pathlib import Path | |
| DATA = Path(__file__).resolve().parent.parent / "data" | |
| BINANCE = "https://data-api.binance.vision/api/v3/klines" | |
| def get(url): | |
| with urllib.request.urlopen(url, timeout=30) as r: | |
| return r.read() | |
| def binance_daily(symbol): | |
| rows, start = [], 1500000000000 # mid-2017, before the first listing | |
| while True: | |
| url = f"{BINANCE}?symbol={symbol}&interval=1d&limit=1000&startTime={start}" | |
| batch = json.loads(get(url)) | |
| if not batch: | |
| break | |
| for k in batch: | |
| if k[6] > time.time() * 1000: # today's candle is not closed yet | |
| continue | |
| day = time.strftime("%Y-%m-%d", time.gmtime(k[0] / 1000)) | |
| rows.append((day, float(k[4]))) | |
| start = batch[-1][0] + 86400000 | |
| if len(batch) < 1000: | |
| break | |
| return rows | |
| def yahoo_daily(symbol, start="2005-01-01"): | |
| p1 = int(time.mktime(time.strptime(start, "%Y-%m-%d"))) | |
| url = (f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}" | |
| f"?period1={p1}&period2={int(time.time())}&interval=1d&events=div%2Csplit") | |
| req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"}) | |
| with urllib.request.urlopen(req, timeout=30) as r: | |
| res = json.loads(r.read())["chart"]["result"][0] | |
| today = time.strftime("%Y-%m-%d", time.gmtime()) | |
| rows = [] | |
| for ts, px in zip(res["timestamp"], res["indicators"]["adjclose"][0]["adjclose"]): | |
| day = time.strftime("%Y-%m-%d", time.gmtime(ts)) | |
| if px is not None and day < today: # today's bar may not be closed yet | |
| rows.append((day, round(px, 4))) | |
| return rows | |
| def save(name, rows): | |
| with open(DATA / f"{name}.csv", "w", newline="") as f: | |
| w = csv.writer(f) | |
| w.writerow(["date", "close"]) | |
| w.writerows(rows) | |
| print(name, len(rows), rows[0][0] if rows else "-", rows[-1][0] if rows else "-") | |
| CRYPTO = dict(btc="BTCUSDT", eth="ETHUSDT", bnb="BNBUSDT", xrp="XRPUSDT", ltc="LTCUSDT", | |
| ada="ADAUSDT") | |
| ETF = dict(spy="SPY", qqq="QQQ", gld="GLD", tlt="TLT") | |
| if __name__ == "__main__": | |
| DATA.mkdir(exist_ok=True) | |
| for name, sym in CRYPTO.items(): | |
| save(name, binance_daily(sym)) | |
| for name, sym in ETF.items(): | |
| try: | |
| save(name, yahoo_daily(sym)) | |
| except Exception as e: | |
| print(name, "skipped:", e, file=sys.stderr) | |