9.5 KiB
@stock-bot/data-pipeline
Normalizes raw provider collections from MongoDB (stock) into canonical PostgreSQL security-master records and curated research datasets.
Safety & Connection Model
- Port:
2002(PIPELINE_SERVICE_PORT, default2002indocker-compose.yml/docker-compose.dev.yml). - Read-Only MongoDB Enforcement: Bootstraps its DI container with
mongoReadOnly: true, connecting viaMONGODB_READ_URI(studio_stock_bot_read@stock) and blocking all write, index, and collection-mutation methods at the client wrapper layer. - Dev vs QA Targets:
- In
development, reads QA MongoDB read-only and writes only to isolated dev PostgreSQL (localhost:5433/trading_bot_dev).assertEnvironmentSafety()hard-blocks writable connections to QA MongoDB (27017/stock) or QA PostgreSQL (5432/trading_bot). - Destructive sync flags (
?clear=true,POST /sync/clear) are restricted in non-test environments; never run destructive clears againsttrading_bot.
- In
Current Runtime Scope
- MongoDB Inputs:
exchanges,eodExchanges,ibExchanges,qmExchanges,eodSymbols,ibSymbols,qmSymbols. - PostgreSQL Tables (
database/postgres/init/02-master-schema.sql):exchanges&provider_exchange_mappingssymbols&provider_mappingssync_status
- HTTP Endpoints (
src/routes/):GET /health— liveness & database readinessGET /sync/status&GET /sync/status/enhanced— sync state and countsPOST /sync/exchanges/all— normalize exchange reference catalogPOST /sync/symbols/:provider— syncqm,eod, oribsymbol mappings
Target Architecture (Milestone M1 & M2)
Full specifications live in:
- DATA-CONTRACTS.md — Empirical 31-collection rules, bi-temporal security master (
exchange,exchange_source_map,instrument,instrument_identifier_history,listing,corporate_action_continuity,listing_symbol_history,provider_mapping,resolution_conflict,override,golden_field_audit), Hive Parquet + DuckDB schemas (bars_1d,fundamentals_pit,earnings_events_pit,short_interest_pit,macro_pit,fx_rates_1d), and QuestDB10.2.0intraday schema. - MILESTONES.md — Step-by-step
M0(read-only wrapper hardening),M1(US + Canada security master &bars_1d+fx_rates_1dcuration), andM2(qmFilings-backed PIT fundamentals, earnings, short interest, and macro curation). - phase1-investigation.md — Initial provider exchange/symbol investigation notes.
Commands
Run from the repository root:
# Start pipeline in dev mode (targets localhost:5433/trading_bot_dev)
bun run --cwd apps/stock/data-pipeline dev
# Typecheck & build
bun run typecheck
bun run build
# Run PostgreSQL environment & read-only MongoDB safety tests
bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/pipeline-safety.test.ts
Pass 1 Exchange Seed Generator
The committed baseline seed in database/postgres/init/35-security-master-exchange-seed.sql covers the 11 US+CA ISO 10383 MICs and the 17 documented explicit provider mappings. To regenerate a full reviewable candidate seed and unresolved-codes report from the read-only QA MongoDB collections (eodExchanges, ibExchanges, qmExchanges, ceoExchanges) on the host:
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
bun run apps/stock/data-pipeline/src/security-master/generate-exchange-seed.ts \
--sql-out ./tmp/35-security-master-exchange-seed.generated.sql \
--report-out ./tmp/pass1-unresolved-exchanges.md
- Read-only guarantee: The CLI initializes config with
mongoReadOnly: true, connects viaMONGODB_READ_URIwithreadOnly: true, performs zero MongoDB writes, and performs zero PostgreSQL writes. - Review and upgrade workflow: Keep
database/postgres/init/35-security-master-exchange-seed.sqlimmutable as the reproducible Pass 1 baseline—runPostgresMigrationsrecords applied filenames inmigrationsand skips any file it has already run, so editing migration35in place would not reach databases that already applied it. Instead, inspect./tmp/pass1-unresolved-exchanges.mdfor unresolved codes (unknown MICs, multi-valuedOperatingMIC, missing MICs), add approved additions or corrections as a new numbered migration underdatabase/postgres/init/(for example36-security-master-exchange-overrides.sql, settingreviewed_byon director-approved rows) and register it inMASTER_FILESinlibs/data/postgres/src/migrations.ts(also updatingEXPLICIT_EXCHANGE_SOURCE_RULESif future generator runs should classify those codes explicitly). Verify the upgrade against a schema where migration35has already run—not only a fresh schema—confirming the new migration applies cleanly and that re-applying the baseline never overwrites rows wherereviewed_by IS NOT NULL.
Pass 4 Cross-Sectional Price Cross-Check
apps/stock/data-pipeline/src/security-master/price-cross-check.ts provides pure, zero-I/O verification for candidate source-to-source listing pairs before persisting provider_mapping / resolution_conflict rows:
- Stratified date sampling (
selectSampleDates): Drops invalid/non-YYYY-MM-DDvalues, deduplicates, sorts ascending, and selectscountdates (default25) by splitting the calendar intocountcontiguous near-equal strata and picking the middle date of each (returning all valid unique dates when<= count). - Price ratio & FX rules (
crossCheckPrices): Compares raw sample closes over dates where both sides have a finiteclose > 0(conflicting duplicate closes or FX rates drop that date and are counted; missing FX dates on cross-currency pairs are skipped and never forward-filled). Expectedleft/rightratio is1.0for matching ISO currencies,usdCad(CAD per 1 USD) forCAD/USD, and1 / usdCadforUSD/CAD; any other currency combination returnsunsupported_currency_pair. - Return correlation: Computes two-pass centered Pearson correlation of consecutive log returns in a canonical common currency (converting CAD closes to USD via
cadClose / usdCadforCAD/USDpairs so correlation is orientation-symmetric and unaffected by FX moves on flat USD prices), rounded to4decimal places (provider_mapping.price_corr NUMERIC(5,4)). Returnsnullwhen fewer than3returns exist or either series has zero variance. - Strict verdict priority & defaults:
unsupported_currency_pair->insufficient_data(usableDates < 5orpriceCorr === null) ->ratio_mismatch(medianRatiooutside inclusive[1 - 0.02, 1 + 0.02]) ->low_correlation(priceCorr < 0.9) ->confirmed. Malformed candidate pairs or endpoints never abort the batch; each malformed slot is counted instats.invalidPairsand recorded with a deterministic non-confirming verdict so verdict counts always reconcile withpairsIn. - Conflicts: Emits
resolution_conflict-shaped records only forratio_mismatch(price_ratio_mismatch) andlow_correlation(price_low_correlation), keyed toleft.sourceandleft.sourceIdwith a JSON-serializabledetailpayload.
Security Master Persistence (persistSecurityMaster)
apps/stock/data-pipeline/src/security-master/persist.ts persists in-memory Pass 3 (Stage A/B), Pass 5 (resolution_conflict), and Pass 6 (delisting-chains) results into the master track PostgreSQL tables inside a single transaction guarded by pg_advisory_xact_lock(0x534d5053, hashtext(current_schema())):
- Permanent IDs & idempotency: Upserts
instrumentbyprimary_isinand resolveslistingby(instrument_id, mic, ticker_root, class_suffix, currency)without ever changing or deleting an existinginstrument_idorlisting_id. - Override precedence: After upserting
provider_mapping(tier1_isin = 0.990,tier2_cusip = 0.950,tier3_ticker_span = 0.800), unconditionally enforces every row inoverride(method = 'override',confidence = 1.000,price_corr = NULL) so re-runs with conflicting matcher output cannot overwrite director overrides. - No guessing: Instruments with null/blank
canonicalNameor absent fromsecurityTypeByIsin, and listings with an unknownmic, are skipped and counted per reason along with all dependent listings, mappings, Pass 6 outcomes, and continuities. - Batched writes & local benchmark: All bulk reads/writes use parameterised
UNNESTbatches (default/max chunk size5000). Run the PostgreSQL integration suite and fixed-seed 20,000-instrument / 20,000-listing / 60,000-mapping benchmark against an isolatedstock_bot_safety_*schema with:
bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts
- Recorded baseline (
2026-11-28, host PostgreSQL isolatedstock_bot_safety_*schema, defaultchunkSize = 5000):- Workload:
20,000instruments,20,000listings,60,000provider mappings (100,000core rows;140,000total rows including20,000instrument_identifier_historyand20,000listing_symbol_historyrows). - Observed end-to-end test wall time:
2.20s(2200.02ms, reported bybun test; includes isolated schema migration, synthetic fixture construction,persistSecurityMaster, andCOUNT(*)verification becausetest/setup.tssuppressesconsole.info). - Throughput (conservative lower bound over full test wall time):
45,454core rows/s (100,000 / 2.20002s),63,636total rows/s (140,000 / 2.20002s).
- Workload: