T-212: merge dev
This commit is contained in:
commit
60ab228207
11 changed files with 5319 additions and 87 deletions
|
|
@ -1,6 +1,6 @@
|
|||
"""Stock Bot Python Research SDK (`stockbot`)."""
|
||||
|
||||
from . import data
|
||||
from . import data, features
|
||||
from .calculations import (
|
||||
DSR_VALIDATION_GATE,
|
||||
EULER_MASCHERONI,
|
||||
|
|
@ -18,7 +18,26 @@ from .calculations import (
|
|||
newey_west_mean_test,
|
||||
trial_moments,
|
||||
)
|
||||
from .data import MarketDataStore
|
||||
from .data import MarketDataStore, PsycopgQuestDbExecutor, QuestDbExecutor
|
||||
from .features import (
|
||||
RET_1D_V1,
|
||||
FeatureBatchManifest,
|
||||
FeatureBatchWriteReceipt,
|
||||
FeatureDefinition,
|
||||
FeatureLibraryError,
|
||||
FeatureRefParts,
|
||||
FeatureRegistry,
|
||||
PlannedFeatureWrite,
|
||||
RegisteredFeature,
|
||||
create_feature_registry,
|
||||
feature_definition_hash,
|
||||
feature_ref,
|
||||
parse_feature_ref,
|
||||
plan_feature_batch,
|
||||
register_signal,
|
||||
run_feature_batch,
|
||||
validate_feature_definition,
|
||||
)
|
||||
from .ledger import (
|
||||
ClusterDsrSummary,
|
||||
RecordedTrial,
|
||||
|
|
@ -43,7 +62,27 @@ from .vault import (
|
|||
|
||||
__all__ = [
|
||||
"data",
|
||||
"features",
|
||||
"MarketDataStore",
|
||||
"QuestDbExecutor",
|
||||
"PsycopgQuestDbExecutor",
|
||||
"register_signal",
|
||||
"create_feature_registry",
|
||||
"FeatureDefinition",
|
||||
"RegisteredFeature",
|
||||
"FeatureRefParts",
|
||||
"PlannedFeatureWrite",
|
||||
"FeatureBatchWriteReceipt",
|
||||
"FeatureBatchManifest",
|
||||
"FeatureRegistry",
|
||||
"FeatureLibraryError",
|
||||
"RET_1D_V1",
|
||||
"feature_ref",
|
||||
"parse_feature_ref",
|
||||
"feature_definition_hash",
|
||||
"validate_feature_definition",
|
||||
"plan_feature_batch",
|
||||
"run_feature_batch",
|
||||
"TrialLedgerClient",
|
||||
"RecordedTrial",
|
||||
"ClusterDsrSummary",
|
||||
|
|
|
|||
|
|
@ -1,36 +1,280 @@
|
|||
"""Vault-fenced DuckDB + Polars `MarketDataStore` for curated Hive Parquet."""
|
||||
"""Vault-fenced DuckDB + Polars + optional QuestDB `MarketDataStore` for curated datasets."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
import os
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
import re
|
||||
from datetime import date, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Literal, Sequence
|
||||
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 reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`."""
|
||||
"""Vault-fenced DuckDB + Parquet + optional QuestDB reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
|
|
@ -40,8 +284,23 @@ class MarketDataStore:
|
|||
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:
|
||||
self.curated_root = str(Path(curated_root).resolve())
|
||||
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()
|
||||
|
|
@ -50,13 +309,22 @@ class MarketDataStore:
|
|||
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:
|
||||
self._con.close()
|
||||
try:
|
||||
self._con.close()
|
||||
finally:
|
||||
if self._questdb_executor is not None:
|
||||
self._questdb_executor.close()
|
||||
|
||||
def __enter__(self) -> "MarketDataStore":
|
||||
return self
|
||||
|
|
@ -76,6 +344,12 @@ class MarketDataStore:
|
|||
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}')"
|
||||
|
|
@ -100,6 +374,113 @@ class MarketDataStore:
|
|||
)
|
||||
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,
|
||||
*,
|
||||
|
|
@ -112,8 +493,23 @@ class MarketDataStore:
|
|||
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 NotImplementedError(f"Timeframe {timeframe!r} is reserved for QuestDB (M2).")
|
||||
raise MarketDataStoreValidationError(
|
||||
f"Invalid bars timeframe {timeframe!r}. Expected '1d' or '1m'."
|
||||
)
|
||||
|
||||
fenced = apply_vault_fence(
|
||||
from_date,
|
||||
to_date,
|
||||
|
|
@ -122,9 +518,13 @@ class MarketDataStore:
|
|||
scope=scope,
|
||||
vault_operator_authorized=self.vault_operator_authorized,
|
||||
)
|
||||
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
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]
|
||||
|
|
@ -190,6 +590,161 @@ class MarketDataStore:
|
|||
"""
|
||||
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,
|
||||
*,
|
||||
|
|
@ -198,10 +753,16 @@ class MarketDataStore:
|
|||
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")
|
||||
from_d = datetime.fromtimestamp(fenced.from_ms / 1000.0, tz=timezone.utc).date()
|
||||
to_d = datetime.fromtimestamp(fenced.to_ms / 1000.0, tz=timezone.utc).date()
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
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]
|
||||
|
|
@ -231,10 +792,21 @@ class MarketDataStore:
|
|||
) -> pl.DataFrame:
|
||||
if not kinds:
|
||||
raise MarketDataStoreValidationError("events requires at least one kind.")
|
||||
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced")
|
||||
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
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 <= ?"]
|
||||
|
|
@ -254,15 +826,118 @@ class MarketDataStore:
|
|||
"""
|
||||
return self._con.execute(sql, params).pl()
|
||||
|
||||
def fx(self, *, pair: str = "USD.CAD", timeframe: str = "1d", from_date: str, to_date: str) -> pl.DataFrame:
|
||||
if timeframe != "1d":
|
||||
raise NotImplementedError("FX intraday 1m is reserved for QuestDB (M2).")
|
||||
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}")
|
||||
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, scope="vault_fenced")
|
||||
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
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()}')
|
||||
|
|
@ -274,11 +949,20 @@ class MarketDataStore:
|
|||
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}")
|
||||
fenced = apply_vault_fence(on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced")
|
||||
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 = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
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"""
|
||||
|
|
@ -293,3 +977,117 @@ class MarketDataStore:
|
|||
"""
|
||||
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()
|
||||
|
|
|
|||
2254
python/stockbot/features.py
Normal file
2254
python/stockbot/features.py
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -7,6 +7,7 @@ from typing import Any, Mapping
|
|||
import polars as pl
|
||||
|
||||
from .calculations import analyze_signal_panel, compute_event_study
|
||||
from .features import register_signal
|
||||
from .ledger import (
|
||||
ClusterDsrSummary,
|
||||
HorizonBucket,
|
||||
|
|
|
|||
|
|
@ -6,7 +6,8 @@ import calendar
|
|||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Literal, Mapping
|
||||
|
||||
DataScope = Literal["vault_fenced", "vault_evaluation_only"]
|
||||
|
|
@ -15,7 +16,11 @@ DEFAULT_DUCKDB_MEMORY_LIMIT = "6GB"
|
|||
DEFAULT_DUCKDB_THREADS = 4
|
||||
DEFAULT_DUCKDB_TEMP_DIRECTORY = "/mnt/data/stockbot/tmp/duckdb"
|
||||
|
||||
_EPOCH_UTC = datetime(1970, 1, 1, tzinfo=timezone.utc)
|
||||
_DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
|
||||
_ISO_INSTANT_RE = re.compile(
|
||||
r"^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|([+-])(\d{2}):(\d{2}))$"
|
||||
)
|
||||
_MEM_LIMIT_RE = re.compile(r"^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$")
|
||||
|
||||
|
||||
|
|
@ -47,19 +52,25 @@ class FencedTimeRange:
|
|||
scope: DataScope
|
||||
clamped_to: bool
|
||||
clamped_as_of: bool
|
||||
from_micros: int | None = None
|
||||
to_micros: int | None = None
|
||||
as_of_micros: int | None = None
|
||||
|
||||
@property
|
||||
def from_micros(self) -> int:
|
||||
return self.from_ms * 1000
|
||||
|
||||
@property
|
||||
def to_micros(self) -> int:
|
||||
# Expand end-of-ms inclusive boundary to last microsecond (.999999) when ms ends in 999
|
||||
return self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0)
|
||||
|
||||
@property
|
||||
def as_of_micros(self) -> int:
|
||||
return self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0)
|
||||
def __post_init__(self) -> None:
|
||||
if self.from_micros is None:
|
||||
object.__setattr__(self, "from_micros", self.from_ms * 1000)
|
||||
if self.to_micros is None:
|
||||
object.__setattr__(
|
||||
self,
|
||||
"to_micros",
|
||||
self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0),
|
||||
)
|
||||
if self.as_of_micros is None:
|
||||
object.__setattr__(
|
||||
self,
|
||||
"as_of_micros",
|
||||
self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0),
|
||||
)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
|
|
@ -78,30 +89,76 @@ class DuckDbConnectionBudget:
|
|||
)
|
||||
|
||||
|
||||
def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
|
||||
def _datetime_to_epoch_micros(dt: datetime) -> int:
|
||||
delta = dt.astimezone(timezone.utc) - _EPOCH_UTC
|
||||
return (delta.days * 86_400 + delta.seconds) * 1_000_000 + delta.microseconds
|
||||
|
||||
|
||||
def epoch_micros_to_datetime(micros: int) -> datetime:
|
||||
"""Converts exact UTC epoch microseconds to a timezone-aware UTC datetime without float rounding."""
|
||||
return _EPOCH_UTC + timedelta(microseconds=micros)
|
||||
|
||||
|
||||
def format_utc_iso_micros(micros: int) -> str:
|
||||
"""Formats exact UTC epoch microseconds as ISO-8601 UTC string."""
|
||||
dt = epoch_micros_to_datetime(micros)
|
||||
if dt.microsecond % 1000 == 0:
|
||||
ms = dt.microsecond // 1000
|
||||
return dt.strftime("%Y-%m-%dT%H:%M:%S") + f".{ms:03d}Z"
|
||||
return dt.strftime("%Y-%m-%dT%H:%M:%S") + f".{dt.microsecond:06d}Z"
|
||||
|
||||
|
||||
def parse_timestamp_micros(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
|
||||
"""Parses a UTC ISO-8601 date or timestamp into exact integer epoch microseconds."""
|
||||
if not isinstance(raw, str) or not raw:
|
||||
raise MarketDataStoreValidationError(f'Expected non-empty ISO-8601 string for "{field}".')
|
||||
|
||||
m = _DATE_ONLY_RE.match(raw)
|
||||
if m:
|
||||
year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
if bound_kind == "start":
|
||||
dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc)
|
||||
else:
|
||||
dt = datetime(year, month, day, 23, 59, 59, 999000, tzinfo=timezone.utc)
|
||||
return int(dt.timestamp() * 1000)
|
||||
try:
|
||||
if bound_kind == "start":
|
||||
dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc)
|
||||
else:
|
||||
dt = datetime(year, month, day, 23, 59, 59, 999_999, tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid calendar date for "{field}": "{raw}".'
|
||||
) from exc
|
||||
return _datetime_to_epoch_micros(dt)
|
||||
|
||||
try:
|
||||
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
|
||||
) from exc
|
||||
if dt.tzinfo is None:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Naive timestamp without timezone offset is forbidden for "{field}": "{raw}".'
|
||||
)
|
||||
dt_utc = dt.astimezone(timezone.utc)
|
||||
return int(dt_utc.timestamp() * 1000)
|
||||
im = _ISO_INSTANT_RE.match(raw)
|
||||
if im:
|
||||
year, month, day = int(im.group(1)), int(im.group(2)), int(im.group(3))
|
||||
hour, minute, second = int(im.group(4)), int(im.group(5)), int(im.group(6))
|
||||
frac = im.group(7)
|
||||
micros = int(frac[:6].ljust(6, "0")) if frac is not None else 0
|
||||
tz_token = im.group(8)
|
||||
offset_micros = 0
|
||||
if tz_token != "Z":
|
||||
tz_sign = 1 if im.group(9) == "+" else -1
|
||||
tz_hours = int(im.group(10))
|
||||
tz_mins = int(im.group(11))
|
||||
if tz_hours > 23 or tz_mins > 59:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid timezone offset for "{field}": "{raw}".'
|
||||
)
|
||||
offset_micros = tz_sign * (tz_hours * 60 + tz_mins) * 60_000_000
|
||||
try:
|
||||
dt = datetime(year, month, day, hour, minute, second, micros, tzinfo=timezone.utc)
|
||||
except ValueError as exc:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
|
||||
) from exc
|
||||
return _datetime_to_epoch_micros(dt) - offset_micros
|
||||
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
|
||||
)
|
||||
|
||||
|
||||
def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
|
||||
return parse_timestamp_micros(raw, bound_kind, field) // 1000
|
||||
|
||||
|
||||
def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int:
|
||||
|
|
@ -113,11 +170,11 @@ def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int:
|
|||
elif isinstance(max_ingested_ts, datetime):
|
||||
if max_ingested_ts.tzinfo is None:
|
||||
raise MarketDataStoreValidationError("max_ingested_ts datetime must be timezone-aware.")
|
||||
epoch_ms = int(max_ingested_ts.astimezone(timezone.utc).timestamp() * 1000)
|
||||
epoch_ms = _datetime_to_epoch_micros(max_ingested_ts) // 1000
|
||||
else:
|
||||
raise MarketDataStoreValidationError("Invalid max_ingested_ts type.")
|
||||
|
||||
dt = datetime.fromtimestamp(epoch_ms / 1000.0, tz=timezone.utc)
|
||||
dt = epoch_micros_to_datetime(epoch_ms * 1000)
|
||||
total_months = dt.year * 12 + (dt.month - 1) - 6
|
||||
target_year, target_month_zero = divmod(total_months, 12)
|
||||
target_month = target_month_zero + 1
|
||||
|
|
@ -133,11 +190,11 @@ def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int:
|
|||
dt.microsecond,
|
||||
tzinfo=timezone.utc,
|
||||
)
|
||||
return int(cutoff_dt.timestamp() * 1000)
|
||||
return _datetime_to_epoch_micros(cutoff_dt) // 1000
|
||||
|
||||
|
||||
def vault_cutoff_date_str(vault_cutoff_ts: int) -> str:
|
||||
return datetime.fromtimestamp(vault_cutoff_ts / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
return epoch_micros_to_datetime(vault_cutoff_ts * 1000).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def apply_vault_fence(
|
||||
|
|
@ -148,11 +205,15 @@ def apply_vault_fence(
|
|||
scope: DataScope = "vault_fenced",
|
||||
vault_operator_authorized: bool = False,
|
||||
) -> FencedTimeRange:
|
||||
from_ms = parse_timestamp_ms(from_bound, "start", "from")
|
||||
to_ms = parse_timestamp_ms(to_bound, "end", "to")
|
||||
if to_ms < from_ms:
|
||||
if not isinstance(vault_cutoff_ts, int) or isinstance(vault_cutoff_ts, bool):
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Query end "{to_bound}" ({to_ms}) precedes start "{from_bound}" ({from_ms}).'
|
||||
f"Invalid epoch millisecond timestamp for vault_cutoff_ts: {vault_cutoff_ts!r}."
|
||||
)
|
||||
from_micros = parse_timestamp_micros(from_bound, "start", "from")
|
||||
to_micros = parse_timestamp_micros(to_bound, "end", "to")
|
||||
if to_micros < from_micros:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Query end "{to_bound}" ({to_micros // 1000}) precedes start "{from_bound}" ({from_micros // 1000}).'
|
||||
)
|
||||
|
||||
if scope == "vault_evaluation_only":
|
||||
|
|
@ -160,43 +221,54 @@ def apply_vault_fence(
|
|||
raise VaultScopeNotAuthorizedError(
|
||||
"Data scope 'vault_evaluation_only' requires explicit human operator authorization."
|
||||
)
|
||||
as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of is not None else to_ms
|
||||
as_of_micros = (
|
||||
parse_timestamp_micros(as_of, "end", "as_of") if as_of is not None else to_micros
|
||||
)
|
||||
return FencedTimeRange(
|
||||
from_ms=from_ms,
|
||||
to_ms=to_ms,
|
||||
as_of_ms=as_of_ms,
|
||||
from_ms=from_micros // 1000,
|
||||
to_ms=to_micros // 1000,
|
||||
as_of_ms=as_of_micros // 1000,
|
||||
scope=scope,
|
||||
clamped_to=False,
|
||||
clamped_as_of=False,
|
||||
from_micros=from_micros,
|
||||
to_micros=to_micros,
|
||||
as_of_micros=as_of_micros,
|
||||
)
|
||||
|
||||
if scope != "vault_fenced":
|
||||
raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}")
|
||||
|
||||
if from_ms >= vault_cutoff_ts:
|
||||
raise VaultHoldoutFenceError(from_bound, from_ms, vault_cutoff_ts)
|
||||
cutoff_micros = vault_cutoff_ts * 1000
|
||||
max_allowed_micros = cutoff_micros - 1
|
||||
|
||||
if from_micros >= cutoff_micros:
|
||||
raise VaultHoldoutFenceError(from_bound, from_micros // 1000, vault_cutoff_ts)
|
||||
|
||||
clamped_to = False
|
||||
if to_ms >= vault_cutoff_ts:
|
||||
to_ms = vault_cutoff_ts - 1
|
||||
if to_micros >= cutoff_micros:
|
||||
to_micros = max_allowed_micros
|
||||
clamped_to = True
|
||||
|
||||
clamped_as_of = False
|
||||
if as_of is None:
|
||||
as_of_ms = vault_cutoff_ts - 1
|
||||
as_of_micros = max_allowed_micros
|
||||
else:
|
||||
as_of_ms = parse_timestamp_ms(as_of, "end", "as_of")
|
||||
if as_of_ms >= vault_cutoff_ts:
|
||||
as_of_ms = vault_cutoff_ts - 1
|
||||
as_of_micros = parse_timestamp_micros(as_of, "end", "as_of")
|
||||
if as_of_micros >= cutoff_micros:
|
||||
as_of_micros = max_allowed_micros
|
||||
clamped_as_of = True
|
||||
|
||||
return FencedTimeRange(
|
||||
from_ms=from_ms,
|
||||
to_ms=to_ms,
|
||||
as_of_ms=as_of_ms,
|
||||
from_ms=from_micros // 1000,
|
||||
to_ms=to_micros // 1000,
|
||||
as_of_ms=as_of_micros // 1000,
|
||||
scope="vault_fenced",
|
||||
clamped_to=clamped_to,
|
||||
clamped_as_of=clamped_as_of,
|
||||
from_micros=from_micros,
|
||||
to_micros=to_micros,
|
||||
as_of_micros=as_of_micros,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -224,3 +296,30 @@ def resolve_duckdb_budget(
|
|||
if not tmp_dir or not tmp_dir.startswith("/"):
|
||||
raise MarketDataStoreValidationError(f"Invalid DuckDB temp_directory: {tmp_dir!r}")
|
||||
return DuckDbConnectionBudget(memory_limit=mem, threads=raw_threads, temp_directory=tmp_dir)
|
||||
|
||||
|
||||
def validate_curated_root(raw: str | Path) -> str:
|
||||
"""Validates `curated_root` as an absolute POSIX path without quotes, semicolons, control chars, or globs."""
|
||||
if isinstance(raw, Path):
|
||||
value = str(raw)
|
||||
elif isinstance(raw, str):
|
||||
value = raw
|
||||
else:
|
||||
raise MarketDataStoreValidationError(
|
||||
f"Invalid curated_root {raw!r}. Expected a non-empty absolute POSIX path."
|
||||
)
|
||||
|
||||
if not value or not value.startswith("/"):
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid curated_root "{value}". Expected a non-empty absolute POSIX path.'
|
||||
)
|
||||
|
||||
for ch in value:
|
||||
code = ord(ch)
|
||||
if code <= 0x1F or code == 0x7F or ch in ("'", ";", "*", "?", "[", "]"):
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid curated_root "{value}". Path must not contain control characters, quotes, semicolons, or glob characters (*, ?, [, ]).'
|
||||
)
|
||||
|
||||
normalized = value.rstrip("/")
|
||||
return normalized if normalized else "/"
|
||||
|
|
|
|||
1506
python/tests/test_m2_sdk_parity.py
Normal file
1506
python/tests/test_m2_sdk_parity.py
Normal file
File diff suppressed because it is too large
Load diff
447
python/tests/test_m2_sdk_qa_edges.py
Normal file
447
python/tests/test_m2_sdk_qa_edges.py
Normal file
|
|
@ -0,0 +1,447 @@
|
|||
"""QA edge cases for T-213 (M2.4b) Python `stockbot` batch runner and cross_section.
|
||||
|
||||
Offline only: every test builds its own temporary curated root of Parquet fixtures and
|
||||
touches no QA database, live QuestDB, or execution module.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Mapping
|
||||
|
||||
import duckdb
|
||||
import polars as pl
|
||||
import pytest
|
||||
|
||||
import stockbot.features as features_mod
|
||||
from stockbot import (
|
||||
RET_1D_V1,
|
||||
DuckDbConnectionBudget,
|
||||
FeatureDefinition,
|
||||
FeatureLibraryError,
|
||||
MarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
VaultHoldoutFenceError,
|
||||
run_feature_batch,
|
||||
)
|
||||
from stockbot.vault import parse_timestamp_micros
|
||||
|
||||
UTC = timezone.utc
|
||||
VAULT_CUTOFF_DATE = "2025-07-01"
|
||||
VAULT_CUTOFF_MS = parse_timestamp_micros(VAULT_CUTOFF_DATE, "start", "cutoff") // 1000
|
||||
|
||||
|
||||
def _budget(tmp_path: Path) -> DuckDbConnectionBudget:
|
||||
tmp_dir = tmp_path / "duckdb_tmp"
|
||||
tmp_dir.mkdir(parents=True, exist_ok=True)
|
||||
return DuckDbConnectionBudget(memory_limit="512MB", threads=2, temp_directory=str(tmp_dir))
|
||||
|
||||
|
||||
def _write_parquet(df: pl.DataFrame, out_path: Path) -> None:
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
con = duckdb.connect(":memory:")
|
||||
try:
|
||||
con.execute("SET TimeZone = 'UTC';")
|
||||
con.register("src", df)
|
||||
con.execute(f"COPY src TO '{out_path}' (FORMAT PARQUET, COMPRESSION ZSTD)")
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
def _bars(rows: list[tuple[int, datetime, float]]) -> pl.DataFrame:
|
||||
"""Builds bars_1d rows (listing_id, bar-close ts, close) with known_at == ts."""
|
||||
return pl.DataFrame(
|
||||
{
|
||||
"listing_id": [r[0] for r in rows],
|
||||
"session_date": [r[1].date() for r in rows],
|
||||
"ts": [r[1] for r in rows],
|
||||
"open": [r[2] for r in rows],
|
||||
"high": [r[2] for r in rows],
|
||||
"low": [r[2] for r in rows],
|
||||
"close": [r[2] for r in rows],
|
||||
"volume": [1000.0 for _ in rows],
|
||||
"vwap": [r[2] for r in rows],
|
||||
"currency": ["USD" for _ in rows],
|
||||
"source": ["eod" for _ in rows],
|
||||
"known_at": [r[1] for r in rows],
|
||||
},
|
||||
schema_overrides={
|
||||
"listing_id": pl.Int32,
|
||||
"ts": pl.Datetime("us", "UTC"),
|
||||
"known_at": pl.Datetime("us", "UTC"),
|
||||
"session_date": pl.Date,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def _seed_two_year_bars(curated: Path) -> None:
|
||||
_write_parquet(
|
||||
_bars(
|
||||
[
|
||||
(1, datetime(2024, 12, 30, 21, tzinfo=UTC), 8.0),
|
||||
(1, datetime(2024, 12, 31, 21, tzinfo=UTC), 10.0),
|
||||
(2, datetime(2024, 12, 31, 21, tzinfo=UTC), 20.0),
|
||||
]
|
||||
),
|
||||
curated / "bars_1d" / "year=2024" / "part.parquet",
|
||||
)
|
||||
_write_parquet(
|
||||
_bars(
|
||||
[
|
||||
(1, datetime(2025, 1, 2, 21, tzinfo=UTC), 50.0),
|
||||
(2, datetime(2025, 1, 2, 21, tzinfo=UTC), 30.0),
|
||||
# Post-Vault bar (cutoff 2025-07-01): must never reach any partition.
|
||||
(1, datetime(2025, 7, 2, 21, tzinfo=UTC), 1000.0),
|
||||
]
|
||||
),
|
||||
curated / "bars_1d" / "year=2025" / "part.parquet",
|
||||
)
|
||||
|
||||
|
||||
def _partition(curated: Path, name: str, year: int) -> Path:
|
||||
return curated / "features" / name / "v1" / f"year={year}" / "part.parquet"
|
||||
|
||||
|
||||
def _sql_feature(name: str, sql: str) -> FeatureDefinition:
|
||||
return FeatureDefinition(
|
||||
name=name,
|
||||
version=1,
|
||||
family="technical",
|
||||
kind="duckdb_sql",
|
||||
inputs=("bars_1d",),
|
||||
warmup_bars=0,
|
||||
known_at_rule="bar_close",
|
||||
sql=sql,
|
||||
)
|
||||
|
||||
|
||||
def test_sql_batch_earlier_year_partition_cannot_see_later_year_bars(tmp_path: Path) -> None:
|
||||
# Arrange: an unordered whole-history window (MAX over the listing) would leak the
|
||||
# 2025 close of 50.0 into 2024 rows if the 2024 scan were only fenced by the Vault cutoff.
|
||||
curated = tmp_path / "curated"
|
||||
_seed_two_year_bars(curated)
|
||||
defn = _sql_feature(
|
||||
"max_close_all",
|
||||
"SELECT listing_id, ts, ts AS known_at, "
|
||||
"MAX(close) OVER (PARTITION BY listing_id) AS value "
|
||||
"FROM {{input:bars_1d}}",
|
||||
)
|
||||
|
||||
# Act
|
||||
manifest = run_feature_batch(
|
||||
defn,
|
||||
curated_root=curated,
|
||||
from_year=2024,
|
||||
to_year=2025,
|
||||
vault_cutoff_date=VAULT_CUTOFF_DATE,
|
||||
budget=_budget(tmp_path),
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert [w.year for w in manifest.writes] == [2024, 2025]
|
||||
out_2024 = pl.read_parquet(_partition(curated, "max_close_all", 2024), hive_partitioning=False)
|
||||
out_2025 = pl.read_parquet(_partition(curated, "max_close_all", 2025), hive_partitioning=False)
|
||||
assert out_2024.select("listing_id", "value").rows() == [(1, 10.0), (1, 10.0), (2, 20.0)]
|
||||
# 2025 sees 2024 history plus Jan 2 bars, never the post-Vault 1000.0 close.
|
||||
assert out_2025.select("listing_id", "value").rows() == [(1, 50.0), (2, 30.0)]
|
||||
|
||||
|
||||
def test_feature_batch_replay_is_deterministic_and_idempotent_on_same_definition(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
# Arrange: two independent curated roots with identical retained inputs.
|
||||
root_a = tmp_path / "a" / "curated"
|
||||
root_b = tmp_path / "b" / "curated"
|
||||
_seed_two_year_bars(root_a)
|
||||
_seed_two_year_bars(root_b)
|
||||
|
||||
# Act: run A twice (same definition re-publish) and B once.
|
||||
kwargs = dict(from_year=2024, to_year=2025, vault_cutoff_date=VAULT_CUTOFF_DATE)
|
||||
manifest_a1 = run_feature_batch(RET_1D_V1, curated_root=root_a, budget=_budget(tmp_path / "a"), **kwargs)
|
||||
sidecar_a = (root_a / "features" / "ret_1d" / "v1" / "_definition.json").read_bytes()
|
||||
manifest_a2 = run_feature_batch(RET_1D_V1, curated_root=root_a, budget=_budget(tmp_path / "a"), **kwargs)
|
||||
manifest_b = run_feature_batch(RET_1D_V1, curated_root=root_b, budget=_budget(tmp_path / "b"), **kwargs)
|
||||
|
||||
# Assert: same hash, unchanged sidecar, identical ordered rows across replays/roots.
|
||||
assert manifest_a1.definition_hash == manifest_a2.definition_hash == manifest_b.definition_hash
|
||||
assert (root_a / "features" / "ret_1d" / "v1" / "_definition.json").read_bytes() == sidecar_a
|
||||
assert json.loads(sidecar_a)["definition_hash"] == manifest_a1.definition_hash
|
||||
for year in (2024, 2025):
|
||||
a = pl.read_parquet(_partition(root_a, "ret_1d", year), hive_partitioning=False)
|
||||
b = pl.read_parquet(_partition(root_b, "ret_1d", year), hive_partitioning=False)
|
||||
assert a.equals(b)
|
||||
# Hand-computed ret_1d: 2024 L1 10/8-1 = 0.25; 2025 L1 50/10-1 = 4.0, L2 30/20-1 = 0.5.
|
||||
out_2024 = pl.read_parquet(_partition(root_a, "ret_1d", 2024), hive_partitioning=False)
|
||||
out_2025 = pl.read_parquet(_partition(root_a, "ret_1d", 2025), hive_partitioning=False)
|
||||
assert out_2024.select("listing_id", "value").rows() == [(1, pytest.approx(0.25))]
|
||||
assert out_2025.select("listing_id", "value").rows() == [
|
||||
(1, pytest.approx(4.0)),
|
||||
(2, pytest.approx(0.5)),
|
||||
]
|
||||
|
||||
|
||||
def test_unreadable_definition_sidecar_fails_closed_before_any_write(tmp_path: Path) -> None:
|
||||
# Arrange
|
||||
curated = tmp_path / "curated"
|
||||
_seed_two_year_bars(curated)
|
||||
version_dir = curated / "features" / "ret_1d" / "v1"
|
||||
version_dir.mkdir(parents=True)
|
||||
(version_dir / "_definition.json").write_text("{not json", encoding="utf-8")
|
||||
|
||||
# Act
|
||||
with pytest.raises(FeatureLibraryError) as err:
|
||||
run_feature_batch(
|
||||
RET_1D_V1,
|
||||
curated_root=curated,
|
||||
from_year=2024,
|
||||
to_year=2025,
|
||||
vault_cutoff_date=VAULT_CUTOFF_DATE,
|
||||
budget=_budget(tmp_path),
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert err.value.code == "FEATURE_VERSION_IMMUTABLE"
|
||||
assert sorted(p.name for p in version_dir.rglob("*")) == ["_definition.json"]
|
||||
|
||||
|
||||
def test_claim_collision_between_check_and_link_aborts_before_publishing(
|
||||
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
# Arrange: deterministically inject a competing writer's claim in the window between the
|
||||
# missing-sidecar check and the create-if-absent link.
|
||||
curated = tmp_path / "curated"
|
||||
_seed_two_year_bars(curated)
|
||||
real_link = os.link
|
||||
link_calls: list[str] = []
|
||||
|
||||
def _competing_link(src: str, dst: str) -> None:
|
||||
link_calls.append(dst)
|
||||
with open(dst, "w", encoding="utf-8") as fh:
|
||||
json.dump({"definition_hash": "0" * 64, "ref": "ret_1d@v1"}, fh)
|
||||
real_link(src, dst) # raises FileExistsError, exactly as a lost race would
|
||||
|
||||
monkeypatch.setattr(features_mod.os, "link", _competing_link)
|
||||
|
||||
# Act
|
||||
with pytest.raises(FeatureLibraryError) as err:
|
||||
run_feature_batch(
|
||||
RET_1D_V1,
|
||||
curated_root=curated,
|
||||
from_year=2024,
|
||||
to_year=2025,
|
||||
vault_cutoff_date=VAULT_CUTOFF_DATE,
|
||||
budget=_budget(tmp_path),
|
||||
)
|
||||
|
||||
# Assert: the loser verified the winning hash and published nothing.
|
||||
assert len(link_calls) == 1
|
||||
assert err.value.code == "FEATURE_VERSION_IMMUTABLE"
|
||||
version_dir = curated / "features" / "ret_1d" / "v1"
|
||||
assert list(version_dir.rglob("*.parquet")) == []
|
||||
assert list(version_dir.rglob("*.tmp")) == []
|
||||
assert json.loads((version_dir / "_definition.json").read_text())["definition_hash"] == "0" * 64
|
||||
|
||||
|
||||
def test_polars_output_rows_at_or_after_vault_cutoff_are_dropped_at_microsecond_boundary(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
# Arrange: callable fabricates rows straddling the cutoff by one microsecond.
|
||||
curated = tmp_path / "curated"
|
||||
_seed_two_year_bars(curated)
|
||||
just_before = datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=UTC)
|
||||
at_cutoff = datetime(2025, 7, 1, 0, 0, 0, tzinfo=UTC)
|
||||
|
||||
def _fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.DataFrame:
|
||||
inputs["bars_1d"].collect()
|
||||
return pl.DataFrame(
|
||||
{
|
||||
"listing_id": [1, 2],
|
||||
"ts": [just_before, at_cutoff],
|
||||
"known_at": [just_before, at_cutoff],
|
||||
"value": [1.5, 2.5],
|
||||
},
|
||||
schema_overrides={
|
||||
"listing_id": pl.Int32,
|
||||
"ts": pl.Datetime("us", "UTC"),
|
||||
"known_at": pl.Datetime("us", "UTC"),
|
||||
},
|
||||
)
|
||||
|
||||
defn = FeatureDefinition(
|
||||
name="cutoff_probe",
|
||||
version=1,
|
||||
family="technical",
|
||||
kind="polars",
|
||||
inputs=("bars_1d",),
|
||||
warmup_bars=0,
|
||||
known_at_rule="bar_close",
|
||||
polars_fn=_fn,
|
||||
expression="cutoff_probe",
|
||||
)
|
||||
|
||||
# Act
|
||||
run_feature_batch(
|
||||
defn,
|
||||
curated_root=curated,
|
||||
from_year=2025,
|
||||
to_year=2025,
|
||||
vault_cutoff_date=VAULT_CUTOFF_DATE,
|
||||
budget=_budget(tmp_path),
|
||||
)
|
||||
|
||||
# Assert
|
||||
out = pl.read_parquet(_partition(curated, "cutoff_probe", 2025), hive_partitioning=False)
|
||||
assert out.select("listing_id", "ts", "value").rows() == [(1, just_before, 1.5)]
|
||||
|
||||
|
||||
def test_polars_non_finite_value_fails_without_publishing_partition_or_claim(
|
||||
tmp_path: Path,
|
||||
) -> None:
|
||||
# Arrange
|
||||
curated = tmp_path / "curated"
|
||||
_seed_two_year_bars(curated)
|
||||
|
||||
def _fn(inputs: Mapping[str, pl.LazyFrame]) -> pl.LazyFrame:
|
||||
return inputs["bars_1d"].select(
|
||||
pl.col("listing_id"),
|
||||
pl.col("ts"),
|
||||
pl.col("ts").alias("known_at"),
|
||||
(pl.col("close") / 0.0).alias("value"),
|
||||
)
|
||||
|
||||
defn = FeatureDefinition(
|
||||
name="inf_probe",
|
||||
version=1,
|
||||
family="technical",
|
||||
kind="polars",
|
||||
inputs=("bars_1d",),
|
||||
warmup_bars=0,
|
||||
known_at_rule="bar_close",
|
||||
polars_fn=_fn,
|
||||
expression="close / 0",
|
||||
)
|
||||
|
||||
# Act
|
||||
with pytest.raises(FeatureLibraryError) as err:
|
||||
run_feature_batch(
|
||||
defn,
|
||||
curated_root=curated,
|
||||
from_year=2024,
|
||||
to_year=2024,
|
||||
vault_cutoff_date=VAULT_CUTOFF_DATE,
|
||||
budget=_budget(tmp_path),
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert err.value.code == "BATCH_WRITE_FAILED"
|
||||
assert err.value.failed_year == 2024
|
||||
assert err.value.completed_years == ()
|
||||
version_dir = curated / "features" / "inf_probe" / "v1"
|
||||
assert not (version_dir / "_definition.json").exists()
|
||||
assert list(version_dir.rglob("*.parquet")) == []
|
||||
assert list(version_dir.rglob("*.tmp")) == []
|
||||
|
||||
|
||||
def _seed_cross_section_fixture(curated: Path) -> None:
|
||||
session_close = datetime(2025, 6, 30, 21, tzinfo=UTC)
|
||||
_write_parquet(
|
||||
_bars([(1, session_close, 10.0), (2, session_close, 20.0), (3, session_close, 30.0)]),
|
||||
curated / "bars_1d" / "year=2025" / "part.parquet",
|
||||
)
|
||||
feature = pl.DataFrame(
|
||||
{
|
||||
"listing_id": [1, 2],
|
||||
"ts": [session_close, session_close],
|
||||
# L1 becomes known exactly at the Vault cutoff (must be fenced out);
|
||||
# L2 one microsecond earlier (must be returned).
|
||||
"known_at": [
|
||||
datetime(2025, 7, 1, 0, 0, 0, tzinfo=UTC),
|
||||
datetime(2025, 6, 30, 23, 59, 59, 999_999, tzinfo=UTC),
|
||||
],
|
||||
"value": [9.0, 7.0],
|
||||
},
|
||||
schema_overrides={
|
||||
"listing_id": pl.Int32,
|
||||
"ts": pl.Datetime("us", "UTC"),
|
||||
"known_at": pl.Datetime("us", "UTC"),
|
||||
},
|
||||
)
|
||||
_write_parquet(feature, _partition(curated, "probe", 2025))
|
||||
|
||||
|
||||
def test_cross_section_clamps_late_as_of_to_vault_cutoff_microsecond(tmp_path: Path) -> None:
|
||||
# Arrange
|
||||
curated = tmp_path / "curated"
|
||||
_seed_cross_section_fixture(curated)
|
||||
|
||||
with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store:
|
||||
# Act
|
||||
cs = store.cross_section(
|
||||
features=["probe@v1", "probe@v1"],
|
||||
date="2025-06-30",
|
||||
universe="US_EQ",
|
||||
as_of="2025-08-01T00:00:00Z",
|
||||
)
|
||||
|
||||
# Assert: duplicate refs collapse; L1 (known_at == cutoff) null; L3 has no row -> null.
|
||||
assert cs.columns == ["listing_id", "probe@v1"]
|
||||
assert cs.rows() == [(1, None), (2, 7.0), (3, None)]
|
||||
assert cs.schema["listing_id"] == pl.Int32
|
||||
assert cs.schema["probe@v1"] == pl.Float64
|
||||
|
||||
|
||||
def test_cross_section_rejects_vault_dates_and_non_canonical_refs(tmp_path: Path) -> None:
|
||||
# Arrange
|
||||
curated = tmp_path / "curated"
|
||||
_seed_cross_section_fixture(curated)
|
||||
|
||||
with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store:
|
||||
# Act / Assert: a date on the cutoff is in the holdout.
|
||||
with pytest.raises(VaultHoldoutFenceError):
|
||||
store.cross_section(features=["probe@v1"], date="2025-07-01", universe="US_EQ")
|
||||
for bad_ref in ("probe", "probe@v01", "probe@v0", "Probe@v1", "probe@v1/../x"):
|
||||
with pytest.raises(MarketDataStoreValidationError):
|
||||
store.cross_section(features=[bad_ref], date="2025-06-30", universe="US_EQ")
|
||||
for bad_date in ("2025-6-30", "2025-06-30T00:00:00Z", "2025-02-30"):
|
||||
with pytest.raises(MarketDataStoreValidationError):
|
||||
store.cross_section(features=["probe@v1"], date=bad_date, universe="US_EQ")
|
||||
with pytest.raises(MarketDataStoreValidationError):
|
||||
store.cross_section(features=["probe@v1"], date="2025-06-30", universe="EU_EQ") # type: ignore[arg-type]
|
||||
|
||||
|
||||
def test_cross_section_universe_excludes_listing_whose_bar_is_not_yet_known(tmp_path: Path) -> None:
|
||||
# Arrange: L3's only bar is published after as_of, so it is not in the as-of universe.
|
||||
curated = tmp_path / "curated"
|
||||
curated.mkdir()
|
||||
close = datetime(2025, 6, 30, 21, tzinfo=UTC)
|
||||
bars = _bars([(1, close, 10.0), (3, close, 30.0)]).with_columns(
|
||||
pl.when(pl.col("listing_id") == 3)
|
||||
.then(pl.lit(datetime(2025, 6, 30, 22, 30, tzinfo=UTC)))
|
||||
.otherwise(pl.col("known_at"))
|
||||
.cast(pl.Datetime("us", "UTC"))
|
||||
.alias("known_at")
|
||||
)
|
||||
_write_parquet(bars, curated / "bars_1d" / "year=2025" / "part.parquet")
|
||||
_write_parquet(
|
||||
pl.DataFrame(
|
||||
{"listing_id": [1], "ts": [close], "known_at": [close], "value": [0.5]},
|
||||
schema_overrides={
|
||||
"listing_id": pl.Int32,
|
||||
"ts": pl.Datetime("us", "UTC"),
|
||||
"known_at": pl.Datetime("us", "UTC"),
|
||||
},
|
||||
),
|
||||
_partition(curated, "probe", 2025),
|
||||
)
|
||||
|
||||
with MarketDataStore(curated, vault_cutoff_ts=VAULT_CUTOFF_MS, budget=_budget(tmp_path)) as store:
|
||||
# Act
|
||||
cs = store.cross_section(
|
||||
features=["probe@v1"], date="2025-06-30", universe="US_EQ", as_of="2025-06-30T22:00:00Z"
|
||||
)
|
||||
|
||||
# Assert
|
||||
assert cs.rows() == [(1, 0.5)]
|
||||
Loading…
Add table
Add a link
Reference in a new issue