File size: 2,389 Bytes
ee446e8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#!/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()