feat(m1): complete curate-etl MongoDB driver, DuckDB MarketDataStore, Python SDK, and M1 evidence

This commit is contained in:
Boki 2026-11-30 10:18:58 -05:00
parent 88308e1f12
commit d9191304fb
62 changed files with 9608 additions and 366 deletions

View file

@ -0,0 +1,153 @@
"""Unit tests for the `stockbot` Python SDK (Vault fence, DSR parity, DuckDB/Parquet store)."""
from __future__ import annotations
import math
from datetime import date, datetime, timezone
from pathlib import Path
import polars as pl
import pytest
from stockbot import (
MarketDataStore,
VaultHoldoutFenceError,
VaultScopeNotAuthorizedError,
analyze_signal_panel,
apply_vault_fence,
canonical_expression_hash,
compute_vault_cutoff_ts,
deflated_sharpe_ratio,
effective_independent_trials,
resolve_duckdb_budget,
trial_moments,
)
def test_vault_cutoff_and_fencing_rules() -> None:
cutoff = compute_vault_cutoff_ts("2025-08-13")
expected = int(datetime(2025, 2, 13, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000)
assert cutoff == expected
# Clamps to and as_of strictly below cutoff
fenced = apply_vault_fence("2020-01-01", "2025-08-13", cutoff)
assert fenced.clamped_to is True
assert fenced.to_ms == cutoff - 1
assert fenced.as_of_ms == cutoff - 1
# Rejects start >= cutoff
with pytest.raises(VaultHoldoutFenceError):
apply_vault_fence("2025-02-13", "2025-05-01", cutoff)
# Rejects unauthorized vault_evaluation_only
with pytest.raises(VaultScopeNotAuthorizedError):
apply_vault_fence("2025-02-13", "2025-05-01", cutoff, scope="vault_evaluation_only")
def test_trial_moments_and_dsr_match_canonical_math() -> None:
series = [0.01, 0.02, -0.005, 0.015, 0.008, -0.002, 0.012, 0.004]
m = trial_moments(series)
assert m.n_obs == 8
assert m.sharpe_unann > 0.0
assert m.kurtosis >= m.skewness ** 2 + 1.0
# Identical series -> rho = 1.0 -> N_hat = 1.0
dates = [f"2024-01-0{i+1}" for i in range(len(series))]
eff_dup = effective_independent_trials(
[(1, dict(zip(dates, series))), (2, dict(zip(dates, series)))]
)
assert math.isclose(eff_dup.mean_correlation or 0.0, 1.0, rel_tol=1e-9)
assert math.isclose(eff_dup.n_hat, 1.0, rel_tol=1e-9)
dsr = deflated_sharpe_ratio(
sharpe_unann=m.sharpe_unann,
n_obs=m.n_obs,
skewness=m.skewness,
kurtosis=m.kurtosis,
n_hat=2.0,
cluster_sharpes=[m.sharpe_unann, 0.1],
)
assert 0.0 <= dsr.dsr <= 1.0
assert dsr.standard_error > 0.0
def test_canonical_expression_hash_is_deterministic() -> None:
h1 = canonical_expression_hash(
expression=" ca_shorts neg_shares_short ",
params={"b": 2, "a": 1, "skip": None},
universe="CA_EQ",
sample_start="2018-01-01",
sample_end="2025-01-31",
horizon="5d",
)
h2 = canonical_expression_hash(
expression="ca_shorts neg_shares_short",
params={"a": 1, "b": 2},
universe="CA_EQ",
sample_start="2018-01-01",
sample_end="2025-01-31",
horizon="5d",
)
assert len(h1) == 64
assert h1 == h2
def test_duckdb_market_data_store_enforces_vault_fence(tmp_path: Path) -> None:
bars_dir = tmp_path / "bars_1d" / "year=2025"
bars_dir.mkdir(parents=True)
df = pl.DataFrame(
{
"listing_id": pl.Series([1, 1], dtype=pl.Int32),
"ts": pl.Series(
[
datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc),
datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc),
],
dtype=pl.Datetime("us", "UTC"),
),
"session_date": pl.Series([date(2025, 2, 10), date(2025, 2, 20)], dtype=pl.Date),
"open": [10.0, 11.0],
"high": [10.5, 11.5],
"low": [9.8, 10.8],
"close": [10.2, 11.2],
"volume": [1000.0, 2000.0],
"vwap": [None, None],
"currency": ["CAD", "CAD"],
"source": ["eod", "eod"],
"known_at": pl.Series(
[
datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc),
datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc),
],
dtype=pl.Datetime("us", "UTC"),
),
}
)
df.write_parquet(bars_dir / "part.parquet")
cutoff = compute_vault_cutoff_ts("2025-08-13") # 2025-02-13
budget = resolve_duckdb_budget(memory_limit="1GB", threads=2, temp_directory=str(tmp_path / "tmp"))
with MarketDataStore(tmp_path, vault_cutoff_ts=cutoff, budget=budget) as store:
out = store.bars(from_date="2025-01-01", to_date="2025-08-13", adjustment="raw")
assert out.height == 1
assert str(out["session_date"][0]) == "2025-02-10"
def test_signal_panel_analyzer_excludes_vault_rows() -> None:
rows = []
for day_idx in range(1, 20):
d = f"2025-02-{day_idx:02d}"
for lid in range(1, 15):
rows.append(
{
"session_date": d,
"listing_id": lid,
"signal": float(lid),
"forward_return": 0.001 * lid + (0.0001 * day_idx),
}
)
panel = pl.DataFrame(rows)
res = analyze_signal_panel(panel, vault_cutoff_date="2025-02-13", min_cross_section=10)
assert res["vault_excluded_rows"] > 0
assert all(d < "2025-02-13" for d in res["dates"]) # type: ignore[union-attr]
assert res["mean_rank_ic"] > 0.9 # type: ignore[operator]