Fix daily_update.py: complete rewrite with full update_symbol logic (DOGEUSDT, XRPUSDT, SOLUSDT + others)
Browse files- scripts/daily_update.py +77 -62
scripts/daily_update.py
CHANGED
|
@@ -1,19 +1,19 @@
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
-
|
| 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
|
| 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=<
|
| 16 |
-
python daily_update.py --dry-run
|
|
|
|
| 17 |
"""
|
| 18 |
|
| 19 |
import argparse
|
|
@@ -38,7 +38,7 @@ 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 = ["
|
| 42 |
|
| 43 |
PA_SCHEMA = pa.schema([
|
| 44 |
("open_time_s", pa.int64()),
|
|
@@ -51,14 +51,14 @@ PA_SCHEMA = pa.schema([
|
|
| 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
|
| 62 |
r.raise_for_status()
|
| 63 |
with zipfile.ZipFile(io.BytesIO(r.content)) as z:
|
| 64 |
with z.open(z.namelist()[0]) as f:
|
|
@@ -68,13 +68,14 @@ def download_daily(symbol: str, date: datetime.date, retries: int = 3):
|
|
| 68 |
names=["open_time", "open", "high", "low", "close", "volume"],
|
| 69 |
dtype={
|
| 70 |
"open_time": np.int64,
|
| 71 |
-
"open":
|
| 72 |
-
"high":
|
| 73 |
-
"low":
|
| 74 |
-
"close":
|
| 75 |
-
"volume":
|
| 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)
|
|
@@ -89,13 +90,13 @@ def download_daily(symbol: str, date: datetime.date, retries: int = 3):
|
|
| 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 |
-
#
|
| 99 |
print(f" Fetching existing parquet from HF...", flush=True)
|
| 100 |
try:
|
| 101 |
local_existing = hf_hub_download(
|
|
@@ -103,83 +104,95 @@ def update_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> int:
|
|
| 103 |
filename=hf_path,
|
| 104 |
repo_type="dataset",
|
| 105 |
token=HF_TOKEN,
|
| 106 |
-
force_download=True,
|
| 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
|
| 114 |
-
|
| 115 |
-
print(f"
|
| 116 |
-
|
| 117 |
-
#
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
return 0
|
| 125 |
|
| 126 |
-
print(f" Missing {len(
|
|
|
|
| 127 |
if dry_run:
|
| 128 |
-
print(f" [
|
| 129 |
return 0
|
| 130 |
|
| 131 |
-
# Download missing
|
| 132 |
new_frames = []
|
| 133 |
-
for
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
|
|
|
| 140 |
|
| 141 |
if not new_frames:
|
| 142 |
-
print(f" No new data available")
|
| 143 |
return 0
|
| 144 |
|
| 145 |
-
|
| 146 |
-
n_new
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
.sort_values("open_time_s")
|
| 150 |
-
.reset_index(drop=True))
|
| 151 |
-
del existing, new_data, new_frames; gc.collect()
|
| 152 |
|
| 153 |
-
|
| 154 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
| 161 |
-
del combined, table; gc.collect()
|
| 162 |
|
| 163 |
-
print(f" Uploading {file_mb:.0f} MB ({n_new:
|
| 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}:
|
| 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",
|
| 180 |
help="Show what would be downloaded without uploading")
|
| 181 |
-
parser.add_argument("--symbols",
|
| 182 |
-
help="Only update these symbols (default: all
|
| 183 |
args = parser.parse_args()
|
| 184 |
|
| 185 |
if not HF_TOKEN and not args.dry_run:
|
|
@@ -191,6 +204,8 @@ def main():
|
|
| 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
|
|
@@ -199,7 +214,7 @@ def main():
|
|
| 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")
|
|
|
|
| 1 |
#!/usr/bin/env python3
|
| 2 |
"""
|
| 3 |
+
daily_update.py
|
| 4 |
+
===============
|
| 5 |
+
Checks the latest timestamp in each asset's combined Parquet on HuggingFace,
|
| 6 |
+
downloads any missing daily 1s files from Binance Vision, and appends them.
|
|
|
|
| 7 |
|
| 8 |
+
Run this script daily (e.g. via a cron job, Replit workflow, or HF Spaces scheduler).
|
| 9 |
|
| 10 |
Binance daily endpoint:
|
| 11 |
https://data.binance.vision/data/spot/daily/klines/{SYMBOL}/1s/{SYMBOL}-1s-YYYY-MM-DD.zip
|
| 12 |
|
| 13 |
Usage:
|
| 14 |
+
HF_TOKEN=<token> python scripts/daily_update.py
|
| 15 |
+
python scripts/daily_update.py --dry-run # show what would be fetched, no upload
|
| 16 |
+
python scripts/daily_update.py --symbols DOGEUSDT # update one symbol only
|
| 17 |
"""
|
| 18 |
|
| 19 |
import argparse
|
|
|
|
| 38 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 39 |
BINANCE_DAILY = "https://data.binance.vision/data/spot/daily/klines"
|
| 40 |
|
| 41 |
+
SYMBOLS = ["DOGEUSDT", "XRPUSDT", "SOLUSDT", "BTCUSDT", "ETHUSDT", "BNBUSDT"]
|
| 42 |
|
| 43 |
PA_SCHEMA = pa.schema([
|
| 44 |
("open_time_s", pa.int64()),
|
|
|
|
| 51 |
|
| 52 |
|
| 53 |
def download_daily(symbol: str, date: datetime.date, retries: int = 3):
|
| 54 |
+
"""Download one day of 1s OHLCV 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:
|
|
|
|
| 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 |
+
# Binance timestamps are milliseconds; some older files use microseconds
|
| 79 |
sample = df["open_time"].iloc[0]
|
| 80 |
divisor = 1_000_000 if sample > 2e12 else 1_000
|
| 81 |
df["open_time_s"] = (df["open_time"] // divisor).astype(np.int64)
|
|
|
|
| 90 |
def update_symbol(symbol: str, api: HfApi, dry_run: bool = False) -> int:
|
| 91 |
"""
|
| 92 |
Update one asset's combined Parquet with any missing days.
|
| 93 |
+
Returns number of new rows appended (0 if already up to date or dry-run).
|
| 94 |
"""
|
| 95 |
hf_path = f"data/{symbol}_1s.parquet"
|
| 96 |
print(f"\n {'─'*50}")
|
| 97 |
print(f" {symbol}")
|
| 98 |
|
| 99 |
+
# ── 1. Fetch existing combined Parquet ────────────────────────────────────
|
| 100 |
print(f" Fetching existing parquet from HF...", flush=True)
|
| 101 |
try:
|
| 102 |
local_existing = hf_hub_download(
|
|
|
|
| 104 |
filename=hf_path,
|
| 105 |
repo_type="dataset",
|
| 106 |
token=HF_TOKEN,
|
| 107 |
+
force_download=True, # always get freshest version
|
| 108 |
)
|
| 109 |
+
existing = pd.read_parquet(local_existing, engine="pyarrow")
|
| 110 |
except Exception as e:
|
| 111 |
print(f" Could not fetch existing file: {e}")
|
| 112 |
+
print(f" Has the combined file been created yet? Run merge_yearly.py first.")
|
| 113 |
return 0
|
| 114 |
|
| 115 |
+
latest_ts = int(existing["open_time_s"].max())
|
| 116 |
+
latest_date = datetime.date.fromtimestamp(latest_ts)
|
| 117 |
+
print(f" Existing rows: {len(existing):,} | latest: {latest_date}")
|
| 118 |
+
|
| 119 |
+
# ── 2. Determine which dates are missing ──────────────────────────────────
|
| 120 |
+
# Binance publishes the previous day's data with ~1-2 hour delay UTC
|
| 121 |
+
yesterday = datetime.date.today() - datetime.timedelta(days=1)
|
| 122 |
+
missing_dates = []
|
| 123 |
+
d = latest_date + datetime.timedelta(days=1)
|
| 124 |
+
while d <= yesterday:
|
| 125 |
+
missing_dates.append(d)
|
| 126 |
+
d += datetime.timedelta(days=1)
|
| 127 |
+
|
| 128 |
+
if not missing_dates:
|
| 129 |
+
print(f" Already up to date through {latest_date}. Nothing to do.")
|
| 130 |
return 0
|
| 131 |
|
| 132 |
+
print(f" Missing {len(missing_dates)} day(s): {missing_dates[0]} → {missing_dates[-1]}")
|
| 133 |
+
|
| 134 |
if dry_run:
|
| 135 |
+
print(f" [dry-run] Would download {len(missing_dates)} day(s) and append them.")
|
| 136 |
return 0
|
| 137 |
|
| 138 |
+
# ── 3. Download missing daily files ───────────────────────────────────────
|
| 139 |
new_frames = []
|
| 140 |
+
for date in missing_dates:
|
| 141 |
+
print(f" Fetching {date}...", flush=True)
|
| 142 |
+
df = download_daily(symbol, date)
|
| 143 |
+
if df is not None:
|
| 144 |
+
print(f" {len(df):,} rows")
|
| 145 |
+
new_frames.append(df)
|
| 146 |
+
else:
|
| 147 |
+
print(f" Not available yet — skipping.")
|
| 148 |
|
| 149 |
if not new_frames:
|
| 150 |
+
print(f" No new data available for download.")
|
| 151 |
return 0
|
| 152 |
|
| 153 |
+
# ── 4. Merge and deduplicate ──────────────────────────────────────────────
|
| 154 |
+
n_new = sum(len(f) for f in new_frames)
|
| 155 |
+
new_data = pd.concat(new_frames, ignore_index=True)
|
| 156 |
+
del new_frames; gc.collect()
|
|
|
|
|
|
|
|
|
|
| 157 |
|
| 158 |
+
combined = pd.concat([existing, new_data], ignore_index=True)
|
| 159 |
+
del existing, new_data; gc.collect()
|
| 160 |
+
|
| 161 |
+
combined = (
|
| 162 |
+
combined
|
| 163 |
+
.sort_values("open_time_s")
|
| 164 |
+
.drop_duplicates("open_time_s")
|
| 165 |
+
.reset_index(drop=True)
|
| 166 |
+
)
|
| 167 |
+
latest_after = datetime.date.fromtimestamp(int(combined["open_time_s"].max()))
|
| 168 |
|
| 169 |
+
# ── 5. Write and upload ───────────────────────────────────────────────────
|
| 170 |
local_out = Path(f"/tmp/{symbol}_1s_updated.parquet")
|
| 171 |
table = pa.Table.from_pandas(combined, schema=PA_SCHEMA, preserve_index=False)
|
| 172 |
+
del combined; gc.collect()
|
| 173 |
pq.write_table(table, local_out, compression="snappy")
|
| 174 |
+
file_mb = local_out.stat().st_size / 1e6
|
|
|
|
| 175 |
|
| 176 |
+
print(f" Uploading {file_mb:.0f} MB (+{n_new:,} new rows, now through {latest_after})...",
|
| 177 |
flush=True)
|
| 178 |
api.upload_file(
|
| 179 |
path_or_fileobj=str(local_out),
|
| 180 |
path_in_repo=hf_path,
|
| 181 |
repo_id=REPO_ID,
|
| 182 |
repo_type="dataset",
|
| 183 |
+
commit_message=f"Daily update {symbol}: +{n_new:,} rows through {latest_after}",
|
| 184 |
)
|
| 185 |
+
local_out.unlink(missing_ok=True)
|
| 186 |
+
print(f" Done: +{n_new:,} rows → data is current through {latest_after}")
|
| 187 |
return n_new
|
| 188 |
|
| 189 |
|
| 190 |
def main():
|
| 191 |
parser = argparse.ArgumentParser(description="Daily updater for 1s crypto dataset")
|
| 192 |
+
parser.add_argument("--dry-run", action="store_true",
|
| 193 |
help="Show what would be downloaded without uploading")
|
| 194 |
+
parser.add_argument("--symbols", nargs="+", default=SYMBOLS,
|
| 195 |
+
help="Only update these symbols (default: all)")
|
| 196 |
args = parser.parse_args()
|
| 197 |
|
| 198 |
if not HF_TOKEN and not args.dry_run:
|
|
|
|
| 204 |
print(f"{'='*55}")
|
| 205 |
print(f" 1s Crypto Dataset — Daily Updater")
|
| 206 |
print(f" {datetime.datetime.utcnow().strftime('%Y-%m-%d %H:%M UTC')}")
|
| 207 |
+
if args.dry_run:
|
| 208 |
+
print(" Mode: DRY RUN")
|
| 209 |
print(f"{'='*55}")
|
| 210 |
|
| 211 |
total_new = 0
|
|
|
|
| 214 |
n = update_symbol(symbol, api, dry_run=args.dry_run)
|
| 215 |
total_new += n
|
| 216 |
except Exception as e:
|
| 217 |
+
print(f" FATAL ERROR updating {symbol}: {e}")
|
| 218 |
|
| 219 |
print(f"\n{'='*55}")
|
| 220 |
print(f" Update complete — {total_new:,} total new rows added")
|