# Stock Bot — AI Algo Research Platform Plan As of 2026-11-26 (revised post-audit). Owner: Boki. Stock Bot becomes a personal **edge factory**: ideas go in, AI agents test them at scale on honest point-in-time data, you explore alongside them, and survivors move through paper trading to live trading on Interactive Brokers — then get monitored until their edge decays. Companion specs: - **[MILESTONES.md](MILESTONES.md)** — executable milestone checklist (`M0` → `M5`), scope cuts, and exit criteria. - **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** — raw provider quirks, security-master DDL, `known_at` rules, and Parquet/QuestDB schemas. - **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** — canonical metrics, trial ledger ($\hat{N}$ DSR & PBO), 6-month Vault, recency gate, and IB/TSX execution rules. --- ## Contents 1. [Vision and principles](#1-vision-and-principles) 2. [Where the project stands](#2-where-the-project-stands) 3. [Decisions log](#3-decisions-log) 4. [System architecture](#4-system-architecture) 5. [Data architecture and storage](#5-data-architecture-and-storage) 6. [Step 1 — Cross-source merge (security master)](#6-step-1--cross-source-merge-security-master) 7. [Step 2 — Processing the remaining datasets](#7-step-2--processing-the-remaining-datasets) 8. [Feature library](#8-feature-library) 9. [Backtesting](#9-backtesting) 10. [Orchestration](#10-orchestration) 11. [Research and analytics playground](#11-research-and-analytics-playground) 12. [Agent layer](#12-agent-layer) 13. [Execution: paper to live on IB](#13-execution-paper-to-live-on-ib) 14. [The app](#14-the-app) 15. [Strategy lifecycle](#15-strategy-lifecycle) 16. [Roadmap](#16-roadmap) --- ## 1. Vision and principles The real product is **trustworthy evidence produced fast**. Most retail algo work fails because results look good and are not real. The edge comes from: - **Rigor at scale** — agents can run thousands of tests; the platform makes sure the statistics account for that and penalize pre-LLM regime decay. - **Data few others combine** — 14.8M CEO.ca posts, 30.5M US/Canadian filings with second-level timestamps, 693k CIRO short records, fundamentals, dividends, splits, earnings, 54 years of USD/CAD (`5.2M` 1m bars), and `3.4B` 1m bars across US and Canadian markets. - **Capacity-constrained niches** — Canadian small/mid-caps (`TSX`/`TSXV`/`CSE`), cross-border US/CA interlisted pairs, and filing/short/retail-flow events where institutional AI pods cannot deploy size. - **Research speed** — "is there something here?" answered in seconds over Parquet + DuckDB, before writing a line of strategy code. - **Execution quality** — one Rust financial kernel for portfolio backtest, paper, and live IB execution, paired with dual drift monitoring. Ideas come from two places: you, and the Quant profile in Studio (`~/repos/studio`). Agents test them. You research alongside them. Everything that can give an edge is in scope: intraday, swing/daily, cross-sectional equity portfolios, FX, and event/alt-data strategies. ### Design principles 1. **Point-in-time everything — with honest provenance.** Every query answers "as known at time T": universe membership, prices, fundamentals, events. Where raw vendors omit true availability timestamps, the pipeline applies conservative statutory/publication lags and tags `known_at_source` (`filing_timestamp` vs `statutory_lag_estimate`) so strategies never unknowingly trade estimated timestamps at intraday precision. 2. **Single source of truth per calculation.** - **Rust (`apps/stock/engine/src/financial`)** owns all accounting, cash/margin, corporate actions, fills, risk, and replay. - **`@stock-bot/calculations`** owns canonical return/drawdown/Sharpe/DSR/PBO statistics served by the Research Kernel API. - **Batch feature jobs** compute versioned features once; Python notebooks, the Tier 1 screener, and Tier 2 TypeScript/Rust strategies all consume the exact same materialized feature values. 3. **Signal-first, not strategy-first.** Research starts with "does this signal predict anything?" Strategies are built only on signals that survived cost, regime, and recency checks. 4. **Every trial counts.** An immutable trial ledger records every signal analysis, screen, and backtest with its return/IC vector. Significance is adjusted for effective independent trials $\hat{N}$ (Deflated Sharpe Ratio) and Combinatorial Symmetric Cross-Validation (PBO), backed by a rolling **6-month Air-Gapped Vault** and a **Post-2023 Recency Gate**. 5. **Agents and you use the same tools.** One Research Kernel API, one MCP surface, one Python SDK. Autonomous campaign agents run in network-isolated containers with no host shell or direct DB port access. 6. **Rigor lives in the engine, not the UX.** Keep receipts, fencing, and provenance underneath. Make the surface fast and playful. 7. **Raw stays raw.** MongoDB is the provider landing zone. Only `data-pipeline` reads it via `MONGODB_READ_URI` (`studio_stock_bot_read`). 8. **Stable identity.** Everything downstream keys on permanent integer `listing_id` (or ISO country / currency pair), never on mutable tickers. --- ## 2. Where the project stands The October engineering backlog closed at **113 done / 5 deferred (`D04`, `P03`, `P05`, `P06`, `CL21`) / 4 merged = 122 retained tasks**, delivering: - the canonical fixed-decimal Rust financial kernel (`Ledger`, `RiskAccount`, `MatchingAccount`, `Replay`); - canonical single-asset research with 3-phase chronological validation, walk-forward, and cost sensitivity; - an isolated Linux Docker + seccomp + Rust PID1 guardian sandbox for agent-written TypeScript (`A02`); - scoped `sb-research.*` agent credentials (`A01`) and a typed `ResearchClient`; - a 1/2/4-slot worker pool and human-reviewed paper deployments; - full `quant` server deployment (`12900K`, 24 threads, 125 GiB RAM, 4 TB WD Black SN850X NVMe at `/mnt/data/stockbot`). ### Baseline gates & Phase 0 findings (2026-11-26) 9 of 11 repository gates pass on the current working tree; audit uncovered specific Phase 0 items that must land before Phase A: - **Failing gates:** `test:tooling` (`178 pass, 1 fail` — `scripts/test/workspace.test.ts:85` expects `docker-compose.yml` after `scripts/docker.sh` switched default to `dev`) and `lint:check` (`63 curly errors + 2 warnings = 65`: `61` in `phase1-inventory.ts`, `4` in WIP files). - **Dev PostgreSQL init bug:** `database/postgres/init/01`–`05` hardcode `\c trading_bot;`, leaving `trading_bot_dev` (`5433`) with zero master/pipeline tables on fresh startup. - **Read-only MongoDB bypass:** `MongoDBClient.getDatabase()`/`collection()` (`libs/data/mongodb/src/client.ts`) expose unwrapped driver objects bypassing `mongoReadOnly`, used by legacy `sync-ib-exchanges.operations.ts`; `env-safety.ts` warns instead of throwing when `dataPipeline` uses `trading_admin`. - **Credential & holdout leaks:** `apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19` contains a hardcoded proxy URL credential; `research-agents.service.ts:51` allows `sb-research.*` tokens to call `/api/v2/datasets/canonical/:hash/export` (leaking holdout bars) and lacks cumulative lifetime/campaign trial caps; `data-ingestion` runs scheduled crawls on boot unless `QUEUE_ENABLE_SCHEDULED_JOBS=false`. - **Stray root files to remove:** `tetest.ts`, `test-queue.ts`, `proxy-playwrite.ts`, `test-rust-strategies.js`, `test-typescript-strategy.js`, `test-e2e-backtest.sh`. ### Raw data inventory (QA MongoDB `stock` — 31 collections) | Provider | Collections (documents) | Key Audit Notes | | --- | --- | --- | | **EOD** | `eodSymbols` 318k, `eodExchanges` 76, `eodPrices` 846M, `eodIntraday1M` 3.40B, `eodIntraday5M` 1.08B, `eodIntraday1H` 110M, `eodSymbolChange` 230, `eodFundamentalsOLD` 107k, `eodFinancialsOLD` 2.98M | `eodPrices` has raw OHLC + **split-adjusted `volume`**; `eodIntraday1M` (US back to 2003) has **split-adjusted OHLC**; `CAD.FOREX` has `12.1k` 1d + `5.2M` 1m USD/CAD bars; `eodSymbolChange` only covers Aug 2024–Jul 2025 US; `eodFinancialsOLD` sets `filingDate == reportDate` on 99.3% of rows. | | **QM** | `qmSymbols` 47k, `qmExchanges` 25, `qmPrices` 51.5M, `qmIntraday` 173M, `qmFinancials` 1.86M, `qmFinancials-old` 908k, `qmFilings` 30.5M, `qmEarnings` 445k, `qmDividends` 496k, `qmSplits` 18.8k | `qmPrices` has raw OHLC + **raw `sharevolume`**; `qmIntraday` covers TSX/CA 1m (from May 2024) with both raw & adjusted columns; `qmFilings` holds US EDGAR + **Canadian SEDAR+** `timefiled` to the second (no parsed Form 4 share counts); `qmFinancials` has `0%` `filingDate` and `0` restatements (rescued via `qmFilings` join). | | **IB** | `ibSymbols` 18.4k, `ibExchanges` 214 | `100%` ISIN, `99.98%` CUSIP, `100%` `conid`; `exchangeId` records execution/ATS venues (`AEQLIT`, `ARCAEDGE`, `IEX`, `OTCLNKECN`), **not** primary listing MICs (`NYSE`=370, `NASDAQ`=241, `TSE`=514). | | **CEO** | `ceoSymbols` 12.6k, `ceoExchanges` 4, `ceoPosts` 14.8M, `ceoShorts` 693k | 100% Canadian (`TSX`, `CDX`, `CNQ`, `AQL`); `ceoShorts` back to Apr 2017 (stamps 15th/month-end report dates, requiring `+4bd` CIRO publication lag); `ceoPosts` has 1.8% edited posts (`edited != null`) and `@thenewswire` bot accounts. | | **TE** | `teCountries` 198, `teIndicators` 163, `teData` 14.8k, `teMarketData` 435, `teUrls` 2.4M | `teData` stores `{d, v}` final-revised series only (no release dates or vintages → lagged regime use only); `teMarketData` includes `USDCAD` daily bars through Apr 2026. | | **TT** | `ttFutures` 1.46M | Individual historical contracts with corrupted date strings (`"NaN-at-e\""`, `"2001-/0-2/"`) → deferred out of scope. | --- ## 3. Decisions log | # | Decision | Status | | --- | --- | --- | | **D1** | **Storage split:** Curate daily bars, corporate actions, PIT fundamentals/events/shorts/macro, FX, and versioned features directly into **Hive Parquet + DuckDB** behind `MarketDataStore`. Reserve **QuestDB `10.2.0`** (`SYMBOL CAPACITY 65536 NOCACHE`) for `1m`/`5m`/`1h` intraday and hot live/paper bars. No dual-backend parity harness. | Settled (2026-11-26) | | **D2** | **Copilot:** Desktop first — Claude Code / Claude Desktop connected through an MCP server. Autonomous campaign agents run in network-isolated containers with MCP-only access. | Settled (2026-11-26) | | **D3** | **Markets:** Multi-market, with US + Canada (and USD/CAD + G10 spot FX) as priority; `ttFutures` out of scope. | Settled (2026-11-26) | | **D4** | **Web app:** Evolve incrementally alongside backend phases; no rewrite. | Settled (2026-11-26) | | **D5** | **First step:** Cross-source entity resolution in `data-pipeline` (two-stage: global ISIN/CUSIP → `instrument`, EOD/QM venue → `listing`, IB `conid` attached at `(instrument_id, currency)`). | Settled (2026-11-26) | | **D6** | **End state:** Paper → live on **Interactive Brokers Margin account** (`USD` + `CAD` cash/margin sub-ledgers, `FXCONV` sweeps, `IDEALPRO` when trading FX alpha, $\le 80$ active intraday streaming symbols on isolated `9900K` host). | Settled (2026-11-26) | | **D7** | **Strategy scope:** Intraday, swing/daily, cross-sectional long/short equity portfolios, FX, and event/alt-data strategies (excluding macro-release surprises and insider dollar-volume in v1). | Settled (2026-11-26) | | **D8** | **Research playground:** Market intelligence, exploration lab, strategy tearsheets, and agent lab feed — delivered incrementally starting with Signal Lab + MCP. | Settled (2026-11-26) | | **D9** | **marimo** confirmed for Python labs: `marimo edit --watch --mcp` on separate loopback origin (`127.0.0.1:2718`), zero-RAM `marimo export html` snapshots in the Agent Feed, `_`-prefixed local variables, and mandatory `marimo check` AST/DAG gating. | Confirmed (2026-11-26) | | **D10** | **Holdout & recency defense:** Rolling **6-month Air-Gapped Vault** (`today - 6m`, unreadable by `MarketDataStore`/MCP/marimo during research, unlocked once at human `Validated → Paper` gate; no toggle switch in v1) + mandatory **Post-2023 Recency Gate**. | Settled (2026-11-26) | | **D11** | **Python → TypeScript bridge:** Signals promote via **materialized batch feature jobs** (`register_signal` → versioned `features` column read by Rust `Replay` + `StrategyContext`), eliminating manual Python-to-TypeScript indicator rewrites. | Settled (2026-11-26) | | **D12** | **Knowledge base:** Mount Studio's 83-card `catalog/quant/library/library.yml` read-only for methodology/literature; store only empirical Stock Bot `findings`, `dead_ends`, and `provider_caveats` in PostgreSQL. | Settled (2026-11-26) | --- ## 4. System architecture ```text ┌────────────────────────────────────────────┐ Ideas: you + Studio ───▶ │ AGENTS (desktop copilot, Studio, campaigns)│ └───────────────┬────────────────────────────┘ │ MCP tools / HTTP API / Python SDK ┌──────────────────────────────────────────▼─────────────────────────────────────────┐ │ RESEARCH KERNEL (one API) │ │ query data (vault-fenced) · analyze signal · event study · screen · backtest · │ │ tearsheet · findings · campaigns · trial ledger · vault promotion gate │ └───────┬───────────────────┬──────────────────────┬───────────────────┬─────────────┘ │ │ │ │ ┌───────▼───────┐ ┌────────▼────────┐ ┌─────────▼────────┐ ┌───────▼─────────┐ │ DATA │ │ BACKTEST │ │ ORCHESTRATION │ │ EXECUTION │ │ MarketDataStore│ │ columnar screen │ │ campaigns, │ │ paper host → │ │ • DuckDB/Parq │ │ + Rust engine │ │ budgets, local │ │ IB Gateway (9900K│ │ • QuestDB 10.2│ │ + CPCV/DSR/PBO │ │ worker pool │ │ OMS, dual drift)│ └───────▲───────┘ └─────────────────┘ └──────────────────┘ └─────────────────┘ │ ┌───────┴──────────────────────────────────────────────┐ │ PIPELINE (data-pipeline): raw → merged → curated → │ │ batch features; security master in PostgreSQL │ └───────▲──────────────────────────────────────────────┘ │ read-only (MONGODB_READ_URI: studio_stock_bot_read) ┌───────┴───────────────┐ ┌──────────────────────────────────────────┐ │ MongoDB raw landing │◀───────│ data-ingestion (providers: EOD, QM, IB, │ │ (QA, never written │ │ CEO, TE) │ │ from dev/tests) │ └──────────────────────────────────────────┘ └───────────────────────┘ APP (web-app): Lab (+ marimo) · Agents · Strategies · Data · Trading · Markets · Home ``` | Layer | Owns | Language | | --- | --- | --- | | `data-ingestion` | Provider crawlers → raw MongoDB (scheduled jobs disabled outside dedicated ingester) | TypeScript | | `data-pipeline` + `curate-etl` | Entity resolution & orchestration (TS), zero-copy BSON bulk bar ETL (`tools/curate-etl` in Rust), PIT/feature batch jobs → Postgres + Parquet + QuestDB | TypeScript + Rust (`RawDocumentBuf`/Arrow/ILP) + Python/DuckDB | | Research kernel | Single API + MCP server enforcing vault cutoff, budgets, trial ledger, and canonical metrics | TypeScript (`web-api` / `orchestrator` / `@stock-bot/calculations`) | | Engine | Authoritative accounting, multi-currency margin ledger, corporate actions, fills, risk, replay | Rust (`apps/stock/engine/src/financial`) | | Python SDK + marimo | Exploration, Signal Analyzer, Event Study, Tier 1 columnar screener, feature batch definitions | Python (`polars`, `duckdb`, `marimo`) | | `web-app` | Incremental UI over Research Kernel state | TypeScript / React | --- ## 5. Data architecture and storage Full schemas and SQL contracts live in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)**. ### Layers | Layer | Store | Contents | Who writes | Who reads | | --- | --- | --- | --- | --- | | Raw | MongoDB (`stock`) | Provider documents as fetched | `data-ingestion` | `data-pipeline` only (`studio_stock_bot_read`) | | Reference | PostgreSQL | Exchanges, instruments, identifier history, listings, symbol history, provider mappings, corporate-action continuations, conflicts, overrides | `data-pipeline` | Everything | | Curated (Daily & PIT) | **Parquet + DuckDB** | `bars_1d`, `adj_factors`, `corporate_actions`, bitemporal `fundamentals` + wide PIT/TTM snapshots, `events`, `shorts`, `macro`, `fx_1d` | `data-pipeline` | `MarketDataStore` | | Curated (Intraday & Hot) | **QuestDB `10.2.0`** | `bars_1m` (`5m`/`1h` via `SAMPLE BY` or materialized), `fx_1m`, recorded live/paper IB bars & quotes, sparse `bar_revisions` | `data-pipeline`, IB bridge | `MarketDataStore` | | Features | **Parquet + DuckDB** (1d) / **QuestDB** (intraday) | Versioned precomputed feature series (`(listing_id, ts, known_at, value)`) | Feature jobs | `MarketDataStore`, Screener, Rust `Replay` | | Research & Vault state | PostgreSQL | Projects, campaigns, `trial_ledger` (with return vectors), findings, strategies, runs, `vault_evaluations` | Research kernel | App, MCP, SDK | ### Access rules & performance targets 1. **One access contract (`MarketDataStore` in TS, `stockbot.data` in Python).** Every non-vault call enforces `ts < VAULT_CUTOFF_TS` and `known_at <= asOf` inside the adapter. No raw-SQL escape hatch is exposed to agents; human localhost sessions may query read-only pre-vault DuckDB views. 2. **Storage & memory hygiene.** - `MarketDataStore` and Parquet expose `listing_id` as `INT32`; inside QuestDB `10.2.0`, `listing_id` is stored as `SYMBOL CAPACITY 65536 NOCACHE` so `LATEST ON` backward partition scans and `ASOF JOIN` fast paths work without JVM heap bloat. - QuestDB `bars_1m` uses **`PARTITION BY MONTH`** (`270` partitions across 22.5y instead of `~5,670` daily partitions) with host `vm.max_map_count >= 1048576`, `ulimits.nofile = 1048576`, and `QDB_RAM_USAGE_LIMIT_BYTES` capped (`20 GiB` on `quant`). Sealed `>90d` monthly partitions may be compressed in-place (`ALTER TABLE bars_1m CONVERT PARTITION TO PARQUET`) if NVMe capacity requires it; recent partitions remain native mmap. - Every DuckDB connection explicitly sets `memory_limit = '6GB'`, `threads = 4`, and `temp_directory` on `quant` (instead of DuckDB's `80%` host-RAM default), leaving `~24 GiB` of `quant`'s `125 GiB` unallocated for Linux NVMe page cache. 3. **Measured storage targets on `quant` (`12900K`, SN850X NVMe):** - **W1:** 20y US+CA daily universe (~15k active+delisted listings, ~45M bars) + 1 signal IC/quantile scan: **`< 3 s` warm / `< 8 s` cold**. - **W2:** 1 listing, 1y of `1m` bars (~100k–200k rows) from QuestDB: **`< 250 ms` warm / `< 1 s` cold**. - **W3:** 4 concurrent campaign workers: **p95 slowdown `< 35%`**, zero OOM or lease expiries. - **W4:** 1 date cross-section (~8k alive listings × 20 features): **`< 100 ms`**. --- ## 6. Step 1 — Cross-source merge (security master) Exact DDL and edge-case rules are specified in **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)**. ### Target model (PostgreSQL) - `exchange`: `mic` (ISO 10383 PK), `operating_mic`, `name`, `country_iso`, `currency`, `timezone`, `calendar_code`, `is_composite_or_ats`. - `exchange_source_map`: `(source, source_code)` → `mic` (or explicit non-primary role: `'composite' | 'ats_routing' | 'forex' | 'excluded_fund'`), `reviewed_by`. - `instrument`: `instrument_id` (`INT4` identity), `primary_isin`, `primary_cusip`, `canonical_name`, `security_type` (`common`, `preferred`, `unit`, `warrant`, `right`, `etf`, `cdr`, `fx`), `issuer_country`. - `instrument_identifier_history`: `(instrument_id, id_type, id_value, valid_from, valid_to, source)` — preserves continuity across TSXV share consolidations and corporate redomiciliations (`LIN`). - `listing`: permanent `listing_id` (`INT4` identity), `instrument_id`, `mic`, `ticker_root`, `class_suffix`, `currency`, `ib_conid`, `listed_from`, `listed_to`, `delist_reason`. - `listing_symbol_history`: `(listing_id, ticker, valid_from, valid_to, source)`. - `corporate_action_continuity`: `(from_listing_id, to_listing_id, effective_date, kind)` — links primary-venue delistings (`SIVB` on `XNAS`) to same-ISIN OTC continuations (`SIVBQ` on `OTCM`) so bankruptcy losses are never truncated at halt price. - `provider_mapping`: `(source, source_id, valid_from)` → `listing_id`, `valid_to`, `method`, `confidence`. - `resolution_conflict`, `override` (always wins on re-runs), and `golden_field_audit`. ### Six-pass resolution pipeline 1. **Pass 1 — Exchanges (~320 rows):** Seed ISO 10383 MICs; map EOD (`76`), IB (`214`), QM (`25`), and CEO (`4: TSX→XTSE, CDX→XTSX, CNQ→XCNQ, AQL→NEOE`). Explicitly tag EOD `US` as composite (resolved via per-symbol `eodSymbols.Exchange`), exclude EOD `NMFQS` (`44,970` mutual funds) from equity universes, and mark IB ATS/smart codes (`AEQLIT`, `ARCAEDGE`, `BEX`, `DRCTEDGE`, `EDGEA`, `IEX`, `MEMX`, `OTCLNKECN`, `PSX`, `IBEOS`) as **`ats_routing`** rather than primary listing MICs. 2. **Pass 2 — Normalization & Observed Spans:** Parse root + suffix (`AAA-P`/`AAA.P`, `AACT U`/`AACT.U`, `SCU.UN`, strip CEO `.TO`/`.V`), Luhn-validate ISINs (rejecting placeholder/checksum-bad values like `CATSETEST001`, `CA00149WBAD4`, `CA8131391062` while recovering a checksum-corrupted US/CA ISIN from a valid 9-char CUSIP, e.g. `037833100` → `US0378331005` or `82509L107` → `CA82509L1076`), fix `provider-symbol.ts` to read IB `exchangeId`/`description`, and precompute `[first_bar_date, last_bar_date]` per `(source, source_id)`. 3. **Pass 3 — Two-Stage Matching (Instrument first, Listing second):** - **Stage A (`instrument`):** Match globally by Luhn-valid ISIN and US/CA CUSIP-derived ISIN (`IB ↔ EOD`). Interlisted US/CA shares (`SHOP` on `XTSE` CAD and `XNYS` USD) share one `instrument_id` and get two `listing_id`s. - **Stage B (`listing` & non-ISIN sources):** Assign primary `listing.mic` from EOD `Exchange` + QM `exchange`; attach IB `conid` at `(instrument_id, currency)` (resolving the 83% TSX-on-`AEQLIT` and >90% NYSE/Nasdaq-on-ATS `ibSymbols` problem). Match QM and CEO by `(normalized_ticker, mic, currency)` **requiring overlapping `[first_bar_date, last_bar_date]` spans** so reused tickers (`FB` 2012–2022 Meta vs `FB` 2025 ProShares ETF; CSE `CNX`/`CC` duplicates) never collide. 4. **Pass 4 — Fast Cross-Sectional Price Cross-Check:** Extract 25 stratified trading dates via `{ date: { $in: sampleDates } }` (hitting `eodPrices`'s `{date: 1, eodSearchCode: 1}` index sequentially in seconds rather than scanning 846M docs per pair) or run in DuckDB post-extract; verify price ratio ($\approx 1.0$ or $\approx \text{USD/CAD}$) and return correlation. 5. **Pass 5 — Conflict Export & Overrides:** Write unresolved conflicts to `resolution_conflict`; review initial US+CA conflicts via generated markdown/CSV + SQL `override` seed file in Milestone 1 (deferring the React review UI until ongoing delta runs warrant it). 6. **Pass 6 — Golden Record & OTC Delisting Chains:** Populate golden fields (`IB` → `EOD` for ISIN/CUSIP/`conid`/currency; `EOD` → `QM` for name/sector/listing span) and link same-ISIN `XNAS`/`XNYS` → `OTCM` delisting continuations. --- ## 7. Step 2 — Processing the remaining datasets | Dataset | Raw sources | Curation & PIT (`known_at`) Rules | Store | | --- | --- | --- | --- | | **Daily bars** | `eodPrices`, `qmPrices` | Raw OHLC; **un-adjust `eodPrices.volume`** using cumulative `qmSplits` factors (cross-checked against raw `qmPrices.sharevolume`); `known_at` = session close | Parquet (`bars_1d`) | | **Intraday bars** | `eodIntraday1M` (US 2003–2025), `qmIntraday` (CA/US 2024–2025) | **Un-adjust `eodIntraday1M` OHLCV** for post-bar splits (cross-checked against `qmIntraday` raw & `bars_1d`); enforce venue session calendars | QuestDB `10.2.0` (`bars_1m`) | | **Corporate actions** | `qmSplits`, `qmDividends`, `eodPrices`/`qmPrices` spans | Drop `splitratio == 1` no-ops; ignore bogus `qmDividends.usdFxRate: 1`; link same-ISIN OTC delistings (`SIVB`→`SIVBQ`) + apply Shumway terminal delisting returns (`-30%` involuntary unlinked delist, `-100%` cancelled `-Q`/Pink) | Parquet (`corporate_actions`, `adj_factors`) | | **Fundamentals** | `qmFinancials`, `qmFinancials-old` + `qmFilings` (`eodFinancialsOLD` pre-QM fallback only; **`eodFundamentalsOLD` snapshots quarantined**) | Join `(listing_id, periodEndDate)` to earliest matching `10-Q`/`10-K`/`40-F`/SEDAR `Interim/Annual financial statements` `timefiled` in `qmFilings`. Fallback: statutory lag (`+45d Q / +90d FY` US & TSX; **`+60d Q / +120d FY` TSXV/CSE**) tagged `known_at_source = 'statutory_lag_estimate'`. Materialize 2D `(period_end, known_at)` deduplicated wide PIT + TTM snapshots. | Parquet (`fundamentals_pit`) | | **Earnings** | `qmEarnings` + `qmFilings` | Resolve `"announceTime": "N/A"` (`66.9%` of rows) via `qmFilings` `8-K` / `News release` `timefiled`; otherwise lag to `reportDate 16:05 ET` (tradable `T+1` open) | Parquet (`events`) | | **Filings** | `qmFilings` (`30.5M`) | Parse `timefiled` (`EST`/`EDT` → UTC); expose form-type & filing-arrival events (Form 4 / 144 / 8-K / NI 43-101 / 45-106F1 counts; insider share/dollar parsing deferred) | Parquet (`events`) | | **CEO posts** | `ceoPosts` (`14.8M`) via `ceoSymbols` | Separate `bot == "1"` (`@thenewswire`) from retail posts; if `edited != null` (`1.8%`), guard text features with `known_at = edited` | Parquet (`events`) | | **Shorts** | `ceoShorts` (`693k`, CA 2017–2025) | Stamp `known_at = report_timestamp + 4 Canadian business days (17:00 ET)` to match CIRO dissemination lag | Parquet (`shorts`) | | **Macro** | `teCountries`, `teIndicators`, `teData` | Lagged publication cutoffs (`+1d` policy rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP); **regime filters only** (final-revised values, no release event studies) | Parquet (`macro`) | | **FX** | `eodPrices`/`eodIntraday1M` (`CAD.FOREX`, `CADUSD.FOREX`) + `teMarketData` (`USDCAD`) | Curate existing 1971–2026 daily + `5.2M` `1m` USD/CAD series immediately; add IB `USD.CAD` live feed in Milestone 5 | Parquet (`fx_1d`) + QuestDB (`fx_1m`) | --- ## 8. Feature library Features are defined once as **versioned DuckDB SQL or Python/Polars batch jobs** (`features//_v`), materialized to Parquet/QuestDB with `(listing_id, ts, known_at, value: f64)`, and registered with warm-up length, inputs, `known_at` rule, and unit tests: - **Technical:** multi-horizon log/simple returns, realized vol, Wilder RSI (`flatValue = 50.0` standardized), ATR, MA distance, overnight/intraday gaps, dollar-volume z-score (on un-adjusted volume!), VWAP distance, opening range. - **Cross-sectional:** universe/sector-neutralized ranks and winsorized z-scores per date. - **Fundamental (PIT):** E/P, B/P, FCF yield, ROE, gross/operating margins, Sloan accruals, YoY asset/revenue growth, net-debt/EBITDA — computed strictly from 2D-deduplicated TTM snapshots. - **Event & Canadian alt-data:** days since/until earnings, filing-burst flags (`45-106F1` financings, `NI 43-101`, Form 4/144 clusters), CEO.ca retail vs newswire post velocity, CIRO short-interest % of float & semi-monthly $\Delta$ days-to-cover. - **Cross-border & FX:** interlisted TSX vs NYSE CAD-adjusted basis (`CAD.FOREX` 1m/1d) and lead-lag spreads. - **Regime:** market breadth, realized-vol state, sector dispersion, lagged central-bank/CPI/PMI state. **Promotion bridge (D11):** Calling `register_signal(...)` from Python/marimo registers a versioned batch feature job. Rust `Replay` and TypeScript `StrategyContext` receive a read-only `features: Record` map at each decision barrier — so zero indicator or statistical math is ever rewritten in zero-import TypeScript. --- ## 9. Backtesting Mathematical formulas and ledger schemas are specified in **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)**. ### Tier 1 — Fast columnar screener (Polars / DuckDB) - Evaluates hundreds to thousands of `feature × horizon × universe × rebalance` variants in seconds over precomputed Parquet columns, applying linear spread + commission + borrow-rate turnover haircuts. - Net-new columnar screener (distinct from deferred backlog task `P06`, which remains closed; `D04` shared features and `P03` worker dataset caching are reopened instead). - Finds candidates only; **never** certifies a strategy. Logs the complete synchronous return matrix $M_{T \times N}$ to `trial_ledger` in one atomic batch. ### Tier 2 — Authoritative Rust portfolio engine (`apps/stock/engine/src/financial`) Extends the existing 8-decimal Rust kernel (retiring legacy `f64` `BacktestEngine` and TypeScript `SimulationExecution` upon cutover): - **Atomic timestamp-slice marking (`F06` fix):** Apply all instrument marks at timestamp `t` before evaluating `RiskAccount` portfolio drawdown/daily-loss latches so hedged long/short moves never trigger false intermediate halts. - **Simultaneous target rebalancing:** Credit haircut-adjusted pending `Sell` proceeds against same-barrier `Buy` reservations in `MatchingAccount::submit` so fully invested cross-sectional rotations execute cleanly in one barrier. - **Zero-JSON market-data path & Feature side-channel:** Eliminate the 8× JSON/Zod/IPC/N-API bar path (`backtest_datasets.payload` `255 MB` `JSONB` ceiling, `structuredClone`, `fork({ serialization: 'json' })`, and `api/canonical.rs` triple `serde_json::Value` parse). Retain only `(hash, manifest, parquet_paths)` in PostgreSQL, read Parquet/Arrow columns directly inside Rust `Replay`, restrict `canonical.rs` `keys_match` to small control/config envelopes, and stream multi-asset decision-barrier slices to `candidate-sandbox.ts` as compact **Arrow IPC / flat `Float64Array` binary frames** on declared rebalance barriers. - **Long/short, multi-currency margin & corporate actions:** Signed quantities/targets, short borrow fee accrual, `BTreeMap` (`USD` + `CAD` cash/margin balances with IB benchmark+spread interest on negative balances, plus tradable FX pairs), ex-date split share adjustments, cash dividend postings, TSX/TSXV board-lot sizing (`100`/`500`/`1,000` shares), and OTC/Shumway delisting liquidations. ### Validation suite, Trial Ledger & 6-Month Vault - **Trial ledger (`trial_ledger` in PostgreSQL):** Groups trials deterministically by `(universe_market, horizon_bucket)` (`{US, CA, US_CA, FX} × {intraday, swing_1_10d, position_10d_plus}`) and stores each variant's out-of-warmup daily return/IC vector (`FLOAT4[]`) to compute Bailey & López de Prado **effective independent trials $\hat{N}$**, non-normal **Deflated Sharpe Ratio (DSR $\ge 0.95$)**, and **PBO ($\le 0.20$)** via CSCV ($S = 16$). - **Purged Walk-Forward & CPCV:** Replaces `labelHorizonMs = 0` with mandatory `purge = horizon + warmup` and `embargo = max(5d, 0.01 * T)`. - **Post-2023 Recency Gate:** Post-2023 IC and Sharpe must be positive and $\ge 50\%$ of pre-2023 levels so decayed pre-LLM anomalies fail automatically. - **Rolling 6-Month Air-Gapped Vault (`D10`):** Most recent 6 months (~126 trading days) fenced off from all research/MCP/marimo reads; evaluated **once** when **you** promote a `Validated` strategy toward `Paper` ($\le 10$ vault evaluations/year recorded in immutable `vault_evaluations`). --- ## 10. Orchestration - **Single-host research & campaign execution on `quant` (`12900K`):** With 24 threads, 125 GiB RAM, and 3.6 TiB NVMe on `quant`, all databases, DuckDB/QuestDB stores, and 4–8 worker-pool slots run locally on `quant` — avoiding distributed multi-host worker complexity until 24 cores saturate. - **Campaigns with hard SQL budgets:** `campaign → experiments → trials`, with cumulative trial, bar-evaluation, and wall-clock caps enforced by PostgreSQL `BEFORE INSERT` triggers (closing today's concurrent-only `active_trials` gap). - **Shared dataset/feature memory (`P03`):** Trials in a campaign share memory-mapped Parquet/Arrow columns on `quant`. - **Notifications:** Desktop/phone alerts (ntfy or Discord) when campaigns complete, vault candidates surface, or data monitors trip. --- ## 11. Research and analytics playground 1. **Exploration Lab (built first):** - **Signal Analyzer:** IC, rank-IC, decay across `1d/5d/20d`, quantile spreads, turnover, breakeven cost, and breakdowns by regime, sector, market-cap tier, country (`US` vs `CA`), and pre/post-2023. - **Event Study:** Pre/post abnormal return fans around filings (`NI 43-101`, `45-106F1`, Form 4/8-K), earnings, CIRO short spikes, and CEO.ca bursts. - **marimo Labs (`D9`):** - `marimo edit ./research/notebooks --watch --mcp` runs on a **dedicated loopback origin (`127.0.0.1:2718`)** with token auth so iframe scripts never share `web-app`'s `SameSite=Strict` `stock_bot_session` cookie. - Agent findings attach **static HTML exports (`marimo export html`)** rendered in `