Fix merge_yearly.py: stream one year at a time to avoid OOM
Browse files- scripts/merge_yearly.py +47 -45
scripts/merge_yearly.py
CHANGED
|
@@ -5,12 +5,15 @@ merge_yearly.py
|
|
| 5 |
Combines each asset's per-year Parquet files on HuggingFace into one
|
| 6 |
big combined Parquet per asset, then uploads it back to the dataset repo.
|
| 7 |
|
|
|
|
|
|
|
|
|
|
| 8 |
Assets handled: DOGEUSDT, XRPUSDT, SOLUSDT
|
| 9 |
(BTCUSDT / ETHUSDT / BNBUSDT already have combined files)
|
| 10 |
|
| 11 |
-
HF layout
|
| 12 |
-
data/{SYMBOL}/{SYMBOL}_{YEAR}.parquet
|
| 13 |
-
data/{SYMBOL}_1s.parquet
|
| 14 |
|
| 15 |
Usage:
|
| 16 |
HF_TOKEN=<token> python scripts/merge_yearly.py
|
|
@@ -42,6 +45,9 @@ PA_SCHEMA = pa.schema([
|
|
| 42 |
("volume", pa.float64()),
|
| 43 |
])
|
| 44 |
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
def yearly_files_for(symbol: str) -> list[str]:
|
| 47 |
"""Return sorted list of HF repo paths for a symbol's yearly parquets."""
|
|
@@ -52,6 +58,7 @@ def yearly_files_for(symbol: str) -> list[str]:
|
|
| 52 |
|
| 53 |
def merge_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> None:
|
| 54 |
hf_out_path = f"data/{symbol}_1s.parquet"
|
|
|
|
| 55 |
print(f"\n{'─'*55}")
|
| 56 |
print(f" {symbol}")
|
| 57 |
|
|
@@ -64,49 +71,44 @@ def merge_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> None:
|
|
| 64 |
for yf in yearly:
|
| 65 |
print(f" {yf}")
|
| 66 |
|
| 67 |
-
frames = []
|
| 68 |
-
for yf in yearly:
|
| 69 |
-
year = yf.split("_")[-1].replace(".parquet", "")
|
| 70 |
-
print(f" Downloading {year}...", flush=True)
|
| 71 |
-
local = hf_hub_download(
|
| 72 |
-
repo_id=REPO_ID,
|
| 73 |
-
filename=yf,
|
| 74 |
-
repo_type="dataset",
|
| 75 |
-
token=HF_TOKEN,
|
| 76 |
-
)
|
| 77 |
-
df = pd.read_parquet(local, engine="pyarrow")
|
| 78 |
-
print(f" {len(df):>12,} rows ({df['open_time_s'].min()} → {df['open_time_s'].max()})")
|
| 79 |
-
frames.append(df)
|
| 80 |
-
|
| 81 |
-
print(" Concatenating...", flush=True)
|
| 82 |
-
combined = pd.concat(frames, ignore_index=True)
|
| 83 |
-
del frames; gc.collect()
|
| 84 |
-
|
| 85 |
-
before = len(combined)
|
| 86 |
-
combined = (
|
| 87 |
-
combined
|
| 88 |
-
.sort_values("open_time_s")
|
| 89 |
-
.drop_duplicates("open_time_s")
|
| 90 |
-
.reset_index(drop=True)
|
| 91 |
-
)
|
| 92 |
-
after = len(combined)
|
| 93 |
-
if before != after:
|
| 94 |
-
print(f" Dropped {before - after:,} duplicate rows.")
|
| 95 |
-
|
| 96 |
-
print(f" Total rows: {len(combined):,}")
|
| 97 |
-
print(f" Date range: {combined['open_time_s'].min()} → {combined['open_time_s'].max()}")
|
| 98 |
-
|
| 99 |
if dry_run:
|
| 100 |
-
print(" [dry-run] skipping upload.")
|
| 101 |
return
|
| 102 |
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
file_mb = local_out.stat().st_size / 1e6
|
| 109 |
-
print(f"
|
|
|
|
| 110 |
|
| 111 |
print(f" Uploading to {hf_out_path}...", flush=True)
|
| 112 |
api.upload_file(
|
|
@@ -114,7 +116,7 @@ def merge_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> None:
|
|
| 114 |
path_in_repo=hf_out_path,
|
| 115 |
repo_id=REPO_ID,
|
| 116 |
repo_type="dataset",
|
| 117 |
-
commit_message=f"Merge yearly files → {symbol}_1s.parquet ({file_mb:.0f} MB)",
|
| 118 |
)
|
| 119 |
local_out.unlink(missing_ok=True)
|
| 120 |
print(f" Done — uploaded {hf_out_path}")
|
|
@@ -123,7 +125,7 @@ def merge_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> None:
|
|
| 123 |
def main():
|
| 124 |
parser = argparse.ArgumentParser(description="Merge yearly Parquet files per asset")
|
| 125 |
parser.add_argument("--dry-run", action="store_true",
|
| 126 |
-
help="Print stats but skip uploading")
|
| 127 |
parser.add_argument("--symbols", nargs="+", default=SYMBOLS,
|
| 128 |
help="Override which symbols to process")
|
| 129 |
args = parser.parse_args()
|
|
@@ -138,7 +140,7 @@ def main():
|
|
| 138 |
print(" merge_yearly.py — Combine yearly Parquets")
|
| 139 |
print(f" Symbols: {', '.join(args.symbols)}")
|
| 140 |
if args.dry_run:
|
| 141 |
-
print(" Mode: DRY RUN
|
| 142 |
print(f"{'='*55}")
|
| 143 |
|
| 144 |
for symbol in args.symbols:
|
|
|
|
| 5 |
Combines each asset's per-year Parquet files on HuggingFace into one
|
| 6 |
big combined Parquet per asset, then uploads it back to the dataset repo.
|
| 7 |
|
| 8 |
+
Memory-efficient: streams one year at a time using ParquetWriter,
|
| 9 |
+
never holds more than one year in RAM.
|
| 10 |
+
|
| 11 |
Assets handled: DOGEUSDT, XRPUSDT, SOLUSDT
|
| 12 |
(BTCUSDT / ETHUSDT / BNBUSDT already have combined files)
|
| 13 |
|
| 14 |
+
HF layout:
|
| 15 |
+
source: data/{SYMBOL}/{SYMBOL}_{YEAR}.parquet
|
| 16 |
+
output: data/{SYMBOL}_1s.parquet
|
| 17 |
|
| 18 |
Usage:
|
| 19 |
HF_TOKEN=<token> python scripts/merge_yearly.py
|
|
|
|
| 45 |
("volume", pa.float64()),
|
| 46 |
])
|
| 47 |
|
| 48 |
+
# Write in chunks so we never have more than ~50M rows in RAM at once
|
| 49 |
+
CHUNK_ROWS = 10_000_000
|
| 50 |
+
|
| 51 |
|
| 52 |
def yearly_files_for(symbol: str) -> list[str]:
|
| 53 |
"""Return sorted list of HF repo paths for a symbol's yearly parquets."""
|
|
|
|
| 58 |
|
| 59 |
def merge_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> None:
|
| 60 |
hf_out_path = f"data/{symbol}_1s.parquet"
|
| 61 |
+
local_out = Path(f"/tmp/{symbol}_1s.parquet")
|
| 62 |
print(f"\n{'─'*55}")
|
| 63 |
print(f" {symbol}")
|
| 64 |
|
|
|
|
| 71 |
for yf in yearly:
|
| 72 |
print(f" {yf}")
|
| 73 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
if dry_run:
|
| 75 |
+
print(" [dry-run] skipping download and upload.")
|
| 76 |
return
|
| 77 |
|
| 78 |
+
total_rows = 0
|
| 79 |
+
writer = None
|
| 80 |
+
|
| 81 |
+
try:
|
| 82 |
+
for yf in yearly:
|
| 83 |
+
year = yf.split("_")[-1].replace(".parquet", "")
|
| 84 |
+
print(f" Downloading {year}...", flush=True)
|
| 85 |
+
local = hf_hub_download(
|
| 86 |
+
repo_id=REPO_ID,
|
| 87 |
+
filename=yf,
|
| 88 |
+
repo_type="dataset",
|
| 89 |
+
token=HF_TOKEN,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
# Read and write in chunks to keep memory low
|
| 93 |
+
pf = pq.ParquetFile(local)
|
| 94 |
+
year_rows = 0
|
| 95 |
+
for batch in pf.iter_batches(batch_size=CHUNK_ROWS, schema=PA_SCHEMA):
|
| 96 |
+
if writer is None:
|
| 97 |
+
writer = pq.ParquetWriter(str(local_out), PA_SCHEMA, compression="snappy")
|
| 98 |
+
writer.write_batch(batch)
|
| 99 |
+
year_rows += batch.num_rows
|
| 100 |
+
|
| 101 |
+
total_rows += year_rows
|
| 102 |
+
print(f" {year_rows:>12,} rows written (running total: {total_rows:,})")
|
| 103 |
+
del pf; gc.collect()
|
| 104 |
+
|
| 105 |
+
finally:
|
| 106 |
+
if writer:
|
| 107 |
+
writer.close()
|
| 108 |
+
|
| 109 |
file_mb = local_out.stat().st_size / 1e6
|
| 110 |
+
print(f" Total rows: {total_rows:,}")
|
| 111 |
+
print(f" File size: {file_mb:.1f} MB")
|
| 112 |
|
| 113 |
print(f" Uploading to {hf_out_path}...", flush=True)
|
| 114 |
api.upload_file(
|
|
|
|
| 116 |
path_in_repo=hf_out_path,
|
| 117 |
repo_id=REPO_ID,
|
| 118 |
repo_type="dataset",
|
| 119 |
+
commit_message=f"Merge yearly files → {symbol}_1s.parquet ({total_rows:,} rows, {file_mb:.0f} MB)",
|
| 120 |
)
|
| 121 |
local_out.unlink(missing_ok=True)
|
| 122 |
print(f" Done — uploaded {hf_out_path}")
|
|
|
|
| 125 |
def main():
|
| 126 |
parser = argparse.ArgumentParser(description="Merge yearly Parquet files per asset")
|
| 127 |
parser.add_argument("--dry-run", action="store_true",
|
| 128 |
+
help="Print stats but skip downloading and uploading")
|
| 129 |
parser.add_argument("--symbols", nargs="+", default=SYMBOLS,
|
| 130 |
help="Override which symbols to process")
|
| 131 |
args = parser.parse_args()
|
|
|
|
| 140 |
print(" merge_yearly.py — Combine yearly Parquets")
|
| 141 |
print(f" Symbols: {', '.join(args.symbols)}")
|
| 142 |
if args.dry_run:
|
| 143 |
+
print(" Mode: DRY RUN")
|
| 144 |
print(f"{'='*55}")
|
| 145 |
|
| 146 |
for symbol in args.symbols:
|