"""Run EXPLAIN ANALYZE for representative scanner DSL filters.""" from __future__ import annotations import argparse from pathlib import Path import duckdb from core.dsl.compiler import SqlCompiler from core.dsl.grammar import GrammarParser, parse_bool_expr FILTERS = { "gap-volume": "gap_pct > 5% and volume > 1000000", "relative-volume": "rel_vol > 1.5 and close > 5", "momentum-volume": "change_pct > 3% and volume > 500000", } def compile_where(expr: str) -> str: parsed = GrammarParser().parse(expr) return SqlCompiler().compile_bool(parse_bool_expr(parsed.remaining_filter)) def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--output", default="reports/explain_analyze.txt") args = parser.parse_args() output = Path(args.output) output.parent.mkdir(parents=True, exist_ok=True) con = duckdb.connect() with output.open("w", encoding="utf-8") as report: report.write("Representative scanner SQL EXPLAIN ANALYZE\n") report.write("Source: data/alpaca_merged.parquet\n\n") for name, expr in FILTERS.items(): where = compile_where(expr) sql = ( "SELECT symbol, timestamp, close, volume, gap_pct, rel_vol, change_pct " "FROM read_parquet('data/alpaca_merged.parquet') " f"WHERE {where} LIMIT 250" ) report.write(f"=== {name} ===\nDSL: {expr}\nSQL: {sql}\n\n") report.write(con.execute(f"EXPLAIN ANALYZE {sql}").fetchone()[1]) report.write("\n\n") if __name__ == "__main__": main()