oss-backtest-kit 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- oss_backtest_kit/__init__.py +6 -0
- oss_backtest_kit/data/__init__.py +7 -0
- oss_backtest_kit/data/__main__.py +70 -0
- oss_backtest_kit/data/_http.py +136 -0
- oss_backtest_kit/data/archive.py +289 -0
- oss_backtest_kit/data/check.py +115 -0
- oss_backtest_kit/data/rest_tail.py +150 -0
- oss_backtest_kit/engine.py +405 -0
- oss_backtest_kit/stats.py +246 -0
- oss_backtest_kit-0.1.0.dist-info/METADATA +209 -0
- oss_backtest_kit-0.1.0.dist-info/RECORD +14 -0
- oss_backtest_kit-0.1.0.dist-info/WHEEL +5 -0
- oss_backtest_kit-0.1.0.dist-info/licenses/LICENSE +21 -0
- oss_backtest_kit-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Public market-data download and verification helpers."""
|
|
2
|
+
|
|
3
|
+
from . import archive, check, rest_tail
|
|
4
|
+
from ._http import DataError, HttpClient, RefusedError, TooLargeError
|
|
5
|
+
|
|
6
|
+
__all__ = ["archive", "check", "rest_tail", "DataError", "HttpClient",
|
|
7
|
+
"RefusedError", "TooLargeError"]
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Command line: python -m oss_backtest_kit.data {archive,rest,check} ..."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import sys
|
|
5
|
+
|
|
6
|
+
from . import archive, check, rest_tail
|
|
7
|
+
from ._http import DataError
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _csv(text):
|
|
11
|
+
return [x for x in text.split(",") if x]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def main(argv=None):
|
|
15
|
+
ap = argparse.ArgumentParser(prog="python -m oss_backtest_kit.data")
|
|
16
|
+
sub = ap.add_subparsers(dest="cmd", required=True)
|
|
17
|
+
|
|
18
|
+
a = sub.add_parser("archive", help="download archive files with checksum verification")
|
|
19
|
+
a.add_argument("--kinds", required=True, help="comma list of: %s" % ",".join(archive.KINDS))
|
|
20
|
+
a.add_argument("--symbols", required=True, help="comma list, e.g. BTCUSDT")
|
|
21
|
+
a.add_argument("--interval", help="bar interval for kline kinds, e.g. 1h")
|
|
22
|
+
a.add_argument("--from", dest="start", required=True, help="first month YYYY-MM")
|
|
23
|
+
a.add_argument("--to", dest="end", required=True, help="last month YYYY-MM")
|
|
24
|
+
a.add_argument("--out", required=True, help="output directory")
|
|
25
|
+
|
|
26
|
+
r = sub.add_parser("rest", help="fetch recent bars from the public REST API")
|
|
27
|
+
r.add_argument("--kinds", required=True)
|
|
28
|
+
r.add_argument("--symbols", required=True)
|
|
29
|
+
r.add_argument("--interval", required=True)
|
|
30
|
+
r.add_argument("--from", dest="start", required=True, help="UTC day YYYY-MM-DD")
|
|
31
|
+
r.add_argument("--to", dest="end", help="UTC day YYYY-MM-DD (exclusive)")
|
|
32
|
+
r.add_argument("--out", required=True)
|
|
33
|
+
|
|
34
|
+
c = sub.add_parser("check", help="verify manifest and bar continuity")
|
|
35
|
+
c.add_argument("--out", required=True)
|
|
36
|
+
c.add_argument("--kind", help="series kind to check for gaps")
|
|
37
|
+
c.add_argument("--symbol")
|
|
38
|
+
c.add_argument("--interval")
|
|
39
|
+
|
|
40
|
+
args = ap.parse_args(argv)
|
|
41
|
+
try:
|
|
42
|
+
if args.cmd == "archive":
|
|
43
|
+
for (sym, kind), stat in archive.download(
|
|
44
|
+
_csv(args.kinds), _csv(args.symbols), args.start, args.end,
|
|
45
|
+
args.out, args.interval).items():
|
|
46
|
+
print(sym, kind, stat)
|
|
47
|
+
return 0
|
|
48
|
+
if args.cmd == "rest":
|
|
49
|
+
for path in rest_tail.run(_csv(args.symbols), _csv(args.kinds), args.interval,
|
|
50
|
+
args.start, args.out, args.end):
|
|
51
|
+
print(path)
|
|
52
|
+
return 0
|
|
53
|
+
rep = check.check_manifest(args.out)
|
|
54
|
+
print("manifest", rep)
|
|
55
|
+
bad = bool(rep["problems"])
|
|
56
|
+
if args.kind:
|
|
57
|
+
cont = check.check_continuity(args.out, args.kind, args.symbol, args.interval)
|
|
58
|
+
print("continuity", cont)
|
|
59
|
+
bad = bad or bool(cont["gaps"] or cont["duplicates"] or cont["bad_close_time"])
|
|
60
|
+
return 1 if bad else 0
|
|
61
|
+
except archive.DiskLowError as exc:
|
|
62
|
+
print("STOP:", exc)
|
|
63
|
+
return 4
|
|
64
|
+
except (DataError, ValueError) as exc:
|
|
65
|
+
print("ERROR:", exc)
|
|
66
|
+
return 2
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
if __name__ == "__main__":
|
|
70
|
+
sys.exit(main())
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""A deliberately strict HTTPS GET client for public market-data hosts.
|
|
2
|
+
|
|
3
|
+
Safety properties:
|
|
4
|
+
|
|
5
|
+
* one allowed host, https only, default port only
|
|
6
|
+
* no proxy settings taken from the environment
|
|
7
|
+
* redirects are never followed (a redirect is an error)
|
|
8
|
+
* the response body is size-bounded and the whole request has a deadline
|
|
9
|
+
* the opener is injectable so tests can run fully offline
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import time
|
|
13
|
+
import urllib.error
|
|
14
|
+
import urllib.parse
|
|
15
|
+
import urllib.request
|
|
16
|
+
import ssl
|
|
17
|
+
|
|
18
|
+
__all__ = ["DataError", "RefusedError", "TooLargeError", "TransientError", "HttpClient"]
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class DataError(Exception):
|
|
22
|
+
"""Base class for download problems."""
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class RefusedError(DataError):
|
|
26
|
+
"""The request or response broke a safety rule (host, scheme, redirect)."""
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class TooLargeError(DataError):
|
|
30
|
+
"""The response body exceeded the size limit."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TransientError(DataError):
|
|
34
|
+
"""A retryable failure (network error, timeout, server error)."""
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
38
|
+
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
|
39
|
+
return None # urllib then raises HTTPError for the 3xx response
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def default_opener():
|
|
43
|
+
"""Opener without environment proxies and without redirect following."""
|
|
44
|
+
return urllib.request.build_opener(
|
|
45
|
+
urllib.request.ProxyHandler({}),
|
|
46
|
+
_NoRedirect,
|
|
47
|
+
urllib.request.HTTPSHandler(context=ssl.create_default_context()),
|
|
48
|
+
).open
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class HttpClient:
|
|
52
|
+
"""GET client bound to a single host.
|
|
53
|
+
|
|
54
|
+
``opener(request, timeout=...)`` must return a file-like response with
|
|
55
|
+
``read``/``read1``, ``geturl()`` and ``headers``. Defaults to a hardened
|
|
56
|
+
urllib opener.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
def __init__(self, allowed_host, opener=None, max_bytes=64 * 1024 * 1024,
|
|
60
|
+
deadline_s=300.0, socket_timeout_s=30.0, retries=4,
|
|
61
|
+
backoff_s=2.0, sleep=time.sleep, clock=time.monotonic,
|
|
62
|
+
user_agent="oss-backtest-kit"):
|
|
63
|
+
self.allowed_host = allowed_host
|
|
64
|
+
self.opener = opener or default_opener()
|
|
65
|
+
self.max_bytes = max_bytes
|
|
66
|
+
self.deadline_s = deadline_s
|
|
67
|
+
self.socket_timeout_s = socket_timeout_s
|
|
68
|
+
self.retries = retries
|
|
69
|
+
self.backoff_s = backoff_s
|
|
70
|
+
self.sleep = sleep
|
|
71
|
+
self.clock = clock
|
|
72
|
+
self.user_agent = user_agent
|
|
73
|
+
|
|
74
|
+
def _check_url(self, url):
|
|
75
|
+
u = urllib.parse.urlsplit(url)
|
|
76
|
+
if u.scheme != "https" or u.hostname != self.allowed_host or u.port not in (None, 443):
|
|
77
|
+
raise RefusedError("refused url: %s" % url)
|
|
78
|
+
if "@" in u.netloc:
|
|
79
|
+
raise RefusedError("refused url with embedded userinfo: %s" % url)
|
|
80
|
+
|
|
81
|
+
def _once(self, url):
|
|
82
|
+
self._check_url(url)
|
|
83
|
+
start = self.clock()
|
|
84
|
+
req = urllib.request.Request(url, headers={"User-Agent": self.user_agent})
|
|
85
|
+
try:
|
|
86
|
+
resp = self.opener(req, timeout=self.socket_timeout_s)
|
|
87
|
+
except urllib.error.HTTPError as exc:
|
|
88
|
+
code = exc.code
|
|
89
|
+
exc.close()
|
|
90
|
+
if code == 404:
|
|
91
|
+
return None
|
|
92
|
+
if 300 <= code < 400:
|
|
93
|
+
raise RefusedError("redirect refused (%d): %s" % (code, url))
|
|
94
|
+
if code == 429 or code >= 500:
|
|
95
|
+
raise TransientError("http %d: %s" % (code, url))
|
|
96
|
+
raise DataError("http %d: %s" % (code, url))
|
|
97
|
+
except (urllib.error.URLError, OSError) as exc:
|
|
98
|
+
raise TransientError("network error %r: %s" % (exc, url))
|
|
99
|
+
try:
|
|
100
|
+
status = getattr(resp, "status", 200)
|
|
101
|
+
if 300 <= status < 400:
|
|
102
|
+
raise RefusedError("redirect refused (%d): %s" % (status, url))
|
|
103
|
+
if urllib.parse.urlsplit(resp.geturl()).hostname != self.allowed_host:
|
|
104
|
+
raise RefusedError("unexpected final url: %s" % resp.geturl())
|
|
105
|
+
parts, total = [], 0
|
|
106
|
+
read = getattr(resp, "read1", None) or resp.read
|
|
107
|
+
while True:
|
|
108
|
+
chunk = read(65536)
|
|
109
|
+
if not chunk:
|
|
110
|
+
break
|
|
111
|
+
total += len(chunk)
|
|
112
|
+
if total > self.max_bytes:
|
|
113
|
+
raise TooLargeError("response larger than %d bytes: %s" % (self.max_bytes, url))
|
|
114
|
+
if self.clock() - start > self.deadline_s:
|
|
115
|
+
raise TransientError("deadline exceeded: %s" % url)
|
|
116
|
+
parts.append(chunk)
|
|
117
|
+
return b"".join(parts), getattr(resp, "headers", {}) or {}
|
|
118
|
+
finally:
|
|
119
|
+
close = getattr(resp, "close", None)
|
|
120
|
+
if close:
|
|
121
|
+
close()
|
|
122
|
+
|
|
123
|
+
def get(self, url):
|
|
124
|
+
"""Return ``(body_bytes, headers)``, or ``None`` on HTTP 404.
|
|
125
|
+
|
|
126
|
+
Retries transient failures; refusals and oversize bodies are final.
|
|
127
|
+
"""
|
|
128
|
+
last = None
|
|
129
|
+
for attempt in range(self.retries + 1):
|
|
130
|
+
try:
|
|
131
|
+
return self._once(url)
|
|
132
|
+
except TransientError as exc:
|
|
133
|
+
last = str(exc)
|
|
134
|
+
if attempt < self.retries:
|
|
135
|
+
self.sleep(self.backoff_s * (attempt + 1))
|
|
136
|
+
raise DataError("failed after retries: %s" % last)
|
|
@@ -0,0 +1,289 @@
|
|
|
1
|
+
"""Download public daily/monthly archive files from data.binance.vision.
|
|
2
|
+
|
|
3
|
+
Every zip is verified against the published ``.CHECKSUM`` (SHA-256) before it
|
|
4
|
+
is written or recorded. Files are never overwritten. Each file is written to a
|
|
5
|
+
temporary name, synced, and only then published under its final name, so a
|
|
6
|
+
final name never holds partial content. Verified downloads are listed in
|
|
7
|
+
``MANIFEST.csv`` inside the output directory.
|
|
8
|
+
|
|
9
|
+
Use of the data is subject to the exchange's public data terms; this module
|
|
10
|
+
only fetches what the caller asks for.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import csv
|
|
14
|
+
import datetime as dt
|
|
15
|
+
import hashlib
|
|
16
|
+
import io
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import shutil
|
|
20
|
+
import tempfile
|
|
21
|
+
import time
|
|
22
|
+
import zipfile
|
|
23
|
+
from pathlib import Path
|
|
24
|
+
|
|
25
|
+
from ._http import DataError, HttpClient
|
|
26
|
+
|
|
27
|
+
__all__ = ["BASE", "HOST", "KINDS", "MANIFEST_COLS", "DiskLowError", "atomic_create",
|
|
28
|
+
"build_url", "download", "months", "write_new"]
|
|
29
|
+
|
|
30
|
+
HOST = "data.binance.vision"
|
|
31
|
+
BASE = "https://%s/data/futures/um" % HOST
|
|
32
|
+
MIN_FREE_BYTES = 2 * 1024 ** 3
|
|
33
|
+
MAX_UNZIPPED_BYTES = 1024 ** 3
|
|
34
|
+
MANIFEST_COLS = ["kind", "symbol", "interval", "freq", "period", "url", "sha256",
|
|
35
|
+
"download_utc", "bytes", "rows", "first_ts_ms", "last_ts_ms", "local_path"]
|
|
36
|
+
|
|
37
|
+
# kind -> (needs_interval, daily_only)
|
|
38
|
+
KINDS = {
|
|
39
|
+
"klines": (True, False),
|
|
40
|
+
"markPriceKlines": (True, False),
|
|
41
|
+
"indexPriceKlines": (True, False),
|
|
42
|
+
"premiumIndexKlines": (True, False),
|
|
43
|
+
"fundingRate": (False, False),
|
|
44
|
+
"metrics": (False, True),
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
_SYMBOL_RE = re.compile(r"^[A-Z0-9]{2,20}$")
|
|
48
|
+
_INTERVAL_RE = re.compile(r"^[0-9]{1,2}[mhdwM]$")
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
class DiskLowError(DataError):
|
|
52
|
+
"""Free disk space would fall below the safety margin."""
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def _validate(kind, symbol, interval):
|
|
56
|
+
if kind not in KINDS:
|
|
57
|
+
raise ValueError("unknown kind %r; choose from %s" % (kind, sorted(KINDS)))
|
|
58
|
+
if not _SYMBOL_RE.match(symbol):
|
|
59
|
+
raise ValueError("bad symbol %r" % symbol)
|
|
60
|
+
if interval and not _INTERVAL_RE.match(interval):
|
|
61
|
+
raise ValueError("bad interval %r; use a value such as 1h" % (interval,))
|
|
62
|
+
if KINDS[kind][0] and not interval:
|
|
63
|
+
raise ValueError("kind %s needs an interval such as 1h" % kind)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def build_url(kind, symbol, freq, period, interval=None):
|
|
67
|
+
"""URL of one archive zip. ``freq`` is ``monthly`` or ``daily``."""
|
|
68
|
+
_validate(kind, symbol, interval)
|
|
69
|
+
if freq not in ("monthly", "daily"):
|
|
70
|
+
raise ValueError("freq must be monthly or daily")
|
|
71
|
+
if KINDS[kind][0]:
|
|
72
|
+
folder = "%s/%s/%s" % (kind, symbol, interval)
|
|
73
|
+
name = "%s-%s-%s.zip" % (symbol, interval, period)
|
|
74
|
+
else:
|
|
75
|
+
folder = "%s/%s" % (kind, symbol)
|
|
76
|
+
name = "%s-%s-%s.zip" % (symbol, kind, period)
|
|
77
|
+
return "%s/%s/%s/%s" % (BASE, freq, folder, name)
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def months(start, end):
|
|
81
|
+
"""Yield ``YYYY-MM`` strings from ``start`` to ``end`` inclusive."""
|
|
82
|
+
y, m = map(int, start.split("-"))
|
|
83
|
+
y2, m2 = map(int, end.split("-"))
|
|
84
|
+
while (y, m) <= (y2, m2):
|
|
85
|
+
yield "%04d-%02d" % (y, m)
|
|
86
|
+
y, m = (y + 1, 1) if m == 12 else (y, m + 1)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def _need_space(path, nbytes, min_free):
|
|
90
|
+
p = Path(path)
|
|
91
|
+
while not p.exists():
|
|
92
|
+
p = p.parent
|
|
93
|
+
if shutil.disk_usage(str(p)).free - nbytes < min_free:
|
|
94
|
+
raise DiskLowError("free disk space too low to write %d bytes at %s" % (nbytes, p))
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def atomic_create(path, data, min_free=0):
|
|
98
|
+
"""Publish ``data`` at ``path`` only once it is completely written.
|
|
99
|
+
|
|
100
|
+
The bytes go to a temporary file in the same directory, are synced, and are
|
|
101
|
+
then hard-linked to ``path``; the link fails with ``FileExistsError`` if
|
|
102
|
+
``path`` exists, so nothing is overwritten. The temporary name is always
|
|
103
|
+
removed, so a failure leaves neither a partial final file nor a temp file.
|
|
104
|
+
"""
|
|
105
|
+
path = Path(path)
|
|
106
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
107
|
+
_need_space(path.parent, len(data), min_free)
|
|
108
|
+
fd, tmp = tempfile.mkstemp(prefix=".%s." % path.name, suffix=".part", dir=str(path.parent))
|
|
109
|
+
try:
|
|
110
|
+
with os.fdopen(fd, "wb") as fh:
|
|
111
|
+
fh.write(data)
|
|
112
|
+
fh.flush()
|
|
113
|
+
os.fsync(fh.fileno())
|
|
114
|
+
os.link(tmp, str(path))
|
|
115
|
+
finally:
|
|
116
|
+
os.unlink(tmp)
|
|
117
|
+
return path
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def write_new(path, data, stamp, min_free=MIN_FREE_BYTES):
|
|
121
|
+
"""Create ``path`` exclusively and atomically; return the path that holds ``data``.
|
|
122
|
+
|
|
123
|
+
If the file already exists with identical content it is kept. If it exists
|
|
124
|
+
with different content, the data goes to a fresh sibling name. Nothing is
|
|
125
|
+
ever overwritten or truncated.
|
|
126
|
+
"""
|
|
127
|
+
path = Path(path)
|
|
128
|
+
digest = hashlib.sha256(data).hexdigest()
|
|
129
|
+
candidates = [path] + [
|
|
130
|
+
path.with_name("%s.redl%s_%d%s" % (path.stem, stamp, i, path.suffix)) for i in range(100)
|
|
131
|
+
]
|
|
132
|
+
for cand in candidates:
|
|
133
|
+
try:
|
|
134
|
+
return atomic_create(cand, data, min_free)
|
|
135
|
+
except FileExistsError:
|
|
136
|
+
if hashlib.sha256(cand.read_bytes()).hexdigest() == digest:
|
|
137
|
+
return cand
|
|
138
|
+
raise DataError("no free file name near %s" % path)
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _to_ms(value):
|
|
142
|
+
value = value.strip()
|
|
143
|
+
if value.isdigit():
|
|
144
|
+
n = int(value)
|
|
145
|
+
if n >= 10 ** 15:
|
|
146
|
+
return n // 1000
|
|
147
|
+
return n if n >= 10 ** 12 else n * 1000
|
|
148
|
+
t = dt.datetime.strptime(value, "%Y-%m-%d %H:%M:%S").replace(tzinfo=dt.timezone.utc)
|
|
149
|
+
return int(t.timestamp() * 1000)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _scan(blob):
|
|
153
|
+
"""Return ``(rows, first_ms, last_ms)`` of the first csv inside a zip."""
|
|
154
|
+
with zipfile.ZipFile(io.BytesIO(blob)) as zf:
|
|
155
|
+
info = zf.infolist()[0]
|
|
156
|
+
if info.file_size > MAX_UNZIPPED_BYTES:
|
|
157
|
+
raise DataError("zip member too large: %d bytes" % info.file_size)
|
|
158
|
+
rows, first, last = 0, None, None
|
|
159
|
+
with zf.open(info) as fh:
|
|
160
|
+
for i, rec in enumerate(csv.reader(io.TextIOWrapper(fh, "ascii"))):
|
|
161
|
+
if not rec or (i == 0 and not rec[0].strip()[:1].isdigit()):
|
|
162
|
+
continue
|
|
163
|
+
ms = _to_ms(rec[0])
|
|
164
|
+
first = ms if first is None else first
|
|
165
|
+
last = ms
|
|
166
|
+
rows += 1
|
|
167
|
+
return rows, first, last
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _parse_checksum(blob):
|
|
171
|
+
words = blob.decode("ascii", "replace").split()
|
|
172
|
+
if words and re.fullmatch(r"[0-9a-fA-F]{64}", words[0]):
|
|
173
|
+
return words[0].lower()
|
|
174
|
+
return None
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def _done_urls(manifest):
|
|
178
|
+
if not manifest.exists():
|
|
179
|
+
return set()
|
|
180
|
+
with open(manifest, newline="") as fh:
|
|
181
|
+
return {r["url"] for r in csv.DictReader(fh)}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _record(manifest, row, min_free):
|
|
185
|
+
"""Add one complete row: a new manifest is published atomically with its
|
|
186
|
+
header; an existing one gets the row in a single append write."""
|
|
187
|
+
_need_space(manifest.parent, 4096, min_free)
|
|
188
|
+
buf = io.StringIO()
|
|
189
|
+
csv.DictWriter(buf, MANIFEST_COLS).writerow(row)
|
|
190
|
+
line = buf.getvalue().encode("utf-8")
|
|
191
|
+
if not manifest.exists():
|
|
192
|
+
head = io.StringIO()
|
|
193
|
+
csv.DictWriter(head, MANIFEST_COLS).writeheader()
|
|
194
|
+
try:
|
|
195
|
+
atomic_create(manifest, head.getvalue().encode("utf-8") + line, min_free)
|
|
196
|
+
return
|
|
197
|
+
except FileExistsError:
|
|
198
|
+
pass
|
|
199
|
+
fd = os.open(str(manifest), os.O_WRONLY | os.O_APPEND)
|
|
200
|
+
try:
|
|
201
|
+
if os.write(fd, line) != len(line):
|
|
202
|
+
raise DataError("short write to %s" % manifest)
|
|
203
|
+
os.fsync(fd)
|
|
204
|
+
finally:
|
|
205
|
+
os.close(fd)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def fetch_one(client, out_dir, kind, symbol, freq, period, interval=None,
|
|
209
|
+
done=None, min_free=MIN_FREE_BYTES, pause_s=0.0, sleep=time.sleep):
|
|
210
|
+
"""Download, verify and record one archive file.
|
|
211
|
+
|
|
212
|
+
Returns ``skip`` (already in manifest), ``absent`` (404), ``ok``,
|
|
213
|
+
``no_checksum`` or ``mismatch``. Only ``ok`` files are saved and recorded.
|
|
214
|
+
"""
|
|
215
|
+
out_dir = Path(out_dir)
|
|
216
|
+
url = build_url(kind, symbol, freq, period, interval)
|
|
217
|
+
done = _done_urls(out_dir / "MANIFEST.csv") if done is None else done
|
|
218
|
+
if url in done:
|
|
219
|
+
return "skip"
|
|
220
|
+
got = client.get(url)
|
|
221
|
+
sleep(pause_s)
|
|
222
|
+
if got is None:
|
|
223
|
+
return "absent"
|
|
224
|
+
blob = got[0]
|
|
225
|
+
ck = client.get(url + ".CHECKSUM")
|
|
226
|
+
sleep(pause_s)
|
|
227
|
+
want = _parse_checksum(ck[0]) if ck else None
|
|
228
|
+
if want is None:
|
|
229
|
+
return "no_checksum"
|
|
230
|
+
digest = hashlib.sha256(blob).hexdigest()
|
|
231
|
+
if digest != want:
|
|
232
|
+
return "mismatch"
|
|
233
|
+
rows, first, last = _scan(blob)
|
|
234
|
+
if not KINDS[kind][0]:
|
|
235
|
+
interval = None # not part of this kind's URL, so not part of its path
|
|
236
|
+
rel = Path(kind) / symbol / (interval or "-") / freq / url.rsplit("/", 1)[1]
|
|
237
|
+
if out_dir.resolve() not in (out_dir / rel).resolve().parents:
|
|
238
|
+
raise DataError("refusing to write outside %s" % out_dir)
|
|
239
|
+
stamp = dt.datetime.now(dt.timezone.utc).strftime("%Y%m%dT%H%M%S")
|
|
240
|
+
path = write_new(out_dir / rel, blob, stamp, min_free)
|
|
241
|
+
write_new(path.with_name(path.name + ".CHECKSUM"), ck[0], stamp, min_free)
|
|
242
|
+
_record(out_dir / "MANIFEST.csv", {
|
|
243
|
+
"kind": kind, "symbol": symbol, "interval": interval or "", "freq": freq,
|
|
244
|
+
"period": period, "url": url, "sha256": digest,
|
|
245
|
+
"download_utc": dt.datetime.now(dt.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
246
|
+
"bytes": len(blob), "rows": rows, "first_ts_ms": first, "last_ts_ms": last,
|
|
247
|
+
"local_path": path.relative_to(out_dir).as_posix()}, min_free)
|
|
248
|
+
done.add(url)
|
|
249
|
+
return "ok"
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def download(kinds, symbols, start_month, end_month, out_dir, interval=None,
|
|
253
|
+
client=None, today=None, min_free=MIN_FREE_BYTES, pause_s=0.12,
|
|
254
|
+
sleep=time.sleep):
|
|
255
|
+
"""Download a date range. Monthly files first, daily files for months without one.
|
|
256
|
+
|
|
257
|
+
``start_month`` / ``end_month`` are ``YYYY-MM``. Daily fallback runs up to
|
|
258
|
+
yesterday (UTC); ``metrics`` exists only as daily files. Returns a dict
|
|
259
|
+
``{(symbol, kind): {status: count}}``.
|
|
260
|
+
"""
|
|
261
|
+
for kind in kinds:
|
|
262
|
+
for symbol in symbols:
|
|
263
|
+
_validate(kind, symbol, interval)
|
|
264
|
+
client = client or HttpClient(HOST)
|
|
265
|
+
out_dir = Path(out_dir)
|
|
266
|
+
today = today or dt.datetime.now(dt.timezone.utc).date()
|
|
267
|
+
yesterday = today - dt.timedelta(days=1)
|
|
268
|
+
done = _done_urls(out_dir / "MANIFEST.csv")
|
|
269
|
+
summary = {}
|
|
270
|
+
for symbol in symbols:
|
|
271
|
+
for kind in kinds:
|
|
272
|
+
stat = summary.setdefault((symbol, kind), {})
|
|
273
|
+
|
|
274
|
+
def bump(status):
|
|
275
|
+
stat[status] = stat.get(status, 0) + 1
|
|
276
|
+
|
|
277
|
+
for period in months(start_month, end_month):
|
|
278
|
+
res = "absent" if KINDS[kind][1] else fetch_one(
|
|
279
|
+
client, out_dir, kind, symbol, "monthly", period, interval,
|
|
280
|
+
done, min_free, pause_s, sleep)
|
|
281
|
+
if res != "absent":
|
|
282
|
+
bump(res)
|
|
283
|
+
continue
|
|
284
|
+
day = dt.date(int(period[:4]), int(period[5:]), 1)
|
|
285
|
+
while day.strftime("%Y-%m") == period and day <= yesterday:
|
|
286
|
+
bump(fetch_one(client, out_dir, kind, symbol, "daily", day.isoformat(),
|
|
287
|
+
interval, done, min_free, pause_s, sleep))
|
|
288
|
+
day += dt.timedelta(days=1)
|
|
289
|
+
return summary
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
"""Integrity and continuity checks for a directory filled by ``archive.download``.
|
|
2
|
+
|
|
3
|
+
Read-only: nothing is written. Two checks:
|
|
4
|
+
|
|
5
|
+
* :func:`check_manifest` - every manifest file exists, its SHA-256 equals the
|
|
6
|
+
manifest value and the saved ``.CHECKSUM`` sidecar.
|
|
7
|
+
* :func:`check_continuity` - merged bars of one series have no duplicates, no
|
|
8
|
+
gaps and consistent open/close times.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
import csv
|
|
12
|
+
import hashlib
|
|
13
|
+
import heapq
|
|
14
|
+
import io
|
|
15
|
+
import re
|
|
16
|
+
import zipfile
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
__all__ = ["interval_ms", "check_manifest", "check_continuity", "check_funding_spacing"]
|
|
20
|
+
|
|
21
|
+
_UNITS = {"m": 60000, "h": 3600000, "d": 86400000, "w": 7 * 86400000}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def interval_ms(interval):
|
|
25
|
+
"""Bar length in ms for fixed-length intervals (m, h, d, w)."""
|
|
26
|
+
m = re.fullmatch(r"([0-9]{1,2})([mhdw])", interval)
|
|
27
|
+
if not m:
|
|
28
|
+
raise ValueError("unsupported interval %r (monthly bars have no fixed length)" % interval)
|
|
29
|
+
return int(m.group(1)) * _UNITS[m.group(2)]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ms(value):
|
|
33
|
+
n = int(value)
|
|
34
|
+
return n // 1000 if n >= 10 ** 15 else n
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _manifest_rows(out_dir):
|
|
38
|
+
path = Path(out_dir) / "MANIFEST.csv"
|
|
39
|
+
if not path.exists():
|
|
40
|
+
return []
|
|
41
|
+
with open(path, newline="") as fh:
|
|
42
|
+
return list(csv.DictReader(fh))
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _records(out_dir, rel):
|
|
46
|
+
with zipfile.ZipFile(Path(out_dir) / rel) as zf, zf.open(zf.namelist()[0]) as fh:
|
|
47
|
+
for rec in csv.reader(io.TextIOWrapper(fh, "ascii")):
|
|
48
|
+
if rec and rec[0].strip()[:1].isdigit():
|
|
49
|
+
yield rec
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def check_manifest(out_dir):
|
|
53
|
+
"""Return ``{"verified": n, "problems": {name: count}}``."""
|
|
54
|
+
out_dir = Path(out_dir)
|
|
55
|
+
rows = _manifest_rows(out_dir)
|
|
56
|
+
problems = {}
|
|
57
|
+
|
|
58
|
+
def bad(name):
|
|
59
|
+
problems[name] = problems.get(name, 0) + 1
|
|
60
|
+
|
|
61
|
+
for r in rows:
|
|
62
|
+
p = out_dir / r["local_path"]
|
|
63
|
+
if not p.is_file():
|
|
64
|
+
bad("missing_file")
|
|
65
|
+
continue
|
|
66
|
+
digest = hashlib.sha256(p.read_bytes()).hexdigest()
|
|
67
|
+
if digest != r["sha256"]:
|
|
68
|
+
bad("sha_vs_manifest")
|
|
69
|
+
ck = p.with_name(p.name + ".CHECKSUM")
|
|
70
|
+
if not ck.is_file():
|
|
71
|
+
bad("missing_checksum_file")
|
|
72
|
+
elif digest != (ck.read_text().split() or [""])[0].lower():
|
|
73
|
+
bad("sha_vs_checksum_file")
|
|
74
|
+
return {"verified": len(rows), "problems": problems}
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def check_continuity(out_dir, kind, symbol, interval):
|
|
78
|
+
"""Gap and shape report for one kline-type series listed in the manifest."""
|
|
79
|
+
out_dir = Path(out_dir)
|
|
80
|
+
step = interval_ms(interval)
|
|
81
|
+
files = sorted((r for r in _manifest_rows(out_dir)
|
|
82
|
+
if r["kind"] == kind and r["symbol"] == symbol and r["interval"] == interval),
|
|
83
|
+
key=lambda r: int(r["first_ts_ms"] or 0))
|
|
84
|
+
streams = (_records(out_dir, r["local_path"]) for r in files)
|
|
85
|
+
prev, first, bars, dup, bad_close, gaps = None, None, 0, 0, 0, []
|
|
86
|
+
for rec in heapq.merge(*streams, key=lambda rec: _ms(rec[0])):
|
|
87
|
+
t = _ms(rec[0])
|
|
88
|
+
if len(rec) > 6 and _ms(rec[6]) != t + step - 1:
|
|
89
|
+
bad_close += 1
|
|
90
|
+
if prev is not None:
|
|
91
|
+
if t <= prev:
|
|
92
|
+
dup += 1
|
|
93
|
+
continue
|
|
94
|
+
if t != prev + step:
|
|
95
|
+
gaps.append((prev, t))
|
|
96
|
+
first = t if first is None else first
|
|
97
|
+
prev, bars = t, bars + 1
|
|
98
|
+
missing = sum((b - a) // step - 1 for a, b in gaps)
|
|
99
|
+
return {"files": len(files), "bars": bars, "first_ms": first, "last_ms": prev,
|
|
100
|
+
"duplicates": dup, "gaps": gaps, "missing_bars": missing,
|
|
101
|
+
"bad_close_time": bad_close}
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def check_funding_spacing(out_dir, symbol):
|
|
105
|
+
"""Histogram of hours between funding events: ``{hours: count}``."""
|
|
106
|
+
out_dir = Path(out_dir)
|
|
107
|
+
files = sorted((r for r in _manifest_rows(out_dir)
|
|
108
|
+
if r["kind"] == "fundingRate" and r["symbol"] == symbol),
|
|
109
|
+
key=lambda r: int(r["first_ts_ms"] or 0))
|
|
110
|
+
ts = sorted(_ms(rec[0]) for r in files for rec in _records(out_dir, r["local_path"]))
|
|
111
|
+
hist = {}
|
|
112
|
+
for a, b in zip(ts, ts[1:]):
|
|
113
|
+
h = round((b - a) / 3600000.0, 2)
|
|
114
|
+
hist[h] = hist.get(h, 0) + 1
|
|
115
|
+
return hist
|