#!/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= 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()