#!/usr/bin/env python3 """ merge_yearly.py =============== Combines each asset's per-year Parquet files on HuggingFace into one big combined Parquet per asset, then uploads it back to the dataset repo. Memory-efficient: streams one year at a time using ParquetWriter, never holds more than one year in RAM. Assets handled: DOGEUSDT, XRPUSDT, SOLUSDT (BTCUSDT / ETHUSDT / BNBUSDT already have combined files) HF layout: source: data/{SYMBOL}/{SYMBOL}_{YEAR}.parquet output: data/{SYMBOL}_1s.parquet Usage: HF_TOKEN= python scripts/merge_yearly.py python scripts/merge_yearly.py --dry-run # no upload, just prints stats """ import argparse import gc import os import sys from pathlib import Path import pandas as pd import pyarrow as pa import pyarrow.parquet as pq from huggingface_hub import HfApi, hf_hub_download, list_repo_files REPO_ID = "commanderzee/1s-crypto-data" HF_TOKEN = os.environ.get("HF_TOKEN", "") SYMBOLS = ["DOGEUSDT", "XRPUSDT", "SOLUSDT"] PA_SCHEMA = pa.schema([ ("open_time_s", pa.int64()), ("open", pa.float64()), ("high", pa.float64()), ("low", pa.float64()), ("close", pa.float64()), ("volume", pa.float64()), ]) # Write in chunks so we never have more than ~50M rows in RAM at once CHUNK_ROWS = 10_000_000 def yearly_files_for(symbol: str) -> list[str]: """Return sorted list of HF repo paths for a symbol's yearly parquets.""" all_files = list(list_repo_files(REPO_ID, repo_type="dataset", token=HF_TOKEN)) prefix = f"data/{symbol}/{symbol}_" return sorted(f for f in all_files if f.startswith(prefix) and f.endswith(".parquet")) def merge_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> None: hf_out_path = f"data/{symbol}_1s.parquet" local_out = Path(f"/tmp/{symbol}_1s.parquet") print(f"\n{'─'*55}") print(f" {symbol}") yearly = yearly_files_for(symbol) if not yearly: print(f" No yearly files found — skipping.") return print(f" Found {len(yearly)} yearly file(s):") for yf in yearly: print(f" {yf}") if dry_run: print(" [dry-run] skipping download and upload.") return total_rows = 0 writer = None try: for yf in yearly: year = yf.split("_")[-1].replace(".parquet", "") print(f" Downloading {year}...", flush=True) local = hf_hub_download( repo_id=REPO_ID, filename=yf, repo_type="dataset", token=HF_TOKEN, ) # Read and write in chunks to keep memory low pf = pq.ParquetFile(local) year_rows = 0 for batch in pf.iter_batches(batch_size=CHUNK_ROWS, schema=PA_SCHEMA): if writer is None: writer = pq.ParquetWriter(str(local_out), PA_SCHEMA, compression="snappy") writer.write_batch(batch) year_rows += batch.num_rows total_rows += year_rows print(f" {year_rows:>12,} rows written (running total: {total_rows:,})") del pf; gc.collect() finally: if writer: writer.close() file_mb = local_out.stat().st_size / 1e6 print(f" Total rows: {total_rows:,}") print(f" File size: {file_mb:.1f} MB") print(f" Uploading to {hf_out_path}...", flush=True) api.upload_file( path_or_fileobj=str(local_out), path_in_repo=hf_out_path, repo_id=REPO_ID, repo_type="dataset", commit_message=f"Merge yearly files → {symbol}_1s.parquet ({total_rows:,} rows, {file_mb:.0f} MB)", ) local_out.unlink(missing_ok=True) print(f" Done — uploaded {hf_out_path}") def main(): parser = argparse.ArgumentParser(description="Merge yearly Parquet files per asset") parser.add_argument("--dry-run", action="store_true", help="Print stats but skip downloading and uploading") parser.add_argument("--symbols", nargs="+", default=SYMBOLS, help="Override which symbols to process") args = parser.parse_args() if not HF_TOKEN: print("ERROR: HF_TOKEN environment variable not set") sys.exit(1) api = HfApi(token=HF_TOKEN) print(f"{'='*55}") print(" merge_yearly.py — Combine yearly Parquets") print(f" Symbols: {', '.join(args.symbols)}") if args.dry_run: print(" Mode: DRY RUN") print(f"{'='*55}") for symbol in args.symbols: try: merge_symbol(symbol, api, dry_run=args.dry_run) except Exception as e: print(f" ERROR processing {symbol}: {e}") raise print(f"\n{'='*55}") print(" Merge complete.") print(f"{'='*55}") if __name__ == "__main__": main()