Fix daily_update.py: complete rewrite with full update_symbol logic (DOGEUSDT, XRPUSDT, SOLUSDT + others)
Browse files1234567891011121314151617181918 unmodified lines383940414243446 unmodified lines51525354555657585960616263643 unmodified lines686970717273747576777879808 unmodified lines89909192939495969798991001011 unmodified line1031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841855 unmodified lines1911921931941951962 unmodified lines199200201202203204205#!/usr/bin/env python3"""Daily updater for commanderzee/1s-crypto-data==============================================Checks the latest timestamp in each asset's combined Parquet,downloads any missing daily 1s files from Binance Vision, andappends them to the HuggingFace dataset.Run this script daily (e.g. via a cron job, Replit workflow, or HF Space).Binance daily endpoint:https://data.binance.vision/data/spot/daily/klines/{SYMBOL}/1s/{SYMBOL}-1s-YYYY-MM-DD.zipUsage:HF_TOKEN=<your_token> python daily_update.pypython daily_update.py --dry-run # show what would be downloaded, no upload"""import argparse18 unmodified linesHF_TOKEN = os.environ.get("HF_TOKEN", "")BINANCE_DAILY = "https://data.binance.vision/data/spot/daily/klines"SYMBOLS = ["BTCUSDT", "ETHUSDT", "BNBUSDT", "XRPUSDT", "DOGEUSDT", "SOLUSDT"]PA_SCHEMA = pa.schema([("open_time_s", pa.int64()),6 unmodified linesdef download_daily(symbol: str, date: datetime.date, retries: int = 3):"""Download one day of 1s 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 yetr.raise_for_status()with zipfile.ZipFile(io.BytesIO(r.content)) as z:with z.open(z.namelist()[0]) as f:3 unmodified linesnames=["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,})sample = df["open_time"].iloc[0]divisor = 1_000_000 if sample > 2e12 else 1_000df["open_time_s"] = (df["open_time"] // divisor).astype(np.int64)8 unmodified linesdef 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."""hf_path = f"data/{symbol}_1s.parquet"print(f"\n {'─'*50}")print(f" {symbol}")# Download existing combined Parquet from HFprint(f" Fetching existing parquet from HF...", flush=True)try:local_existing = hf_hub_download(1 unmodified linefilename=hf_path,repo_type="dataset",token=HF_TOKEN,force_download=True, # always get freshest version)existing = pd.read_parquet(local_existing)except Exception as e:print(f" Could not fetch existing file: {e}")return 0latest_ts = existing["open_time_s"].max()latest_dt = datetime.datetime.utcfromtimestamp(latest_ts).date()print(f" Latest data: {latest_dt} ({len(existing):,} rows)")# Determine missing days: day after latest through yesterday UTCyesterday = datetime.datetime.utcnow().date() - datetime.timedelta(days=1)missing = [latest_dt + datetime.timedelta(days=d)for d in range(1, (yesterday - latest_dt).days + 1)]if not missing:print(f" Already up to date (latest={latest_dt}, yesterday={yesterday})")return 0print(f" Missing {len(missing)} day(s): {missing[0]} → {missing[-1]}")if dry_run:print(f" [DRY RUN] would download {len(missing)} days — no upload")return 0# Download missing daysnew_frames = []for d in missing:df = download_daily(symbol, d)if df is None:print(f" {d}: not yet available — stopping here")breaknew_frames.append(df)print(f" {d}: {len(df):,} rows downloaded", flush=True)if not new_frames:print(f" No new data available")return 0new_data = pd.concat(new_frames, ignore_index=True)n_new = len(new_data)combined = (pd.concat([existing, new_data], ignore_index=True).drop_duplicates("open_time_s").sort_values("open_time_s").reset_index(drop=True))del existing, new_data, new_frames; gc.collect()latest_after = datetime.datetime.utcfromtimestamp(combined["open_time_s"].max()).date()# Write and uploadlocal_out = Path(f"/tmp/{symbol}_1s_updated.parquet")table = pa.Table.from_pandas(combined, schema=PA_SCHEMA, preserve_index=False)pq.write_table(table, local_out, compression="snappy")file_mb = local_out.stat().st_size / 1e6del combined, table; gc.collect()print(f" Uploading {file_mb:.0f} MB ({n_new:+,} new rows, now up to {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}: add {n_new:,} rows through {latest_after}",)local_out.unlink()print(f" Done: +{n_new:,} rows → {latest_after}")return n_newdef 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 6)")args = parser.parse_args()if not HF_TOKEN and not args.dry_run:5 unmodified linesprint(f"{'='*55}")print(f" 1s Crypto Dataset — Daily Updater")print(f" {datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}")print(f"{'='*55}")total_new = 02 unmodified linesn = update_symbol(symbol, api, dry_run=args.dry_run)total_new += nexcept Exception as e:print(f" ERROR updating {symbol}: {e}")print(f"\n{'='*55}")print(f" Update complete — {total_new:,} total new rows added")1234567891011121314151617181918 unmodified lines383940414243446 unmodified lines51525354555657585960616263643 unmodified lines68697071727374757677787980818 unmodified lines909192939495969798991001011021 unmodified line1041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971985 unmodified lines2042052062072082092102112 unmodified lines214215216217218219220#!/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.zipUsage:HF_TOKEN=<token> python scripts/daily_update.pypython scripts/daily_update.py --dry-run # show what would be fetched, no uploadpython scripts/daily_update.py --symbols DOGEUSDT # update one symbol only"""import argparse18 unmodified linesHF_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()),6 unmodified linesdef 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 yetr.raise_for_status()with zipfile.ZipFile(io.BytesIO(r.content)) as z:with z.open(z.namelist()[0]) as f:3 unmodified linesnames=["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 microsecondssample = df["open_time"].iloc[0]divisor = 1_000_000 if sample > 2e12 else 1_000df["open_time_s"] = (df["open_time"] // divisor).astype(np.int64)8 unmodified linesdef 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(1 unmodified linefilename=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 0latest_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 UTCyesterday = 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 0print(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 / 1e6print(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_newdef 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:5 unmodified linesprint(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 = 02 unmodified linesn = update_symbol(symbol, api, dry_run=args.dry_run)total_new += nexcept Exception as e:print(f" FATAL ERROR updating {symbol}: {e}")print(f"\n{'='*55}")print(f" Update complete — {total_new:,} total new rows added")
scripts/daily_update.py+77-62