SPB Git

spb/findata

Public
14.0 KB · 266 lines python
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 annotations1011import re12from datetime import date13from typing import Any1415import duckdb16import pyarrow as pa17from findata_core.db import connection18from findata_schema import BARS_SCHEMA1920from findata_ingest.lake import Lake, live_files212223def _con(read_only: bool = True) -> duckdb.DuckDBPyConnection:24    con = duckdb.connect(database=":memory:", config={"threads": 4, "memory_limit": "4GB", "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, Any] | 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.IGNORECASE)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|explain)\b", sql, re.IGNORECASE):127        raise ValueError("statement must start with SELECT / WITH")128    is_explain = bool(re.match(r"^\s*explain\b", sql, re.I))129    con = _con()130    scoped_used: list[str] = []131    dirs = []132    for r in Lake().roots():133        rr = str(r.resolve()).replace("'", "''")134        dirs += [f"'{rr}/curated'", f"'{rr}/_retired'"]135    con.execute(f"SET allowed_directories = [{', '.join(dirs)}]")136    for name, spec in (views or {}).items():137        if not re.fullmatch(r"[a-z][a-z0-9_]*", name):138            raise ValueError(f"bad view name {name}")139        if name not in _referenced_views(sql, {name: spec}):140            continue  # only materialize views the statement uses (directory globs are not free)141        if isinstance(spec, dict) and spec.get("sql"):142            fast = None143            if spec.get("dataset_id"):144                try:145                    fast = scoped_view_sql(spec["dataset_id"], spec.get("kind", ""), extract_scope(sql), Lake())146                except Exception:147                    fast = None148            con.execute(f"CREATE VIEW {name} AS {fast or spec['sql']}")149            scoped_used.append(name if fast else f"{name} (full scan)")150        elif isinstance(spec, list) and spec:  # legacy explicit file list151            lst = ", ".join("'" + g.replace("'", "''") + "'" for g in spec)152            con.execute(f"CREATE VIEW {name} AS SELECT * FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false)")153        else:154            con.execute(f"CREATE VIEW {name} AS SELECT * FROM (VALUES (NULL)) t(empty) WHERE false")155    con.execute("SET enable_external_access = false")156    timer = threading.Timer(timeout_s, con.interrupt)157    timer.start()158    try:159        body = sql.strip().rstrip(";")160        tbl = _arrow(con, body if is_explain else f"SELECT * FROM ({body}) q LIMIT {int(max_rows) + 1}", None)161    except duckdb.InterruptException as e:162        raise TimeoutError(f"query exceeded {timeout_s}s") from e163    finally:164        timer.cancel()165    truncated = tbl.num_rows > max_rows166    return tbl.slice(0, max_rows), {"truncated": truncated, "views": scoped_used}167168169_views_cache: dict[str, Any] = {"at": 0.0, "value": None}170171172def dataset_views() -> dict[str, dict[str, Any]]:173    """SQL views for the playground/assistant: one per dataset with data, built from Hive-style directory globs174    (`curated/<dataset>/{base,delta}/**`) so that DuckDB prunes partitions (`symbol=`, `year=`, `session_date=`,175    `underlying=`, `period=`) from the path instead of receiving millions of file names. The directory tree is the176    live set (retired files are moved out); files of an in-progress publication may be visible for a few minutes.177    Cached 5 minutes."""178    import time179    if _views_cache["value"] is not None and time.monotonic() - _views_cache["at"] < 300:180        return _views_cache["value"]181    lake = Lake()182    out: dict[str, dict[str, Any]] = {}183    with connection() as conn:184        ds = conn.execute("SELECT id, kind FROM datasets WHERE kind IN ('market_bars','derived','options') AND current_version > 0").fetchall()185        for d in ds:186            root = lake.root_for(d["id"])187            layouts = {}188            for layout in ("base", "delta"):189                ldir = root / "curated" / d["id"] / layout190                if ldir.exists() and next(ldir.rglob("*.parquet"), None) is not None:  # skip emptied layouts191                    layouts[layout] = str(ldir / "**" / "*.parquet").replace("'", "''")192            if not layouts:193                continue194            parts = []195            if d["kind"] == "options":196                parts.append(f"SELECT * FROM read_parquet('{layouts['base']}', hive_partitioning=true)")197            else:198                if "base" in layouts:   # partition columns symbol=, year= come from the path (pruned before any file is opened)199                    parts.append(f"SELECT * FROM read_parquet('{layouts['base']}', hive_partitioning=true)")200                if "delta" in layouts:  # session files: derive the same columns so UNION ALL BY NAME lines up201                    parts.append(f"SELECT *, symbol_as_reported AS symbol, year(session_date)::BIGINT AS year "202                                 f"FROM read_parquet('{layouts['delta']}', hive_partitioning=false)")203            out[d["id"].replace(".", "_")] = {"sql": " UNION ALL BY NAME ".join(parts), "layouts": sorted(layouts), "root": str(root),204                                              "kind": d["kind"], "dataset_id": d["id"]}205    _views_cache.update(at=time.monotonic(), value=out)206    return out207208209_SYM_RE = re.compile(r"\b(?:symbol|symbol_as_reported|underlying)\s*=\s*'([A-Za-z0-9.\-_]+)'", re.I)210_SYM_IN_RE = re.compile(r"\b(?:symbol|symbol_as_reported|underlying)\s+IN\s*\(([^)]+)\)", re.I)211_YEAR_RE = re.compile(r"\byear\s*=\s*(\d{4})\b", re.I)212_YEAR_IN_RE = re.compile(r"\byear\s+IN\s*\(([^)]+)\)", re.I)213_DATE_RE = re.compile(r"\b(?:session_date|trade_date)\s*(>=|<=|=|>|<)\s*(?:DATE\s*)?'(\d{4}-\d{2}-\d{2})'", re.I)214_BETWEEN_RE = re.compile(r"\b(?:session_date|trade_date)\s+BETWEEN\s+(?:DATE\s*)?'(\d{4}-\d{2}-\d{2})'\s+AND\s+(?:DATE\s*)?'(\d{4}-\d{2}-\d{2})'", re.I)215216217def extract_scope(sql: str) -> dict[str, Any]:218    """Pull simple equality/IN/range predicates on partition columns out of a statement so that the file list can219    be resolved from the catalog (indexed) instead of globbing hundreds of thousands of files."""220    from datetime import date as _date221    syms: set[str] = {m.group(1).upper() for m in _SYM_RE.finditer(sql)}222    for m in _SYM_IN_RE.finditer(sql):223        syms |= {x.strip().strip("'\"").upper() for x in m.group(1).split(",") if x.strip()}224    years: set[int] = {int(m.group(1)) for m in _YEAR_RE.finditer(sql)}225    for m in _YEAR_IN_RE.finditer(sql):226        years |= {int(x) for x in re.findall(r"\d{4}", m.group(1))}227    start = end = None228    for op, d in _DATE_RE.findall(sql):229        dd = _date.fromisoformat(d)230        if op in (">=", ">", "="):231            start = dd if start is None else max(start, dd)232        if op in ("<=", "<", "="):233            end = dd if end is None else min(end, dd)234    for a, b in _BETWEEN_RE.findall(sql):235        start = max(start, _date.fromisoformat(a)) if start else _date.fromisoformat(a)236        end = min(end, _date.fromisoformat(b)) if end else _date.fromisoformat(b)237    if years:238        ys, ye = _date(min(years), 1, 1), _date(max(years), 12, 31)239        start = ys if start is None else max(start, ys)240        end = ye if end is None else min(end, ye)241    return {"symbols": sorted(syms), "start": start, "end": end}242243244def scoped_view_sql(dataset_id: str, kind: str, scope: dict[str, Any], lake: Lake) -> str | None:245    """Explicit file list from the catalog for symbol-scoped statements (fast path). None → use the glob view."""246    if not scope["symbols"]:247        return None248    with connection() as conn:249        files = live_files(conn, dataset_id, scope["symbols"], scope["start"], scope["end"])250    if len(files) > 20000:251        return None252    if not files:253        return "SELECT * FROM (VALUES (NULL)) t(empty) WHERE false"254    lst = ", ".join("'" + str(lake.resolve(f["path"])).replace("'", "''") + "'" for f in files)255    if kind == "options":256        return (f"SELECT * EXCLUDE (filename), regexp_extract(filename, 'period=([^/]+)', 1) AS period "257                f"FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false, filename=true)")258    return (f"SELECT *, symbol_as_reported AS symbol, year(session_date)::BIGINT AS year "259            f"FROM read_parquet([{lst}], union_by_name=true, hive_partitioning=false)")260261262def _referenced_views(sql: str, views: dict[str, Any]) -> list[str]:263    import re as _re264    low = sql.lower()265    return [name for name in views if _re.search(r"\b" + _re.escape(name) + r"\b", low)]266
Files · 6665d8eb03ff011fcb876eb3c6317cb75a3c014b
Menu

Theme