commanderzee commited on
Commit
c976a58
·
verified ·
1 Parent(s): 77434ce

Add daily updater script

Browse files
Files changed (1) hide show
  1. scripts/daily_update.py +210 -0
scripts/daily_update.py ADDED
@@ -0,0 +1,210 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Daily updater for commanderzee/1s-crypto-data
4
+ ==============================================
5
+ Checks the latest timestamp in each asset's combined Parquet,
6
+ downloads any missing daily 1s files from Binance Vision, and
7
+ appends them to the HuggingFace dataset.
8
+
9
+ Run this script daily (e.g. via a cron job, Replit workflow, or HF Space).
10
+
11
+ Binance daily endpoint:
12
+ https://data.binance.vision/data/spot/daily/klines/{SYMBOL}/1s/{SYMBOL}-1s-YYYY-MM-DD.zip
13
+
14
+ Usage:
15
+ HF_TOKEN=<your_token> python daily_update.py
16
+ python daily_update.py --dry-run # show what would be downloaded, no upload
17
+ """
18
+
19
+ import argparse
20
+ import datetime
21
+ import gc
22
+ import io
23
+ import os
24
+ import sys
25
+ import time
26
+ import zipfile
27
+ from pathlib import Path
28
+
29
+ import numpy as np
30
+ import pandas as pd
31
+ import pyarrow as pa
32
+ import pyarrow.parquet as pq
33
+ import requests
34
+ from huggingface_hub import HfApi, hf_hub_download
35
+
36
+ # ── Config ────────────────────────────────────────────────────────────────────
37
+ REPO_ID = "commanderzee/1s-crypto-data"
38
+ HF_TOKEN = os.environ.get("HF_TOKEN", "")
39
+ BINANCE_DAILY = "https://data.binance.vision/data/spot/daily/klines"
40
+
41
+ SYMBOLS = ["BTCUSDT", "ETHUSDT", "BNBUSDT", "XRPUSDT", "DOGEUSDT", "SOLUSDT"]
42
+
43
+ PA_SCHEMA = pa.schema([
44
+ ("open_time_s", pa.int64()),
45
+ ("open", pa.float64()),
46
+ ("high", pa.float64()),
47
+ ("low", pa.float64()),
48
+ ("close", pa.float64()),
49
+ ("volume", pa.float64()),
50
+ ])
51
+
52
+
53
+ def download_daily(symbol: str, date: datetime.date, retries: int = 3):
54
+ """Download one day of 1s data from Binance Vision. Returns DataFrame or None."""
55
+ fname = f"{symbol}-1s-{date:%Y-%m-%d}.zip"
56
+ url = f"{BINANCE_DAILY}/{symbol}/1s/{fname}"
57
+ for attempt in range(retries):
58
+ try:
59
+ r = requests.get(url, timeout=120)
60
+ if r.status_code == 404:
61
+ return None # day not published yet
62
+ r.raise_for_status()
63
+ with zipfile.ZipFile(io.BytesIO(r.content)) as z:
64
+ with z.open(z.namelist()[0]) as f:
65
+ df = pd.read_csv(
66
+ f, header=None,
67
+ usecols=[0, 1, 2, 3, 4, 5],
68
+ names=["open_time", "open", "high", "low", "close", "volume"],
69
+ dtype={
70
+ "open_time": np.int64,
71
+ "open": np.float64,
72
+ "high": np.float64,
73
+ "low": np.float64,
74
+ "close": np.float64,
75
+ "volume": np.float64,
76
+ }
77
+ )
78
+ sample = df["open_time"].iloc[0]
79
+ divisor = 1_000_000 if sample > 2e12 else 1_000
80
+ df["open_time_s"] = (df["open_time"] // divisor).astype(np.int64)
81
+ return df[["open_time_s", "open", "high", "low", "close", "volume"]]
82
+ except Exception as e:
83
+ if attempt == retries - 1:
84
+ print(f" ERROR downloading {symbol} {date}: {e}")
85
+ return None
86
+ time.sleep(3)
87
+
88
+
89
+ def update_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> int:
90
+ """
91
+ Update one asset's combined Parquet with any missing days.
92
+ Returns number of new rows appended.
93
+ """
94
+ hf_path = f"data/{symbol}_1s.parquet"
95
+ print(f"\n {'─'*50}")
96
+ print(f" {symbol}")
97
+
98
+ # Download existing combined Parquet from HF
99
+ print(f" Fetching existing parquet from HF...", flush=True)
100
+ try:
101
+ local_existing = hf_hub_download(
102
+ repo_id=REPO_ID,
103
+ filename=hf_path,
104
+ repo_type="dataset",
105
+ token=HF_TOKEN,
106
+ force_download=True, # always get freshest version
107
+ )
108
+ existing = pd.read_parquet(local_existing)
109
+ except Exception as e:
110
+ print(f" Could not fetch existing file: {e}")
111
+ return 0
112
+
113
+ latest_ts = existing["open_time_s"].max()
114
+ latest_dt = datetime.datetime.utcfromtimestamp(latest_ts).date()
115
+ print(f" Latest data: {latest_dt} ({len(existing):,} rows)")
116
+
117
+ # Determine missing days: day after latest through yesterday UTC
118
+ yesterday = datetime.datetime.utcnow().date() - datetime.timedelta(days=1)
119
+ missing = [latest_dt + datetime.timedelta(days=d)
120
+ for d in range(1, (yesterday - latest_dt).days + 1)]
121
+
122
+ if not missing:
123
+ print(f" Already up to date (latest={latest_dt}, yesterday={yesterday})")
124
+ return 0
125
+
126
+ print(f" Missing {len(missing)} day(s): {missing[0]} → {missing[-1]}")
127
+ if dry_run:
128
+ print(f" [DRY RUN] would download {len(missing)} days — no upload")
129
+ return 0
130
+
131
+ # Download missing days
132
+ new_frames = []
133
+ for d in missing:
134
+ df = download_daily(symbol, d)
135
+ if df is None:
136
+ print(f" {d}: not yet available — stopping here")
137
+ break
138
+ new_frames.append(df)
139
+ print(f" {d}: {len(df):,} rows downloaded", flush=True)
140
+
141
+ if not new_frames:
142
+ print(f" No new data available")
143
+ return 0
144
+
145
+ new_data = pd.concat(new_frames, ignore_index=True)
146
+ n_new = len(new_data)
147
+ combined = (pd.concat([existing, new_data], ignore_index=True)
148
+ .drop_duplicates("open_time_s")
149
+ .sort_values("open_time_s")
150
+ .reset_index(drop=True))
151
+ del existing, new_data, new_frames; gc.collect()
152
+
153
+ latest_after = datetime.datetime.utcfromtimestamp(
154
+ combined["open_time_s"].max()).date()
155
+
156
+ # Write and upload
157
+ local_out = Path(f"/tmp/{symbol}_1s_updated.parquet")
158
+ table = pa.Table.from_pandas(combined, schema=PA_SCHEMA, preserve_index=False)
159
+ pq.write_table(table, local_out, compression="snappy")
160
+ file_mb = local_out.stat().st_size / 1e6
161
+ del combined, table; gc.collect()
162
+
163
+ print(f" Uploading {file_mb:.0f} MB ({n_new:+,} new rows, now up to {latest_after})...",
164
+ flush=True)
165
+ api.upload_file(
166
+ path_or_fileobj=str(local_out),
167
+ path_in_repo=hf_path,
168
+ repo_id=REPO_ID,
169
+ repo_type="dataset",
170
+ commit_message=f"Daily update {symbol}: add {n_new:,} rows through {latest_after}",
171
+ )
172
+ local_out.unlink()
173
+ print(f" Done: +{n_new:,} rows → {latest_after}")
174
+ return n_new
175
+
176
+
177
+ def main():
178
+ parser = argparse.ArgumentParser(description="Daily updater for 1s crypto dataset")
179
+ parser.add_argument("--dry-run", action="store_true",
180
+ help="Show what would be downloaded without uploading")
181
+ parser.add_argument("--symbols", nargs="+", default=SYMBOLS,
182
+ help="Only update these symbols (default: all 6)")
183
+ args = parser.parse_args()
184
+
185
+ if not HF_TOKEN and not args.dry_run:
186
+ print("ERROR: HF_TOKEN environment variable not set")
187
+ sys.exit(1)
188
+
189
+ api = HfApi(token=HF_TOKEN)
190
+
191
+ print(f"{'='*55}")
192
+ print(f" 1s Crypto Dataset — Daily Updater")
193
+ print(f" {datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}")
194
+ print(f"{'='*55}")
195
+
196
+ total_new = 0
197
+ for symbol in args.symbols:
198
+ try:
199
+ n = update_symbol(symbol, api, dry_run=args.dry_run)
200
+ total_new += n
201
+ except Exception as e:
202
+ print(f" ERROR updating {symbol}: {e}")
203
+
204
+ print(f"\n{'='*55}")
205
+ print(f" Update complete — {total_new:,} total new rows added")
206
+ print(f"{'='*55}")
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()