File size: 4,852 Bytes
93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb 937bfd5 93f4fdb | 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 | #!/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=<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()
|