macro-indicators / ingest.py
ZipLime's picture
Add ziplime PIT dataset: docs, manifest, recipe, ingest, workflow, bundle
de2ca63 verified
Raw
History Blame Contribute Delete
1.86 kB
"""
Shared append-only ingest harness for a ziplime PIT dataset.
Reads `recipe.fetch(since)`, stamps `ingested_at`, drops byte-identical duplicates of
existing (entity_id, event_date, knowledge_date) rows, and **appends** to the Delta table.
It never issues UPDATE/DELETE/MERGE — append-only is the PIT invariant the linter enforces.
"""
from __future__ import annotations
import argparse, hashlib
from datetime import datetime, timezone
from pathlib import Path
import polars as pl
from deltalake import DeltaTable, write_deltalake
import recipe
TABLE_URI = str(Path(__file__).parent / "data" / "data_bundle" /
"yahoo_finance_daily_data" / "1784755946" / "data.delta")
def _row_hash(df: pl.DataFrame) -> pl.Series:
cols = [c for c in df.columns if c != "ingested_at"]
return df.select(cols).hash_rows().cast(pl.Utf8)
async def main(since: datetime) -> None:
fresh = await recipe.fetch(since)
if fresh.is_empty():
print("recipe returned no rows; nothing to append")
return
fresh = fresh.with_columns(
pl.lit(datetime.now(timezone.utc)).alias("ingested_at"),
)
try:
existing = pl.from_arrow(DeltaTable(TABLE_URI).to_pyarrow_table())
seen = set(_row_hash(existing).to_list())
fresh = fresh.filter(~_row_hash(fresh).is_in(seen))
except Exception:
pass # first ingest / fresh table
if fresh.is_empty():
print("no new or revised rows after dedup")
return
write_deltalake(TABLE_URI, fresh.to_arrow(), mode="append")
print(f"appended {len(fresh)} rows to {TABLE_URI}")
if __name__ == "__main__":
ap = argparse.ArgumentParser()
ap.add_argument("--since", default="2025-01-01")
args = ap.parse_args()
import asyncio
asyncio.run(main(datetime.fromisoformat(args.since).replace(tzinfo=timezone.utc)))