1093 lines
44 KiB
Python
1093 lines
44 KiB
Python
"""Vault-fenced DuckDB + Polars + optional QuestDB `MarketDataStore` for curated datasets."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
import os
|
|
import re
|
|
from datetime import date, timedelta
|
|
from pathlib import Path
|
|
from typing import Any, Literal, Mapping, Protocol, Sequence, runtime_checkable
|
|
from urllib.parse import unquote, urlsplit
|
|
|
|
import duckdb
|
|
import polars as pl
|
|
import psycopg
|
|
|
|
from .features import FeatureLibraryError, parse_feature_ref
|
|
from .vault import (
|
|
DataScope,
|
|
DuckDbConnectionBudget,
|
|
MarketDataStoreValidationError,
|
|
VaultHoldoutFenceError,
|
|
apply_vault_fence,
|
|
epoch_micros_to_datetime,
|
|
format_utc_iso_micros,
|
|
resolve_duckdb_budget,
|
|
validate_curated_root,
|
|
)
|
|
|
|
EventKind = Literal["filing", "earnings", "ceo_post", "corporate_action"]
|
|
AdjustmentMode = Literal["raw", "split", "total"]
|
|
UniverseRef = Literal["US_EQ", "CA_EQ", "US_CA_EQ"]
|
|
|
|
_INT32_MIN = -2_147_483_648
|
|
_INT32_MAX = 2_147_483_647
|
|
_FX_1M_BAR_DURATION_MICROS = 60_000_000
|
|
|
|
_DATE_ONLY_RE = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
_CANONICAL_POSITIVE_INT_RE = re.compile(r"^[1-9]\d*$")
|
|
_CANONICAL_SIGNED_INT_RE = re.compile(r"^-?(?:0|[1-9]\d*)$")
|
|
_URL_USERINFO_RE = re.compile(r"://[^@\s/]+@")
|
|
_KV_PASSWORD_RE = re.compile(r"(password\s*=\s*)(?:'[^']*'|\"[^\"]*\"|\S+)", re.IGNORECASE)
|
|
|
|
_EVENT_KINDS: tuple[EventKind, ...] = ("filing", "earnings", "ceo_post", "corporate_action")
|
|
_EVENT_KIND_SET: frozenset[str] = frozenset(_EVENT_KINDS)
|
|
|
|
_UNIVERSE_CURRENCIES: dict[str, tuple[str, ...]] = {
|
|
"US_EQ": ("USD",),
|
|
"CA_EQ": ("CAD",),
|
|
"US_CA_EQ": ("USD", "CAD"),
|
|
}
|
|
|
|
FUNDAMENTALS_PIT_VALUE_FIELDS: tuple[str, ...] = (
|
|
"revenue",
|
|
"net_income",
|
|
"operating_cash_flow",
|
|
"total_assets",
|
|
"total_equity",
|
|
"shares_outstanding",
|
|
"ttm_revenue",
|
|
"ttm_net_income",
|
|
"ttm_operating_cash_flow",
|
|
)
|
|
_FUNDAMENTALS_PIT_VALUE_FIELD_SET: frozenset[str] = frozenset(FUNDAMENTALS_PIT_VALUE_FIELDS)
|
|
_FUNDAMENTALS_TTM_VALUE_FIELD_SET: frozenset[str] = frozenset(
|
|
("ttm_revenue", "ttm_net_income", "ttm_operating_cash_flow")
|
|
)
|
|
|
|
_BARS_1M_SCHEMA: dict[str, pl.DataType] = {
|
|
"listing_id": pl.Int32,
|
|
"ts": pl.Datetime("us", "UTC"),
|
|
"open": pl.Float64,
|
|
"high": pl.Float64,
|
|
"low": pl.Float64,
|
|
"close": pl.Float64,
|
|
"volume": pl.Float64,
|
|
"vwap": pl.Float64,
|
|
"known_at": pl.Datetime("us", "UTC"),
|
|
}
|
|
|
|
_FX_1M_SCHEMA: dict[str, pl.DataType] = {
|
|
"pair": pl.String,
|
|
"ts": pl.Datetime("us", "UTC"),
|
|
"open": pl.Float64,
|
|
"high": pl.Float64,
|
|
"low": pl.Float64,
|
|
"close": pl.Float64,
|
|
"source": pl.String,
|
|
"known_at": pl.Datetime("us", "UTC"),
|
|
}
|
|
|
|
|
|
def _redact_dsn(message: str, dsn: str) -> str:
|
|
redacted = message
|
|
if dsn:
|
|
redacted = redacted.replace(dsn, "<redacted-dsn>")
|
|
try:
|
|
parsed = urlsplit(dsn)
|
|
if parsed.password:
|
|
redacted = redacted.replace(parsed.password, "***")
|
|
decoded_pw = unquote(parsed.password)
|
|
if decoded_pw:
|
|
redacted = redacted.replace(decoded_pw, "***")
|
|
except Exception:
|
|
pass
|
|
redacted = _URL_USERINFO_RE.sub("://<redacted>@", redacted)
|
|
redacted = _KV_PASSWORD_RE.sub(r"\1***", redacted)
|
|
return redacted
|
|
|
|
|
|
@runtime_checkable
|
|
class QuestDbExecutor(Protocol):
|
|
"""Injected PGWire SQL executor protocol for QuestDB intraday queries."""
|
|
|
|
def query(self, sql: str, params: Sequence[Any]) -> Sequence[Mapping[str, Any]]: ...
|
|
|
|
def close(self) -> None: ...
|
|
|
|
|
|
class PsycopgQuestDbExecutor:
|
|
"""Autocommit psycopg PGWire executor for QuestDB with credential redaction on errors."""
|
|
|
|
def __init__(self, dsn: str) -> None:
|
|
if not isinstance(dsn, str) or not dsn.strip():
|
|
raise MarketDataStoreValidationError("questdb_dsn must be a non-empty string.")
|
|
self._dsn = dsn
|
|
self._conn: psycopg.Connection[Any] | None = None
|
|
|
|
def _ensure_conn(self) -> psycopg.Connection[Any]:
|
|
if self._conn is None or self._conn.closed:
|
|
try:
|
|
self._conn = psycopg.connect(self._dsn, autocommit=True)
|
|
except Exception as exc:
|
|
safe_msg = _redact_dsn(f"QuestDB connection failed: {exc}", self._dsn)
|
|
raise RuntimeError(safe_msg) from None
|
|
return self._conn
|
|
|
|
def query(self, sql: str, params: Sequence[Any]) -> list[dict[str, Any]]:
|
|
conn = self._ensure_conn()
|
|
try:
|
|
with conn.cursor() as cur:
|
|
cur.execute(sql, tuple(params))
|
|
if cur.description is None:
|
|
return []
|
|
columns = [desc.name for desc in cur.description]
|
|
rows = cur.fetchall()
|
|
return [dict(zip(columns, row)) for row in rows]
|
|
except Exception as exc:
|
|
safe_msg = _redact_dsn(f"QuestDB query failed: {exc}", self._dsn)
|
|
raise RuntimeError(safe_msg) from None
|
|
|
|
def close(self) -> None:
|
|
if self._conn is not None and not self._conn.closed:
|
|
try:
|
|
self._conn.close()
|
|
finally:
|
|
self._conn = None
|
|
|
|
|
|
def _validate_int32_listing_ids(
|
|
raw: Sequence[int],
|
|
*,
|
|
field: str = "listing_ids",
|
|
positive_only: bool = False,
|
|
sort_ascending: bool = False,
|
|
) -> list[int]:
|
|
if isinstance(raw, (str, bytes)) or not isinstance(raw, Sequence) or len(raw) == 0:
|
|
raise MarketDataStoreValidationError(
|
|
f'Expected a non-empty sequence of INT32 listing IDs for "{field}".'
|
|
)
|
|
min_val = 1 if positive_only else _INT32_MIN
|
|
seen: set[int] = set()
|
|
normalized: list[int] = []
|
|
for idx, item in enumerate(raw):
|
|
if isinstance(item, bool) or not isinstance(item, int) or item < min_val or item > _INT32_MAX:
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid INT32 listing ID at {field}[{idx}]: {item!r}."
|
|
)
|
|
if item not in seen:
|
|
seen.add(item)
|
|
normalized.append(item)
|
|
if sort_ascending:
|
|
normalized.sort()
|
|
return normalized
|
|
|
|
|
|
def _validate_non_empty_strings(raw: Sequence[str], field: str) -> list[str]:
|
|
if isinstance(raw, (str, bytes)) or not isinstance(raw, Sequence) or len(raw) == 0:
|
|
raise MarketDataStoreValidationError(
|
|
f'Expected a non-empty sequence of strings for "{field}".'
|
|
)
|
|
seen: set[str] = set()
|
|
out: list[str] = []
|
|
for idx, item in enumerate(raw):
|
|
if not isinstance(item, str) or not item.strip():
|
|
raise MarketDataStoreValidationError(
|
|
f'Expected a non-empty string at {field}[{idx}], got {item!r}.'
|
|
)
|
|
if item not in seen:
|
|
seen.add(item)
|
|
out.append(item)
|
|
return out
|
|
|
|
|
|
def _validate_fundamentals_fields(raw: Sequence[str], field: str = "fields") -> list[str]:
|
|
if isinstance(raw, (str, bytes)) or not isinstance(raw, Sequence) or len(raw) == 0:
|
|
raise MarketDataStoreValidationError(
|
|
f'Expected a non-empty sequence of fundamentals value fields for "{field}".'
|
|
)
|
|
seen: set[str] = set()
|
|
out: list[str] = []
|
|
for item in raw:
|
|
if not isinstance(item, str) or item not in _FUNDAMENTALS_PIT_VALUE_FIELD_SET:
|
|
raise MarketDataStoreValidationError(
|
|
f'Unknown fundamentals field {item!r}. Expected one of: {", ".join(FUNDAMENTALS_PIT_VALUE_FIELDS)}.'
|
|
)
|
|
if item not in seen:
|
|
seen.add(item)
|
|
out.append(item)
|
|
return out
|
|
|
|
|
|
def _parse_questdb_micros(raw: Any, column: str, row_idx: int) -> int:
|
|
if isinstance(raw, int) and not isinstance(raw, bool):
|
|
return raw
|
|
if isinstance(raw, str) and _CANONICAL_SIGNED_INT_RE.match(raw):
|
|
return int(raw)
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid QuestDB timestamp column "{column}" in result row {row_idx}: {raw!r}.'
|
|
)
|
|
|
|
|
|
def _read_required_finite_float(row: Mapping[str, Any], key: str, row_idx: int) -> float:
|
|
val = row.get(key)
|
|
if isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(float(val)):
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid numeric column "{key}" in result row {row_idx}: {val!r}.'
|
|
)
|
|
fval = float(val)
|
|
return 0.0 if fval == 0.0 else fval
|
|
|
|
|
|
def _read_nullable_finite_float(row: Mapping[str, Any], key: str, row_idx: int) -> float | None:
|
|
val = row.get(key)
|
|
if val is None:
|
|
return None
|
|
if isinstance(val, bool) or not isinstance(val, (int, float)) or not math.isfinite(float(val)):
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid nullable numeric column "{key}" in result row {row_idx}: {val!r}.'
|
|
)
|
|
fval = float(val)
|
|
return 0.0 if fval == 0.0 else fval
|
|
|
|
|
|
def _parse_questdb_listing_id(
|
|
row: Mapping[str, Any], row_idx: int, requested_ids: frozenset[int]
|
|
) -> int:
|
|
raw = row.get("listing_id")
|
|
if isinstance(raw, str) and _CANONICAL_POSITIVE_INT_RE.match(raw):
|
|
parsed = int(raw)
|
|
else:
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid bars_1m listing_id SYMBOL in result row {row_idx}: {raw!r}."
|
|
)
|
|
if parsed < 1 or parsed > _INT32_MAX:
|
|
raise MarketDataStoreValidationError(
|
|
f"Out-of-range bars_1m listing_id SYMBOL in result row {row_idx}: {raw!r}."
|
|
)
|
|
if parsed not in requested_ids:
|
|
raise MarketDataStoreValidationError(
|
|
f"Unexpected unrequested listing_id {parsed} in bars_1m result row {row_idx}."
|
|
)
|
|
return parsed
|
|
|
|
|
|
class MarketDataStore:
|
|
"""Vault-fenced DuckDB + Parquet + optional QuestDB reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`."""
|
|
|
|
def __init__(
|
|
self,
|
|
curated_root: str | Path,
|
|
*,
|
|
vault_cutoff_ts: int,
|
|
vault_operator_authorized: bool = False,
|
|
budget: DuckDbConnectionBudget | None = None,
|
|
adj_factors_path: str | Path | None = None,
|
|
questdb_dsn: str | None = None,
|
|
questdb_executor: QuestDbExecutor | None = None,
|
|
) -> None:
|
|
if isinstance(vault_cutoff_ts, bool) or not isinstance(vault_cutoff_ts, int):
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid epoch millisecond timestamp for vault_cutoff_ts: {vault_cutoff_ts!r}."
|
|
)
|
|
if questdb_dsn is not None and questdb_executor is not None:
|
|
raise MarketDataStoreValidationError(
|
|
"Options questdb_dsn and questdb_executor are mutually exclusive."
|
|
)
|
|
if questdb_executor is not None and not isinstance(questdb_executor, QuestDbExecutor):
|
|
raise MarketDataStoreValidationError(
|
|
"Expected questdb_executor implementing query(sql, params) and close()."
|
|
)
|
|
|
|
self.curated_root = validate_curated_root(curated_root)
|
|
self.vault_cutoff_ts = vault_cutoff_ts
|
|
self.vault_operator_authorized = vault_operator_authorized
|
|
self.budget = budget or resolve_duckdb_budget()
|
|
self.adj_factors_path = (
|
|
str(Path(adj_factors_path).resolve())
|
|
if adj_factors_path is not None
|
|
else str(Path(self.curated_root) / "adj_factors" / "part.parquet")
|
|
)
|
|
self._questdb_executor: QuestDbExecutor | None = (
|
|
PsycopgQuestDbExecutor(questdb_dsn) if questdb_dsn is not None else questdb_executor
|
|
)
|
|
|
|
os.makedirs(self.budget.temp_directory, exist_ok=True)
|
|
self._con = duckdb.connect(":memory:")
|
|
self._con.execute("SET TimeZone = 'UTC';")
|
|
for stmt in self.budget.statements:
|
|
self._con.execute(stmt)
|
|
|
|
def close(self) -> None:
|
|
try:
|
|
self._con.close()
|
|
finally:
|
|
if self._questdb_executor is not None:
|
|
self._questdb_executor.close()
|
|
|
|
def __enter__(self) -> "MarketDataStore":
|
|
return self
|
|
|
|
def __exit__(self, *_: object) -> None:
|
|
self.close()
|
|
|
|
def _bars_glob(self) -> str:
|
|
return f"{self.curated_root}/bars_1d/year=*/part.parquet"
|
|
|
|
def _events_glob(self) -> str:
|
|
return f"{self.curated_root}/events/year=*/*.parquet"
|
|
|
|
def _shorts_path(self) -> str:
|
|
return f"{self.curated_root}/shorts/part.parquet"
|
|
|
|
def _fx_path(self) -> str:
|
|
return f"{self.curated_root}/fx_1d/part.parquet"
|
|
|
|
def _fundamentals_pit_glob(self) -> str:
|
|
return f"{self.curated_root}/fundamentals_pit/year=*/part.parquet"
|
|
|
|
def _macro_path(self) -> str:
|
|
return f"{self.curated_root}/macro/part.parquet"
|
|
|
|
def _verify_fenced_adj_factors(self, as_of_micros: int, scope: DataScope) -> str:
|
|
rows = self._con.execute(
|
|
f"SELECT key::VARCHAR AS k, value::VARCHAR AS v FROM parquet_kv_metadata('{self.adj_factors_path}')"
|
|
).fetchall()
|
|
kv = {str(k): str(v) for k, v in rows if str(k).startswith("stock_bot.adj_factors.")}
|
|
kind = kv.get("stock_bot.adj_factors.snapshot_kind")
|
|
if kind != "point_in_time_fenced":
|
|
raise MarketDataStoreValidationError(
|
|
f"Adjusted bars require point_in_time_fenced adj_factors snapshot (got {kind!r} at {self.adj_factors_path})."
|
|
)
|
|
if scope == "vault_fenced":
|
|
raw_vc = kv.get("stock_bot.adj_factors.vault_cutoff_micros")
|
|
expected_vc = self.vault_cutoff_ts * 1000
|
|
if raw_vc is None or raw_vc == "none" or int(raw_vc) > expected_vc:
|
|
raise MarketDataStoreValidationError(
|
|
f"adj_factors vault_cutoff_micros ({raw_vc}) incompatible with store cutoff ({expected_vc})."
|
|
)
|
|
raw_as_of = kv.get("stock_bot.adj_factors.as_of_micros")
|
|
if raw_as_of is not None and raw_as_of != "none" and int(raw_as_of) > as_of_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"adj_factors as_of_micros ({raw_as_of}) exceeds query as_of_micros ({as_of_micros})."
|
|
)
|
|
return self.adj_factors_path
|
|
|
|
def _bars_1m(
|
|
self,
|
|
*,
|
|
listing_ids: Sequence[int] | None,
|
|
currencies: Sequence[str] | None,
|
|
from_date: str,
|
|
to_date: str,
|
|
adjustment: AdjustmentMode,
|
|
as_of: str | None,
|
|
scope: DataScope,
|
|
) -> pl.DataFrame:
|
|
if self._questdb_executor is None:
|
|
raise MarketDataStoreValidationError(
|
|
"Intraday 1m bars require questdb_dsn or questdb_executor to be configured."
|
|
)
|
|
if adjustment in ("split", "total"):
|
|
raise NotImplementedError(
|
|
f"Adjustment {adjustment!r} is not supported for intraday '1m' bars; bars_1m stores raw split-unadjusted values."
|
|
)
|
|
if adjustment != "raw":
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid bars adjustment {adjustment!r}. Expected 'raw'."
|
|
)
|
|
if currencies is not None:
|
|
raise MarketDataStoreValidationError(
|
|
"The currencies filter is not supported for intraday '1m' bars."
|
|
)
|
|
if listing_ids is None:
|
|
raise MarketDataStoreValidationError(
|
|
"Intraday '1m' bars require a non-empty listing_ids sequence."
|
|
)
|
|
sorted_ids = _validate_int32_listing_ids(
|
|
listing_ids, field="listing_ids", positive_only=True, sort_ascending=True
|
|
)
|
|
fenced = apply_vault_fence(
|
|
from_date,
|
|
to_date,
|
|
self.vault_cutoff_ts,
|
|
as_of=as_of,
|
|
scope=scope,
|
|
vault_operator_authorized=self.vault_operator_authorized,
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
placeholders = ", ".join(["%s"] * len(sorted_ids))
|
|
sql = (
|
|
"SELECT listing_id, CAST(ts AS LONG) AS ts_us, open, high, low, close, volume, vwap, "
|
|
"CAST(known_at AS LONG) AS known_at_us "
|
|
"FROM bars_1m "
|
|
f"WHERE ts >= %s AND ts <= %s AND listing_id IN ({placeholders}) AND known_at <= %s "
|
|
"ORDER BY ts, listing_id"
|
|
)
|
|
params: list[str] = [
|
|
format_utc_iso_micros(fenced.from_micros),
|
|
format_utc_iso_micros(fenced.to_micros),
|
|
*(str(lid) for lid in sorted_ids),
|
|
format_utc_iso_micros(fenced.as_of_micros),
|
|
]
|
|
raw_rows = self._questdb_executor.query(sql, params)
|
|
requested_set = frozenset(sorted_ids)
|
|
cutoff_micros = self.vault_cutoff_ts * 1000
|
|
|
|
records: list[dict[str, Any]] = []
|
|
for idx, raw in enumerate(raw_rows):
|
|
if not isinstance(raw, Mapping):
|
|
raise MarketDataStoreValidationError(
|
|
f"QuestDB executor returned a non-mapping bars_1m row at index {idx}."
|
|
)
|
|
lid = _parse_questdb_listing_id(raw, idx, requested_set)
|
|
ts_us = _parse_questdb_micros(raw.get("ts_us"), "ts_us", idx)
|
|
if ts_us < fenced.from_micros or ts_us > fenced.to_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"Row {idx} timestamp ts ({ts_us} us) is outside fenced range [{fenced.from_micros}, {fenced.to_micros}] us."
|
|
)
|
|
if fenced.scope == "vault_fenced" and ts_us >= cutoff_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"Row {idx} timestamp ts ({ts_us} us) violates Vault cutoff ({cutoff_micros} us)."
|
|
)
|
|
known_at_us = _parse_questdb_micros(raw.get("known_at_us"), "known_at_us", idx)
|
|
if known_at_us > fenced.as_of_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"Row {idx} availability known_at ({known_at_us} us) exceeds fenced as_of ({fenced.as_of_micros} us)."
|
|
)
|
|
if fenced.scope == "vault_fenced" and known_at_us >= cutoff_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"Row {idx} availability known_at ({known_at_us} us) violates Vault cutoff ({cutoff_micros} us)."
|
|
)
|
|
records.append(
|
|
{
|
|
"listing_id": lid,
|
|
"ts": epoch_micros_to_datetime(ts_us),
|
|
"open": _read_required_finite_float(raw, "open", idx),
|
|
"high": _read_required_finite_float(raw, "high", idx),
|
|
"low": _read_required_finite_float(raw, "low", idx),
|
|
"close": _read_required_finite_float(raw, "close", idx),
|
|
"volume": _read_required_finite_float(raw, "volume", idx),
|
|
"vwap": _read_nullable_finite_float(raw, "vwap", idx),
|
|
"known_at": epoch_micros_to_datetime(known_at_us),
|
|
}
|
|
)
|
|
|
|
if not records:
|
|
return pl.DataFrame(schema=_BARS_1M_SCHEMA)
|
|
return pl.DataFrame(records, schema=_BARS_1M_SCHEMA)
|
|
|
|
def bars(
|
|
self,
|
|
*,
|
|
listing_ids: Sequence[int] | None = None,
|
|
currencies: Sequence[str] | None = None,
|
|
timeframe: str = "1d",
|
|
from_date: str,
|
|
to_date: str,
|
|
adjustment: AdjustmentMode = "raw",
|
|
as_of: str | None = None,
|
|
scope: DataScope = "vault_fenced",
|
|
) -> pl.DataFrame:
|
|
if timeframe == "1m":
|
|
return self._bars_1m(
|
|
listing_ids=listing_ids,
|
|
currencies=currencies,
|
|
from_date=from_date,
|
|
to_date=to_date,
|
|
adjustment=adjustment,
|
|
as_of=as_of,
|
|
scope=scope,
|
|
)
|
|
if timeframe in ("5m", "1h"):
|
|
raise NotImplementedError(f"Timeframe {timeframe!r} is not supported.")
|
|
if timeframe != "1d":
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid bars timeframe {timeframe!r}. Expected '1d' or '1m'."
|
|
)
|
|
|
|
fenced = apply_vault_fence(
|
|
from_date,
|
|
to_date,
|
|
self.vault_cutoff_ts,
|
|
as_of=as_of,
|
|
scope=scope,
|
|
vault_operator_authorized=self.vault_operator_authorized,
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
from_ts = epoch_micros_to_datetime(fenced.from_micros)
|
|
to_ts = epoch_micros_to_datetime(fenced.to_micros)
|
|
as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros)
|
|
|
|
where = ["b.ts >= ?", "b.ts <= ?", "b.known_at <= ?"]
|
|
params: list[object] = [from_ts, to_ts, as_of_ts]
|
|
if listing_ids is not None:
|
|
if len(listing_ids) == 0:
|
|
return pl.DataFrame()
|
|
placeholders = ", ".join(["?"] * len(listing_ids))
|
|
where.append(f"b.listing_id IN ({placeholders})")
|
|
params.extend(int(x) for x in listing_ids)
|
|
if currencies is not None:
|
|
placeholders = ", ".join(["?"] * len(currencies))
|
|
where.append(f"b.currency IN ({placeholders})")
|
|
params.extend(str(c) for c in currencies)
|
|
|
|
where_sql = " AND ".join(where)
|
|
if adjustment == "raw":
|
|
sql = f"""
|
|
SELECT
|
|
b.listing_id,
|
|
b.session_date,
|
|
b.ts,
|
|
b.open,
|
|
b.high,
|
|
b.low,
|
|
b.close,
|
|
b.volume,
|
|
b.vwap,
|
|
b.currency,
|
|
b.source,
|
|
b.known_at
|
|
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b
|
|
WHERE {where_sql}
|
|
ORDER BY b.listing_id ASC, b.session_date ASC
|
|
"""
|
|
return self._con.execute(sql, params).pl()
|
|
|
|
adj_path = self._verify_fenced_adj_factors(fenced.as_of_micros, fenced.scope)
|
|
price_col = "cum_split_factor" if adjustment == "split" else "cum_total_factor"
|
|
sql = f"""
|
|
WITH adj AS (
|
|
SELECT listing_id, ex_date, cum_split_factor, cum_total_factor
|
|
FROM read_parquet('{adj_path}')
|
|
WHERE known_at <= ?
|
|
)
|
|
SELECT
|
|
b.listing_id,
|
|
b.session_date,
|
|
b.ts,
|
|
b.open / COALESCE(a.{price_col}, 1.0) AS open,
|
|
b.high / COALESCE(a.{price_col}, 1.0) AS high,
|
|
b.low / COALESCE(a.{price_col}, 1.0) AS low,
|
|
b.close / COALESCE(a.{price_col}, 1.0) AS close,
|
|
b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume,
|
|
CASE WHEN b.vwap IS NULL THEN NULL ELSE b.vwap / COALESCE(a.{price_col}, 1.0) END AS vwap,
|
|
b.currency,
|
|
b.source,
|
|
b.known_at
|
|
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b
|
|
ASOF LEFT JOIN adj a
|
|
ON b.listing_id = a.listing_id AND b.session_date < a.ex_date
|
|
WHERE {where_sql}
|
|
ORDER BY b.listing_id ASC, b.session_date ASC
|
|
"""
|
|
return self._con.execute(sql, [as_of_ts, *params]).pl()
|
|
|
|
def fundamentals_as_of(
|
|
self,
|
|
*,
|
|
listing_ids: Sequence[int],
|
|
fields: Sequence[str],
|
|
as_of: str,
|
|
allow_estimated_lag: bool = True,
|
|
) -> pl.DataFrame:
|
|
"""Vault-fenced 2D PIT fundamentals reader over `fundamentals_pit/year=*/part.parquet`.
|
|
|
|
Selects at most one snapshot per requested `listing_id` — the latest with
|
|
`effective_known_at <= as_of` (clamped strictly below `vault_cutoff_ts * 1000` µs).
|
|
When `allow_estimated_lag=False`, listings whose latest snapshot has
|
|
`has_estimated_lag = true` are omitted without falling back to older snapshots, and
|
|
requested `ttm_*` value fields plus `ttm_period_end`/`ttm_currency` are masked to
|
|
NULL when `ttm_has_estimated_lag` is true while preserving `ttm_has_estimated_lag`.
|
|
"""
|
|
valid_ids = _validate_int32_listing_ids(listing_ids, field="listing_ids")
|
|
valid_fields = _validate_fundamentals_fields(fields, field="fields")
|
|
if not isinstance(allow_estimated_lag, bool):
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid allow_estimated_lag {allow_estimated_lag!r}. Expected a bool."
|
|
)
|
|
|
|
try:
|
|
fenced = apply_vault_fence(
|
|
as_of,
|
|
as_of,
|
|
self.vault_cutoff_ts,
|
|
as_of=as_of,
|
|
scope="vault_fenced",
|
|
)
|
|
assert fenced.as_of_micros is not None
|
|
effective_as_of_micros = fenced.as_of_micros
|
|
except VaultHoldoutFenceError:
|
|
effective_as_of_micros = self.vault_cutoff_ts * 1000 - 1
|
|
|
|
as_of_iso = format_utc_iso_micros(effective_as_of_micros)
|
|
has_ttm_field = any(f in _FUNDAMENTALS_TTM_VALUE_FIELD_SET for f in valid_fields)
|
|
|
|
inner_cols: list[str] = [
|
|
"f.listing_id",
|
|
"f.effective_known_at",
|
|
"f.known_at_source",
|
|
"f.has_estimated_lag",
|
|
"f.period_end",
|
|
"f.fiscal_period",
|
|
"f.currency",
|
|
"f.period_known_at",
|
|
]
|
|
outer_cols: list[str] = [
|
|
"s.listing_id",
|
|
"s.effective_known_at",
|
|
"s.known_at_source",
|
|
"s.has_estimated_lag",
|
|
"s.period_end",
|
|
"s.fiscal_period",
|
|
"s.currency",
|
|
"s.period_known_at",
|
|
]
|
|
|
|
for field in valid_fields:
|
|
inner_cols.append(f"f.{field}")
|
|
if field in _FUNDAMENTALS_TTM_VALUE_FIELD_SET:
|
|
outer_cols.append(
|
|
f"CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.{field} ELSE NULL END AS {field}"
|
|
)
|
|
else:
|
|
outer_cols.append(f"s.{field}")
|
|
|
|
if has_ttm_field:
|
|
inner_cols.extend(["f.ttm_period_end", "f.ttm_currency", "f.ttm_has_estimated_lag"])
|
|
outer_cols.extend(
|
|
[
|
|
"CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_period_end ELSE NULL END AS ttm_period_end",
|
|
"CASE WHEN opts.allow_estimated_lag OR NOT COALESCE(s.ttm_has_estimated_lag, FALSE) THEN s.ttm_currency ELSE NULL END AS ttm_currency",
|
|
"s.ttm_has_estimated_lag",
|
|
]
|
|
)
|
|
|
|
lid_ph = ", ".join(["?"] * len(valid_ids))
|
|
sql = (
|
|
f"WITH latest AS (SELECT {', '.join(inner_cols)} "
|
|
"FROM read_parquet(?, hive_partitioning = true) AS f "
|
|
f"WHERE f.listing_id IN ({lid_ph}) AND f.effective_known_at <= CAST(? AS TIMESTAMPTZ) "
|
|
"QUALIFY ROW_NUMBER() OVER (PARTITION BY f.listing_id ORDER BY f.effective_known_at DESC) = 1) "
|
|
f"SELECT {', '.join(outer_cols)} "
|
|
"FROM latest AS s "
|
|
"CROSS JOIN (SELECT CAST(? AS BOOLEAN) AS allow_estimated_lag) AS opts "
|
|
"WHERE (opts.allow_estimated_lag OR NOT s.has_estimated_lag) "
|
|
"ORDER BY s.listing_id ASC"
|
|
)
|
|
params: list[object] = [
|
|
self._fundamentals_pit_glob(),
|
|
*valid_ids,
|
|
as_of_iso,
|
|
allow_estimated_lag,
|
|
]
|
|
return self._con.execute(sql, params).pl()
|
|
|
|
def macro_as_of(
|
|
self,
|
|
*,
|
|
countries: Sequence[str],
|
|
indicators: Sequence[str],
|
|
from_date: str,
|
|
to_date: str,
|
|
as_of: str | None = None,
|
|
) -> pl.DataFrame:
|
|
"""Vault-fenced lagged macro reader over `macro/part.parquet` (coarse regime filters only).
|
|
|
|
`teData` stores final-revised macro values without release vintages; `curate-macro`
|
|
applies statutory lag classes (+1d policy rates, +35d monthly, +65d/+90d GDP) into
|
|
`known_at` so this reader is suitable for coarse regime filters only, never
|
|
release-day surprise trading (`design/DATA-CONTRACTS.md` §1).
|
|
"""
|
|
valid_countries = _validate_non_empty_strings(countries, "countries")
|
|
valid_indicators = _validate_non_empty_strings(indicators, "indicators")
|
|
fenced = apply_vault_fence(
|
|
from_date,
|
|
to_date,
|
|
self.vault_cutoff_ts,
|
|
as_of=as_of,
|
|
scope="vault_fenced",
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
from_d = epoch_micros_to_datetime(fenced.from_micros).date()
|
|
to_d = epoch_micros_to_datetime(fenced.to_micros).date()
|
|
as_of_iso = format_utc_iso_micros(fenced.as_of_micros)
|
|
|
|
country_ph = ", ".join(["?"] * len(valid_countries))
|
|
indicator_ph = ", ".join(["?"] * len(valid_indicators))
|
|
sql = (
|
|
"SELECT m.country_iso, m.indicator, m.period_date, m.known_at, m.known_at_source, m.value "
|
|
"FROM read_parquet(?) AS m "
|
|
f"WHERE m.country_iso IN ({country_ph}) "
|
|
f"AND m.indicator IN ({indicator_ph}) "
|
|
"AND m.period_date >= ? "
|
|
"AND m.period_date <= ? "
|
|
"AND m.known_at <= CAST(? AS TIMESTAMPTZ) "
|
|
"ORDER BY m.country_iso ASC, m.indicator ASC, m.period_date ASC"
|
|
)
|
|
params: list[object] = [
|
|
self._macro_path(),
|
|
*valid_countries,
|
|
*valid_indicators,
|
|
from_d,
|
|
to_d,
|
|
as_of_iso,
|
|
]
|
|
return self._con.execute(sql, params).pl()
|
|
|
|
def shorts_as_of(
|
|
self,
|
|
*,
|
|
listing_ids: Sequence[int] | None = None,
|
|
from_date: str,
|
|
to_date: str,
|
|
as_of: str | None = None,
|
|
) -> pl.DataFrame:
|
|
fenced = apply_vault_fence(
|
|
from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced"
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
from_d = epoch_micros_to_datetime(fenced.from_micros).date()
|
|
to_d = epoch_micros_to_datetime(fenced.to_micros).date()
|
|
as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros)
|
|
|
|
where = ["report_date >= ?", "report_date <= ?", "known_at <= ?"]
|
|
params: list[object] = [from_d, to_d, as_of_ts]
|
|
if listing_ids is not None:
|
|
if len(listing_ids) == 0:
|
|
return pl.DataFrame()
|
|
placeholders = ", ".join(["?"] * len(listing_ids))
|
|
where.append(f"listing_id IN ({placeholders})")
|
|
params.extend(int(x) for x in listing_ids)
|
|
|
|
sql = f"""
|
|
SELECT listing_id, report_date, known_at, shares_short, net_change, pct_float, source
|
|
FROM read_parquet('{self._shorts_path()}')
|
|
WHERE {' AND '.join(where)}
|
|
ORDER BY listing_id ASC, report_date ASC
|
|
"""
|
|
return self._con.execute(sql, params).pl()
|
|
|
|
def events(
|
|
self,
|
|
*,
|
|
kinds: Sequence[EventKind],
|
|
listing_ids: Sequence[int] | None = None,
|
|
from_date: str,
|
|
to_date: str,
|
|
as_of: str | None = None,
|
|
) -> pl.DataFrame:
|
|
if not kinds:
|
|
raise MarketDataStoreValidationError("events requires at least one kind.")
|
|
for k in kinds:
|
|
if k not in _EVENT_KIND_SET:
|
|
raise MarketDataStoreValidationError(
|
|
f"Unknown EventKind {k!r}. Expected one of: {', '.join(_EVENT_KINDS)}."
|
|
)
|
|
fenced = apply_vault_fence(
|
|
from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced"
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
from_ts = epoch_micros_to_datetime(fenced.from_micros)
|
|
to_ts = epoch_micros_to_datetime(fenced.to_micros)
|
|
as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros)
|
|
|
|
kind_ph = ", ".join(["?"] * len(kinds))
|
|
where = [f"kind IN ({kind_ph})", "ts >= ?", "ts <= ?", "known_at <= ?"]
|
|
params: list[object] = [*kinds, from_ts, to_ts, as_of_ts]
|
|
if listing_ids is not None:
|
|
if len(listing_ids) == 0:
|
|
return pl.DataFrame()
|
|
lid_ph = ", ".join(["?"] * len(listing_ids))
|
|
where.append(f"listing_id IN ({lid_ph})")
|
|
params.extend(int(x) for x in listing_ids)
|
|
|
|
sql = f"""
|
|
SELECT listing_id, ts, known_at, known_at_source, kind, subtype, payload_json
|
|
FROM read_parquet('{self._events_glob()}', hive_partitioning = true)
|
|
WHERE {' AND '.join(where)}
|
|
ORDER BY listing_id ASC, ts ASC, kind ASC, subtype ASC, payload_json ASC, known_at ASC, known_at_source ASC
|
|
"""
|
|
return self._con.execute(sql, params).pl()
|
|
|
|
def _fx_1m(
|
|
self,
|
|
*,
|
|
from_date: str,
|
|
to_date: str,
|
|
as_of: str | None,
|
|
) -> pl.DataFrame:
|
|
if self._questdb_executor is None:
|
|
raise MarketDataStoreValidationError(
|
|
"Intraday 1m FX requires questdb_dsn or questdb_executor to be configured."
|
|
)
|
|
fenced = apply_vault_fence(
|
|
from_date,
|
|
to_date,
|
|
self.vault_cutoff_ts,
|
|
as_of=as_of,
|
|
scope="vault_fenced",
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
cutoff_micros = self.vault_cutoff_ts * 1000
|
|
# fx_1m stores bar-start `ts` with no `known_at` column; enforce bar-close availability
|
|
# (`bar_close = ts + 60s` strictly < vault_cutoff_ts and <= effective as_of).
|
|
max_bar_close_micros = min(fenced.as_of_micros, cutoff_micros - 1)
|
|
max_ts_micros = min(fenced.to_micros, max_bar_close_micros - _FX_1M_BAR_DURATION_MICROS)
|
|
if max_ts_micros < fenced.from_micros:
|
|
return pl.DataFrame(schema=_FX_1M_SCHEMA)
|
|
|
|
sql = (
|
|
"SELECT pair, CAST(ts AS LONG) AS ts_us, open, high, low, close, source "
|
|
"FROM fx_1m "
|
|
"WHERE pair = %s AND ts >= %s AND ts <= %s "
|
|
"ORDER BY ts ASC"
|
|
)
|
|
params = [
|
|
"USDCAD",
|
|
format_utc_iso_micros(fenced.from_micros),
|
|
format_utc_iso_micros(max_ts_micros),
|
|
]
|
|
raw_rows = self._questdb_executor.query(sql, params)
|
|
records: list[dict[str, Any]] = []
|
|
for idx, raw in enumerate(raw_rows):
|
|
if not isinstance(raw, Mapping):
|
|
raise MarketDataStoreValidationError(
|
|
f"QuestDB executor returned a non-mapping fx_1m row at index {idx}."
|
|
)
|
|
row_pair = raw.get("pair")
|
|
if row_pair != "USDCAD":
|
|
raise MarketDataStoreValidationError(
|
|
f"Unexpected fx_1m pair {row_pair!r} in result row {idx}; expected 'USDCAD'."
|
|
)
|
|
ts_us = _parse_questdb_micros(raw.get("ts_us"), "ts_us", idx)
|
|
bar_close_us = ts_us + _FX_1M_BAR_DURATION_MICROS
|
|
if ts_us < fenced.from_micros or ts_us > fenced.to_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"Row {idx} fx_1m timestamp ts ({ts_us} us) is outside fenced range [{fenced.from_micros}, {fenced.to_micros}] us."
|
|
)
|
|
if bar_close_us >= cutoff_micros or bar_close_us > fenced.as_of_micros:
|
|
raise MarketDataStoreValidationError(
|
|
f"Row {idx} fx_1m bar_close ({bar_close_us} us) exceeds availability fence (as_of={fenced.as_of_micros} us, cutoff={cutoff_micros} us)."
|
|
)
|
|
source = raw.get("source")
|
|
if not isinstance(source, str) or not source:
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid fx_1m source in result row {idx}: {source!r}."
|
|
)
|
|
records.append(
|
|
{
|
|
"pair": row_pair,
|
|
"ts": epoch_micros_to_datetime(ts_us),
|
|
"open": _read_required_finite_float(raw, "open", idx),
|
|
"high": _read_required_finite_float(raw, "high", idx),
|
|
"low": _read_required_finite_float(raw, "low", idx),
|
|
"close": _read_required_finite_float(raw, "close", idx),
|
|
"source": source,
|
|
"known_at": epoch_micros_to_datetime(bar_close_us),
|
|
}
|
|
)
|
|
|
|
if not records:
|
|
return pl.DataFrame(schema=_FX_1M_SCHEMA)
|
|
return pl.DataFrame(records, schema=_FX_1M_SCHEMA)
|
|
|
|
def fx(
|
|
self,
|
|
*,
|
|
pair: str = "USD.CAD",
|
|
timeframe: str = "1d",
|
|
from_date: str,
|
|
to_date: str,
|
|
as_of: str | None = None,
|
|
) -> pl.DataFrame:
|
|
if pair != "USD.CAD":
|
|
raise MarketDataStoreValidationError(f"Unsupported FX pair: {pair!r}")
|
|
if timeframe == "1m":
|
|
return self._fx_1m(from_date=from_date, to_date=to_date, as_of=as_of)
|
|
if timeframe != "1d":
|
|
raise MarketDataStoreValidationError(
|
|
f"Unsupported FX timeframe {timeframe!r}. Expected '1d' or '1m'."
|
|
)
|
|
fenced = apply_vault_fence(
|
|
from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced"
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
from_ts = epoch_micros_to_datetime(fenced.from_micros)
|
|
to_ts = epoch_micros_to_datetime(fenced.to_micros)
|
|
as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros)
|
|
sql = f"""
|
|
SELECT pair, session_date, ts, open, high, low, close, source, known_at
|
|
FROM read_parquet('{self._fx_path()}')
|
|
WHERE pair = 'USDCAD' AND ts >= ? AND ts <= ? AND known_at <= ?
|
|
ORDER BY session_date ASC
|
|
"""
|
|
return self._con.execute(sql, [from_ts, to_ts, as_of_ts]).pl()
|
|
|
|
def universe(self, *, ref: UniverseRef, on_date: str, lookback_days: int = 7) -> list[int]:
|
|
if ref not in _UNIVERSE_CURRENCIES:
|
|
raise MarketDataStoreValidationError(f"Unsupported universe ref: {ref!r}")
|
|
if not isinstance(on_date, str) or not _DATE_ONLY_RE.match(on_date):
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid universe date "{on_date}". Expected a UTC calendar date in YYYY-MM-DD format.'
|
|
)
|
|
fenced = apply_vault_fence(
|
|
on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced"
|
|
)
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
end_d = date.fromisoformat(on_date)
|
|
start_d = end_d - timedelta(days=lookback_days)
|
|
to_ts = epoch_micros_to_datetime(fenced.to_micros)
|
|
as_of_ts = epoch_micros_to_datetime(fenced.as_of_micros)
|
|
currencies = _UNIVERSE_CURRENCIES[ref]
|
|
ph = ", ".join(["?"] * len(currencies))
|
|
sql = f"""
|
|
SELECT DISTINCT listing_id
|
|
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true)
|
|
WHERE currency IN ({ph})
|
|
AND session_date >= ?
|
|
AND session_date <= ?
|
|
AND ts <= ?
|
|
AND known_at <= ?
|
|
ORDER BY listing_id ASC
|
|
"""
|
|
rows = self._con.execute(sql, [*currencies, start_d, end_d, to_ts, as_of_ts]).fetchall()
|
|
return [int(r[0]) for r in rows]
|
|
|
|
def cross_section(
|
|
self,
|
|
*,
|
|
features: Sequence[str],
|
|
date: str,
|
|
universe: UniverseRef,
|
|
as_of: str | None = None,
|
|
lookback_days: int = 7,
|
|
) -> pl.DataFrame:
|
|
"""Vault-fenced survivorship-free cross-section over materialized feature Parquet partitions.
|
|
|
|
Reads `<curated_root>/features/<name>/v<version>/year=*/part.parquet` for each canonical
|
|
`<name>@v<version>` ref and `LEFT JOIN`s against the active universe on `date`, preserving
|
|
NULLs for listings missing a feature observation and ordering by `listing_id ASC`.
|
|
"""
|
|
if isinstance(features, (str, bytes)) or not isinstance(features, Sequence) or len(features) == 0:
|
|
raise MarketDataStoreValidationError(
|
|
'Expected a non-empty sequence of canonical "<name>@v<version>" feature refs.'
|
|
)
|
|
if universe not in _UNIVERSE_CURRENCIES:
|
|
raise MarketDataStoreValidationError(
|
|
f"Unsupported universe ref: {universe!r}. Expected one of: US_EQ, CA_EQ, US_CA_EQ."
|
|
)
|
|
if not isinstance(date, str) or not _DATE_ONLY_RE.match(date):
|
|
raise MarketDataStoreValidationError(
|
|
f'Invalid cross_section date "{date}". Expected a UTC calendar date in YYYY-MM-DD format.'
|
|
)
|
|
if isinstance(lookback_days, bool) or not isinstance(lookback_days, int) or lookback_days < 1:
|
|
raise MarketDataStoreValidationError(
|
|
f"Invalid lookback_days {lookback_days!r}. Expected a positive integer."
|
|
)
|
|
|
|
parsed_refs: list[tuple[str, str, int]] = []
|
|
seen_refs: set[str] = set()
|
|
for raw_ref in features:
|
|
try:
|
|
parts = parse_feature_ref(raw_ref)
|
|
except FeatureLibraryError as exc:
|
|
raise MarketDataStoreValidationError(str(exc)) from exc
|
|
canonical = f"{parts.name}@v{parts.version}"
|
|
if canonical not in seen_refs:
|
|
seen_refs.add(canonical)
|
|
parsed_refs.append((canonical, parts.name, parts.version))
|
|
|
|
fenced = apply_vault_fence(
|
|
date,
|
|
date,
|
|
self.vault_cutoff_ts,
|
|
as_of=as_of,
|
|
scope="vault_fenced",
|
|
)
|
|
assert fenced.from_micros is not None
|
|
assert fenced.to_micros is not None
|
|
assert fenced.as_of_micros is not None
|
|
|
|
end_d = epoch_micros_to_datetime(fenced.to_micros).date()
|
|
start_d = end_d - timedelta(days=lookback_days)
|
|
from_iso = format_utc_iso_micros(fenced.from_micros)
|
|
to_iso = format_utc_iso_micros(fenced.to_micros)
|
|
as_of_iso = format_utc_iso_micros(fenced.as_of_micros)
|
|
universe_known_at_iso = format_utc_iso_micros(min(fenced.to_micros, fenced.as_of_micros))
|
|
|
|
currencies = _UNIVERSE_CURRENCIES[universe]
|
|
curr_ph = ", ".join(["?"] * len(currencies))
|
|
|
|
ctes: list[str] = [
|
|
(
|
|
"u AS ("
|
|
"SELECT DISTINCT b.listing_id "
|
|
f"FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) AS b "
|
|
f"WHERE b.currency IN ({curr_ph}) "
|
|
"AND b.session_date >= ? "
|
|
"AND b.session_date <= ? "
|
|
"AND b.ts <= CAST(? AS TIMESTAMPTZ) "
|
|
"AND b.known_at <= CAST(? AS TIMESTAMPTZ)"
|
|
")"
|
|
)
|
|
]
|
|
params: list[object] = [
|
|
*currencies,
|
|
start_d,
|
|
end_d,
|
|
to_iso,
|
|
universe_known_at_iso,
|
|
]
|
|
select_cols: list[str] = ["CAST(u.listing_id AS INTEGER) AS listing_id"]
|
|
joins: list[str] = []
|
|
|
|
for idx, (canonical_ref, name, version) in enumerate(parsed_refs):
|
|
alias = f"f_{idx}"
|
|
feat_glob = f"{self.curated_root}/features/{name}/v{version}/year=*/part.parquet"
|
|
ctes.append(
|
|
f"{alias} AS ("
|
|
"SELECT listing_id, CAST(value AS DOUBLE) AS value "
|
|
f"FROM read_parquet('{feat_glob}', hive_partitioning = true) "
|
|
"WHERE ts >= CAST(? AS TIMESTAMPTZ) "
|
|
"AND ts <= CAST(? AS TIMESTAMPTZ) "
|
|
"AND known_at <= CAST(? AS TIMESTAMPTZ) "
|
|
"QUALIFY ROW_NUMBER() OVER (PARTITION BY listing_id ORDER BY ts DESC, known_at DESC) = 1"
|
|
")"
|
|
)
|
|
params.extend([from_iso, to_iso, as_of_iso])
|
|
escaped_col = canonical_ref.replace('"', '""')
|
|
select_cols.append(f'{alias}.value AS "{escaped_col}"')
|
|
joins.append(f"LEFT JOIN {alias} ON u.listing_id = {alias}.listing_id")
|
|
|
|
sql = (
|
|
f"WITH {', '.join(ctes)} "
|
|
f"SELECT {', '.join(select_cols)} "
|
|
f"FROM u {' '.join(joins)} "
|
|
"ORDER BY u.listing_id ASC"
|
|
)
|
|
return self._con.execute(sql, params).pl()
|