251 lines
9 KiB
Python
251 lines
9 KiB
Python
import marimo
|
|
|
|
__generated_with = "0.26.0"
|
|
app = marimo.App(width="medium")
|
|
|
|
|
|
@app.cell
|
|
def _():
|
|
import os
|
|
from pathlib import Path
|
|
|
|
import marimo as mo
|
|
import polars as pl
|
|
|
|
from stockbot import (
|
|
MarketDataStore,
|
|
TrialLedgerClient,
|
|
compute_vault_cutoff_ts,
|
|
resolve_duckdb_budget,
|
|
run_event_study_trial,
|
|
run_signal_study,
|
|
vault_cutoff_date_str,
|
|
)
|
|
|
|
curated_root = Path(os.environ.get("STOCK_BOT_CURATED_ROOT", "/mnt/data/stockbot/m1-curated"))
|
|
max_ingested_date = os.environ.get("STOCK_BOT_MAX_INGESTED_DATE", "2025-08-13")
|
|
vault_cutoff_ts = compute_vault_cutoff_ts(max_ingested_date)
|
|
vault_cutoff_date = vault_cutoff_date_str(vault_cutoff_ts)
|
|
trial_ledger_dsn = os.environ.get("STOCK_BOT_TRIAL_LEDGER_DSN", "")
|
|
temp_dir = os.environ.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY", "/tmp/stockbot-duckdb")
|
|
|
|
mo.md(
|
|
f"""
|
|
# Canadian `ceoShorts` & `qmFilings` Signal Lab Study (M1)
|
|
|
|
- **Curated Root:** `{curated_root}`
|
|
- **Max Ingested Date:** `{max_ingested_date}`
|
|
- **Rolling 6-Month Vault Cutoff (exclusive):** `{vault_cutoff_date}`
|
|
- **Trial Ledger Configured:** `{"yes" if bool(trial_ledger_dsn) else "no"}`
|
|
"""
|
|
)
|
|
return (
|
|
MarketDataStore,
|
|
TrialLedgerClient,
|
|
curated_root,
|
|
mo,
|
|
pl,
|
|
resolve_duckdb_budget,
|
|
run_event_study_trial,
|
|
run_signal_study,
|
|
temp_dir,
|
|
trial_ledger_dsn,
|
|
vault_cutoff_date,
|
|
vault_cutoff_ts,
|
|
)
|
|
|
|
|
|
@app.cell
|
|
def _(
|
|
MarketDataStore,
|
|
curated_root,
|
|
mo,
|
|
pl,
|
|
resolve_duckdb_budget,
|
|
temp_dir,
|
|
vault_cutoff_date,
|
|
vault_cutoff_ts,
|
|
):
|
|
_budget = resolve_duckdb_budget(
|
|
memory_limit="4GB",
|
|
threads=4,
|
|
temp_directory=temp_dir,
|
|
)
|
|
_adj_fenced = curated_root / "adj_factors_fenced" / "part.parquet"
|
|
if not _adj_fenced.exists():
|
|
_adj_fenced = curated_root / "adj_factors" / "part.parquet"
|
|
_adj_mode = "total" if _adj_fenced.exists() else "raw"
|
|
|
|
with MarketDataStore(
|
|
curated_root,
|
|
vault_cutoff_ts=vault_cutoff_ts,
|
|
budget=_budget,
|
|
adj_factors_path=_adj_fenced if _adj_fenced.exists() else None,
|
|
) as _store:
|
|
_ca_bars = _store.bars(
|
|
currencies=["CAD"],
|
|
from_date="2017-01-01",
|
|
to_date=vault_cutoff_date,
|
|
adjustment=_adj_mode,
|
|
)
|
|
_ca_shorts = _store.shorts_as_of(
|
|
from_date="2017-01-01",
|
|
to_date=vault_cutoff_date,
|
|
)
|
|
_ca_events = _store.events(
|
|
kinds=["filing"],
|
|
from_date="2017-01-01",
|
|
to_date=vault_cutoff_date,
|
|
)
|
|
|
|
_ca_listing_ids = _ca_bars.select("listing_id").unique()
|
|
_ca_events = _ca_events.join(_ca_listing_ids, on="listing_id", how="semi")
|
|
_ca_shorts = _ca_shorts.join(_ca_listing_ids, on="listing_id", how="semi")
|
|
|
|
# Confirm zero Vault rows leaked into any frame
|
|
_vault_bar_leaks = int(
|
|
_ca_bars.filter(pl.col("session_date").cast(pl.String) >= vault_cutoff_date).height
|
|
)
|
|
assert _vault_bar_leaks == 0, f"Vault fence breach: {_vault_bar_leaks} bars >= {vault_cutoff_date}"
|
|
|
|
# Build strict PIT ceoShorts signal panel (join_asof known_at <= bar.ts) with 5-session forward return
|
|
_bars_fwd = (
|
|
_ca_bars.sort(["listing_id", "session_date"])
|
|
.with_columns(
|
|
(pl.col("close").shift(-5).over("listing_id") / pl.col("close") - 1.0).alias(
|
|
"forward_return"
|
|
),
|
|
(pl.col("close") * pl.col("volume")).alias("dollar_vol"),
|
|
)
|
|
.filter(pl.col("forward_return").is_finite() & (pl.col("close") > 0.10))
|
|
)
|
|
|
|
_shorts_sorted = (
|
|
_ca_shorts.select(["listing_id", "known_at", "shares_short", "net_change"])
|
|
.filter(pl.col("shares_short") > 0)
|
|
.sort(["listing_id", "known_at"])
|
|
)
|
|
|
|
shorts_panel = (
|
|
_bars_fwd.sort(["listing_id", "ts"])
|
|
.join_asof(
|
|
_shorts_sorted,
|
|
left_on="ts",
|
|
right_on="known_at",
|
|
by="listing_id",
|
|
strategy="backward",
|
|
)
|
|
.filter(pl.col("shares_short").is_not_null())
|
|
.with_columns(
|
|
(-(pl.col("shares_short") / (pl.col("volume").clip(lower_bound=1.0)))).alias("signal")
|
|
)
|
|
.select(["session_date", "listing_id", "signal", "forward_return"])
|
|
)
|
|
|
|
ca_bars_summary = {
|
|
"adjustment": _adj_mode,
|
|
"ca_bars_rows": int(_ca_bars.height),
|
|
"ca_shorts_rows": int(_ca_shorts.height),
|
|
"ca_filings_rows": int(_ca_events.height),
|
|
"shorts_panel_rows": int(shorts_panel.height),
|
|
"vault_bar_leaks": _vault_bar_leaks,
|
|
}
|
|
ca_bars_slim = _ca_bars.filter(pl.col("close") >= 0.10).select(["listing_id", "session_date", "ts", "close"])
|
|
ca_filings_slim = _ca_events.select(["listing_id", "known_at", "subtype"])
|
|
|
|
mo.md(
|
|
f"""
|
|
## Loaded Curated Canadian Datasets (Zero Vault Rows)
|
|
|
|
- **Adjustment mode:** `{ca_bars_summary['adjustment']}`
|
|
- **Canadian `bars_1d` rows:** `{ca_bars_summary['ca_bars_rows']:,}` (`vault_bar_leaks = {ca_bars_summary['vault_bar_leaks']}`)
|
|
- **Canadian `shorts` (`ceoShorts`, +4bd lag) rows:** `{ca_bars_summary['ca_shorts_rows']:,}`
|
|
- **Canadian `events` (`qmFilings`) rows:** `{ca_bars_summary['ca_filings_rows']:,}`
|
|
- **Joined PIT `ceoShorts` panel rows:** `{ca_bars_summary['shorts_panel_rows']:,}`
|
|
"""
|
|
)
|
|
return ca_bars_slim, ca_bars_summary, ca_filings_slim, shorts_panel
|
|
|
|
|
|
@app.cell
|
|
def _(
|
|
TrialLedgerClient,
|
|
ca_bars_slim,
|
|
ca_filings_slim,
|
|
mo,
|
|
run_event_study_trial,
|
|
run_signal_study,
|
|
shorts_panel,
|
|
trial_ledger_dsn,
|
|
vault_cutoff_date,
|
|
):
|
|
if not trial_ledger_dsn:
|
|
mo.stop(True, mo.md("Set `STOCK_BOT_TRIAL_LEDGER_DSN` to write trials to `trial_ledger`."))
|
|
|
|
_ledger = TrialLedgerClient(trial_ledger_dsn)
|
|
|
|
shorts_study = run_signal_study(
|
|
panel=shorts_panel,
|
|
ledger=_ledger,
|
|
principal_id="operator",
|
|
universe_market="CA_EQ",
|
|
horizon_bucket="swing_1_10d",
|
|
horizon_label="5d",
|
|
expression="neg_ciro_short_interest_to_volume_5d",
|
|
params={"lag_bd": 4, "horizon_sessions": 5, "min_price_cad": 0.10, "n_quantiles": 5},
|
|
vault_cutoff_date=vault_cutoff_date,
|
|
n_quantiles=5,
|
|
min_cross_section=10,
|
|
ledger_series="rank_ic",
|
|
)
|
|
|
|
filings_study = run_event_study_trial(
|
|
bars_df=ca_bars_slim,
|
|
events_df=ca_filings_slim,
|
|
ledger=_ledger,
|
|
principal_id="operator",
|
|
universe_market="CA_EQ",
|
|
horizon_bucket="swing_1_10d",
|
|
expression="ca_qm_filings_abnormal_return_event_study",
|
|
params={"pre_days": 5, "post_days": 10, "benchmark": "equal_weight"},
|
|
vault_cutoff_date=vault_cutoff_date,
|
|
pre_days=5,
|
|
post_days=10,
|
|
min_events=5,
|
|
)
|
|
|
|
_s_trial = shorts_study["trial"]
|
|
_s_dsr = shorts_study["dsr"]
|
|
_s_ana = shorts_study["analysis"]
|
|
_f_trial = filings_study["trial"]
|
|
_f_dsr = filings_study["dsr"]
|
|
_f_stu = filings_study["study"]
|
|
|
|
mo.md(
|
|
f"""
|
|
## Study Results & `trial_ledger` Deflated Sharpe
|
|
|
|
### 1. Canadian `ceoShorts` 5-Day Forward Return Signal
|
|
- **Status:** `{shorts_study['status']}`
|
|
- **Trial ID:** `{_s_trial.trial_id if _s_trial else None}` | **n_obs:** `{_s_trial.n_obs if _s_trial else 0}`
|
|
- **Mean Rank-IC:** `{_s_ana['mean_rank_ic']:.6f}` (Newey-West t = `{_s_ana['rank_ic_nw_t']:.3f}`)
|
|
- **Mean Q5-Q1 Spread:** `{_s_ana['mean_quantile_spread']:.6f}` (Turnover = `{_s_ana['mean_top_quantile_turnover']:.3f}`)
|
|
- **Recency Gate (Post-2023):** `{_s_ana['recency_rank_ic']}`
|
|
- **Unannualized Sharpe:** `{_s_trial.sharpe_unann if _s_trial else float('nan'):.6f}`
|
|
- **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_s_dsr.cluster_size if _s_dsr else 0}` / `{_s_dsr.effective_trials if _s_dsr else 0.0:.4f}`
|
|
- **Deflated Sharpe Ratio (DSR):** `{_s_dsr.dsr if _s_dsr else float('nan'):.6f}` (`passes_gate = {_s_dsr.passes_gate if _s_dsr else False}`)
|
|
|
|
### 2. Canadian `qmFilings` Event Study (`[-5, +10]` sessions)
|
|
- **Status:** `{filings_study['status']}`
|
|
- **Trial ID:** `{_f_trial.trial_id if _f_trial else None}` | **Events Used:** `{_f_stu.get('events_used', 0)}` | **Event Dates:** `{_f_stu.get('n_dates', 0)}`
|
|
- **Mean Post-Event CAR:** `{_f_stu.get('car_mean', float('nan')):.6f}` (Newey-West t = `{_f_stu.get('car_nw_t', float('nan')):.3f}`)
|
|
- **Recency Gate (Post-2023):** `{_f_stu.get('recency')}`
|
|
- **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_f_dsr.cluster_size if _f_dsr else 0}` / `{_f_dsr.effective_trials if _f_dsr else 0.0:.4f}`
|
|
- **Deflated Sharpe Ratio (DSR):** `{_f_dsr.dsr if _f_dsr else float('nan'):.6f}` (`passes_gate = {_f_dsr.passes_gate if _f_dsr else False}`)
|
|
"""
|
|
)
|
|
return filings_study, shorts_study
|
|
|
|
|
|
if __name__ == "__main__":
|
|
app.run()
|