1"""Read side: DuckDB over the live Parquet file set selected from the Postgres manifest (`lake_files`).23Adjustments are applied at query time from `corporate_actions` (explicit, reproducible):4 split : multiply prices by Π(1/ratio) for splits with ex_date > bar session_date; divide volume by the same factor5 split_div : additionally multiply by Π(1 - div/prev_close) for dividends with ex_date > session_date6 (prev_close = last raw close strictly before ex_date in the requested data — if unavailable the7 dividend factor is skipped and reported in `adjustment_notes`).8"""9from __future__ import annotations1011from datetime import date12from typing import Any1314import duckdb15import pyarrow as pa1617from findata_core.config import get_settings18from findata_core.db import connection19from findata_ingest.lake import Lake, live_files20from findata_schema import BARS_SCHEMA212223def _con(read_only: bool = True) -> duckdb.DuckDBPyConnection:24 con = duckdb.connect(database=":memory:", config={"threads": 8, "memory_limit": "8GB", "TimeZone": "UTC"})25 return con262728def _arrow(con: duckdb.DuckDBPyConnection, sql: str, params: dict[str, Any] | None) -> pa.Table:29 try:30 rel = con.sql(sql, params=params) if params else con.sql(sql)31 return rel.to_arrow_table()32 except TypeError: # older duckdb without params= on sql()33 return con.execute(sql, params).fetch_arrow_table()343536def empty_bars() -> pa.Table:37 return pa.table({f.name: pa.array([], type=f.type) for f in BARS_SCHEMA}, schema=BARS_SCHEMA)383940def read_bars(dataset_id: str, symbols: list[str], start: date | None, end: date | None, version: int | None = None,41 limit: int | None = None, columns: list[str] | None = None, lake: Lake | None = None) -> tuple[pa.Table, dict[str, Any]]:42 lake = lake or Lake()43 with connection() as conn:44 files = live_files(conn, dataset_id, symbols, start, end, version)45 ver = conn.execute("SELECT current_version FROM datasets WHERE id=%s", (dataset_id,)).fetchone()46 meta = {"dataset_id": dataset_id, "version": version if version is not None else (ver["current_version"] if ver else None),47 "files_scanned": len(files)}48 if not files:49 return empty_bars(), meta50 paths = [str(lake.resolve(f["path"])) for f in files]51 con = _con()52 con.register("paths", pa.table({"p": paths}))53 cols = ", ".join(columns) if columns else "*"54 where = ["symbol_as_reported IN (SELECT UNNEST($syms))"]55 params: dict[str, Any] = {"syms": symbols}56 if start:57 where.append("session_date >= $start")58 params["start"] = start59 if end:60 where.append("session_date <= $end")61 params["end"] = end62 sql = f"SELECT {cols} FROM read_parquet($paths, union_by_name=true, hive_partitioning=false) WHERE {' AND '.join(where)} ORDER BY symbol_as_reported, timestamp_utc"63 params["paths"] = paths64 if limit:65 sql += f" LIMIT {int(limit) + 1}"66 tbl = _arrow(con, sql, params)67 meta["truncated"] = bool(limit and tbl.num_rows > limit)68 if limit and tbl.num_rows > limit:69 tbl = tbl.slice(0, limit)70 if not columns:71 tbl = tbl.cast(BARS_SCHEMA)72 return tbl, meta737475def apply_adjustment(table: pa.Table, adjustment: str, lake: Lake | None = None) -> tuple[pa.Table, list[str]]:76 """Return an adjusted copy of raw bars (`adjustment_type` column updated). Never mutates the lake."""77 if adjustment in ("raw", None) or table.num_rows == 0:78 return table, []79 import polars as pl80 df = pl.from_arrow(table)81 syms = df.get_column("symbol_as_reported").unique().to_list()82 iids = [f"firstrate:{df.filter(pl.col('symbol_as_reported') == s).get_column('asset_class')[0]}:{s}" for s in syms]83 with connection() as conn:84 acts = conn.execute("SELECT instrument_id, action_type, ex_date, value::float8 AS value FROM corporate_actions WHERE instrument_id = ANY(%s) ORDER BY ex_date",85 (iids,)).fetchall()86 notes: list[str] = []87 if not acts:88 notes.append("no corporate actions on file for requested symbols")89 return df.with_columns(pl.lit(adjustment).alias("adjustment_type")).to_arrow().cast(BARS_SCHEMA), notes90 out_frames = []91 for s in syms:92 sub = df.filter(pl.col("symbol_as_reported") == s).sort("timestamp_utc")93 iid = f"firstrate:{sub.get_column('asset_class')[0]}:{s}"94 factor = pl.Series("f", [1.0] * sub.height)95 sd = sub.get_column("session_date")96 for a in acts:97 if a["instrument_id"] != iid:98 continue99 if a["action_type"] == "split":100 f = 1.0 / float(a["value"])101 factor = factor * pl.Series([f if d < a["ex_date"] else 1.0 for d in sd])102 elif a["action_type"] == "dividend" and adjustment == "split_div":103 prev = sub.filter(pl.col("session_date") < a["ex_date"]).get_column("close")104 if prev.len() == 0:105 notes.append(f"{s}: dividend {a['ex_date']} skipped (no prior close in range)")106 continue107 f = 1.0 - float(a["value"]) / float(prev[-1])108 factor = factor * pl.Series([f if d < a["ex_date"] else 1.0 for d in sd])109 sub = sub.with_columns(factor.alias("_f")).with_columns(110 (pl.col("open") * pl.col("_f")).alias("open"), (pl.col("high") * pl.col("_f")).alias("high"),111 (pl.col("low") * pl.col("_f")).alias("low"), (pl.col("close") * pl.col("_f")).alias("close"),112 (pl.col("volume") / pl.col("_f")).alias("volume"), pl.lit(adjustment).alias("adjustment_type")).drop("_f")113 out_frames.append(sub)114 res = pl.concat(out_frames).sort(["symbol_as_reported", "timestamp_utc"])115 return res.to_arrow().cast(BARS_SCHEMA), notes116117118def run_sql(sql: str, max_rows: int, timeout_s: int, views: dict[str, list[str]] | None = None) -> tuple[pa.Table, dict[str, Any]]:119 """Sandboxed read-only SQL: DuckDB in-memory, external access limited to the registered dataset views."""120 import re121 import threading122123 forbidden = re.compile(r"\b(attach|copy|export|import|install|load|create|insert|update|delete|drop|alter|pragma|set|call|read_csv|read_json|read_text|glob|httpfs)\b", re.I)124 if forbidden.search(sql) or ";" in sql.strip().rstrip(";"):125 raise ValueError("only a single read-only SELECT statement is allowed")126 if not re.match(r"^\s*(select|with|describe|show|summarize)\b", sql, re.I):127 raise ValueError("statement must start with SELECT / WITH")128 con = _con()129 lake_root = str(Lake().root).replace("'", "''")130 con.execute(f"SET allowed_directories = ['{lake_root}/curated', '{lake_root}/_retired']")131 for name, paths in (views or {}).items():132 if not re.fullmatch(r"[a-z][a-z0-9_]*", name):133 raise ValueError(f"bad view name {name}")134 if paths:135 lst = ", ".join("'" + p.replace("'", "''") + "'" for p in paths)136 con.execute(f"CREATE VIEW {name} AS SELECT * FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false)")137 else:138 con.execute(f"CREATE VIEW {name} AS SELECT * FROM (VALUES (NULL)) t(empty) WHERE false")139 con.execute("SET enable_external_access = false")140 timer = threading.Timer(timeout_s, con.interrupt)141 timer.start()142 try:143 tbl = _arrow(con, f"SELECT * FROM ({sql.strip().rstrip(';')}) q LIMIT {int(max_rows) + 1}", None)144 except duckdb.InterruptException as e:145 raise TimeoutError(f"query exceeded {timeout_s}s") from e146 finally:147 timer.cancel()148 truncated = tbl.num_rows > max_rows149 return tbl.slice(0, max_rows), {"truncated": truncated}150151152def dataset_views() -> dict[str, list[str]]:153 """Map SQL view names (dataset ids with dots → underscores) to live file lists."""154 lake = Lake()155 out: dict[str, list[str]] = {}156 with connection() as conn:157 ds = conn.execute("SELECT id FROM datasets WHERE kind IN ('market_bars','derived')").fetchall()158 for d in ds:159 files = live_files(conn, d["id"])160 out[d["id"].replace(".", "_")] = [str(lake.abs(f["path"])) for f in files]161 return out162