Spaces:
Running
Running
Download scripts/enrich_data.py from Arrechenash/stocks: direct link, hf CLI and curl.
- Browser
- Download file 2.39 kB
-
https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/scripts/enrich_data.py
- Command line
-
hf download hf://spaces/Arrechenash/stocks/scripts/enrich_data.py
-
curl -L -o enrich_data.py https://huggingface.co/spaces/Arrechenash/stocks/resolve/main/scripts/enrich_data.py
2.39 kB
| #!/usr/bin/env python3 | |
| """Compute derived columns from raw OHLCV data.""" | |
| import contextlib | |
| import logging | |
| import os | |
| import sys | |
| import time | |
| from config import DUCKDB_PATH, LOCAL_MERGED | |
| from core.data_enricher import DataEnricher | |
| from core.infra.data_gate import DataGateError | |
| # Configure logging | |
| logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") | |
| logger = logging.getLogger(__name__) | |
| def build_duckdb_index(): | |
| """Build the persistent DuckDB index from the enriched parquet. | |
| Runs after ``DataEnricher.enrich()`` succeeds so the index is always in | |
| sync with the latest parquet. Atomic write (tmp + ``os.replace``) keeps | |
| the previous index usable if this step crashes mid-build. | |
| """ | |
| if not os.path.exists(LOCAL_MERGED): | |
| logger.warning("Parquet not found — skipping DuckDB index build") | |
| return | |
| logger.info("Building DuckDB index from enriched parquet...") | |
| t0 = time.time() | |
| tmp = DUCKDB_PATH + ".tmp" | |
| try: | |
| import duckdb | |
| con = duckdb.connect(tmp) | |
| con.execute(f"CREATE TABLE daily_data AS SELECT * FROM '{LOCAL_MERGED}' ORDER BY symbol, timestamp") | |
| con.execute("CREATE INDEX idx_ts ON daily_data (timestamp)") | |
| con.close() | |
| os.replace(tmp, DUCKDB_PATH) | |
| logger.info(f"DuckDB index built in {time.time() - t0:.1f}s") | |
| except Exception as e: | |
| logger.error(f"Failed to build DuckDB index: {e}") | |
| if os.path.exists(tmp): | |
| with contextlib.suppress(Exception): | |
| os.remove(tmp) | |
| def main(): | |
| from app.context import register_providers | |
| register_providers() # providers resolve by name; scripts are a composition root too | |
| enricher = DataEnricher() | |
| try: | |
| enricher.enrich() | |
| except DataGateError: | |
| # Non-zero exit so `make sync` fails loudly and cron/HF automation | |
| # sees the pipeline did NOT produce a publishable dataset. The old | |
| # parquet is untouched (the gate runs before the write). | |
| logger.error("Data quality gate FAILED — merged parquet NOT updated") | |
| sys.exit(1) | |
| # Build persistent DuckDB index so the app queries the table directly | |
| # instead of scanning the raw parquet on every connection. | |
| build_duckdb_index() | |
| logger.info("\n✓ Data enrichment complete") | |
| if __name__ == "__main__": | |
| main() | |