Add merge_yearly.py: combine yearly parquets into one file per asset
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157#!/usr/bin/env python3"""merge_yearly.py===============Combines each asset's per-year Parquet files on HuggingFace into onebig combined Parquet per asset, then uploads it back to the dataset repo.
Assets handled: DOGEUSDT, XRPUSDT, SOLUSDT(BTCUSDT / ETHUSDT / BNBUSDT already have combined files)
HF layout assumed: data/{SYMBOL}/{SYMBOL}_{YEAR}.parquet (source yearly files) data/{SYMBOL}_1s.parquet (output combined file)
Usage: HF_TOKEN=<token> python scripts/merge_yearly.py python scripts/merge_yearly.py --dry-run # no upload, just prints stats"""
import argparseimport gcimport osimport sysfrom pathlib import Path
import pandas as pdimport pyarrow as paimport pyarrow.parquet as pqfrom 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()),])
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" 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}")
frames = [] 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, ) df = pd.read_parquet(local, engine="pyarrow") print(f" {len(df):>12,} rows ({df['open_time_s'].min()} → {df['open_time_s'].max()})") frames.append(df)
print(" Concatenating...", flush=True) combined = pd.concat(frames, ignore_index=True) del frames; gc.collect()
before = len(combined) combined = ( combined .sort_values("open_time_s") .drop_duplicates("open_time_s") .reset_index(drop=True) ) after = len(combined) if before != after: print(f" Dropped {before - after:,} duplicate rows.")
print(f" Total rows: {len(combined):,}") print(f" Date range: {combined['open_time_s'].min()} → {combined['open_time_s'].max()}")
if dry_run: print(" [dry-run] skipping upload.") return
local_out = Path(f"/tmp/{symbol}_1s.parquet") print(f" Writing parquet...", flush=True) 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" 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 ({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 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 (no uploads)") 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()scripts/merge_yearly.pyAdded+157