193 lines
21 KiB
Markdown
193 lines
21 KiB
Markdown
# `@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`, default `2002` in `docker-compose.yml` / `docker-compose.dev.yml`).
|
|
- **Read-Only MongoDB Enforcement:** Bootstraps its DI container with `mongoReadOnly: true`, connecting via `MONGODB_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 against `trading_bot`.
|
|
|
|
## Current Runtime Scope
|
|
- **MongoDB Inputs:** `exchanges`, `eodExchanges`, `ibExchanges`, `qmExchanges`, `eodSymbols`, `ibSymbols`, `qmSymbols`.
|
|
- **PostgreSQL Tables (`database/postgres/init/02-master-schema.sql`):**
|
|
- `exchanges` & `provider_exchange_mappings`
|
|
- `symbols` & `provider_mappings`
|
|
- `sync_status`
|
|
- **HTTP Endpoints (`src/routes/`):**
|
|
- `GET /health` — liveness & database readiness
|
|
- `GET /sync/status` & `GET /sync/status/enhanced` — sync state and counts
|
|
- `POST /sync/exchanges/all` — normalize exchange reference catalog
|
|
- `POST /sync/symbols/:provider` — sync `qm`, `eod`, or `ib` symbol mappings
|
|
|
|
## Target Architecture (`Milestone M1` & `M2`)
|
|
Full specifications live in:
|
|
- [DATA-CONTRACTS.md](../../../design/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 QuestDB `10.2.0` intraday schema.
|
|
- [MILESTONES.md](../../../design/MILESTONES.md) — Step-by-step `M0` (read-only wrapper hardening), `M1` (US + Canada security master & `bars_1d` + `fx_rates_1d` curation), and `M2` (`qmFilings`-backed PIT fundamentals, earnings, short interest, and macro curation).
|
|
- [phase1-investigation.md](../../../design/data-pipeline/phase1-investigation.md) — Initial provider exchange/symbol investigation notes.
|
|
|
|
## Commands
|
|
Run from the repository root:
|
|
|
|
```bash
|
|
# 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:
|
|
|
|
```bash
|
|
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 via `MONGODB_READ_URI` with `readOnly: true`, performs zero MongoDB writes, and performs zero PostgreSQL writes.
|
|
- **Review and upgrade workflow:** Keep `database/postgres/init/35-security-master-exchange-seed.sql` immutable as the reproducible Pass 1 baseline—`runPostgresMigrations` records applied filenames in `migrations` and skips any file it has already run, so editing migration `35` in place would not reach databases that already applied it. Instead, inspect `./tmp/pass1-unresolved-exchanges.md` for unresolved codes (unknown MICs, multi-valued `OperatingMIC`, missing MICs), add approved additions or corrections as a **new** numbered migration under `database/postgres/init/` (for example `36-security-master-exchange-overrides.sql`, setting `reviewed_by` on director-approved rows) and register it in `MASTER_FILES` in `libs/data/postgres/src/migrations.ts` (also updating `EXPLICIT_EXCHANGE_SOURCE_RULES` if future generator runs should classify those codes explicitly). Verify the upgrade against a schema where migration `35` has already run—not only a fresh schema—confirming the new migration applies cleanly and that re-applying the baseline never overwrites rows where `reviewed_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-DD` values, deduplicates, sorts ascending, and selects `count` dates (default `25`) by splitting the calendar into `count` contiguous 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 finite `close > 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). Expected `left/right` ratio is `1.0` for matching ISO currencies, `usdCad` (CAD per 1 USD) for `CAD`/`USD`, and `1 / usdCad` for `USD`/`CAD`; any other currency combination returns `unsupported_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 / usdCad` for `CAD`/`USD` pairs so correlation is orientation-symmetric and unaffected by FX moves on flat USD prices), rounded to `4` decimal places (`provider_mapping.price_corr NUMERIC(5,4)`). Returns `null` when fewer than `3` returns exist or either series has zero variance.
|
|
- **Strict verdict priority & defaults:** `unsupported_currency_pair` -> `insufficient_data` (`usableDates < 5` or `priceCorr === null`) -> `ratio_mismatch` (`medianRatio` outside 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 in `stats.invalidPairs` and recorded with a deterministic non-confirming verdict so verdict counts always reconcile with `pairsIn`.
|
|
- **Conflicts:** Emits `resolution_conflict`-shaped records only for `ratio_mismatch` (`price_ratio_mismatch`) and `low_correlation` (`price_low_correlation`), keyed to `left.source` and `left.sourceId` with a JSON-serializable `detail` payload.
|
|
|
|
## 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 `instrument` by `primary_isin` and resolves `listing` by `(instrument_id, mic, ticker_root, class_suffix, currency)` without ever changing or deleting an existing `instrument_id` or `listing_id`.
|
|
- **Override precedence:** After upserting `provider_mapping` (`tier1_isin = 0.990`, `tier2_cusip = 0.950`, `tier3_ticker_span = 0.800`), unconditionally enforces every row in `override` (`method = 'override'`, `confidence = 1.000`, `price_corr = NULL`) so re-runs with conflicting matcher output cannot overwrite director overrides.
|
|
- **Stale fallback cleanup:** When a run supplies only dated `provider_mapping` rows (`validFrom !== '1900-01-01'`) for a `(source, source_id)`, any leftover `1900-01-01` fallback row for that pair is deleted in batched `UNNEST` statements within the same transaction and counted in `providerMappingsDeletedStaleFallback`. Rows with `method = 'override'`, rows protected by an `override` entry at `1900-01-01`, dated rows, and `(source, source_id)` pairs absent from the run are never deleted.
|
|
- **No guessing:** Instruments with null/blank `canonicalName` or absent from `securityTypeByIsin`, and listings with an unknown `mic`, 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 `UNNEST` batches (default/max chunk size `5000`). Run the PostgreSQL integration suite and fixed-seed 20,000-instrument / 20,000-listing / 60,000-mapping benchmark against an isolated `stock_bot_safety_*` schema with:
|
|
|
|
```bash
|
|
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 isolated `stock_bot_safety_*` schema, default `chunkSize = 5000`):**
|
|
- Workload: `20,000` instruments, `20,000` listings, `60,000` provider mappings (`100,000` core rows; `140,000` total rows including `20,000` `instrument_identifier_history` and `20,000` `listing_symbol_history` rows).
|
|
- Observed end-to-end test wall time: `2.36s` (`2359.01ms`, reported by `bun test`; includes isolated schema migration, synthetic fixture construction, `persistSecurityMaster`, and `COUNT(*)` verification).
|
|
- Throughput (conservative lower bound over full test wall time): `42,391` core rows/s (`100,000 / 2.35901s`), `59,347` total rows/s (`140,000 / 2.35901s`).
|
|
|
|
## Read-Only Source-Symbol Readers (`source-symbol-readers.ts`)
|
|
`apps/stock/data-pipeline/src/security-master/source-symbol-readers.ts` adapts raw `eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, and `eodSymbolChange` documents into deterministic Stage A (`StageASourceRecord`) and Stage B (`StageBEodListingInput`, `StageBIbContractInput`, `StageBTickerSourceInput`, `StageBSymbolChangeInput`) inputs via `readSecurityMasterSources`:
|
|
|
|
- **Read-only streaming contract:** `ReadOnlySourceSymbolReader` exposes strictly `isReadOnly()` and `find()` returning an incremental `AsyncIterable` (rejecting buffered array results). Production callers adapt a read-only `MongoDBClient` via `createReadOnlyMongoSourceSymbolReader(client)`, which streams through `collection.find(filter, options)` (`FindCursor`, never `cursor.toArray()`), closes cursors in `finally`, projects `_id: 0` (omitting `qmSymbols.profile`/`symbolInfo`, projecting `eodSymbolChange.effective`), and pushes down `$or` country/venue filters preserving normalized spellings and venue fallbacks (default `['US', 'CA']`).
|
|
- **Provider & Pass 1 rules enforced:** `createExchangeSourceLookup` layers reviewed US+CA venue mappings (`REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS`) on top of the 17-row Pass 1 baseline (`EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS`) with caller/Pass 1 rows overriding. Readers exclude `eodSymbols` `Exchange="NMFQS"` mutual funds, preserve `delisted: true` and duplicate QM `(symbol, exchange)` pairs (`VOY:CNX` + `VOY:CC`), set Stage A country strictly to issuer country (never listing country), never use IB ATS `exchangeId` venues (`AEQLIT`, `OTCLNKECN`, etc.) as listing MIC or `primaryExchange`, strip CEO `.TO`/`.V` suffixes with Stage B double-strip protection, parse `eodSymbolChange.effective` (alongside `effectiveDate`/`date`), null invalid ISIN/CUSIP check digits without throwing, and reconcile `docsRead === emitted + sum(skips)` per collection.
|
|
- **Local synthetic benchmark:** Run the unit suite and fixed-seed 368,000-doc synthetic benchmark (`300,000` `eodSymbols` + `50,000` `qmSymbols` + `18,000` `ibSymbols`, zero DB connections) with:
|
|
|
|
```bash
|
|
bun test test/unit/security-master-source-symbol-readers.test.ts
|
|
```
|
|
|
|
- **Recorded baseline (`2026-11-28`, local sandbox, in-memory async cursor fake reader):**
|
|
- Workload: `368,000` synthetic docs (`300,000` `eodSymbols`, `50,000` `qmSymbols`, `18,000` `ibSymbols`) including NMFQS exclusion, country normalization, ISIN/CUSIP check-digit validation, ticker parsing, and deterministic ASCII sorting.
|
|
- Observed throughput: `754,047 docs/s` (`488.0 ms` wall time, floor `>= 25,000 docs/s`).
|
|
|
|
## EOD Security-Type Classifier (`security-type.ts`)
|
|
`apps/stock/data-pipeline/src/security-master/security-type.ts` maps raw EODHD `Type` strings into the canonical PostgreSQL `instrument.security_type` enum (`SecurityType`) and builds the `securityTypeByIsin` map required by `persistSecurityMaster` (wired automatically through `readEodSymbols` and `readSecurityMasterSources`).
|
|
|
|
- **Mapping table (`EOD_SECURITY_TYPE_MAP`, trimmed, whitespace-collapsed, case-insensitive):**
|
|
|
|
| EODHD `Type` | Canonical `SecurityType` |
|
|
| --- | --- |
|
|
| `Common Stock` | `common` |
|
|
| `Preferred Stock` | `preferred` |
|
|
| `ETF` | `etf` |
|
|
| `Unit`, `Units` | `unit` |
|
|
| `Warrant`, `Warrants` | `warrant` |
|
|
| `Right`, `Rights` | `right` |
|
|
| `CDR` | `cdr` |
|
|
| `Currency`, `Forex`, `FX` | `fx` |
|
|
|
|
- **Published-vocabulary & no-guess rule:** Because QA MongoDB is unreachable from the agent sandbox, the table is based on the published EODHD `Type` vocabulary. Non-equity-like values (`FUND`, `Mutual Fund`, `Bond`, `Notes`, `INDEX`, etc.), blanks, non-strings, and unmapped strings return `null` and are never guessed from ticker suffixes or company names. A non-string `Type` on an `eodSymbols` document does not skip the document from Stage A/B — it is counted under `securityTypeStats.missingType`.
|
|
- **Stage A membership & raw vocabulary diagnostics:** `readEodSymbols` / `readSecurityMasterSources` build the loader-facing `securityTypeByIsin` map, `securityTypeConflicts`, and `securityTypeLoaderStats` strictly from EOD rows accepted as Stage A instrument members (`buildSecurityTypeByIsinForStageA`), so rows quarantined by Stage A (`isin_cusip_mismatch`, `duplicate_source_id`) can neither supply nor veto a valid instrument's security type. At the same time, `securityTypeStats` and `unknownSecurityTypes` reconcile over **all** emitted EOD rows (also retained in `securityTypeRecords`), so unmapped vocabulary on quarantined rows is never silently hidden.
|
|
- **Reviewing unmapped values & conflicts:** After a real security-master run, inspect `unknownSecurityTypes` (sorted by count descending, then ASCII, reconciling with `securityTypeStats.unknownType` across all emitted EOD rows) for any newly observed provider strings that should be added to `EOD_SECURITY_TYPE_MAP`, and inspect `securityTypeConflicts` (ISINs omitted from `securityTypeByIsin` because multiple Stage A-accepted EOD documents disagreed on their classified type; capped by `maxSecurityTypeConflicts`, default `200`, reconciling with `securityTypeLoaderStats.isinsConflicting` and `conflictsTruncated`).
|
|
- **Local synthetic benchmark:** Run the unit suite and fixed-seed 300,000-record synthetic benchmark (zero DB connections) with:
|
|
|
|
```bash
|
|
bun test test/unit/security-master-security-type.test.ts
|
|
```
|
|
|
|
- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):**
|
|
- Workload: `300,000` synthetic EOD records (`100,000` distinct ISIN buckets, mixed mapped/unknown/missing types, and `20` conflicting ISINs exercising Pass 2 conflict collection).
|
|
- Observed throughput: `4,277,092 records/s` (`70.1 ms` wall time, floor `>= 100,000 records/s`).
|
|
|
|
## Security-Master Run Composer (`run.ts`)
|
|
`apps/stock/data-pipeline/src/security-master/run.ts` provides a pure, zero-I/O entry point (`composeSecurityMasterRun`) that wires in-memory source-symbol reader outputs and observed bar spans end to end without touching MongoDB, PostgreSQL, or the filesystem:
|
|
|
|
`sources + barSpans -> matchInstrumentsStageA -> attachBarSpansToStageBInput -> matchListingsStageB -> linkDelistingChains (Pass 6) -> optional crossCheckPrices (Pass 4) -> buildMatchReport (+ Markdown / CSV / override-template SQL) + PersistSecurityMasterInput`
|
|
|
|
- **Pure & deterministic:** Contains zero I/O imports and zero wall-clock calls. Shuffling any input array or `securityTypeByIsin` map insertion order produces byte-identical Markdown, CSV, override-template SQL, and deep-equal `PersistSecurityMasterInput`.
|
|
- **Explicit Pass 4 skipping:** When `sampleCloses` is omitted or empty, Pass 4 is marked `skipped` in both `stats.pass4` and the rendered Markdown (`- Status: skipped (no sample closes supplied)`), `pass4` is `null`, and `persistInput.pass4` is omitted — it is never reported as passed.
|
|
- **Malformed-record resilience & reconciliation:** Pre-pass sanitizers skip and count malformed or sparse entries across every input array without aborting the run, and every step reconciles `recordsIn === resolved + unresolved + skipped` with `report.conflicts.length === stageA + stageB + pass4 + pass6`.
|
|
- **Local synthetic benchmark:** Run the unit suite and fixed-seed 100,000-record synthetic benchmark (zero DB connections) with:
|
|
|
|
```bash
|
|
bun test test/unit/security-master-run.test.ts
|
|
```
|
|
|
|
- **Recorded baseline (`2026-11-28`, local sandbox, zero DB connections):**
|
|
- Workload: `100,000` synthetic source records (`50,000` EOD + `25,000` IB + `25,000` QM, `75,000` bar spans, `50,000` security types) composed end to end through Stage A, Stage B, Pass 6, Pass 4 pair derivation, MatchReport + Markdown/CSV/SQL rendering, and `PersistSecurityMasterInput` assembly.
|
|
- Observed throughput: `208,502 records/s` (`479.6 ms` wall time, asserted floor `>= 10,000 records/s`).
|
|
|
|
## Running the security master
|
|
`apps/stock/data-pipeline/src/security-master/run-security-master.ts` runs the full read-only MongoDB security-master pipeline (`read-exchanges` -> `read-sources` -> `compute-bar-spans` -> `composeSecurityMasterRun`) and writes deterministic report artifacts, with opt-in PostgreSQL persistence via `--persist`.
|
|
|
|
### Dry run (read-only MongoDB, zero PostgreSQL connections)
|
|
```bash
|
|
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
|
|
bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \
|
|
--as-of 2026-01-15 \
|
|
--out-dir ./tmp/security-master-report
|
|
```
|
|
|
|
- **Scope of `--as-of <YYYY-MM-DD>`:** `--as-of` sets the calendar reference date for Pass 6 delisting classification (active grace window vs. delisted outcome). It does **not** take a historical point-in-time snapshot of MongoDB — source symbol records and bar spans are read from the current collections, so the report can incorporate provider observations recorded after `--as-of`.
|
|
|
|
### Persist to isolated dev PostgreSQL (`localhost:5433/trading_bot_dev`)
|
|
Apply the `master` track migrations to isolated dev PostgreSQL first (passing the dev target variables explicitly so a QA-configured shell cannot migrate QA):
|
|
|
|
```bash
|
|
NODE_ENV=development \
|
|
POSTGRES_HOST=localhost \
|
|
POSTGRES_PORT=5433 \
|
|
POSTGRES_DATABASE=trading_bot_dev \
|
|
bun run db:migrate --track master
|
|
```
|
|
|
|
Then run the CLI with `--persist` against the same isolated dev PostgreSQL target:
|
|
|
|
```bash
|
|
NODE_ENV=development \
|
|
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
|
|
POSTGRES_HOST=localhost \
|
|
POSTGRES_PORT=5433 \
|
|
POSTGRES_DATABASE=trading_bot_dev \
|
|
bun run apps/stock/data-pipeline/src/security-master/run-security-master.ts \
|
|
--as-of 2026-01-15 \
|
|
--out-dir ./tmp/security-master-report \
|
|
--persist
|
|
```
|
|
|
|
- **Safety guards:** MongoDB is always opened with `mongoReadOnly: true` via `MONGODB_READ_URI`. Without `--persist`, no PostgreSQL client is constructed. With `--persist`, `assertSecurityMasterPersistSafety()` runs `assertEnvironmentSafety()` (with `STOCK_BOT_ALLOW_DEV_ON_QA_DB` stripped) and enforces `NODE_ENV=development` against an isolated dev PostgreSQL database (`*_dev` / `stock_bot_safety*`), blocking `NODE_ENV=qa` and QA PostgreSQL (`localhost:5432/trading_bot`) before any PostgreSQL client is created.
|
|
- **Pass 4 status:** Pass 4 cross-sectional price cross-check input (`sampleCloses` / `fxRates`) is **not yet wired** into this CLI; `composeSecurityMasterRun` is invoked without sample closes and Pass 4 is explicitly reported as `skipped` (`pass4: null`).
|
|
|
|
### Output files (`--out-dir`)
|
|
All four files are deterministic and byte-identical for identical inputs (no wall-clock timestamps or output paths):
|
|
- `match-report.md` — Human-readable match report covering exchange coverage, per-source/per-country resolution, unresolved breakdowns, Pass 4 (`skipped`), Pass 6 delisting chains, and conflicts.
|
|
- `conflicts.csv` — Unified deterministic conflict export across Stage A, Stage B, Pass 4, and Pass 6.
|
|
- `override-template.sql` — Commented SQL template for director-reviewed `override` entries.
|
|
- `run-stats.json` — Canonical ASCII-key-sorted JSON summary of exchange, reader, security-type, bar-span, composer, and report stats (`pass4Wired: false`).
|