commanderzee commited on
Commit
93f4fdb
·
verified ·
1 Parent(s): 320ff09

Add merge_yearly.py: combine yearly parquets into one file per asset

Browse files
Files changed (1) hide show
  1. scripts/merge_yearly.py +157 -0
scripts/merge_yearly.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ merge_yearly.py
4
+ ===============
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 assumed:
12
+ data/{SYMBOL}/{SYMBOL}_{YEAR}.parquet (source yearly files)
13
+ data/{SYMBOL}_1s.parquet (output combined file)
14
+
15
+ Usage:
16
+ HF_TOKEN=<token> python scripts/merge_yearly.py
17
+ python scripts/merge_yearly.py --dry-run # no upload, just prints stats
18
+ """
19
+
20
+ import argparse
21
+ import gc
22
+ import os
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ import pandas as pd
27
+ import pyarrow as pa
28
+ import pyarrow.parquet as pq
29
+ from huggingface_hub import HfApi, hf_hub_download, list_repo_files
30
+
31
+ REPO_ID = "commanderzee/1s-crypto-data"
32
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
33
+
34
+ SYMBOLS = ["DOGEUSDT", "XRPUSDT", "SOLUSDT"]
35
+
36
+ PA_SCHEMA = pa.schema([
37
+ ("open_time_s", pa.int64()),
38
+ ("open", pa.float64()),
39
+ ("high", pa.float64()),
40
+ ("low", pa.float64()),
41
+ ("close", pa.float64()),
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."""
48
+ all_files = list(list_repo_files(REPO_ID, repo_type="dataset", token=HF_TOKEN))
49
+ prefix = f"data/{symbol}/{symbol}_"
50
+ return sorted(f for f in all_files if f.startswith(prefix) and f.endswith(".parquet"))
51
+
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
+
58
+ yearly = yearly_files_for(symbol)
59
+ if not yearly:
60
+ print(f" No yearly files found — skipping.")
61
+ return
62
+
63
+ print(f" Found {len(yearly)} yearly file(s):")
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
+ local_out = Path(f"/tmp/{symbol}_1s.parquet")
104
+ print(f" Writing parquet...", flush=True)
105
+ table = pa.Table.from_pandas(combined, schema=PA_SCHEMA, preserve_index=False)
106
+ del combined; gc.collect()
107
+ pq.write_table(table, local_out, compression="snappy")
108
+ file_mb = local_out.stat().st_size / 1e6
109
+ print(f" File size: {file_mb:.1f} MB")
110
+
111
+ print(f" Uploading to {hf_out_path}...", flush=True)
112
+ api.upload_file(
113
+ path_or_fileobj=str(local_out),
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}")
121
+
122
+
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()
130
+
131
+ if not HF_TOKEN:
132
+ print("ERROR: HF_TOKEN environment variable not set")
133
+ sys.exit(1)
134
+
135
+ api = HfApi(token=HF_TOKEN)
136
+
137
+ print(f"{'='*55}")
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 (no uploads)")
142
+ print(f"{'='*55}")
143
+
144
+ for symbol in args.symbols:
145
+ try:
146
+ merge_symbol(symbol, api, dry_run=args.dry_run)
147
+ except Exception as e:
148
+ print(f" ERROR processing {symbol}: {e}")
149
+ raise
150
+
151
+ print(f"\n{'='*55}")
152
+ print(" Merge complete.")
153
+ print(f"{'='*55}")
154
+
155
+
156
+ if __name__ == "__main__":
157
+ main()