| |
| """Audit downloaded PMData daily ZIP archives without extracting them.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import datetime as dt |
| import json |
| import zipfile |
| from pathlib import Path |
|
|
| import pyarrow.parquet as pq |
|
|
|
|
| ROOT = Path(__file__).resolve().parents[1] |
| DEFAULT_DATA_ROOT = ROOT / "data" / "pmdata" |
|
|
|
|
| def iter_dates(start_date: str, end_date: str) -> list[str]: |
| start = dt.date.fromisoformat(start_date) |
| end = dt.date.fromisoformat(end_date) |
| if end < start: |
| raise ValueError(f"end date {end} is before start date {start}") |
| dates = [] |
| cur = start |
| while cur <= end: |
| dates.append(cur.isoformat()) |
| cur += dt.timedelta(days=1) |
| return dates |
|
|
|
|
| def parquet_rows_from_zip(zf: zipfile.ZipFile, names: list[str]) -> int: |
| total = 0 |
| for name in names: |
| with zf.open(name) as fh: |
| total += pq.ParquetFile(fh).metadata.num_rows |
| return total |
|
|
|
|
| def expected_names(series: str, date: str) -> list[str]: |
| day = dt.date.fromisoformat(date) |
| start = int(dt.datetime(day.year, day.month, day.day, tzinfo=dt.timezone.utc).timestamp()) |
| prefix = f"{series.split('-', 1)[0]}-updown-5m" if series.endswith("-5m") else series |
| return [f"{prefix}-{start + i * 300}.parquet" for i in range(288)] |
|
|
|
|
| def audit_zip(path: Path, *, series: str, date: str) -> dict[str, object]: |
| if not path.exists(): |
| return {"path": str(path), "exists": False} |
|
|
| with zipfile.ZipFile(path) as zf: |
| bad_file = zf.testzip() |
| infos = zf.infolist() |
| parquet_names = [info.filename for info in infos if info.filename.endswith(".parquet")] |
| missing = [name for name in expected_names(series, date) if name not in set(parquet_names)] |
| row_count = parquet_rows_from_zip(zf, parquet_names) |
| return { |
| "path": str(path), |
| "exists": True, |
| "zip_ok": bad_file is None, |
| "bad_file": bad_file, |
| "zip_bytes": path.stat().st_size, |
| "parquet_files": len(parquet_names), |
| "uncompressed_bytes": sum(info.file_size for info in infos), |
| "row_count": row_count, |
| "first_file": parquet_names[0] if parquet_names else None, |
| "last_file": parquet_names[-1] if parquet_names else None, |
| "missing_expected_files": missing, |
| } |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument("--data-root", type=Path, default=DEFAULT_DATA_ROOT) |
| parser.add_argument("--series", default="btc-5m") |
| parser.add_argument("--start-date", required=True) |
| parser.add_argument("--end-date", required=True) |
| parser.add_argument("--out", type=Path, required=True) |
| args = parser.parse_args() |
|
|
| days = [] |
| totals = { |
| "zip_bytes": 0, |
| "uncompressed_bytes": 0, |
| "poly_l2_rows": 0, |
| "polygon_trades_rows": 0, |
| "poly_l2_files": 0, |
| "polygon_trades_files": 0, |
| } |
|
|
| for date in iter_dates(args.start_date, args.end_date): |
| day_dir = args.data_root / args.series / date |
| l2 = audit_zip(day_dir / f"{args.series}_poly_l2_{date}.zip", series=args.series, date=date) |
| trades = audit_zip( |
| day_dir / f"{args.series}_polygon_trades_{date}.zip", series=args.series, date=date |
| ) |
|
|
| for item in (l2, trades): |
| if item.get("exists"): |
| totals["zip_bytes"] += int(item["zip_bytes"]) |
| totals["uncompressed_bytes"] += int(item["uncompressed_bytes"]) |
| if l2.get("exists"): |
| totals["poly_l2_rows"] += int(l2["row_count"]) |
| totals["poly_l2_files"] += int(l2["parquet_files"]) |
| if trades.get("exists"): |
| totals["polygon_trades_rows"] += int(trades["row_count"]) |
| totals["polygon_trades_files"] += int(trades["parquet_files"]) |
|
|
| days.append({"date": date, "poly_l2": l2, "polygon_trades": trades}) |
|
|
| report = { |
| "series": args.series, |
| "start_date": args.start_date, |
| "end_date": args.end_date, |
| "day_count": len(days), |
| "expected_market_files_per_zip": 288, |
| "totals": totals, |
| "all_expected_files_present": all( |
| day["poly_l2"].get("exists") and day["polygon_trades"].get("exists") for day in days |
| ), |
| "all_zips_ok": all( |
| day["poly_l2"].get("zip_ok") and day["polygon_trades"].get("zip_ok") for day in days |
| ), |
| "all_zips_have_288_parquets": all( |
| day["poly_l2"].get("parquet_files") == 288 |
| and day["polygon_trades"].get("parquet_files") == 288 |
| for day in days |
| ), |
| "days": days, |
| } |
|
|
| args.out.parent.mkdir(parents=True, exist_ok=True) |
| args.out.write_text(json.dumps(report, indent=2), encoding="utf-8") |
| print(f"wrote {args.out}") |
| print(json.dumps({k: report[k] for k in ("day_count", "totals", "all_expected_files_present", "all_zips_ok", "all_zips_have_288_parquets")}, indent=2)) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|