380 lines
28 KiB
Markdown
380 lines
28 KiB
Markdown
# Stock Bot — Data, Security Master & Storage Contracts
|
||
|
||
Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, DuckDB/Parquet + QuestDB `10.2.0` curated tables, and `MarketDataStore`. Every rule below was verified against live QA MongoDB (`stock`, 31 collections) on 2026-11-26.
|
||
|
||
---
|
||
|
||
## 1. Empirical Provider Rules & Traps (QA MongoDB `stock`)
|
||
|
||
`data-pipeline` connects strictly read-only via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`). Never trust raw field names without applying the provider-specific transformations below:
|
||
|
||
| Collection (Docs) | Verified Empirical Behavior | Mandatory `data-pipeline` Rule |
|
||
| --- | --- | --- |
|
||
| `eodPrices` (`845.7M`) | `open/high/low/close` are **raw**, **but `volume` is retroactively split-adjusted** (`NVDA` pre-10:1 split `2024-06-07` has `close=1208.88`, `volume=412.39M` = $10\times$ raw; `X.TO` pre-5:1 split has $5\times$ raw volume). Indexes: `{date:1, eodSearchCode:1}` and `{eodSearchCode:1}` (no `{eodSearchCode:1, date:1}`). | Divide historical `volume` by cumulative post-bar split factor so `close * raw_volume` equals true dollar volume; cross-check against `qmPrices.sharevolume`. Query cross-sectional slices by `date` first when scanning MongoDB. |
|
||
| `qmPrices` (`51.5M`) | `unadjustedopen..unadjustedclose` and `sharevolume` are **genuinely raw** (both price and share count). Index: `{qmSearchCode:1, date:1}`. | Use as primary raw-volume truth and cross-check partner for `eodPrices`. |
|
||
| `eodIntraday1M` (`3.40B`) | **OHLCV is ALREADY retroactively split-adjusted** (`NEXM.V` pre-1:20 reverse split on `2025-06-18` reports `close=24.29` instead of raw `~1.21`). Covers US deeply back to Dec 2003; sparse/empty on many TSX tickers (`SHOP.TO` has `0` rows). | Un-adjust pre-split OHLCV using cumulative split factors before writing raw `bars_1m` (or never re-apply `adj_factors` on top without un-adjusting first!). Verify `1m` session close vs raw `bars_1d.close`. |
|
||
| `qmIntraday` (`173.3M`) | Stores **both** raw (`open..close`, `sharevolume`) and adjusted (`adjustedopen..adjustedclose`, `avolume`). Covers TSX/CA (`SHOP:CA`, `X:CA`) from ~May 2024 onward. | Primary `1m` intraday source for Canadian listings where `eodIntraday1M` is empty, and split-calibration truth for overlapping symbols. |
|
||
| `eodSymbols` (`317.8k`) | `103.8k` rows have composite `eodExchange="US"`, of which **`44,970` (`43.3%`) have `Exchange="NMFQS"` (mutual funds)**, `18,114` `PINK`, `15,858` `NASDAQ`, `9,879` `NYSE`. `52,745` US + `3,136` CA rows have `delisted=true`. EOD retroactively renames changed tickers (`META.US` holds 2012–2022 Facebook; `FB.US` is now a 2025 ProShares ETF) and overwrote pre-bankruptcy `GM.US` (`starts 2010-11-18`) and `HTZ.US` (`starts 2021-07-01`). | Resolve US MIC from `eodSymbols.Exchange` (not `eodExchange="US"`); exclude `NMFQS` from equity universes; never assume `Code.US` is a single historical company without checking bar spans and `qmFilings`. |
|
||
| `ibSymbols` (`18,402`) | Fields use **`exchangeId`** and **`description`** (which legacy `provider-symbol.ts` ignored). `100%` ISIN/CUSIP/`conid`, **but `exchangeId` is an execution/ATS venue, NOT primary listing MIC**: CA has `AEQLIT=2,506` (`65%`) vs `TSE=514`; US has `OTCLNKECN=6,627`, `ARCAEDGE=1,067`, `BEX=777`, `DRCTEDGE=682`, `IEX=509` vs **`NYSE=370` (`2.5%`) and `NASDAQ=241` (`1.7%`)**! Contains placeholder/checksum-bad ISINs (`CATSETEST001`, `CA00149WBAD4`, `CA8131391062` for `SCU.UN`). | **Never block `ibSymbols` on MIC.** Validate ISIN Luhn check digit (derive `US`/`CA` + CUSIP + check digit when ISIN checksum fails on a valid 9-char CUSIP), match globally to `instrument`, and attach `conid` to `listing` by `(instrument_id, currency)`. |
|
||
| `qmSymbols` (`47,243`) | `0%` ISIN/CUSIP; `15,790` US + `3,626` CA rows have `active=false`. Contains duplicate `(symbol, exchange)` pairs on CSE (`VOY:CNX` active + `VOY:CC` inactive). | Disambiguate via `active` flag, `qmSearchCode`, and observed `[first_bar_date, last_bar_date]` overlap. |
|
||
| `ceoSymbols` (`12,589`), `ceoPosts` (`14.78M`), `ceoShorts` (`692.9k`) | 100% Canadian (`CNQ=4,583`, `TSX=4,127`, `CDX=3,292`, `AQL=587`). `ceoSymbols.symbol` embeds `.TO`/`.V` suffixes. `ceoPosts` has `1.8%` edited posts (`edited != null` mutates `spiel`) and `bot="1"` (`@thenewswire`). `ceoShorts.timestamp` is the 15th / month-end **report period date**, NOT CIRO dissemination date. | Map `TSX→XTSE`, `CDX→XTSX`, `CNQ→XCNQ`, `AQL→NEOE`; strip embedded `.TO`/`.V`; separate `bot="1"` posts and set text `known_at = COALESCE(edited, timestamp)`; set `ceoShorts` `known_at = timestamp + 4 Canadian business days (17:00 ET)`. |
|
||
| `qmFinancials` (`1.86M`), `qmFinancials-old` (`908k`) | Standardized `BalanceSheet`, `CashFlow`, `IncomeStatement`, `periodEndDate`, `reportDate` — **`0%` `filingDate` and `0` restatement versions** (overwritten in place). | Derive `known_at` by joining `(listing_id, periodEndDate)` to `qmFilings.timefiled`; where unlinked, add statutory deadline lag (`+45d Q / +90d FY` US & TSX; `+60d Q / +120d FY` TSXV/CSE) with `known_at_source = 'statutory_lag_estimate'`. |
|
||
| `eodFinancialsOLD` (`2.98M`), `eodFundamentalsOLD` (`106.6k`) | `eodFinancialsOLD` sets `filingDate == reportDate` on **`99.26%`** of rows. `eodFundamentalsOLD` has `filing_date: null`, unversioned current valuation ratios, and mislabels USD figures as `"CAD"` on NEO CDRs (`AAPL` CDR `$335B` assets). | **Quarantine `eodFundamentalsOLD` `Highlights`/`Valuation` from all backtests.** Use `eodFinancialsOLD` only for pre-QM historical backfill with mandatory statutory lag (ignoring its `filingDate`). |
|
||
| `qmFilings` (`30.52M`) | Has exact second-level `timefiled` (`"2025-01-31T06:01:27 EST"`) for both US EDGAR (`10-Q`, `10-K`, `8-K`, `4`, `144`) and **Canadian SEDAR+** (`Interim financial statements/report`, `Annual financial statements`, `MD&A`, `52-109`, `NI 43-101`, `45-106F1`). Metadata + external download URLs only (no parsed Form 4 share counts). | Primary `known_at` clock for `qmFinancials` and `qmEarnings`, plus standalone filing-arrival/form-type event stream. Convert `EST`/`EDT` strings cleanly using `America/New_York` rules. |
|
||
| `qmEarnings` (`444.9k`) | `66.94%` (`297,779`) have `announceTime="N/A"` (`80,481` `AMC`, `66,605` `BTO`); `consensusEps` is overwritten post-hoc. | Link to same-day `qmFilings` `8-K` / `News release` `timefiled`; if still unknown, set `known_at = reportDate 16:05 ET` (tradable `T+1` open). |
|
||
| `qmDividends` (`495.9k`), `qmSplits` (`18.8k`), `eodSymbolChange` (`230`) | `qmDividends`: `82.3%` have `declared < date`, bogus `usdFxRate: 1` on CAD rows. `qmSplits`: `30.1%` have `declared`, `258` have `splitratio == 1`; empirically across `16,892/16,892` rows with numeric `forfactor`/`tofactor` (`100%`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g. `NVDA 2024-06-10`: `forfactor=1, tofactor=10, splitratio=0.1`; `GE 2021-08-02`: `forfactor=8, tofactor=1, splitratio=8`). `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; invert QuoteMedia `qmSplits` to canonical `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1) else `1 / splitratio`; never rely on `eodSymbolChange` for multi-year ticker history. |
|
||
| `teData` (`14.8k`), `teMarketData` (`435`), `CAD.FOREX` | `teData` has `{d, v}` final-revised values only (no release dates/vintages). `CAD.FOREX` (`eodPrices` `12,109` 1d, `eodIntraday1M` `5.20M` 1m) + `teMarketData.USDCAD` (`2,865` 1d through Apr 2026) already provide complete USD/CAD history. | Lag `teData` (`+1d` central-bank rates, `+35d` monthly CPI/NFP, `+65d/+90d` GDP) for coarse regime filters only. Curate `CAD.FOREX` + `teMarketData.USDCAD` directly into `fx_1d` and `fx_1m`. |
|
||
|
||
---
|
||
|
||
## 2. Security Master Schema (PostgreSQL)
|
||
|
||
Applied via `@stock-bot/postgres` (`master` migration track; no `\c` meta-commands):
|
||
|
||
```sql
|
||
CREATE TABLE IF NOT EXISTS exchange (
|
||
mic VARCHAR(10) PRIMARY KEY, -- ISO 10383 (e.g. XNYS, XNAS, XTSE, XTSX, XCNQ, NEOE, OTCM)
|
||
operating_mic VARCHAR(10) NOT NULL,
|
||
name TEXT NOT NULL,
|
||
country_iso CHAR(2) NOT NULL,
|
||
currency CHAR(3) NOT NULL,
|
||
timezone TEXT NOT NULL, -- e.g. 'America/New_York', 'America/Toronto'
|
||
calendar_code VARCHAR(16) NOT NULL,
|
||
board_lot_policy VARCHAR(16) NOT NULL DEFAULT 'us_100'
|
||
CHECK (board_lot_policy IN ('us_100', 'tsx_tiered', 'fx')),
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS exchange_source_map (
|
||
source VARCHAR(16) NOT NULL, -- 'eod' | 'qm' | 'ib' | 'ceo'
|
||
source_code VARCHAR(32) NOT NULL,
|
||
role VARCHAR(20) NOT NULL
|
||
CHECK (role IN ('primary_venue', 'composite', 'ats_routing', 'forex', 'excluded_fund')),
|
||
mic VARCHAR(10) REFERENCES exchange(mic),
|
||
country_iso CHAR(2),
|
||
method VARCHAR(32) NOT NULL,
|
||
reviewed_by TEXT,
|
||
PRIMARY KEY (source, source_code)
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS instrument (
|
||
instrument_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||
primary_isin CHAR(12) UNIQUE,
|
||
primary_cusip CHAR(9),
|
||
canonical_name TEXT NOT NULL,
|
||
security_type VARCHAR(16) NOT NULL
|
||
CHECK (security_type IN ('common', 'preferred', 'unit', 'warrant', 'right', 'etf', 'cdr', 'fx')),
|
||
issuer_country CHAR(2),
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS instrument_identifier_history (
|
||
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
|
||
id_type VARCHAR(8) NOT NULL
|
||
CHECK (id_type IN ('ISIN', 'CUSIP')),
|
||
id_value VARCHAR(16) NOT NULL,
|
||
valid_from DATE NOT NULL,
|
||
valid_to DATE,
|
||
source VARCHAR(16) NOT NULL,
|
||
PRIMARY KEY (id_type, id_value, valid_from)
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS listing (
|
||
listing_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||
instrument_id INTEGER NOT NULL REFERENCES instrument(instrument_id),
|
||
mic VARCHAR(10) NOT NULL REFERENCES exchange(mic),
|
||
ticker_root VARCHAR(24) NOT NULL,
|
||
class_suffix VARCHAR(12) NOT NULL DEFAULT '',
|
||
currency CHAR(3) NOT NULL,
|
||
ib_conid BIGINT,
|
||
ib_primary_exchange VARCHAR(16), -- e.g. 'NYSE', 'NASDAQ', 'TSE', 'VENTURE'
|
||
listed_from DATE,
|
||
listed_to DATE,
|
||
delist_reason VARCHAR(24)
|
||
CHECK (delist_reason IN ('active', 'merger_cash', 'moved_to_otc', 'bankruptcy_cancelled', 'unknown_involuntary')),
|
||
terminal_return NUMERIC(10, 6), -- e.g. -0.300000 or -1.000000 when no post-delist OTC bar exists
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS corporate_action_continuity (
|
||
from_listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||
to_listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||
effective_date DATE NOT NULL,
|
||
kind VARCHAR(24) NOT NULL
|
||
CHECK (kind IN ('otc_delist_transfer', 'venue_uplisting', 'reorg_continuation')),
|
||
PRIMARY KEY (from_listing_id, effective_date)
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS listing_symbol_history (
|
||
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||
ticker VARCHAR(32) NOT NULL,
|
||
valid_from DATE NOT NULL,
|
||
valid_to DATE,
|
||
source VARCHAR(16) NOT NULL,
|
||
PRIMARY KEY (listing_id, ticker, valid_from)
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS provider_mapping (
|
||
source VARCHAR(16) NOT NULL,
|
||
source_id VARCHAR(64) NOT NULL, -- eodSearchCode, qmSearchCode, ib conid/id, ceoId
|
||
valid_from DATE NOT NULL DEFAULT '1900-01-01',
|
||
valid_to DATE,
|
||
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||
method VARCHAR(24) NOT NULL
|
||
CHECK (method IN ('tier1_isin', 'tier2_cusip', 'tier3_ticker_span', 'tier4_name', 'override')),
|
||
confidence NUMERIC(4, 3) NOT NULL
|
||
CHECK (confidence BETWEEN 0 AND 1),
|
||
price_corr NUMERIC(5, 4),
|
||
PRIMARY KEY (source, source_id, valid_from)
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS resolution_conflict (
|
||
conflict_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||
source VARCHAR(16) NOT NULL,
|
||
source_id VARCHAR(64) NOT NULL,
|
||
conflict_kind VARCHAR(32) NOT NULL,
|
||
candidate_listing_id INTEGER REFERENCES listing(listing_id),
|
||
existing_listing_id INTEGER REFERENCES listing(listing_id),
|
||
detail JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||
status VARCHAR(16) NOT NULL DEFAULT 'open',
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||
resolved_at TIMESTAMPTZ
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS override (
|
||
source VARCHAR(16) NOT NULL,
|
||
source_id VARCHAR(64) NOT NULL,
|
||
valid_from DATE NOT NULL DEFAULT '1900-01-01',
|
||
valid_to DATE,
|
||
listing_id INTEGER NOT NULL REFERENCES listing(listing_id),
|
||
reason TEXT NOT NULL,
|
||
created_by TEXT NOT NULL,
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||
PRIMARY KEY (source, source_id, valid_from)
|
||
);
|
||
|
||
CREATE TABLE IF NOT EXISTS golden_field_audit (
|
||
audit_id INTEGER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||
entity_type VARCHAR(16) NOT NULL
|
||
CHECK (entity_type IN ('instrument', 'listing')),
|
||
entity_id INTEGER NOT NULL,
|
||
field_name TEXT NOT NULL,
|
||
chosen_value TEXT,
|
||
chosen_source VARCHAR(16) NOT NULL,
|
||
candidates JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||
decided_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||
);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_listing_instrument_id
|
||
ON listing (instrument_id);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_listing_mic_ticker
|
||
ON listing (mic, ticker_root, class_suffix);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_listing_ib_conid
|
||
ON listing (ib_conid)
|
||
WHERE ib_conid IS NOT NULL;
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_provider_mapping_listing_id
|
||
ON provider_mapping (listing_id);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_instrument_identifier_history_instrument_id
|
||
ON instrument_identifier_history (instrument_id);
|
||
```
|
||
|
||
`override` is keyed by `(source, source_id, valid_from)` and applied last with precedence `1.000`. The minimal definitions for `resolution_conflict`, `override`, and `golden_field_audit` above are open to revision as M1 Passes 1–6 are built.
|
||
|
||
### M1 `>= 95%` US/CA Equity Resolution Gate Denominator
|
||
|
||
The M1 exit gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered venues** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`). Every match report preserves raw catalog totals (`Total`, `Resolved %`) alongside explicit itemized exclusions:
|
||
|
||
- **`Excluded by Design`:** `excluded_fund` (`NMFQS`, `NMF`), `composite_venue` (`US`, `TSXC`, `TSXVC`), `ats_routing_venue` (`EDGX`), and `forex_venue` (`FOREX`).
|
||
- **`Out of Gate Scope`:**
|
||
1. `zero_bar_catalog_ghost` — secondary ticker-only rows (`qm`) with `missing_span` (`0` bars in `qmPrices`), which Stage B intentionally refuses to match to prevent ticker-reuse corruption (`FB`).
|
||
2. `uncovered_venue` — listings on exchanges absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`, `ceo`, and `ib:AEQLIT`, plus `ceo:NEOE` where EODHD carries only 19 of 587 listings).
|
||
3. `non_equity_instrument` — non-common-equity instruments & test tickers (warrants `.WT`/`.WS`, convertible debentures `.DB`, subscription receipts/rights `.R`/`.RT`, SPAC/REIT units `.U`/`.UN`, preferred shares `.PR*`/`-P*`, TSXV NEX inactive shells `.H`, TSXV CPCs `.P`, and exchange test symbols).
|
||
|
||
### Research Knowledge & Findings Schema (PostgreSQL, Append-Only)
|
||
|
||
Applied via `@stock-bot/postgres` (`research` migration track, `database/postgres/init/37-research-findings.sql`, immediately after `36-trial-ledger.sql`). Owned by Stock Bot research alongside `trial_ledger` and `vault_evaluations` (see [`design/VALIDATION-AND-RIGOR.md`](VALIDATION-AND-RIGOR.md) §2A and §3 for those tables).
|
||
|
||
- **Research-visible boundary:** `findings` and `provider_caveats` store research-visible empirical evidence only. Callers and MCP adapters (`file_finding`, `read_knowledge`) are responsible for verifying that every `trial_ref` belongs to the research-visible `trial_ledger` and for excluding Vault holdout observations or Vault-only evidence from stored text and opaque `evidence_refs`.
|
||
- **Append-only enforcement:** Both tables reuse `reject_research_evidence_mutation()` from `17-research-retention.sql` via row-level `BEFORE UPDATE OR DELETE` (`findings_retained`, `provider_caveats_retained`) and statement-level `BEFORE TRUNCATE` (`findings_no_truncate`, `provider_caveats_no_truncate`) triggers, raising SQLSTATE `23514` on any mutation attempt.
|
||
- **Character-length & whitespace convention:** SQL `CHECK` constraints enforce PostgreSQL `char_length(...)` (Unicode code points) matching the MCP tool caps (`title` trimmed `1..256`, `summary` trimmed `1..4096`, each ref `<= 256`, `idempotency_key` `1..128`). Nonblank and trimmed-length checks use `research_trim_ecmascript(...)`, which strips the explicit 25-character ECMAScript `WhiteSpace` + `LineTerminator` set (`U+0009`..`U+000D`, `U+0020`, `U+00A0`, `U+1680`, `U+2000`..`U+200A`, `U+2028`, `U+2029`, `U+202F`, `U+205F`, `U+3000`, `U+FEFF`) regardless of database collation. JavaScript/Zod validation counts UTF-16 code units, which can reach the same numeric limit sooner for supplementary Unicode characters.
|
||
|
||
```sql
|
||
CREATE TABLE IF NOT EXISTS findings (
|
||
id TEXT PRIMARY KEY
|
||
CHECK (research_trim_ecmascript(id) <> ''),
|
||
kind TEXT NOT NULL
|
||
CHECK (kind IN ('finding', 'dead_end')),
|
||
title TEXT NOT NULL
|
||
CHECK (char_length(research_trim_ecmascript(title)) BETWEEN 1 AND 256),
|
||
summary TEXT NOT NULL
|
||
CHECK (char_length(research_trim_ecmascript(summary)) BETWEEN 1 AND 4096),
|
||
status TEXT NOT NULL DEFAULT 'pending_review'
|
||
CHECK (research_trim_ecmascript(status) <> ''),
|
||
created_at TIMESTAMPTZ NOT NULL,
|
||
trial_refs TEXT[] NOT NULL
|
||
CHECK (cardinality(trial_refs) <= 32)
|
||
CHECK (COALESCE(array_ndims(trial_refs), 1) = 1)
|
||
CHECK (research_finding_refs_valid(trial_refs, 256)),
|
||
evidence_refs TEXT[] NOT NULL
|
||
CHECK (cardinality(evidence_refs) <= 32)
|
||
CHECK (COALESCE(array_ndims(evidence_refs), 1) = 1)
|
||
CHECK (research_finding_refs_valid(evidence_refs, 256)),
|
||
idempotency_key TEXT
|
||
CHECK (idempotency_key IS NULL OR (research_trim_ecmascript(idempotency_key) <> '' AND char_length(idempotency_key) BETWEEN 1 AND 128))
|
||
);
|
||
|
||
CREATE UNIQUE INDEX IF NOT EXISTS idx_findings_idempotency_key
|
||
ON findings (idempotency_key)
|
||
WHERE idempotency_key IS NOT NULL;
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_findings_created_at
|
||
ON findings (created_at);
|
||
|
||
CREATE TABLE IF NOT EXISTS provider_caveats (
|
||
id TEXT PRIMARY KEY
|
||
CHECK (research_trim_ecmascript(id) <> ''),
|
||
provider TEXT NOT NULL
|
||
CHECK (research_trim_ecmascript(provider) <> ''),
|
||
dataset TEXT NOT NULL
|
||
CHECK (research_trim_ecmascript(dataset) <> ''),
|
||
caveat TEXT NOT NULL
|
||
CHECK (research_trim_ecmascript(caveat) <> ''),
|
||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||
);
|
||
|
||
CREATE INDEX IF NOT EXISTS idx_provider_caveats_lower_provider
|
||
ON provider_caveats (lower(provider));
|
||
```
|
||
|
||
- **Reference arrays (`trial_refs`, `evidence_refs`):** Stored as opaque 1-dimensional `TEXT[]` arrays (empty arrays permitted via `COALESCE(array_ndims(...), 1) = 1`, max 32 entries each, no `NULL` elements, max 256 chars per entry enforced via `research_finding_refs_valid`). Reference normalization, deduplication, minimum `trial_refs` count, and research-visibility checks remain in the MCP tool/adapter layer.
|
||
- **Indexes:** `idx_findings_idempotency_key` (partial unique `WHERE idempotency_key IS NOT NULL`) supports atomic compare-and-append idempotency while allowing multiple `NULL` keys; `idx_findings_created_at` supports chronological listing; `idx_provider_caveats_lower_provider` supports case-insensitive provider filtering in `read_knowledge`.
|
||
|
||
---
|
||
|
||
## 3. Curated Storage Schemas
|
||
|
||
### A. DuckDB + Hive Parquet (`/mnt/data/stockbot/curated/`)
|
||
|
||
All Parquet files use `ZSTD` compression, integer `listing_id` (`INT32`), UTC `TIMESTAMPTZ` (`ts`, `known_at`), and explicit `known_at_source`.
|
||
|
||
- **Bulk ETL rule (`tools/curate-etl`):** Multi-hundred-million and multi-billion-row collections (`eodPrices` `846M`, `eodIntraday1M` `3.40B`, `eodIntraday5M` `1.08B`, `qmFilings` `30.5M`) are curated via a dedicated Rust binary in the Cargo workspace (`mongodb::bson::RawDocumentBuf` zero-copy BSON cursors + in-RAM `provider_mapping`/`qmSplits` lookup tables + `rayon` sharded `parquet`/ILP writers)—**never** through single-threaded JS/Node object-allocation loops.
|
||
- **DuckDB connection budget:** Every `MarketDataStore` (TS) and `stockbot.data` (Python) DuckDB instance must execute at connection open:
|
||
```sql
|
||
SET memory_limit = '6GB';
|
||
SET threads = 4;
|
||
SET temp_directory = '/mnt/data/stockbot/tmp/duckdb';
|
||
```
|
||
(overridable via env on local dev, e.g. `2GB`/`2` threads) so concurrent campaign workers never inherit DuckDB's default `80%` host-RAM (`~100 GiB`) ceiling.
|
||
|
||
Schemas:
|
||
|
||
- **`bars_1d/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, session_date DATE, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, volume DOUBLE, vwap DOUBLE, currency VARCHAR, source VARCHAR, known_at TIMESTAMPTZ)` — strictly raw OHLC and **un-adjusted** share `volume`, sorted by `(listing_id, session_date)`.
|
||
- **`adj_factors/part.parquet`**: `(listing_id INT32, ex_date DATE, split_factor DOUBLE, div_cash DOUBLE, div_currency VARCHAR, cum_split_factor DOUBLE, cum_total_factor DOUBLE, known_at TIMESTAMPTZ)`.
|
||
- **`corporate_actions/part.parquet`**: `(listing_id INT32, ex_date DATE, declared_date DATE, kind VARCHAR, ratio DOUBLE, cash_amount DOUBLE, currency VARCHAR, successor_listing_id INT32, terminal_return DOUBLE, known_at TIMESTAMPTZ, known_at_source VARCHAR)`.
|
||
- **`fundamentals_bitemporal/part.parquet`**: `(listing_id INT32, period_end DATE, fiscal_period VARCHAR, currency VARCHAR, known_at TIMESTAMPTZ, known_at_source VARCHAR, <standardized statement columns...>)`.
|
||
- **`fundamentals_pit/year=YYYY/part.parquet`**: Pre-resolved point-in-time snapshots partitioned by the UTC year of `effective_known_at`, sorted and unique by `(listing_id, effective_known_at)`: `(listing_id INT32 NOT NULL, effective_known_at TIMESTAMPTZ NOT NULL, known_at_source VARCHAR NOT NULL, has_estimated_lag BOOLEAN NOT NULL, period_end DATE NOT NULL, fiscal_period VARCHAR NOT NULL, currency VARCHAR NOT NULL, period_known_at TIMESTAMPTZ NOT NULL, revenue DOUBLE, net_income DOUBLE, operating_cash_flow DOUBLE, total_assets DOUBLE, total_equity DOUBLE, shares_outstanding DOUBLE, ttm_period_end DATE, ttm_currency VARCHAR, ttm_revenue DOUBLE, ttm_net_income DOUBLE, ttm_operating_cash_flow DOUBLE, ttm_has_estimated_lag BOOLEAN)` (all `ttm_*` columns are `NULL` when 4 consecutive standalone quarters in one currency are unavailable). Each snapshot computes:
|
||
$$\text{latest } k \text{ periods by } \texttt{period\_end} \text{ of } \left(\arg\max_{\texttt{known\_at} \le \texttt{effective\_known\_at}} \text{ per } (\texttt{listing\_id}, \texttt{period\_end})\right)$$
|
||
forward-filling un-restated fields and precomputing 4-quarter TTM sums so a restatement of Q1 never overwrites Q2; the physical Parquet row flattens the latest visible resolved period (`periods[0]`) alongside the precomputed `ttm_*` columns (lagged slots `periods[1..]` are omitted).
|
||
- **`events/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, known_at_source VARCHAR, kind VARCHAR, subtype VARCHAR, payload_json VARCHAR)`.
|
||
- **`shorts/part.parquet`**: `(listing_id INT32, report_date DATE, known_at TIMESTAMPTZ, shares_short DOUBLE, net_change DOUBLE, pct_float DOUBLE, source VARCHAR)`.
|
||
- **`macro/part.parquet`**: `(country_iso VARCHAR, indicator VARCHAR, period_date DATE, known_at TIMESTAMPTZ, known_at_source VARCHAR, value DOUBLE)`.
|
||
- **`fx_1d/part.parquet`**: `(pair VARCHAR, session_date DATE, ts TIMESTAMPTZ, open DOUBLE, high DOUBLE, low DOUBLE, close DOUBLE, source VARCHAR, known_at TIMESTAMPTZ)`.
|
||
- **`features/<feature_name>/v<version>/year=YYYY/part.parquet`**: `(listing_id INT32, ts TIMESTAMPTZ, known_at TIMESTAMPTZ, value DOUBLE)`.
|
||
|
||
### B. QuestDB `10.2.0` (Intraday & Live Streaming)
|
||
|
||
Image pinned to `questdb/questdb:10.2.0`. Host kernel must enforce `vm.max_map_count >= 1048576` (`/etc/sysctl.d/99-stockbot.conf`), container `ulimits.nofile` set to `1048576`, and off-heap memory bounded via `QDB_RAM_USAGE_LIMIT_BYTES=21474836480` (`20 GiB`) + JVM `-Xms2g -Xmx4g` inside a `28g` container `mem_limit` on `quant`.
|
||
|
||
`listing_id` is stored as decimal string inside `SYMBOL CAPACITY 65536 NOCACHE` and converted to `number` (`INT32`) at the `MarketDataStore` adapter boundary. `bars_1m` uses **`PARTITION BY MONTH`** (`270` partitions / `~3,780` files across 22.5 years at `~13.2M` rows/month, vs. `~5,670` partitions / `~79,000` files under `PARTITION BY DAY`—cutting 1-year `W2` cold partition seeks from 252 to 12 while keeping live monthly WAL `< 40 MB`):
|
||
|
||
```sql
|
||
CREATE TABLE IF NOT EXISTS bars_1m (
|
||
listing_id SYMBOL CAPACITY 65536 NOCACHE,
|
||
open DOUBLE,
|
||
high DOUBLE,
|
||
low DOUBLE,
|
||
close DOUBLE,
|
||
volume DOUBLE,
|
||
vwap DOUBLE,
|
||
session SYMBOL CAPACITY 8 CACHE, -- 'PRE' | 'RTH' | 'POST'
|
||
source SYMBOL CAPACITY 8 CACHE, -- 'eod_unadj' | 'qm_raw' | 'ib_live'
|
||
known_at TIMESTAMP,
|
||
ts TIMESTAMP
|
||
) TIMESTAMP(ts) PARTITION BY MONTH WAL
|
||
DEDUP UPSERT KEYS(ts, listing_id);
|
||
|
||
CREATE TABLE IF NOT EXISTS fx_1m (
|
||
pair SYMBOL CAPACITY 32 CACHE, -- 'USD.CAD'
|
||
open DOUBLE,
|
||
high DOUBLE,
|
||
low DOUBLE,
|
||
close DOUBLE,
|
||
source SYMBOL CAPACITY 8 CACHE,
|
||
ts TIMESTAMP
|
||
) TIMESTAMP(ts) PARTITION BY MONTH WAL
|
||
DEDUP UPSERT KEYS(ts, pair);
|
||
|
||
CREATE TABLE IF NOT EXISTS bar_revisions (
|
||
listing_id SYMBOL CAPACITY 65536 NOCACHE,
|
||
timeframe SYMBOL CAPACITY 8 CACHE,
|
||
bar_ts TIMESTAMP,
|
||
prev_close DOUBLE,
|
||
new_close DOUBLE,
|
||
prev_volume DOUBLE,
|
||
new_volume DOUBLE,
|
||
revised_at TIMESTAMP
|
||
) TIMESTAMP(revised_at) PARTITION BY MONTH WAL;
|
||
```
|
||
|
||
---
|
||
|
||
## 4. `MarketDataStore` Contract
|
||
|
||
```ts
|
||
export type DataScope = 'vault_fenced' | 'vault_evaluation_only';
|
||
|
||
export interface MarketDataStore {
|
||
bars(q: {
|
||
listingIds: number[];
|
||
timeframe: '1m' | '5m' | '1h' | '1d';
|
||
from: string;
|
||
to: string;
|
||
adjustment: 'raw' | 'split' | 'total';
|
||
asOf?: string;
|
||
scope?: DataScope; // defaults to 'vault_fenced'; 'vault_evaluation_only' requires human operator Vault token
|
||
}): AsyncIterable<BarBatch>;
|
||
|
||
crossSection(q: {
|
||
features: string[]; // versioned refs, e.g. 'rsi_14@v1'
|
||
date: string;
|
||
universe: UniverseRef;
|
||
asOf?: string;
|
||
}): Promise<Table>;
|
||
|
||
fundamentalsAsOf(q: {
|
||
listingIds: number[];
|
||
fields: string[];
|
||
asOf: string;
|
||
allowEstimatedLag?: boolean; // default true for daily/swing, false for intraday event triggers
|
||
}): Promise<Table>;
|
||
|
||
events(q: {
|
||
kinds: EventKind[];
|
||
listingIds?: number[];
|
||
from: string;
|
||
to: string;
|
||
asOf?: string;
|
||
}): Promise<Table>;
|
||
|
||
shortsAsOf(q: { listingIds: number[]; from: string; to: string; asOf?: string }): Promise<Table>;
|
||
macroAsOf(q: { countries: string[]; indicators: string[]; from: string; to: string; asOf?: string }): Promise<Table>;
|
||
fx(q: { pair: 'USD.CAD'; timeframe: '1m' | '1d'; from: string; to: string }): Promise<Table>;
|
||
universe(q: { ref: UniverseRef; date: string }): Promise<number[]>; // survivorship-free active listings on date
|
||
}
|
||
```
|
||
|
||
**Hard adapter invariant:** When `scope !== 'vault_evaluation_only'`, the adapter clamps `to` and `asOf` to `< VAULT_CUTOFF_TS` (rejecting requests with `from >= VAULT_CUTOFF_TS` with `VaultHoldoutFenceError`).
|