File size: 2,619 Bytes
28673f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
"""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)