- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
42 KiB
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 — executable milestone checklist (
M0→M5), scope cuts, and exit criteria. - DATA-CONTRACTS.md — raw provider quirks, security-master DDL,
known_atrules, and Parquet/QuestDB schemas. - VALIDATION-AND-RIGOR.md — canonical metrics, trial ledger (
\hat{N}DSR & PBO), 6-month Vault, recency gate, and IB/TSX execution rules.
Contents
- Vision and principles
- Where the project stands
- Decisions log
- System architecture
- Data architecture and storage
- Step 1 — Cross-source merge (security master)
- Step 2 — Processing the remaining datasets
- Feature library
- Backtesting
- Orchestration
- Research and analytics playground
- Agent layer
- Execution: paper to live on IB
- The app
- Strategy lifecycle
- 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.2M1m bars), and3.4B1m 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
- 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_timestampvsstatutory_lag_estimate) so strategies never unknowingly trade estimated timestamps at intraday precision. - 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/calculationsowns 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.
- Rust (
- 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.
- 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. - 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.
- Rigor lives in the engine, not the UX. Keep receipts, fencing, and provenance underneath. Make the surface fast and playful.
- Raw stays raw. MongoDB is the provider landing zone. Only
data-pipelinereads it viaMONGODB_READ_URI(studio_stock_bot_read). - 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 typedResearchClient; - a 1/2/4-slot worker pool and human-reviewed paper deployments;
- full
quantserver 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:85expectsdocker-compose.ymlafterscripts/docker.shswitched default todev) andlint:check(63 curly errors + 2 warnings = 65:61inphase1-inventory.ts,4in WIP files). - Dev PostgreSQL init bug:
database/postgres/init/01–05hardcode\c trading_bot;, leavingtrading_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 bypassingmongoReadOnly, used by legacysync-ib-exchanges.operations.ts;env-safety.tswarns instead of throwing whendataPipelineusestrading_admin. - Credential & holdout leaks:
apps/stock/data-ingestion/src/handlers/ib/shared/config.ts:19contains a hardcoded proxy URL credential;research-agents.service.ts:51allowssb-research.*tokens to call/api/v2/datasets/canonical/:hash/export(leaking holdout bars) and lacks cumulative lifetime/campaign trial caps;data-ingestionruns scheduled crawls on boot unlessQUEUE_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
┌────────────────────────────────────────────┐
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.
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
- One access contract (
MarketDataStorein TS,stockbot.datain Python). Every non-vault call enforcests < VAULT_CUTOFF_TSandknown_at <= asOfinside the adapter. No raw-SQL escape hatch is exposed to agents; human localhost sessions may query read-only pre-vault DuckDB views. - Storage & memory hygiene.
MarketDataStoreand Parquet exposelisting_idasINT32; inside QuestDB10.2.0,listing_idis stored asSYMBOL CAPACITY 65536 NOCACHEsoLATEST ONbackward partition scans andASOF JOINfast paths work without JVM heap bloat.- QuestDB
bars_1musesPARTITION BY MONTH(270partitions across 22.5y instead of~5,670daily partitions) with hostvm.max_map_count >= 1048576,ulimits.nofile = 1048576, andQDB_RAM_USAGE_LIMIT_BYTEScapped (20 GiBonquant). Sealed>90dmonthly 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, andtemp_directoryonquant(instead of DuckDB's80%host-RAM default), leaving~24 GiBofquant's125 GiBunallocated for Linux NVMe page cache.
- 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 swarm /< 8 scold. - W2: 1 listing, 1y of
1mbars (~100k–200k rows) from QuestDB:< 250 mswarm /< 1 scold. - 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.
- W1: 20y US+CA daily universe (~15k active+delisted listings, ~45M bars) + 1 signal IC/quantile scan:
6. Step 1 — Cross-source merge (security master)
Exact DDL and edge-case rules are specified in 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(INT4identity),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: permanentlisting_id(INT4identity),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 (SIVBonXNAS) to same-ISIN OTC continuations (SIVBQonOTCM) 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), andgolden_field_audit.
Six-pass resolution pipeline
- 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 EODUSas composite (resolved via per-symboleodSymbols.Exchange), exclude EODNMFQS(44,970mutual funds) from equity universes, and mark IB ATS/smart codes (AEQLIT,ARCAEDGE,BEX,DRCTEDGE,EDGEA,IEX,MEMX,OTCLNKECN,PSX,IBEOS) asats_routingrather than primary listing MICs. - 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 (rejectingCATSETEST001,CA00149WBAD4, checksum-corruptedCA8131391062while recovering valid CUSIP813139106→CA8131391064), fixprovider-symbol.tsto read IBexchangeId/description, and precompute[first_bar_date, last_bar_date]per(source, source_id). - 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 (SHOPonXTSECAD andXNYSUSD) share oneinstrument_idand get twolisting_ids. - Stage B (
listing& non-ISIN sources): Assign primarylisting.micfrom EODExchange+ QMexchange; attach IBconidat(instrument_id, currency)(resolving the 83% TSX-on-AEQLITand >90% NYSE/Nasdaq-on-ATSibSymbolsproblem). Match QM and CEO by(normalized_ticker, mic, currency)requiring overlapping[first_bar_date, last_bar_date]spans so reused tickers (FB2012–2022 Meta vsFB2025 ProShares ETF; CSECNX/CCduplicates) never collide.
- Stage A (
- Pass 4 — Fast Cross-Sectional Price Cross-Check: Extract 25 stratified trading dates via
{ date: { $in: sampleDates } }(hittingeodPrices'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.0or\approx \text{USD/CAD}) and return correlation. - Pass 5 — Conflict Export & Overrides: Write unresolved conflicts to
resolution_conflict; review initial US+CA conflicts via generated markdown/CSV + SQLoverrideseed file in Milestone 1 (deferring the React review UI until ongoing delta runs warrant it). - Pass 6 — Golden Record & OTC Delisting Chains: Populate golden fields (
IB→EODfor ISIN/CUSIP/conid/currency;EOD→QMfor name/sector/listing span) and link same-ISINXNAS/XNYS→OTCMdelisting 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/<family>/<name>_v<k>), 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.0standardized), 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-106F1financings,NI 43-101, Form 4/144 clusters), CEO.ca retail vs newswire post velocity, CIRO short-interest % of float & semi-monthly\Deltadays-to-cover. - Cross-border & FX: interlisted TSX vs NYSE CAD-adjusted basis (
CAD.FOREX1m/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<string, number | null> 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.
Tier 1 — Fast columnar screener (Polars / DuckDB)
- Evaluates hundreds to thousands of
feature × horizon × universe × rebalancevariants 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;D04shared features andP03worker dataset caching are reopened instead). - Finds candidates only; never certifies a strategy. Logs the complete synchronous return matrix
M_{T \times N}totrial_ledgerin 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 (
F06fix): Apply all instrument marks at timestamptbefore evaluatingRiskAccountportfolio drawdown/daily-loss latches so hedged long/short moves never trigger false intermediate halts. - Simultaneous target rebalancing: Credit haircut-adjusted pending
Sellproceeds against same-barrierBuyreservations inMatchingAccount::submitso 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.payload255 MBJSONBceiling,structuredClone,fork({ serialization: 'json' }), andapi/canonical.rstripleserde_json::Valueparse). Retain only(hash, manifest, parquet_paths)in PostgreSQL, read Parquet/Arrow columns directly inside RustReplay, restrictcanonical.rskeys_matchto small control/config envelopes, and stream multi-asset decision-barrier slices tocandidate-sandbox.tsas compact Arrow IPC / flatFloat64Arraybinary frames on declared rebalance barriers. - Long/short, multi-currency margin & corporate actions: Signed quantities/targets, short borrow fee accrual,
BTreeMap<Currency, Posting>(USD+CADcash/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,000shares), and OTC/Shumway delisting liquidations.
Validation suite, Trial Ledger & 6-Month Vault
- Trial ledger (
trial_ledgerin 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 = 0with mandatorypurge = horizon + warmupandembargo = 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 aValidatedstrategy towardPaper(\le 10vault evaluations/year recorded in immutablevault_evaluations).
10. Orchestration
- Single-host research & campaign execution on
quant(12900K): With 24 threads, 125 GiB RAM, and 3.6 TiB NVMe onquant, all databases, DuckDB/QuestDB stores, and 4–8 worker-pool slots run locally onquant— 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 PostgreSQLBEFORE INSERTtriggers (closing today's concurrent-onlyactive_trialsgap). - Shared dataset/feature memory (
P03): Trials in a campaign share memory-mapped Parquet/Arrow columns onquant. - Notifications: Desktop/phone alerts (ntfy or Discord) when campaigns complete, vault candidates surface, or data monitors trip.
11. Research and analytics playground
- 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 (USvsCA), 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 --mcpruns on a dedicated loopback origin (127.0.0.1:2718) with token auth so iframe scripts never shareweb-app'sSameSite=Strictstock_bot_sessioncookie.- Agent findings attach static HTML exports (
marimo export html) rendered in<iframe sandbox="allow-scripts" srcDoc={...}>(zero idle Python RAM); interactivemarimo run --session-ttl 300launches on-demand only. - Agent notebook writes must pass
marimo check --format=json(0errors) and use_-prefixed cell-local variables for heavy Polars frames.
- Signal Analyzer: IC, rank-IC, decay across
- Tearsheets: Equity, underwater drawdown, rolling Sharpe, trade-to-bar drill-down (over unified
lightweight-charts), exposures, capacity, full validation suite (DSR,PBO,CPCV, recency), and live dual drift. - Agent Lab Feed: Findings + dead ends linked to immutable trial counts, $\hat{N}$-adjusted DSR, and static HTML notebook snapshots, with one-click
Approve / Reject / Dig deeper / Promote to Paper (run 6m Vault). - Market Intelligence (
Markets&Home): Built incrementally in Phase 4 once core research and portfolio backtesting are live.
12. Agent layer
- Roles:
Scout(Studio/notes → testable hypothesis + economic rationale),Data Analyst(coverage &known_at_sourcecheck),Signal Researcher(IC / event studies),Strategy Builder(register_signal→ Tier 1 screen → Tier 2 Rust backtest),Skeptic(audits look-ahead, split/volume artifacts, liquidity/board-lots, post-2023 decay, multiple testing),Portfolio Manager(marginal Sharpe & correlation vs existing book),Monitor(paper/live drift & decay). - Knowledge base (
D12): MCP mounts Studio's 83-card~/repos/studio/catalog/quant/library/library.ymlread-only for statistical/methodological cards, while PostgreSQL stores Stock Bot's empiricalfindings,dead_ends, andprovider_caveats. - Security & isolation:
- Desktop Claude Code connects via MCP (
D2) for interactive copilot work. - Autonomous campaign agents run in network-isolated containers reaching only the Research Kernel MCP/HTTP endpoint (
sb-research.*tokens with/exportrevoked,GETroutes project-scoped, and SQL cumulative trial caps).
- Desktop Claude Code connects via MCP (
- Studio bridge: Studio Quant ideas (
hypothesis) trigger bounded Stock Bot campaigns via API and receive structuredverdict + DSR + tearsheet/HTML linkreceipts back.
13. Execution: paper to live on IB
Deployed on the dedicated, isolated 9900K host (docs/servers.md) in Milestone 5:
- Paper runtime fixes (prerequisite): Compact
simulation_accountsstate (periodic snapshot + tail receipts, eliminating today'sO(N)double genesis replay inapps/stock/engine/src/api/paper.rs), exposeMatchingResetover NAPI, and execute non-builtin strategy code inside theA02sandbox rather than importing raw JS into the privilegedpaper-hostprocess. - IB Gateway & Market Data Bridge: Headless
IB Gatewaysupervised byIBC(handling nightly ~21:00 ET resets and1100→1102stream re-subscriptions). AggregatesreqRealTimeBars(5s, TRADES)+ L1reqMktDataquotes into session-aligned bars emitted after bar-close + 2s grace, budgeted to\le 80concurrent symbols within IBKR's standard 100-line cap. - Contract & Canadian market-structure rules:
- Pin
(conid, symbol, currency, exchange="SMART", primaryExchange)fromlistingso interlisted US/CA tickers (SHOP,RY,TD) never route across borders. - Enforce TSX/TSXV price-tiered board lots (
100sh $\ge $1.00$,500sh $$0.10\text{–}$0.995$,1,000sh $< $0.10$) and auction cutoffs (15:40 ETTSX MOC vs15:50 ETNYSE/Nasdaq MOC).
- Pin
- IBKR Margin
USD/CAD& FX policy:- Track separate
USDandCADcash/margin sub-ledgers in RustLedger, accruing daily IBKR benchmark+spread interest on negative currency balances. - Route cash-funding conversions to
exchange="FXCONV"($2min, updates cash without creating virtual FX positions); route intentional FX alpha trades toexchange="IDEALPRO".
- Track separate
- OMS, Risk & Dual Drift Monitoring:
- Idempotent client order IDs, partial-fill state machine, continuous broker-vs-ledger position/cash reconciliation, per-strategy + global daily-loss/drawdown/order-rate kill switches.
- Dual Drift Monitor: separates (1) Execution Drift (live IB fills vs Rust replay on recorded live IB bars/quotes) from (2) Feed Basis Drift (Rust replay on recorded IB bars vs next-day curated EOD/QM bars).
14. The app
Evolves incrementally (D4) from today's 29.6k-line React codebase (apps/stock/web-app/src/features/*):
- Immediate cleanup: Wire existing
ResearchAgentsPage.tsx(/research/agents) intoSidebar.tsxand consolidate the two separatelightweight-chartswrappers (src/components/charts/Chart.tsxandsrc/features/charts/components/SymbolChart.tsx). - Target navigation (delivered with each milestone):
- Lab (Signal Analyzer, Event Study, static-HTML + live marimo link)
- Strategies (lifecycle stages, tearsheets, CPCV/DSR/PBO + 6m Vault gate)
- Agents (campaigns, budgets, findings/dead-ends feed,
sb-research.*tokens) - Data (
exchanges/symbols/pipeline+ coverage map, quality monitors, conflict queue) - Trading (
paper+ IB live positions, USD/CAD cash & margin, Dual Drift, kill switches) - Markets & Home (greenfield — note
src/features/dashboardis currently empty and deferred until Milestone 4).
15. Strategy lifecycle
Idea ─▶ Hypothesis ─▶ Signal ─▶ Candidate ─▶ Validated ──[You: 6m Vault]──▶ Paper ─▶ Live ─▶ Retired
| Stage | Quantitative Gate to Enter | Who Approves |
|---|---|---|
| Hypothesis | Economic rationale, target universe/horizon, known_at_source verified clean |
Agent (Scout + Data Analyst) |
| Signal | $ | \overline{\text{Rank IC}} |
| Candidate | Tier 1 screen net Sharpe \ge 1.0 at 1.5\times costs; turnover within 2\% ADV |
Agent |
| Validated | Tier 2 Rust engine + Purged Walk-Forward/CPCV: DSR $\ge 0.95$ (cluster \hat{N}), PBO $\le 0.20$, net Sharpe > 0 at 2.0\times costs + Skeptic sign-off |
Agent proposes to Lab Feed |
| Paper | One-shot 6-month Vault Holdout Sharpe > 0.5 & within 1.5\sigma of CPCV + manual code/evidence review |
You |
| Live | \ge 30 paper trading days & \ge 50 trades; Execution Drift \le 15\text{ bps/trade}; 0 unrecovered reconciliation breaks |
You (small → scaled) |
| Retired | Rolling decay or drift beyond bounds, or manual halt | Monitor proposes, You confirm |
16. Roadmap
Detailed checklists, file targets, and exit criteria live in MILESTONES.md:
| Milestone | Delivers | Target Window |
|---|---|---|
| M0 — Safety & Gate Lock | All 11 gates green, dev PG \c bug fixed, @stock-bot/postgres migrations, MongoDBClient readOnly leak closed, proxy secret purged, sb-research.* /export blocked |
Days 1–3 |
| M1 — Vertical Slice 1 (Security Master + Daily/Event Signal Lab) | US+CA security master (Passes 1–6 via SQL/CSV overrides), curated bars_1d + corporate_actions + fx_1d + qmFilings/qmEarnings/ceoShorts in DuckDB+Parquet, 6m Vault fence, trial_ledger + DSR, Python stockbot SDK + marimo Signal Analyzer |
Weeks 1–3 |
| M2 — MCP Copilot, Intraday QuestDB & PIT Fundamentals | MCP server + Studio library mount, qmFinancials × qmFilings 2D PIT fundamentals, QuestDB 10.2.0 bars_1m + fx_1m (split-unadjusted), versioned batch Feature Library |
Weeks 4–5 |
| M3 — Portfolio Backtest v2 (Screener + Multi-Asset Rust) | Tier 1 columnar screener, Tier 2 Rust multi-asset upgrades (atomic marks, target sell-netting, features channel, long/short margin, USD/CAD, corporate actions, OTC delistings, Arrow load), CPCV + PBO + Vault promotion gate |
Weeks 6–9 |
| M4 — Autonomous Campaigns, Studio Bridge & Lab UI | Containerized campaign runner with SQL cumulative budgets, agent roles + Skeptic, Studio webhook bridge, unified web-app Lab/Agents/Data/Markets/Home screens |
Weeks 10–12 |
M5 — Compacted Paper → Live IB Margin (9900K) |
paper.rs state compaction + sandboxed paper candidates, headless IB Gateway + IBC bridge on 9900K, OMS + TSX board-lots + FXCONV, continuous reconciliation, Dual Drift Monitor, small-capital live |
Weeks 13–16 |