T-213: M2.4b — Add Python stockbot register_signal, batch feature runner, and M2 MarketDataStore methods

This commit is contained in:
Studio 2026-12-05 13:49:03 -05:00
parent 40548adddb
commit 81ffdef24c
6 changed files with 4219 additions and 86 deletions

View file

@ -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 "/"