File size: 8,840 Bytes
c976a58
 
74c5b1c
 
 
 
c976a58
74c5b1c
c976a58
 
 
 
 
74c5b1c
 
 
c976a58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74c5b1c
c976a58
 
 
 
 
 
 
 
 
 
 
 
74c5b1c
c976a58
 
 
 
 
 
74c5b1c
c976a58
 
 
 
 
 
 
 
 
74c5b1c
 
 
 
 
c976a58
 
74c5b1c
c976a58
 
 
 
 
 
 
 
 
 
 
 
 
 
74c5b1c
c976a58
 
 
 
 
74c5b1c
c976a58
 
 
 
 
 
 
74c5b1c
c976a58
74c5b1c
c976a58
 
74c5b1c
c976a58
 
74c5b1c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c976a58
 
74c5b1c
 
c976a58
74c5b1c
c976a58
 
74c5b1c
c976a58
74c5b1c
 
 
 
 
 
 
 
c976a58
 
74c5b1c
c976a58
 
74c5b1c
 
 
 
c976a58
74c5b1c
 
 
 
 
 
 
 
 
 
c976a58
74c5b1c
c976a58
 
74c5b1c
c976a58
74c5b1c
c976a58
74c5b1c
c976a58
 
 
 
 
 
74c5b1c
c976a58
74c5b1c
 
c976a58
 
 
 
 
74c5b1c
c976a58
74c5b1c
 
c976a58
 
 
 
 
 
 
 
 
 
 
74c5b1c
 
c976a58
 
 
 
 
 
 
 
74c5b1c
c976a58
 
 
 
 
 
 
 
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
#!/usr/bin/env python3
"""
daily_update.py
===============
Checks the latest timestamp in each asset's combined Parquet on HuggingFace,
downloads any missing daily 1s files from Binance Vision, and appends them.

Run this script daily (e.g. via a cron job, Replit workflow, or HF Spaces scheduler).

Binance daily endpoint:
  https://data.binance.vision/data/spot/daily/klines/{SYMBOL}/1s/{SYMBOL}-1s-YYYY-MM-DD.zip

Usage:
  HF_TOKEN=<token> python scripts/daily_update.py
  python scripts/daily_update.py --dry-run            # show what would be fetched, no upload
  python scripts/daily_update.py --symbols DOGEUSDT   # update one symbol only
"""

import argparse
import datetime
import gc
import io
import os
import sys
import time
import zipfile
from pathlib import Path

import numpy as np
import pandas as pd
import pyarrow as pa
import pyarrow.parquet as pq
import requests
from huggingface_hub import HfApi, hf_hub_download

# ── Config ────────────────────────────────────────────────────────────────────
REPO_ID       = "commanderzee/1s-crypto-data"
HF_TOKEN      = os.environ.get("HF_TOKEN", "")
BINANCE_DAILY = "https://data.binance.vision/data/spot/daily/klines"

SYMBOLS = ["DOGEUSDT", "XRPUSDT", "SOLUSDT", "BTCUSDT", "ETHUSDT", "BNBUSDT"]

PA_SCHEMA = pa.schema([
    ("open_time_s", pa.int64()),
    ("open",        pa.float64()),
    ("high",        pa.float64()),
    ("low",         pa.float64()),
    ("close",       pa.float64()),
    ("volume",      pa.float64()),
])


def download_daily(symbol: str, date: datetime.date, retries: int = 3):
    """Download one day of 1s OHLCV data from Binance Vision. Returns DataFrame or None."""
    fname = f"{symbol}-1s-{date:%Y-%m-%d}.zip"
    url   = f"{BINANCE_DAILY}/{symbol}/1s/{fname}"
    for attempt in range(retries):
        try:
            r = requests.get(url, timeout=120)
            if r.status_code == 404:
                return None   # day not published yet
            r.raise_for_status()
            with zipfile.ZipFile(io.BytesIO(r.content)) as z:
                with z.open(z.namelist()[0]) as f:
                    df = pd.read_csv(
                        f, header=None,
                        usecols=[0, 1, 2, 3, 4, 5],
                        names=["open_time", "open", "high", "low", "close", "volume"],
                        dtype={
                            "open_time": np.int64,
                            "open":      np.float64,
                            "high":      np.float64,
                            "low":       np.float64,
                            "close":     np.float64,
                            "volume":    np.float64,
                        }
                    )
            # Binance timestamps are milliseconds; some older files use microseconds
            sample  = df["open_time"].iloc[0]
            divisor = 1_000_000 if sample > 2e12 else 1_000
            df["open_time_s"] = (df["open_time"] // divisor).astype(np.int64)
            return df[["open_time_s", "open", "high", "low", "close", "volume"]]
        except Exception as e:
            if attempt == retries - 1:
                print(f"    ERROR downloading {symbol} {date}: {e}")
                return None
            time.sleep(3)


def update_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> int:
    """
    Update one asset's combined Parquet with any missing days.
    Returns number of new rows appended (0 if already up to date or dry-run).
    """
    hf_path = f"data/{symbol}_1s.parquet"
    print(f"\n  {'─'*50}")
    print(f"  {symbol}")

    # ── 1. Fetch existing combined Parquet ────────────────────────────────────
    print(f"  Fetching existing parquet from HF...", flush=True)
    try:
        local_existing = hf_hub_download(
            repo_id=REPO_ID,
            filename=hf_path,
            repo_type="dataset",
            token=HF_TOKEN,
            force_download=True,   # always get freshest version
        )
        existing = pd.read_parquet(local_existing, engine="pyarrow")
    except Exception as e:
        print(f"  Could not fetch existing file: {e}")
        print(f"  Has the combined file been created yet? Run merge_yearly.py first.")
        return 0

    latest_ts   = int(existing["open_time_s"].max())
    latest_date = datetime.date.fromtimestamp(latest_ts)
    print(f"  Existing rows: {len(existing):,}  |  latest: {latest_date}")

    # ── 2. Determine which dates are missing ──────────────────────────────────
    # Binance publishes the previous day's data with ~1-2 hour delay UTC
    yesterday     = datetime.date.today() - datetime.timedelta(days=1)
    missing_dates = []
    d = latest_date + datetime.timedelta(days=1)
    while d <= yesterday:
        missing_dates.append(d)
        d += datetime.timedelta(days=1)

    if not missing_dates:
        print(f"  Already up to date through {latest_date}. Nothing to do.")
        return 0

    print(f"  Missing {len(missing_dates)} day(s): {missing_dates[0]}{missing_dates[-1]}")

    if dry_run:
        print(f"  [dry-run] Would download {len(missing_dates)} day(s) and append them.")
        return 0

    # ── 3. Download missing daily files ───────────────────────────────────────
    new_frames = []
    for date in missing_dates:
        print(f"    Fetching {date}...", flush=True)
        df = download_daily(symbol, date)
        if df is not None:
            print(f"      {len(df):,} rows")
            new_frames.append(df)
        else:
            print(f"      Not available yet — skipping.")

    if not new_frames:
        print(f"  No new data available for download.")
        return 0

    # ── 4. Merge and deduplicate ──────────────────────────────────────────────
    n_new    = sum(len(f) for f in new_frames)
    new_data = pd.concat(new_frames, ignore_index=True)
    del new_frames; gc.collect()

    combined = pd.concat([existing, new_data], ignore_index=True)
    del existing, new_data; gc.collect()

    combined = (
        combined
        .sort_values("open_time_s")
        .drop_duplicates("open_time_s")
        .reset_index(drop=True)
    )
    latest_after = datetime.date.fromtimestamp(int(combined["open_time_s"].max()))

    # ── 5. Write and upload ───────────────────────────────────────────────────
    local_out = Path(f"/tmp/{symbol}_1s_updated.parquet")
    table     = pa.Table.from_pandas(combined, schema=PA_SCHEMA, preserve_index=False)
    del combined; gc.collect()
    pq.write_table(table, local_out, compression="snappy")
    file_mb = local_out.stat().st_size / 1e6

    print(f"  Uploading {file_mb:.0f} MB (+{n_new:,} new rows, now through {latest_after})...",
          flush=True)
    api.upload_file(
        path_or_fileobj=str(local_out),
        path_in_repo=hf_path,
        repo_id=REPO_ID,
        repo_type="dataset",
        commit_message=f"Daily update {symbol}: +{n_new:,} rows through {latest_after}",
    )
    local_out.unlink(missing_ok=True)
    print(f"  Done: +{n_new:,} rows → data is current through {latest_after}")
    return n_new


def main():
    parser = argparse.ArgumentParser(description="Daily updater for 1s crypto dataset")
    parser.add_argument("--dry-run", action="store_true",
                        help="Show what would be downloaded without uploading")
    parser.add_argument("--symbols", nargs="+", default=SYMBOLS,
                        help="Only update these symbols (default: all)")
    args = parser.parse_args()

    if not HF_TOKEN and not args.dry_run:
        print("ERROR: HF_TOKEN environment variable not set")
        sys.exit(1)

    api = HfApi(token=HF_TOKEN)

    print(f"{'='*55}")
    print(f"  1s Crypto Dataset — Daily Updater")
    print(f"  {datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}")
    if args.dry_run:
        print("  Mode: DRY RUN")
    print(f"{'='*55}")

    total_new = 0
    for symbol in args.symbols:
        try:
            n = update_symbol(symbol, api, dry_run=args.dry_run)
            total_new += n
        except Exception as e:
            print(f"  FATAL ERROR updating {symbol}: {e}")

    print(f"\n{'='*55}")
    print(f"  Update complete — {total_new:,} total new rows added")
    print(f"{'='*55}")


if __name__ == "__main__":
    main()