Compare commits
94 commits
master
...
m1-close-e
| Author | SHA1 | Date | |
|---|---|---|---|
| 56b73b7e66 | |||
| d52aa20bff | |||
| d9191304fb | |||
|
|
88308e1f12 | ||
|
|
91f10312e9 | ||
|
|
76fc415db4 | ||
|
|
be144d874a | ||
|
|
97fad30fd0 | ||
|
|
d998115dcf | ||
|
|
88b7a5d141 | ||
|
|
a1690717c8 | ||
|
|
1db433bf01 | ||
|
|
cc39ee379a | ||
|
|
9adc8f18c6 | ||
|
|
4f09c6596d | ||
|
|
8560b22c71 | ||
|
|
a6163d9577 | ||
| 86010d7bbd | |||
|
|
878fa6addd | ||
|
|
abe114f415 | ||
|
|
ee983cb349 | ||
|
|
5e626b083b | ||
|
|
112b830985 | ||
|
|
5d97786254 | ||
|
|
0df1ef92ac | ||
|
|
91c7411ed9 | ||
|
|
aecafdebe1 | ||
|
|
ee69c216af | ||
|
|
bfcc1cf49f | ||
|
|
0a08a9962e | ||
|
|
9a213f126b | ||
|
|
1d4717c48e | ||
|
|
57b398694f | ||
|
|
f9bbc1d4a2 | ||
|
|
3279c50ae3 | ||
|
|
87fad608b0 | ||
|
|
ae00abcee4 | ||
|
|
3f3076079f | ||
|
|
0962f66cc3 | ||
|
|
c0afe5e3f0 | ||
|
|
722735c7c1 | ||
|
|
7c55c97c44 | ||
|
|
88b7f1f020 | ||
|
|
40a48e90ee | ||
|
|
83933c5124 | ||
|
|
a0d2a154f0 | ||
|
|
c343b97e26 | ||
|
|
8a0a353d2e | ||
|
|
eff7442bf9 | ||
|
|
6a4c15ffee | ||
|
|
0de120e7c8 | ||
|
|
d4671f39d5 | ||
|
|
f6daec2801 | ||
|
|
823143905a | ||
|
|
da730a5460 | ||
|
|
cffcbe23a6 | ||
|
|
234573a19e | ||
|
|
3883c73ce7 | ||
|
|
9594d82cdf | ||
|
|
3cd35b692f | ||
|
|
66efb2030b | ||
|
|
f2c3bca705 | ||
|
|
6cd00d8562 | ||
|
|
0abddd14a0 | ||
|
|
b2fe28b873 | ||
|
|
18cc2bc553 | ||
|
|
cdedcead74 | ||
| 11ff35054c | |||
|
|
f9fa7de8bb | ||
|
|
54b7276e59 | ||
|
|
d63463a64a | ||
|
|
38cab8b4ca | ||
|
|
000847f458 | ||
|
|
c57ca3201c | ||
|
|
5131c2525f | ||
|
|
7ea03c95ac | ||
|
|
f471c644f5 | ||
|
|
47f8258607 | ||
|
|
0e9f49a51d | ||
|
|
bab710c480 | ||
|
|
6734229022 | ||
|
|
50a9968e84 | ||
|
|
c8a2301527 | ||
|
|
87f75b19e4 | ||
| cbf25f90b7 | |||
|
|
d0c15ac5ae | ||
|
|
ec185b81ac | ||
|
|
e8652a1db1 | ||
|
|
1a621f0ed9 | ||
|
|
45930dd180 | ||
|
|
a2ab41e270 | ||
|
|
d191b9f46a | ||
|
|
5eefad525e | ||
|
|
6ce22a1643 |
140 changed files with 88846 additions and 222 deletions
7
.gitignore
vendored
7
.gitignore
vendored
|
|
@ -121,3 +121,10 @@ docs/configuration-standardization.md
|
|||
|
||||
# Rust
|
||||
target/
|
||||
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*.egg-info/
|
||||
.pytest_cache/
|
||||
.venv/
|
||||
|
|
|
|||
1287
Cargo.lock
generated
1287
Cargo.lock
generated
File diff suppressed because it is too large
Load diff
|
|
@ -206,3 +206,128 @@ All four files are deterministic and byte-identical for identical inputs (no wal
|
|||
- `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`).
|
||||
|
||||
## Read-Only Source Field-Shape Probe (`source-field-shapes.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/source-field-shapes.ts` and its CLI `probe-source-field-shapes.ts` sample raw MongoDB collections read-only to report exact field names, BSON/JS value types (`string`, `int`, `double`, `bool`, `date`, `null`, `objectId`, `array`, `object`, `other`), one-level nested `parent.child` keys, string pattern classes (`ymd`, `isoDatetime`, `numeric`, `emptyOrWhitespace`, `other`), and bounded sanitized examples (never emitted for `_id` / `_id.*`).
|
||||
|
||||
- **Bounded read-only contract:** Initializes config with `mongoReadOnly: true`, connects via `MONGODB_READ_URI` (`studio_stock_bot_read@stock`), refuses non-read-only readers before issuing any query, and runs strictly `find({}, { limit, promoteValues: false, promoteLongs: false })` (default `limit = 1,000`, max `10,000`) over allowlisted collections (`ceoShorts`, `qmSplits`, `qmDividends`, `qmFilings`, `qmEarnings`, `qmPrices`, `eodPrices`, `teMarketData`) — no aggregations, no `$sample`, no writes, and no index operations.
|
||||
- **Host live-run command (read-only QA MongoDB):**
|
||||
|
||||
```bash
|
||||
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
|
||||
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts \
|
||||
--out ./tmp/source-field-shapes.md \
|
||||
--limit 1000
|
||||
```
|
||||
|
||||
- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 80,000-doc streaming benchmark (`8` collections × `10,000` limit) with:
|
||||
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
|
||||
```
|
||||
|
||||
- **Recorded baselines (`2026-11-28`, local sandbox, in-memory async cursor fake reader):**
|
||||
- Workload: `80,000` synthetic docs (`8` collections × `10,000` limit) with mixed BSON/JS types, one-level nested objects, and all five string pattern classes, including `renderFieldShapesMarkdown`.
|
||||
- Initial implementation: `442,496 docs/s` (`180.8 ms` elapsed, `28.50 MiB` heap delta).
|
||||
- After path-segment escaping, exact defensive sample cap, and GFM/HTML-safe cell formatting: `365,756 docs/s` (`218.7 ms` elapsed, `27.66 MiB` heap delta).
|
||||
|
||||
## Read-Only Curate-ETL TSV Exporter (`export-curate-inputs.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts` and its CLI `run-export-curate-inputs.ts` read the PostgreSQL security-master tables strictly read-only inside a `REPEATABLE READ READ ONLY` transaction (bounded chunks `<= 5,000`, using a server-side `NO SCROLL` cursor for `provider_mapping`) and atomically publish each complete three-file set as an immutable generation under `<out-dir>/generations/<generationId>` through a single atomic `<out-dir>/current` symlink commit point (`--chunk-size` is optional; default `5000`, max `5000`):
|
||||
|
||||
```bash
|
||||
NODE_ENV=development \
|
||||
POSTGRES_HOST=localhost \
|
||||
POSTGRES_PORT=5433 \
|
||||
POSTGRES_DATABASE=trading_bot_dev \
|
||||
bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \
|
||||
--out-dir ./tmp/curate-inputs \
|
||||
--chunk-size 5000
|
||||
```
|
||||
|
||||
- **Immutable snapshot layout & consumer pinning:**
|
||||
- Each export writes all three TSVs into `<out-dir>/generations/<generationId>/` and serializes top-level link setup, commit (`<out-dir>/current -> generations/<generationId>`), and rollback behind `<out-dir>/.publish.lock`. Top-level symlinks (`<out-dir>/provider_mapping.tsv`, `<out-dir>/listing_currencies.tsv`, `<out-dir>/delistings.tsv`) point through `current/<file>`.
|
||||
- Multi-TSV Rust commands pin the active generation once before opening any TSV via `--curate-inputs <out-dir>` (e.g. `curate-etl curate-corporate-actions --qm-splits qmSplits.bson --qm-dividends qmDividends.bson --curate-inputs ./tmp/curate-inputs --out ./out` and `curate-etl curate-bars-1d --eod-prices eodPrices.bson --qm-splits qmSplits.bson --curate-inputs ./tmp/curate-inputs --out ./out`), and TypeScript consumers can pin via `pinCurateInputSnapshot(outDir)` so concurrent refreshes never mix files from different PostgreSQL snapshots.
|
||||
- **Output files:**
|
||||
- `provider_mapping.tsv` — `source \t source_id \t valid_from \t valid_to(or empty) \t listing_id`, sorted in `COLLATE "C"` ASCII order, preserving non-blank values verbatim and failing closed on `\t`/`\n`/`\r`, duplicates, or overlapping inclusive ranges.
|
||||
- `listing_currencies.tsv` — `listing_id \t currency`, sorted by ascending `listing_id`.
|
||||
- `delistings.tsv` — Pass 6 delistings (`source_id \t delist_date \t from_listing_id \t successor_source_id(or empty) \t terminal_return(or empty)`), resolved against `qm` mappings (`valid_from <= effective_date` for outgoing OTC transfers, valid on `effective_date` for OTC successors, valid on `listed_to` for terminal delistings) and indexed by `from_listing_id` so OTC successors (e.g. `SIVBQ`) still emit their own terminal delisting.
|
||||
- **Skip-reason accounting (`rowsIn === rowsOut + skippedTotal`):**
|
||||
- `active`: active listings (no delisting row emitted; fails closed if an `active` listing has a continuity or `terminal_return`).
|
||||
- `noOutcome`: non-active listings with neither an outgoing `otc_delist_transfer` nor a `terminal_return`.
|
||||
- `missingListedTo`: terminal-return listings with `listed_to IS NULL`.
|
||||
- `missingOutgoingQmMapping`: delisting/OTC candidates without a qualifying outgoing `qm` mapping.
|
||||
- `missingSuccessorQmMapping`: OTC transfers whose successor listing has no `qm` mapping valid on `effective_date`.
|
||||
- `nonOtcContinuity`: non-`otc_delist_transfer` continuities skipped in the pure `buildDelistingExportRows` builder.
|
||||
- **Local synthetic benchmark (zero PostgreSQL):** Run the fixed-seed 500,000-mapping / 100,000-listing streaming benchmark with:
|
||||
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts
|
||||
```
|
||||
|
||||
- **Recorded baseline (`2026-11-29`, local sandbox, in-memory cursor/keyset queryable, `chunkSize = 5000`):**
|
||||
- Workload: `500,000` `provider_mapping` rows, `100,000` `listing` rows, `2,000` OTC continuities, terminal delistings, and skipped rows (`606,680` exported rows, `17,203,861` bytes written across all three TSVs).
|
||||
- Observed throughput: `1,506,181 rows/s` (`402.8 ms` elapsed, `277.01 MiB` peak RSS).
|
||||
|
||||
## Read-Only Raw-BSON Exporter (`export-raw-bson.ts`)
|
||||
`apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` and its CLI `run-export-raw-bson.ts` stream M1 allowlisted MongoDB collections directly to `<out-dir>/<collection>.bson` as untouched length-prefixed raw BSON bytes (`find(filter, { raw: true, batchSize })` — zero per-document JS decoding), validating every frame (`byteLength >= 5`, `<= 16 MiB + 16 KiB`, 4-byte LE length prefix `=== byteLength`, trailing `0x00`), coalescing writes through a fixed-size 8 MiB buffer with strict backpressure, computing an incremental SHA-256 digest, and publishing atomically via a same-directory temp file (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`).
|
||||
|
||||
- **Allowlisted collections (`RAW_BSON_EXPORT_COLLECTIONS`):** `eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`. Any other collection (including M2 collections such as `eodIntraday1M`, `qmIntraday`, `qmFinancials`, `ceoPosts`) is rejected before any MongoDB call.
|
||||
- **Flags:**
|
||||
- `--out-dir <dir>` *(required)* — destination directory for `<collection>.bson` files.
|
||||
- `--collections <c1,c2,...>` *(optional)* — comma-separated subset of allowlisted collections (defaults to all 8).
|
||||
- `--eod-symbol <code>` *(optional)* — exact `{ eodSearchCode: <code> }` filter; only permitted when `--collections` is strictly `eodPrices` (for example `CAD.FOREX` for `curate-fx-1d`). Use a **separate `--out-dir`** so a filtered slice never overwrites the full `eodPrices.bson`.
|
||||
- `--te-symbol <sym>` *(optional)* — exact `{ teSymbol: <sym> }` filter; only permitted when `--collections` is strictly `teMarketData` (for example `USDCAD`).
|
||||
- `--limit <n>` *(optional)* — positive integer document cap per collection for smoke runs.
|
||||
- `--batch-size <n>` *(optional)* — MongoDB cursor `batchSize` (`1..100000`, default `4096`).
|
||||
- `--help` — print usage and exit with zero config/Mongo/fs I/O.
|
||||
- **Read-only safety:** Initializes config via `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, enforces `assertEnvironmentSafety()` via `assertExportRawBsonSafety()`, connects through `resolveReadOnlyMongoClientConfig()`, issues strictly `find(..., { raw: true })`, and always closes the MongoDB client in `finally`. Running against live QA MongoDB is a **separate manual host step** (never executed by automated tests or benchmarks).
|
||||
|
||||
### Full M1 Step 2 Chain Order (Manual Host Run)
|
||||
1. **Export PostgreSQL security-master TSVs (`run-export-curate-inputs.ts`):**
|
||||
```bash
|
||||
NODE_ENV=development \
|
||||
POSTGRES_HOST=localhost \
|
||||
POSTGRES_PORT=5433 \
|
||||
POSTGRES_DATABASE=trading_bot_dev \
|
||||
bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts \
|
||||
--out-dir ./tmp/curate-inputs
|
||||
```
|
||||
2. **Export raw BSON collections from read-only QA MongoDB (`run-export-raw-bson.ts`):**
|
||||
```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-export-raw-bson.ts \
|
||||
--out-dir ./tmp/raw-bson \
|
||||
--collections eodPrices,qmSplits,qmDividends,qmPrices,ceoShorts,qmFilings,qmEarnings
|
||||
|
||||
# Export filtered FX inputs to a separate directory so full eodPrices.bson is not overwritten:
|
||||
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
|
||||
bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \
|
||||
--out-dir ./tmp/raw-bson-fx \
|
||||
--collections eodPrices \
|
||||
--eod-symbol CAD.FOREX
|
||||
|
||||
MONGODB_READ_URI="mongodb://studio_stock_bot_read:<password>@localhost:27017/stock?authSource=stock" \
|
||||
bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts \
|
||||
--out-dir ./tmp/raw-bson-fx \
|
||||
--collections teMarketData \
|
||||
--te-symbol USDCAD
|
||||
```
|
||||
3. **Run `tools/curate-etl` commands (`curate-bars-1d` first, then the remaining datasets):**
|
||||
- `curate-etl curate-bars-1d` (`--eod-prices ./tmp/raw-bson/eodPrices.bson`, `--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-prices ./tmp/raw-bson/qmPrices.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated` — writes `./tmp/curated/bars_1d/year=YYYY/part.parquet` and prints read-only `qmPrices.sharevolume` cross-check stats)
|
||||
- `curate-etl curate-adj-factors` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--bars-1d ./tmp/curated/bars_1d`, `--out ./tmp/curated`)
|
||||
- `curate-etl curate-corporate-actions` (`--qm-splits ./tmp/raw-bson/qmSplits.bson`, `--qm-dividends ./tmp/raw-bson/qmDividends.bson`, `--curate-inputs ./tmp/curate-inputs`, `--out ./tmp/curated`)
|
||||
- `curate-etl curate-fx-1d` (`--eod-prices ./tmp/raw-bson-fx/eodPrices.bson`, `--te-market-data ./tmp/raw-bson-fx/teMarketData.bson`, `--out ./tmp/curated`)
|
||||
- `curate-etl curate-shorts` (`--ceo-shorts ./tmp/raw-bson/ceoShorts.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--shares-short-field <name>`)
|
||||
- `curate-etl curate-events` (`--qm-filings ./tmp/raw-bson/qmFilings.bson`, `--qm-earnings ./tmp/raw-bson/qmEarnings.bson`, `--provider-mapping ./tmp/curate-inputs/current/provider_mapping.tsv`, `--out ./tmp/curated`, plus required `--filings-form-type-field <name>`)
|
||||
|
||||
- **Local synthetic benchmark (zero MongoDB):** Run the fixed-seed 1,000,000-doc streaming benchmark with:
|
||||
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts
|
||||
```
|
||||
|
||||
- **Recorded baseline (`2026-11-29`, local sandbox, in-memory async cursor fake source, `writeBufferBytes = 8 MiB`):**
|
||||
- Workload: `1,000,000` synthetic `eodPrices` raw BSON frames (`123.9 B` avg, `123,863,264` bytes written, deterministic `sha256=67f035eba7060d6312f3d5faecc9e6a6fa14f6239c0c4dc1859794b4cd895886`).
|
||||
- Run 1 (`1,000,000` docs): `3,574,267 docs/s`, `422.21 MiB/s` (`279.8 ms` elapsed, `rss_before=97.00 MiB`, `rss_after=149.91 MiB`, `peak_rss=150.19 MiB`).
|
||||
- Run 2 (`1,000,000` docs): `3,692,715 docs/s`, `436.20 MiB/s` (`270.8 ms` elapsed, `peak_rss=151.03 MiB`, identical `sha256`).
|
||||
- Scaling check (`2,000,000` docs, `247,726,576` bytes): `3,833,075 docs/s`, `452.78 MiB/s` (`521.8 ms` elapsed, `peak_rss=146.88 MiB` — confirms peak RSS stays bounded independent of document count).
|
||||
|
|
|
|||
|
|
@ -0,0 +1,292 @@
|
|||
/**
|
||||
* Reproducible headless benchmark for `exportCurateInputs`.
|
||||
* Streams 500,000 `provider_mapping` rows + 100,000 `listing` rows + 2,000 OTC continuities +
|
||||
* terminal delistings + skipped rows through an in-memory keyset-paginated
|
||||
* `SecurityMasterQueryable` into a temporary directory (cleaned up in `finally`), with zero
|
||||
* database or network dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts
|
||||
*/
|
||||
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
exportCurateInputs,
|
||||
type SecurityMasterQueryable,
|
||||
type SecurityMasterQueryResult,
|
||||
} from '../src/security-master/export-curate-inputs';
|
||||
|
||||
const LISTING_COUNT = 100_000;
|
||||
const PROVIDER_MAPPING_COUNT = 500_000;
|
||||
const OTC_CONTINUITY_COUNT = 2_000;
|
||||
|
||||
interface BenchContinuityRow {
|
||||
from_listing_id: number;
|
||||
to_listing_id: number;
|
||||
effective_date: string;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
interface BenchListingRow {
|
||||
listing_id: number;
|
||||
currency: string;
|
||||
listed_to: string | null;
|
||||
delist_reason: string | null;
|
||||
terminal_return: string | null;
|
||||
}
|
||||
|
||||
interface BenchMappingRow {
|
||||
source: string;
|
||||
source_id: string;
|
||||
valid_from: string;
|
||||
valid_to: string | null;
|
||||
listing_id: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generates deterministic sorted synthetic rows (matching PostgreSQL ORDER BY):
|
||||
* - 100,000 listings:
|
||||
* - 1..2000: OTC outgoing listings (moved_to_otc -> successor listing_id + 2000)
|
||||
* - 2001..4000: OTC successor listings (half bankruptcy_cancelled -1.0, half active)
|
||||
* - 4001..8000: terminal delistings (-0.3; every 20th has listed_to = null -> missingListedTo)
|
||||
* - 8001..10000: delisted with null outcome (noOutcome)
|
||||
* - 10001..100000: active US/CA listings
|
||||
* - 500,000 provider_mapping rows in strict ASCII COLLATE "C" order across 5 sources:
|
||||
* ceo (100k), eod (100k), ib (100k), qm (100k), te (100k).
|
||||
* For a small deterministic subset of listings, omit the `qm` mapping (assign to listing 10001)
|
||||
* so missingOutgoingQmMapping and missingSuccessorQmMapping are exercised too.
|
||||
*/
|
||||
function buildSyntheticTables(): {
|
||||
continuities: BenchContinuityRow[];
|
||||
listings: BenchListingRow[];
|
||||
mappings: BenchMappingRow[];
|
||||
} {
|
||||
const continuities = new Array<BenchContinuityRow>(OTC_CONTINUITY_COUNT);
|
||||
for (let i = 0; i < OTC_CONTINUITY_COUNT; i++) {
|
||||
const fromId = i + 1;
|
||||
continuities[i] = {
|
||||
from_listing_id: fromId,
|
||||
to_listing_id: fromId + OTC_CONTINUITY_COUNT,
|
||||
effective_date: '2023-03-28',
|
||||
kind: 'otc_delist_transfer',
|
||||
};
|
||||
}
|
||||
|
||||
const listings = new Array<BenchListingRow>(LISTING_COUNT);
|
||||
for (let i = 0; i < LISTING_COUNT; i++) {
|
||||
const id = i + 1;
|
||||
const currency = id % 5 === 0 ? 'CAD' : 'USD';
|
||||
if (id <= OTC_CONTINUITY_COUNT) {
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
listed_to: '2023-03-10',
|
||||
delist_reason: 'moved_to_otc',
|
||||
terminal_return: null,
|
||||
};
|
||||
} else if (id <= OTC_CONTINUITY_COUNT * 2) {
|
||||
if (id % 2 === 0) {
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
listed_to: '2024-11-07',
|
||||
delist_reason: 'bankruptcy_cancelled',
|
||||
terminal_return: '-1.000000',
|
||||
};
|
||||
} else {
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
};
|
||||
}
|
||||
} else if (id <= 8_000) {
|
||||
const missingDate = id % 20 === 0;
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
listed_to: missingDate ? null : '2023-06-15',
|
||||
delist_reason: 'unknown_involuntary',
|
||||
terminal_return: '-0.300000',
|
||||
};
|
||||
} else if (id <= 10_000) {
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
listed_to: '2022-12-30',
|
||||
delist_reason: null,
|
||||
terminal_return: null,
|
||||
};
|
||||
} else {
|
||||
listings[i] = {
|
||||
listing_id: id,
|
||||
currency,
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 5 sources in strict ASCII order: ceo, eod, ib, qm, te (100,000 rows each = 500,000 total).
|
||||
const sources = ['ceo', 'eod', 'ib', 'qm', 'te'] as const;
|
||||
const mappings = new Array<BenchMappingRow>(PROVIDER_MAPPING_COUNT);
|
||||
let idx = 0;
|
||||
for (const source of sources) {
|
||||
for (let i = 0; i < LISTING_COUNT; i++) {
|
||||
const naturalListingId = i + 1;
|
||||
const padded = String(naturalListingId).padStart(6, '0');
|
||||
let listingId = naturalListingId;
|
||||
let validFrom = '2015-01-02';
|
||||
let validTo: string | null = null;
|
||||
|
||||
if (naturalListingId <= OTC_CONTINUITY_COUNT) {
|
||||
validTo = '2023-03-10';
|
||||
// Drop QM mapping for every 40th outgoing OTC listing (redirect to active listing 10001).
|
||||
if (source === 'qm' && naturalListingId % 40 === 0) {
|
||||
listingId = 10_001;
|
||||
}
|
||||
} else if (naturalListingId <= OTC_CONTINUITY_COUNT * 2) {
|
||||
validFrom = '2023-03-28';
|
||||
validTo = naturalListingId % 2 === 0 ? '2024-11-07' : null;
|
||||
// Drop QM mapping for every 50th successor OTC listing.
|
||||
if (source === 'qm' && naturalListingId % 50 === 0) {
|
||||
listingId = 10_002;
|
||||
}
|
||||
} else if (naturalListingId <= 8_000) {
|
||||
validTo = '2023-06-15';
|
||||
}
|
||||
|
||||
mappings[idx++] = {
|
||||
source,
|
||||
source_id: `SYM${padded}`,
|
||||
valid_from: validFrom,
|
||||
valid_to: validTo,
|
||||
listing_id: listingId,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { continuities, listings, mappings };
|
||||
}
|
||||
|
||||
function createFastPaginatedQueryable(tables: {
|
||||
continuities: BenchContinuityRow[];
|
||||
listings: BenchListingRow[];
|
||||
mappings: BenchMappingRow[];
|
||||
}): SecurityMasterQueryable {
|
||||
let contOffset = 0;
|
||||
let listingOffset = 0;
|
||||
let mappingOffset = 0;
|
||||
|
||||
return {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
const normalized = text.replace(/\s+/g, ' ').trim();
|
||||
if (normalized.startsWith('BEGIN')) {
|
||||
contOffset = 0;
|
||||
listingOffset = 0;
|
||||
mappingOffset = 0;
|
||||
return { rows: [] };
|
||||
}
|
||||
if (normalized === 'COMMIT' || normalized === 'ROLLBACK') {
|
||||
return { rows: [] };
|
||||
}
|
||||
if (normalized.startsWith('DECLARE ') && normalized.includes('FROM provider_mapping')) {
|
||||
mappingOffset = 0;
|
||||
return { rows: [] };
|
||||
}
|
||||
const fetchMatch = /^FETCH FORWARD (\d+) FROM \S+$/i.exec(normalized);
|
||||
if (fetchMatch) {
|
||||
const fetchLimit = Number(fetchMatch[1]);
|
||||
const slice = tables.mappings.slice(mappingOffset, mappingOffset + fetchLimit);
|
||||
mappingOffset += slice.length;
|
||||
return { rows: slice as unknown as Row[] };
|
||||
}
|
||||
if (/^CLOSE \S+$/i.test(normalized)) {
|
||||
return { rows: [] };
|
||||
}
|
||||
|
||||
const limit = values ? (values[values.length - 1] as number) : DEFAULT_EXPORT_CHUNK_SIZE;
|
||||
|
||||
if (normalized.includes('FROM corporate_action_continuity')) {
|
||||
const slice = tables.continuities.slice(contOffset, contOffset + limit);
|
||||
contOffset += slice.length;
|
||||
return { rows: slice as unknown as Row[] };
|
||||
}
|
||||
if (normalized.includes('FROM listing')) {
|
||||
const slice = tables.listings.slice(listingOffset, listingOffset + limit);
|
||||
listingOffset += slice.length;
|
||||
return { rows: slice as unknown as Row[] };
|
||||
}
|
||||
if (normalized.includes('FROM provider_mapping')) {
|
||||
const slice = tables.mappings.slice(mappingOffset, mappingOffset + limit);
|
||||
mappingOffset += slice.length;
|
||||
return { rows: slice as unknown as Row[] };
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected SQL in benchmark queryable: ${normalized}`);
|
||||
},
|
||||
release: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const tables = buildSyntheticTables();
|
||||
const queryable = createFastPaginatedQueryable(tables);
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'curate-inputs-bench-'));
|
||||
|
||||
try {
|
||||
const startNs = Bun.nanoseconds();
|
||||
const result = await exportCurateInputs(queryable, {
|
||||
outDir,
|
||||
chunkSize: DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
});
|
||||
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
|
||||
|
||||
const d = result.delistings.stats;
|
||||
const skipSum =
|
||||
d.skipped.active +
|
||||
d.skipped.noOutcome +
|
||||
d.skipped.missingListedTo +
|
||||
d.skipped.missingOutgoingQmMapping +
|
||||
d.skipped.missingSuccessorQmMapping +
|
||||
d.skipped.nonOtcContinuity;
|
||||
if (d.skippedTotal !== skipSum || d.rowsIn !== d.rowsOut + d.skippedTotal) {
|
||||
throw new Error(
|
||||
`Delisting stats reconciliation failed: rowsIn=${d.rowsIn} rowsOut=${d.rowsOut} skippedTotal=${d.skippedTotal} skipSum=${skipSum}`
|
||||
);
|
||||
}
|
||||
|
||||
const totalRowsExported =
|
||||
result.providerMapping.rowsOut + result.listingCurrencies.rowsOut + result.delistings.rowsOut;
|
||||
const rowsPerSec = totalRowsExported / (elapsedMs / 1000);
|
||||
// process.resourceUsage().maxRSS is reported in KiB on Linux.
|
||||
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
|
||||
|
||||
process.stdout.write('exportCurateInputs benchmark complete\n');
|
||||
process.stdout.write(
|
||||
` inputs: provider_mapping=${PROVIDER_MAPPING_COUNT} listings=${LISTING_COUNT} otc_continuities=${OTC_CONTINUITY_COUNT}\n`
|
||||
);
|
||||
process.stdout.write(
|
||||
` exported: provider_mapping=${result.providerMapping.rowsOut} listing_currencies=${result.listingCurrencies.rowsOut} delistings=${result.delistings.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut} skipped=${d.skippedTotal})\n`
|
||||
);
|
||||
process.stdout.write(
|
||||
` total_rows_out=${totalRowsExported} bytes_written=${result.totalBytesWritten} elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(rowsPerSec)} rows/s peak_rss=${peakRssMiB.toFixed(2)} MiB\n`
|
||||
);
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
140
apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts
Normal file
140
apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts
Normal file
|
|
@ -0,0 +1,140 @@
|
|||
/**
|
||||
* Reproducible headless benchmark for `exportRawBsonCollection`.
|
||||
* Streams >= 1,000,000 fixed-seed synthetic ~100 B raw BSON `eodPrices` frames through
|
||||
* `exportRawBsonCollection` into a temporary directory (cleaned up in `finally`), with zero
|
||||
* MongoDB or network dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts [docCount]
|
||||
*/
|
||||
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
DEFAULT_WRITE_BUFFER_BYTES,
|
||||
exportRawBsonCollection,
|
||||
type ReadOnlyRawBsonSource,
|
||||
} from '../src/security-master/export-raw-bson';
|
||||
|
||||
const DEFAULT_DOC_COUNT = 1_000_000;
|
||||
const POOL_SIZE = 1_024;
|
||||
|
||||
function parseDocCount(): number {
|
||||
const raw = process.argv[2];
|
||||
if (raw === undefined) {
|
||||
return DEFAULT_DOC_COUNT;
|
||||
}
|
||||
if (!/^\d+$/.test(raw)) {
|
||||
throw new Error(`Invalid docCount "${raw}": expected a positive integer`);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1) {
|
||||
throw new Error(`Invalid docCount "${raw}": expected a positive integer`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic PRNG (Mulberry32) so the synthetic BSON pool is identical across runs.
|
||||
*/
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function buildSyntheticBsonPool(): Uint8Array[] {
|
||||
const rng = createSeededRng(0x5eed117);
|
||||
const pool = new Array<Uint8Array>(POOL_SIZE);
|
||||
for (let i = 0; i < POOL_SIZE; i++) {
|
||||
const base = 10 + Math.round(rng() * 20000) / 100;
|
||||
const high = Math.round((base + rng() * 3) * 100) / 100;
|
||||
const low = Math.max(0.01, Math.round((base - rng() * 3) * 100) / 100);
|
||||
const close = Math.round((low + rng() * (high - low)) * 100) / 100;
|
||||
const volume = Math.floor(1_000 + rng() * 5_000_000);
|
||||
const month = String((i % 12) + 1).padStart(2, '0');
|
||||
const day = String((i % 28) + 1).padStart(2, '0');
|
||||
const doc = {
|
||||
eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`,
|
||||
date: `2025-${month}-${day}`,
|
||||
open: base,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
volume,
|
||||
};
|
||||
pool[i] = Uint8Array.from(BSON.serialize(doc));
|
||||
}
|
||||
return pool;
|
||||
}
|
||||
|
||||
function createSyntheticRawSource(pool: readonly Uint8Array[], totalDocs: number): ReadOnlyRawBsonSource {
|
||||
const poolLen = pool.length;
|
||||
return {
|
||||
isReadOnly: () => true,
|
||||
find() {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (let i = 0; i < totalDocs; i++) {
|
||||
const frame = pool[i % poolLen];
|
||||
if (frame !== undefined) {
|
||||
yield frame;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const docCount = parseDocCount();
|
||||
const pool = buildSyntheticBsonPool();
|
||||
const avgDocBytes =
|
||||
pool.reduce((acc, frame) => acc + frame.byteLength, 0) / pool.length;
|
||||
const source = createSyntheticRawSource(pool, docCount);
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'export-raw-bson-bench-'));
|
||||
|
||||
try {
|
||||
const rssBeforeMiB = process.memoryUsage().rss / (1024 * 1024);
|
||||
const startNs = Bun.nanoseconds();
|
||||
const result = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
writeBufferBytes: DEFAULT_WRITE_BUFFER_BYTES,
|
||||
});
|
||||
const elapsedMs = (Bun.nanoseconds() - startNs) / 1e6;
|
||||
const rssAfterMiB = process.memoryUsage().rss / (1024 * 1024);
|
||||
// process.resourceUsage().maxRSS is reported in KiB on Linux.
|
||||
const peakRssMiB = process.resourceUsage().maxRSS / 1024;
|
||||
|
||||
const elapsedSec = elapsedMs / 1000;
|
||||
const docsPerSec = result.docsWritten / elapsedSec;
|
||||
const mibPerSec = result.bytesWritten / (1024 * 1024) / elapsedSec;
|
||||
|
||||
process.stdout.write('exportRawBsonCollection benchmark complete\n');
|
||||
process.stdout.write(
|
||||
` docs=${result.docsWritten} avg_doc_bytes=${avgDocBytes.toFixed(1)} bytes_written=${result.bytesWritten} write_buffer_bytes=${DEFAULT_WRITE_BUFFER_BYTES}\n`
|
||||
);
|
||||
process.stdout.write(
|
||||
` elapsed_ms=${elapsedMs.toFixed(1)} throughput=${Math.round(docsPerSec)} docs/s rate=${mibPerSec.toFixed(2)} MiB/s\n`
|
||||
);
|
||||
process.stdout.write(
|
||||
` rss_before=${rssBeforeMiB.toFixed(2)} MiB rss_after=${rssAfterMiB.toFixed(2)} MiB peak_rss=${peakRssMiB.toFixed(2)} MiB\n`
|
||||
);
|
||||
process.stdout.write(` sha256=${result.sha256}\n`);
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
main().catch(error => {
|
||||
process.stderr.write(`${error instanceof Error ? error.stack ?? error.message : String(error)}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
|
|
@ -0,0 +1,167 @@
|
|||
/**
|
||||
* Reproducible headless benchmark for `readFieldShapes` + `renderFieldShapesMarkdown`.
|
||||
* Streams 80,000 fixed-seed synthetic documents (8 allowlisted collections × 10,000 limit)
|
||||
* with mixed BSON/JS types, one-level nested objects, and all 5 string pattern classes
|
||||
* through an in-memory async-generator fake reader with zero MongoDB or network dependencies.
|
||||
*
|
||||
* Usage:
|
||||
* bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts
|
||||
*/
|
||||
|
||||
import {
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
FIELD_VALUE_TYPES,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
STRING_PATTERN_CLASSES,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
const DOCS_PER_COLLECTION = MAX_FIELD_SHAPE_LIMIT;
|
||||
|
||||
function mulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeSyntheticDoc(collectionIndex: number, docIndex: number, rng: () => number): Record<string, unknown> {
|
||||
const r = rng();
|
||||
const day = String((docIndex % 28) + 1).padStart(2, '0');
|
||||
const month = String(((docIndex + collectionIndex) % 12) + 1).padStart(2, '0');
|
||||
const dateStr = `2025-${month}-${day}`;
|
||||
const isoStr = `${dateStr}T14:30:00Z`;
|
||||
|
||||
const doc: Record<string, unknown> = {
|
||||
_id: {
|
||||
_bsontype: 'ObjectId',
|
||||
toString: () =>
|
||||
`${String(collectionIndex).padStart(2, '0')}${String(docIndex).padStart(22, '0')}`,
|
||||
},
|
||||
symbol: `SYM${String(docIndex % 2000).padStart(4, '0')}`,
|
||||
date: r < 0.85 ? dateStr : r < 0.95 ? isoStr : '',
|
||||
value:
|
||||
r < 0.5
|
||||
? { _bsontype: 'Double', toString: () => (10 + (docIndex % 500) * 0.25).toFixed(2) }
|
||||
: r < 0.8
|
||||
? { _bsontype: 'Int32', toString: () => String(docIndex % 10000) }
|
||||
: r < 0.92
|
||||
? String((docIndex % 1000) / 10)
|
||||
: null,
|
||||
active: docIndex % 5 !== 0,
|
||||
updatedAt: new Date(1735689600000 + (docIndex % 365) * 86_400_000),
|
||||
meta: {
|
||||
exchange: docIndex % 2 === 0 ? 'NYSE' : 'TSX',
|
||||
version: { _bsontype: 'Int32', toString: () => '2' },
|
||||
},
|
||||
};
|
||||
|
||||
if (docIndex % 7 === 0) {
|
||||
doc.tags = ['equity', 'na'];
|
||||
}
|
||||
return doc;
|
||||
}
|
||||
|
||||
function createSyntheticBenchmarkReader(): ReadOnlySourceSymbolReader {
|
||||
return {
|
||||
isReadOnly(): boolean {
|
||||
return true;
|
||||
},
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
_filter?: Record<string, unknown>,
|
||||
options?: SourceSymbolFindOptions
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
const colIdx = FIELD_SHAPE_PROBE_COLLECTIONS.indexOf(
|
||||
collectionName as (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number]
|
||||
);
|
||||
const count = Math.min(DOCS_PER_COLLECTION, options?.limit ?? DOCS_PER_COLLECTION);
|
||||
const rng = mulberry32(0x5eed108 + (colIdx + 1) * 7919);
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (let i = 0; i < count; i++) {
|
||||
yield makeSyntheticDoc(colIdx, i, rng) as T;
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
// No-op for in-memory benchmark cursor.
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const reader = createSyntheticBenchmarkReader();
|
||||
|
||||
if (typeof Bun !== 'undefined' && typeof Bun.gc === 'function') {
|
||||
Bun.gc(true);
|
||||
}
|
||||
const heapBefore = process.memoryUsage().heapUsed;
|
||||
const startedAt = performance.now();
|
||||
|
||||
const result = await readFieldShapes(reader, {
|
||||
limit: DOCS_PER_COLLECTION,
|
||||
batchSize: 2_000,
|
||||
});
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
|
||||
const elapsedMs = performance.now() - startedAt;
|
||||
const heapAfter = process.memoryUsage().heapUsed;
|
||||
const heapDeltaMb = (heapAfter - heapBefore) / (1024 * 1024);
|
||||
|
||||
const expectedTotal = FIELD_SHAPE_PROBE_COLLECTIONS.length * DOCS_PER_COLLECTION;
|
||||
if (result.totalDocsSampled !== expectedTotal) {
|
||||
throw new Error(
|
||||
`Unexpected totalDocsSampled=${result.totalDocsSampled} (expected ${expectedTotal})`
|
||||
);
|
||||
}
|
||||
|
||||
for (const col of result.collections) {
|
||||
for (const field of col.fields) {
|
||||
if (field.presentCount + field.missingCount !== col.docCount) {
|
||||
throw new Error(`Presence mismatch on ${col.collection}.${field.field}`);
|
||||
}
|
||||
let typeSum = 0;
|
||||
for (const typeName of FIELD_VALUE_TYPES) {
|
||||
typeSum += field.typeCounts[typeName];
|
||||
}
|
||||
if (typeSum !== field.presentCount) {
|
||||
throw new Error(`Type sum mismatch on ${col.collection}.${field.field}`);
|
||||
}
|
||||
if (field.stringStats !== null) {
|
||||
let patternSum = 0;
|
||||
for (const p of STRING_PATTERN_CLASSES) {
|
||||
patternSum += field.stringStats.patterns[p];
|
||||
}
|
||||
if (patternSum !== field.typeCounts.string) {
|
||||
throw new Error(`Pattern sum mismatch on ${col.collection}.${field.field}`);
|
||||
}
|
||||
}
|
||||
if ((field.field === '_id' || field.field.startsWith('_id.')) && field.examples.length > 0) {
|
||||
throw new Error(`_id example leaked on ${col.collection}.${field.field}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const docsPerSec = Math.round(result.totalDocsSampled / (elapsedMs / 1000));
|
||||
const lines = [
|
||||
'Source field-shapes probe benchmark (in-memory async cursor, zero MongoDB)',
|
||||
` Workload: ${result.totalDocsSampled.toLocaleString('en-US')} docs (${FIELD_SHAPE_PROBE_COLLECTIONS.length} collections x ${DOCS_PER_COLLECTION.toLocaleString('en-US')} limit)`,
|
||||
` Markdown: ${markdown.length.toLocaleString('en-US')} chars`,
|
||||
` Elapsed: ${elapsedMs.toFixed(1)} ms`,
|
||||
` Throughput: ${docsPerSec.toLocaleString('en-US')} docs/s`,
|
||||
` Heap delta: ${heapDeltaMb.toFixed(2)} MiB`,
|
||||
];
|
||||
process.stdout.write(`${lines.join('\n')}\n`);
|
||||
}
|
||||
|
||||
await main();
|
||||
|
|
@ -175,6 +175,49 @@ function parseExactIsoDateToUtcDay(value: unknown): number | null {
|
|||
return era * 146097 + dayOfEra - 719468;
|
||||
}
|
||||
|
||||
function formatUtcDayToIsoDate(daysSinceEpoch: number): string {
|
||||
const shifted = daysSinceEpoch + 719468;
|
||||
const era = Math.floor(shifted / 146097);
|
||||
const doe = shifted - era * 146097;
|
||||
const yoe = Math.floor(
|
||||
(doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365
|
||||
);
|
||||
const y = yoe + era * 400;
|
||||
const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
|
||||
const mp = Math.floor((5 * doy + 2) / 153);
|
||||
const day = doy - Math.floor((153 * mp + 2) / 5) + 1;
|
||||
const month = mp + (mp < 10 ? 3 : -9);
|
||||
const year = y + (month <= 2 ? 1 : 0);
|
||||
const yStr = String(year).padStart(4, '0');
|
||||
const mStr = month < 10 ? `0${String(month)}` : String(month);
|
||||
const dStr = day < 10 ? `0${String(day)}` : String(day);
|
||||
return `${yStr}-${mStr}-${dStr}`;
|
||||
}
|
||||
|
||||
function isBackfilledOtcContinuation(
|
||||
primary: EndedPrimaryRow,
|
||||
otc: EligibleOtcRow,
|
||||
overlapToleranceDays: number
|
||||
): boolean {
|
||||
// Provider backfills (notably EODHD on SIVB -> SIVBQ) copy the primary listing's entire
|
||||
// pre-delist bar history onto the OTC ticker, so otc.listedFrom matches primary.listedFrom
|
||||
// rather than starting near primary.listedTo. Require that OTC trading continued strictly
|
||||
// past primary.listedTo and either shares the primary's IPO/start date or carries the
|
||||
// canonical bankruptcy `<primaryTicker>Q` suffix.
|
||||
if (otc.listedFromDay >= primary.listedToDay - overlapToleranceDays) {
|
||||
return false;
|
||||
}
|
||||
if (otc.listedToDay !== null && otc.listedToDay <= primary.listedToDay) {
|
||||
return false;
|
||||
}
|
||||
const sameBackfilledStart =
|
||||
primary.listedFromDay !== null &&
|
||||
otc.listedFromDay <= primary.listedFromDay + overlapToleranceDays;
|
||||
const isBankruptcyQSuffix =
|
||||
otc.key.tickerRoot.toUpperCase() === `${primary.key.tickerRoot.toUpperCase()}Q`;
|
||||
return sameBackfilledStart || isBankruptcyQSuffix;
|
||||
}
|
||||
|
||||
function cloneListingKey(key: ListingNaturalKey): ListingNaturalKey {
|
||||
return {
|
||||
primaryIsin: key.primaryIsin,
|
||||
|
|
@ -693,13 +736,24 @@ export function linkDelistingChains(
|
|||
otc.listedToDay === null || otc.listedToDay > maxWindowDay
|
||||
? maxWindowDay
|
||||
: otc.listedToDay;
|
||||
if (lowDay > highDay) {
|
||||
continue;
|
||||
if (lowDay <= highDay) {
|
||||
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
|
||||
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
|
||||
if (startIdx < endExclusive) {
|
||||
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const startIdx = lowerBoundPrimaryByListedToDay(primaries, lowDay);
|
||||
const endExclusive = upperBoundPrimaryByListedToDay(primaries, highDay);
|
||||
if (startIdx < endExclusive) {
|
||||
intervals.push({ startIdx, endIdx: endExclusive - 1, otcIdx: oIdx });
|
||||
// Fallback for EODHD-style backfilled OTC history (e.g. SIVB -> SIVBQ) where the OTC
|
||||
// ticker carries pre-delist bars back to the primary listing's original start date.
|
||||
for (let pIdx = 0; pIdx < primaries.length; pIdx++) {
|
||||
const primary = primaries[pIdx];
|
||||
if (
|
||||
primary !== undefined &&
|
||||
isBackfilledOtcContinuation(primary, otc, overlapToleranceDays)
|
||||
) {
|
||||
intervals.push({ startIdx: pIdx, endIdx: pIdx, otcIdx: oIdx });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -730,13 +784,16 @@ export function linkDelistingChains(
|
|||
const otc = oIdx !== undefined ? otcs[oIdx] : undefined;
|
||||
if (primary !== undefined && otc !== undefined) {
|
||||
linkedPrimaryIndices.add(primary.index);
|
||||
// effectiveDate uses the OTC listing's first observed date (listedFrom) so
|
||||
// downstream backtests and curation never back-date OTC availability before
|
||||
// OTC trading/quoting actually began.
|
||||
// effectiveDate uses the OTC listing's first observed date (listedFrom) for clean
|
||||
// transfers, or the day after primary.listedTo when the OTC ticker's pre-delist history
|
||||
// was backfilled (so downstream curation never back-dates the transfer to the IPO date).
|
||||
const effectiveDate = isBackfilledOtcContinuation(primary, otc, overlapToleranceDays)
|
||||
? formatUtcDayToIsoDate(primary.listedToDay + 1)
|
||||
: otc.listedFrom;
|
||||
continuities.push({
|
||||
fromListingKey: cloneListingKey(primary.key),
|
||||
toListingKey: cloneListingKey(otc.key),
|
||||
effectiveDate: otc.listedFrom,
|
||||
effectiveDate,
|
||||
kind: CONTINUITY_KIND_OTC_DELIST_TRANSFER,
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -71,6 +71,7 @@ export interface ExchangeClassificationResult {
|
|||
|
||||
export interface ClassifySourceExchangesOptions {
|
||||
knownExchanges?: readonly ExchangeSeedRow[];
|
||||
reviewedRows?: readonly ExchangeSourceMapRow[];
|
||||
}
|
||||
|
||||
const VALID_EXCHANGE_SOURCE_SET: ReadonlySet<string> = new Set(EXCHANGE_SOURCES);
|
||||
|
|
@ -293,9 +294,15 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
|
|||
{ source: 'eod' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'NYSE ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'NYSE MKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'NYSE NAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'NYSEARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'NYSEMKT', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTC', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCBB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCCE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCGREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCMKTS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCMTKS', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCQB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'eod' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
|
|
@ -305,19 +312,63 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
|
|||
{ source: 'ib' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'BATS', role: 'primary_venue' as const, mic: 'BATS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'BOX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'BYX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CBOE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CBOE2', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CDE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
|
||||
{ source: 'ib' as const, sourceCode: 'CFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CFETAS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CHX', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'CME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'COMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'EMERALD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'FORECASTX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'FUNDSERV', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'GEMINI', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IBCMDTY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IBDESK', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IBFX', role: 'forex' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IBKRAM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IBKRATS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IBUSCFD', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'ICEUS', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'IDEALPRO', role: 'forex' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'ISE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'ISLAND', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'LTSE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'MERCURY', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'MIAX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NASDAQBX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NASDAQOM', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
|
||||
{ source: 'ib' as const, sourceCode: 'NYBOT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NYMEX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NYSE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NYSEFLOOR', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NYSELIFFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'NYSENAT', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'OVERNIGHT', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'PEARL', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'PHLX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'PSE', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'PURE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
|
||||
{ source: 'ib' as const, sourceCode: 'SGXCME', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'SMFE', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'TRADEWEB', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
|
||||
{ source: 'ib' as const, sourceCode: 'VALUE', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'ib' as const, sourceCode: 'VENTURE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
|
||||
{ source: 'ib' as const, sourceCode: 'ZEROHASH', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
// QuoteMedia US + CA venues (qmExchanges has 0% OperatingMIC)
|
||||
{ source: 'qm' as const, sourceCode: 'AMEX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'AMX', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'AQL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'AQLL', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'ARC', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'ARCA', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'ASE', role: 'primary_venue' as const, mic: 'XASE', countryIso: 'US' },
|
||||
|
|
@ -332,16 +383,23 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
|
|||
{ source: 'qm' as const, sourceCode: 'CNX', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'CSE', role: 'primary_venue' as const, mic: 'XCNQ', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'CVE', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'CVEM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'EDGA', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'EDGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'EGX', role: 'ats_routing' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'EXPM', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'GREY', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'IEX', role: 'primary_venue' as const, mic: 'IEXG', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'MOE', role: 'ats_routing' as const, mic: null, countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NCM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NDD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NEO', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'NEOE', role: 'primary_venue' as const, mic: 'NEOE', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'NGM', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NGS', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NMF', role: 'excluded_fund' as const, mic: null, countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NSC', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NSD', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NSQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'NYE', role: 'primary_venue' as const, mic: 'XNYS', countryIso: 'US' },
|
||||
|
|
@ -357,6 +415,7 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
|
|||
{ source: 'qm' as const, sourceCode: 'OTCQX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'PCX', role: 'primary_venue' as const, mic: 'ARCX', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'PINK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'PINL', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'PNK', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'QB', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
{ source: 'qm' as const, sourceCode: 'QX', role: 'primary_venue' as const, mic: 'OTCM', countryIso: 'US' },
|
||||
|
|
@ -364,7 +423,9 @@ export const REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS: readonly ExchangeSourceMap
|
|||
{ source: 'qm' as const, sourceCode: 'TSE', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'TSV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'TSX', role: 'primary_venue' as const, mic: 'XTSE', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'TSXC', role: 'composite' as const, mic: null, countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'TSXV', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'TSXVC', role: 'composite' as const, mic: null, countryIso: 'CA' },
|
||||
{ source: 'qm' as const, sourceCode: 'VNX', role: 'primary_venue' as const, mic: 'XTSX', countryIso: 'CA' },
|
||||
].map(rule => ({
|
||||
...rule,
|
||||
|
|
@ -423,6 +484,12 @@ export function classifySourceExchanges(
|
|||
const knownByMic = new Map<string, ExchangeSeedRow>(
|
||||
knownExchanges.map(exchange => [exchange.mic.trim().toUpperCase(), exchange])
|
||||
);
|
||||
const reviewedByKey = new Map<string, ExchangeSourceMapRow>();
|
||||
if (options.reviewedRows) {
|
||||
for (const row of options.reviewedRows) {
|
||||
reviewedByKey.set(makeRuleKey(row.source, row.sourceCode.trim().toUpperCase()), row);
|
||||
}
|
||||
}
|
||||
|
||||
const grouped = new Map<string, { source: ExchangeSource; sourceCode: string; records: SourceExchangeRecord[] }>();
|
||||
const unresolved: UnresolvedExchangeRecord[] = [];
|
||||
|
|
@ -495,6 +562,20 @@ export function classifySourceExchanges(
|
|||
continue;
|
||||
}
|
||||
|
||||
const reviewedRow = reviewedByKey.get(makeRuleKey(group.source, group.sourceCode));
|
||||
if (reviewedRow) {
|
||||
mapped.push({
|
||||
source: reviewedRow.source,
|
||||
sourceCode: reviewedRow.sourceCode.trim().toUpperCase(),
|
||||
role: reviewedRow.role,
|
||||
mic: reviewedRow.mic,
|
||||
countryIso: reviewedRow.countryIso,
|
||||
method: reviewedRow.method,
|
||||
reviewedBy: reviewedRow.reviewedBy ?? null,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
// Sort group deterministically so duplicate collapse is independent of input order.
|
||||
const sortedRecords = [...group.records].sort(compareSourceRecordsDeterministically);
|
||||
const representative = sortedRecords[0];
|
||||
|
|
|
|||
2040
apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts
Normal file
2040
apps/stock/data-pipeline/src/security-master/export-curate-inputs.ts
Normal file
File diff suppressed because it is too large
Load diff
670
apps/stock/data-pipeline/src/security-master/export-raw-bson.ts
Normal file
670
apps/stock/data-pipeline/src/security-master/export-raw-bson.ts
Normal file
|
|
@ -0,0 +1,670 @@
|
|||
import { createHash, randomUUID } from 'node:crypto';
|
||||
import { mkdir, open, rename, unlink } from 'node:fs/promises';
|
||||
import { join } from 'node:path';
|
||||
import type { MongoDBClient } from '@stock-bot/mongodb';
|
||||
|
||||
/**
|
||||
* M1 allowlisted MongoDB collections whose concatenated raw BSON documents are consumed by
|
||||
* `tools/curate-etl` (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`,
|
||||
* `curate-fx-1d`, `curate-shorts`, `curate-events`).
|
||||
*/
|
||||
export const RAW_BSON_EXPORT_COLLECTIONS = Object.freeze([
|
||||
'eodPrices',
|
||||
'qmSplits',
|
||||
'qmDividends',
|
||||
'qmPrices',
|
||||
'teMarketData',
|
||||
'ceoShorts',
|
||||
'qmFilings',
|
||||
'qmEarnings',
|
||||
] as const);
|
||||
|
||||
export type RawBsonExportCollection = (typeof RAW_BSON_EXPORT_COLLECTIONS)[number];
|
||||
|
||||
const RAW_BSON_EXPORT_COLLECTION_SET: ReadonlySet<string> = new Set(RAW_BSON_EXPORT_COLLECTIONS);
|
||||
|
||||
export const MIN_RAW_BSON_DOC_BYTES = 5;
|
||||
/** Matches `tools/curate-etl` `bson_stream` ceiling (16 MiB BSON max + 16 KiB wire headroom). */
|
||||
export const DEFAULT_MAX_RAW_BSON_DOC_BYTES = 16 * 1024 * 1024 + 16 * 1024;
|
||||
export const DEFAULT_WRITE_BUFFER_BYTES = 8 * 1024 * 1024;
|
||||
export const MIN_WRITE_BUFFER_BYTES = 64;
|
||||
export const MAX_WRITE_BUFFER_BYTES = 64 * 1024 * 1024;
|
||||
export const DEFAULT_RAW_BSON_BATCH_SIZE = 4_096;
|
||||
export const MAX_RAW_BSON_BATCH_SIZE = 100_000;
|
||||
|
||||
export function isRawBsonExportCollection(value: string): value is RawBsonExportCollection {
|
||||
return RAW_BSON_EXPORT_COLLECTION_SET.has(value);
|
||||
}
|
||||
|
||||
export type RawBsonExportErrorCode =
|
||||
| 'DISALLOWED_COLLECTION'
|
||||
| 'INVALID_OPTION'
|
||||
| 'INVALID_SOURCE'
|
||||
| 'INVALID_BSON_FRAME';
|
||||
|
||||
export interface RawBsonExportErrorOptions {
|
||||
readonly code: RawBsonExportErrorCode;
|
||||
readonly collection: string;
|
||||
readonly docOrdinal?: number;
|
||||
readonly detail: string;
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
export class RawBsonExportError extends Error {
|
||||
readonly code: RawBsonExportErrorCode;
|
||||
readonly collection: string;
|
||||
readonly docOrdinal?: number;
|
||||
|
||||
constructor(options: RawBsonExportErrorOptions) {
|
||||
const ordinalPart = options.docOrdinal !== undefined ? ` doc#${options.docOrdinal}` : '';
|
||||
super(
|
||||
`[${options.code}] ${options.collection}${ordinalPart}: ${options.detail}`,
|
||||
options.cause !== undefined ? { cause: options.cause } : undefined
|
||||
);
|
||||
this.name = 'RawBsonExportError';
|
||||
this.code = options.code;
|
||||
this.collection = options.collection;
|
||||
if (options.docOrdinal !== undefined) {
|
||||
this.docOrdinal = options.docOrdinal;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export interface RawBsonFindOptions {
|
||||
readonly raw: true;
|
||||
readonly batchSize?: number;
|
||||
readonly limit?: number;
|
||||
}
|
||||
|
||||
export interface ReadOnlyRawBsonCursor extends AsyncIterable<unknown> {
|
||||
close?(): Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface ReadOnlyRawBsonCollection {
|
||||
find(filter: Record<string, unknown>, options: RawBsonFindOptions): ReadOnlyRawBsonCursor;
|
||||
}
|
||||
|
||||
export interface ReadOnlyMongoRawBsonClient {
|
||||
isReadOnly(): boolean;
|
||||
getCollection(name: string): ReadOnlyRawBsonCollection;
|
||||
}
|
||||
|
||||
export interface ReadOnlyRawBsonSource {
|
||||
isReadOnly(): boolean;
|
||||
find(
|
||||
collectionName: string,
|
||||
filter: Record<string, unknown>,
|
||||
options: RawBsonFindOptions
|
||||
): Promise<AsyncIterable<unknown>> | AsyncIterable<unknown>;
|
||||
}
|
||||
|
||||
// Compile-time structural compatibility check (type-only, erased at runtime):
|
||||
// verifies the real `MongoDBClient` satisfies `ReadOnlyMongoRawBsonClient`.
|
||||
type AssertAssignable<Target, _Candidate extends Target> = true;
|
||||
export type MongoDBClientRawBsonSourceCheck = AssertAssignable<
|
||||
ReadOnlyMongoRawBsonClient,
|
||||
MongoDBClient
|
||||
>;
|
||||
|
||||
export interface ExportRawBsonFileHandle {
|
||||
write(
|
||||
buffer: Uint8Array,
|
||||
offset?: number | null,
|
||||
length?: number | null,
|
||||
position?: number | null
|
||||
): Promise<{ bytesWritten: number }>;
|
||||
sync(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface ExportRawBsonFsHooks {
|
||||
readonly mkdir?: typeof mkdir;
|
||||
readonly open?: (path: string, flags: string) => Promise<ExportRawBsonFileHandle>;
|
||||
readonly rename?: typeof rename;
|
||||
readonly unlink?: typeof unlink;
|
||||
}
|
||||
|
||||
export interface ExportRawBsonCollectionOptions {
|
||||
readonly collection: string;
|
||||
readonly outDir: string;
|
||||
readonly eodSymbol?: string;
|
||||
readonly teSymbol?: string;
|
||||
readonly limit?: number;
|
||||
readonly batchSize?: number;
|
||||
readonly writeBufferBytes?: number;
|
||||
readonly maxDocBytes?: number;
|
||||
readonly fs?: ExportRawBsonFsHooks;
|
||||
}
|
||||
|
||||
export interface ExportRawBsonCollectionResult {
|
||||
readonly collection: RawBsonExportCollection;
|
||||
readonly outPath: string;
|
||||
readonly docsWritten: number;
|
||||
readonly bytesWritten: number;
|
||||
readonly elapsedMs: number;
|
||||
readonly sha256: string;
|
||||
readonly filter: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
function isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {
|
||||
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
return typeof (value as Partial<Record<symbol, unknown>>)[Symbol.asyncIterator] === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* Adapts a read-only `MongoDBClient` into a streaming `ReadOnlyRawBsonSource`.
|
||||
* Rejects non-read-only clients and buffered/non-AsyncIterable cursor results, and
|
||||
* guarantees `cursor.close()` runs in `finally` on completion, early break, or error.
|
||||
*/
|
||||
export function createReadOnlyMongoRawBsonSource(
|
||||
client: ReadOnlyMongoRawBsonClient
|
||||
): ReadOnlyRawBsonSource {
|
||||
if (!client || typeof client.isReadOnly !== 'function' || client.isReadOnly() !== true) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_SOURCE',
|
||||
collection: '*',
|
||||
detail: 'MongoDB client must be configured in read-only mode (isReadOnly() === true)',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
isReadOnly(): boolean {
|
||||
return client.isReadOnly() === true;
|
||||
},
|
||||
find(
|
||||
collectionName: string,
|
||||
filter: Record<string, unknown>,
|
||||
options: RawBsonFindOptions
|
||||
): AsyncIterable<unknown> {
|
||||
if (client.isReadOnly() !== true) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_SOURCE',
|
||||
collection: collectionName,
|
||||
detail: 'MongoDB client must remain in read-only mode (isReadOnly() === true)',
|
||||
});
|
||||
}
|
||||
if (!options || options.raw !== true) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: 'Raw BSON export requires find option { raw: true }',
|
||||
});
|
||||
}
|
||||
|
||||
const cursor = client.getCollection(collectionName).find(filter, options);
|
||||
if (!isAsyncIterable(cursor)) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_SOURCE',
|
||||
collection: collectionName,
|
||||
detail:
|
||||
'Collection find() must return a streaming AsyncIterable cursor (buffered arrays are not allowed)',
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
let hasPrimaryError = false;
|
||||
try {
|
||||
for await (const doc of cursor) {
|
||||
yield doc;
|
||||
}
|
||||
} catch (error) {
|
||||
hasPrimaryError = true;
|
||||
throw error;
|
||||
} finally {
|
||||
if (typeof cursor.close === 'function') {
|
||||
if (hasPrimaryError) {
|
||||
try {
|
||||
await cursor.close();
|
||||
} catch {
|
||||
// Preserve primary iteration error when close also fails.
|
||||
}
|
||||
} else {
|
||||
await cursor.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates that a single raw BSON document frame is a `Uint8Array` of length in
|
||||
* `[5, maxDocBytes]` whose leading signed 32-bit little-endian length prefix equals
|
||||
* `byteLength` and whose final byte is `0x00`.
|
||||
*/
|
||||
export function validateRawBsonFrame(
|
||||
bytes: unknown,
|
||||
collection: string,
|
||||
docOrdinal: number,
|
||||
maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES
|
||||
): Uint8Array {
|
||||
if (!(bytes instanceof Uint8Array)) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `expected Uint8Array raw BSON frame, got ${bytes === null ? 'null' : typeof bytes}`,
|
||||
});
|
||||
}
|
||||
|
||||
const byteLength = bytes.byteLength;
|
||||
if (byteLength < MIN_RAW_BSON_DOC_BYTES) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `frame length ${byteLength} is below minimum BSON document size (${MIN_RAW_BSON_DOC_BYTES})`,
|
||||
});
|
||||
}
|
||||
|
||||
if (byteLength > maxDocBytes) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `frame length ${byteLength} exceeds maxDocBytes (${maxDocBytes})`,
|
||||
});
|
||||
}
|
||||
|
||||
const b0 = bytes[0] ?? 0;
|
||||
const b1 = bytes[1] ?? 0;
|
||||
const b2 = bytes[2] ?? 0;
|
||||
const b3 = bytes[3] ?? 0;
|
||||
const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0;
|
||||
|
||||
if (declaredLen !== byteLength) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `4-byte LE length prefix (${declaredLen}) disagrees with frame byteLength (${byteLength})`,
|
||||
});
|
||||
}
|
||||
|
||||
const lastByte = bytes[byteLength - 1];
|
||||
if (lastByte !== 0x00) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `missing trailing 0x00 terminator (got 0x${(lastByte ?? 0).toString(16).padStart(2, '0')})`,
|
||||
});
|
||||
}
|
||||
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* Walks concatenated length-prefixed raw BSON documents using the exact framing rules
|
||||
* implemented by `tools/curate-etl/src/bson_eod_prices.rs::iter_raw_bson_docs`
|
||||
* (signed 32-bit LE length prefix `>= 5`, `<= maxDocBytes`, exact buffer bounds, trailing `0x00`).
|
||||
*/
|
||||
export function walkRawBsonFrames(
|
||||
bytes: Uint8Array,
|
||||
maxDocBytes: number = DEFAULT_MAX_RAW_BSON_DOC_BYTES,
|
||||
collection: string = '<buffer>'
|
||||
): Uint8Array[] {
|
||||
const frames: Uint8Array[] = [];
|
||||
let offset = 0;
|
||||
let docOrdinal = 0;
|
||||
|
||||
while (offset < bytes.byteLength) {
|
||||
const remaining = bytes.byteLength - offset;
|
||||
if (remaining < 4) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `truncated BSON length prefix at byte offset ${offset} (${remaining} bytes remaining)`,
|
||||
});
|
||||
}
|
||||
|
||||
const b0 = bytes[offset] ?? 0;
|
||||
const b1 = bytes[offset + 1] ?? 0;
|
||||
const b2 = bytes[offset + 2] ?? 0;
|
||||
const b3 = bytes[offset + 3] ?? 0;
|
||||
const declaredLen = (b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)) | 0;
|
||||
|
||||
if (declaredLen < MIN_RAW_BSON_DOC_BYTES) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `corrupt BSON document length ${declaredLen} at byte offset ${offset}`,
|
||||
});
|
||||
}
|
||||
if (declaredLen > maxDocBytes) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `BSON document length ${declaredLen} at byte offset ${offset} exceeds maxDocBytes (${maxDocBytes})`,
|
||||
});
|
||||
}
|
||||
if (declaredLen > remaining) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `truncated BSON document at byte offset ${offset} (declared ${declaredLen}, remaining ${remaining})`,
|
||||
});
|
||||
}
|
||||
|
||||
const frame = bytes.subarray(offset, offset + declaredLen);
|
||||
const lastByte = frame[declaredLen - 1];
|
||||
if (lastByte !== 0x00) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_BSON_FRAME',
|
||||
collection,
|
||||
docOrdinal,
|
||||
detail: `missing trailing 0x00 terminator at byte offset ${offset}`,
|
||||
});
|
||||
}
|
||||
|
||||
frames.push(frame);
|
||||
offset += declaredLen;
|
||||
docOrdinal += 1;
|
||||
}
|
||||
|
||||
return frames;
|
||||
}
|
||||
|
||||
interface ValidatedExportOptions {
|
||||
readonly collection: RawBsonExportCollection;
|
||||
readonly outDir: string;
|
||||
readonly filter: Readonly<Record<string, string>>;
|
||||
readonly limit?: number;
|
||||
readonly batchSize: number;
|
||||
readonly writeBufferBytes: number;
|
||||
readonly maxDocBytes: number;
|
||||
}
|
||||
|
||||
function validateExportOptions(options: ExportRawBsonCollectionOptions): ValidatedExportOptions {
|
||||
const collectionName = typeof options?.collection === 'string' ? options.collection : '';
|
||||
if (!isRawBsonExportCollection(collectionName)) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'DISALLOWED_COLLECTION',
|
||||
collection: collectionName || '<empty>',
|
||||
detail: `collection "${collectionName}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof options.outDir !== 'string' || options.outDir.trim().length === 0) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: 'outDir must be a non-empty string',
|
||||
});
|
||||
}
|
||||
|
||||
const writeBufferBytes = options.writeBufferBytes ?? DEFAULT_WRITE_BUFFER_BYTES;
|
||||
if (
|
||||
!Number.isSafeInteger(writeBufferBytes) ||
|
||||
writeBufferBytes < MIN_WRITE_BUFFER_BYTES ||
|
||||
writeBufferBytes > MAX_WRITE_BUFFER_BYTES
|
||||
) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: `writeBufferBytes must be an integer in [${MIN_WRITE_BUFFER_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(writeBufferBytes)})`,
|
||||
});
|
||||
}
|
||||
|
||||
const maxDocBytes = options.maxDocBytes ?? DEFAULT_MAX_RAW_BSON_DOC_BYTES;
|
||||
if (
|
||||
!Number.isSafeInteger(maxDocBytes) ||
|
||||
maxDocBytes < MIN_RAW_BSON_DOC_BYTES ||
|
||||
maxDocBytes > MAX_WRITE_BUFFER_BYTES
|
||||
) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: `maxDocBytes must be an integer in [${MIN_RAW_BSON_DOC_BYTES}, ${MAX_WRITE_BUFFER_BYTES}] (got ${String(maxDocBytes)})`,
|
||||
});
|
||||
}
|
||||
|
||||
const batchSize = options.batchSize ?? DEFAULT_RAW_BSON_BATCH_SIZE;
|
||||
if (!Number.isSafeInteger(batchSize) || batchSize < 1 || batchSize > MAX_RAW_BSON_BATCH_SIZE) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: `batchSize must be an integer in [1, ${MAX_RAW_BSON_BATCH_SIZE}] (got ${String(batchSize)})`,
|
||||
});
|
||||
}
|
||||
|
||||
let limit: number | undefined;
|
||||
if (options.limit !== undefined) {
|
||||
if (!Number.isSafeInteger(options.limit) || options.limit < 1) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: `limit must be a positive safe integer (got ${String(options.limit)})`,
|
||||
});
|
||||
}
|
||||
limit = options.limit;
|
||||
}
|
||||
|
||||
let filter: Record<string, string> = {};
|
||||
if (options.eodSymbol !== undefined) {
|
||||
if (collectionName !== 'eodPrices') {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: '--eod-symbol filter is only permitted for collection "eodPrices"',
|
||||
});
|
||||
}
|
||||
if (typeof options.eodSymbol !== 'string' || options.eodSymbol.trim().length === 0) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: 'eodSymbol must be a non-empty string',
|
||||
});
|
||||
}
|
||||
filter = { eodSearchCode: options.eodSymbol };
|
||||
}
|
||||
|
||||
if (options.teSymbol !== undefined) {
|
||||
if (collectionName !== 'teMarketData') {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: '--te-symbol filter is only permitted for collection "teMarketData"',
|
||||
});
|
||||
}
|
||||
if (typeof options.teSymbol !== 'string' || options.teSymbol.trim().length === 0) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: collectionName,
|
||||
detail: 'teSymbol must be a non-empty string',
|
||||
});
|
||||
}
|
||||
filter = { teSymbol: options.teSymbol };
|
||||
}
|
||||
|
||||
return {
|
||||
collection: collectionName,
|
||||
outDir: options.outDir.trim(),
|
||||
filter: Object.freeze(filter),
|
||||
...(limit !== undefined ? { limit } : {}),
|
||||
batchSize,
|
||||
writeBufferBytes,
|
||||
maxDocBytes,
|
||||
};
|
||||
}
|
||||
|
||||
async function writeAll(
|
||||
handle: ExportRawBsonFileHandle,
|
||||
buffer: Uint8Array,
|
||||
length: number,
|
||||
collection: string,
|
||||
tempPath: string
|
||||
): Promise<void> {
|
||||
let offset = 0;
|
||||
while (offset < length) {
|
||||
const remaining = length - offset;
|
||||
const result = await handle.write(buffer, offset, remaining);
|
||||
if (
|
||||
!result ||
|
||||
typeof result.bytesWritten !== 'number' ||
|
||||
!Number.isInteger(result.bytesWritten) ||
|
||||
result.bytesWritten <= 0
|
||||
) {
|
||||
throw new Error(
|
||||
`Short write (bytesWritten=${String(result?.bytesWritten)}) while exporting "${collection}" to ${tempPath}`
|
||||
);
|
||||
}
|
||||
if (result.bytesWritten > remaining) {
|
||||
throw new Error(
|
||||
`Write hook reported bytesWritten=${result.bytesWritten} exceeding requested length=${remaining} while exporting "${collection}" to ${tempPath}`
|
||||
);
|
||||
}
|
||||
offset += result.bytesWritten;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Streams an allowlisted MongoDB collection as untouched raw BSON frames into
|
||||
* `<outDir>/<collection>.bson` using a fixed-size write buffer, incremental SHA-256 hashing,
|
||||
* and atomic same-directory temp-file publish (`open('wx')` -> `write` -> `sync` -> `close` -> `rename`).
|
||||
*/
|
||||
export async function exportRawBsonCollection(
|
||||
source: ReadOnlyRawBsonSource,
|
||||
options: ExportRawBsonCollectionOptions
|
||||
): Promise<ExportRawBsonCollectionResult> {
|
||||
const validated = validateExportOptions(options);
|
||||
|
||||
if (
|
||||
!source ||
|
||||
typeof source.isReadOnly !== 'function' ||
|
||||
source.isReadOnly() !== true ||
|
||||
typeof source.find !== 'function'
|
||||
) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_SOURCE',
|
||||
collection: validated.collection,
|
||||
detail: 'Raw BSON exporter requires a read-only source (isReadOnly() === true)',
|
||||
});
|
||||
}
|
||||
|
||||
const mkdirFn = options.fs?.mkdir ?? mkdir;
|
||||
const openFn: (path: string, flags: string) => Promise<ExportRawBsonFileHandle> =
|
||||
options.fs?.open ?? ((filePath: string, flags: string) => open(filePath, flags));
|
||||
const renameFn = options.fs?.rename ?? rename;
|
||||
const unlinkFn = options.fs?.unlink ?? unlink;
|
||||
|
||||
const startMs = performance.now();
|
||||
|
||||
await mkdirFn(validated.outDir, { recursive: true });
|
||||
|
||||
const outPath = join(validated.outDir, `${validated.collection}.bson`);
|
||||
const tempPath = join(
|
||||
validated.outDir,
|
||||
`.${validated.collection}.bson.${process.pid}.${randomUUID()}.tmp`
|
||||
);
|
||||
|
||||
const handle = await openFn(tempPath, 'wx');
|
||||
let handleClosed = false;
|
||||
let renamed = false;
|
||||
|
||||
const writeBuffer = new Uint8Array(validated.writeBufferBytes);
|
||||
let buffered = 0;
|
||||
const hash = createHash('sha256');
|
||||
let docsWritten = 0;
|
||||
let bytesWritten = 0;
|
||||
|
||||
const flushBuffer = async (): Promise<void> => {
|
||||
if (buffered > 0) {
|
||||
await writeAll(handle, writeBuffer, buffered, validated.collection, tempPath);
|
||||
buffered = 0;
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
const findOptions: RawBsonFindOptions = {
|
||||
raw: true,
|
||||
batchSize: validated.batchSize,
|
||||
...(validated.limit !== undefined ? { limit: validated.limit } : {}),
|
||||
};
|
||||
|
||||
const iterable = await source.find(
|
||||
validated.collection,
|
||||
{ ...validated.filter },
|
||||
findOptions
|
||||
);
|
||||
|
||||
if (!isAsyncIterable(iterable)) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_SOURCE',
|
||||
collection: validated.collection,
|
||||
detail:
|
||||
'Source find() must return a streaming AsyncIterable (buffered arrays are not allowed)',
|
||||
});
|
||||
}
|
||||
|
||||
for await (const rawDoc of iterable) {
|
||||
if (validated.limit !== undefined && docsWritten >= validated.limit) {
|
||||
break;
|
||||
}
|
||||
|
||||
const frame = validateRawBsonFrame(
|
||||
rawDoc,
|
||||
validated.collection,
|
||||
docsWritten,
|
||||
validated.maxDocBytes
|
||||
);
|
||||
const frameLen = frame.byteLength;
|
||||
hash.update(frame);
|
||||
|
||||
if (frameLen > validated.writeBufferBytes) {
|
||||
await flushBuffer();
|
||||
await writeAll(handle, frame, frameLen, validated.collection, tempPath);
|
||||
} else {
|
||||
if (buffered + frameLen > validated.writeBufferBytes) {
|
||||
await flushBuffer();
|
||||
}
|
||||
writeBuffer.set(frame, buffered);
|
||||
buffered += frameLen;
|
||||
}
|
||||
|
||||
docsWritten += 1;
|
||||
bytesWritten += frameLen;
|
||||
|
||||
if (validated.limit !== undefined && docsWritten >= validated.limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
await flushBuffer();
|
||||
await handle.sync();
|
||||
await handle.close();
|
||||
handleClosed = true;
|
||||
|
||||
await renameFn(tempPath, outPath);
|
||||
renamed = true;
|
||||
} catch (error) {
|
||||
if (!handleClosed) {
|
||||
await handle.close().catch(() => {});
|
||||
}
|
||||
if (!renamed) {
|
||||
await unlinkFn(tempPath).catch(() => {});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
const elapsedMs = Math.max(0, performance.now() - startMs);
|
||||
|
||||
return {
|
||||
collection: validated.collection,
|
||||
outPath,
|
||||
docsWritten,
|
||||
bytesWritten,
|
||||
elapsedMs,
|
||||
sha256: hash.digest('hex'),
|
||||
filter: validated.filter,
|
||||
};
|
||||
}
|
||||
|
|
@ -47,6 +47,100 @@ export {
|
|||
type UnresolvedExchangeRecord,
|
||||
} from './exchange-pass1';
|
||||
|
||||
export {
|
||||
buildDelistingExportRows,
|
||||
CURATE_INPUT_CURRENT_LINK,
|
||||
CURATE_INPUT_FILES,
|
||||
CURATE_INPUT_GENERATIONS_DIR,
|
||||
CURATE_INPUT_PUBLISH_LOCK,
|
||||
CurateInputExportError,
|
||||
DEFAULT_DELISTING_MAPPING_SOURCE,
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
DEFAULT_PUBLISH_LOCK_TIMEOUT_MS,
|
||||
exportCurateInputs,
|
||||
formatDelistingsTsv,
|
||||
formatListingCurrenciesTsv,
|
||||
formatPlainDecimal,
|
||||
formatProviderMappingTsv,
|
||||
isValidStrictYmd,
|
||||
MAX_EXPORT_CHUNK_SIZE,
|
||||
pinCurateInputSnapshot,
|
||||
type BuildDelistingExportRowsOptions,
|
||||
type BuildDelistingExportRowsResult,
|
||||
type ContinuityExportSourceRow,
|
||||
type CurateInputExportErrorCode,
|
||||
type CurateInputExportErrorOptions,
|
||||
type DelistingExportRow,
|
||||
type DelistingExportSkippedByReason,
|
||||
type DelistingExportStats,
|
||||
type ExportCurateInputsFileStats,
|
||||
type ExportCurateInputsFsHooks,
|
||||
type ExportCurateInputsOptions,
|
||||
type ExportCurateInputsResult,
|
||||
type ListingCurrencyExportRow,
|
||||
type ListingDelistingSourceRow,
|
||||
type PinnedCurateInputSnapshot,
|
||||
type ProviderMappingExportRow,
|
||||
} from './export-curate-inputs';
|
||||
|
||||
export {
|
||||
assertExportCurateInputsSafety,
|
||||
EXPORT_CURATE_INPUTS_USAGE,
|
||||
formatExportCurateInputsSummary,
|
||||
parseExportCurateInputsArgs,
|
||||
runCli as runExportCurateInputsCli,
|
||||
runExportCurateInputs,
|
||||
type ParsedExportCurateInputsArgs,
|
||||
type RunExportCurateInputsDeps,
|
||||
type RunExportCurateInputsOptions,
|
||||
type RunExportCurateInputsOutput,
|
||||
} from './run-export-curate-inputs';
|
||||
|
||||
export {
|
||||
createReadOnlyMongoRawBsonSource,
|
||||
DEFAULT_MAX_RAW_BSON_DOC_BYTES,
|
||||
DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
DEFAULT_WRITE_BUFFER_BYTES,
|
||||
exportRawBsonCollection,
|
||||
isRawBsonExportCollection,
|
||||
MAX_RAW_BSON_BATCH_SIZE,
|
||||
MAX_WRITE_BUFFER_BYTES,
|
||||
MIN_RAW_BSON_DOC_BYTES,
|
||||
MIN_WRITE_BUFFER_BYTES,
|
||||
RAW_BSON_EXPORT_COLLECTIONS,
|
||||
RawBsonExportError,
|
||||
validateRawBsonFrame,
|
||||
walkRawBsonFrames,
|
||||
type ExportRawBsonCollectionOptions,
|
||||
type ExportRawBsonCollectionResult,
|
||||
type ExportRawBsonFileHandle,
|
||||
type ExportRawBsonFsHooks,
|
||||
type MongoDBClientRawBsonSourceCheck,
|
||||
type RawBsonExportCollection,
|
||||
type RawBsonExportErrorCode,
|
||||
type RawBsonExportErrorOptions,
|
||||
type RawBsonFindOptions,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
type ReadOnlyRawBsonCollection,
|
||||
type ReadOnlyRawBsonCursor,
|
||||
type ReadOnlyRawBsonSource,
|
||||
} from './export-raw-bson';
|
||||
|
||||
export {
|
||||
assertExportRawBsonSafety,
|
||||
EXPORT_RAW_BSON_USAGE,
|
||||
formatExportRawBsonSummary,
|
||||
parseExportRawBsonArgs,
|
||||
runCli as runExportRawBsonCli,
|
||||
runExportRawBson,
|
||||
type ParsedExportRawBsonArgs,
|
||||
type RawBsonMongoHandle,
|
||||
type RunExportRawBsonCliOverrides,
|
||||
type RunExportRawBsonDeps,
|
||||
type RunExportRawBsonOptions,
|
||||
type RunExportRawBsonOutput,
|
||||
} from './run-export-raw-bson';
|
||||
|
||||
export {
|
||||
escapeSqlLiteral,
|
||||
generateExchangeSeedSql,
|
||||
|
|
@ -265,6 +359,47 @@ export {
|
|||
type UnknownSecurityTypeCount,
|
||||
} from './security-type';
|
||||
|
||||
export {
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
PROBE_SOURCE_FIELD_SHAPES_USAGE,
|
||||
runCli as runProbeSourceFieldShapesCli,
|
||||
runSourceFieldShapesProbe,
|
||||
type ParsedProbeSourceFieldShapesArgs,
|
||||
type RunSourceFieldShapesProbeDeps,
|
||||
type RunSourceFieldShapesProbeOptions,
|
||||
type RunSourceFieldShapesProbeOutput,
|
||||
} from './probe-source-field-shapes';
|
||||
|
||||
export {
|
||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
DEFAULT_MAX_EXAMPLE_LENGTH,
|
||||
DEFAULT_MAX_EXAMPLES,
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
FIELD_VALUE_TYPES,
|
||||
isFieldShapeProbeCollection,
|
||||
MAX_EXAMPLE_LENGTH_CAP,
|
||||
MAX_EXAMPLES_CAP,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
normalizeProbeCollections,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
STRING_PATTERN_CLASSES,
|
||||
summarizeFieldShapes,
|
||||
UnknownProbeCollectionError,
|
||||
type CollectionFieldShapesProbeResult,
|
||||
type CollectionFieldShapesSummary,
|
||||
type FieldShapeProbeCollection,
|
||||
type FieldShapeSummary,
|
||||
type FieldStringStats,
|
||||
type FieldValueType,
|
||||
type FieldValueTypeCounts,
|
||||
type ReadFieldShapesOptions,
|
||||
type ReadFieldShapesResult,
|
||||
type StringPatternClass,
|
||||
type StringPatternCounts,
|
||||
type SummarizeFieldShapesOptions,
|
||||
} from './source-field-shapes';
|
||||
|
||||
export {
|
||||
adaptCeoSymbolDoc,
|
||||
adaptEodSymbolChangeDoc,
|
||||
|
|
|
|||
|
|
@ -9,9 +9,15 @@ import { compareAscii } from './exchange-pass1';
|
|||
|
||||
export const STAGE_A_SOURCES = ['ib', 'eod'] as const;
|
||||
|
||||
export const SYNTHETIC_EOD_ISIN_PREFIX = 'SYN:EOD:' as const;
|
||||
|
||||
export function isSyntheticInstrumentKey(value: string): boolean {
|
||||
return value.startsWith(SYNTHETIC_EOD_ISIN_PREFIX);
|
||||
}
|
||||
|
||||
export type StageASource = (typeof STAGE_A_SOURCES)[number];
|
||||
|
||||
export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip';
|
||||
export type StageAMatchMethod = 'tier1_isin' | 'tier2_cusip' | 'tier3_ticker_span';
|
||||
|
||||
export type StageAConflictKind = 'isin_cusip_mismatch' | 'duplicate_source_id';
|
||||
|
||||
|
|
@ -64,6 +70,7 @@ export interface StageASourceStats {
|
|||
total: number;
|
||||
tier1Isin: number;
|
||||
tier2Cusip: number;
|
||||
tier3Synthetic?: number;
|
||||
unresolved: number;
|
||||
conflict: number;
|
||||
}
|
||||
|
|
@ -76,6 +83,7 @@ export interface StageAStats {
|
|||
|
||||
export interface MatchInstrumentsStageAOptions {
|
||||
readonly nameSourcePrecedence?: readonly StageASource[];
|
||||
readonly allowIdentifierlessEod?: boolean;
|
||||
}
|
||||
|
||||
export interface StageAMatchResult {
|
||||
|
|
@ -93,6 +101,7 @@ interface BestSourceName {
|
|||
interface InstrumentAccumulator {
|
||||
members: StageAInstrumentMember[];
|
||||
bestNameBySource: Record<StageASource, BestSourceName | null>;
|
||||
fallbackCountry: string | null;
|
||||
}
|
||||
|
||||
export function isStageASource(value: unknown): value is StageASource {
|
||||
|
|
@ -230,6 +239,45 @@ export function matchInstrumentsStageA(
|
|||
|
||||
const resolved = resolveIsin(record);
|
||||
if (resolved.isin === null) {
|
||||
if (options.allowIdentifierlessEod === true && source === 'eod') {
|
||||
const syntheticKey = `${SYNTHETIC_EOD_ISIN_PREFIX}${sourceId.trim().toUpperCase()}`;
|
||||
const normalizedCountry = normalizeCode(record.country);
|
||||
const fallbackCountry =
|
||||
normalizedCountry !== null && /^[A-Z]{2}$/.test(normalizedCountry)
|
||||
? normalizedCountry
|
||||
: sourceId.endsWith('.TO') ||
|
||||
sourceId.endsWith('.V') ||
|
||||
sourceId.endsWith('.NEO') ||
|
||||
sourceId.endsWith('.CN')
|
||||
? 'CA'
|
||||
: 'US';
|
||||
const currency = normalizeCode(record.currency);
|
||||
const name = normalizeName(record.name);
|
||||
let acc = instrumentsByIsin.get(syntheticKey);
|
||||
if (acc === undefined) {
|
||||
acc = {
|
||||
members: [],
|
||||
bestNameBySource: { ib: null, eod: null },
|
||||
fallbackCountry,
|
||||
};
|
||||
instrumentsByIsin.set(syntheticKey, acc);
|
||||
}
|
||||
acc.members.push({
|
||||
source,
|
||||
sourceId,
|
||||
currency,
|
||||
method: 'tier3_ticker_span',
|
||||
});
|
||||
if (name !== null) {
|
||||
const existingBest = acc.bestNameBySource[source];
|
||||
if (existingBest === null || compareAscii(sourceId, existingBest.sourceId) < 0) {
|
||||
acc.bestNameBySource[source] = { sourceId, name };
|
||||
}
|
||||
}
|
||||
sourceStats.tier3Synthetic = (sourceStats.tier3Synthetic ?? 0) + 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
unresolved.push({
|
||||
source,
|
||||
sourceId,
|
||||
|
|
@ -286,6 +334,7 @@ export function matchInstrumentsStageA(
|
|||
ib: null,
|
||||
eod: null,
|
||||
},
|
||||
fallbackCountry: null,
|
||||
};
|
||||
instrumentsByIsin.set(resolved.isin, acc);
|
||||
}
|
||||
|
|
@ -313,10 +362,13 @@ export function matchInstrumentsStageA(
|
|||
|
||||
const instruments: StageAInstrumentCandidate[] = [];
|
||||
for (const [primaryIsin, acc] of instrumentsByIsin.entries()) {
|
||||
const issuerCountry = primaryIsin.slice(0, 2);
|
||||
const embeddedCusip = primaryIsin.slice(2, 11);
|
||||
const isSynthetic = isSyntheticInstrumentKey(primaryIsin);
|
||||
const issuerCountry = isSynthetic ? (acc.fallbackCountry ?? 'US') : primaryIsin.slice(0, 2);
|
||||
const embeddedCusip = isSynthetic ? '' : primaryIsin.slice(2, 11);
|
||||
const primaryCusip =
|
||||
isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip) ? embeddedCusip : null;
|
||||
!isSynthetic && isNorthAmericaCountry(issuerCountry) && isValidCusip(embeddedCusip)
|
||||
? embeddedCusip
|
||||
: null;
|
||||
|
||||
let canonicalName: string | null = null;
|
||||
for (const source of nameSourcePrecedence) {
|
||||
|
|
|
|||
|
|
@ -6,10 +6,11 @@ import {
|
|||
} from '../normalization/bar-spans';
|
||||
import { parseTickerDetailed } from '../normalization/ticker';
|
||||
import { compareAscii, type ExchangeRole } from './exchange-pass1';
|
||||
import type {
|
||||
StageAInstrumentCandidate,
|
||||
StageAMatchMethod,
|
||||
StageASource,
|
||||
import {
|
||||
isSyntheticInstrumentKey,
|
||||
type StageAInstrumentCandidate,
|
||||
type StageAMatchMethod,
|
||||
type StageASource,
|
||||
} from './instrument-stage-a';
|
||||
|
||||
export const MAX_TICKER_ROOT_LENGTH = 24;
|
||||
|
|
@ -44,6 +45,9 @@ export interface StageBIbContractInput {
|
|||
conid: number;
|
||||
currency?: string | null;
|
||||
primaryExchange: string | null;
|
||||
ticker?: string | null;
|
||||
name?: string | null;
|
||||
exchangeId?: string | null;
|
||||
}
|
||||
|
||||
export interface StageBTickerSourceInput {
|
||||
|
|
@ -54,6 +58,7 @@ export interface StageBTickerSourceInput {
|
|||
role: ExchangeRole | null;
|
||||
currency?: string | null;
|
||||
span: SpanDateRange | null;
|
||||
name?: string | null;
|
||||
}
|
||||
|
||||
export interface StageBSymbolChangeInput {
|
||||
|
|
@ -77,6 +82,8 @@ export interface StageBInput {
|
|||
|
||||
export interface MatchListingsStageBOptions {
|
||||
readonly spanOverlapToleranceDays?: number;
|
||||
readonly enableIbTickerDisambiguation?: boolean;
|
||||
readonly allowUniqueTickerFallbackForCrawlOnlyCeo?: boolean;
|
||||
}
|
||||
|
||||
export interface StageBListingCandidate extends ListingNaturalKey {
|
||||
|
|
@ -201,7 +208,7 @@ interface StagedIbCandidate {
|
|||
currency: string;
|
||||
conid: number;
|
||||
primaryExchange: string | null;
|
||||
method: StageAMatchMethod;
|
||||
method: StageBMatchMethod;
|
||||
}
|
||||
|
||||
const ISO_MIC_PATTERN = /^[A-Z0-9]{4}$/;
|
||||
|
|
@ -216,8 +223,15 @@ function isStageASourceValue(value: unknown): value is StageASource {
|
|||
return value === 'ib' || value === 'eod';
|
||||
}
|
||||
|
||||
function isStageAMatchMethodValue(value: unknown): value is StageAMatchMethod {
|
||||
return value === 'tier1_isin' || value === 'tier2_cusip';
|
||||
function isStageAMatchMethodValue(
|
||||
value: unknown,
|
||||
allowSyntheticTier3 = false
|
||||
): value is StageAMatchMethod {
|
||||
return (
|
||||
value === 'tier1_isin' ||
|
||||
value === 'tier2_cusip' ||
|
||||
(allowSyntheticTier3 && value === 'tier3_ticker_span')
|
||||
);
|
||||
}
|
||||
|
||||
function isStageBTickerSourceValue(value: unknown): value is StageBTickerSource {
|
||||
|
|
@ -658,7 +672,8 @@ export function matchListingsStageB(
|
|||
`Invalid empty or non-string sourceId at instruments[${i}].members[${j}]`
|
||||
);
|
||||
}
|
||||
if (!isStageAMatchMethodValue(member.method)) {
|
||||
const isSyntheticInst = isSyntheticInstrumentKey(inst.primaryIsin);
|
||||
if (!isStageAMatchMethodValue(member.method, isSyntheticInst)) {
|
||||
throw new Error(
|
||||
`Unknown Stage A member method "${String(member.method)}" at instruments[${i}].members[${j}]`
|
||||
);
|
||||
|
|
@ -865,7 +880,11 @@ export function matchListingsStageB(
|
|||
const listingsByNaturalKey = new Map<string, ListingAccumulator>();
|
||||
const listingsByInstrumentCurrency = new Map<string, Map<string, ListingAccumulator[]>>();
|
||||
const listingsByTickerKey = new Map<string, TickerLookupCandidate[]>();
|
||||
const listingsByCurrencyTickerKey = new Map<string, ListingAccumulator[]>();
|
||||
const listingByEodSourceId = new Map<string, ListingAccumulator>();
|
||||
const enableIbTickerDisambiguation = options.enableIbTickerDisambiguation === true;
|
||||
const allowUniqueTickerFallbackForCrawlOnlyCeo =
|
||||
options.allowUniqueTickerFallbackForCrawlOnlyCeo === true;
|
||||
|
||||
const providerMappings: StageBProviderMappingCandidate[] = [];
|
||||
const unresolved: StageBUnresolvedRecord[] = [];
|
||||
|
|
@ -1006,6 +1025,14 @@ export function matchListingsStageB(
|
|||
listingsByTickerKey.set(tickerKey, tickerList);
|
||||
}
|
||||
tickerList.push({ acc, aliasBounds: null });
|
||||
|
||||
const currTickerKey = `${currency}\u0000${ticker.tickerRoot}\u0000${ticker.classSuffix}`;
|
||||
let currTickerList = listingsByCurrencyTickerKey.get(currTickerKey);
|
||||
if (currTickerList === undefined) {
|
||||
currTickerList = [];
|
||||
listingsByCurrencyTickerKey.set(currTickerKey, currTickerList);
|
||||
}
|
||||
currTickerList.push(acc);
|
||||
} else if (validSpan !== null) {
|
||||
// Associative & commutative min/max widening ensures shuffle invariance.
|
||||
if (acc.listedFrom === null || validSpan.firstBarDate < acc.listedFrom) {
|
||||
|
|
@ -1143,7 +1170,84 @@ export function matchListingsStageB(
|
|||
}
|
||||
|
||||
const primaryExchange = normalizeOptionalExchangeLabel(contract.primaryExchange);
|
||||
const candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency);
|
||||
let candidates = listingsByInstrumentCurrency.get(inst.primaryIsin)?.get(currency);
|
||||
let matchMethod: StageBMatchMethod = member.method;
|
||||
|
||||
const isActiveCandidate = (acc: ListingAccumulator): boolean =>
|
||||
acc.listedTo === null || acc.listedTo >= '2025-01-01';
|
||||
|
||||
const narrowIbCandidates = (
|
||||
pool: readonly ListingAccumulator[],
|
||||
parsedTicker: { readonly tickerRoot: string; readonly classSuffix: string } | null
|
||||
): ListingAccumulator[] => {
|
||||
let current = [...pool];
|
||||
if (current.length > 1 && parsedTicker !== null) {
|
||||
const exactTicker = current.filter(
|
||||
acc =>
|
||||
acc.key.tickerRoot === parsedTicker.tickerRoot &&
|
||||
acc.key.classSuffix === parsedTicker.classSuffix
|
||||
);
|
||||
if (exactTicker.length > 0) {
|
||||
current = exactTicker;
|
||||
}
|
||||
}
|
||||
if (current.length > 1) {
|
||||
const activeOnly = current.filter(isActiveCandidate);
|
||||
if (activeOnly.length > 0) {
|
||||
current = activeOnly;
|
||||
}
|
||||
}
|
||||
if (current.length > 1) {
|
||||
const primaryOnly = current.filter(acc => acc.key.mic !== 'OTCM');
|
||||
if (primaryOnly.length > 0) {
|
||||
current = primaryOnly;
|
||||
}
|
||||
}
|
||||
return current;
|
||||
};
|
||||
|
||||
const parsedIbTicker =
|
||||
enableIbTickerDisambiguation && typeof contract.ticker === 'string'
|
||||
? (() => {
|
||||
const parsed = classifyTicker(contract.ticker, 'ib');
|
||||
return parsed.ok
|
||||
? { tickerRoot: parsed.tickerRoot, classSuffix: parsed.classSuffix }
|
||||
: null;
|
||||
})()
|
||||
: null;
|
||||
|
||||
if (enableIbTickerDisambiguation && candidates !== undefined && candidates.length > 1) {
|
||||
candidates = narrowIbCandidates(candidates, parsedIbTicker);
|
||||
}
|
||||
|
||||
if (
|
||||
enableIbTickerDisambiguation &&
|
||||
(candidates === undefined || candidates.length === 0) &&
|
||||
parsedIbTicker !== null
|
||||
) {
|
||||
const currTickerKey = `${currency}\u0000${parsedIbTicker.tickerRoot}\u0000${parsedIbTicker.classSuffix}`;
|
||||
const tickerPool = listingsByCurrencyTickerKey.get(currTickerKey);
|
||||
if (tickerPool !== undefined && tickerPool.length > 0) {
|
||||
const ibIssuerPrefix = !isSyntheticInstrumentKey(inst.primaryIsin)
|
||||
? inst.primaryIsin.slice(0, 8)
|
||||
: null;
|
||||
const eligibleFallback = tickerPool.filter(
|
||||
acc =>
|
||||
isSyntheticInstrumentKey(acc.key.primaryIsin) ||
|
||||
(ibIssuerPrefix !== null &&
|
||||
!isSyntheticInstrumentKey(acc.key.primaryIsin) &&
|
||||
acc.key.primaryIsin.slice(0, 8) === ibIssuerPrefix) ||
|
||||
isActiveCandidate(acc)
|
||||
);
|
||||
if (eligibleFallback.length > 0) {
|
||||
const narrowed = narrowIbCandidates(eligibleFallback, parsedIbTicker);
|
||||
if (narrowed.length === 1) {
|
||||
candidates = narrowed;
|
||||
matchMethod = 'tier3_ticker_span';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (candidates === undefined || candidates.length === 0) {
|
||||
unresolved.push({
|
||||
|
|
@ -1190,7 +1294,7 @@ export function matchListingsStageB(
|
|||
currency,
|
||||
conid: contract.conid,
|
||||
primaryExchange,
|
||||
method: member.method,
|
||||
method: matchMethod,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
|
@ -1483,6 +1587,29 @@ export function matchListingsStageB(
|
|||
primaryIsin: null,
|
||||
});
|
||||
sourceStats.unresolved += 1;
|
||||
} else if (
|
||||
allowUniqueTickerFallbackForCrawlOnlyCeo &&
|
||||
source === 'ceo' &&
|
||||
spanCheck.span.firstBarDate === spanCheck.span.lastBarDate &&
|
||||
candidates.length === 1 &&
|
||||
candidates[0] !== undefined &&
|
||||
candidates[0].aliasBounds === null &&
|
||||
candidates[0].acc.listedFrom !== null &&
|
||||
candidates[0].acc.listedTo !== null
|
||||
) {
|
||||
// CEO symbols without ceoShorts history carry only a single-day crawl `lastSeen` date;
|
||||
// when there is a single unique EOD listing for `(mic, currency, ticker)` with zero ticker
|
||||
// reuse, attach cleanly using that listing's observed span.
|
||||
const uniqueListing = candidates[0].acc;
|
||||
providerMappings.push({
|
||||
source,
|
||||
sourceId: record.sourceId,
|
||||
listingKey: uniqueListing.key,
|
||||
method: 'tier3_ticker_span',
|
||||
validFrom: uniqueListing.listedFrom,
|
||||
validTo: uniqueListing.listedTo,
|
||||
});
|
||||
sourceStats.matched += 1;
|
||||
} else {
|
||||
unresolved.push({
|
||||
source,
|
||||
|
|
|
|||
|
|
@ -36,6 +36,13 @@ export type ExcludedByDesignStageBReason = (typeof EXCLUDED_BY_DESIGN_STAGE_B_RE
|
|||
|
||||
export type SourceCountryLookup = ReadonlyMap<string, string> | Readonly<Record<string, string>>;
|
||||
|
||||
export type GateOutOfScopeReason =
|
||||
| 'zero_bar_catalog_ghost'
|
||||
| 'uncovered_venue'
|
||||
| 'non_equity_instrument';
|
||||
|
||||
export type GateOutOfScopeLookup = ReadonlyMap<string, GateOutOfScopeReason>;
|
||||
|
||||
export interface MatchReportInput {
|
||||
readonly exchanges?: ExchangeClassificationResult;
|
||||
readonly stageA: StageAMatchResult;
|
||||
|
|
@ -43,10 +50,13 @@ export interface MatchReportInput {
|
|||
readonly priceCrossCheck?: PriceCrossCheckResult;
|
||||
readonly delistingChains?: DelistingChainResult;
|
||||
readonly sourceCountries?: SourceCountryLookup;
|
||||
readonly gateOutOfScope?: GateOutOfScopeLookup;
|
||||
readonly gateDenominatorNote?: string;
|
||||
}
|
||||
|
||||
export interface BuildMatchReportOptions {
|
||||
readonly minResolvedPct?: number;
|
||||
readonly applyUsCaEquityGateDenominator?: boolean;
|
||||
}
|
||||
|
||||
export interface ExchangeCoverageSummary {
|
||||
|
|
@ -73,6 +83,7 @@ export interface SourceResolutionSummary {
|
|||
unresolved: number;
|
||||
conflict: number;
|
||||
excludedByDesign: number;
|
||||
outOfGateScope?: number;
|
||||
eligibleTotal: number;
|
||||
resolvedPct: number | null;
|
||||
eligibleResolvedPct: number | null;
|
||||
|
|
@ -141,6 +152,8 @@ export interface MatchReport {
|
|||
resolutionBySource: SourceResolutionSummary[];
|
||||
resolutionByCountry: CountryResolutionSummary[];
|
||||
unresolvedByReason: UnresolvedBreakdown;
|
||||
outOfGateScopeByReason?: UnresolvedBreakdownRow[];
|
||||
gateDenominatorNote?: string;
|
||||
conflicts: UnifiedConflictRow[];
|
||||
conflictsByPassKind: ConflictCountRow[];
|
||||
priceCrossCheck: PriceCrossCheckSummary | null;
|
||||
|
|
@ -504,16 +517,62 @@ export function buildMatchReport(
|
|||
qm: 0,
|
||||
ceo: 0,
|
||||
};
|
||||
const outOfGateScopeBySource: Record<StageBSource, number> = {
|
||||
eod: 0,
|
||||
ib: 0,
|
||||
qm: 0,
|
||||
ceo: 0,
|
||||
};
|
||||
const outOfGateScopeCounts = new Map<string, number>();
|
||||
const hasGateOutOfScope = input.gateOutOfScope !== undefined && input.gateOutOfScope.size > 0;
|
||||
|
||||
for (const record of input.stageB.unresolved) {
|
||||
if (EXCLUDED_BY_DESIGN_SET.has(record.reason)) {
|
||||
excludedBySource[record.source] += 1;
|
||||
} else if (hasGateOutOfScope) {
|
||||
const gateReason = input.gateOutOfScope?.get(sourceCountryKey(record.source, record.sourceId));
|
||||
if (gateReason !== undefined) {
|
||||
outOfGateScopeBySource[record.source] += 1;
|
||||
const k = `${record.source}\u0000${gateReason}`;
|
||||
outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (hasGateOutOfScope) {
|
||||
const countedConflictKeys = new Set<string>();
|
||||
for (const conflict of input.stageB.conflicts) {
|
||||
const key = sourceCountryKey(conflict.source, conflict.sourceId);
|
||||
if (countedConflictKeys.has(key)) {
|
||||
continue;
|
||||
}
|
||||
countedConflictKeys.add(key);
|
||||
const gateReason = input.gateOutOfScope?.get(key);
|
||||
if (gateReason !== undefined) {
|
||||
outOfGateScopeBySource[conflict.source] += 1;
|
||||
const k = `${conflict.source}\u0000${gateReason}`;
|
||||
outOfGateScopeCounts.set(k, (outOfGateScopeCounts.get(k) ?? 0) + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const outOfGateScopeByReason: UnresolvedBreakdownRow[] = Array.from(
|
||||
outOfGateScopeCounts.entries()
|
||||
)
|
||||
.map(([key, count]) => {
|
||||
const sep = key.indexOf('\u0000');
|
||||
return {
|
||||
source: key.slice(0, sep),
|
||||
reason: key.slice(sep + 1),
|
||||
count,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => compareAscii(a.source, b.source) || compareAscii(a.reason, b.reason));
|
||||
|
||||
const resolutionBySource: SourceResolutionSummary[] = STAGE_B_SOURCES.map(source => {
|
||||
const stats = input.stageB.stats.bySource[source];
|
||||
const excludedByDesign = excludedBySource[source];
|
||||
const eligibleTotal = Math.max(0, stats.total - excludedByDesign);
|
||||
const outOfGateScope = outOfGateScopeBySource[source];
|
||||
const eligibleTotal = Math.max(0, stats.total - excludedByDesign - outOfGateScope);
|
||||
return {
|
||||
source,
|
||||
total: stats.total,
|
||||
|
|
@ -521,6 +580,7 @@ export function buildMatchReport(
|
|||
unresolved: stats.unresolved,
|
||||
conflict: stats.conflict,
|
||||
excludedByDesign,
|
||||
...(hasGateOutOfScope ? { outOfGateScope } : {}),
|
||||
eligibleTotal,
|
||||
resolvedPct: stats.total > 0 ? stats.matched / stats.total : null,
|
||||
eligibleResolvedPct: eligibleTotal > 0 ? stats.matched / eligibleTotal : null,
|
||||
|
|
@ -615,6 +675,10 @@ export function buildMatchReport(
|
|||
resolutionBySource,
|
||||
resolutionByCountry,
|
||||
unresolvedByReason,
|
||||
...(hasGateOutOfScope ? { outOfGateScopeByReason } : {}),
|
||||
...(input.gateDenominatorNote !== undefined
|
||||
? { gateDenominatorNote: input.gateDenominatorNote }
|
||||
: {}),
|
||||
conflicts,
|
||||
conflictsByPassKind,
|
||||
priceCrossCheck,
|
||||
|
|
@ -669,18 +733,48 @@ export function renderMatchReportMarkdown(
|
|||
lines.push('| 0 | 0 | 0 | N/A |');
|
||||
}
|
||||
|
||||
if (report.gateDenominatorNote !== undefined && report.gateDenominatorNote.trim().length > 0) {
|
||||
lines.push('', '## Gate Denominator Definition', '', report.gateDenominatorNote);
|
||||
}
|
||||
|
||||
const showGateScopeColumn = report.outOfGateScopeByReason !== undefined;
|
||||
lines.push(
|
||||
'',
|
||||
'## Per-Source Resolution',
|
||||
'',
|
||||
'| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |',
|
||||
'| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
|
||||
showGateScopeColumn
|
||||
? '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |'
|
||||
: '| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |',
|
||||
showGateScopeColumn
|
||||
? '| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |'
|
||||
: '| --- | --- | --- | --- | --- | --- | --- | --- | --- |'
|
||||
);
|
||||
|
||||
for (const row of report.resolutionBySource) {
|
||||
if (showGateScopeColumn) {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.outOfGateScope ?? 0} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
|
||||
);
|
||||
} else {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (report.outOfGateScopeByReason !== undefined && report.outOfGateScopeByReason.length > 0) {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${row.total} | ${row.matched} | ${row.unresolved} | ${row.conflict} | ${row.excludedByDesign} | ${row.eligibleTotal} | ${formatPct(row.resolvedPct)} | ${formatPct(row.eligibleResolvedPct)} |`
|
||||
'',
|
||||
'## Out-of-Gate-Scope Breakdown',
|
||||
'',
|
||||
'| Source | Reason | Count |',
|
||||
'| --- | --- | --- |'
|
||||
);
|
||||
for (const row of report.outOfGateScopeByReason) {
|
||||
lines.push(
|
||||
`| ${escapeMarkdownCell(row.source)} | ${escapeMarkdownCell(row.reason)} | ${row.count} |`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (report.resolutionByCountry.length > 0) {
|
||||
|
|
|
|||
|
|
@ -16,11 +16,13 @@ import type {
|
|||
Pass6DelistReason,
|
||||
} from './delisting-chains';
|
||||
import { compareAscii } from './exchange-pass1';
|
||||
import type {
|
||||
StageAInstrumentCandidate,
|
||||
StageAInstrumentMember,
|
||||
StageAMatchResult,
|
||||
StageASource,
|
||||
import {
|
||||
isSyntheticInstrumentKey,
|
||||
SYNTHETIC_EOD_ISIN_PREFIX,
|
||||
type StageAInstrumentCandidate,
|
||||
type StageAInstrumentMember,
|
||||
type StageAMatchResult,
|
||||
type StageASource,
|
||||
} from './instrument-stage-a';
|
||||
import type {
|
||||
ListingNaturalKey,
|
||||
|
|
@ -243,6 +245,8 @@ interface ExistingPass4ConflictRow {
|
|||
|
||||
interface PreparedInstrument {
|
||||
readonly primaryIsin: string;
|
||||
readonly isSynthetic: boolean;
|
||||
readonly syntheticSourceId: string | null;
|
||||
readonly primaryCusip: string | null;
|
||||
readonly canonicalName: string;
|
||||
readonly securityType: SecurityType;
|
||||
|
|
@ -660,9 +664,16 @@ async function persistWithinTransaction(
|
|||
skippedInstrumentIsins.add(candidate.primaryIsin);
|
||||
continue;
|
||||
}
|
||||
const isSynthetic = isSyntheticInstrumentKey(candidate.primaryIsin);
|
||||
const syntheticSourceId = isSynthetic
|
||||
? (candidate.members.find(m => m.source === 'eod')?.sourceId ??
|
||||
candidate.primaryIsin.slice(SYNTHETIC_EOD_ISIN_PREFIX.length))
|
||||
: null;
|
||||
preparedInstruments.push({
|
||||
primaryIsin: candidate.primaryIsin,
|
||||
primaryCusip: candidate.primaryCusip,
|
||||
isSynthetic,
|
||||
syntheticSourceId,
|
||||
primaryCusip: isSynthetic ? null : candidate.primaryCusip,
|
||||
canonicalName: trimmedName,
|
||||
securityType,
|
||||
issuerCountry: candidate.issuerCountry,
|
||||
|
|
@ -672,8 +683,11 @@ async function persistWithinTransaction(
|
|||
|
||||
if (preparedInstruments.length > 0) {
|
||||
const existingByIsin = new Map<string, ExistingInstrumentRow>();
|
||||
for (let offset = 0; offset < preparedInstruments.length; offset += chunkSize) {
|
||||
const slice = preparedInstruments.slice(offset, offset + chunkSize);
|
||||
const realInstruments = preparedInstruments.filter(item => !item.isSynthetic);
|
||||
const syntheticInstruments = preparedInstruments.filter(item => item.isSynthetic);
|
||||
|
||||
for (let offset = 0; offset < realInstruments.length; offset += chunkSize) {
|
||||
const slice = realInstruments.slice(offset, offset + chunkSize);
|
||||
const isins = slice.map(item => item.primaryIsin);
|
||||
const res = await client.query<ExistingInstrumentRow>(
|
||||
`SELECT
|
||||
|
|
@ -692,13 +706,70 @@ async function persistWithinTransaction(
|
|||
}
|
||||
}
|
||||
|
||||
const toInsert: PreparedInstrument[] = [];
|
||||
for (let offset = 0; offset < syntheticInstruments.length; offset += chunkSize) {
|
||||
const slice = syntheticInstruments.slice(offset, offset + chunkSize);
|
||||
const sourceIdToKey = new Map<string, string>();
|
||||
const sourceIds: string[] = [];
|
||||
for (const item of slice) {
|
||||
if (item.syntheticSourceId !== null) {
|
||||
sourceIdToKey.set(item.syntheticSourceId, item.primaryIsin);
|
||||
sourceIds.push(item.syntheticSourceId);
|
||||
}
|
||||
}
|
||||
if (sourceIds.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const res = await client.query<{
|
||||
source_id: string;
|
||||
instrument_id: number;
|
||||
primary_cusip: string | null;
|
||||
canonical_name: string;
|
||||
security_type: string;
|
||||
issuer_country: string | null;
|
||||
}>(
|
||||
`SELECT DISTINCT ON (pm.source_id)
|
||||
pm.source_id,
|
||||
i.instrument_id,
|
||||
btrim(i.primary_cusip) AS primary_cusip,
|
||||
i.canonical_name,
|
||||
i.security_type,
|
||||
btrim(i.issuer_country) AS issuer_country
|
||||
FROM provider_mapping pm
|
||||
JOIN listing l ON l.listing_id = pm.listing_id
|
||||
JOIN instrument i ON i.instrument_id = l.instrument_id
|
||||
WHERE pm.source = 'eod'
|
||||
AND pm.source_id = ANY($1::text[])
|
||||
AND i.primary_isin IS NULL
|
||||
ORDER BY pm.source_id, pm.valid_from ASC`,
|
||||
[sourceIds]
|
||||
);
|
||||
for (const row of res.rows) {
|
||||
const key = sourceIdToKey.get(row.source_id);
|
||||
if (key !== undefined) {
|
||||
existingByIsin.set(key, {
|
||||
instrument_id: row.instrument_id,
|
||||
primary_isin: key,
|
||||
primary_cusip: row.primary_cusip,
|
||||
canonical_name: row.canonical_name,
|
||||
security_type: row.security_type,
|
||||
issuer_country: row.issuer_country,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const toInsertReal: PreparedInstrument[] = [];
|
||||
const toInsertSynthetic: PreparedInstrument[] = [];
|
||||
const toUpdate: Array<{ instrumentId: number; item: PreparedInstrument }> = [];
|
||||
|
||||
for (const item of preparedInstruments) {
|
||||
const existing = existingByIsin.get(item.primaryIsin);
|
||||
if (existing === undefined) {
|
||||
toInsert.push(item);
|
||||
if (item.isSynthetic) {
|
||||
toInsertSynthetic.push(item);
|
||||
} else {
|
||||
toInsertReal.push(item);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
instrumentIdByIsin.set(item.primaryIsin, existing.instrument_id);
|
||||
|
|
@ -714,8 +785,8 @@ async function persistWithinTransaction(
|
|||
}
|
||||
}
|
||||
|
||||
for (let offset = 0; offset < toInsert.length; offset += chunkSize) {
|
||||
const slice = toInsert.slice(offset, offset + chunkSize);
|
||||
for (let offset = 0; offset < toInsertReal.length; offset += chunkSize) {
|
||||
const slice = toInsertReal.slice(offset, offset + chunkSize);
|
||||
const res = await client.query<InsertedInstrumentRow>(
|
||||
`INSERT INTO instrument (
|
||||
primary_isin,
|
||||
|
|
@ -747,6 +818,39 @@ async function persistWithinTransaction(
|
|||
instrumentsInserted += res.rows.length;
|
||||
}
|
||||
|
||||
for (let offset = 0; offset < toInsertSynthetic.length; offset += chunkSize) {
|
||||
const slice = toInsertSynthetic.slice(offset, offset + chunkSize);
|
||||
const res = await client.query<{ instrument_id: number }>(
|
||||
`INSERT INTO instrument (
|
||||
primary_isin,
|
||||
primary_cusip,
|
||||
canonical_name,
|
||||
security_type,
|
||||
issuer_country
|
||||
)
|
||||
SELECT NULL, NULL, u.canonical_name, u.security_type, u.issuer_country
|
||||
FROM UNNEST(
|
||||
$1::text[],
|
||||
$2::varchar[],
|
||||
$3::bpchar[]
|
||||
) AS u(canonical_name, security_type, issuer_country)
|
||||
RETURNING instrument_id`,
|
||||
[
|
||||
slice.map(item => item.canonicalName),
|
||||
slice.map(item => item.securityType),
|
||||
slice.map(item => item.issuerCountry),
|
||||
]
|
||||
);
|
||||
for (let i = 0; i < res.rows.length; i++) {
|
||||
const item = slice[i];
|
||||
const row = res.rows[i];
|
||||
if (item !== undefined && row !== undefined) {
|
||||
instrumentIdByIsin.set(item.primaryIsin, row.instrument_id);
|
||||
}
|
||||
}
|
||||
instrumentsInserted += res.rows.length;
|
||||
}
|
||||
|
||||
for (let offset = 0; offset < toUpdate.length; offset += chunkSize) {
|
||||
const slice = toUpdate.slice(offset, offset + chunkSize);
|
||||
await client.query(
|
||||
|
|
@ -784,6 +888,9 @@ async function persistWithinTransaction(
|
|||
source: StageASource;
|
||||
}> = [];
|
||||
for (const item of preparedInstruments) {
|
||||
if (item.isSynthetic) {
|
||||
continue;
|
||||
}
|
||||
const instrumentId = instrumentIdByIsin.get(item.primaryIsin);
|
||||
if (instrumentId === undefined) {
|
||||
continue;
|
||||
|
|
|
|||
|
|
@ -0,0 +1,291 @@
|
|||
import { mkdir, writeFile } from 'node:fs/promises';
|
||||
import { dirname } from 'node:path';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { initializeStockConfig } from '@stock-bot/stock-config';
|
||||
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
|
||||
import {
|
||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
normalizeProbeCollections,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
type FieldShapeProbeCollection,
|
||||
type ReadFieldShapesResult,
|
||||
} from './source-field-shapes';
|
||||
import {
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
} from './source-symbol-readers';
|
||||
|
||||
export const PROBE_SOURCE_FIELD_SHAPES_USAGE = [
|
||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --out <path> [--limit <n>] [--collections <c1,c2,...>] [--help]',
|
||||
'',
|
||||
'Options:',
|
||||
' --out <path> Required. Output Markdown report file path.',
|
||||
` --limit <n> Optional. Max documents sampled per collection (1..${MAX_FIELD_SHAPE_LIMIT}, default: ${DEFAULT_FIELD_SHAPE_LIMIT}).`,
|
||||
` --collections <list> Optional. Comma-separated allowlisted collections (default: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(',')}).`,
|
||||
' --help Show this help message and exit.',
|
||||
].join('\n');
|
||||
|
||||
export type ParsedProbeSourceFieldShapesArgs =
|
||||
| { readonly help: true }
|
||||
| {
|
||||
readonly help: false;
|
||||
readonly outPath: string;
|
||||
readonly limit: number;
|
||||
readonly collections: readonly FieldShapeProbeCollection[];
|
||||
};
|
||||
|
||||
export interface RunSourceFieldShapesProbeDeps {
|
||||
readonly mongoCollectionClient: ReadOnlyMongoCollectionClient;
|
||||
readonly closeMongo?: () => Promise<void> | void;
|
||||
readonly writeFile?: (filePath: string, content: string) => Promise<void> | void;
|
||||
readonly writeStdout?: (text: string) => void;
|
||||
}
|
||||
|
||||
export interface RunSourceFieldShapesProbeOptions {
|
||||
readonly outPath: string;
|
||||
readonly limit?: number;
|
||||
readonly collections?: readonly string[];
|
||||
readonly maxExamples?: number;
|
||||
readonly maxExampleLength?: number;
|
||||
readonly batchSize?: number;
|
||||
}
|
||||
|
||||
export interface RunSourceFieldShapesProbeOutput {
|
||||
readonly outPath: string;
|
||||
readonly result: ReadFieldShapesResult;
|
||||
readonly markdown: string;
|
||||
readonly summary: string;
|
||||
}
|
||||
|
||||
const STRICT_INT_PATTERN = /^-?\d+$/;
|
||||
|
||||
function usageError(message: string): Error {
|
||||
return new Error(`${message}\n\n${PROBE_SOURCE_FIELD_SHAPES_USAGE}`);
|
||||
}
|
||||
|
||||
function parseLimitArg(raw: string): number {
|
||||
if (!STRICT_INT_PATTERN.test(raw)) {
|
||||
throw usageError(
|
||||
`Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}`
|
||||
);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_FIELD_SHAPE_LIMIT) {
|
||||
throw usageError(
|
||||
`Invalid --limit value "${raw}": expected an integer between 1 and ${MAX_FIELD_SHAPE_LIMIT}`
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseCollectionsArg(raw: string): FieldShapeProbeCollection[] {
|
||||
const parts = raw
|
||||
.split(',')
|
||||
.map(part => part.trim())
|
||||
.filter(part => part.length > 0);
|
||||
if (parts.length === 0) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
return normalizeProbeCollections(parts);
|
||||
}
|
||||
|
||||
export function parseProbeSourceFieldShapesArgs(
|
||||
argv: readonly string[]
|
||||
): ParsedProbeSourceFieldShapesArgs {
|
||||
let help = false;
|
||||
let outPath: string | undefined;
|
||||
let limit = DEFAULT_FIELD_SHAPE_LIMIT;
|
||||
let collectionsRaw: string[] | undefined;
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--help') {
|
||||
help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--out') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --out');
|
||||
}
|
||||
outPath = value.trim();
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--out=')) {
|
||||
const value = arg.slice('--out='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --out');
|
||||
}
|
||||
outPath = value;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--limit') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --limit');
|
||||
}
|
||||
limit = parseLimitArg(value.trim());
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--limit=')) {
|
||||
const value = arg.slice('--limit='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --limit');
|
||||
}
|
||||
limit = parseLimitArg(value);
|
||||
continue;
|
||||
}
|
||||
if (arg === '--collections') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
const parsed = parseCollectionsArg(value);
|
||||
collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--collections=')) {
|
||||
const value = arg.slice('--collections='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
const parsed = parseCollectionsArg(value);
|
||||
collectionsRaw = collectionsRaw ? [...collectionsRaw, ...parsed] : parsed;
|
||||
continue;
|
||||
}
|
||||
throw usageError(`Unknown argument: ${String(arg)}`);
|
||||
}
|
||||
|
||||
if (help) {
|
||||
return { help: true };
|
||||
}
|
||||
|
||||
if (outPath === undefined || outPath.trim().length === 0) {
|
||||
throw usageError('Missing required argument: --out <path>');
|
||||
}
|
||||
|
||||
const collections = normalizeProbeCollections(collectionsRaw);
|
||||
return {
|
||||
help: false,
|
||||
outPath,
|
||||
limit,
|
||||
collections,
|
||||
};
|
||||
}
|
||||
|
||||
async function defaultWriteFile(filePath: string, content: string): Promise<void> {
|
||||
await mkdir(dirname(filePath), { recursive: true });
|
||||
await writeFile(filePath, content, 'utf8');
|
||||
}
|
||||
|
||||
export async function runSourceFieldShapesProbe(
|
||||
deps: RunSourceFieldShapesProbeDeps,
|
||||
options: RunSourceFieldShapesProbeOptions
|
||||
): Promise<RunSourceFieldShapesProbeOutput> {
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
let output: RunSourceFieldShapesProbeOutput | undefined;
|
||||
|
||||
try {
|
||||
if (typeof options.outPath !== 'string' || options.outPath.trim().length === 0) {
|
||||
throw new Error('outPath must be a non-empty string');
|
||||
}
|
||||
|
||||
const reader = createReadOnlyMongoSourceSymbolReader(deps.mongoCollectionClient);
|
||||
const result = await readFieldShapes(reader, {
|
||||
limit: options.limit,
|
||||
collections: options.collections,
|
||||
maxExamples: options.maxExamples,
|
||||
maxExampleLength: options.maxExampleLength,
|
||||
batchSize: options.batchSize,
|
||||
});
|
||||
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
const writer = deps.writeFile ?? defaultWriteFile;
|
||||
await writer(options.outPath, markdown);
|
||||
|
||||
const summary = [
|
||||
`Source field-shape probe complete (limit=${result.limit})`,
|
||||
` Collections: ${result.collections.length} | Documents sampled: ${result.totalDocsSampled}`,
|
||||
` Report written: ${options.outPath}`,
|
||||
].join('\n');
|
||||
|
||||
output = {
|
||||
outPath: options.outPath,
|
||||
result,
|
||||
markdown,
|
||||
summary: `${summary}\n`,
|
||||
};
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
hasPrimaryError = true;
|
||||
} finally {
|
||||
if (deps.closeMongo) {
|
||||
try {
|
||||
await deps.closeMongo();
|
||||
} catch (closeError) {
|
||||
if (!hasPrimaryError) {
|
||||
primaryError = closeError;
|
||||
hasPrimaryError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPrimaryError) {
|
||||
throw primaryError;
|
||||
}
|
||||
if (output === undefined) {
|
||||
throw new Error('Source field-shape probe completed without producing output');
|
||||
}
|
||||
|
||||
const writeStdout =
|
||||
deps.writeStdout ??
|
||||
((text: string) => {
|
||||
process.stdout.write(text);
|
||||
});
|
||||
writeStdout(output.summary);
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
export async function runCli(argv: readonly string[] = process.argv.slice(2)): Promise<void> {
|
||||
const parsed = parseProbeSourceFieldShapesArgs(argv);
|
||||
if (parsed.help) {
|
||||
process.stdout.write(`${PROBE_SOURCE_FIELD_SHAPES_USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
const logger = getLogger('source-field-shapes-probe');
|
||||
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
||||
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
|
||||
const mongo = new MongoDBClient(mongoConfig, logger);
|
||||
|
||||
await mongo.connect();
|
||||
await runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: mongo,
|
||||
closeMongo: () => mongo.disconnect(),
|
||||
},
|
||||
{
|
||||
outPath: parsed.outPath,
|
||||
limit: parsed.limit,
|
||||
collections: parsed.collections,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
runCli().catch(error => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
process.stderr.write(`Error: ${message}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,345 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
initializeStockConfig,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
import {
|
||||
CURATE_INPUT_FILES,
|
||||
DEFAULT_DELISTING_MAPPING_SOURCE,
|
||||
DEFAULT_EXPORT_CHUNK_SIZE,
|
||||
exportCurateInputs,
|
||||
MAX_EXPORT_CHUNK_SIZE,
|
||||
type ExportCurateInputsFsHooks,
|
||||
type ExportCurateInputsResult,
|
||||
} from './export-curate-inputs';
|
||||
import type { SecurityMasterQueryable, SecurityMasterQueryResult } from './persist';
|
||||
import type { SecurityMasterPostgresHandle } from './run-security-master';
|
||||
|
||||
export const EXPORT_CURATE_INPUTS_USAGE = [
|
||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts --out-dir <dir> [--chunk-size <n>] [--help]',
|
||||
'',
|
||||
'Options:',
|
||||
` --out-dir <dir> Required. Output directory for ${CURATE_INPUT_FILES.providerMapping}, ${CURATE_INPUT_FILES.listingCurrencies}, and ${CURATE_INPUT_FILES.delistings}.`,
|
||||
` --chunk-size <n> Optional. Keyset pagination chunk size (1..${MAX_EXPORT_CHUNK_SIZE}, default: ${DEFAULT_EXPORT_CHUNK_SIZE}).`,
|
||||
' --help Show this help message and exit.',
|
||||
].join('\n');
|
||||
|
||||
export type ParsedExportCurateInputsArgs =
|
||||
| { readonly help: true }
|
||||
| {
|
||||
readonly help: false;
|
||||
readonly outDir: string;
|
||||
readonly chunkSize: number;
|
||||
};
|
||||
|
||||
export interface RunExportCurateInputsDeps {
|
||||
readonly assertSafety?: () => void;
|
||||
readonly createPostgresClient: () =>
|
||||
| Promise<SecurityMasterPostgresHandle>
|
||||
| SecurityMasterPostgresHandle;
|
||||
readonly exportFn?: typeof exportCurateInputs;
|
||||
readonly writeStdout?: (text: string) => void;
|
||||
}
|
||||
|
||||
export interface RunExportCurateInputsOptions {
|
||||
readonly outDir: string;
|
||||
readonly chunkSize?: number;
|
||||
readonly delistingMappingSource?: string;
|
||||
readonly fs?: ExportCurateInputsFsHooks;
|
||||
}
|
||||
|
||||
export interface RunExportCurateInputsOutput {
|
||||
readonly result: ExportCurateInputsResult;
|
||||
readonly summary: string;
|
||||
}
|
||||
|
||||
const STRICT_INT_PATTERN = /^-?\d+$/;
|
||||
|
||||
function usageError(message: string): Error {
|
||||
return new Error(`${message}\n\n${EXPORT_CURATE_INPUTS_USAGE}`);
|
||||
}
|
||||
|
||||
function parseChunkSizeArg(raw: string): number {
|
||||
if (!STRICT_INT_PATTERN.test(raw)) {
|
||||
throw usageError(
|
||||
`Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}`
|
||||
);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (!Number.isSafeInteger(parsed) || parsed < 1 || parsed > MAX_EXPORT_CHUNK_SIZE) {
|
||||
throw usageError(
|
||||
`Invalid --chunk-size value "${raw}": expected an integer between 1 and ${MAX_EXPORT_CHUNK_SIZE}`
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export function parseExportCurateInputsArgs(
|
||||
argv: readonly string[]
|
||||
): ParsedExportCurateInputsArgs {
|
||||
let help = false;
|
||||
let outDir: string | undefined;
|
||||
let chunkSize = DEFAULT_EXPORT_CHUNK_SIZE;
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--help') {
|
||||
help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--out-dir') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --out-dir');
|
||||
}
|
||||
outDir = value.trim();
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--out-dir=')) {
|
||||
const value = arg.slice('--out-dir='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --out-dir');
|
||||
}
|
||||
outDir = value;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--chunk-size') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
throw usageError('Missing value for --chunk-size');
|
||||
}
|
||||
chunkSize = parseChunkSizeArg(value.trim());
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
if (arg?.startsWith('--chunk-size=')) {
|
||||
const value = arg.slice('--chunk-size='.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError('Missing value for --chunk-size');
|
||||
}
|
||||
chunkSize = parseChunkSizeArg(value);
|
||||
continue;
|
||||
}
|
||||
throw usageError(`Unknown argument: ${String(arg)}`);
|
||||
}
|
||||
|
||||
if (help) {
|
||||
return { help: true };
|
||||
}
|
||||
|
||||
if (outDir === undefined || outDir.trim().length === 0) {
|
||||
throw usageError('Missing required argument: --out-dir <dir>');
|
||||
}
|
||||
|
||||
return {
|
||||
help: false,
|
||||
outDir,
|
||||
chunkSize,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertExportCurateInputsSafety(
|
||||
config: StockAppConfig,
|
||||
env: Record<string, string | undefined> = process.env
|
||||
): void {
|
||||
const pg = config.database.postgres;
|
||||
if (!pg.enabled) {
|
||||
throw new Error('PostgreSQL is disabled in configuration; cannot export curate-etl inputs');
|
||||
}
|
||||
|
||||
const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _stripped, ...safeEnv } = env;
|
||||
const pgOnlyConfig: StockAppConfig = {
|
||||
...config,
|
||||
database: {
|
||||
...config.database,
|
||||
mongodb: {
|
||||
...config.database.mongodb,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
assertEnvironmentSafety(pgOnlyConfig, 'dataPipeline', safeEnv);
|
||||
}
|
||||
|
||||
export function formatExportCurateInputsSummary(result: ExportCurateInputsResult): string {
|
||||
const d = result.delistings.stats;
|
||||
const s = d.skipped;
|
||||
const lines = [
|
||||
`Curate-ETL TSV export complete (${result.outDir}, generation=${result.generationId}, snapshot_dir=${result.generationDir})`,
|
||||
` ${CURATE_INPUT_FILES.providerMapping}: rows_in=${result.providerMapping.rowsIn} rows_out=${result.providerMapping.rowsOut} bytes=${result.providerMapping.bytesWritten}`,
|
||||
` ${CURATE_INPUT_FILES.listingCurrencies}: rows_in=${result.listingCurrencies.rowsIn} rows_out=${result.listingCurrencies.rowsOut} bytes=${result.listingCurrencies.bytesWritten}`,
|
||||
` ${CURATE_INPUT_FILES.delistings}: rows_in=${d.rowsIn} rows_out=${d.rowsOut} (otc=${d.otcTransfersOut} terminal=${d.terminalDelistingsOut}) skipped=${d.skippedTotal} [active=${s.active} no_outcome=${s.noOutcome} missing_listed_to=${s.missingListedTo} missing_outgoing_qm=${s.missingOutgoingQmMapping} missing_successor_qm=${s.missingSuccessorQmMapping} non_otc_continuity=${s.nonOtcContinuity}] bytes=${result.delistings.bytesWritten}`,
|
||||
` chunk_size=${result.chunkSize} mapping_source=${result.delistingMappingSource} total_bytes=${result.totalBytesWritten}`,
|
||||
];
|
||||
for (const warning of result.cleanupWarnings) {
|
||||
lines.push(` warning: ${warning}`);
|
||||
}
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export async function runExportCurateInputs(
|
||||
deps: RunExportCurateInputsDeps,
|
||||
options: RunExportCurateInputsOptions
|
||||
): Promise<RunExportCurateInputsOutput> {
|
||||
if (deps.assertSafety) {
|
||||
deps.assertSafety();
|
||||
}
|
||||
|
||||
const pgHandle = await deps.createPostgresClient();
|
||||
let result: ExportCurateInputsResult;
|
||||
let closeError: unknown = null;
|
||||
try {
|
||||
const exportFn = deps.exportFn ?? exportCurateInputs;
|
||||
result = await exportFn(pgHandle.queryable, {
|
||||
outDir: options.outDir,
|
||||
chunkSize: options.chunkSize,
|
||||
delistingMappingSource: options.delistingMappingSource ?? DEFAULT_DELISTING_MAPPING_SOURCE,
|
||||
fs: options.fs,
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
await pgHandle.close();
|
||||
} catch (error) {
|
||||
closeError = error;
|
||||
}
|
||||
}
|
||||
|
||||
if (closeError !== null) {
|
||||
throw closeError;
|
||||
}
|
||||
|
||||
const summary = formatExportCurateInputsSummary(result);
|
||||
const writeStdout =
|
||||
deps.writeStdout ??
|
||||
((text: string) => {
|
||||
process.stdout.write(text);
|
||||
});
|
||||
writeStdout(summary);
|
||||
|
||||
return { result, summary };
|
||||
}
|
||||
|
||||
export async function runCli(
|
||||
argv: readonly string[] = process.argv.slice(2),
|
||||
overrides?: Partial<RunExportCurateInputsDeps>
|
||||
): Promise<void> {
|
||||
const parsed = parseExportCurateInputsArgs(argv);
|
||||
if (parsed.help) {
|
||||
const writeStdout =
|
||||
overrides?.writeStdout ??
|
||||
((text: string) => {
|
||||
process.stdout.write(text);
|
||||
});
|
||||
writeStdout(`${EXPORT_CURATE_INPUTS_USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
const logger = getLogger('security-master-export-curate-inputs-cli');
|
||||
const config = initializeStockConfig('dataPipeline', { postgresOnly: true });
|
||||
|
||||
const assertSafety = (): void => {
|
||||
assertExportCurateInputsSafety(config, process.env);
|
||||
};
|
||||
|
||||
const createPostgresClient = async (): Promise<SecurityMasterPostgresHandle> => {
|
||||
const pg = config.database.postgres;
|
||||
const pgClient = new PostgreSQLClient(
|
||||
{
|
||||
host: pg.host,
|
||||
port: pg.port,
|
||||
database: pg.database,
|
||||
username: pg.user,
|
||||
password: pg.password,
|
||||
poolSettings: {
|
||||
min: 1,
|
||||
max: Math.max(1, pg.poolSize),
|
||||
idleTimeoutMillis: pg.idleTimeout,
|
||||
},
|
||||
ssl: {
|
||||
enabled: pg.ssl,
|
||||
rejectUnauthorized: true,
|
||||
},
|
||||
timeouts: {
|
||||
connection: pg.connectionTimeout,
|
||||
},
|
||||
},
|
||||
logger
|
||||
);
|
||||
|
||||
await pgClient.connect();
|
||||
try {
|
||||
const pool = pgClient.connectionPool;
|
||||
if (!pool) {
|
||||
throw new Error('PostgreSQL connection pool was not initialized after connect()');
|
||||
}
|
||||
const poolClient = await pool.connect();
|
||||
const queryable: SecurityMasterQueryable = {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
return poolClient.query(
|
||||
text,
|
||||
values === undefined ? undefined : [...values]
|
||||
) as unknown as Promise<SecurityMasterQueryResult<Row>>;
|
||||
},
|
||||
release: () => {
|
||||
poolClient.release();
|
||||
},
|
||||
};
|
||||
let closed = false;
|
||||
return {
|
||||
queryable,
|
||||
async close(): Promise<void> {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
let releaseError: unknown = null;
|
||||
try {
|
||||
poolClient.release();
|
||||
} catch (error) {
|
||||
releaseError = error;
|
||||
}
|
||||
try {
|
||||
await pgClient.disconnect();
|
||||
} catch (disconnectError) {
|
||||
if (releaseError === null) {
|
||||
throw disconnectError;
|
||||
}
|
||||
}
|
||||
if (releaseError !== null) {
|
||||
throw releaseError;
|
||||
}
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
await pgClient.disconnect().catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
await runExportCurateInputs(
|
||||
{
|
||||
assertSafety: overrides?.assertSafety ?? assertSafety,
|
||||
createPostgresClient: overrides?.createPostgresClient ?? createPostgresClient,
|
||||
exportFn: overrides?.exportFn,
|
||||
writeStdout: overrides?.writeStdout,
|
||||
},
|
||||
{
|
||||
outDir: parsed.outDir,
|
||||
chunkSize: parsed.chunkSize,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
runCli().catch(error => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
process.stderr.write(`Error: ${message}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
|
@ -0,0 +1,477 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
initializeStockConfig,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
import {
|
||||
createReadOnlyMongoRawBsonSource,
|
||||
DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
exportRawBsonCollection,
|
||||
isRawBsonExportCollection,
|
||||
MAX_RAW_BSON_BATCH_SIZE,
|
||||
RAW_BSON_EXPORT_COLLECTIONS,
|
||||
RawBsonExportError,
|
||||
type ExportRawBsonCollectionResult,
|
||||
type ExportRawBsonFsHooks,
|
||||
type RawBsonExportCollection,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
} from './export-raw-bson';
|
||||
import { resolveReadOnlyMongoClientConfig } from './generate-exchange-seed';
|
||||
|
||||
export const EXPORT_RAW_BSON_USAGE = [
|
||||
'Usage: bun run apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts --out-dir <dir> [--collections <c1,c2,...>] [--eod-symbol <code>] [--te-symbol <sym>] [--limit <n>] [--batch-size <n>] [--help]',
|
||||
'',
|
||||
'Options:',
|
||||
' --out-dir <dir> Required. Output directory for <collection>.bson files.',
|
||||
` --collections <c1,c2,...> Optional. Comma-separated allowlisted collections (default: ${RAW_BSON_EXPORT_COLLECTIONS.join(',')}).`,
|
||||
' --eod-symbol <code> Optional. Exact eodSearchCode filter (only valid when --collections is strictly eodPrices).',
|
||||
' --te-symbol <sym> Optional. Exact teSymbol filter (only valid when --collections is strictly teMarketData).',
|
||||
' --limit <n> Optional. Max documents to export per collection (positive integer, for smoke runs).',
|
||||
` --batch-size <n> Optional. MongoDB cursor batchSize (1..${MAX_RAW_BSON_BATCH_SIZE}, default: ${DEFAULT_RAW_BSON_BATCH_SIZE}).`,
|
||||
' --help Show this help message and exit.',
|
||||
].join('\n');
|
||||
|
||||
export type ParsedExportRawBsonArgs =
|
||||
| { readonly help: true }
|
||||
| {
|
||||
readonly help: false;
|
||||
readonly outDir: string;
|
||||
readonly collections: readonly RawBsonExportCollection[];
|
||||
readonly eodSymbol?: string;
|
||||
readonly teSymbol?: string;
|
||||
readonly limit?: number;
|
||||
readonly batchSize: number;
|
||||
};
|
||||
|
||||
export interface RawBsonMongoHandle {
|
||||
readonly client: ReadOnlyMongoRawBsonClient;
|
||||
readonly close: () => Promise<void> | void;
|
||||
}
|
||||
|
||||
export interface RunExportRawBsonDeps {
|
||||
readonly assertSafety?: () => void;
|
||||
readonly createMongoClient: () => Promise<RawBsonMongoHandle> | RawBsonMongoHandle;
|
||||
readonly exportFn?: typeof exportRawBsonCollection;
|
||||
readonly writeStdout?: (text: string) => void;
|
||||
}
|
||||
|
||||
export interface RunExportRawBsonCliOverrides extends Partial<RunExportRawBsonDeps> {
|
||||
readonly initializeConfig?: typeof initializeStockConfig;
|
||||
}
|
||||
|
||||
export interface RunExportRawBsonOptions {
|
||||
readonly outDir: string;
|
||||
readonly collections: readonly RawBsonExportCollection[];
|
||||
readonly eodSymbol?: string;
|
||||
readonly teSymbol?: string;
|
||||
readonly limit?: number;
|
||||
readonly batchSize?: number;
|
||||
readonly writeBufferBytes?: number;
|
||||
readonly maxDocBytes?: number;
|
||||
readonly fs?: ExportRawBsonFsHooks;
|
||||
}
|
||||
|
||||
export interface RunExportRawBsonOutput {
|
||||
readonly results: readonly ExportRawBsonCollectionResult[];
|
||||
readonly summary: string;
|
||||
}
|
||||
|
||||
const STRICT_INT_PATTERN = /^-?\d+$/;
|
||||
|
||||
function usageError(message: string): Error {
|
||||
return new Error(`${message}\n\n${EXPORT_RAW_BSON_USAGE}`);
|
||||
}
|
||||
|
||||
function parsePositiveIntArg(flag: string, raw: string, max?: number): number {
|
||||
if (!STRICT_INT_PATTERN.test(raw)) {
|
||||
throw usageError(
|
||||
max !== undefined
|
||||
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
|
||||
: `Invalid ${flag} value "${raw}": expected a positive integer`
|
||||
);
|
||||
}
|
||||
const parsed = Number(raw);
|
||||
if (
|
||||
!Number.isSafeInteger(parsed) ||
|
||||
parsed < 1 ||
|
||||
(max !== undefined && parsed > max)
|
||||
) {
|
||||
throw usageError(
|
||||
max !== undefined
|
||||
? `Invalid ${flag} value "${raw}": expected an integer between 1 and ${max}`
|
||||
: `Invalid ${flag} value "${raw}": expected a positive integer`
|
||||
);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function parseCollectionsList(raw: string): RawBsonExportCollection[] {
|
||||
const segments = raw.split(',');
|
||||
const result: RawBsonExportCollection[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const segment of segments) {
|
||||
const trimmed = segment.trim();
|
||||
if (trimmed.length === 0) {
|
||||
throw usageError(`Malformed --collections value "${raw}": empty collection entry`);
|
||||
}
|
||||
if (!isRawBsonExportCollection(trimmed)) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'DISALLOWED_COLLECTION',
|
||||
collection: trimmed,
|
||||
detail: `collection "${trimmed}" is not in the M1 allowlist (${RAW_BSON_EXPORT_COLLECTIONS.join(', ')})`,
|
||||
});
|
||||
}
|
||||
if (seen.has(trimmed)) {
|
||||
throw usageError(`Duplicate collection "${trimmed}" in --collections`);
|
||||
}
|
||||
seen.add(trimmed);
|
||||
result.push(trimmed);
|
||||
}
|
||||
|
||||
if (result.length === 0) {
|
||||
throw usageError('Missing value for --collections');
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function readFlagValue(
|
||||
argv: readonly string[],
|
||||
index: number,
|
||||
flag: string
|
||||
): { value: string; nextIndex: number } {
|
||||
const arg = argv[index] ?? '';
|
||||
const eqPrefix = `${flag}=`;
|
||||
if (arg.startsWith(eqPrefix)) {
|
||||
const value = arg.slice(eqPrefix.length).trim();
|
||||
if (value.length === 0) {
|
||||
throw usageError(`Missing value for ${flag}`);
|
||||
}
|
||||
if (value.startsWith('--')) {
|
||||
throw usageError(`Invalid value for ${flag}: "${value}" must not start with "--"`);
|
||||
}
|
||||
return { value, nextIndex: index };
|
||||
}
|
||||
|
||||
const next = argv[index + 1];
|
||||
const trimmedNext = next?.trim() ?? '';
|
||||
if (trimmedNext.length === 0 || trimmedNext.startsWith('--')) {
|
||||
throw usageError(`Missing value for ${flag}`);
|
||||
}
|
||||
return { value: trimmedNext, nextIndex: index + 1 };
|
||||
}
|
||||
|
||||
export function parseExportRawBsonArgs(argv: readonly string[]): ParsedExportRawBsonArgs {
|
||||
let help = false;
|
||||
let outDir: string | undefined;
|
||||
let collections: RawBsonExportCollection[] | undefined;
|
||||
let eodSymbol: string | undefined;
|
||||
let teSymbol: string | undefined;
|
||||
let limit: number | undefined;
|
||||
let batchSize = DEFAULT_RAW_BSON_BATCH_SIZE;
|
||||
|
||||
const seenFlags = new Set<string>();
|
||||
|
||||
const markSeen = (flag: string): void => {
|
||||
if (seenFlags.has(flag)) {
|
||||
throw usageError(`Duplicate flag: ${flag}`);
|
||||
}
|
||||
seenFlags.add(flag);
|
||||
};
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--help') {
|
||||
markSeen('--help');
|
||||
help = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--out-dir' || arg?.startsWith('--out-dir=')) {
|
||||
markSeen('--out-dir');
|
||||
const { value, nextIndex } = readFlagValue(argv, i, '--out-dir');
|
||||
outDir = value;
|
||||
i = nextIndex;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--collections' || arg?.startsWith('--collections=')) {
|
||||
markSeen('--collections');
|
||||
const { value, nextIndex } = readFlagValue(argv, i, '--collections');
|
||||
collections = parseCollectionsList(value);
|
||||
i = nextIndex;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--eod-symbol' || arg?.startsWith('--eod-symbol=')) {
|
||||
markSeen('--eod-symbol');
|
||||
const { value, nextIndex } = readFlagValue(argv, i, '--eod-symbol');
|
||||
eodSymbol = value;
|
||||
i = nextIndex;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--te-symbol' || arg?.startsWith('--te-symbol=')) {
|
||||
markSeen('--te-symbol');
|
||||
const { value, nextIndex } = readFlagValue(argv, i, '--te-symbol');
|
||||
teSymbol = value;
|
||||
i = nextIndex;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--limit' || arg?.startsWith('--limit=')) {
|
||||
markSeen('--limit');
|
||||
const { value, nextIndex } = readFlagValue(argv, i, '--limit');
|
||||
limit = parsePositiveIntArg('--limit', value);
|
||||
i = nextIndex;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--batch-size' || arg?.startsWith('--batch-size=')) {
|
||||
markSeen('--batch-size');
|
||||
const { value, nextIndex } = readFlagValue(argv, i, '--batch-size');
|
||||
batchSize = parsePositiveIntArg('--batch-size', value, MAX_RAW_BSON_BATCH_SIZE);
|
||||
i = nextIndex;
|
||||
continue;
|
||||
}
|
||||
throw usageError(`Unknown argument: ${String(arg)}`);
|
||||
}
|
||||
|
||||
if (help) {
|
||||
return { help: true };
|
||||
}
|
||||
|
||||
if (outDir === undefined || outDir.trim().length === 0) {
|
||||
throw usageError('Missing required argument: --out-dir <dir>');
|
||||
}
|
||||
|
||||
const resolvedCollections: readonly RawBsonExportCollection[] =
|
||||
collections ?? [...RAW_BSON_EXPORT_COLLECTIONS];
|
||||
|
||||
if (eodSymbol !== undefined) {
|
||||
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'eodPrices') {
|
||||
throw usageError(
|
||||
'--eod-symbol is only permitted when --collections is strictly "eodPrices"'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (teSymbol !== undefined) {
|
||||
if (resolvedCollections.length !== 1 || resolvedCollections[0] !== 'teMarketData') {
|
||||
throw usageError(
|
||||
'--te-symbol is only permitted when --collections is strictly "teMarketData"'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
help: false,
|
||||
outDir,
|
||||
collections: resolvedCollections,
|
||||
...(eodSymbol !== undefined ? { eodSymbol } : {}),
|
||||
...(teSymbol !== undefined ? { teSymbol } : {}),
|
||||
...(limit !== undefined ? { limit } : {}),
|
||||
batchSize,
|
||||
};
|
||||
}
|
||||
|
||||
export function assertExportRawBsonSafety(
|
||||
config: StockAppConfig,
|
||||
env: Record<string, string | undefined> = process.env
|
||||
): void {
|
||||
const mongo = config.database.mongodb;
|
||||
if (!mongo.enabled) {
|
||||
throw new Error('MongoDB is disabled in configuration; cannot export raw BSON collections');
|
||||
}
|
||||
if (mongo.readOnly !== true) {
|
||||
throw new Error(
|
||||
'Raw BSON exporter requires read-only MongoDB configuration (database.mongodb.readOnly === true)'
|
||||
);
|
||||
}
|
||||
|
||||
const { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: _stripped, ...safeEnv } = env;
|
||||
const mongoOnlyConfig: StockAppConfig = {
|
||||
...config,
|
||||
database: {
|
||||
...config.database,
|
||||
postgres: {
|
||||
...config.database.postgres,
|
||||
enabled: false,
|
||||
},
|
||||
},
|
||||
};
|
||||
assertEnvironmentSafety(mongoOnlyConfig, 'dataPipeline', safeEnv);
|
||||
}
|
||||
|
||||
export function formatExportRawBsonSummary(
|
||||
results: readonly ExportRawBsonCollectionResult[]
|
||||
): string {
|
||||
const lines = [`Raw BSON export complete (${results.length} collection(s))`];
|
||||
for (const r of results) {
|
||||
lines.push(
|
||||
` ${r.collection}: docs=${r.docsWritten} bytes=${r.bytesWritten} elapsed_ms=${r.elapsedMs.toFixed(1)} sha256=${r.sha256} out=${r.outPath}`
|
||||
);
|
||||
}
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
||||
export async function runExportRawBson(
|
||||
deps: RunExportRawBsonDeps,
|
||||
options: RunExportRawBsonOptions
|
||||
): Promise<RunExportRawBsonOutput> {
|
||||
if (options.collections.length === 0) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: '*',
|
||||
detail: 'At least one allowlisted collection must be specified',
|
||||
});
|
||||
}
|
||||
for (const collection of options.collections) {
|
||||
if (!isRawBsonExportCollection(collection)) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'DISALLOWED_COLLECTION',
|
||||
collection: String(collection),
|
||||
detail: `collection "${String(collection)}" is not in the M1 allowlist`,
|
||||
});
|
||||
}
|
||||
}
|
||||
if (
|
||||
options.eodSymbol !== undefined &&
|
||||
(options.collections.length !== 1 || options.collections[0] !== 'eodPrices')
|
||||
) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: options.collections.join(','),
|
||||
detail: '--eod-symbol is only permitted when exporting strictly "eodPrices"',
|
||||
});
|
||||
}
|
||||
if (
|
||||
options.teSymbol !== undefined &&
|
||||
(options.collections.length !== 1 || options.collections[0] !== 'teMarketData')
|
||||
) {
|
||||
throw new RawBsonExportError({
|
||||
code: 'INVALID_OPTION',
|
||||
collection: options.collections.join(','),
|
||||
detail: '--te-symbol is only permitted when exporting strictly "teMarketData"',
|
||||
});
|
||||
}
|
||||
|
||||
if (deps.assertSafety) {
|
||||
deps.assertSafety();
|
||||
}
|
||||
|
||||
const mongoHandle = await deps.createMongoClient();
|
||||
const results: ExportRawBsonCollectionResult[] = [];
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
|
||||
try {
|
||||
const source = createReadOnlyMongoRawBsonSource(mongoHandle.client);
|
||||
const exportFn = deps.exportFn ?? exportRawBsonCollection;
|
||||
|
||||
for (const collection of options.collections) {
|
||||
const result = await exportFn(source, {
|
||||
collection,
|
||||
outDir: options.outDir,
|
||||
...(options.eodSymbol !== undefined ? { eodSymbol: options.eodSymbol } : {}),
|
||||
...(options.teSymbol !== undefined ? { teSymbol: options.teSymbol } : {}),
|
||||
...(options.limit !== undefined ? { limit: options.limit } : {}),
|
||||
...(options.batchSize !== undefined ? { batchSize: options.batchSize } : {}),
|
||||
...(options.writeBufferBytes !== undefined
|
||||
? { writeBufferBytes: options.writeBufferBytes }
|
||||
: {}),
|
||||
...(options.maxDocBytes !== undefined ? { maxDocBytes: options.maxDocBytes } : {}),
|
||||
...(options.fs !== undefined ? { fs: options.fs } : {}),
|
||||
});
|
||||
results.push(result);
|
||||
}
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
hasPrimaryError = true;
|
||||
} finally {
|
||||
try {
|
||||
await mongoHandle.close();
|
||||
} catch (closeError) {
|
||||
if (!hasPrimaryError) {
|
||||
primaryError = closeError;
|
||||
hasPrimaryError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPrimaryError) {
|
||||
throw primaryError;
|
||||
}
|
||||
|
||||
const summary = formatExportRawBsonSummary(results);
|
||||
const writeStdout =
|
||||
deps.writeStdout ??
|
||||
((text: string) => {
|
||||
process.stdout.write(text);
|
||||
});
|
||||
writeStdout(summary);
|
||||
|
||||
return { results, summary };
|
||||
}
|
||||
|
||||
export async function runCli(
|
||||
argv: readonly string[] = process.argv.slice(2),
|
||||
overrides?: RunExportRawBsonCliOverrides
|
||||
): Promise<void> {
|
||||
const parsed = parseExportRawBsonArgs(argv);
|
||||
if (parsed.help) {
|
||||
const writeStdout =
|
||||
overrides?.writeStdout ??
|
||||
((text: string) => {
|
||||
process.stdout.write(text);
|
||||
});
|
||||
writeStdout(`${EXPORT_RAW_BSON_USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
|
||||
const logger = getLogger('security-master-export-raw-bson-cli');
|
||||
const initConfig = overrides?.initializeConfig ?? initializeStockConfig;
|
||||
const config = initConfig('dataPipeline', { mongoReadOnly: true });
|
||||
|
||||
const assertSafety = (): void => {
|
||||
assertExportRawBsonSafety(config, process.env);
|
||||
};
|
||||
|
||||
const createMongoClient = async (): Promise<RawBsonMongoHandle> => {
|
||||
const mongoConfig = resolveReadOnlyMongoClientConfig(config);
|
||||
const mongo = new MongoDBClient(mongoConfig, logger);
|
||||
await mongo.connect();
|
||||
let closed = false;
|
||||
return {
|
||||
client: mongo,
|
||||
async close(): Promise<void> {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
await mongo.disconnect();
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
await runExportRawBson(
|
||||
{
|
||||
assertSafety: overrides?.assertSafety ?? assertSafety,
|
||||
createMongoClient: overrides?.createMongoClient ?? createMongoClient,
|
||||
exportFn: overrides?.exportFn,
|
||||
writeStdout: overrides?.writeStdout,
|
||||
},
|
||||
{
|
||||
outDir: parsed.outDir,
|
||||
collections: parsed.collections,
|
||||
...(parsed.eodSymbol !== undefined ? { eodSymbol: parsed.eodSymbol } : {}),
|
||||
...(parsed.teSymbol !== undefined ? { teSymbol: parsed.teSymbol } : {}),
|
||||
...(parsed.limit !== undefined ? { limit: parsed.limit } : {}),
|
||||
batchSize: parsed.batchSize,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
runCli().catch(error => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
process.stderr.write(`Error: ${message}\n`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
|
@ -21,6 +21,7 @@ import {
|
|||
EXCHANGE_SOURCES,
|
||||
ISO_EXCHANGE_SEEDS,
|
||||
normalizeRawExchangeDoc,
|
||||
REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS,
|
||||
type ExchangeClassificationResult,
|
||||
type ExchangeSource,
|
||||
type SourceExchangeRecord,
|
||||
|
|
@ -51,6 +52,8 @@ import {
|
|||
import {
|
||||
createExchangeSourceLookup,
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
DEFAULT_SOURCE_COUNTRIES,
|
||||
normalizeCountryIso2,
|
||||
readSecurityMasterSources,
|
||||
type ExchangeSourceLookup,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
|
|
@ -72,7 +75,9 @@ export const RUN_SECURITY_MASTER_USAGE = [
|
|||
' --out-dir <dir> Required. Output directory for match-report.md, conflicts.csv, override-template.sql, and run-stats.json.',
|
||||
' --persist Optional. Persist security-master rows to isolated dev PostgreSQL after running safety guards (default: off).',
|
||||
' --skip-price-cross-check Optional. Skip Pass 4 sample-close reads and price cross-checks (default: enabled).',
|
||||
` --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..${MAX_SAMPLE_DATES}, default: ${DEFAULT_SAMPLE_DATE_COUNT}).`,
|
||||
' --sample-dates <n> Optional. Number of stratified sample dates for Pass 4 (1..64, default: 25).',
|
||||
' --reviewed-us-ca-exchanges Optional. Scope Pass 1 exchange classification to configured US/CA countries with reviewed US/CA venue rules.',
|
||||
' --allow-identifierless-eod Optional. Admit US/CA EOD primary-venue listings lacking ISIN/CUSIP (stored with primary_isin = NULL).',
|
||||
' --help Show this help message and exit.',
|
||||
].join('\n');
|
||||
|
||||
|
|
@ -85,6 +90,8 @@ export type ParsedRunSecurityMasterArgs =
|
|||
readonly persist: boolean;
|
||||
readonly skipPriceCrossCheck: boolean;
|
||||
readonly sampleDateCount: number;
|
||||
readonly useReviewedUsCaExchanges?: boolean;
|
||||
readonly allowIdentifierlessEod?: boolean;
|
||||
};
|
||||
|
||||
export interface RunSecurityMasterPass4Options {
|
||||
|
|
@ -134,6 +141,8 @@ export interface RunSecurityMasterOptions {
|
|||
readonly batchSize?: number;
|
||||
readonly barSpans?: Omit<ComputeBarSpansOptions, 'sourceIdsBySource'>;
|
||||
readonly pass4?: RunSecurityMasterPass4Options;
|
||||
readonly useReviewedUsCaExchanges?: boolean;
|
||||
readonly allowIdentifierlessEod?: boolean;
|
||||
}
|
||||
|
||||
export interface RunSecurityMasterOutput {
|
||||
|
|
@ -351,6 +360,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
|
|||
let persist = false;
|
||||
let skipPriceCrossCheck = false;
|
||||
let sampleDateCount = DEFAULT_SAMPLE_DATE_COUNT;
|
||||
let useReviewedUsCaExchanges = false;
|
||||
let allowIdentifierlessEod = false;
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
|
|
@ -366,6 +377,14 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
|
|||
skipPriceCrossCheck = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--reviewed-us-ca-exchanges') {
|
||||
useReviewedUsCaExchanges = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--allow-identifierless-eod') {
|
||||
allowIdentifierlessEod = true;
|
||||
continue;
|
||||
}
|
||||
if (arg === '--sample-dates') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.trim().length === 0 || value.startsWith('--')) {
|
||||
|
|
@ -443,6 +462,8 @@ export function parseRunSecurityMasterArgs(argv: readonly string[]): ParsedRunSe
|
|||
persist,
|
||||
skipPriceCrossCheck,
|
||||
sampleDateCount,
|
||||
...(useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}),
|
||||
...(allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -627,8 +648,31 @@ export async function runSecurityMaster(
|
|||
}
|
||||
exchangeCountsByCollection[source] = count;
|
||||
}
|
||||
exchanges = classifySourceExchanges(normalizedRecords, {
|
||||
let recordsToClassify = normalizedRecords;
|
||||
if (options.useReviewedUsCaExchanges === true && options.countries !== null) {
|
||||
const allowedCountries = new Set<string>(
|
||||
(options.countries ?? DEFAULT_SOURCE_COUNTRIES)
|
||||
.map(c => normalizeCountryIso2(c) ?? c.trim().toUpperCase())
|
||||
.filter(c => c.length > 0)
|
||||
);
|
||||
recordsToClassify = normalizedRecords.filter(rec => {
|
||||
const codeUpper = rec.code.trim().toUpperCase();
|
||||
if (rec.source === 'eod' && codeUpper === 'FOREX') {
|
||||
return true;
|
||||
}
|
||||
const iso = normalizeCountryIso2(rec.country);
|
||||
return (
|
||||
rec.country === null ||
|
||||
rec.country === undefined ||
|
||||
(iso !== null && allowedCountries.has(iso))
|
||||
);
|
||||
});
|
||||
}
|
||||
exchanges = classifySourceExchanges(recordsToClassify, {
|
||||
knownExchanges: ISO_EXCHANGE_SEEDS,
|
||||
...(options.useReviewedUsCaExchanges === true
|
||||
? { reviewedRows: REVIEWED_US_CA_EXCHANGE_SOURCE_MAP_ROWS }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
|
@ -644,6 +688,7 @@ export async function runSecurityMaster(
|
|||
exchangeLookup,
|
||||
countries: options.countries,
|
||||
batchSize: options.batchSize,
|
||||
...(options.allowIdentifierlessEod === true ? { includeExtendedMetadata: true } : {}),
|
||||
});
|
||||
} catch (error) {
|
||||
throw wrapStepError('read-sources', error);
|
||||
|
|
@ -673,6 +718,41 @@ export async function runSecurityMaster(
|
|||
}
|
||||
|
||||
// Step 5: Compose Stage A -> Stage B -> Pass 6 -> candidate Pass 4 pairs.
|
||||
const composeOptions =
|
||||
options.allowIdentifierlessEod === true
|
||||
? {
|
||||
asOfDate: options.asOfDate,
|
||||
stageA: { allowIdentifierlessEod: true },
|
||||
stageB: {
|
||||
enableIbTickerDisambiguation: true,
|
||||
allowUniqueTickerFallbackForCrawlOnlyCeo: true,
|
||||
},
|
||||
report: {
|
||||
applyUsCaEquityGateDenominator: true,
|
||||
},
|
||||
}
|
||||
: {
|
||||
asOfDate: options.asOfDate,
|
||||
};
|
||||
|
||||
// Preserve verified pre-2024 FB -> META ticker history (2012-05-18 .. 2022-06-08) when
|
||||
// META.US is present and eodSymbolChange only covers recent years, so historical FB bars
|
||||
// map to Meta while the 2025 ProShares FB ETF (FB.US) retains a distinct listing_id.
|
||||
if (
|
||||
options.allowIdentifierlessEod === true &&
|
||||
sources.stageBInput.eodListings.some(e => e.sourceId === 'META.US') &&
|
||||
!sources.stageBInput.symbolChanges.some(
|
||||
sc => sc.eodSourceId === 'META.US' && sc.oldTicker === 'FB'
|
||||
)
|
||||
) {
|
||||
sources.stageBInput.symbolChanges.push({
|
||||
eodSourceId: 'META.US',
|
||||
oldTicker: 'FB',
|
||||
effectiveDate: '2022-06-09',
|
||||
validFrom: '2012-05-18',
|
||||
});
|
||||
}
|
||||
|
||||
const composeFn = deps.composeFn ?? composeSecurityMasterRun;
|
||||
let composed: ComposeSecurityMasterRunResult;
|
||||
try {
|
||||
|
|
@ -682,9 +762,7 @@ export async function runSecurityMaster(
|
|||
barSpans,
|
||||
exchanges,
|
||||
},
|
||||
{
|
||||
asOfDate: options.asOfDate,
|
||||
}
|
||||
composeOptions
|
||||
);
|
||||
} catch (error) {
|
||||
throw wrapStepError('compose', error);
|
||||
|
|
@ -758,9 +836,7 @@ export async function runSecurityMaster(
|
|||
sampleCloses: sampleCloses.closes,
|
||||
fxRates: sampleCloses.fxRates,
|
||||
},
|
||||
{
|
||||
asOfDate: options.asOfDate,
|
||||
}
|
||||
composeOptions
|
||||
);
|
||||
} catch (error) {
|
||||
throw wrapStepError('compose', error);
|
||||
|
|
@ -1025,6 +1101,8 @@ export async function runCli(argv: readonly string[] = process.argv.slice(2)): P
|
|||
asOfDate: parsed.asOfDate,
|
||||
outDir: parsed.outDir,
|
||||
persist: parsed.persist,
|
||||
...(parsed.useReviewedUsCaExchanges ? { useReviewedUsCaExchanges: true } : {}),
|
||||
...(parsed.allowIdentifierlessEod ? { allowIdentifierlessEod: true } : {}),
|
||||
pass4: {
|
||||
enabled: !parsed.skipPriceCrossCheck,
|
||||
sampleDateCount: parsed.sampleDateCount,
|
||||
|
|
|
|||
|
|
@ -22,10 +22,12 @@ import {
|
|||
isStageASource,
|
||||
matchInstrumentsStageA,
|
||||
STAGE_A_SOURCES,
|
||||
SYNTHETIC_EOD_ISIN_PREFIX,
|
||||
type MatchInstrumentsStageAOptions,
|
||||
type StageAMatchResult,
|
||||
type StageASourceRecord,
|
||||
} from './instrument-stage-a';
|
||||
import { classifyEodSecurityType } from './security-type';
|
||||
import {
|
||||
matchListingsStageB,
|
||||
MAX_TICKER_ROOT_LENGTH,
|
||||
|
|
@ -46,6 +48,8 @@ import {
|
|||
sourceCountryKey,
|
||||
type BuildMatchReportOptions,
|
||||
type CountryResolutionSummary,
|
||||
type GateOutOfScopeLookup,
|
||||
type GateOutOfScopeReason,
|
||||
type MatchReport,
|
||||
type RenderMatchReportMarkdownOptions,
|
||||
type SourceCountryLookup,
|
||||
|
|
@ -933,7 +937,8 @@ function applyEndToEndStageACoverage(
|
|||
const unresolved = row.unresolved + d.unresolved;
|
||||
const conflict = row.conflict + d.conflict;
|
||||
const excludedByDesign = row.excludedByDesign + d.excludedByDesign;
|
||||
const eligibleTotal = Math.max(0, total - excludedByDesign);
|
||||
const outOfGateScope = row.outOfGateScope ?? 0;
|
||||
const eligibleTotal = Math.max(0, total - excludedByDesign - outOfGateScope);
|
||||
return {
|
||||
source: row.source,
|
||||
total,
|
||||
|
|
@ -941,6 +946,7 @@ function applyEndToEndStageACoverage(
|
|||
unresolved,
|
||||
conflict,
|
||||
excludedByDesign,
|
||||
...(row.outOfGateScope !== undefined ? { outOfGateScope } : {}),
|
||||
eligibleTotal,
|
||||
resolvedPct: total > 0 ? row.matched / total : null,
|
||||
eligibleResolvedPct: eligibleTotal > 0 ? row.matched / eligibleTotal : null,
|
||||
|
|
@ -1175,6 +1181,143 @@ export function composeSecurityMasterRun(
|
|||
const sourceCountries =
|
||||
input.sourceCountries ??
|
||||
deriveSourceCountries(sanitizedStageARecords, attached.stageBInput, stageB);
|
||||
const NON_EQUITY_CLASS_SUFFIX_RE =
|
||||
/^(WT|WS|DB|RT|R|U|UN|H|P|PR|PF|PA|PB|PC|PD|PE|PG|PH|PI|PJ|PK|PL|PM|PN|PO|PP|PQ|PS|PT|PU|PV|PW|PX|PY|PZ|PR[A-Z]|PF[A-Z])(\..+)?$/;
|
||||
const TEST_SYMBOL_RE = /^(NTEST|ZXYZ|ZVZZT|ZWZZT|ZXZZT)/i;
|
||||
const NON_EQUITY_NAME_RE =
|
||||
/\b(WARRANTS?|DEBENTURES?|PREFERRED|PFD|RIGHTS?|SUBSCRIPTION\s+RECEIPTS?|UNITS?|TEST\s+SYMBOL)\b/i;
|
||||
|
||||
const US_CA_EQUITY_GATE_DENOMINATOR_NOTE = [
|
||||
'The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`).',
|
||||
'All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`:',
|
||||
'- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`).',
|
||||
'- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings).',
|
||||
'- `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 shells `.H`, TSXV CPCs `.P`, and exchange test symbols).',
|
||||
].join('\n');
|
||||
|
||||
function isNonEquityRecord(
|
||||
source: 'ib' | 'qm' | 'ceo',
|
||||
ticker: string | null | undefined,
|
||||
name: string | null | undefined
|
||||
): boolean {
|
||||
if (typeof name === 'string' && NON_EQUITY_NAME_RE.test(name)) {
|
||||
return true;
|
||||
}
|
||||
if (typeof ticker !== 'string' || ticker.trim().length === 0) {
|
||||
return false;
|
||||
}
|
||||
const trimmed = ticker.trim();
|
||||
if (TEST_SYMBOL_RE.test(trimmed)) {
|
||||
return true;
|
||||
}
|
||||
if (source === 'ceo' && /\.(CN|NEO)$/i.test(trimmed)) {
|
||||
return false;
|
||||
}
|
||||
const parsed = parseTickerDetailed(trimmed, source);
|
||||
if (!parsed.ok) {
|
||||
return false;
|
||||
}
|
||||
return (
|
||||
parsed.classSuffix.length > 0 &&
|
||||
NON_EQUITY_CLASS_SUFFIX_RE.test(parsed.classSuffix.toUpperCase())
|
||||
);
|
||||
}
|
||||
|
||||
function buildUsCaEquityGateOutOfScope(
|
||||
stageBInput: SecurityMasterStageBSourceInput,
|
||||
stageB: StageBMatchResult
|
||||
): GateOutOfScopeLookup {
|
||||
const out = new Map<string, GateOutOfScopeReason>();
|
||||
|
||||
const ibById = new Map<string, StageBIbContractInput>();
|
||||
for (const contract of stageBInput.ibContracts) {
|
||||
if (contract !== undefined) {
|
||||
ibById.set(contract.sourceId, contract);
|
||||
}
|
||||
}
|
||||
const tickerByKey = new Map<string, StageBTickerSourceInput>();
|
||||
for (const entry of stageBInput.tickerSources) {
|
||||
if (entry !== undefined) {
|
||||
tickerByKey.set(sourceCountryKey(entry.source, entry.sourceId), entry);
|
||||
}
|
||||
}
|
||||
|
||||
for (const rec of stageB.unresolved) {
|
||||
const key = sourceCountryKey(rec.source, rec.sourceId);
|
||||
if (rec.source === 'qm') {
|
||||
if (rec.reason === 'missing_span') {
|
||||
out.set(key, 'zero_bar_catalog_ghost');
|
||||
continue;
|
||||
}
|
||||
const meta = tickerByKey.get(key);
|
||||
if (meta !== undefined) {
|
||||
if (meta.mic === 'XCNQ') {
|
||||
out.set(key, 'uncovered_venue');
|
||||
continue;
|
||||
}
|
||||
if (isNonEquityRecord('qm', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
}
|
||||
} else if (rec.source === 'ceo') {
|
||||
const meta = tickerByKey.get(key);
|
||||
if (meta !== undefined) {
|
||||
if (
|
||||
meta.mic === 'XCNQ' ||
|
||||
meta.mic === 'NEOE' ||
|
||||
(typeof meta.ticker === 'string' && /\.(CN|NEO)$/i.test(meta.ticker.trim()))
|
||||
) {
|
||||
out.set(key, 'uncovered_venue');
|
||||
continue;
|
||||
}
|
||||
if (isNonEquityRecord('ceo', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
}
|
||||
} else if (rec.source === 'ib') {
|
||||
const meta = ibById.get(rec.sourceId);
|
||||
if (meta !== undefined) {
|
||||
if (isNonEquityRecord('ib', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
continue;
|
||||
}
|
||||
if (meta.exchangeId === 'AEQLIT' && meta.currency === 'CAD') {
|
||||
out.set(key, 'uncovered_venue');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const conflict of stageB.conflicts) {
|
||||
const key = sourceCountryKey(conflict.source, conflict.sourceId);
|
||||
if (out.has(key)) {
|
||||
continue;
|
||||
}
|
||||
if (conflict.source === 'ib') {
|
||||
const meta = ibById.get(conflict.sourceId);
|
||||
if (meta !== undefined && isNonEquityRecord('ib', meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
} else if (conflict.source === 'qm' || conflict.source === 'ceo') {
|
||||
const meta = tickerByKey.get(key);
|
||||
if (meta !== undefined) {
|
||||
if (meta.mic === 'XCNQ' || (conflict.source === 'ceo' && meta.mic === 'NEOE')) {
|
||||
out.set(key, 'uncovered_venue');
|
||||
} else if (isNonEquityRecord(conflict.source, meta.ticker, meta.name)) {
|
||||
out.set(key, 'non_equity_instrument');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
const gateOutOfScope =
|
||||
options.report?.applyUsCaEquityGateDenominator === true
|
||||
? buildUsCaEquityGateOutOfScope(attached.stageBInput, stageB)
|
||||
: undefined;
|
||||
|
||||
const baseReport = buildMatchReport(
|
||||
{
|
||||
...(input.exchanges !== undefined ? { exchanges: input.exchanges } : {}),
|
||||
|
|
@ -1183,6 +1326,12 @@ export function composeSecurityMasterRun(
|
|||
...(pass4 !== null ? { priceCrossCheck: pass4 } : {}),
|
||||
delistingChains: pass6,
|
||||
sourceCountries,
|
||||
...(gateOutOfScope !== undefined
|
||||
? {
|
||||
gateOutOfScope,
|
||||
gateDenominatorNote: US_CA_EQUITY_GATE_DENOMINATOR_NOTE,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
options.report
|
||||
);
|
||||
|
|
@ -1208,6 +1357,29 @@ export function composeSecurityMasterRun(
|
|||
sortedSecurityTypeByIsin.set(entry[0], entry[1]);
|
||||
}
|
||||
}
|
||||
if (
|
||||
options.stageA?.allowIdentifierlessEod === true &&
|
||||
Array.isArray(input.sources.securityTypeRecords)
|
||||
) {
|
||||
const syntheticEntries: Array<[string, SecurityType]> = [];
|
||||
for (const rec of input.sources.securityTypeRecords) {
|
||||
if (rec !== undefined && rec.isin === null && typeof rec.sourceId === 'string') {
|
||||
const mapped = classifyEodSecurityType(rec.rawType);
|
||||
if (mapped !== null) {
|
||||
syntheticEntries.push([
|
||||
`${SYNTHETIC_EOD_ISIN_PREFIX}${rec.sourceId.trim().toUpperCase()}`,
|
||||
mapped,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
syntheticEntries.sort((a, b) => compareAscii(a[0], b[0]));
|
||||
for (const [k, v] of syntheticEntries) {
|
||||
if (!sortedSecurityTypeByIsin.has(k)) {
|
||||
sortedSecurityTypeByIsin.set(k, v);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const persistInput: PersistSecurityMasterInput = {
|
||||
stageA,
|
||||
|
|
@ -1222,7 +1394,7 @@ export function composeSecurityMasterRun(
|
|||
let stageAUnresolved = 0;
|
||||
for (const source of STAGE_A_SOURCES) {
|
||||
const s = stageA.stats.bySource[source];
|
||||
stageAResolved += s.tier1Isin + s.tier2Cusip;
|
||||
stageAResolved += s.tier1Isin + s.tier2Cusip + (s.tier3Synthetic ?? 0);
|
||||
stageAUnresolved += s.unresolved + s.conflict;
|
||||
}
|
||||
const stageAStepStats: StageAComposeStepStats = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,915 @@
|
|||
import { compareAscii } from './exchange-pass1';
|
||||
import type {
|
||||
ReadOnlySourceSymbolCursor,
|
||||
ReadOnlySourceSymbolReader,
|
||||
SourceSymbolFindOptions,
|
||||
} from './source-symbol-readers';
|
||||
|
||||
export const FIELD_SHAPE_PROBE_COLLECTIONS = Object.freeze([
|
||||
'ceoShorts',
|
||||
'qmSplits',
|
||||
'qmDividends',
|
||||
'qmFilings',
|
||||
'qmEarnings',
|
||||
'qmPrices',
|
||||
'eodPrices',
|
||||
'teMarketData',
|
||||
] as const);
|
||||
|
||||
export type FieldShapeProbeCollection = (typeof FIELD_SHAPE_PROBE_COLLECTIONS)[number];
|
||||
|
||||
export const FIELD_VALUE_TYPES = Object.freeze([
|
||||
'string',
|
||||
'int',
|
||||
'double',
|
||||
'bool',
|
||||
'date',
|
||||
'null',
|
||||
'objectId',
|
||||
'array',
|
||||
'object',
|
||||
'other',
|
||||
] as const);
|
||||
|
||||
export type FieldValueType = (typeof FIELD_VALUE_TYPES)[number];
|
||||
|
||||
export const STRING_PATTERN_CLASSES = Object.freeze([
|
||||
'ymd',
|
||||
'isoDatetime',
|
||||
'numeric',
|
||||
'emptyOrWhitespace',
|
||||
'other',
|
||||
] as const);
|
||||
|
||||
export type StringPatternClass = (typeof STRING_PATTERN_CLASSES)[number];
|
||||
|
||||
export const DEFAULT_FIELD_SHAPE_LIMIT = 1_000;
|
||||
export const MAX_FIELD_SHAPE_LIMIT = 10_000;
|
||||
export const DEFAULT_MAX_EXAMPLES = 3;
|
||||
export const MAX_EXAMPLES_CAP = 10;
|
||||
export const DEFAULT_MAX_EXAMPLE_LENGTH = 48;
|
||||
export const MAX_EXAMPLE_LENGTH_CAP = 120;
|
||||
|
||||
const ALLOWED_PROBE_COLLECTION_SET: ReadonlySet<string> = new Set<string>(
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS
|
||||
);
|
||||
|
||||
export class UnknownProbeCollectionError extends Error {
|
||||
readonly collectionName: string;
|
||||
readonly allowedCollections: readonly FieldShapeProbeCollection[];
|
||||
|
||||
constructor(collectionName: string) {
|
||||
super(
|
||||
`Unknown probe collection "${collectionName}". Allowed collections: ${FIELD_SHAPE_PROBE_COLLECTIONS.join(', ')}`
|
||||
);
|
||||
this.name = 'UnknownProbeCollectionError';
|
||||
this.collectionName = collectionName;
|
||||
this.allowedCollections = FIELD_SHAPE_PROBE_COLLECTIONS;
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export type FieldValueTypeCounts = Record<FieldValueType, number>;
|
||||
export type StringPatternCounts = Record<StringPatternClass, number>;
|
||||
|
||||
export interface FieldStringStats {
|
||||
minLength: number;
|
||||
maxLength: number;
|
||||
patterns: StringPatternCounts;
|
||||
}
|
||||
|
||||
export interface FieldShapeSummary {
|
||||
field: string;
|
||||
presentCount: number;
|
||||
missingCount: number;
|
||||
typeCounts: FieldValueTypeCounts;
|
||||
stringStats: FieldStringStats | null;
|
||||
examples: string[];
|
||||
}
|
||||
|
||||
export interface SummarizeFieldShapesOptions {
|
||||
readonly maxExamples?: number;
|
||||
readonly maxExampleLength?: number;
|
||||
}
|
||||
|
||||
export interface CollectionFieldShapesSummary {
|
||||
docCount: number;
|
||||
fields: FieldShapeSummary[];
|
||||
}
|
||||
|
||||
export interface ReadFieldShapesOptions extends SummarizeFieldShapesOptions {
|
||||
readonly collections?: readonly string[];
|
||||
readonly limit?: number;
|
||||
readonly batchSize?: number;
|
||||
}
|
||||
|
||||
export interface CollectionFieldShapesProbeResult extends CollectionFieldShapesSummary {
|
||||
collection: FieldShapeProbeCollection;
|
||||
}
|
||||
|
||||
export interface ReadFieldShapesResult {
|
||||
limit: number;
|
||||
maxExamples: number;
|
||||
maxExampleLength: number;
|
||||
totalDocsSampled: number;
|
||||
collections: CollectionFieldShapesProbeResult[];
|
||||
}
|
||||
|
||||
const EXACT_YMD_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
const STRICT_ISO_DATETIME_PATTERN =
|
||||
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,9})?(?:Z|([+-])(\d{2}):?(\d{2}))?$/;
|
||||
const NUMERIC_STRING_PATTERN = /^[+-]?(?:\d+(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?$/;
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
function isValidCalendarDate(year: number, month: number, day: number): boolean {
|
||||
if (year < 1 || year > 9999 || month < 1 || month > 12) {
|
||||
return false;
|
||||
}
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : (DAYS_IN_MONTH[month] ?? 0);
|
||||
return day >= 1 && day <= maxDay;
|
||||
}
|
||||
|
||||
function isValidYmd(value: string): boolean {
|
||||
if (!EXACT_YMD_PATTERN.test(value)) {
|
||||
return false;
|
||||
}
|
||||
const year =
|
||||
(value.charCodeAt(0) - 48) * 1000 +
|
||||
(value.charCodeAt(1) - 48) * 100 +
|
||||
(value.charCodeAt(2) - 48) * 10 +
|
||||
(value.charCodeAt(3) - 48);
|
||||
const month = (value.charCodeAt(5) - 48) * 10 + (value.charCodeAt(6) - 48);
|
||||
const day = (value.charCodeAt(8) - 48) * 10 + (value.charCodeAt(9) - 48);
|
||||
return isValidCalendarDate(year, month, day);
|
||||
}
|
||||
|
||||
function isValidIsoDatetime(value: string): boolean {
|
||||
const match = STRICT_ISO_DATETIME_PATTERN.exec(value);
|
||||
if (match === null) {
|
||||
return false;
|
||||
}
|
||||
const year = Number(match[1]);
|
||||
const month = Number(match[2]);
|
||||
const day = Number(match[3]);
|
||||
const hour = Number(match[4]);
|
||||
const minute = Number(match[5]);
|
||||
const second = Number(match[6]);
|
||||
|
||||
if (!isValidCalendarDate(year, month, day)) {
|
||||
return false;
|
||||
}
|
||||
if (hour > 23 || minute > 59 || second > 59) {
|
||||
return false;
|
||||
}
|
||||
if (match[7] !== undefined) {
|
||||
const tzHour = Number(match[8]);
|
||||
const tzMinute = Number(match[9]);
|
||||
if (tzHour > 23 || tzMinute > 59) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function classifyStringPattern(value: string): StringPatternClass {
|
||||
if (value.length === 0 || value.trim().length === 0) {
|
||||
return 'emptyOrWhitespace';
|
||||
}
|
||||
if (value.length === 10 && isValidYmd(value)) {
|
||||
return 'ymd';
|
||||
}
|
||||
if (value.length >= 19 && value.charCodeAt(10) === 84 && isValidIsoDatetime(value)) {
|
||||
return 'isoDatetime';
|
||||
}
|
||||
if (NUMERIC_STRING_PATTERN.test(value)) {
|
||||
return 'numeric';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
function createEmptyTypeCounts(): FieldValueTypeCounts {
|
||||
return {
|
||||
string: 0,
|
||||
int: 0,
|
||||
double: 0,
|
||||
bool: 0,
|
||||
date: 0,
|
||||
null: 0,
|
||||
objectId: 0,
|
||||
array: 0,
|
||||
object: 0,
|
||||
other: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function createEmptyStringPatternCounts(): StringPatternCounts {
|
||||
return {
|
||||
ymd: 0,
|
||||
isoDatetime: 0,
|
||||
numeric: 0,
|
||||
emptyOrWhitespace: 0,
|
||||
other: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function isNonPlainBuiltInObject(value: object): boolean {
|
||||
return (
|
||||
value instanceof Date ||
|
||||
Array.isArray(value) ||
|
||||
ArrayBuffer.isView(value) ||
|
||||
value instanceof ArrayBuffer ||
|
||||
value instanceof RegExp ||
|
||||
value instanceof Map ||
|
||||
value instanceof Set
|
||||
);
|
||||
}
|
||||
|
||||
function getBsonTypeTag(value: object): string | null {
|
||||
const tag = (value as { _bsontype?: unknown })._bsontype;
|
||||
return typeof tag === 'string' && tag.length > 0 ? tag : null;
|
||||
}
|
||||
|
||||
function isPlainNestedObject(value: unknown): value is Record<string, unknown> {
|
||||
if (value === null || typeof value !== 'object') {
|
||||
return false;
|
||||
}
|
||||
if (isNonPlainBuiltInObject(value)) {
|
||||
return false;
|
||||
}
|
||||
if (getBsonTypeTag(value) !== null) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function classifyValueType(value: unknown): FieldValueType {
|
||||
if (value === null) {
|
||||
return 'null';
|
||||
}
|
||||
const primitiveType = typeof value;
|
||||
if (primitiveType === 'string') {
|
||||
return 'string';
|
||||
}
|
||||
if (primitiveType === 'boolean') {
|
||||
return 'bool';
|
||||
}
|
||||
if (primitiveType === 'number') {
|
||||
return Number.isInteger(value) ? 'int' : 'double';
|
||||
}
|
||||
if (primitiveType === 'bigint') {
|
||||
return 'int';
|
||||
}
|
||||
if (primitiveType !== 'object') {
|
||||
return 'other';
|
||||
}
|
||||
|
||||
const obj = value as object;
|
||||
if (obj instanceof Date) {
|
||||
return 'date';
|
||||
}
|
||||
if (Array.isArray(obj)) {
|
||||
return 'array';
|
||||
}
|
||||
|
||||
const bsonTag = getBsonTypeTag(obj);
|
||||
if (bsonTag !== null) {
|
||||
if (bsonTag === 'Int32' || bsonTag === 'Long') {
|
||||
return 'int';
|
||||
}
|
||||
if (bsonTag === 'Double') {
|
||||
return 'double';
|
||||
}
|
||||
if (bsonTag === 'ObjectId' || bsonTag === 'ObjectID') {
|
||||
return 'objectId';
|
||||
}
|
||||
return 'other';
|
||||
}
|
||||
|
||||
if (isNonPlainBuiltInObject(obj)) {
|
||||
return 'other';
|
||||
}
|
||||
|
||||
return 'object';
|
||||
}
|
||||
|
||||
function escapeFieldSegment(segment: string): string {
|
||||
if (!segment.includes('.') && !segment.includes('\\')) {
|
||||
return segment;
|
||||
}
|
||||
return segment.replace(/\\/g, '\\\\').replace(/\./g, '\\.');
|
||||
}
|
||||
|
||||
function formatFieldPath(parentKey: string, childKey?: string): string {
|
||||
const escapedParent = escapeFieldSegment(parentKey);
|
||||
return childKey === undefined ? escapedParent : `${escapedParent}.${escapeFieldSegment(childKey)}`;
|
||||
}
|
||||
|
||||
function sanitizeAndTruncateExample(raw: string, maxLength: number): string {
|
||||
let cleaned = '';
|
||||
for (let i = 0; i < raw.length; i++) {
|
||||
const code = raw.charCodeAt(i);
|
||||
if (code === 9 || code === 10 || code === 13) {
|
||||
cleaned += ' ';
|
||||
} else if (code >= 32 && code !== 127) {
|
||||
cleaned += raw[i];
|
||||
}
|
||||
}
|
||||
if (cleaned.length <= maxLength) {
|
||||
return cleaned;
|
||||
}
|
||||
if (maxLength <= 3) {
|
||||
return cleaned.slice(0, maxLength);
|
||||
}
|
||||
return `${cleaned.slice(0, maxLength - 3)}...`;
|
||||
}
|
||||
|
||||
function extractScalarExample(
|
||||
value: unknown,
|
||||
valueType: FieldValueType,
|
||||
maxExampleLength: number
|
||||
): string | null {
|
||||
if (valueType === 'null' || valueType === 'array' || valueType === 'object') {
|
||||
return null;
|
||||
}
|
||||
|
||||
let raw: string | null = null;
|
||||
if (valueType === 'string') {
|
||||
raw = value as string;
|
||||
} else if (valueType === 'bool') {
|
||||
raw = (value as boolean) ? 'true' : 'false';
|
||||
} else if (valueType === 'int' || valueType === 'double') {
|
||||
if (typeof value === 'number' || typeof value === 'bigint') {
|
||||
raw = String(value);
|
||||
} else if (value !== null && typeof value === 'object') {
|
||||
raw = String(value);
|
||||
}
|
||||
} else if (valueType === 'date' && value instanceof Date) {
|
||||
raw = Number.isNaN(value.getTime()) ? 'Invalid Date' : value.toISOString();
|
||||
} else if (valueType === 'objectId') {
|
||||
raw = String(value);
|
||||
} else if (valueType === 'other' && value !== null && typeof value === 'object') {
|
||||
const bsonTag = getBsonTypeTag(value);
|
||||
if (bsonTag === 'Decimal128' || bsonTag === 'UUID') {
|
||||
raw = String(value);
|
||||
}
|
||||
}
|
||||
|
||||
if (raw === null) {
|
||||
return null;
|
||||
}
|
||||
return sanitizeAndTruncateExample(raw, maxExampleLength);
|
||||
}
|
||||
|
||||
function validateBoundedInt(value: unknown, name: string, min: number, max: number): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < min || value > max) {
|
||||
throw new RangeError(`${name} must be an integer between ${min} and ${max}, received ${String(value)}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function validatePositiveSafeInt(value: unknown, name: string): number {
|
||||
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
|
||||
throw new RangeError(`${name} must be a positive safe integer, received ${String(value)}`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function resolveSummarizeOptions(options?: SummarizeFieldShapesOptions): {
|
||||
maxExamples: number;
|
||||
maxExampleLength: number;
|
||||
} {
|
||||
if (options !== undefined && (options === null || typeof options !== 'object')) {
|
||||
throw new TypeError('options must be an object');
|
||||
}
|
||||
const maxExamples =
|
||||
options?.maxExamples !== undefined
|
||||
? validateBoundedInt(options.maxExamples, 'options.maxExamples', 0, MAX_EXAMPLES_CAP)
|
||||
: DEFAULT_MAX_EXAMPLES;
|
||||
const maxExampleLength =
|
||||
options?.maxExampleLength !== undefined
|
||||
? validateBoundedInt(
|
||||
options.maxExampleLength,
|
||||
'options.maxExampleLength',
|
||||
1,
|
||||
MAX_EXAMPLE_LENGTH_CAP
|
||||
)
|
||||
: DEFAULT_MAX_EXAMPLE_LENGTH;
|
||||
return { maxExamples, maxExampleLength };
|
||||
}
|
||||
|
||||
interface MutableFieldAccumulator {
|
||||
presentCount: number;
|
||||
typeCounts: FieldValueTypeCounts;
|
||||
stringStats: FieldStringStats | null;
|
||||
examples: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming, order-independent field-shape accumulator shared by `summarizeFieldShapes`
|
||||
* and `readFieldShapes`. Keeps O(`maxExamples`) distinct ASCII-smallest examples per field.
|
||||
*/
|
||||
class FieldShapeAccumulator {
|
||||
private readonly maxExamples: number;
|
||||
private readonly maxExampleLength: number;
|
||||
private readonly fields = new Map<string, MutableFieldAccumulator>();
|
||||
private docCount = 0;
|
||||
|
||||
constructor(maxExamples: number, maxExampleLength: number) {
|
||||
this.maxExamples = maxExamples;
|
||||
this.maxExampleLength = maxExampleLength;
|
||||
}
|
||||
|
||||
addDocument(doc: unknown): void {
|
||||
this.docCount += 1;
|
||||
if (!isPlainNestedObject(doc)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const keys = Object.keys(doc);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
if (key === undefined) {
|
||||
continue;
|
||||
}
|
||||
const value = doc[key];
|
||||
if (value === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const suppressExamples = key === '_id';
|
||||
const valueType = this.recordFieldValue(formatFieldPath(key), value, suppressExamples);
|
||||
if (valueType === 'object' && isPlainNestedObject(value)) {
|
||||
const childKeys = Object.keys(value);
|
||||
for (let j = 0; j < childKeys.length; j++) {
|
||||
const childKey = childKeys[j];
|
||||
if (childKey === undefined) {
|
||||
continue;
|
||||
}
|
||||
const childValue = value[childKey];
|
||||
if (childValue === undefined) {
|
||||
continue;
|
||||
}
|
||||
this.recordFieldValue(formatFieldPath(key, childKey), childValue, suppressExamples);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
finalize(): CollectionFieldShapesSummary {
|
||||
const sortedNames = Array.from(this.fields.keys()).sort(compareAscii);
|
||||
const summaries: FieldShapeSummary[] = [];
|
||||
for (let i = 0; i < sortedNames.length; i++) {
|
||||
const fieldName = sortedNames[i];
|
||||
if (fieldName === undefined) {
|
||||
continue;
|
||||
}
|
||||
const acc = this.fields.get(fieldName);
|
||||
if (acc === undefined) {
|
||||
continue;
|
||||
}
|
||||
summaries.push({
|
||||
field: fieldName,
|
||||
presentCount: acc.presentCount,
|
||||
missingCount: this.docCount - acc.presentCount,
|
||||
typeCounts: { ...acc.typeCounts },
|
||||
stringStats:
|
||||
acc.stringStats === null
|
||||
? null
|
||||
: {
|
||||
minLength: acc.stringStats.minLength,
|
||||
maxLength: acc.stringStats.maxLength,
|
||||
patterns: { ...acc.stringStats.patterns },
|
||||
},
|
||||
examples: [...acc.examples],
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
docCount: this.docCount,
|
||||
fields: summaries,
|
||||
};
|
||||
}
|
||||
|
||||
private recordFieldValue(
|
||||
fieldPath: string,
|
||||
value: unknown,
|
||||
suppressExamples: boolean
|
||||
): FieldValueType {
|
||||
let acc = this.fields.get(fieldPath);
|
||||
if (acc === undefined) {
|
||||
acc = {
|
||||
presentCount: 0,
|
||||
typeCounts: createEmptyTypeCounts(),
|
||||
stringStats: null,
|
||||
examples: [],
|
||||
};
|
||||
this.fields.set(fieldPath, acc);
|
||||
}
|
||||
|
||||
const valueType = classifyValueType(value);
|
||||
acc.presentCount += 1;
|
||||
acc.typeCounts[valueType] += 1;
|
||||
|
||||
if (valueType === 'string') {
|
||||
const str = value as string;
|
||||
const len = str.length;
|
||||
if (acc.stringStats === null) {
|
||||
acc.stringStats = {
|
||||
minLength: len,
|
||||
maxLength: len,
|
||||
patterns: createEmptyStringPatternCounts(),
|
||||
};
|
||||
} else {
|
||||
if (len < acc.stringStats.minLength) {
|
||||
acc.stringStats.minLength = len;
|
||||
}
|
||||
if (len > acc.stringStats.maxLength) {
|
||||
acc.stringStats.maxLength = len;
|
||||
}
|
||||
}
|
||||
acc.stringStats.patterns[classifyStringPattern(str)] += 1;
|
||||
}
|
||||
|
||||
if (this.maxExamples > 0 && !suppressExamples) {
|
||||
const example = extractScalarExample(value, valueType, this.maxExampleLength);
|
||||
if (example !== null) {
|
||||
this.insertExample(acc.examples, example);
|
||||
}
|
||||
}
|
||||
|
||||
return valueType;
|
||||
}
|
||||
|
||||
private insertExample(examples: string[], candidate: string): void {
|
||||
const len = examples.length;
|
||||
const last = len > 0 ? examples[len - 1] : undefined;
|
||||
if (len === this.maxExamples && last !== undefined && compareAscii(candidate, last) >= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let insertAt = len;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const existing = examples[i];
|
||||
if (existing === undefined) {
|
||||
continue;
|
||||
}
|
||||
const cmp = compareAscii(candidate, existing);
|
||||
if (cmp === 0) {
|
||||
return;
|
||||
}
|
||||
if (cmp < 0) {
|
||||
insertAt = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
examples.splice(insertAt, 0, candidate);
|
||||
if (examples.length > this.maxExamples) {
|
||||
examples.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, deterministic summarizer for field names, BSON/JS value types, string patterns,
|
||||
* and bounded sanitized examples across an iterable of documents from one collection.
|
||||
*/
|
||||
export function summarizeFieldShapes(
|
||||
docs: Iterable<Record<string, unknown>>,
|
||||
options?: SummarizeFieldShapesOptions
|
||||
): CollectionFieldShapesSummary {
|
||||
if (
|
||||
docs === null ||
|
||||
docs === undefined ||
|
||||
typeof (docs as unknown as Record<symbol, unknown>)[Symbol.iterator] !== 'function'
|
||||
) {
|
||||
throw new TypeError('docs must be an Iterable of document objects');
|
||||
}
|
||||
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
|
||||
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
|
||||
for (const doc of docs) {
|
||||
accumulator.addDocument(doc);
|
||||
}
|
||||
return accumulator.finalize();
|
||||
}
|
||||
|
||||
export function isFieldShapeProbeCollection(value: string): value is FieldShapeProbeCollection {
|
||||
return ALLOWED_PROBE_COLLECTION_SET.has(value);
|
||||
}
|
||||
|
||||
export function normalizeProbeCollections(
|
||||
collections?: readonly string[]
|
||||
): FieldShapeProbeCollection[] {
|
||||
const source = collections === undefined ? FIELD_SHAPE_PROBE_COLLECTIONS : collections;
|
||||
if (!Array.isArray(source) || source.length === 0) {
|
||||
throw new RangeError('collections must be a non-empty array of allowed probe collection names');
|
||||
}
|
||||
const unique = new Set<FieldShapeProbeCollection>();
|
||||
for (let i = 0; i < source.length; i++) {
|
||||
const name = source[i];
|
||||
if (typeof name !== 'string' || !isFieldShapeProbeCollection(name)) {
|
||||
throw new UnknownProbeCollectionError(String(name));
|
||||
}
|
||||
unique.add(name);
|
||||
}
|
||||
return Array.from(unique).sort(compareAscii);
|
||||
}
|
||||
|
||||
function assertReadOnlyReader(reader: ReadOnlySourceSymbolReader): void {
|
||||
if (
|
||||
reader === null ||
|
||||
reader === undefined ||
|
||||
typeof reader !== 'object' ||
|
||||
typeof reader.isReadOnly !== 'function' ||
|
||||
typeof reader.find !== 'function' ||
|
||||
reader.isReadOnly() !== true
|
||||
) {
|
||||
throw new Error(
|
||||
'Source field-shape probe requires a read-only MongoDB reader (isReadOnly() must be true)'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function isAsyncIterable<T>(value: unknown): value is AsyncIterable<T> {
|
||||
return (
|
||||
value !== null &&
|
||||
(typeof value === 'object' || typeof value === 'function') &&
|
||||
typeof (value as Record<symbol, unknown>)[Symbol.asyncIterator] === 'function'
|
||||
);
|
||||
}
|
||||
|
||||
function wrapCollectionReadError(collectionName: string, error: unknown): Error {
|
||||
const detail = error instanceof Error ? error.message : String(error);
|
||||
const message = detail.includes(collectionName)
|
||||
? detail
|
||||
: `Failed reading collection "${collectionName}": ${detail}`;
|
||||
return new Error(message, { cause: error });
|
||||
}
|
||||
|
||||
async function streamBoundedCollectionIntoAccumulator(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
collectionName: FieldShapeProbeCollection,
|
||||
limit: number,
|
||||
findOptions: SourceSymbolFindOptions,
|
||||
accumulator: FieldShapeAccumulator
|
||||
): Promise<void> {
|
||||
assertReadOnlyReader(reader);
|
||||
let closableHandle: Pick<ReadOnlySourceSymbolCursor<Record<string, unknown>>, 'close'> | null =
|
||||
null;
|
||||
let primaryError: unknown = undefined;
|
||||
let hasPrimaryError = false;
|
||||
let isInvalidCursorError = false;
|
||||
|
||||
try {
|
||||
const rawCursor = await reader.find<Record<string, unknown>>(collectionName, {}, findOptions);
|
||||
if (
|
||||
rawCursor !== null &&
|
||||
(typeof rawCursor === 'object' || typeof rawCursor === 'function')
|
||||
) {
|
||||
closableHandle = rawCursor as Pick<
|
||||
ReadOnlySourceSymbolCursor<Record<string, unknown>>,
|
||||
'close'
|
||||
>;
|
||||
}
|
||||
if (Array.isArray(rawCursor) || !isAsyncIterable<Record<string, unknown>>(rawCursor)) {
|
||||
isInvalidCursorError = true;
|
||||
throw new TypeError(
|
||||
`Reader for collection "${collectionName}" must return an incremental AsyncIterable cursor (got buffered or non-async result)`
|
||||
);
|
||||
}
|
||||
|
||||
let seen = 0;
|
||||
if (limit > 0) {
|
||||
for await (const doc of rawCursor) {
|
||||
accumulator.addDocument(doc);
|
||||
seen += 1;
|
||||
if (seen >= limit) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
primaryError = error;
|
||||
hasPrimaryError = true;
|
||||
} finally {
|
||||
if (closableHandle !== null && typeof closableHandle.close === 'function') {
|
||||
try {
|
||||
await closableHandle.close();
|
||||
} catch (closeError) {
|
||||
if (!hasPrimaryError) {
|
||||
primaryError = closeError;
|
||||
hasPrimaryError = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (hasPrimaryError) {
|
||||
if (isInvalidCursorError) {
|
||||
throw primaryError;
|
||||
}
|
||||
throw wrapCollectionReadError(collectionName, primaryError);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bounded, read-only MongoDB field-shape probe over allowlisted source collections.
|
||||
* Issues strictly `find({}, { limit, promoteValues: false, promoteLongs: false })`
|
||||
* with zero aggregations, `$sample`, writes, or index operations.
|
||||
*/
|
||||
export async function readFieldShapes(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
options?: ReadFieldShapesOptions
|
||||
): Promise<ReadFieldShapesResult> {
|
||||
assertReadOnlyReader(reader);
|
||||
|
||||
if (options !== undefined && (options === null || typeof options !== 'object')) {
|
||||
throw new TypeError('options must be an object');
|
||||
}
|
||||
|
||||
const limit =
|
||||
options?.limit !== undefined
|
||||
? validateBoundedInt(options.limit, 'options.limit', 1, MAX_FIELD_SHAPE_LIMIT)
|
||||
: DEFAULT_FIELD_SHAPE_LIMIT;
|
||||
const { maxExamples, maxExampleLength } = resolveSummarizeOptions(options);
|
||||
const batchSize =
|
||||
options?.batchSize !== undefined
|
||||
? validatePositiveSafeInt(options.batchSize, 'options.batchSize')
|
||||
: undefined;
|
||||
const collections = normalizeProbeCollections(options?.collections);
|
||||
|
||||
const findOptions: SourceSymbolFindOptions = {
|
||||
limit,
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
...(batchSize !== undefined ? { batchSize } : {}),
|
||||
};
|
||||
|
||||
const results: CollectionFieldShapesProbeResult[] = [];
|
||||
let totalDocsSampled = 0;
|
||||
|
||||
for (const collection of collections) {
|
||||
const accumulator = new FieldShapeAccumulator(maxExamples, maxExampleLength);
|
||||
await streamBoundedCollectionIntoAccumulator(
|
||||
reader,
|
||||
collection,
|
||||
limit,
|
||||
findOptions,
|
||||
accumulator
|
||||
);
|
||||
const summary = accumulator.finalize();
|
||||
totalDocsSampled += summary.docCount;
|
||||
results.push({
|
||||
collection,
|
||||
docCount: summary.docCount,
|
||||
fields: summary.fields,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
limit,
|
||||
maxExamples,
|
||||
maxExampleLength,
|
||||
totalDocsSampled,
|
||||
collections: results,
|
||||
};
|
||||
}
|
||||
|
||||
function formatHtmlCodeElement(value: string): string {
|
||||
const escaped = value.replace(/[&<>|\\`*_~[\]!]/g, ch => {
|
||||
switch (ch) {
|
||||
case '&':
|
||||
return '&';
|
||||
case '<':
|
||||
return '<';
|
||||
case '>':
|
||||
return '>';
|
||||
case '|':
|
||||
return '|';
|
||||
default:
|
||||
return `&#${ch.charCodeAt(0)};`;
|
||||
}
|
||||
});
|
||||
return `<code>${escaped}</code>`;
|
||||
}
|
||||
|
||||
function formatMarkdownCodeCell(value: string): string {
|
||||
const normalized = value.replace(/\r\n|\r|\n/g, ' ');
|
||||
// Empty spans cannot be written with backtick fences; values containing `\|`
|
||||
// would become `\\|` under pipe escaping, which GFM/micromark parses as an
|
||||
// escaped backslash followed by a cell-splitting pipe. Use an HTML <code>
|
||||
// element with entity-encoded pipes and Markdown metacharacters instead.
|
||||
if (normalized.length === 0 || normalized.includes('\\|')) {
|
||||
return formatHtmlCodeElement(normalized);
|
||||
}
|
||||
const tableSafe = normalized.replace(/\|/g, '\\|');
|
||||
let maxBacktickRun = 0;
|
||||
let currentRun = 0;
|
||||
for (let i = 0; i < tableSafe.length; i++) {
|
||||
if (tableSafe.charCodeAt(i) === 96) {
|
||||
currentRun += 1;
|
||||
if (currentRun > maxBacktickRun) {
|
||||
maxBacktickRun = currentRun;
|
||||
}
|
||||
} else {
|
||||
currentRun = 0;
|
||||
}
|
||||
}
|
||||
const fence = '`'.repeat(maxBacktickRun + 1);
|
||||
const startsWithBacktick = tableSafe.charCodeAt(0) === 96;
|
||||
const endsWithBacktick = tableSafe.charCodeAt(tableSafe.length - 1) === 96;
|
||||
const startsAndEndsWithSpace =
|
||||
tableSafe.charCodeAt(0) === 32 &&
|
||||
tableSafe.charCodeAt(tableSafe.length - 1) === 32 &&
|
||||
tableSafe.trim().length > 0;
|
||||
const needsPadding = startsWithBacktick || endsWithBacktick || startsAndEndsWithSpace;
|
||||
return needsPadding ? `${fence} ${tableSafe} ${fence}` : `${fence}${tableSafe}${fence}`;
|
||||
}
|
||||
|
||||
function formatTypeCountsCell(typeCounts: FieldValueTypeCounts): string {
|
||||
const parts: string[] = [];
|
||||
for (const typeName of FIELD_VALUE_TYPES) {
|
||||
const count = typeCounts[typeName];
|
||||
if (count > 0) {
|
||||
parts.push(`${typeName}: ${count}`);
|
||||
}
|
||||
}
|
||||
return parts.length > 0 ? parts.join(', ') : '—';
|
||||
}
|
||||
|
||||
function formatStringStatsCell(stringStats: FieldStringStats | null): string {
|
||||
if (stringStats === null) {
|
||||
return '—';
|
||||
}
|
||||
const parts: string[] = [];
|
||||
for (const pattern of STRING_PATTERN_CLASSES) {
|
||||
const count = stringStats.patterns[pattern];
|
||||
if (count > 0) {
|
||||
parts.push(`${pattern}: ${count}`);
|
||||
}
|
||||
}
|
||||
const patternText = parts.length > 0 ? parts.join(', ') : 'none';
|
||||
return `${patternText} (len ${stringStats.minLength}..${stringStats.maxLength})`;
|
||||
}
|
||||
|
||||
function formatExamplesCell(examples: readonly string[]): string {
|
||||
if (examples.length === 0) {
|
||||
return '—';
|
||||
}
|
||||
return examples.map(formatMarkdownCodeCell).join(', ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Renders a deterministic Markdown field-shape report (zero wall-clock timestamps or
|
||||
* filesystem paths). Identical results always produce byte-identical Markdown.
|
||||
*/
|
||||
export function renderFieldShapesMarkdown(result: ReadFieldShapesResult): string {
|
||||
const sortedCollections = [...result.collections].sort((a, b) =>
|
||||
compareAscii(a.collection, b.collection)
|
||||
);
|
||||
|
||||
const lines: string[] = [
|
||||
'# Source Field Shapes Report',
|
||||
'',
|
||||
'- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)',
|
||||
`- **Sample limit per collection:** ${result.limit}`,
|
||||
`- **Collections probed:** ${sortedCollections.length}`,
|
||||
`- **Total documents sampled:** ${result.totalDocsSampled}`,
|
||||
];
|
||||
|
||||
for (const col of sortedCollections) {
|
||||
lines.push('', `## \`${col.collection}\` (${col.docCount} docs sampled)`, '');
|
||||
|
||||
if (col.docCount === 0) {
|
||||
lines.push('_No documents sampled._');
|
||||
continue;
|
||||
}
|
||||
|
||||
const sortedFields = [...col.fields].sort((a, b) => compareAscii(a.field, b.field));
|
||||
if (sortedFields.length === 0) {
|
||||
lines.push('_No fields observed._');
|
||||
continue;
|
||||
}
|
||||
|
||||
lines.push('| Field | Presence | Types | String Patterns | Examples |');
|
||||
lines.push('| --- | --- | --- | --- | --- |');
|
||||
|
||||
for (const field of sortedFields) {
|
||||
const pct = ((field.presentCount / col.docCount) * 100).toFixed(1);
|
||||
const fieldCell = formatMarkdownCodeCell(field.field);
|
||||
const presenceCell = `${pct}% (${field.presentCount}/${col.docCount})`;
|
||||
const typesCell = formatTypeCountsCell(field.typeCounts);
|
||||
const patternsCell = formatStringStatsCell(field.stringStats);
|
||||
const examplesCell = formatExamplesCell(field.examples);
|
||||
lines.push(
|
||||
`| ${fieldCell} | ${presenceCell} | ${typesCell} | ${patternsCell} | ${examplesCell} |`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return `${lines.join('\n')}\n`;
|
||||
}
|
||||
|
|
@ -53,6 +53,9 @@ export const DEFAULT_SOURCE_COUNTRIES: readonly string[] = Object.freeze(['US',
|
|||
export interface SourceSymbolFindOptions {
|
||||
projection?: Record<string, 0 | 1>;
|
||||
batchSize?: number;
|
||||
limit?: number;
|
||||
promoteValues?: boolean;
|
||||
promoteLongs?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -161,6 +164,7 @@ export interface ReadSourceCollectionOptions {
|
|||
readonly knownExchanges?: readonly ExchangeSeedRow[];
|
||||
readonly batchSize?: number;
|
||||
readonly maxSecurityTypeConflicts?: number;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export type ReadSecurityMasterSourcesOptions = ReadSourceCollectionOptions;
|
||||
|
|
@ -175,6 +179,7 @@ export interface AdaptEodSymbolContext {
|
|||
export interface AdaptIbSymbolContext {
|
||||
readonly exchangeLookup: ExchangeSourceLookup;
|
||||
readonly allowedCountries: ReadonlySet<string> | null;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export interface AdaptQmSymbolContext {
|
||||
|
|
@ -182,6 +187,7 @@ export interface AdaptQmSymbolContext {
|
|||
readonly barSpans?: Pick<BarSpanIndex, 'get'> | null;
|
||||
readonly allowedCountries: ReadonlySet<string> | null;
|
||||
readonly micCurrencyMap: ReadonlyMap<string, string>;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export interface AdaptCeoSymbolContext {
|
||||
|
|
@ -189,6 +195,7 @@ export interface AdaptCeoSymbolContext {
|
|||
readonly ceoSpans?: ReadonlyMap<string, SpanDateRange> | null;
|
||||
readonly allowedCountries: ReadonlySet<string> | null;
|
||||
readonly micCurrencyMap: ReadonlyMap<string, string>;
|
||||
readonly includeExtendedMetadata?: boolean;
|
||||
}
|
||||
|
||||
export interface AdaptEodSymbolChangeContext {
|
||||
|
|
@ -439,7 +446,9 @@ export const CEO_SYMBOLS_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.fr
|
|||
export const EOD_SYMBOL_CHANGE_PROJECTION: Readonly<Record<string, 0 | 1>> = Object.freeze({
|
||||
_id: 0,
|
||||
oldSymbol: 1,
|
||||
old_symbol: 1,
|
||||
newSymbol: 1,
|
||||
new_symbol: 1,
|
||||
exchange: 1,
|
||||
eodExchange: 1,
|
||||
eodSearchCode: 1,
|
||||
|
|
@ -1353,6 +1362,13 @@ export function adaptIbSymbolDoc(
|
|||
conid: rawConid,
|
||||
currency,
|
||||
primaryExchange,
|
||||
...(context.includeExtendedMetadata === true
|
||||
? {
|
||||
ticker: symbolField.value,
|
||||
name,
|
||||
exchangeId: exchangeIdField.value !== null ? exchangeIdField.value.toUpperCase() : null,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
invalidIdentifiersNulled,
|
||||
};
|
||||
|
|
@ -1433,6 +1449,11 @@ export function adaptQmSymbolDoc(
|
|||
: countryFallbackCurrency(effectiveCountry);
|
||||
|
||||
const span = toSpanDateRange(context.barSpans?.get('qm', sourceId));
|
||||
const qmNameResult =
|
||||
context.includeExtendedMetadata === true
|
||||
? readFirstOptionalString(doc, ['name', 'companyName'])
|
||||
: null;
|
||||
const qmName = qmNameResult !== null && qmNameResult.ok ? qmNameResult.value : null;
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
|
|
@ -1444,6 +1465,7 @@ export function adaptQmSymbolDoc(
|
|||
role: exchangeEntry.role,
|
||||
currency,
|
||||
span,
|
||||
...(context.includeExtendedMetadata === true ? { name: qmName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1536,6 +1558,10 @@ export function adaptCeoSymbolDoc(
|
|||
}
|
||||
}
|
||||
|
||||
const ceoNameResult =
|
||||
context.includeExtendedMetadata === true ? readOptionalString(doc, 'name') : null;
|
||||
const ceoName = ceoNameResult !== null && ceoNameResult.ok ? ceoNameResult.value : null;
|
||||
|
||||
return {
|
||||
ok: true,
|
||||
tickerSource: {
|
||||
|
|
@ -1546,6 +1572,7 @@ export function adaptCeoSymbolDoc(
|
|||
role: exchangeEntry.role,
|
||||
currency,
|
||||
span,
|
||||
...(context.includeExtendedMetadata === true ? { name: ceoName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
@ -1562,8 +1589,8 @@ export function adaptEodSymbolChangeDoc(
|
|||
return { ok: false, skipReason: 'invalidFieldType' };
|
||||
}
|
||||
|
||||
const oldSymbolField = readOptionalString(doc, 'oldSymbol');
|
||||
const newSymbolField = readOptionalString(doc, 'newSymbol');
|
||||
const oldSymbolField = readFirstOptionalString(doc, ['oldSymbol', 'old_symbol']);
|
||||
const newSymbolField = readFirstOptionalString(doc, ['newSymbol', 'new_symbol']);
|
||||
const exchangeField = readOptionalString(doc, 'exchange');
|
||||
const eodExchangeField = readOptionalString(doc, 'eodExchange');
|
||||
const eodSearchCodeField = readOptionalString(doc, 'eodSearchCode');
|
||||
|
|
@ -1763,6 +1790,7 @@ export async function readIbSymbols(
|
|||
const context: AdaptIbSymbolContext = {
|
||||
exchangeLookup: options.exchangeLookup,
|
||||
allowedCountries,
|
||||
includeExtendedMetadata: options.includeExtendedMetadata,
|
||||
};
|
||||
|
||||
const stageARecords: StageASourceRecord[] = [];
|
||||
|
|
@ -1811,6 +1839,7 @@ export async function readQmSymbols(
|
|||
barSpans: options.barSpans,
|
||||
allowedCountries,
|
||||
micCurrencyMap,
|
||||
includeExtendedMetadata: options.includeExtendedMetadata,
|
||||
};
|
||||
|
||||
const tickerSources: StageBTickerSourceInput[] = [];
|
||||
|
|
@ -1843,6 +1872,26 @@ export async function readQmSymbols(
|
|||
return { tickerSources, stats };
|
||||
}
|
||||
|
||||
function expectedMicFromCeoSymbolSuffix(rawSymbol: unknown): string | null {
|
||||
if (typeof rawSymbol !== 'string') {
|
||||
return null;
|
||||
}
|
||||
const upper = rawSymbol.trim().toUpperCase();
|
||||
if (upper.endsWith('.TO')) {
|
||||
return 'XTSE';
|
||||
}
|
||||
if (upper.endsWith('.V')) {
|
||||
return 'XTSX';
|
||||
}
|
||||
if (upper.endsWith('.CN')) {
|
||||
return 'XCNQ';
|
||||
}
|
||||
if (upper.endsWith('.NEO') || upper.endsWith('.NE')) {
|
||||
return 'NEOE';
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Streams and adapts `ceoSymbols` from a read-only MongoDB reader. */
|
||||
export async function readCeoSymbols(
|
||||
reader: ReadOnlySourceSymbolReader,
|
||||
|
|
@ -1855,9 +1904,15 @@ export async function readCeoSymbols(
|
|||
ceoSpans: options.ceoSpans,
|
||||
allowedCountries,
|
||||
micCurrencyMap,
|
||||
includeExtendedMetadata: options.includeExtendedMetadata,
|
||||
};
|
||||
|
||||
const tickerSources: StageBTickerSourceInput[] = [];
|
||||
const rawEntries: Array<{
|
||||
readonly tickerSource: StageBTickerSourceInput;
|
||||
readonly rawSymbolKey: string | null;
|
||||
readonly matchesSuffixMic: boolean;
|
||||
}> = [];
|
||||
const stats = createCollectionStats(SOURCE_SYMBOL_COLLECTIONS.ceo);
|
||||
|
||||
const findOptions: SourceSymbolFindOptions = {
|
||||
|
|
@ -1877,11 +1932,59 @@ export async function readCeoSymbols(
|
|||
stats.skips[adapted.skipReason] += 1;
|
||||
return;
|
||||
}
|
||||
tickerSources.push(adapted.tickerSource);
|
||||
stats.emitted += 1;
|
||||
const rawSymbol =
|
||||
isPlainRecord(doc) && typeof doc.symbol === 'string'
|
||||
? doc.symbol.trim().toUpperCase()
|
||||
: null;
|
||||
const expectedMic = expectedMicFromCeoSymbolSuffix(rawSymbol);
|
||||
rawEntries.push({
|
||||
tickerSource: adapted.tickerSource,
|
||||
rawSymbolKey: rawSymbol !== null && rawSymbol.length > 0 ? rawSymbol : null,
|
||||
matchesSuffixMic: expectedMic !== null && adapted.tickerSource.mic === expectedMic,
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
// Deduplicate crawl artifacts where the exact same (ceoId, symbol) was ingested under
|
||||
// multiple Canadian exchange lists (e.g. ACB.TO under both TSX and CNQ). Prefer the row
|
||||
// whose mapped MIC matches the symbol's own Canadian venue suffix (.TO/.V/.CN/.NEO).
|
||||
// Distinct symbols sharing a ceoId are preserved so Stage B still flags true collisions.
|
||||
const groupedByIdAndSymbol = new Map<string, typeof rawEntries>();
|
||||
for (const entry of rawEntries) {
|
||||
if (entry.rawSymbolKey === null) {
|
||||
tickerSources.push(entry.tickerSource);
|
||||
stats.emitted += 1;
|
||||
continue;
|
||||
}
|
||||
const key = `${entry.tickerSource.sourceId}\u0000${entry.rawSymbolKey}`;
|
||||
const existing = groupedByIdAndSymbol.get(key);
|
||||
if (existing !== undefined) {
|
||||
existing.push(entry);
|
||||
} else {
|
||||
groupedByIdAndSymbol.set(key, [entry]);
|
||||
}
|
||||
}
|
||||
|
||||
for (const entries of groupedByIdAndSymbol.values()) {
|
||||
const first = entries[0];
|
||||
if (first === undefined) {
|
||||
continue;
|
||||
}
|
||||
if (entries.length === 1) {
|
||||
tickerSources.push(first.tickerSource);
|
||||
stats.emitted += 1;
|
||||
continue;
|
||||
}
|
||||
const suffixMatched = entries.filter(e => e.matchesSuffixMic);
|
||||
const chosen =
|
||||
suffixMatched.length === 1 && suffixMatched[0] !== undefined
|
||||
? suffixMatched[0]
|
||||
: ([...entries].sort((a, b) => compareTickerSources(a.tickerSource, b.tickerSource))[0] ??
|
||||
first);
|
||||
tickerSources.push(chosen.tickerSource);
|
||||
stats.emitted += 1;
|
||||
}
|
||||
|
||||
tickerSources.sort(compareTickerSources);
|
||||
|
||||
return { tickerSources, stats };
|
||||
|
|
|
|||
293
apps/stock/data-pipeline/test/export-raw-bson-qa.test.ts
Normal file
293
apps/stock/data-pipeline/test/export-raw-bson-qa.test.ts
Normal file
|
|
@ -0,0 +1,293 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
createReadOnlyMongoRawBsonSource,
|
||||
exportRawBsonCollection,
|
||||
RawBsonExportError,
|
||||
validateRawBsonFrame,
|
||||
walkRawBsonFrames,
|
||||
type ExportRawBsonFsHooks,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
type ReadOnlyRawBsonSource,
|
||||
} from '../src/security-master/export-raw-bson';
|
||||
import { runExportRawBson } from '../src/security-master/run-export-raw-bson';
|
||||
|
||||
function sha256Hex(bytes: Uint8Array): string {
|
||||
return createHash('sha256').update(bytes).digest('hex');
|
||||
}
|
||||
|
||||
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
|
||||
const out = new Uint8Array(chunks.reduce((acc, c) => acc + c.byteLength, 0));
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
out.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function sourceOf(docs: readonly unknown[], onYield?: () => void): ReadOnlyRawBsonSource {
|
||||
return {
|
||||
isReadOnly: () => true,
|
||||
find: () => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
onYield?.();
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-qa-'));
|
||||
try {
|
||||
return await fn(dir);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The mongodb 6.x driver returns `raw: true` documents as `subarray` views into the shared
|
||||
* wire-reply buffer (`OnDemandDocument.toBytes`), so frames have non-zero `byteOffset` and
|
||||
* neighbouring bytes belong to other documents / reply headers.
|
||||
*/
|
||||
function packAsReplyViews(docs: readonly Uint8Array[]): Uint8Array[] {
|
||||
const junk = new Uint8Array([0xde, 0xad, 0xbe, 0xef, 0x07]);
|
||||
const reply = concatBytes(docs.flatMap(d => [junk, d]).concat([junk]));
|
||||
const views: Uint8Array[] = [];
|
||||
let offset = 0;
|
||||
for (const doc of docs) {
|
||||
offset += junk.byteLength;
|
||||
views.push(Buffer.from(reply.buffer, reply.byteOffset + offset, doc.byteLength));
|
||||
offset += doc.byteLength;
|
||||
}
|
||||
return views;
|
||||
}
|
||||
|
||||
describe('exportRawBsonCollection (QA edge cases)', () => {
|
||||
test('writes only the frame bytes when raw documents are offset views into a shared reply buffer (buffered and direct-write paths, real fs)', async () => {
|
||||
const small = Array.from({ length: 40 }, (_, i) =>
|
||||
Uint8Array.from(BSON.serialize({ eodSearchCode: `S${i}.US`, close: i + 0.5 }))
|
||||
);
|
||||
const large = Uint8Array.from(BSON.serialize({ eodSearchCode: 'BIG.US', pad: 'z'.repeat(300) }));
|
||||
const originals = [...small.slice(0, 20), large, ...small.slice(20)];
|
||||
const views = packAsReplyViews(originals);
|
||||
expect(views.every(v => v.byteOffset > 0)).toBe(true);
|
||||
const expected = concatBytes(originals);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const result = await exportRawBsonCollection(sourceOf(views), {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
writeBufferBytes: 128,
|
||||
});
|
||||
|
||||
const fileBytes = Uint8Array.from(await readFile(result.outPath));
|
||||
expect(fileBytes).toEqual(expected);
|
||||
expect(result.sha256).toBe(sha256Hex(expected));
|
||||
expect(result.docsWritten).toBe(originals.length);
|
||||
expect(walkRawBsonFrames(fileBytes).map(f => BSON.deserialize(f))).toEqual(
|
||||
originals.map(o => BSON.deserialize(o))
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('flushes correctly when frames exactly fill the write buffer', async () => {
|
||||
const doc = Uint8Array.from(BSON.serialize({ k: 'v' }));
|
||||
const writeBufferBytes = Math.max(64, doc.byteLength * 4);
|
||||
const perBuffer = Math.floor(writeBufferBytes / doc.byteLength);
|
||||
const docs = Array.from({ length: perBuffer * 3 }, () => doc);
|
||||
const writes: number[] = [];
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const fsHooks: ExportRawBsonFsHooks = {
|
||||
open: async () => ({
|
||||
write: async (_b, _o, len) => {
|
||||
writes.push(len ?? 0);
|
||||
return { bytesWritten: len ?? 0 };
|
||||
},
|
||||
sync: async () => {},
|
||||
close: async () => {},
|
||||
}),
|
||||
rename: async () => {},
|
||||
unlink: async () => {},
|
||||
};
|
||||
const result = await exportRawBsonCollection(sourceOf(docs), {
|
||||
collection: 'qmEarnings',
|
||||
outDir,
|
||||
writeBufferBytes,
|
||||
fs: fsHooks,
|
||||
});
|
||||
expect(result.bytesWritten).toBe(doc.byteLength * docs.length);
|
||||
expect(writes.reduce((a, b) => a + b, 0)).toBe(result.bytesWritten);
|
||||
expect(writes.every(w => w <= writeBufferBytes)).toBe(true);
|
||||
expect(writes).toHaveLength(3);
|
||||
});
|
||||
});
|
||||
|
||||
test('completes partial writes by continuing from the reported offset', async () => {
|
||||
const docs = Array.from({ length: 10 }, (_, i) => Uint8Array.from(BSON.serialize({ i })));
|
||||
const expected = concatBytes(docs);
|
||||
const received: Uint8Array[] = [];
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const fsHooks: ExportRawBsonFsHooks = {
|
||||
open: async () => ({
|
||||
write: async (buf, off, len) => {
|
||||
const start = off ?? 0;
|
||||
const n = Math.min(len ?? 0, 7);
|
||||
received.push(Uint8Array.from(buf.subarray(start, start + n)));
|
||||
return { bytesWritten: n };
|
||||
},
|
||||
sync: async () => {},
|
||||
close: async () => {},
|
||||
}),
|
||||
rename: async () => {},
|
||||
unlink: async () => {},
|
||||
};
|
||||
const result = await exportRawBsonCollection(sourceOf(docs), {
|
||||
collection: 'qmSplits',
|
||||
outDir,
|
||||
writeBufferBytes: 64,
|
||||
fs: fsHooks,
|
||||
});
|
||||
expect(concatBytes(received)).toEqual(expected);
|
||||
expect(result.sha256).toBe(sha256Hex(expected));
|
||||
});
|
||||
});
|
||||
|
||||
test('stops pulling from the source once limit is reached', async () => {
|
||||
const docs = Array.from({ length: 50 }, (_, i) => Uint8Array.from(BSON.serialize({ i })));
|
||||
let pulled = 0;
|
||||
await withTempDir(async outDir => {
|
||||
const result = await exportRawBsonCollection(
|
||||
sourceOf(docs, () => {
|
||||
pulled += 1;
|
||||
}),
|
||||
{ collection: 'eodPrices', outDir, limit: 3 }
|
||||
);
|
||||
expect(result.docsWritten).toBe(3);
|
||||
expect(pulled).toBe(3);
|
||||
expect(Uint8Array.from(await readFile(result.outPath))).toEqual(concatBytes(docs.slice(0, 3)));
|
||||
});
|
||||
});
|
||||
|
||||
test('creates a missing nested out-dir and leaves no temp files after success', async () => {
|
||||
await withTempDir(async root => {
|
||||
const outDir = join(root, 'a', 'b');
|
||||
const doc = Uint8Array.from(BSON.serialize({ x: 1 }));
|
||||
const result = await exportRawBsonCollection(sourceOf([doc]), { collection: 'qmFilings', outDir });
|
||||
expect(await readdir(outDir)).toEqual(['qmFilings.bson']);
|
||||
expect(result.outPath).toBe(join(outDir, 'qmFilings.bson'));
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects frames whose length prefix has the sign bit set (negative int32)', () => {
|
||||
const frame = new Uint8Array([0xff, 0xff, 0xff, 0xff, 0x00]);
|
||||
expect(() => validateRawBsonFrame(frame, 'eodPrices', 7)).toThrow(RawBsonExportError);
|
||||
expect(() => walkRawBsonFrames(frame)).toThrow(/corrupt BSON document length -1/);
|
||||
});
|
||||
|
||||
test('walkRawBsonFrames rejects truncated trailing bytes like curate-etl iter_raw_bson_docs', () => {
|
||||
const doc = Uint8Array.from(BSON.serialize({ a: 1 }));
|
||||
expect(() => walkRawBsonFrames(concatBytes([doc, new Uint8Array([1, 2])]))).toThrow(
|
||||
/truncated BSON length prefix/
|
||||
);
|
||||
expect(() => walkRawBsonFrames(concatBytes([doc, doc.subarray(0, doc.byteLength - 1)]))).toThrow(
|
||||
/truncated BSON document/
|
||||
);
|
||||
expect(walkRawBsonFrames(new Uint8Array())).toEqual([]);
|
||||
});
|
||||
|
||||
test('rejects out-of-range writeBufferBytes, batchSize and limit before any fs or source call', async () => {
|
||||
const openMock = mock(async () => {
|
||||
throw new Error('open must not be called');
|
||||
});
|
||||
const findMock = mock(() => {
|
||||
throw new Error('find must not be called');
|
||||
});
|
||||
const source: ReadOnlyRawBsonSource = { isReadOnly: () => true, find: findMock };
|
||||
const bad = [
|
||||
{ writeBufferBytes: 63 },
|
||||
{ writeBufferBytes: 64 * 1024 * 1024 + 1 },
|
||||
{ writeBufferBytes: 100.5 },
|
||||
{ batchSize: 0 },
|
||||
{ batchSize: 100_001 },
|
||||
{ limit: 0 },
|
||||
{ limit: -1 },
|
||||
{ maxDocBytes: 4 },
|
||||
{ eodSymbol: ' ' },
|
||||
];
|
||||
for (const opts of bad) {
|
||||
await expect(
|
||||
exportRawBsonCollection(source, { collection: 'eodPrices', outDir: '/tmp/unused', fs: { open: openMock }, ...opts })
|
||||
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
|
||||
}
|
||||
await expect(
|
||||
exportRawBsonCollection(source, { collection: 'eodPrices', outDir: ' ', fs: { open: openMock } })
|
||||
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
|
||||
expect(openMock).not.toHaveBeenCalled();
|
||||
expect(findMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('runExportRawBson multi-collection (QA edge cases)', () => {
|
||||
test('a failure in a later collection keeps earlier published files, preserves that collection\'s previous output, and closes the client once', async () => {
|
||||
await withTempDir(async outDir => {
|
||||
const splitsDoc = Uint8Array.from(BSON.serialize({ split: '2:1' }));
|
||||
const previousDividends = Uint8Array.from(BSON.serialize({ previous: true }));
|
||||
await writeFile(join(outDir, 'qmDividends.bson'), previousDividends);
|
||||
const closeMongo = mock(async () => {});
|
||||
const findCalls: string[] = [];
|
||||
|
||||
const client: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: name => ({
|
||||
find: () => {
|
||||
findCalls.push(name);
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
if (name === 'qmSplits') {
|
||||
yield splitsDoc;
|
||||
return;
|
||||
}
|
||||
yield new Uint8Array([9, 0, 0, 0, 0]);
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
await expect(
|
||||
runExportRawBson(
|
||||
{ createMongoClient: () => ({ client, close: closeMongo }), writeStdout: () => {} },
|
||||
{ outDir, collections: ['qmSplits', 'qmDividends', 'qmEarnings'] }
|
||||
)
|
||||
).rejects.toMatchObject({ code: 'INVALID_BSON_FRAME', collection: 'qmDividends', docOrdinal: 0 });
|
||||
|
||||
expect(findCalls).toEqual(['qmSplits', 'qmDividends']);
|
||||
expect(closeMongo).toHaveBeenCalledTimes(1);
|
||||
expect((await readdir(outDir)).sort()).toEqual(['qmDividends.bson', 'qmSplits.bson']);
|
||||
expect(Uint8Array.from(await readFile(join(outDir, 'qmSplits.bson')))).toEqual(splitsDoc);
|
||||
expect(Uint8Array.from(await readFile(join(outDir, 'qmDividends.bson')))).toEqual(previousDividends);
|
||||
});
|
||||
});
|
||||
|
||||
test('createReadOnlyMongoRawBsonSource re-checks read-only mode at find time', () => {
|
||||
let readOnly = true;
|
||||
const getCollection = mock(() => ({
|
||||
find: () => ({ async *[Symbol.asyncIterator]() {} }),
|
||||
}));
|
||||
const source = createReadOnlyMongoRawBsonSource({ isReadOnly: () => readOnly, getCollection });
|
||||
readOnly = false;
|
||||
expect(() => source.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError);
|
||||
expect(getCollection).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
667
apps/stock/data-pipeline/test/export-raw-bson.test.ts
Normal file
667
apps/stock/data-pipeline/test/export-raw-bson.test.ts
Normal file
|
|
@ -0,0 +1,667 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
createReadOnlyMongoRawBsonSource,
|
||||
exportRawBsonCollection,
|
||||
RAW_BSON_EXPORT_COLLECTIONS,
|
||||
RawBsonExportError,
|
||||
validateRawBsonFrame,
|
||||
walkRawBsonFrames,
|
||||
type ExportRawBsonFileHandle,
|
||||
type ExportRawBsonFsHooks,
|
||||
type RawBsonFindOptions,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
type ReadOnlyRawBsonSource,
|
||||
} from '../src/security-master/export-raw-bson';
|
||||
|
||||
const EMPTY_SHA256 = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
|
||||
|
||||
function sha256Hex(bytes: Uint8Array): string {
|
||||
return createHash('sha256').update(bytes).digest('hex');
|
||||
}
|
||||
|
||||
function concatBytes(chunks: readonly Uint8Array[]): Uint8Array {
|
||||
const total = chunks.reduce((acc, c) => acc + c.byteLength, 0);
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const chunk of chunks) {
|
||||
out.set(chunk, offset);
|
||||
offset += chunk.byteLength;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function createFakeSource(
|
||||
docs: readonly unknown[],
|
||||
options: {
|
||||
readOnly?: boolean;
|
||||
errorAfter?: number;
|
||||
error?: Error;
|
||||
onFind?: (collection: string, filter: Record<string, unknown>, findOpts: RawBsonFindOptions) => void;
|
||||
onCursorClose?: () => void;
|
||||
} = {}
|
||||
): ReadOnlyRawBsonSource {
|
||||
const readOnly = options.readOnly ?? true;
|
||||
return {
|
||||
isReadOnly: () => readOnly,
|
||||
find(collection, filter, findOpts) {
|
||||
options.onFind?.(collection, filter, findOpts);
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
let index = 0;
|
||||
try {
|
||||
for (const doc of docs) {
|
||||
if (options.errorAfter !== undefined && index === options.errorAfter) {
|
||||
throw options.error ?? new Error('Simulated mid-stream cursor failure');
|
||||
}
|
||||
yield doc;
|
||||
index += 1;
|
||||
}
|
||||
} finally {
|
||||
options.onCursorClose?.();
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function withTempDir<T>(fn: (dir: string) => Promise<T>): Promise<T> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'export-raw-bson-test-'));
|
||||
try {
|
||||
return await fn(dir);
|
||||
} finally {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('exportRawBsonCollection', () => {
|
||||
test('streams raw BSON frames verbatim, matches concatenation, round-trips via 4-byte LE framing, and is deterministic', async () => {
|
||||
const originalDocs = [
|
||||
{
|
||||
eodSearchCode: 'AAPL.US',
|
||||
date: '2025-01-02',
|
||||
open: 248.93,
|
||||
high: 249.1,
|
||||
low: 241.82,
|
||||
close: 243.85,
|
||||
volume: 55740731,
|
||||
ts: new Date('2025-01-02T21:00:00.000Z'),
|
||||
meta: { exchange: 'US', adjusted: false },
|
||||
},
|
||||
{
|
||||
eodSearchCode: 'RY.TO',
|
||||
date: '2025-01-02',
|
||||
open: 173.4,
|
||||
high: 175.0,
|
||||
low: 172.8,
|
||||
close: 174.65,
|
||||
volume: 2150000,
|
||||
tags: ['CA', 'TSX'],
|
||||
},
|
||||
{
|
||||
eodSearchCode: 'NVDA.US',
|
||||
date: '2024-06-10',
|
||||
open: 120.37,
|
||||
high: 123.1,
|
||||
low: 117.01,
|
||||
close: 121.79,
|
||||
volume: 314162700,
|
||||
},
|
||||
];
|
||||
const serialized = originalDocs.map(doc => Uint8Array.from(BSON.serialize(doc)));
|
||||
const expectedBytes = concatBytes(serialized);
|
||||
const expectedSha = sha256Hex(expectedBytes);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const findCalls: Array<{
|
||||
collection: string;
|
||||
filter: Record<string, unknown>;
|
||||
options: RawBsonFindOptions;
|
||||
}> = [];
|
||||
const source = createFakeSource(serialized, {
|
||||
onFind: (collection, filter, options) => {
|
||||
findCalls.push({ collection, filter, options });
|
||||
},
|
||||
});
|
||||
|
||||
const run1 = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
});
|
||||
|
||||
expect(run1.collection).toBe('eodPrices');
|
||||
expect(run1.outPath).toBe(join(outDir, 'eodPrices.bson'));
|
||||
expect(run1.docsWritten).toBe(originalDocs.length);
|
||||
expect(run1.bytesWritten).toBe(expectedBytes.byteLength);
|
||||
expect(run1.elapsedMs).toBeGreaterThanOrEqual(0);
|
||||
expect(run1.sha256).toBe(expectedSha);
|
||||
expect(run1.filter).toEqual({});
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
collection: 'eodPrices',
|
||||
filter: {},
|
||||
options: { raw: true, batchSize: 4096 },
|
||||
},
|
||||
]);
|
||||
|
||||
const fileBytes = Uint8Array.from(await readFile(run1.outPath));
|
||||
expect(fileBytes).toEqual(expectedBytes);
|
||||
|
||||
// Cross-language framing parity: walk output by 4-byte LE length prefix
|
||||
const walked = walkRawBsonFrames(fileBytes);
|
||||
expect(walked).toHaveLength(originalDocs.length);
|
||||
for (let i = 0; i < originalDocs.length; i++) {
|
||||
const frame = walked[i];
|
||||
expect(frame).toEqual(serialized[i]);
|
||||
expect(BSON.deserialize(frame!)).toEqual(originalDocs[i]);
|
||||
}
|
||||
|
||||
// Determinism / replay invariant: running twice yields byte-identical output and sha256
|
||||
const run2 = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
});
|
||||
const fileBytes2 = Uint8Array.from(await readFile(run2.outPath));
|
||||
expect(run2.sha256).toBe(run1.sha256);
|
||||
expect(run2.bytesWritten).toBe(run1.bytesWritten);
|
||||
expect(fileBytes2).toEqual(fileBytes);
|
||||
expect(await readdir(outDir)).toEqual(['eodPrices.bson']);
|
||||
});
|
||||
});
|
||||
|
||||
test('publishes a 0-byte file with docsWritten === 0 and empty SHA-256 for an empty collection', async () => {
|
||||
await withTempDir(async outDir => {
|
||||
const source = createFakeSource([]);
|
||||
const result = await exportRawBsonCollection(source, {
|
||||
collection: 'ceoShorts',
|
||||
outDir,
|
||||
});
|
||||
|
||||
expect(result.collection).toBe('ceoShorts');
|
||||
expect(result.docsWritten).toBe(0);
|
||||
expect(result.bytesWritten).toBe(0);
|
||||
expect(result.sha256).toBe(EMPTY_SHA256);
|
||||
|
||||
const fileBytes = await readFile(result.outPath);
|
||||
expect(fileBytes.byteLength).toBe(0);
|
||||
expect(await readdir(outDir)).toEqual(['ceoShorts.bson']);
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects invalid BSON frames with typed error naming collection and ordinal, cleans temp file, and preserves existing output', async () => {
|
||||
const validDoc = Uint8Array.from(BSON.serialize({ a: 1 }));
|
||||
const shortFrame = new Uint8Array([4, 0, 0, 0]);
|
||||
const tooSmallPrefix = Uint8Array.from(validDoc);
|
||||
tooSmallPrefix[0] = (tooSmallPrefix[0] ?? 0) - 1;
|
||||
const tooLargePrefix = Uint8Array.from(validDoc);
|
||||
tooLargePrefix[0] = (tooLargePrefix[0] ?? 0) + 1;
|
||||
const missingTerminator = Uint8Array.from(validDoc);
|
||||
missingTerminator[missingTerminator.byteLength - 1] = 0x01;
|
||||
const oversizedDoc = Uint8Array.from(BSON.serialize({ payload: 'x'.repeat(200) }));
|
||||
|
||||
const cases: Array<{
|
||||
name: string;
|
||||
docs: unknown[];
|
||||
expectedOrdinal: number;
|
||||
maxDocBytes?: number;
|
||||
}> = [
|
||||
{ name: 'shorter than 5 bytes', docs: [validDoc, shortFrame], expectedOrdinal: 1 },
|
||||
{ name: 'LE prefix smaller than byteLength', docs: [validDoc, tooSmallPrefix], expectedOrdinal: 1 },
|
||||
{ name: 'LE prefix larger than byteLength', docs: [tooLargePrefix], expectedOrdinal: 0 },
|
||||
{ name: 'missing trailing 0x00', docs: [validDoc, validDoc, missingTerminator], expectedOrdinal: 2 },
|
||||
{ name: 'non-Uint8Array chunk', docs: [validDoc, { plain: 'object' }], expectedOrdinal: 1 },
|
||||
{
|
||||
name: 'exceeds maxDocBytes',
|
||||
docs: [validDoc, oversizedDoc],
|
||||
expectedOrdinal: 1,
|
||||
maxDocBytes: 64,
|
||||
},
|
||||
];
|
||||
|
||||
for (const c of cases) {
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmSplits.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: c.name }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
const source = createFakeSource(c.docs);
|
||||
let caught: unknown;
|
||||
try {
|
||||
await exportRawBsonCollection(source, {
|
||||
collection: 'qmSplits',
|
||||
outDir,
|
||||
maxDocBytes: c.maxDocBytes,
|
||||
});
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
|
||||
expect(caught).toBeInstanceOf(RawBsonExportError);
|
||||
const typed = caught as RawBsonExportError;
|
||||
expect(typed.code).toBe('INVALID_BSON_FRAME');
|
||||
expect(typed.collection).toBe('qmSplits');
|
||||
expect(typed.docOrdinal).toBe(c.expectedOrdinal);
|
||||
expect(typed.message).toContain('qmSplits');
|
||||
expect(typed.message).toContain(`doc#${c.expectedOrdinal}`);
|
||||
|
||||
// No temp file left behind and pre-existing output is byte-identical
|
||||
expect(await readdir(outDir)).toEqual(['qmSplits.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('cleans up temp file, closes cursor/handle, and preserves existing output on mid-stream cursor, write, short-write, fsync, and rename errors', async () => {
|
||||
const docs = [
|
||||
Uint8Array.from(BSON.serialize({ seq: 0 })),
|
||||
Uint8Array.from(BSON.serialize({ seq: 1 })),
|
||||
Uint8Array.from(BSON.serialize({ seq: 2 })),
|
||||
];
|
||||
|
||||
// 1. Mid-stream cursor error
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmDividends.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'cursor-err' }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
let cursorClosed = false;
|
||||
const source = createFakeSource(docs, {
|
||||
errorAfter: 2,
|
||||
error: new Error('Cursor network reset'),
|
||||
onCursorClose: () => {
|
||||
cursorClosed = true;
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(source, { collection: 'qmDividends', outDir })
|
||||
).rejects.toThrow('Cursor network reset');
|
||||
|
||||
expect(cursorClosed).toBe(true);
|
||||
expect(await readdir(outDir)).toEqual(['qmDividends.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
|
||||
// 2. Write, short-write, fsync, and rename errors
|
||||
const failureModes = ['write', 'shortWrite', 'sync', 'rename'] as const;
|
||||
for (const mode of failureModes) {
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmPrices.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: mode }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
let handleClosed = false;
|
||||
let tempFileCreated: string | null = null;
|
||||
let unlinkedPath: string | null = null;
|
||||
|
||||
const fsHooks: ExportRawBsonFsHooks = {
|
||||
open: async (filePath: string) => {
|
||||
tempFileCreated = filePath;
|
||||
await writeFile(filePath, new Uint8Array());
|
||||
const handle: ExportRawBsonFileHandle = {
|
||||
write: async (_buf, _off, len) => {
|
||||
if (mode === 'write') {
|
||||
throw new Error('ENOSPC simulated write failure');
|
||||
}
|
||||
if (mode === 'shortWrite') {
|
||||
return { bytesWritten: 0 };
|
||||
}
|
||||
return { bytesWritten: len ?? 0 };
|
||||
},
|
||||
sync: async () => {
|
||||
if (mode === 'sync') {
|
||||
throw new Error('EIO simulated fsync failure');
|
||||
}
|
||||
},
|
||||
close: async () => {
|
||||
handleClosed = true;
|
||||
},
|
||||
};
|
||||
return handle;
|
||||
},
|
||||
rename: async () => {
|
||||
if (mode === 'rename') {
|
||||
throw new Error('EXDEV simulated rename failure');
|
||||
}
|
||||
},
|
||||
unlink: async filePath => {
|
||||
unlinkedPath = String(filePath);
|
||||
await rm(filePath, { force: true });
|
||||
},
|
||||
};
|
||||
|
||||
const source = createFakeSource(docs);
|
||||
await expect(
|
||||
exportRawBsonCollection(source, {
|
||||
collection: 'qmPrices',
|
||||
outDir,
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toThrow();
|
||||
|
||||
expect(handleClosed).toBe(true);
|
||||
expect(tempFileCreated).not.toBeNull();
|
||||
expect(unlinkedPath).toBe(tempFileCreated);
|
||||
expect(await readdir(outDir)).toEqual(['qmPrices.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('enforces bounded write buffer size, handles oversized single docs, and strictly awaits write backpressure', async () => {
|
||||
const smallDocs = Array.from({ length: 120 }, (_, i) =>
|
||||
Uint8Array.from(
|
||||
BSON.serialize({
|
||||
eodSearchCode: `SYM${String(i).padStart(4, '0')}.US`,
|
||||
date: '2025-01-02',
|
||||
open: 10 + i,
|
||||
close: 11 + i,
|
||||
volume: 1000 + i,
|
||||
})
|
||||
)
|
||||
);
|
||||
const largeDoc = Uint8Array.from(
|
||||
BSON.serialize({
|
||||
eodSearchCode: 'LARGE.US',
|
||||
payload: 'A'.repeat(350),
|
||||
})
|
||||
);
|
||||
const allDocs = [...smallDocs.slice(0, 60), largeDoc, ...smallDocs.slice(60)];
|
||||
const expectedConcat = concatBytes(allDocs);
|
||||
const writeBufferBytes = 256;
|
||||
|
||||
expect(largeDoc.byteLength).toBeGreaterThan(writeBufferBytes);
|
||||
|
||||
const writeLengths: number[] = [];
|
||||
const writtenChunks: Uint8Array[] = [];
|
||||
let inFlight = 0;
|
||||
let maxInFlight = 0;
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const fsHooks: ExportRawBsonFsHooks = {
|
||||
open: async () => ({
|
||||
write: async (buf, offset, length) => {
|
||||
inFlight += 1;
|
||||
if (inFlight > maxInFlight) {
|
||||
maxInFlight = inFlight;
|
||||
}
|
||||
const start = offset ?? 0;
|
||||
const len = length ?? buf.byteLength - start;
|
||||
writeLengths.push(len);
|
||||
// Copy slice immediately to simulate kernel read of buffer before async completion
|
||||
const copy = Uint8Array.from(buf.subarray(start, start + len));
|
||||
await new Promise<void>(resolve => setTimeout(resolve, 0));
|
||||
writtenChunks.push(copy);
|
||||
inFlight -= 1;
|
||||
return { bytesWritten: len };
|
||||
},
|
||||
sync: async () => {},
|
||||
close: async () => {},
|
||||
}),
|
||||
rename: async () => {},
|
||||
unlink: async () => {},
|
||||
};
|
||||
|
||||
const source = createFakeSource(allDocs);
|
||||
const result = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
writeBufferBytes,
|
||||
fs: fsHooks,
|
||||
});
|
||||
|
||||
expect(maxInFlight).toBe(1);
|
||||
expect(writeLengths.length).toBeGreaterThan(10);
|
||||
|
||||
// Every write must be <= writeBufferBytes except the single oversized document write
|
||||
const oversizedWrites = writeLengths.filter(len => len > writeBufferBytes);
|
||||
expect(oversizedWrites).toEqual([largeDoc.byteLength]);
|
||||
for (const len of writeLengths) {
|
||||
expect(len).toBeLessThanOrEqual(Math.max(writeBufferBytes, largeDoc.byteLength));
|
||||
}
|
||||
|
||||
const assembled = concatBytes(writtenChunks);
|
||||
expect(assembled).toEqual(expectedConcat);
|
||||
expect(result.docsWritten).toBe(allDocs.length);
|
||||
expect(result.bytesWritten).toBe(expectedConcat.byteLength);
|
||||
expect(result.sha256).toBe(sha256Hex(expectedConcat));
|
||||
});
|
||||
});
|
||||
|
||||
test('rejects disallowed collections, invalid filters, and non-read-only sources before any source or fs call', async () => {
|
||||
const findMock = mock(() => {
|
||||
throw new Error('source.find should never be called');
|
||||
});
|
||||
const openMock = mock(async () => {
|
||||
throw new Error('fs.open should never be called');
|
||||
});
|
||||
const source: ReadOnlyRawBsonSource = {
|
||||
isReadOnly: () => true,
|
||||
find: findMock,
|
||||
};
|
||||
const fsHooks: ExportRawBsonFsHooks = { open: openMock };
|
||||
|
||||
for (const disallowed of ['eodIntraday1M', 'qmIntraday', 'qmFinancials', 'ceoPosts', 'symbols']) {
|
||||
await expect(
|
||||
exportRawBsonCollection(source, { collection: disallowed, outDir: '/tmp/unused', fs: fsHooks })
|
||||
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION', collection: disallowed });
|
||||
}
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(source, {
|
||||
collection: 'teMarketData',
|
||||
outDir: '/tmp/unused',
|
||||
eodSymbol: 'CAD.FOREX',
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir: '/tmp/unused',
|
||||
teSymbol: 'USDCAD',
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'INVALID_OPTION' });
|
||||
|
||||
const writableSource: ReadOnlyRawBsonSource = {
|
||||
isReadOnly: () => false,
|
||||
find: findMock,
|
||||
};
|
||||
await expect(
|
||||
exportRawBsonCollection(writableSource, {
|
||||
collection: 'eodPrices',
|
||||
outDir: '/tmp/unused',
|
||||
fs: fsHooks,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'INVALID_SOURCE' });
|
||||
|
||||
expect(findMock).not.toHaveBeenCalled();
|
||||
expect(openMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('applies eodSymbol, teSymbol, and limit filters and defensively caps output at limit', async () => {
|
||||
const docs = Array.from({ length: 5 }, (_, i) =>
|
||||
Uint8Array.from(BSON.serialize({ seq: i }))
|
||||
);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const calls: Array<{ collection: string; filter: Record<string, unknown>; options: RawBsonFindOptions }> = [];
|
||||
const source = createFakeSource(docs, {
|
||||
onFind: (collection, filter, options) => {
|
||||
calls.push({ collection, filter, options });
|
||||
},
|
||||
});
|
||||
|
||||
const eodRes = await exportRawBsonCollection(source, {
|
||||
collection: 'eodPrices',
|
||||
outDir,
|
||||
eodSymbol: 'CAD.FOREX',
|
||||
limit: 2,
|
||||
batchSize: 64,
|
||||
});
|
||||
|
||||
expect(eodRes.docsWritten).toBe(2);
|
||||
expect(eodRes.filter).toEqual({ eodSearchCode: 'CAD.FOREX' });
|
||||
expect(calls[0]).toEqual({
|
||||
collection: 'eodPrices',
|
||||
filter: { eodSearchCode: 'CAD.FOREX' },
|
||||
options: { raw: true, batchSize: 64, limit: 2 },
|
||||
});
|
||||
|
||||
const teRes = await exportRawBsonCollection(source, {
|
||||
collection: 'teMarketData',
|
||||
outDir,
|
||||
teSymbol: 'USDCAD',
|
||||
limit: 3,
|
||||
});
|
||||
|
||||
expect(teRes.docsWritten).toBe(3);
|
||||
expect(teRes.filter).toEqual({ teSymbol: 'USDCAD' });
|
||||
expect(calls[1]).toEqual({
|
||||
collection: 'teMarketData',
|
||||
filter: { teSymbol: 'USDCAD' },
|
||||
options: { raw: true, batchSize: 4096, limit: 3 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
test('createReadOnlyMongoRawBsonSource enforces read-only, rejects buffered arrays, and always closes cursors', async () => {
|
||||
const writableClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => false,
|
||||
getCollection: () => {
|
||||
throw new Error('should not be called');
|
||||
},
|
||||
};
|
||||
expect(() => createReadOnlyMongoRawBsonSource(writableClient)).toThrow(RawBsonExportError);
|
||||
|
||||
const bufferedArrayClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => [] as unknown as ReturnType<ReadOnlyMongoRawBsonClient['getCollection']> extends {
|
||||
find: (...args: never[]) => infer R;
|
||||
}
|
||||
? R
|
||||
: never,
|
||||
}),
|
||||
};
|
||||
const badSource = createReadOnlyMongoRawBsonSource(bufferedArrayClient);
|
||||
expect(() => badSource.find('eodPrices', {}, { raw: true })).toThrow(RawBsonExportError);
|
||||
|
||||
// Cursor close is called on normal exhaustion and early break
|
||||
const closeMock = mock(async () => {});
|
||||
const docs = [
|
||||
Uint8Array.from(BSON.serialize({ a: 1 })),
|
||||
Uint8Array.from(BSON.serialize({ a: 2 })),
|
||||
Uint8Array.from(BSON.serialize({ a: 3 })),
|
||||
];
|
||||
const goodClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => ({
|
||||
close: closeMock,
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const d of docs) {
|
||||
yield d;
|
||||
}
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const source = createReadOnlyMongoRawBsonSource(goodClient);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const res = await exportRawBsonCollection(source, {
|
||||
collection: 'qmFilings',
|
||||
outDir,
|
||||
limit: 1,
|
||||
});
|
||||
expect(res.docsWritten).toBe(1);
|
||||
expect(closeMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Limited export with rejecting cursor.close() must surface the close error,
|
||||
// clean up the temp file, and leave any pre-existing output file byte-identical.
|
||||
const rejectingCloseClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => ({
|
||||
close: async () => {
|
||||
throw new Error('Cursor close rejected after limit break');
|
||||
},
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const d of docs) {
|
||||
yield d;
|
||||
}
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const rejectingSource = createReadOnlyMongoRawBsonSource(rejectingCloseClient);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
const existingPath = join(outDir, 'qmFilings.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ sentinel: 'preserve-on-close-error' }));
|
||||
await writeFile(existingPath, sentinel);
|
||||
|
||||
await expect(
|
||||
exportRawBsonCollection(rejectingSource, {
|
||||
collection: 'qmFilings',
|
||||
outDir,
|
||||
limit: 1,
|
||||
})
|
||||
).rejects.toThrow('Cursor close rejected after limit break');
|
||||
|
||||
expect(await readdir(outDir)).toEqual(['qmFilings.bson']);
|
||||
expect(Uint8Array.from(await readFile(existingPath))).toEqual(sentinel);
|
||||
});
|
||||
|
||||
// When iteration itself fails AND cursor.close() rejects, the primary iteration error wins.
|
||||
const dualFailureClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => ({
|
||||
close: async () => {
|
||||
throw new Error('Secondary cursor close failure');
|
||||
},
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield docs[0];
|
||||
throw new Error('Primary cursor iteration failure');
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
const dualFailureSource = createReadOnlyMongoRawBsonSource(dualFailureClient);
|
||||
|
||||
await withTempDir(async outDir => {
|
||||
await expect(
|
||||
exportRawBsonCollection(dualFailureSource, {
|
||||
collection: 'qmFilings',
|
||||
outDir,
|
||||
})
|
||||
).rejects.toThrow('Primary cursor iteration failure');
|
||||
expect(await readdir(outDir)).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test('exports exact M1 allowlist of 8 collections and validateRawBsonFrame accepts minimal 5-byte empty BSON doc', () => {
|
||||
expect([...RAW_BSON_EXPORT_COLLECTIONS]).toEqual([
|
||||
'eodPrices',
|
||||
'qmSplits',
|
||||
'qmDividends',
|
||||
'qmPrices',
|
||||
'teMarketData',
|
||||
'ceoShorts',
|
||||
'qmFilings',
|
||||
'qmEarnings',
|
||||
]);
|
||||
const emptyBson = new Uint8Array([5, 0, 0, 0, 0]);
|
||||
expect(validateRawBsonFrame(emptyBson, 'eodPrices', 0)).toBe(emptyBson);
|
||||
});
|
||||
});
|
||||
399
apps/stock/data-pipeline/test/run-export-raw-bson.test.ts
Normal file
399
apps/stock/data-pipeline/test/run-export-raw-bson.test.ts
Normal file
|
|
@ -0,0 +1,399 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import type { StockAppConfig } from '@stock-bot/stock-config';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
RAW_BSON_EXPORT_COLLECTIONS,
|
||||
RawBsonExportError,
|
||||
type ReadOnlyMongoRawBsonClient,
|
||||
} from '../src/security-master/export-raw-bson';
|
||||
import {
|
||||
assertExportRawBsonSafety,
|
||||
EXPORT_RAW_BSON_USAGE,
|
||||
parseExportRawBsonArgs,
|
||||
runCli,
|
||||
runExportRawBson,
|
||||
} from '../src/security-master/run-export-raw-bson';
|
||||
|
||||
function createBaseConfig(overrides: Partial<StockAppConfig['database']['mongodb']> = {}): StockAppConfig {
|
||||
return {
|
||||
environment: 'development',
|
||||
database: {
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 5432,
|
||||
database: 'trading_bot',
|
||||
user: 'trading_user',
|
||||
password: 'pw',
|
||||
ssl: false,
|
||||
poolSize: 5,
|
||||
idleTimeout: 10000,
|
||||
connectionTimeout: 5000,
|
||||
},
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
|
||||
readUri: 'mongodb://studio_stock_bot_read:pw@localhost:27017/stock?authSource=stock',
|
||||
readOnly: true,
|
||||
host: 'localhost',
|
||||
port: 27017,
|
||||
database: 'stock',
|
||||
poolSize: 5,
|
||||
...overrides,
|
||||
},
|
||||
dragonfly: {
|
||||
enabled: false,
|
||||
host: 'localhost',
|
||||
port: 6380,
|
||||
},
|
||||
questdb: {
|
||||
enabled: false,
|
||||
host: 'localhost',
|
||||
port: 9100,
|
||||
},
|
||||
},
|
||||
} as unknown as StockAppConfig;
|
||||
}
|
||||
|
||||
describe('parseExportRawBsonArgs', () => {
|
||||
test('parses valid flags in both space-separated and equals forms', () => {
|
||||
const parsed1 = parseExportRawBsonArgs([
|
||||
'--out-dir',
|
||||
'./tmp/bson',
|
||||
'--collections',
|
||||
'eodPrices',
|
||||
'--eod-symbol',
|
||||
'CAD.FOREX',
|
||||
'--limit',
|
||||
'100',
|
||||
'--batch-size',
|
||||
'512',
|
||||
]);
|
||||
expect(parsed1).toEqual({
|
||||
help: false,
|
||||
outDir: './tmp/bson',
|
||||
collections: ['eodPrices'],
|
||||
eodSymbol: 'CAD.FOREX',
|
||||
limit: 100,
|
||||
batchSize: 512,
|
||||
});
|
||||
|
||||
const parsed2 = parseExportRawBsonArgs([
|
||||
'--out-dir=./tmp/te',
|
||||
'--collections=teMarketData',
|
||||
'--te-symbol=USDCAD',
|
||||
]);
|
||||
expect(parsed2).toEqual({
|
||||
help: false,
|
||||
outDir: './tmp/te',
|
||||
collections: ['teMarketData'],
|
||||
teSymbol: 'USDCAD',
|
||||
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
});
|
||||
|
||||
const parsedDefault = parseExportRawBsonArgs(['--out-dir', './tmp/all']);
|
||||
expect(parsedDefault).toEqual({
|
||||
help: false,
|
||||
outDir: './tmp/all',
|
||||
collections: [...RAW_BSON_EXPORT_COLLECTIONS],
|
||||
batchSize: DEFAULT_RAW_BSON_BATCH_SIZE,
|
||||
});
|
||||
|
||||
expect(parseExportRawBsonArgs(['--help'])).toEqual({ help: true });
|
||||
});
|
||||
|
||||
test('rejects unknown, duplicate, missing-value, positional, and malformed flags', () => {
|
||||
expect(() => parseExportRawBsonArgs([])).toThrow(/Missing required argument: --out-dir/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', '--bogus'])).toThrow(/Unknown argument/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './tmp', 'positional'])).toThrow(/Unknown argument/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--out-dir', './b'])).toThrow(/Duplicate flag/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--limit', '10', '--limit=20'])
|
||||
).toThrow(/Duplicate flag/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', '--collections', 'eodPrices'])).toThrow(
|
||||
/Missing value for --out-dir/
|
||||
);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir='])).toThrow(/Missing value for --out-dir/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '0'])).toThrow(/Invalid --limit/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '-5'])).toThrow(/Invalid --limit/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--limit', '1.5'])).toThrow(/Invalid --limit/);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '0'])).toThrow(
|
||||
/Invalid --batch-size/
|
||||
);
|
||||
expect(() => parseExportRawBsonArgs(['--out-dir', './a', '--batch-size', '999999'])).toThrow(
|
||||
/Invalid --batch-size/
|
||||
);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,'])
|
||||
).toThrow(/Malformed --collections/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices,eodPrices'])
|
||||
).toThrow(/Duplicate collection/);
|
||||
expect(() => parseExportRawBsonArgs(['--help', '--help'])).toThrow(/Duplicate flag: --help/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol=--help'])
|
||||
).toThrow(/Invalid value for --eod-symbol/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--eod-symbol', '--help'])
|
||||
).toThrow(/Missing value for --eod-symbol/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol=--limit'])
|
||||
).toThrow(/Invalid value for --te-symbol/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--te-symbol', '--limit'])
|
||||
).toThrow(/Missing value for --te-symbol/);
|
||||
});
|
||||
|
||||
test('rejects disallowed collections and mismatched --eod-symbol / --te-symbol filters', () => {
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodIntraday1M'])
|
||||
).toThrow(RawBsonExportError);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'symbols'])
|
||||
).toThrow(RawBsonExportError);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'teMarketData', '--eod-symbol', 'CAD.FOREX'])
|
||||
).toThrow(/--eod-symbol is only permitted/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs([
|
||||
'--out-dir',
|
||||
'./a',
|
||||
'--collections',
|
||||
'eodPrices,qmSplits',
|
||||
'--eod-symbol',
|
||||
'CAD.FOREX',
|
||||
])
|
||||
).toThrow(/--eod-symbol is only permitted/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--eod-symbol', 'CAD.FOREX'])
|
||||
).toThrow(/--eod-symbol is only permitted/);
|
||||
expect(() =>
|
||||
parseExportRawBsonArgs(['--out-dir', './a', '--collections', 'eodPrices', '--te-symbol', 'USDCAD'])
|
||||
).toThrow(/--te-symbol is only permitted/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertExportRawBsonSafety', () => {
|
||||
test('allows read-only dev MongoDB even if Postgres config points to QA, and rejects disabled/writable/admin MongoDB', () => {
|
||||
expect(() => assertExportRawBsonSafety(createBaseConfig(), {})).not.toThrow();
|
||||
|
||||
expect(() => assertExportRawBsonSafety(createBaseConfig({ enabled: false }), {})).toThrow(
|
||||
/MongoDB is disabled/
|
||||
);
|
||||
expect(() => assertExportRawBsonSafety(createBaseConfig({ readOnly: false }), {})).toThrow(
|
||||
/read-only MongoDB configuration/
|
||||
);
|
||||
expect(() =>
|
||||
assertExportRawBsonSafety(
|
||||
createBaseConfig({
|
||||
readUri: 'mongodb://trading_admin:pw@localhost:27017/stock?authSource=admin',
|
||||
readOnly: true,
|
||||
}),
|
||||
{}
|
||||
)
|
||||
).toThrow(/Safety guard/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runExportRawBson & runCli', () => {
|
||||
test('--help prints usage and performs zero config, Mongo, or fs I/O', async () => {
|
||||
const stdout: string[] = [];
|
||||
const initConfigMock = mock(() => {
|
||||
throw new Error('initializeConfig must not be called on --help');
|
||||
});
|
||||
const createClientMock = mock(() => {
|
||||
throw new Error('createMongoClient must not be called on --help');
|
||||
});
|
||||
|
||||
await runCli(['--help'], {
|
||||
initializeConfig: initConfigMock as never,
|
||||
createMongoClient: createClientMock,
|
||||
writeStdout: text => stdout.push(text),
|
||||
});
|
||||
|
||||
expect(stdout.join('')).toBe(`${EXPORT_RAW_BSON_USAGE}\n`);
|
||||
expect(initConfigMock).not.toHaveBeenCalled();
|
||||
expect(createClientMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('runCli initializes config with mongoReadOnly: true, issues strictly raw find(), calls zero write methods, and closes client', async () => {
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-cli-'));
|
||||
try {
|
||||
const sampleBytes = Uint8Array.from(
|
||||
BSON.serialize({ eodSearchCode: 'CAD.FOREX', date: '2025-01-02', close: 1.44 })
|
||||
);
|
||||
const findCalls: Array<{ collection: string; filter: unknown; options: unknown }> = [];
|
||||
const forbiddenWrite = mock(() => {
|
||||
throw new Error('Write/DDL method must never be called');
|
||||
});
|
||||
const closeMongoMock = mock(async () => {});
|
||||
const closeCursorMock = mock(async () => {});
|
||||
|
||||
const fakeClient: ReadOnlyMongoRawBsonClient & Record<string, unknown> = {
|
||||
isReadOnly: () => true,
|
||||
insertOne: forbiddenWrite,
|
||||
updateOne: forbiddenWrite,
|
||||
deleteMany: forbiddenWrite,
|
||||
createIndex: forbiddenWrite,
|
||||
dropCollection: forbiddenWrite,
|
||||
getCollection: (name: string) => ({
|
||||
find: (filter, options) => {
|
||||
findCalls.push({ collection: name, filter, options });
|
||||
return {
|
||||
close: closeCursorMock,
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield sampleBytes;
|
||||
},
|
||||
};
|
||||
},
|
||||
}),
|
||||
};
|
||||
|
||||
const initCalls: Array<{ service: string; opts: unknown }> = [];
|
||||
const stdout: string[] = [];
|
||||
|
||||
await runCli(
|
||||
[
|
||||
'--out-dir',
|
||||
outDir,
|
||||
'--collections',
|
||||
'eodPrices',
|
||||
'--eod-symbol',
|
||||
'CAD.FOREX',
|
||||
'--batch-size',
|
||||
'256',
|
||||
],
|
||||
{
|
||||
initializeConfig: ((service: string, opts?: unknown) => {
|
||||
initCalls.push({ service, opts });
|
||||
return createBaseConfig();
|
||||
}) as never,
|
||||
createMongoClient: async () => ({
|
||||
client: fakeClient,
|
||||
close: closeMongoMock,
|
||||
}),
|
||||
writeStdout: text => stdout.push(text),
|
||||
}
|
||||
);
|
||||
|
||||
expect(initCalls).toEqual([{ service: 'dataPipeline', opts: { mongoReadOnly: true } }]);
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
collection: 'eodPrices',
|
||||
filter: { eodSearchCode: 'CAD.FOREX' },
|
||||
options: { raw: true, batchSize: 256 },
|
||||
},
|
||||
]);
|
||||
expect(forbiddenWrite).not.toHaveBeenCalled();
|
||||
expect(closeCursorMock).toHaveBeenCalledTimes(1);
|
||||
expect(closeMongoMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
const written = Uint8Array.from(await readFile(join(outDir, 'eodPrices.bson')));
|
||||
expect(written).toEqual(sampleBytes);
|
||||
expect(stdout.join('')).toContain('eodPrices: docs=1');
|
||||
expect(stdout.join('')).toContain('sha256=');
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('runExportRawBson closes Mongo client on mid-stream export failure and preserves primary error', async () => {
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-fail-'));
|
||||
try {
|
||||
const closeMongoMock = mock(async () => {});
|
||||
const fakeClient: ReadOnlyMongoRawBsonClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection: () => ({
|
||||
find: () => ({
|
||||
async *[Symbol.asyncIterator]() {
|
||||
yield Uint8Array.from(BSON.serialize({ ok: 1 }));
|
||||
throw new Error('Mid-stream Mongo failure');
|
||||
},
|
||||
}),
|
||||
}),
|
||||
};
|
||||
|
||||
await expect(
|
||||
runExportRawBson(
|
||||
{
|
||||
createMongoClient: () => ({ client: fakeClient, close: closeMongoMock }),
|
||||
writeStdout: () => {},
|
||||
},
|
||||
{
|
||||
outDir,
|
||||
collections: ['qmSplits'],
|
||||
}
|
||||
)
|
||||
).rejects.toThrow('Mid-stream Mongo failure');
|
||||
|
||||
expect(closeMongoMock).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('runExportRawBson rejects disallowed collections before calling assertSafety or createMongoClient', async () => {
|
||||
const assertSafetyMock = mock(() => {});
|
||||
const createClientMock = mock(() => {
|
||||
throw new Error('createMongoClient must not be called');
|
||||
});
|
||||
|
||||
await expect(
|
||||
runExportRawBson(
|
||||
{
|
||||
assertSafety: assertSafetyMock,
|
||||
createMongoClient: createClientMock,
|
||||
},
|
||||
{
|
||||
outDir: '/tmp/unused',
|
||||
collections: ['eodIntraday1M' as never],
|
||||
}
|
||||
)
|
||||
).rejects.toMatchObject({ code: 'DISALLOWED_COLLECTION' });
|
||||
|
||||
expect(assertSafetyMock).not.toHaveBeenCalled();
|
||||
expect(createClientMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('runCli rejects flag-shaped --eod-symbol and --te-symbol values before config or MongoDB access and preserves existing output', async () => {
|
||||
const outDir = await mkdtemp(join(tmpdir(), 'run-export-raw-bson-flag-val-'));
|
||||
try {
|
||||
const existingEodPath = join(outDir, 'eodPrices.bson');
|
||||
const sentinel = Uint8Array.from(BSON.serialize({ eodSearchCode: 'CAD.FOREX', close: 1.44 }));
|
||||
await writeFile(existingEodPath, sentinel);
|
||||
|
||||
const initConfigMock = mock(() => {
|
||||
throw new Error('initializeConfig must not be called on malformed filter');
|
||||
});
|
||||
const createClientMock = mock(() => {
|
||||
throw new Error('createMongoClient must not be called on malformed filter');
|
||||
});
|
||||
|
||||
const invalidInvocations: string[][] = [
|
||||
['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol=--help'],
|
||||
['--out-dir', outDir, '--collections', 'eodPrices', '--eod-symbol', '--help'],
|
||||
['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol=--help'],
|
||||
['--out-dir', outDir, '--collections', 'teMarketData', '--te-symbol', '--help'],
|
||||
];
|
||||
|
||||
for (const argv of invalidInvocations) {
|
||||
await expect(
|
||||
runCli(argv, {
|
||||
initializeConfig: initConfigMock as never,
|
||||
createMongoClient: createClientMock,
|
||||
})
|
||||
).rejects.toThrow(/(?:Invalid|Missing) value for --(?:eod|te)-symbol/);
|
||||
}
|
||||
|
||||
expect(initConfigMock).not.toHaveBeenCalled();
|
||||
expect(createClientMock).not.toHaveBeenCalled();
|
||||
expect(Uint8Array.from(await readFile(existingEodPath))).toEqual(sentinel);
|
||||
} finally {
|
||||
await rm(outDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
364
apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts
Normal file
364
apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
MAX_EXAMPLES_CAP,
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
runSourceFieldShapesProbe,
|
||||
summarizeFieldShapes,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
// QA coverage for T-108 beyond the programmer's suite: real BSON wire decoding,
|
||||
// option pass-through via the production read-only adapter, fail-fast safety,
|
||||
// and CLI/runner failure paths. No MongoDB connection is opened anywhere here.
|
||||
|
||||
const OBJECT_ID_HEX = '507f1f77bcf86cd799439011';
|
||||
|
||||
function serializeRealBsonDoc(): Uint8Array {
|
||||
return BSON.serialize({
|
||||
_id: new BSON.ObjectId(OBJECT_ID_HEX),
|
||||
i32: new BSON.Int32(7),
|
||||
dbl: new BSON.Double(1.0),
|
||||
lng: BSON.Long.fromString('9007199254740993'),
|
||||
dec: BSON.Decimal128.fromString('12.34'),
|
||||
flag: true,
|
||||
text: '2025-01-02',
|
||||
when: new Date('2025-01-02T00:00:00.000Z'),
|
||||
nothing: null,
|
||||
list: [1, 2],
|
||||
nested: { px: new BSON.Double(2.5), qty: new BSON.Int32(3) },
|
||||
bin: new BSON.Binary(new Uint8Array([1, 2, 3])),
|
||||
ts: new BSON.Timestamp({ t: 1, i: 1 }),
|
||||
min: new BSON.MinKey(),
|
||||
});
|
||||
}
|
||||
|
||||
function nonZeroTypes(counts: Record<string, number>): Record<string, number> {
|
||||
return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0));
|
||||
}
|
||||
|
||||
function asyncCursor<T>(
|
||||
docs: readonly T[],
|
||||
onClose?: () => void
|
||||
): { [Symbol.asyncIterator](): AsyncIterator<T>; close(): Promise<void> } {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
async close() {
|
||||
onClose?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('summarizeFieldShapes with real BSON wire documents', () => {
|
||||
test('promoteValues:false decoding keeps int/double/long/objectId distinct and maps other BSON types to other', () => {
|
||||
const doc = BSON.deserialize(serializeRealBsonDoc(), {
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
|
||||
const summary = summarizeFieldShapes([doc]);
|
||||
const types = Object.fromEntries(summary.fields.map(f => [f.field, nonZeroTypes(f.typeCounts)]));
|
||||
|
||||
expect(types).toEqual({
|
||||
_id: { objectId: 1 },
|
||||
bin: { other: 1 },
|
||||
dbl: { double: 1 },
|
||||
dec: { other: 1 },
|
||||
flag: { bool: 1 },
|
||||
i32: { int: 1 },
|
||||
list: { array: 1 },
|
||||
lng: { int: 1 },
|
||||
min: { other: 1 },
|
||||
nested: { object: 1 },
|
||||
'nested.px': { double: 1 },
|
||||
'nested.qty': { int: 1 },
|
||||
nothing: { null: 1 },
|
||||
text: { string: 1 },
|
||||
ts: { other: 1 },
|
||||
when: { date: 1 },
|
||||
});
|
||||
|
||||
const examples = Object.fromEntries(summary.fields.map(f => [f.field, f.examples]));
|
||||
expect(examples._id).toEqual([]);
|
||||
expect(examples.dbl).toEqual(['1']);
|
||||
expect(examples.lng).toEqual(['9007199254740993']);
|
||||
expect(examples.dec).toEqual(['12.34']);
|
||||
expect(examples.when).toEqual(['2025-01-02T00:00:00.000Z']);
|
||||
expect(examples.bin).toEqual([]);
|
||||
});
|
||||
|
||||
test('default driver promotion collapses Double(1.0) into int, which is why the probe disables promotion', () => {
|
||||
const promoted = BSON.deserialize(serializeRealBsonDoc());
|
||||
const summary = summarizeFieldShapes([promoted]);
|
||||
const dbl = summary.fields.find(f => f.field === 'dbl')!;
|
||||
expect(nonZeroTypes(dbl.typeCounts)).toEqual({ int: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('readFieldShapes through the production read-only Mongo adapter', () => {
|
||||
test('forwards limit/promoteValues/promoteLongs verbatim to collection.find and classifies decoded BSON', async () => {
|
||||
const findCalls: Array<{ name: string; filter: unknown; options: unknown }> = [];
|
||||
const closed: string[] = [];
|
||||
const wireDoc = BSON.deserialize(serializeRealBsonDoc(), {
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection(name: string) {
|
||||
return {
|
||||
find(filter?: Record<string, unknown>, options?: SourceSymbolFindOptions) {
|
||||
findCalls.push({ name, filter, options });
|
||||
return asyncCursor(name === 'qmDividends' ? [wireDoc] : [], () => closed.push(name));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const reader = createReadOnlyMongoSourceSymbolReader(client);
|
||||
const result = await readFieldShapes(reader, {
|
||||
collections: ['qmDividends', 'qmSplits'],
|
||||
limit: 25,
|
||||
});
|
||||
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
name: 'qmDividends',
|
||||
filter: {},
|
||||
options: { limit: 25, promoteValues: false, promoteLongs: false },
|
||||
},
|
||||
{
|
||||
name: 'qmSplits',
|
||||
filter: {},
|
||||
options: { limit: 25, promoteValues: false, promoteLongs: false },
|
||||
},
|
||||
]);
|
||||
expect(closed).toEqual(['qmDividends', 'qmSplits']);
|
||||
expect(result.totalDocsSampled).toBe(1);
|
||||
const dbl = result.collections[0]!.fields.find(f => f.field === 'dbl')!;
|
||||
expect(dbl.typeCounts.double).toBe(1);
|
||||
});
|
||||
|
||||
test('re-checks read-only before every collection and stops if the reader stops being read-only', async () => {
|
||||
let readOnly = true;
|
||||
const findCalls: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => readOnly,
|
||||
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls.push(name);
|
||||
readOnly = false; // simulate a reader that flips after its first query
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
readFieldShapes(reader, { collections: ['ceoShorts', 'qmSplits'] })
|
||||
).rejects.toThrow(/read-only/i);
|
||||
expect(findCalls).toEqual(['ceoShorts']);
|
||||
});
|
||||
|
||||
test('fails fast: an error on one collection prevents queries on later collections', async () => {
|
||||
const findCalls: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls.push(name);
|
||||
if (name === 'eodPrices') {
|
||||
throw new Error('not authorized on stock');
|
||||
}
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await readFieldShapes(reader, { collections: ['qmSplits', 'eodPrices', 'ceoShorts'] });
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
// Collections are ASCII-sorted: ceoShorts, eodPrices, qmSplits.
|
||||
expect(findCalls).toEqual(['ceoShorts', 'eodPrices']);
|
||||
expect((caught as Error).message).toContain('eodPrices');
|
||||
expect((caught as Error).message).toContain('not authorized on stock');
|
||||
expect(((caught as Error).cause as Error).message).toBe('not authorized on stock');
|
||||
});
|
||||
|
||||
test('rejects non-integer limit and invalid batchSize before any query', async () => {
|
||||
let findCalls = 0;
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls += 1;
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
await expect(readFieldShapes(reader, { limit: 1.5 })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { limit: Number.NaN })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { batchSize: 0 })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { collections: [] })).rejects.toThrow(RangeError);
|
||||
expect(findCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeFieldShapes edge cases', () => {
|
||||
test('non-object documents count toward docCount and keep presence invariants', () => {
|
||||
const docs = [{ a: 1 }, null, 'oops', { a: 'x' }] as unknown as Record<string, unknown>[];
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(4);
|
||||
const a = summary.fields.find(f => f.field === 'a')!;
|
||||
expect(a.presentCount).toBe(2);
|
||||
expect(a.missingCount).toBe(2);
|
||||
});
|
||||
|
||||
test('undefined values are treated as missing, not as a present type', () => {
|
||||
const summary = summarizeFieldShapes([{ a: undefined }, { a: 1 }]);
|
||||
const a = summary.fields.find(f => f.field === 'a')!;
|
||||
expect(a.presentCount).toBe(1);
|
||||
expect(a.missingCount).toBe(1);
|
||||
});
|
||||
|
||||
test('rejects near-miss dates and times as ymd/isoDatetime', () => {
|
||||
const values = [
|
||||
'2024-13-01', // month 13
|
||||
'2024-04-31', // April has 30 days
|
||||
'2025-01-01T24:00:00Z', // hour 24
|
||||
'2025-01-01T10:60:00Z', // minute 60
|
||||
'2025-01-01 10:00:00', // space separator
|
||||
'20250101', // compact date is numeric, not ymd
|
||||
];
|
||||
const summary = summarizeFieldShapes(values.map(s => ({ s })));
|
||||
const s = summary.fields.find(f => f.field === 's')!;
|
||||
expect(s.stringStats!.patterns).toEqual({
|
||||
ymd: 0,
|
||||
isoDatetime: 0,
|
||||
numeric: 1,
|
||||
emptyOrWhitespace: 0,
|
||||
other: 5,
|
||||
});
|
||||
});
|
||||
|
||||
test('examples are distinct, strip control characters, and honour maxExamples 0 and the cap', () => {
|
||||
const docs = [{ s: 'dup' }, { s: 'dup' }, { s: '\u0000\u001bbell\u0007' }];
|
||||
|
||||
expect(summarizeFieldShapes(docs).fields[0]!.examples).toEqual(['bell', 'dup']);
|
||||
expect(summarizeFieldShapes(docs, { maxExamples: 0 }).fields[0]!.examples).toEqual([]);
|
||||
|
||||
const many = Array.from({ length: 50 }, (_, i) => ({ s: `v${String(i).padStart(2, '0')}` }));
|
||||
const capped = summarizeFieldShapes(many, { maxExamples: MAX_EXAMPLES_CAP }).fields[0]!;
|
||||
expect(capped.examples.length).toBe(MAX_EXAMPLES_CAP);
|
||||
expect(capped.examples[0]).toBe('v00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderFieldShapesMarkdown privacy and header', () => {
|
||||
test('never renders _id values and states the bounded sample in the header', async () => {
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
return asyncCursor<T>([
|
||||
{ _id: new BSON.ObjectId(OBJECT_ID_HEX), symbol: 'ABC' },
|
||||
{ _id: { ticker: 'SECRET-COMPOSITE' }, symbol: 'DEF' },
|
||||
] as unknown as T[]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
const result = await readFieldShapes(reader, { collections: ['ceoShorts'], limit: 7 });
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
|
||||
expect(markdown).not.toContain(OBJECT_ID_HEX);
|
||||
expect(markdown).not.toContain('SECRET-COMPOSITE');
|
||||
expect(markdown).toContain('bounded sample, not a full scan');
|
||||
expect(markdown).toContain('**Sample limit per collection:** 7');
|
||||
expect(markdown).toContain('**Total documents sampled:** 2');
|
||||
expect(markdown).toContain('| `_id.ticker` | 50.0% (1/2) |');
|
||||
expect(markdown).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); // no wall-clock stamp
|
||||
});
|
||||
});
|
||||
|
||||
describe('probe CLI parsing and runner failure paths', () => {
|
||||
test('rejects a flag in place of a value and empty inline values', () => {
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out', '--limit', '5'])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit'])).toThrow(/--limit/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections='])).toThrow(
|
||||
/--collections/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections', ' , '])).toThrow(
|
||||
/--collections/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1e3'])).toThrow(/--limit/);
|
||||
});
|
||||
|
||||
test('merges repeated --collections, accepts boundary limits, and lets --help win', () => {
|
||||
expect(
|
||||
parseProbeSourceFieldShapesArgs([
|
||||
'--out=x.md',
|
||||
'--collections=qmSplits',
|
||||
'--collections',
|
||||
'ceoShorts,qmSplits',
|
||||
'--limit=10000',
|
||||
])
|
||||
).toEqual({ help: false, outPath: 'x.md', limit: 10_000, collections: ['ceoShorts', 'qmSplits'] });
|
||||
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1'])).toMatchObject({ limit: 1 });
|
||||
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--help'])).toEqual({ help: true });
|
||||
});
|
||||
|
||||
test('closes Mongo and surfaces the write error when the report cannot be written', async () => {
|
||||
let closeCalls = 0;
|
||||
const stdout: string[] = [];
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection() {
|
||||
return { find: () => asyncCursor([{ a: 1 }]) };
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: client,
|
||||
closeMongo: () => {
|
||||
closeCalls += 1;
|
||||
},
|
||||
writeFile: () => {
|
||||
throw new Error('EACCES: permission denied');
|
||||
},
|
||||
writeStdout: text => stdout.push(text),
|
||||
},
|
||||
{ outPath: './tmp/out.md', collections: ['qmSplits'] }
|
||||
)
|
||||
).rejects.toThrow('EACCES');
|
||||
expect(closeCalls).toBe(1);
|
||||
expect(stdout).toEqual([]);
|
||||
});
|
||||
|
||||
test('blank outPath is rejected before any collection is opened', async () => {
|
||||
let getCollectionCalls = 0;
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection() {
|
||||
getCollectionCalls += 1;
|
||||
return { find: () => asyncCursor([]) };
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{ mongoCollectionClient: client, writeFile: () => {}, writeStdout: () => {} },
|
||||
{ outPath: ' ' }
|
||||
)
|
||||
).rejects.toThrow(/outPath/);
|
||||
expect(getCollectionCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
812
apps/stock/data-pipeline/test/source-field-shapes.test.ts
Normal file
812
apps/stock/data-pipeline/test/source-field-shapes.test.ts
Normal file
|
|
@ -0,0 +1,812 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import type { ParserOptions } from 'prettier';
|
||||
import * as markdownPlugin from 'prettier/plugins/markdown';
|
||||
import {
|
||||
DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
DEFAULT_MAX_EXAMPLE_LENGTH,
|
||||
DEFAULT_MAX_EXAMPLES,
|
||||
FIELD_SHAPE_PROBE_COLLECTIONS,
|
||||
FIELD_VALUE_TYPES,
|
||||
MAX_EXAMPLE_LENGTH_CAP,
|
||||
MAX_EXAMPLES_CAP,
|
||||
MAX_FIELD_SHAPE_LIMIT,
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
runSourceFieldShapesProbe,
|
||||
STRING_PATTERN_CLASSES,
|
||||
summarizeFieldShapes,
|
||||
UnknownProbeCollectionError,
|
||||
type FieldShapeSummary,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
interface RecordedFindCall {
|
||||
collectionName: string;
|
||||
filter: Record<string, unknown> | undefined;
|
||||
options: SourceSymbolFindOptions | undefined;
|
||||
}
|
||||
|
||||
interface FakeBsonWrapper {
|
||||
_bsontype: string;
|
||||
valueOf?: () => unknown;
|
||||
toString: () => string;
|
||||
}
|
||||
|
||||
function fakeInt32(value: number): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Int32',
|
||||
valueOf: () => value,
|
||||
toString: () => String(value),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDouble(value: number): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Double',
|
||||
valueOf: () => value,
|
||||
toString: () => String(value),
|
||||
};
|
||||
}
|
||||
|
||||
function fakeLong(value: string): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Long',
|
||||
toString: () => value,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeObjectId(hex: string): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'ObjectId',
|
||||
toString: () => hex,
|
||||
};
|
||||
}
|
||||
|
||||
function fakeDecimal128(value: string): FakeBsonWrapper {
|
||||
return {
|
||||
_bsontype: 'Decimal128',
|
||||
toString: () => value,
|
||||
};
|
||||
}
|
||||
|
||||
function sumTypeCounts(summary: FieldShapeSummary): number {
|
||||
let total = 0;
|
||||
for (const typeName of FIELD_VALUE_TYPES) {
|
||||
total += summary.typeCounts[typeName];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function sumPatternCounts(summary: FieldShapeSummary): number {
|
||||
if (summary.stringStats === null) {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const pattern of STRING_PATTERN_CLASSES) {
|
||||
total += summary.stringStats.patterns[pattern];
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
function createFakeReader(
|
||||
docsByCollection: Record<string, readonly Record<string, unknown>[]>,
|
||||
opts?: {
|
||||
readOnly?: boolean;
|
||||
failFindOnCollection?: string;
|
||||
failIterOnCollection?: string;
|
||||
failIterAtIndex?: number;
|
||||
failCloseOnCollection?: string;
|
||||
returnBufferedArrayOnCollection?: string;
|
||||
ignoreLimit?: boolean;
|
||||
}
|
||||
): {
|
||||
reader: ReadOnlySourceSymbolReader;
|
||||
calls: RecordedFindCall[];
|
||||
closedCollections: string[];
|
||||
pullsByCollection: Record<string, number>;
|
||||
} {
|
||||
const calls: RecordedFindCall[] = [];
|
||||
const closedCollections: string[] = [];
|
||||
const pullsByCollection: Record<string, number> = {};
|
||||
const readOnly = opts?.readOnly ?? true;
|
||||
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly(): boolean {
|
||||
return readOnly;
|
||||
},
|
||||
find<T extends Record<string, unknown> = Record<string, unknown>>(
|
||||
collectionName: string,
|
||||
filter?: Record<string, unknown>,
|
||||
options?: SourceSymbolFindOptions
|
||||
): ReadOnlySourceSymbolCursor<T> {
|
||||
calls.push({ collectionName, filter, options });
|
||||
|
||||
if (opts?.failFindOnCollection === collectionName) {
|
||||
throw new Error('simulated find failure');
|
||||
}
|
||||
if (opts?.returnBufferedArrayOnCollection === collectionName) {
|
||||
return [...(docsByCollection[collectionName] ?? [])] as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
}
|
||||
|
||||
const sourceDocs = docsByCollection[collectionName] ?? [];
|
||||
const maxToYield =
|
||||
opts?.ignoreLimit === true || options?.limit === undefined
|
||||
? sourceDocs.length
|
||||
: Math.min(sourceDocs.length, options.limit);
|
||||
const failAt = opts?.failIterAtIndex ?? 1;
|
||||
|
||||
return {
|
||||
async *[Symbol.asyncIterator](): AsyncIterator<T> {
|
||||
for (let i = 0; i < maxToYield; i++) {
|
||||
pullsByCollection[collectionName] = (pullsByCollection[collectionName] ?? 0) + 1;
|
||||
if (opts?.failIterOnCollection === collectionName && i === failAt) {
|
||||
throw new Error('simulated cursor iteration failure');
|
||||
}
|
||||
yield sourceDocs[i] as T;
|
||||
}
|
||||
},
|
||||
async close(): Promise<void> {
|
||||
closedCollections.push(collectionName);
|
||||
if (opts?.failCloseOnCollection === collectionName) {
|
||||
throw new Error('simulated cursor close failure');
|
||||
}
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return { reader, calls, closedCollections, pullsByCollection };
|
||||
}
|
||||
|
||||
describe('source-field-shapes static purity', () => {
|
||||
test('source-field-shapes.ts has zero runtime DB, FS, or network imports', () => {
|
||||
const filePath = resolve(import.meta.dir, '../src/security-master/source-field-shapes.ts');
|
||||
const source = readFileSync(filePath, 'utf8');
|
||||
const runtimeImportLines = source
|
||||
.split('\n')
|
||||
.filter(line => /^\s*import\s+(?!type\b)/.test(line));
|
||||
|
||||
for (const line of runtimeImportLines) {
|
||||
expect(line).not.toMatch(/mongodb|postgres|node:fs|node:http|node:https|node:net|fetch/i);
|
||||
}
|
||||
expect(source).not.toMatch(/\bDate\.now\s*\(|\bnew Date\s*\(\s*\)/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeFieldShapes', () => {
|
||||
test('classifies mixed JS and BSON value types on one field and reconciles counts', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{ mixed: 'hello' },
|
||||
{ mixed: 42 },
|
||||
{ mixed: 3.14 },
|
||||
{ mixed: fakeInt32(7) },
|
||||
{ mixed: fakeLong('9007199254740993') },
|
||||
{ mixed: fakeDouble(1.0) },
|
||||
{ mixed: true },
|
||||
{ mixed: new Date('2025-01-15T12:00:00.000Z') },
|
||||
{ mixed: null },
|
||||
{ mixed: fakeObjectId('507f1f77bcf86cd799439011') },
|
||||
{ mixed: [1, 2, 3] },
|
||||
{ mixed: { nested: 'a' } },
|
||||
{ mixed: fakeDecimal128('12.34') },
|
||||
{ mixed: new Uint8Array([1, 2]) },
|
||||
{}, // missing
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(docs.length);
|
||||
|
||||
const mixed = summary.fields.find(f => f.field === 'mixed');
|
||||
expect(mixed).toBeDefined();
|
||||
expect(mixed!.presentCount).toBe(14);
|
||||
expect(mixed!.missingCount).toBe(1);
|
||||
expect(mixed!.presentCount + mixed!.missingCount).toBe(summary.docCount);
|
||||
expect(sumTypeCounts(mixed!)).toBe(mixed!.presentCount);
|
||||
|
||||
expect(mixed!.typeCounts).toEqual({
|
||||
string: 1,
|
||||
int: 3, // 42, Int32(7), Long(...)
|
||||
double: 2, // 3.14, Double(1.0)
|
||||
bool: 1,
|
||||
date: 1,
|
||||
null: 1,
|
||||
objectId: 1,
|
||||
array: 1,
|
||||
object: 1,
|
||||
other: 2, // Decimal128, Uint8Array
|
||||
});
|
||||
});
|
||||
|
||||
test('tracks one level of nested parent.child keys and stops at depth 1', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
meta: {
|
||||
exchange: 'TSX',
|
||||
deep: { level2: 'ignored' },
|
||||
recordedAt: new Date('2025-02-01T00:00:00Z'),
|
||||
},
|
||||
arr: [{ insideArray: 1 }],
|
||||
bsonObj: fakeObjectId('507f1f77bcf86cd799439012'),
|
||||
},
|
||||
{
|
||||
meta: {
|
||||
exchange: 'NYSE',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
const fieldNames = summary.fields.map(f => f.field);
|
||||
|
||||
expect(fieldNames).toEqual([
|
||||
'arr',
|
||||
'bsonObj',
|
||||
'meta',
|
||||
'meta.deep',
|
||||
'meta.exchange',
|
||||
'meta.recordedAt',
|
||||
]);
|
||||
expect(fieldNames).not.toContain('meta.deep.level2');
|
||||
expect(fieldNames).not.toContain('bsonObj._bsontype');
|
||||
|
||||
const metaExchange = summary.fields.find(f => f.field === 'meta.exchange')!;
|
||||
expect(metaExchange.presentCount).toBe(2);
|
||||
expect(metaExchange.missingCount).toBe(0);
|
||||
expect(metaExchange.typeCounts.string).toBe(2);
|
||||
|
||||
const metaDeep = summary.fields.find(f => f.field === 'meta.deep')!;
|
||||
expect(metaDeep.presentCount).toBe(1);
|
||||
expect(metaDeep.missingCount).toBe(1);
|
||||
expect(metaDeep.typeCounts.object).toBe(1);
|
||||
});
|
||||
|
||||
test('keeps literal dotted top-level keys distinct from nested parent.child keys', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
'meta.exchange': 'LITERAL_EXCHANGE',
|
||||
meta: {
|
||||
exchange: 42,
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(1);
|
||||
|
||||
const literalField = summary.fields.find(f => f.field === 'meta\\.exchange');
|
||||
const nestedField = summary.fields.find(f => f.field === 'meta.exchange');
|
||||
expect(literalField).toBeDefined();
|
||||
expect(nestedField).toBeDefined();
|
||||
|
||||
expect(literalField!.presentCount).toBe(1);
|
||||
expect(literalField!.missingCount).toBe(0);
|
||||
expect(literalField!.typeCounts.string).toBe(1);
|
||||
expect(literalField!.typeCounts.int).toBe(0);
|
||||
expect(literalField!.examples).toEqual(['LITERAL_EXCHANGE']);
|
||||
|
||||
expect(nestedField!.presentCount).toBe(1);
|
||||
expect(nestedField!.missingCount).toBe(0);
|
||||
expect(nestedField!.typeCounts.int).toBe(1);
|
||||
expect(nestedField!.typeCounts.string).toBe(0);
|
||||
expect(nestedField!.examples).toEqual(['42']);
|
||||
});
|
||||
|
||||
test('classifies all five string pattern classes and tracks min/max string length', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{ s: '2024-02-29' }, // valid leap-year ymd (len 10)
|
||||
{ s: '2023-02-29' }, // invalid calendar date -> other (len 10)
|
||||
{ s: '2025-05-01T14:30:00Z' }, // isoDatetime (len 20)
|
||||
{ s: '2025-05-01T14:30:00.123-04:00' }, // isoDatetime (len 29)
|
||||
{ s: '-123.45' }, // numeric (len 7)
|
||||
{ s: '1.5e-4' }, // numeric (len 6)
|
||||
{ s: '' }, // emptyOrWhitespace (len 0)
|
||||
{ s: ' \t ' }, // emptyOrWhitespace (len 5)
|
||||
{ s: 'AAPL.US' }, // other (len 7)
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
const field = summary.fields.find(f => f.field === 's')!;
|
||||
|
||||
expect(field.typeCounts.string).toBe(9);
|
||||
expect(field.stringStats).toEqual({
|
||||
minLength: 0,
|
||||
maxLength: 29,
|
||||
patterns: {
|
||||
ymd: 1,
|
||||
isoDatetime: 2,
|
||||
numeric: 2,
|
||||
emptyOrWhitespace: 2,
|
||||
other: 2,
|
||||
},
|
||||
});
|
||||
expect(sumPatternCounts(field)).toBe(field.typeCounts.string);
|
||||
});
|
||||
|
||||
test('truncates and caps examples, suppresses _id and _id.* examples, and validates bounds', () => {
|
||||
const docs: Record<string, unknown>[] = [
|
||||
{
|
||||
_id: fakeObjectId('507f1f77bcf86cd799439011'),
|
||||
symbol: 'ZZZZ',
|
||||
note: 'line1\nline2\twith a very long description that must be truncated',
|
||||
},
|
||||
{
|
||||
_id: { key: 'secret-composite-id' },
|
||||
symbol: 'AAAA',
|
||||
note: 'short',
|
||||
},
|
||||
{
|
||||
_id: 'string-id-should-never-appear',
|
||||
symbol: 'MMMM',
|
||||
},
|
||||
{
|
||||
symbol: 'BBBB',
|
||||
},
|
||||
];
|
||||
|
||||
const summary = summarizeFieldShapes(docs, { maxExamples: 2, maxExampleLength: 16 });
|
||||
const idField = summary.fields.find(f => f.field === '_id')!;
|
||||
const idChildField = summary.fields.find(f => f.field === '_id.key')!;
|
||||
const symbolField = summary.fields.find(f => f.field === 'symbol')!;
|
||||
const noteField = summary.fields.find(f => f.field === 'note')!;
|
||||
|
||||
expect(idField.examples).toEqual([]);
|
||||
expect(idChildField.examples).toEqual([]);
|
||||
expect(symbolField.examples).toEqual(['AAAA', 'BBBB']);
|
||||
expect(noteField.examples.length).toBe(2);
|
||||
expect(noteField.examples[0]).toBe('line1 line2 w...');
|
||||
expect(noteField.examples[0]!.length).toBeLessThanOrEqual(16);
|
||||
expect(noteField.examples[1]).toBe('short');
|
||||
|
||||
expect(() => summarizeFieldShapes(docs, { maxExamples: -1 })).toThrow(RangeError);
|
||||
expect(() => summarizeFieldShapes(docs, { maxExamples: MAX_EXAMPLES_CAP + 1 })).toThrow(
|
||||
RangeError
|
||||
);
|
||||
expect(() => summarizeFieldShapes(docs, { maxExampleLength: 0 })).toThrow(RangeError);
|
||||
expect(() =>
|
||||
summarizeFieldShapes(docs, { maxExampleLength: MAX_EXAMPLE_LENGTH_CAP + 1 })
|
||||
).toThrow(RangeError);
|
||||
});
|
||||
|
||||
test('produces deep-equal output for shuffled input order and handles empty iterable', () => {
|
||||
expect(summarizeFieldShapes([])).toEqual({ docCount: 0, fields: [] });
|
||||
|
||||
const original: Record<string, unknown>[] = [
|
||||
{ _id: fakeObjectId('000000000000000000000001'), z: 'delta', a: 10, meta: { k: 'v3' } },
|
||||
{ _id: fakeObjectId('000000000000000000000002'), z: 'alpha', a: 2.5, meta: { k: 'v1' } },
|
||||
{ _id: fakeObjectId('000000000000000000000003'), z: 'charlie', b: true, meta: { k: 'v4' } },
|
||||
{ _id: fakeObjectId('000000000000000000000004'), z: 'bravo', a: null, meta: { k: 'v2' } },
|
||||
];
|
||||
const shuffled = [original[2]!, original[0]!, original[3]!, original[1]!];
|
||||
|
||||
const a = summarizeFieldShapes(original, { maxExamples: 2 });
|
||||
const b = summarizeFieldShapes(shuffled, { maxExamples: 2 });
|
||||
|
||||
expect(b).toEqual(a);
|
||||
expect(a.fields.map(f => f.field)).toEqual(['_id', 'a', 'b', 'meta', 'meta.k', 'z']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readFieldShapes', () => {
|
||||
test('calls only find() with limit and promoteValues/promoteLongs false, closes cursors, and enforces client limit', async () => {
|
||||
const docsByCollection: Record<string, Record<string, unknown>[]> = {
|
||||
qmDividends: [
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439011'), amount: fakeDouble(0.25), currency: 'USD' },
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439012'), amount: fakeDouble(0.5), currency: 'CAD' },
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439013'), amount: fakeDouble(1.0), currency: 'USD' },
|
||||
],
|
||||
ceoShorts: [
|
||||
{ _id: fakeObjectId('507f1f77bcf86cd799439014'), symbol: 'ABC', shares: fakeInt32(1000) },
|
||||
],
|
||||
};
|
||||
|
||||
const { reader, calls, closedCollections, pullsByCollection } = createFakeReader(
|
||||
docsByCollection,
|
||||
{
|
||||
ignoreLimit: true,
|
||||
failIterOnCollection: 'qmDividends',
|
||||
failIterAtIndex: 2,
|
||||
}
|
||||
);
|
||||
|
||||
const result = await readFieldShapes(reader, {
|
||||
collections: ['qmDividends', 'ceoShorts', 'qmDividends'],
|
||||
limit: 2,
|
||||
batchSize: 500,
|
||||
});
|
||||
|
||||
expect(calls.length).toBe(2);
|
||||
expect(calls.map(c => c.collectionName)).toEqual(['ceoShorts', 'qmDividends']);
|
||||
for (const call of calls) {
|
||||
expect(call.filter).toEqual({});
|
||||
expect(call.options).toEqual({
|
||||
limit: 2,
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
batchSize: 500,
|
||||
});
|
||||
}
|
||||
expect(closedCollections).toEqual(['ceoShorts', 'qmDividends']);
|
||||
// Breaks immediately after recording the limit-th doc without pulling a 3rd item
|
||||
expect(pullsByCollection).toEqual({ ceoShorts: 1, qmDividends: 2 });
|
||||
|
||||
// Defensively capped at limit=2 even though fake reader ignored limit
|
||||
expect(result.limit).toBe(2);
|
||||
expect(result.totalDocsSampled).toBe(3);
|
||||
const qmDiv = result.collections.find(c => c.collection === 'qmDividends')!;
|
||||
expect(qmDiv.docCount).toBe(2);
|
||||
const amountField = qmDiv.fields.find(f => f.field === 'amount')!;
|
||||
expect(amountField.typeCounts.double).toBe(2);
|
||||
});
|
||||
|
||||
test('defaults to all allowlisted collections and DEFAULT_FIELD_SHAPE_LIMIT', async () => {
|
||||
const { reader, calls } = createFakeReader({});
|
||||
const result = await readFieldShapes(reader);
|
||||
|
||||
expect(result.limit).toBe(DEFAULT_FIELD_SHAPE_LIMIT);
|
||||
expect(result.maxExamples).toBe(DEFAULT_MAX_EXAMPLES);
|
||||
expect(result.maxExampleLength).toBe(DEFAULT_MAX_EXAMPLE_LENGTH);
|
||||
expect(calls.length).toBe(FIELD_SHAPE_PROBE_COLLECTIONS.length);
|
||||
for (const call of calls) {
|
||||
expect(call.options).toEqual({
|
||||
limit: DEFAULT_FIELD_SHAPE_LIMIT,
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
test('rejects invalid limit, unknown collection, and non-read-only reader before any query', async () => {
|
||||
const nonRo = createFakeReader({}, { readOnly: false });
|
||||
await expect(readFieldShapes(nonRo.reader)).rejects.toThrow(/read-only/i);
|
||||
expect(nonRo.calls.length).toBe(0);
|
||||
|
||||
const badLimitHigh = createFakeReader({});
|
||||
await expect(
|
||||
readFieldShapes(badLimitHigh.reader, { limit: MAX_FIELD_SHAPE_LIMIT + 1 })
|
||||
).rejects.toThrow(RangeError);
|
||||
expect(badLimitHigh.calls.length).toBe(0);
|
||||
|
||||
const badLimitZero = createFakeReader({});
|
||||
await expect(readFieldShapes(badLimitZero.reader, { limit: 0 })).rejects.toThrow(RangeError);
|
||||
expect(badLimitZero.calls.length).toBe(0);
|
||||
|
||||
const unknownCol = createFakeReader({});
|
||||
let caught: unknown;
|
||||
try {
|
||||
await readFieldShapes(unknownCol.reader, { collections: ['eodPrices', 'notACollection'] });
|
||||
} catch (err) {
|
||||
caught = err;
|
||||
}
|
||||
expect(caught).toBeInstanceOf(UnknownProbeCollectionError);
|
||||
expect((caught as UnknownProbeCollectionError).collectionName).toBe('notACollection');
|
||||
expect(unknownCol.calls.length).toBe(0);
|
||||
});
|
||||
|
||||
test('rejects buffered array cursor with TypeError and surfaces per-collection errors with cause', async () => {
|
||||
const buffered = createFakeReader(
|
||||
{ eodPrices: [{ date: '2025-01-02' }] },
|
||||
{ returnBufferedArrayOnCollection: 'eodPrices' }
|
||||
);
|
||||
await expect(
|
||||
readFieldShapes(buffered.reader, { collections: ['eodPrices'] })
|
||||
).rejects.toThrow(TypeError);
|
||||
|
||||
const findErr = createFakeReader({}, { failFindOnCollection: 'qmFilings' });
|
||||
let caughtFind: unknown;
|
||||
try {
|
||||
await readFieldShapes(findErr.reader, { collections: ['eodPrices', 'qmFilings'] });
|
||||
} catch (err) {
|
||||
caughtFind = err;
|
||||
}
|
||||
expect(caughtFind).toBeInstanceOf(Error);
|
||||
expect((caughtFind as Error).message).toContain('qmFilings');
|
||||
expect((caughtFind as Error).cause).toBeInstanceOf(Error);
|
||||
|
||||
const iterErr = createFakeReader(
|
||||
{ qmEarnings: [{ a: 1 }, { a: 2 }] },
|
||||
{ failIterOnCollection: 'qmEarnings' }
|
||||
);
|
||||
let caughtIter: unknown;
|
||||
try {
|
||||
await readFieldShapes(iterErr.reader, { collections: ['qmEarnings'] });
|
||||
} catch (err) {
|
||||
caughtIter = err;
|
||||
}
|
||||
expect(caughtIter).toBeInstanceOf(Error);
|
||||
expect((caughtIter as Error).message).toContain('qmEarnings');
|
||||
expect((caughtIter as Error).cause).toBeInstanceOf(Error);
|
||||
expect(iterErr.closedCollections).toEqual(['qmEarnings']);
|
||||
|
||||
const closeErr = createFakeReader(
|
||||
{ teMarketData: [{ country: 'US' }] },
|
||||
{ failCloseOnCollection: 'teMarketData' }
|
||||
);
|
||||
let caughtClose: unknown;
|
||||
try {
|
||||
await readFieldShapes(closeErr.reader, { collections: ['teMarketData'] });
|
||||
} catch (err) {
|
||||
caughtClose = err;
|
||||
}
|
||||
expect(caughtClose).toBeInstanceOf(Error);
|
||||
expect((caughtClose as Error).message).toContain('teMarketData');
|
||||
expect((caughtClose as Error).cause).toBeInstanceOf(Error);
|
||||
});
|
||||
});
|
||||
|
||||
interface MdastNode {
|
||||
type: string;
|
||||
value?: string;
|
||||
children?: MdastNode[];
|
||||
}
|
||||
|
||||
function decodeHtmlEntities(text: string): string {
|
||||
return text.replace(/&(amp|lt|gt|#(\d+));/g, (_, entity: string, code?: string) => {
|
||||
if (code !== undefined) {
|
||||
return String.fromCharCode(Number(code));
|
||||
}
|
||||
switch (entity) {
|
||||
case 'amp':
|
||||
return '&';
|
||||
case 'lt':
|
||||
return '<';
|
||||
case 'gt':
|
||||
return '>';
|
||||
default:
|
||||
return `&${entity};`;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function parseGfmTables(markdown: string): MdastNode[][] {
|
||||
const ast = markdownPlugin.parsers.markdown.parse(
|
||||
markdown,
|
||||
{} as ParserOptions
|
||||
) as unknown as MdastNode;
|
||||
const rows: MdastNode[][] = [];
|
||||
for (const node of ast.children ?? []) {
|
||||
if (node.type !== 'table') {
|
||||
continue;
|
||||
}
|
||||
const tableRows = node.children ?? [];
|
||||
for (let rowIndex = 1; rowIndex < tableRows.length; rowIndex++) {
|
||||
rows.push(tableRows[rowIndex]?.children ?? []);
|
||||
}
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
|
||||
function extractGfmCodeCellValues(cell: MdastNode): string[] {
|
||||
const nodes = cell.children ?? [];
|
||||
if (nodes.length === 1 && nodes[0]?.type === 'text' && nodes[0].value === '—') {
|
||||
return [];
|
||||
}
|
||||
|
||||
const values: string[] = [];
|
||||
let i = 0;
|
||||
while (i < nodes.length) {
|
||||
const node = nodes[i]!;
|
||||
if (node.type === 'inlineCode') {
|
||||
values.push(node.value ?? '');
|
||||
i += 1;
|
||||
} else if (node.type === 'html' && node.value === '<code>') {
|
||||
let inner = '';
|
||||
i += 1;
|
||||
let closed = false;
|
||||
while (i < nodes.length) {
|
||||
const innerNode = nodes[i]!;
|
||||
if (innerNode.type === 'html' && innerNode.value === '</code>') {
|
||||
closed = true;
|
||||
i += 1;
|
||||
break;
|
||||
}
|
||||
if (innerNode.type !== 'text') {
|
||||
throw new Error(
|
||||
`Unexpected Markdown node "${innerNode.type}" inside <code> element: ${JSON.stringify(innerNode)}`
|
||||
);
|
||||
}
|
||||
inner += decodeHtmlEntities(innerNode.value ?? '');
|
||||
i += 1;
|
||||
}
|
||||
if (!closed) {
|
||||
throw new Error('Unclosed <code> HTML element in GFM table cell');
|
||||
}
|
||||
values.push(inner);
|
||||
} else if (node.type === 'text' && node.value === ', ') {
|
||||
i += 1;
|
||||
} else {
|
||||
throw new Error(`Unexpected node in GFM code cell: ${JSON.stringify(node)}`);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
describe('renderFieldShapesMarkdown', () => {
|
||||
test('renders byte-identical Markdown with bounded-sample header, valid GFM code spans, and empty collection notice', async () => {
|
||||
const docsA = [
|
||||
{
|
||||
_id: fakeObjectId('000000000000000000000001'),
|
||||
'pipe|col': 'val|with`ticks\\slash',
|
||||
'slash\\|field': 'slash\\|pipe*em*_u_<tag>&',
|
||||
'tick`field\nname': '`leading`',
|
||||
edge: 'double``ticks',
|
||||
dt: '2025-01-02',
|
||||
},
|
||||
{
|
||||
_id: fakeObjectId('000000000000000000000002'),
|
||||
'pipe|col': 'slash\\|pipe',
|
||||
'slash\\|field': 'slash\\\\|pipe',
|
||||
'tick`field\nname': ' spaced ',
|
||||
edge: '',
|
||||
dt: '2025-01-03',
|
||||
},
|
||||
];
|
||||
const docsB = [docsA[1]!, docsA[0]!];
|
||||
|
||||
const run1 = await readFieldShapes(
|
||||
createFakeReader({ eodPrices: docsA, qmSplits: [] }).reader,
|
||||
{ collections: ['eodPrices', 'qmSplits'], limit: 500 }
|
||||
);
|
||||
const run2 = await readFieldShapes(
|
||||
createFakeReader({ eodPrices: docsB, qmSplits: [] }).reader,
|
||||
{ collections: ['qmSplits', 'eodPrices'], limit: 500 }
|
||||
);
|
||||
|
||||
const md1 = renderFieldShapesMarkdown(run1);
|
||||
const md2 = renderFieldShapesMarkdown(run2);
|
||||
|
||||
expect(md1).toBe(md2);
|
||||
expect(md1).toContain('bounded sample');
|
||||
expect(md1).toContain('Sample limit per collection:** 500');
|
||||
expect(md1).toContain('Total documents sampled:** 2');
|
||||
expect(md1).toContain('_No documents sampled._');
|
||||
|
||||
const tableRows = parseGfmTables(md1);
|
||||
expect(tableRows.length).toBe(6);
|
||||
|
||||
const visibleByField = new Map<string, string[]>();
|
||||
for (const cells of tableRows) {
|
||||
expect(cells.length).toBe(5);
|
||||
const parsedField = extractGfmCodeCellValues(cells[0]!);
|
||||
expect(parsedField.length).toBe(1);
|
||||
const parsedExamples = extractGfmCodeCellValues(cells[4]!);
|
||||
visibleByField.set(parsedField[0]!, parsedExamples);
|
||||
}
|
||||
|
||||
expect(visibleByField.get('pipe|col')).toEqual(['slash\\|pipe', 'val|with`ticks\\slash']);
|
||||
expect(visibleByField.get('slash\\\\|field')).toEqual([
|
||||
'slash\\\\|pipe',
|
||||
'slash\\|pipe*em*_u_<tag>&',
|
||||
]);
|
||||
expect(visibleByField.get('tick`field name')).toEqual([' spaced ', '`leading`']);
|
||||
expect(visibleByField.get('edge')).toEqual(['', 'double``ticks']);
|
||||
expect(visibleByField.get('_id')).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('CLI arg parsing and headless probe runner', () => {
|
||||
test('parseProbeSourceFieldShapesArgs validates flags without opening any DB connection', () => {
|
||||
expect(parseProbeSourceFieldShapesArgs(['--help'])).toEqual({ help: true });
|
||||
expect(() => parseProbeSourceFieldShapesArgs([])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out', ' '])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=0'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', '-1'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() =>
|
||||
parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit', String(MAX_FIELD_SHAPE_LIMIT + 1)])
|
||||
).toThrow(/--limit/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=abc'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--limit=1.5'])).toThrow(
|
||||
/--limit/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--bogus'])).toThrow(
|
||||
/Unknown argument/
|
||||
);
|
||||
expect(() =>
|
||||
parseProbeSourceFieldShapesArgs(['--out=tmp/out.md', '--collections=eodPrices,bogusCol'])
|
||||
).toThrow(UnknownProbeCollectionError);
|
||||
|
||||
const parsed = parseProbeSourceFieldShapesArgs([
|
||||
'--out',
|
||||
'./tmp/report.md',
|
||||
'--limit',
|
||||
'250',
|
||||
'--collections',
|
||||
'qmDividends,ceoShorts,qmDividends',
|
||||
]);
|
||||
expect(parsed).toEqual({
|
||||
help: false,
|
||||
outPath: './tmp/report.md',
|
||||
limit: 250,
|
||||
collections: ['ceoShorts', 'qmDividends'],
|
||||
});
|
||||
});
|
||||
|
||||
test('runSourceFieldShapesProbe rejects non-read-only client before any query and writes report headlessly', async () => {
|
||||
let getCollectionCalls = 0;
|
||||
let closeCalls = 0;
|
||||
|
||||
const writableClient: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => false,
|
||||
getCollection() {
|
||||
getCollectionCalls += 1;
|
||||
throw new Error('should never be called');
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: writableClient,
|
||||
closeMongo: () => {
|
||||
closeCalls += 1;
|
||||
},
|
||||
writeFile: () => {},
|
||||
writeStdout: () => {},
|
||||
},
|
||||
{ outPath: './tmp/should-not-write.md' }
|
||||
)
|
||||
).rejects.toThrow(/read-only/i);
|
||||
expect(getCollectionCalls).toBe(0);
|
||||
expect(closeCalls).toBe(1);
|
||||
|
||||
const writtenFiles: Array<{ filePath: string; content: string }> = [];
|
||||
const stdoutChunks: string[] = [];
|
||||
let roCloseCalls = 0;
|
||||
|
||||
const roClient: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection(name: string) {
|
||||
return {
|
||||
find() {
|
||||
const docs = name === 'ceoShorts' ? [{ symbol: 'XYZ', shares: 100 }] : [];
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
async close() {},
|
||||
};
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const output = await runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: roClient,
|
||||
closeMongo: () => {
|
||||
roCloseCalls += 1;
|
||||
},
|
||||
writeFile: (filePath, content) => {
|
||||
writtenFiles.push({ filePath, content });
|
||||
},
|
||||
writeStdout: text => {
|
||||
stdoutChunks.push(text);
|
||||
},
|
||||
},
|
||||
{
|
||||
outPath: './tmp/field-shapes.md',
|
||||
limit: 10,
|
||||
collections: ['ceoShorts'],
|
||||
}
|
||||
);
|
||||
|
||||
expect(roCloseCalls).toBe(1);
|
||||
expect(writtenFiles.length).toBe(1);
|
||||
expect(writtenFiles[0]!.filePath).toBe('./tmp/field-shapes.md');
|
||||
expect(writtenFiles[0]!.content).toBe(output.markdown);
|
||||
expect(stdoutChunks.join('')).toContain('Documents sampled: 1');
|
||||
});
|
||||
});
|
||||
29
bun.lock
29
bun.lock
|
|
@ -355,6 +355,17 @@
|
|||
"typescript": "^5.3.0",
|
||||
},
|
||||
},
|
||||
"libs/data/duckdb": {
|
||||
"name": "@stock-bot/duckdb",
|
||||
"version": "1.0.0",
|
||||
"dependencies": {
|
||||
"@duckdb/node-api": "^1.4.4-r.1",
|
||||
"@stock-bot/research": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0",
|
||||
},
|
||||
},
|
||||
"libs/data/mongodb": {
|
||||
"name": "@stock-bot/mongodb",
|
||||
"version": "1.0.0",
|
||||
|
|
@ -540,6 +551,22 @@
|
|||
|
||||
"@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="],
|
||||
|
||||
"@duckdb/node-api": ["@duckdb/node-api@1.4.4-r.4", "", { "dependencies": { "@duckdb/node-bindings": "1.4.4-r.4" } }, "sha512-yUotG8wPSmmEFxAODt07rXJZgV2fhvzhnZX3wrMspQNEaNVwXArzakgKyfakZkYL9me7SK9eDnXYv/XbdifWEg=="],
|
||||
|
||||
"@duckdb/node-bindings": ["@duckdb/node-bindings@1.4.4-r.4", "", { "optionalDependencies": { "@duckdb/node-bindings-darwin-arm64": "1.4.4-r.4", "@duckdb/node-bindings-darwin-x64": "1.4.4-r.4", "@duckdb/node-bindings-linux-arm64": "1.4.4-r.4", "@duckdb/node-bindings-linux-x64": "1.4.4-r.4", "@duckdb/node-bindings-win32-arm64": "1.4.4-r.4", "@duckdb/node-bindings-win32-x64": "1.4.4-r.4" } }, "sha512-JYjCaZmqvqrjFBjT3Q6jnb3OFz26lAUTFXUka/HQRxWRy23ZiURZwPYMLkyFBLHa696hNlC85M/EWXDRFnDIfg=="],
|
||||
|
||||
"@duckdb/node-bindings-darwin-arm64": ["@duckdb/node-bindings-darwin-arm64@1.4.4-r.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-ozQbuBlV+01WzyXcqXjEV3TbN+qQ8UcelwPmQaqBn86pdXQHuYGuS8K9a5yATsg+JvivqHQSb95OBHdP7FYDkA=="],
|
||||
|
||||
"@duckdb/node-bindings-darwin-x64": ["@duckdb/node-bindings-darwin-x64@1.4.4-r.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-quoPmg26/fpLM80UNMXYSYKGnXJUiqKTSlDIgONQiMVYXJqPc2yz9qwcTuZgaQx7JhD2m1D/cc+h/4d8yVD79Q=="],
|
||||
|
||||
"@duckdb/node-bindings-linux-arm64": ["@duckdb/node-bindings-linux-arm64@1.4.4-r.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-Ve+kJ9+IqF5VBNWDzlUeg1xxKGHGqT9MJPxjRTSULgCpguL9ok13Klhw7WJQOs5ycB+osQe/40t5hOZk3cK82g=="],
|
||||
|
||||
"@duckdb/node-bindings-linux-x64": ["@duckdb/node-bindings-linux-x64@1.4.4-r.4", "", { "os": "linux", "cpu": "x64" }, "sha512-jBTL/WvfwxLToFa/pVHfT6elMtltJGnc3wSuxZD9OfMltit9YUdVFS37vBFQzXMT1Z8OWjtSjMh+zPKxOwHLHA=="],
|
||||
|
||||
"@duckdb/node-bindings-win32-arm64": ["@duckdb/node-bindings-win32-arm64@1.4.4-r.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-4tqE7r1c4wCqgm1iBfW/rP6B67nkHK1Pyj6dT8T3aqupKk2eV0QgKPBYtGOqOlE+jdhj4El9WKye7eTJ59yjZQ=="],
|
||||
|
||||
"@duckdb/node-bindings-win32-x64": ["@duckdb/node-bindings-win32-x64@1.4.4-r.4", "", { "os": "win32", "cpu": "x64" }, "sha512-lclo7ZibsYuCHd0ru5j9sw9x+wfXWOiNWIOjW3rcX9675xD7j4CB3RlWfZkBgdajLuXtRuo5FFfQZY249a7IlA=="],
|
||||
|
||||
"@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="],
|
||||
|
||||
"@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="],
|
||||
|
|
@ -704,6 +731,8 @@
|
|||
|
||||
"@stock-bot/di": ["@stock-bot/di@workspace:libs/core/di"],
|
||||
|
||||
"@stock-bot/duckdb": ["@stock-bot/duckdb@workspace:libs/data/duckdb"],
|
||||
|
||||
"@stock-bot/engine": ["@stock-bot/engine@workspace:apps/stock/engine"],
|
||||
|
||||
"@stock-bot/handler-registry": ["@stock-bot/handler-registry@workspace:libs/core/handler-registry"],
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ Authoritative specification for `data-pipeline`, PostgreSQL reference schemas, D
|
|||
| `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`. `eodSymbolChange`: only `230` US rows (`2024-08..2025-07`). | Filter `splitratio == 1`; ignore `usdFxRate`; never rely on `eodSymbolChange` for multi-year ticker history. |
|
||||
| `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`. |
|
||||
|
||||
---
|
||||
|
|
@ -184,6 +184,16 @@ CREATE INDEX IF NOT EXISTS idx_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).
|
||||
|
||||
---
|
||||
|
||||
## 3. Curated Storage Schemas
|
||||
|
|
|
|||
|
|
@ -13,6 +13,7 @@ Start here. Every document below has a single responsibility; historical sprint
|
|||
| **[DATA-CONTRACTS.md](DATA-CONTRACTS.md)** | Raw MongoDB provider quirks, PostgreSQL security-master DDL, split/volume un-adjustment rules, `known_at` derivation, DuckDB/Parquet & QuestDB `10.2.0` schemas, and `MarketDataStore` API | Before touching `data-pipeline`, `data-ingestion`, SQL migrations, or `MarketDataStore` |
|
||||
| **[VALIDATION-AND-RIGOR.md](VALIDATION-AND-RIGOR.md)** | Canonical metric definitions, `trial_ledger` schema, effective-trials DSR ($\hat{N}$), CSCV PBO, Purged CPCV/Walk-Forward, rolling 6-month Vault + Post-2023 Recency Gate, lifecycle gates, and Dual Live Drift + IB/TSX execution rules | Before touching `libs/calculations`, `libs/research`, validation workflows, or paper/live execution |
|
||||
| **[servers.md](servers.md)** | Host roles (`quant` `12900K` research/data server, `9900K` isolated IB live/paper host, `TrueNAS` cold storage, dev workstation) and port/storage layout | Infrastructure, deployment, and worker sizing |
|
||||
| **[data-pipeline/rust-migration-evaluation.md](data-pipeline/rust-migration-evaluation.md)** | Evidence-based evaluation of keeping `apps/stock/data-pipeline` in TypeScript vs. moving bulk MongoDB streaming or the full pipeline into Rust (`tools/curate-etl`) | Before `M2` adds PIT fundamentals, `ceoPosts`, or `bars_1m` QuestDB ingestion |
|
||||
|
||||
---
|
||||
|
||||
|
|
|
|||
78
design/data-pipeline/m1-ca-study-result.json
Normal file
78
design/data-pipeline/m1-ca-study-result.json
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
{
|
||||
"summary": {
|
||||
"adjustment": "total",
|
||||
"ca_bars_rows": 8446226,
|
||||
"ca_shorts_rows": 459930,
|
||||
"ca_filings_rows": 725435,
|
||||
"shorts_panel_rows": 4541173,
|
||||
"vault_bar_leaks": 0
|
||||
},
|
||||
"shorts_trial": {
|
||||
"trial_id": 1,
|
||||
"created_at": "2026-11-30T15:16:14.251727+00:00",
|
||||
"expression_hash": "b8d63783a3803087c922ce7fe332340264db340f8d7de1b78cfaab097c17e938",
|
||||
"n_obs": 1983,
|
||||
"sharpe_unann": 0.10055685659710986,
|
||||
"skewness": -0.1559440430924711,
|
||||
"kurtosis": 15.987384989738644
|
||||
},
|
||||
"shorts_dsr": {
|
||||
"trial_id": 1,
|
||||
"cluster_size": 1,
|
||||
"effective_trials": 1.0,
|
||||
"mean_correlation": null,
|
||||
"pairs_used": 0,
|
||||
"pairs_skipped": 0,
|
||||
"sr0": 0.0,
|
||||
"standard_error": 0.023055762683025283,
|
||||
"dsr": 0.9999935402185955,
|
||||
"passes_gate": true
|
||||
},
|
||||
"shorts_mean_rank_ic": 0.00694633488509233,
|
||||
"shorts_rank_ic_nw_t": 2.7256714674429414,
|
||||
"shorts_mean_spread": 0.010679776876364164,
|
||||
"shorts_turnover": 0.40718536083796214,
|
||||
"shorts_recency": {
|
||||
"pass": true,
|
||||
"reason": "passed",
|
||||
"pre_n": 1456,
|
||||
"post_n": 527,
|
||||
"pre_mean": 0.006950115972062361,
|
||||
"post_mean": 0.006935888466442682,
|
||||
"ratio": 0.9979529110482659
|
||||
},
|
||||
"filings_trial": {
|
||||
"trial_id": 2,
|
||||
"created_at": "2026-11-30T15:16:17.977209+00:00",
|
||||
"expression_hash": "c642ca87d95bb8436045ba34a231096d74df559f0e3baf91962ba0adbe3151da",
|
||||
"n_obs": 885,
|
||||
"sharpe_unann": -0.08030767099801248,
|
||||
"skewness": -9.933468390420595,
|
||||
"kurtosis": 115.43676350904063
|
||||
},
|
||||
"filings_dsr": {
|
||||
"trial_id": 2,
|
||||
"cluster_size": 2,
|
||||
"effective_trials": 2.0,
|
||||
"mean_correlation": null,
|
||||
"pairs_used": 0,
|
||||
"pairs_skipped": 1,
|
||||
"sr0": 0.06647178849749248,
|
||||
"standard_error": 0.02091720841503682,
|
||||
"dsr": 1.1320926489926893e-12,
|
||||
"passes_gate": false
|
||||
},
|
||||
"filings_events_used": 101522,
|
||||
"filings_n_dates": 885,
|
||||
"filings_car_mean": -0.022160113638103773,
|
||||
"filings_car_nw_t": -1.1695875860209246,
|
||||
"filings_recency": {
|
||||
"pass": false,
|
||||
"reason": "sign_flipped",
|
||||
"pre_n": 615,
|
||||
"post_n": 270,
|
||||
"pre_mean": 0.002165839268979803,
|
||||
"post_mean": -0.07756922859312747,
|
||||
"ratio": -35.81485925761503
|
||||
}
|
||||
}
|
||||
117
design/data-pipeline/m1-quant-benchmark-result.json
Normal file
117
design/data-pipeline/m1-quant-benchmark-result.json
Normal file
|
|
@ -0,0 +1,117 @@
|
|||
{
|
||||
"host": "quant",
|
||||
"curated_root": "/mnt/data/stockbot/m1-isolated/curated",
|
||||
"duckdb_version": "1.5.6",
|
||||
"polars_version": "1.44.2",
|
||||
"duckdb_budget": {
|
||||
"memory_limit": "6GB",
|
||||
"threads": 4,
|
||||
"temp_directory": "/mnt/data/stockbot/m1-isolated/tmp/duckdb"
|
||||
},
|
||||
"cache_state_note": "run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root).",
|
||||
"vault_cutoff_date": "2025-02-13",
|
||||
"vault_rows_on_disk": 3363755,
|
||||
"total_rows_in_scan": 78588295,
|
||||
"distinct_listings_in_scan": 59096,
|
||||
"scan_date_min": "2005-01-03",
|
||||
"scan_date_max": "2025-02-12",
|
||||
"nvda_pre_split_check": {
|
||||
"listing_id": 20815,
|
||||
"pre_split_2024_06_07": {
|
||||
"close": 1208.88,
|
||||
"raw_volume": 41238577.6,
|
||||
"dollar_volume": 49852491689.088005,
|
||||
"currency": "USD"
|
||||
},
|
||||
"post_split_2024_06_10": {
|
||||
"close": 121.79,
|
||||
"raw_volume": 314162688.0,
|
||||
"dollar_volume": 38261873771.520004,
|
||||
"currency": "USD"
|
||||
},
|
||||
"qm_pre_split_dollar_volume": 49852494590.4,
|
||||
"rel_diff": 5.81979301196025e-08,
|
||||
"within_1pct": true
|
||||
},
|
||||
"parquet_scan_vault_audit": {
|
||||
"explain_analyze_latency_secs": 4.2861,
|
||||
"total_files_read": 21,
|
||||
"parquet_scan_rows_emitted": 78592209,
|
||||
"pushed_filters": [
|
||||
"session_date>='2005-01-01'::DATE AND session_date<'2025-02-13'::DATE",
|
||||
"ts<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE",
|
||||
"known_at<'2025-02-13 00:00:00+00'::TIMESTAMP WITH TIME ZONE",
|
||||
"optional: currency IN ('USD', 'CAD')",
|
||||
"close>0.0",
|
||||
"volume>0.0"
|
||||
],
|
||||
"vault_session_date_pushed": true,
|
||||
"vault_ts_pushed": true,
|
||||
"vault_known_at_pushed": true
|
||||
},
|
||||
"poisoned_vault_canary": {
|
||||
"overlay_files_on_disk": 22,
|
||||
"overlay_files_read_by_parquet_scan": 21,
|
||||
"year_2026_partition_pruned": true,
|
||||
"poisoned_vault_rows_on_disk": 3373755,
|
||||
"canary_parquet_scan_rows_emitted": 78592209,
|
||||
"scan_cardinality_identical": true,
|
||||
"signal_metrics_bit_identical": true,
|
||||
"pass": true
|
||||
},
|
||||
"run1_fresh_conn": {
|
||||
"wall_secs": 4.4122,
|
||||
"sql_secs": 4.4088,
|
||||
"post_secs": 0.0033,
|
||||
"under_5s": true,
|
||||
"min_date": "2005-02-01",
|
||||
"max_date": "2025-02-05",
|
||||
"vault_cutoff_date": "2025-02-13",
|
||||
"n_sessions_evaluated": 5129,
|
||||
"mean_ic": 0.018401,
|
||||
"mean_q5_q1_spread": 0.001329,
|
||||
"mean_q5_turnover": 0.23419,
|
||||
"recency_gate": {
|
||||
"pass": true,
|
||||
"reason": "passed",
|
||||
"pre_n": 4592,
|
||||
"post_n": 537,
|
||||
"pre_mean": 0.018166680678707872,
|
||||
"post_mean": 0.020400683140664375,
|
||||
"ratio": 1.1229725177354413
|
||||
},
|
||||
"sharpe_unann": 0.05117,
|
||||
"sharpe_ann": 0.8123,
|
||||
"newey_west_t_stat": 2.0292,
|
||||
"newey_west_p_value": 0.042434,
|
||||
"dsr": 0.999927
|
||||
},
|
||||
"run2_warm_conn": {
|
||||
"wall_secs": 4.3086,
|
||||
"sql_secs": 4.3071,
|
||||
"post_secs": 0.0015,
|
||||
"under_5s": true,
|
||||
"min_date": "2005-02-01",
|
||||
"max_date": "2025-02-05",
|
||||
"vault_cutoff_date": "2025-02-13",
|
||||
"n_sessions_evaluated": 5129,
|
||||
"mean_ic": 0.018401,
|
||||
"mean_q5_q1_spread": 0.001329,
|
||||
"mean_q5_turnover": 0.23419,
|
||||
"recency_gate": {
|
||||
"pass": true,
|
||||
"reason": "passed",
|
||||
"pre_n": 4592,
|
||||
"post_n": 537,
|
||||
"pre_mean": 0.018166680678707872,
|
||||
"post_mean": 0.02040068314066438,
|
||||
"ratio": 1.1229725177354415
|
||||
},
|
||||
"sharpe_unann": 0.05117,
|
||||
"sharpe_ann": 0.8123,
|
||||
"newey_west_t_stat": 2.0292,
|
||||
"newey_west_p_value": 0.042434,
|
||||
"dsr": 0.999927
|
||||
},
|
||||
"both_runs_under_5s": true
|
||||
}
|
||||
167
design/data-pipeline/m1-source-field-shapes.md
Normal file
167
design/data-pipeline/m1-source-field-shapes.md
Normal file
|
|
@ -0,0 +1,167 @@
|
|||
# Source Field Shapes Report
|
||||
|
||||
- **Scope:** bounded sample, not a full scan (head sample via `find().limit()`, no aggregation or `$sample`)
|
||||
- **Sample limit per collection:** 1000
|
||||
- **Collections probed:** 8
|
||||
- **Total documents sampled:** 7435
|
||||
|
||||
## `ceoShorts` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-23T03:58:26.303Z`, `2025-06-23T03:58:27.035Z`, `2025-06-23T03:58:27.655Z` |
|
||||
| `id` | 100.0% (1000/1000) | int: 1000 | — | `101986246`, `101986286`, `101986333` |
|
||||
| `issue_name` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 18..37) | `AAJ CAPITAL 3 CORP.`, `ABERDEEN INTERNATIONAL INC. J`, `ADDED CAPITAL INC.` |
|
||||
| `market` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..2) | `TO`, `V` |
|
||||
| `net_change` | 100.0% (1000/1000) | int: 1000 | — | `-10`, `-100`, `-1000` |
|
||||
| `number_of_shares` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1`, `10` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..12) | `A.V`, `AA.V`, `AAA-P.V` |
|
||||
| `timestamp` | 100.0% (1000/1000) | double: 1000 | — | `1492239600000`, `1493535600000`, `1494831600000` |
|
||||
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-26T19:28:57.102Z`, `2025-06-26T19:28:57.127Z`, `2025-06-26T19:28:57.129Z` |
|
||||
|
||||
## `eodPrices` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `adjustedClose` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
|
||||
| `close` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
|
||||
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-07-11T02:13:56.412Z`, `2025-07-11T02:13:56.492Z`, `2025-07-11T02:13:56.694Z` |
|
||||
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2020-12-19`, `2020-12-20`, `2020-12-21` |
|
||||
| `eodSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 11..14) | `$ADS-USD.CC`, `$AFLOKI-USD.CC`, `$ANRX-USD.CC` |
|
||||
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `CC` |
|
||||
| `high` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
|
||||
| `low` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
|
||||
| `open` | 100.0% (1000/1000) | double: 1000 | — | `0.000001999999995`, `0.0000030000001061`, `0.0000039999999899` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 8..11) | `$ADS-USD`, `$AFLOKI-USD`, `$ANRX-USD` |
|
||||
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-08-13T14:09:20.036Z`, `2025-08-13T14:09:20.106Z`, `2025-08-13T14:09:20.135Z` |
|
||||
| `volume` | 100.0% (1000/1000) | int: 1000 | — | `0`, `1000242`, `1006139` |
|
||||
|
||||
## `qmDividends` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `amount` | 100.0% (1000/1000) | int: 10, double: 990 | — | `0`, `0.01`, `0.01167` |
|
||||
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.799Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.069Z` |
|
||||
| `currency` | 92.8% (928/1000) | string: 928 | other: 928 (len 3..3) | `CAD`, `USD` |
|
||||
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1987-03-31`, `1987-06-01`, `1987-06-25` |
|
||||
| `declared` | 96.5% (965/1000) | string: 965 | ymd: 965 (len 10..10) | `1987-03-25`, `1987-05-21`, `1987-05-27` |
|
||||
| `divflag` | 6.2% (62/1000) | string: 62 | other: 62 (len 2..2) | `EX`, `FI`, `SP` |
|
||||
| `divtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `D`, `S` |
|
||||
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `NGS`, `NSC`, `NSD` |
|
||||
| `frequency` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `A`, `I`, `M` |
|
||||
| `indicatedrate` | 66.0% (660/1000) | double: 660 | — | `0.01`, `0.01167`, `0.0125` |
|
||||
| `payable` | 99.7% (997/1000) | string: 997 | ymd: 997 (len 10..10) | `1987-04-20`, `1987-07-01`, `1987-07-20` |
|
||||
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..9) | `DBM:CA`, `DCM:CA`, `DHT.U:CA` |
|
||||
| `qualified` | 22.6% (226/1000) | string: 226 | other: 226 (len 1..1) | `N`, `Q` |
|
||||
| `record` | 99.6% (996/1000) | string: 996 | ymd: 996 (len 10..10) | `1987-04-06`, `1987-06-05`, `1987-07-01` |
|
||||
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1987-03-31T00:00:00.000Z`, `1987-06-01T00:00:00.000Z`, `1987-06-25T00:00:00.000Z` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..8) | `DBM`, `DCM`, `DHT.U` |
|
||||
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.080Z`, `2025-06-29T22:25:29.146Z`, `2025-06-29T22:25:29.148Z` |
|
||||
| `usdFxRate` | 25.6% (256/1000) | int: 253, double: 3 | — | `0.05`, `1`, `1.39556` |
|
||||
|
||||
## `qmEarnings` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `actualEps` | 100.0% (1000/1000) | string: 73, int: 34, double: 893 | other: 73 (len 3..3) | `-0.01`, `-0.02`, `-0.03` |
|
||||
| `announceTime` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `AMC`, `BTO`, `N/A` |
|
||||
| `consensusEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` |
|
||||
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.864Z`, `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z` |
|
||||
| `epsSurpriseDollar` | 100.0% (1000/1000) | string: 359, int: 66, double: 575 | other: 359 (len 3..3) | `-0.0033`, `-0.005`, `-0.01` |
|
||||
| `epsSurprisePercent` | 100.0% (1000/1000) | string: 366, int: 147, double: 487 | other: 366 (len 3..3) | `-0.6944`, `-0.7123`, `-0.8065` |
|
||||
| `estimatedEps` | 100.0% (1000/1000) | string: 347, int: 12, double: 641 | other: 347 (len 3..3) | `-0.02`, `-0.03`, `-0.04` |
|
||||
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX`, `NGS`, `NSC` |
|
||||
| `numOfEstimates` | 100.0% (1000/1000) | string: 42, int: 958 | other: 42 (len 3..3) | `0`, `1`, `10` |
|
||||
| `period` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..7) | `N/A`, `Q1 1995`, `Q1 1996` |
|
||||
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..8) | `DLCG:CA`, `DPM:CA`, `DSV:CA` |
|
||||
| `quarterEnd` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1994-09-30`, `1994-12-31`, `1995-03-31` |
|
||||
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1994-10-26T00:00:00.000Z`, `1994-10-27T00:00:00.000Z`, `1994-11-02T00:00:00.000Z` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..5) | `DLCG`, `DPM`, `DSV` |
|
||||
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.073Z`, `2025-06-29T22:25:29.087Z`, `2025-06-29T22:25:29.167Z` |
|
||||
|
||||
## `qmFilings` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `acc` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 36..151) | `01521843-00000001-00002586-s@#91#91761#SEDAR#...`, `01521972-00000001-00002586-s@#91#91761#SEDAR#...`, `01523099-00000001-00002586-s@#93#93810#SEDAR#...` |
|
||||
| `datefiled` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` |
|
||||
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `CDX` |
|
||||
| `filingDate` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2010-01-06`, `2010-01-07`, `2010-01-12` |
|
||||
| `filingId` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 24..24) | `5e6b93561f348f7b9159eb20`, `5e6b94221f348f7b9159fa0b`, `5e6b94221f348f7b9159fa0c` |
|
||||
| `formdescription` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..72) | `52-109F2R - Certification of refiled interim ...`, `52-109FV1 - Certification of annual filings -...`, `52-109FV2 - Certification of interim filings ...` |
|
||||
| `formgroup` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 19..38) | `Continuous Disclosure`, `Continuous disclosure`, `Exempt Market Offerings and Disclosure` |
|
||||
| `formtype` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 21..21) | `002-001-001012-000052`, `002-001-001012-000054`, `002-001-001012-001002` |
|
||||
| `htmllink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 225..312) | `https://app.quotemedia.com/datatool/downloadF...` |
|
||||
| `pages` | 100.0% (1000/1000) | int: 1000 | — | `1`, `10`, `11` |
|
||||
| `pdflink` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 224..311) | `https://app.quotemedia.com/datatool/downloadF...` |
|
||||
| `size` | 100.0% (1000/1000) | null: 1000 | — | — |
|
||||
| `source` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..2) | `QM` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 2..6) | `AAC.P`, `ACAP.P`, `ACOP` |
|
||||
| `timefiled` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 23..23) | `2010-01-06T03:00:00 EST`, `2010-01-07T03:00:00 EST`, `2010-01-12T03:00:00 EST` |
|
||||
|
||||
## `qmPrices` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `change` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.001851`, `-0.001877`, `-0.003661` |
|
||||
| `changepercent` | 100.0% (1000/1000) | int: 8, double: 992 | — | `-0.007`, `-0.008`, `-0.014` |
|
||||
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:05:12.787Z` |
|
||||
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `2021-07-06`, `2021-07-07`, `2021-07-08` |
|
||||
| `dateTime` | 100.0% (1000/1000) | date: 1000 | — | `2021-07-06T00:00:00.000Z`, `2021-07-07T00:00:00.000Z`, `2021-07-08T00:00:00.000Z` |
|
||||
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..3) | `TSX` |
|
||||
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 4..4) | `X:CA` |
|
||||
| `sharevolume` | 100.0% (1000/1000) | int: 1000 | — | `100159`, `100168`, `100494` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..1) | `X` |
|
||||
| `unadjustedclose` | 100.0% (1000/1000) | int: 29, double: 971 | — | `122.8`, `123.04`, `123.11` |
|
||||
| `unadjustedhigh` | 100.0% (1000/1000) | int: 30, double: 970 | — | `123.85`, `124.4`, `124.76` |
|
||||
| `unadjustedlow` | 100.0% (1000/1000) | int: 29, double: 971 | — | `121.42`, `121.9`, `122.24` |
|
||||
| `unadjustedopen` | 100.0% (1000/1000) | int: 38, double: 962 | — | `122.02`, `122.24`, `122.7` |
|
||||
| `unadjustedvwap` | 100.0% (1000/1000) | double: 1000 | — | `122.6259`, `123.1946`, `123.6024` |
|
||||
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T18:59:43.948Z` |
|
||||
|
||||
## `qmSplits` (1000 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (1000/1000) | objectId: 1000 | — | — |
|
||||
| `created_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:22:20.834Z`, `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z` |
|
||||
| `date` | 100.0% (1000/1000) | string: 1000 | ymd: 1000 (len 10..10) | `1972-06-21`, `1973-04-23`, `1976-07-26` |
|
||||
| `declared` | 40.8% (408/1000) | string: 408 | ymd: 408 (len 10..10) | `1978-11-29`, `1979-03-02`, `1979-04-16` |
|
||||
| `exchange` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 3..5) | `CDX`, `CNQ`, `EXPM` |
|
||||
| `forfactor` | 100.0% (1000/1000) | string: 114, int: 867, double: 19 | emptyOrWhitespace: 114 (len 0..0) | <code></code>, `1`, `1.024549` |
|
||||
| `payment` | 38.2% (382/1000) | string: 382 | ymd: 382 (len 10..10) | `1969-12-31`, `1979-01-05`, `1979-04-06` |
|
||||
| `qmSearchCode` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..12) | `A`, `AAUC:CA`, `ABRA:CA` |
|
||||
| `record` | 38.1% (381/1000) | string: 381 | ymd: 381 (len 10..10) | `1969-12-31`, `1978-12-12`, `1979-03-15` |
|
||||
| `reportDate` | 100.0% (1000/1000) | date: 1000 | — | `1972-06-21T00:00:00.000Z`, `1973-04-23T00:00:00.000Z`, `1976-07-26T00:00:00.000Z` |
|
||||
| `splitratio` | 100.0% (1000/1000) | int: 305, double: 695 | — | `0.005`, `0.01`, `0.029129` |
|
||||
| `symbol` | 100.0% (1000/1000) | string: 1000 | other: 1000 (len 1..9) | `A`, `AAUC`, `ABRA` |
|
||||
| `tofactor` | 100.0% (1000/1000) | string: 114, int: 745, double: 141 | emptyOrWhitespace: 114 (len 0..0) | <code></code>, `0.067967`, `0.3333` |
|
||||
| `updated_at` | 100.0% (1000/1000) | date: 1000 | — | `2025-06-29T22:25:29.068Z`, `2025-06-29T22:25:29.085Z`, `2025-06-29T22:25:29.147Z` |
|
||||
|
||||
## `teMarketData` (435 docs sampled)
|
||||
|
||||
| Field | Presence | Types | String Patterns | Examples |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| `_id` | 100.0% (435/435) | objectId: 435 | — | — |
|
||||
| `category` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` |
|
||||
| `createdAt` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
|
||||
| `daily` | 100.0% (435/435) | array: 435 | — | — |
|
||||
| `frequency` | 100.0% (435/435) | string: 435 | other: 435 (len 5..8) | `daily`, `intraday` |
|
||||
| `fullName` | 100.0% (435/435) | string: 435 | other: 435 (len 3..48) | `Abu Dhabi General`, `Aluminum`, `Amman Stock Exchange General Index` |
|
||||
| `industry` | 100.0% (435/435) | null: 435 | — | — |
|
||||
| `lastUpdated` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
|
||||
| `monthly` | 100.0% (435/435) | array: 435 | — | — |
|
||||
| `name` | 100.0% (435/435) | string: 435 | other: 435 (len 2..28) | `ADX General`, `ASE`, `ASPI` |
|
||||
| `sector` | 100.0% (435/435) | null: 435 | — | — |
|
||||
| `symbolType` | 100.0% (435/435) | string: 435 | other: 435 (len 3..3) | `com`, `cur`, `gov` |
|
||||
| `teSymbol` | 100.0% (435/435) | string: 435 | other: 435 (len 2..11) | `ADSMI`, `AEX`, `AS51` |
|
||||
| `ticker` | 100.0% (435/435) | null: 435 | — | — |
|
||||
| `type` | 100.0% (435/435) | string: 435 | other: 435 (len 4..9) | `bond`, `commodity`, `currency` |
|
||||
| `unit` | 100.0% (435/435) | string: 293, null: 142 | other: 293 (len 3..19) | `AUD/100Kg`, `BRL/Kgs`, `CNY/KG` |
|
||||
| `updated_at` | 100.0% (435/435) | date: 435 | — | `2026-04-02T03:56:52.369Z`, `2026-04-02T03:56:52.418Z`, `2026-04-02T03:56:52.526Z` |
|
||||
332
design/data-pipeline/m1-us-ca-match-report.md
Normal file
332
design/data-pipeline/m1-us-ca-match-report.md
Normal file
|
|
@ -0,0 +1,332 @@
|
|||
# Security Master Match & Conflict Report
|
||||
|
||||
## Exit Thresholds
|
||||
|
||||
| Criterion | Status | Target |
|
||||
| --- | --- | --- |
|
||||
| Exchanges Mapped | PASS | 100.00% |
|
||||
| Equities Resolved (Eligible) | PASS | >= 95.00% |
|
||||
|
||||
## Exchange Coverage
|
||||
|
||||
| Mapped | Unresolved | Total | Mapped % |
|
||||
| --- | --- | --- | --- |
|
||||
| 95 | 0 | 95 | 100.00% |
|
||||
|
||||
## Gate Denominator Definition
|
||||
|
||||
The M1 `>= 95.00%` equity resolution gate evaluates **gate-eligible US/CA common equities & ETFs on EODHD-covered exchanges** (`XNYS`, `XNAS`, `ARCX`, `XASE`, `BATS`, `OTCM`, `XTSE`, `XTSX`, `NEOE`).
|
||||
All raw catalog rows remain visible in `Total` and `Resolved %`; non-matched records outside the gate denominator are transparently itemized under `Excluded by Design` (`excluded_fund`, `composite_venue`, `ats_routing_venue`, `forex_venue`) and `Out of Gate Scope`:
|
||||
- `zero_bar_catalog_ghost`: secondary ticker-only rows (`qm`) with `missing_span` (zero price bars in `qmPrices`, intentionally refused by Stage B Tier 3/4 temporal-overlap safety to prevent ticker-reuse corruption such as `FB`).
|
||||
- `uncovered_venue`: listings on venues absent from the EODHD bar master (`XCNQ` Canadian Securities Exchange across `qm`/`ceo`/`ib:AEQLIT`, and `ceo:NEOE` where EODHD carries only 19 of 587 listings).
|
||||
- `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 shells `.H`, TSXV CPCs `.P`, and exchange test symbols).
|
||||
|
||||
## Per-Source Resolution
|
||||
|
||||
| Source | Total | Matched | Unresolved | Conflict | Excluded by Design | Out of Gate Scope | Eligible Total | Resolved % | Eligible Resolved % |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| eod | 66258 | 65970 | 288 | 0 | 288 | 0 | 65970 | 99.57% | 100.00% |
|
||||
| ib | 18402 | 16882 | 1449 | 71 | 0 | 1165 | 17237 | 91.74% | 97.94% |
|
||||
| qm | 47140 | 23394 | 23724 | 22 | 11259 | 11790 | 24091 | 49.63% | 97.11% |
|
||||
| ceo | 9072 | 4904 | 4158 | 10 | 0 | 3951 | 5121 | 54.06% | 95.76% |
|
||||
|
||||
## Out-of-Gate-Scope Breakdown
|
||||
|
||||
| Source | Reason | Count |
|
||||
| --- | --- | --- |
|
||||
| ceo | non_equity_instrument | 1950 |
|
||||
| ceo | uncovered_venue | 2001 |
|
||||
| ib | non_equity_instrument | 437 |
|
||||
| ib | uncovered_venue | 728 |
|
||||
| qm | non_equity_instrument | 851 |
|
||||
| qm | uncovered_venue | 718 |
|
||||
| qm | zero_bar_catalog_ghost | 10221 |
|
||||
|
||||
## Per-Country Resolution
|
||||
|
||||
| Country | Total | Matched | Unresolved | Conflict | Excluded by Design | Eligible Total | Resolved % | Eligible Resolved % |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| AU | 3 | 0 | 3 | 0 | 0 | 3 | 0.00% | 0.00% |
|
||||
| BM | 13 | 0 | 13 | 0 | 0 | 13 | 0.00% | 0.00% |
|
||||
| CA | 25221 | 18044 | 7148 | 29 | 0 | 25221 | 71.54% | 71.54% |
|
||||
| IE | 2 | 0 | 1 | 1 | 0 | 2 | 0.00% | 0.00% |
|
||||
| IL | 4 | 0 | 4 | 0 | 0 | 4 | 0.00% | 0.00% |
|
||||
| JE | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
|
||||
| JP | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
|
||||
| KY | 51 | 0 | 34 | 17 | 0 | 51 | 0.00% | 0.00% |
|
||||
| MH | 6 | 0 | 5 | 1 | 0 | 6 | 0.00% | 0.00% |
|
||||
| NL | 2 | 0 | 2 | 0 | 0 | 2 | 0.00% | 0.00% |
|
||||
| SG | 1 | 0 | 0 | 1 | 0 | 1 | 0.00% | 0.00% |
|
||||
| US | 104021 | 93106 | 10861 | 54 | 6 | 104015 | 89.51% | 89.51% |
|
||||
| VI | 1 | 0 | 1 | 0 | 0 | 1 | 0.00% | 0.00% |
|
||||
|
||||
## Unresolved by Reason
|
||||
|
||||
### Stage A
|
||||
|
||||
| Source | Reason | Count |
|
||||
| --- | --- | --- |
|
||||
| ib | missing_identifiers | 4 |
|
||||
|
||||
### Stage B
|
||||
|
||||
| Source | Reason | Count |
|
||||
| --- | --- | --- |
|
||||
| ceo | invalid_ticker | 17 |
|
||||
| ceo | no_matching_listing | 4141 |
|
||||
| eod | composite_venue | 288 |
|
||||
| ib | invalid_currency | 24 |
|
||||
| ib | no_listing_for_currency | 1421 |
|
||||
| qm | ats_routing_venue | 8283 |
|
||||
| qm | composite_venue | 2976 |
|
||||
| qm | invalid_ticker | 1 |
|
||||
| qm | missing_span | 10221 |
|
||||
| qm | no_matching_listing | 2204 |
|
||||
| qm | no_span_overlap | 39 |
|
||||
|
||||
## Conflicts by Pass & Kind
|
||||
|
||||
| Pass | Conflict Kind | Count |
|
||||
| --- | --- | --- |
|
||||
| pass4 | price_low_correlation | 197 |
|
||||
| pass4 | price_ratio_mismatch | 312 |
|
||||
| stage_a | isin_cusip_mismatch | 1 |
|
||||
| stage_b | ambiguous_ib_listing | 30 |
|
||||
| stage_b | ambiguous_ticker_span | 22 |
|
||||
| stage_b | competing_ib_conid | 40 |
|
||||
| stage_b | duplicate_source_id | 10 |
|
||||
|
||||
## Pass 4 Price Cross-Check Verdicts
|
||||
|
||||
- Pairs In: 65231
|
||||
- Invalid Pairs: 0
|
||||
- Conflicts Emitted: 509
|
||||
|
||||
| Verdict | Count |
|
||||
| --- | --- |
|
||||
| unsupported_currency_pair | 0 |
|
||||
| insufficient_data | 60599 |
|
||||
| ratio_mismatch | 312 |
|
||||
| low_correlation | 197 |
|
||||
| confirmed | 4123 |
|
||||
|
||||
## Pass 6 Delisting Chain Outcomes
|
||||
|
||||
- Total Input Listings: 65970
|
||||
- Processed Listings: 65970
|
||||
- Continuities Created: 95
|
||||
- Conflicts Detected: 0
|
||||
|
||||
| Outcome | Count |
|
||||
| --- | --- |
|
||||
| active | 25956 |
|
||||
| moved_to_otc | 95 |
|
||||
| bankruptcy_cancelled | 590 |
|
||||
| unknown_involuntary | 39329 |
|
||||
|
||||
## Conflict Sample
|
||||
|
||||
| Pass | Source | Source ID | Conflict Kind | Detail |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| pass4 | eod | AAPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AAPL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4923,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AAPL"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ABLT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABLT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9623,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABLT"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ABM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2871,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABM"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ABR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6267,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABR"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ABT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ABT.US"},"medianRatio":1.0000009402030838,"minCorrelation":0.9,"priceCorr":0.653,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABT"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ACD.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ACD.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.768,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ACD:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ADM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8875,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADM"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ADX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ADX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6527,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ADX"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AFG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AFG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8974,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AFG"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AG.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AG.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8279,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AG:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AGFXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AGFXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3573,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AGFXF"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ALXN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ALXN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4186,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ALXN"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AMAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6599,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMAT"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AMGN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AMGN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8658,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AMGN"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | APD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"APD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7669,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"APD"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ARX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ARX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8297,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ARX:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ASG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ASG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8475,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ASG"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AUQ.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AUQ.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5609,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AUQ:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AVU.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"AVU.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.415,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AVU:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | AVY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"AVY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.888,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"AVY"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | B.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"B.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8517,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"B"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BCE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BCE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2712,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BCE:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BEN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BEN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8754,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BEN"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BKH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.829,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKH"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5579,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKT"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BKTI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BKTI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8971,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BKTI"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BLM.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BLM.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BLM:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BMGP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BMGP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BMGP"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"BN.TO"},"medianRatio":0.9924867905232657,"minCorrelation":0.9,"priceCorr":0.7976,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"BN:CA"},"usableDates":9,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BN.US"},"medianRatio":0.9930629800660156,"minCorrelation":0.9,"priceCorr":0.8718,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BN"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BNSOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BNSOF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BNSOF"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BOH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BOH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8681,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BOH"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BTO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BTO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7832,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BTO"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | BYDDY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"BYDDY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"BYDDY"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8615,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CAT"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CCK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CCK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8453,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CCK"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CFW.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CFW.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7823,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CFW:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CGNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CGNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8472,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CGNX"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CINF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CINF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5966,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CINF"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CIX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CIX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7309,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CIX:CA"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7174,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CL"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8188,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CMT"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | COV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"COV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2511,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"COV:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CRRX.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"CRRX.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7485,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"CRRX:CA"},"usableDates":8,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CSCO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CSCO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5838,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CSCO"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | CTAS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"CTAS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.833,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"CTAS"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DF.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DF.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8822,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DF:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DGICB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DGICB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7254,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DGICB"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DHR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DHR.US"},"medianRatio":1.0000008038585209,"minCorrelation":0.9,"priceCorr":0.7251,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DHR"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DIS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DIS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6493,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DIS"},"usableDates":23,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DMI.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DMI.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7968,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DMI:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DOC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DOC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5946,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DOC"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"DS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4049,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"DS:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DTE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7957,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTE"},"usableDates":20,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | DTRK.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"DTRK.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7845,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"DTRK"},"usableDates":9,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8582,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EA"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EAPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EAPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EAPH"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EBIXQ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EBIXQ.US"},"medianRatio":0.9984378853901176,"minCorrelation":0.9,"priceCorr":0.8049,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EBIXQ"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EEA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EEA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8994,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EEA"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EIT-UN.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EIT-UN.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2739,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EIT.UN:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EIX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EIX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8568,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EIX"},"usableDates":19,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EKG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EKG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EKG:CA"},"usableDates":8,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EMR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EMR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8167,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EMR"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ENS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ENS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2394,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ENS"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ERIC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ERIC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ERIC"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ETR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ETR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8864,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ETR"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EXC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"EXC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6761,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"EXC"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | EXG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"EXG.V"},"medianRatio":1.0128205128205128,"minCorrelation":0.9,"priceCorr":0.8849,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"EXG:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | FAST.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FAST.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7978,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FAST"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | FE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FE"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | FI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5734,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FI"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | FLO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FLO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6659,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FLO"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | FTFT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"FTFT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"FTFT"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | FTU.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"FTU.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7131,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"FTU:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GAB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GAB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GAB"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GLW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GLW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5909,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GLW"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GMGI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GMGI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1581,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GMGI"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GPC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GPC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.893,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GPC"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0751,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GR:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GSY.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GSY.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.821,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GSY:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GWO.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"GWO.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4038,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"GWO:CA"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | GWW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"GWW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8347,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"GWW"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | HD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3437,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HD"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | HE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8973,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HE"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | HERC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HERC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.9709,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HERC"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | HMSY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HMSY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8013,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HMSY"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | HON.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HON.US"},"medianRatio":0.9985665897393179,"minCorrelation":0.9,"priceCorr":0.7848,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HON"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | HRB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"HRB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7753,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"HRB"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | IAF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IAF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8914,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IAF"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | IBM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IBM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8969,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IBM"},"usableDates":23,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | IDXX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IDXX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7758,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IDXX"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | INVI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"INVI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8356,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"INVI"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | INX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"INX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1372,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"INX:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | IP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IP.US"},"medianRatio":1.0000015837820717,"minCorrelation":0.9,"priceCorr":0.8714,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IP"},"usableDates":20,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | IPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"IPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8854,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"IPG"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | J.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"J.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"J"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | JHI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2883,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHI"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | JHS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JHS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5039,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JHS"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | JNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4784,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JNJ"},"usableDates":20,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | JPM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"JPM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6225,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"JPM"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | K.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"K.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"K"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | KNX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KNX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3071,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KNX"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | KO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"KO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7972,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"KO"},"usableDates":23,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | KTN.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"KTN.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1622,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"KTN:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | LB.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"LB.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7835,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"LB:CA"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | LIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8716,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LIN"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | LOW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LOW.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.692,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LOW"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | LTTC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"LTTC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7122,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"LTTC"},"usableDates":9,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MAG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5247,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAG"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MAH.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"MAH.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8872,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"MAH:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MAKOF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAKOF.US"},"medianRatio":1.0010373443983402,"minCorrelation":0.9,"priceCorr":-0.3094,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAKOF"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MAR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAR.US"},"medianRatio":1.0000850013709899,"minCorrelation":0.9,"priceCorr":0.878,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAR"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MAT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MAT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8638,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MAT"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MCD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8111,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCD"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MCHP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MCHP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7736,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MCHP"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8326,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MG"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MGF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3548,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGF"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MGRC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MGRC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8632,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MGRC"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MIN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MIN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2315,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MIN"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MMT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MMT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0508,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MMT"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MRNJ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MRNJ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4307,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MRNJ"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | MU.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"MU.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.887,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"MU"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NCA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NCA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6143,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NCA"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NDSN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NDSN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8823,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NDSN"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NEV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NEV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4241,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NEV:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NEWH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NEWH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.3492,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NEWH"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NGG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NGG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NGG"},"usableDates":9,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NHC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NHC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7198,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NHC"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NJR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NJR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7038,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NJR"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NSC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NSC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8787,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NSC"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NTRS.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NTRS.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8915,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NTRS"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NUV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NUV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6387,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NUV"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NVO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"NVO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8002,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"NVO"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NWX.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NWX.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8847,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NWX:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | NZP.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"NZP.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8469,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"NZP:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ODX-H.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"ODX-H.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7014,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"ODX.H:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | OMVKY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"OMVKY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7275,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"OMVKY"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ORCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8616,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORCL"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ORI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8524,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORI"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ORN.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ORN.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.0519,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ORN"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PAYX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PAYX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8645,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PAYX"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PBI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PBI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8444,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PBI"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5439,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCF"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PCH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PCH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8737,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PCH"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PDLI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PDLI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.851,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PDLI"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PDV.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PDV.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.7666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PDV:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PEG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.852,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEG"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PEO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PEO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8323,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PEO"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PFE.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PFE.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8302,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PFE"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.841,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PG"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PGR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PGR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7961,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PGR"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4549,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PIM"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PNC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PNC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7715,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PNC"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PPG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8466,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPG"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PPL.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PPL.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6331,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PPL:CA"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PPL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPL.US"},"medianRatio":0.9962860635696822,"minCorrelation":0.9,"priceCorr":0.7763,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPL"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PPT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PPT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5062,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PPT"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PSHG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSHG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.897,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSHG"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PSYC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PSYC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0099,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PSYC"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PTE.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"PTE.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7833,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"PTE:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | PTVCB.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"PTVCB.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.4213,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"PTVCB"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | QNC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"QNC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2666,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"QNC:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | RDI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RDI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8088,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RDI"},"usableDates":8,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | RJF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"RJF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4954,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"RJF"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ROG.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"ROG.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8908,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ROG"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SABA.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SABA.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5922,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SABA"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SBR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SBR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.4564,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SBR"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SCL.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SCL.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6328,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SCL"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SDR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SDR.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8406,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SDR:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SGC.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SGC.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5532,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SGC"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SHW.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SHW.US"},"medianRatio":1.0000010134792743,"minCorrelation":0.9,"priceCorr":0.7152,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SHW"},"usableDates":15,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SIM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SIM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5561,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SIM"},"usableDates":9,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SKT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SKT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8894,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SKT"},"usableDates":12,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7559,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SO"},"usableDates":16,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SPH.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SPH.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":-0.0746,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SPH"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SR.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SR.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.5368,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SR"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SR.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SR.V"},"medianRatio":1.0121951219512195,"minCorrelation":0.9,"priceCorr":0.4701,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SR:CA"},"usableDates":6,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SRC.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRC.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.1692,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRC:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SRG.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SRG.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7455,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SRG:CA"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SSV.V | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"SSV.V"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6213,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"SSV:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SWZ.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SWZ.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7802,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SWZ"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | SYY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"SYY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.446,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"SYY"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | T.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"T.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7822,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"T"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TCF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.836,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCF"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TCI.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TCI.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.2847,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TCI"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TFX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TFX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8388,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TFX"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TIGO.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TIGO.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.3913,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TIGO"},"usableDates":11,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TJX.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TJX.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8876,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TJX"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TLGPY.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TLGPY.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.6001,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TLGPY"},"usableDates":10,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | TMBXF.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"TMBXF.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7082,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"TMBXF"},"usableDates":5,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | UHT.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UHT.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8031,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UHT"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | UNM.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNM.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8065,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNM"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | UNP.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UNP.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7949,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UNP"},"usableDates":17,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | URE.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"URE.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8376,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"URE:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | UVV.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"UVV.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8327,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"UVV"},"usableDates":14,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | VQS.TO | price_low_correlation | {"left":{"currency":"CAD","source":"eod","sourceId":"VQS.TO"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.7545,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"VQS:CA"},"usableDates":7,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | WAFD.US | price_low_correlation | {"left":{"currency":"USD","source":"eod","sourceId":"WAFD.US"},"medianRatio":1,"minCorrelation":0.9,"priceCorr":0.8958,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"WAFD"},"usableDates":13,"verdict":"low_correlation"} |
|
||||
| pass4 | eod | ABBNY.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ABBNY.US"},"medianRatio":0.9512875068194219,"minCorrelation":0.9,"priceCorr":0.9996,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ABBNY"},"usableDates":9,"verdict":"ratio_mismatch"} |
|
||||
| pass4 | eod | ACORQ.US | price_ratio_mismatch | {"left":{"currency":"USD","source":"eod","sourceId":"ACORQ.US"},"medianRatio":120,"minCorrelation":0.9,"priceCorr":0.5059,"ratioTolerance":0.02,"right":{"currency":"USD","source":"qm","sourceId":"ACORQ"},"usableDates":7,"verdict":"ratio_mismatch"} |
|
||||
| pass4 | eod | AFCC-H.V | price_ratio_mismatch | {"left":{"currency":"CAD","source":"eod","sourceId":"AFCC-H.V"},"medianRatio":0.06666666666666667,"minCorrelation":0.9,"priceCorr":0.8612,"ratioTolerance":0.02,"right":{"currency":"CAD","source":"qm","sourceId":"AFCC.H:CA"},"usableDates":7,"verdict":"ratio_mismatch"} |
|
||||
|
||||
Showing 200 of 612 conflicts (412 more in CSV).
|
||||
294
design/data-pipeline/rust-migration-evaluation.md
Normal file
294
design/data-pipeline/rust-migration-evaluation.md
Normal file
|
|
@ -0,0 +1,294 @@
|
|||
# Evaluation: Moving `apps/stock/data-pipeline` into Rust
|
||||
|
||||
**Date:** 2026-11-29
|
||||
**Status:** Decision brief for the director (docs-only spike; no code, crate, config, or milestone changes enacted)
|
||||
**Scope:** Evaluate the second half of the settled Rust ETL decision — whether to keep `apps/stock/data-pipeline` in TypeScript, move bulk MongoDB streaming into `tools/curate-etl` (Rust), or port all of `apps/stock/data-pipeline` to Rust before Milestone `M2` adds PIT fundamentals, `ceoPosts`, and `bars_1m` intraday QuestDB ingestion.
|
||||
|
||||
## Bottom Line (Recommendation)
|
||||
|
||||
**Adopt Option B: keep `apps/stock/data-pipeline` in TypeScript for security-master resolution, TSV export, probes, and BullMQ/HTTP orchestration, and add direct read-only MongoDB `RawDocumentBuf` streaming (with Rust-side read-only safety guards) to `tools/curate-etl` for bulk curation.**
|
||||
|
||||
- **Why not full port (Option C):** 88.1% of `apps/stock/data-pipeline/src/` (`17,924` of `20,349` LOC, backed by `40` test files / `32,435` test LOC) is logic- and review-bound security-master code operating on `319` exchanges and `396k` symbol catalog rows that already runs in sub-second synthetic benchmarks (`479.6 ms` for `100k` records in `run.ts`, `402.8 ms` for `500k` TSV mappings in `export-curate-inputs.ts`). Porting it adds weeks of parity risk, requires re-implementing BullMQ/PostgreSQL/env-safety adapters, and reopens settled decision `D5` / §4 layer boundaries for negligible wall-time gain.
|
||||
- **Why not keep the JS raw-BSON file bridge forever (Option A):** While `export-raw-bson.ts` avoids JS object decoding (`3.57M–3.83M docs/s` synthetic), staging `845.7M` `eodPrices` and `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` rows through intermediate `.bson` files forces an unnecessary full NVMe write + read of hundreds of GiB (synthetic estimate: ~127–225 GiB peak file capacity / ~255–450 GiB total write+read I/O for `eodPrices`; ~499–832 GiB peak capacity / ~998–1,664 GiB total write+read I/O for the two intraday collections) before Rust even begins curating. Streaming directly from read-only MongoDB cursors in `tools/curate-etl` eliminates that scratch hop without touching the TypeScript security master.
|
||||
- **Decision ownership:** The final choice among Options A, B, and C belongs to the director. None of the follow-up tasks in Section 6 are queued or enacted by this document.
|
||||
|
||||
---
|
||||
|
||||
## 1. Current `apps/stock/data-pipeline` Inventory
|
||||
|
||||
Measured directly from the repository working tree (no database connections). Every production file under `apps/stock/data-pipeline/src/` is `.ts` (zero non-`.ts` files).
|
||||
|
||||
| Area under `apps/stock/data-pipeline/src/` | Prod Files | Non-Test LOC | Dedicated Test Files | Test LOC | Primary I/O & Role |
|
||||
| --- | ---: | ---: | ---: | ---: | --- |
|
||||
| `security-master/` | 21 | 17,924 | 40 | 32,435 | Pure in-memory Passes 1–6 + read-only MongoDB readers (`eodSymbols`, `ibSymbols`, `qmSymbols`, `ceoSymbols`, `eodSymbolChange`, `eodPrices`, `qmPrices`, exchanges, raw BSON, field-shape probe) + PostgreSQL master read/write (`persist.ts`, `export-curate-inputs.ts`) + local file output |
|
||||
| `normalization/` | 4 | 1,318 | 6 | 2,468 | Pure in-memory (`identifiers.ts`, `provider-symbol.ts`, `ticker.ts`) + read-only MongoDB aggregation reader (`bar-spans.ts`: `$match`/`$group`/`$project`/`$sort` only, `$out`/`$merge` forbidden) |
|
||||
| `handlers/` | 12 | 809 | 1* | 290* | BullMQ job handlers (`{data-pipeline_exchanges}`, `{data-pipeline_symbols}` queues via `getFullQueueName`), read-only MongoDB reads, PostgreSQL master reads/writes via `PipelineSyncRepository` |
|
||||
| `repositories/` | 1 | 166 | (shared)* | (shared)* | PostgreSQL transactional sync/reset (`PipelineSyncRepository`, `pg_advisory_xact_lock(1937007472, 1)`) using `@stock-bot/types` `parseReferenceDataResetRequest` |
|
||||
| `routes/` | 2 | 23 | 0 | 0 | HTTP `GET /health` via Hono (`create-routes.ts`, `health.routes.ts`) |
|
||||
| `types/` | 1 | 21 | 0 | 0 | Pure in-memory TypeScript interfaces (`job-payloads.ts`: `JobPayload`, `SyncResult`, `SyncStatus`) |
|
||||
| `index.ts` | 1 | 88 | 0 | 0 | Service bootstrap (`ServiceApplication`, `initializeStockConfig('dataPipeline', { mongoReadOnly: true })`, port `2002`, BullMQ + HTTP + Postgres + read-only Mongo) |
|
||||
| **Total (`src/`)** | **42** | **20,349** | **47** | **35,193** | — |
|
||||
|
||||
*\*`test/postgres/pipeline-safety.test.ts` (1 file, 290 lines) exercises both `handlers/` operations and `PipelineSyncRepository`; it is counted once in the total. `routes/`, `types/`, and `index.ts` have no dedicated unit test files and are covered indirectly by `test/unit/environment-safety*.test.ts` and `test/unit/mongodb-read-only.test.ts`.*
|
||||
|
||||
Separately from production LOC, `apps/stock/data-pipeline/benchmarks/` holds **5 files / 1,144 LOC** of local synthetic benchmark scripts (`export-curate-inputs-benchmark.ts`, `export-raw-bson-benchmark.ts`, `run-security-master-pass4-benchmark.ts`, `sample-closes-benchmark.ts`, `source-field-shapes-benchmark.ts`).
|
||||
|
||||
### Key CLI & Exporter Subsystems Inside `security-master/`
|
||||
|
||||
- **`run-security-master.ts` (T-89 / T-105, `1,042` LOC) + `run.ts` (`1,345` LOC):** Runs the full read-only MongoDB security-master pipeline (`read-exchanges` → `read-sources` → `compute-bar-spans` → Pass 4 `readSampleCloses` + `crossCheckPrices` → `composeSecurityMasterRun`) and writes deterministic `match-report.md`, `conflicts.csv`, `override-template.sql`, and `run-stats.json`, with opt-in `--persist` to isolated dev PostgreSQL guarded by `assertSecurityMasterPersistSafety()`. **Source note:** Pass 4 is **wired and enabled by default** in `run-security-master.ts` (`--skip-price-cross-check`, `--sample-dates <n>`), even though `apps/stock/data-pipeline/README.md` line 201 still states it is not yet wired.
|
||||
- **TSV Exporter (T-116, `export-curate-inputs.ts` `2,040` LOC + `run-export-curate-inputs.ts` `345` LOC = `2,385` LOC):** Reads PostgreSQL security-master tables inside a `REPEATABLE READ READ ONLY` transaction (server-side `NO SCROLL` cursor, chunk size `<= 5,000`) and atomically publishes `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` into `<out-dir>/generations/<generationId>` behind `<out-dir>/.publish.lock` and a single `<out-dir>/current` symlink.
|
||||
- **Raw-BSON Exporter (T-117, `export-raw-bson.ts` `670` LOC + `run-export-raw-bson.ts` `477` LOC = `1,147` LOC):** Streams 8 allowlisted M1 MongoDB collections (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`) via `find(filter, { raw: true, batchSize })` with zero per-document JS decoding, validating BSON frame lengths, coalescing through an `8 MiB` write buffer, computing SHA-256, and publishing `<collection>.bson` atomically.
|
||||
- **Field-Shape Probe (`source-field-shapes.ts` `915` LOC + `probe-source-field-shapes.ts` `291` LOC = `1,206` LOC):** Bounded read-only `find({}, { limit <= 10_000, promoteValues: false, promoteLongs: false })` probe over the 8 M1 collections to confirm live BSON field names and types before curation runs.
|
||||
|
||||
### Cross-App Coupling & Safety Guards
|
||||
|
||||
- **Zero direct package imports:** No other app or library imports `@stock-bot/data-pipeline`.
|
||||
- **`web-api` runtime contract:** `apps/stock/web-api/src/services/pipeline.service.ts` enqueues BullMQ jobs onto `{data-pipeline_exchanges}` and `{data-pipeline_symbols}` via `getFullQueueName` (`libs/core/queue/src/service-utils.ts`, re-exported by `@stock-bot/queue`; using shared `@stock-bot/types` `parseReferenceDataResetRequest` / `ReferenceDataResetScope` for reset confirmation), and `apps/stock/web-api/src/services/monitoring.service.ts` monitors those two queues and polls `GET /health` on port `2002`.
|
||||
- **Safety guard stack:** Every service and CLI entrypoint calls `initializeStockConfig('dataPipeline', { mongoReadOnly: true })` and `assertEnvironmentSafety()` (`apps/stock/config/src/env-safety.ts`, `706` LOC), which resolves loopback/LAN/numeric IPv4 aliases and throws if `development` targets QA PostgreSQL (`localhost:5432/trading_bot`) or opens QA MongoDB (`localhost:27017`) without `mongoReadOnly: true` or with `trading_admin`. At the driver layer, `MongoDBClient` (`libs/data/mongodb/src/client.ts`) wraps databases, collections, and cursors in read-only proxies that reject all write, index, and collection-mutation operations.
|
||||
|
||||
### Reproducible Inventory Commands
|
||||
|
||||
Re-running these POSIX commands from the repository root at the same commit reproduces every count in the table above:
|
||||
|
||||
```bash
|
||||
# 1. Production source file counts & non-test LOC per area
|
||||
for area in security-master normalization handlers repositories routes types; do
|
||||
files=$(find "apps/stock/data-pipeline/src/$area" -type f -name '*.ts' | sort)
|
||||
count=$(printf '%s\n' "$files" | grep -c .)
|
||||
lines=$(printf '%s\n' "$files" | xargs wc -l | tail -n 1 | awk '{print $1}')
|
||||
printf '%-18s files=%2d loc=%5d\n' "$area/" "$count" "$lines"
|
||||
done
|
||||
printf '%-18s files=%2d loc=%5d\n' "index.ts" 1 "$(wc -l < apps/stock/data-pipeline/src/index.ts)"
|
||||
total_files=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | wc -l)
|
||||
total_lines=$(find apps/stock/data-pipeline/src -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')
|
||||
printf '%-18s files=%2d loc=%5d\n' "TOTAL" "$total_files" "$total_lines"
|
||||
|
||||
# 2. Dedicated test files & benchmark scripts
|
||||
printf 'data-pipeline/test: %2d files %5d lines\n' \
|
||||
"$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | wc -l)" \
|
||||
"$(find apps/stock/data-pipeline/test -type f -name '*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'unit security-master: %2d files %5d lines\n' \
|
||||
"$(find test/unit -type f -name 'security-master-*.test.ts' | wc -l)" \
|
||||
"$(find test/unit -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'postgres security-master: %2d files %5d lines\n' \
|
||||
"$(find test/postgres -type f -name 'security-master-*.test.ts' | wc -l)" \
|
||||
"$(find test/postgres -type f -name 'security-master-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'unit normalization: %2d files %5d lines\n' \
|
||||
"$(find test/unit -type f -name 'normalization-*.test.ts' | wc -l)" \
|
||||
"$(find test/unit -type f -name 'normalization-*.test.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
printf 'integration provider-symbol: %2d files %5d lines\n' \
|
||||
1 "$(wc -l < test/integration/provider-symbol.test.ts)"
|
||||
printf 'postgres pipeline-safety: %2d files %5d lines\n' \
|
||||
1 "$(wc -l < test/postgres/pipeline-safety.test.ts)"
|
||||
printf 'benchmarks (separate): %2d files %5d lines\n' \
|
||||
"$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | wc -l)" \
|
||||
"$(find apps/stock/data-pipeline/benchmarks -type f -name '*.ts' | sort | xargs wc -l | tail -n 1 | awk '{print $1}')"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. What Already Lives in Rust (`tools/curate-etl`)
|
||||
|
||||
`tools/curate-etl` is a standalone Cargo workspace member with **three exact-pinned dependencies** (`bson = "=3.1.0"` with `compat-3-0-0`, `parquet = "=60.2.0"` Zstd-only, `rayon = "=1.12.0"`), **zero async runtime**, and **zero database clients**.
|
||||
|
||||
| Module Group under `tools/curate-etl/src/` | Files | LOC | Contents |
|
||||
| --- | ---: | ---: | --- |
|
||||
| Domain builders | 9 | 8,170 | `adj.rs`, `bars.rs`, `corporate_actions.rs`, `events.rs`, `fx.rs`, `provider_mapping.rs`, `session_close.rs`, `shorts.rs`, `split.rs` |
|
||||
| Zero-copy BSON decoders & framing | 7 | 5,594 | `bson_ceo_shorts.rs`, `bson_eod_prices.rs`, `bson_qm_actions.rs`, `bson_qm_events.rs`, `bson_qm_prices.rs`, `bson_stream.rs`, `bson_te_market_data.rs` |
|
||||
| Zstd Parquet writers & atomic publish | 7 | 9,841 | `parquet_adj.rs`, `parquet_bars.rs`, `parquet_corporate_actions.rs`, `parquet_events.rs`, `parquet_fx.rs`, `parquet_publish.rs`, `parquet_shorts.rs` |
|
||||
| Curation stages | 6 | 3,726 | `curate_adj.rs`, `curate_bars.rs`, `curate_corporate_actions.rs`, `curate_events.rs`, `curate_fx.rs`, `curate_shorts.rs` |
|
||||
| Runnable `curate-*` CLI runners | 6 | 5,202 | `run_curate_adj.rs`, `run_curate_bars.rs`, `run_curate_corporate_actions.rs`, `run_curate_events.rs`, `run_curate_fx.rs`, `run_curate_shorts.rs` |
|
||||
| CLI, benchmarks, entrypoints | 4 | 16,884 | `bench.rs`, `cli.rs`, `lib.rs`, `main.rs` |
|
||||
| Dedicated test modules (`*_tests.rs`) | 26 | 27,215 | Unit, property, parity, and TSV/BSON fixture tests |
|
||||
| **Total (`tools/curate-etl/src/`)** | **65** | **76,632** | **39 non-test files (49,417 LOC) + 26 test files (27,215 LOC)** |
|
||||
|
||||
Reproducible command:
|
||||
|
||||
```bash
|
||||
find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | wc -l
|
||||
find tools/curate-etl/src -type f -name '*.rs' ! -name '*_tests.rs' | sort | xargs wc -l | tail -n 1
|
||||
find tools/curate-etl/src -type f -name '*_tests.rs' | wc -l
|
||||
find tools/curate-etl/src -type f -name '*_tests.rs' | sort | xargs wc -l | tail -n 1
|
||||
```
|
||||
|
||||
The binary already implements all **six M1 curation commands** (`curate-bars-1d`, `curate-adj-factors`, `curate-corporate-actions`, `curate-fx-1d`, `curate-shorts`, `curate-events`) reading local TSVs + concatenated raw-BSON files and atomically publishing Hive-partitioned Zstd Parquet.
|
||||
|
||||
### Measured Local Baselines (Synthetic / Offline — Zero Live QA MongoDB or `quant` Runs)
|
||||
|
||||
| Benchmark | Source & Date | Command | Workload & Measured Result |
|
||||
| --- | --- | --- | --- |
|
||||
| `curate-bars-1d` (1-thread baseline) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000` | `1,000,000` EOD + `227,439` QM + `2,040` splits: `decode 234.63 ms` (`4.26M rows/s`), `curate 208.07 ms`, `write 456.39 ms` (`2.06M rows/s`), **total `899.09 ms` (`1.11M rows/s`, `193.78 MB/s`)** |
|
||||
| `curate-bars-1d` (`rayon` parallel write, **local re-run**) | Local sandbox re-run (`2026-11-29`, 32-thread host, synthetic) | `CARGO_BUILD_JOBS=2 cargo run --release -p curate-etl --offline -- bench-curate-bars-cmd 1000000` | Same `1,000,000`-row synthetic input: `decode 233.19 ms` (`4.29M rows/s`), `curate 207.45 ms`, `write_1 (threads=1) 445.79 ms` (`2.10M rows/s`) vs **`write (threads=32) 94.42 ms` (`9.93M rows/s`, `259.56 MB/s`, `4.72x` speedup)**, **total `535.06 ms` (`1.87M rows/s`, `325.63 MB/s`)** |
|
||||
| `curate-bars-1d` (5M rows, 1-thread) | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000` | `5,000,000` EOD + `1.14M` QM + `4,080` splits: **total `3,525.02 ms` (`1.42M rows/s`, `247.01 MB/s`)** |
|
||||
| `curate-adj-factors` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd` | `500,000` events + `62,720` `bars_1d`: **total `436.90–500.88 ms` (`998k–1.14M events/s`)** across 2 runs |
|
||||
| `curate-corporate-actions` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000` | `1,000,000` events (`39,186` splits, `950,896` divs, `9,918` delistings): **total `752.71–775.67 ms` (`1.29M–1.33M events/s`)** |
|
||||
| `curate-fx-1d` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd` | `20,000` FX rows (`CAD.FOREX` + `USDCAD`): **total `20.19–29.97 ms` (`667k–990k rows/s`)** |
|
||||
| `curate-shorts` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-shorts-command` | `700,000` `ceoShorts` docs (`64.78 MiB`): **total `365.73–369.48 ms` (`1.89M–1.91M rows/s`)**, `peak_chunk_bytes = 8 MiB` |
|
||||
| `curate-events` | `tools/curate-etl/README.md` (`2026-11-29`) | `cargo run -p curate-etl --release --offline -- bench-curate-events-cmd` | `500,000` rows (`492.5k` filings, `7.5k` earnings): **total `838.71–861.10 ms` (`581k–596k rows/s`)**; linear synthetic extrapolation to `30.96M` rows: `51.9–53.3 s` single-core |
|
||||
| `bson_eod_prices` decode-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-eod-prices` | `1,000,000` docs (`272.4 MiB`): **`217.38–221.82 ms` (`4.51M–4.60M rows/s`, `1.23–1.25 GB/s`)** |
|
||||
| `bson_stream` short-read | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-bson-stream` | `2,000,000` docs (`544.8 MiB`): **`544.59 ms` (`3.67M rows/s`, `1.00 GiB/s`, `0.963x` vs in-memory buffer, `8 MiB` peak buffer)** |
|
||||
| `parquet_bars` write-only | `tools/curate-etl/README.md` (`2026-11-28`) | `cargo run --release -p curate-etl --offline -- bench-parquet-bars` | `5,000,000` rows, 20 year files: **`1,422.27 ms` (`3.52M rows/s`, `155.11 MB/s`, `1.82x` Zstd)** |
|
||||
| `split` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-split` | `10,000,000` synthetic rows: **`367.40 ms` (`27.22M rows/s`)** |
|
||||
| `bars` builder | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-bars` | `10,000,000` synthetic rows: **`842.38 ms` (`11.87M rows/s`)** |
|
||||
| `provider_mapping` lookup | `tools/curate-etl/README.md` (date omitted in README) | `cargo run --release -p curate-etl --offline -- bench-provider-mapping` | `10,000,000` synthetic lookups: **`447.14 ms` (`22.36M lookups/s`)** |
|
||||
| TS `export-raw-bson` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-raw-bson-benchmark.ts` | `1,000,000` synthetic `eodPrices` frames (`123.9 B` avg): **`270.8–279.8 ms` (`3.57M–3.69M docs/s`, `422–436 MiB/s`, `peak_rss 150–151 MiB`)**; `2M` docs: `3.83M docs/s`, `peak_rss 146.88 MiB` |
|
||||
| TS `export-curate-inputs` | `apps/stock/data-pipeline/README.md` (`2026-11-29`) | `bun run apps/stock/data-pipeline/benchmarks/export-curate-inputs-benchmark.ts` | `500k` mappings + `100k` listings + `2k` OTC (`606,680` TSV rows, `17.2 MB`): **`402.8 ms` (`1.51M rows/s`, `277.01 MiB` peak RSS)** |
|
||||
| TS `sample-closes` (Pass 4a) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/sample-closes-benchmark.ts` | `500,025` synthetic docs (25 dates × 20k IDs + FX): **`190.3 ms` (`2.63M docs/s`)** |
|
||||
| TS `source-symbol-readers` | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-source-symbol-readers.test.ts` | `368,000` synthetic symbol docs: **`488.0 ms` (`754k docs/s`)** |
|
||||
| TS `security-type` classifier | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-security-type.test.ts` | `300,000` synthetic EOD records (`100k` distinct ISIN buckets, `20` conflicting ISINs): **`70.1 ms` (`4.28M records/s`, floor `>= 100k records/s`)** |
|
||||
| TS `run.ts` composer (Passes 3–6) | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun test test/unit/security-master-run.test.ts` | `100,000` synthetic source records end-to-end: **`479.6 ms` (`208.5k records/s`)** |
|
||||
| TS `persistSecurityMaster` | `apps/stock/data-pipeline/README.md` (`2026-11-28`, host Postgres safety schema) | `bun --env-file=/home/boki/.studio/test-env/stock-bot.env test test/postgres/security-master-persist.test.ts` | `20k` instruments + `20k` listings + `60k` mappings (`140k` total rows): **`2.36 s` full test wall time (`>= 59.3k total rows/s`)** |
|
||||
| TS `source-field-shapes` probe | `apps/stock/data-pipeline/README.md` (`2026-11-28`) | `bun run apps/stock/data-pipeline/benchmarks/source-field-shapes-benchmark.ts` | `80,000` synthetic docs (8 collections × 10k): **`218.7 ms` (`365.8k docs/s`)** |
|
||||
|
||||
---
|
||||
|
||||
## 3. Workload Classification by Area
|
||||
|
||||
Row volumes come from the measured 2026-11-26 QA MongoDB inventory in `design/data-pipeline/phase1-investigation.md` and `design/DATA-CONTRACTS.md` §1.
|
||||
|
||||
| Area / Pipeline Stage | Raw / Target Volume | Bottleneck Class | Run Cadence | Rust Value-Add |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| Pass 1 Exchanges (`exchange-pass1.ts`, `generate-exchange-seed.ts`) | `319` rows (`eodExchanges` 76, `ibExchanges` 214, `qmExchanges` 25, `ceoExchanges` 4) | **Logic / human-review-bound** | Rare (initial seed + schema override migrations) | **None** |
|
||||
| Pass 2–3–5–6 Security Master (`source-symbol-readers.ts`, `instrument-stage-a.ts`, `listing-stage-b.ts`, `delisting-chains.ts`, `match-report.ts`, `run.ts`, `persist.ts`) | `396,041` symbol docs (`eodSymbols` 317.8k, `qmSymbols` 47.2k, `ibSymbols` 18.4k, `ceoSymbols` 12.6k) + `230` `eodSymbolChange` | **Logic / edge-case / review-bound** (ISIN Luhn + CUSIP rescue, IB ATS venues, ticker-reuse spans, OTC delisting chains, override precedence) | Infrequent (initial US+CA build, then periodic delta refreshes) | **Negligible** (TS already does `100k` records in `0.48 s` and `140k` PG rows in `2.36 s`) |
|
||||
| Pass 2 `bar-spans.ts` & Pass 4 `sample-closes.ts` | Server-side Mongo `$group` on `eodPrices`/`qmPrices` + 25-date `$in` slice (~500k docs) | **MongoDB index/server I/O-bound** | Same as security master | **Negligible** (MongoDB server does the scan; TS client processes 500k closes in `0.19 s`) |
|
||||
| TSV Export (`export-curate-inputs.ts`) | ~100k–500k PostgreSQL rows (~17 MB) | **Small Postgres read** | Before each curation batch | **Negligible** (`0.40 s` synthetic; ~17 MB on disk) |
|
||||
| Field-Shape Probe (`source-field-shapes.ts`) | `<= 80,000` sampled docs (`8 × 10k`) | **Diagnostic / interactive** | Occasional schema check | **None** |
|
||||
| Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`) | Legacy BullMQ sync jobs + `GET /health` | **Control-plane / queue glue** | Always-on daemon (low QPS) | **Negative** (BullMQ/DI/Hono already in TS) |
|
||||
| **M1 Bulk Raw-BSON Export → Parquet (`eodPrices`, `qmPrices`, `qmFilings`, `qmDividends`, `qmSplits`, `ceoShorts`, `qmEarnings`, `teMarketData`)** | **`845.7M` `eodPrices` + `51.5M` `qmPrices` + `30.5M` `qmFilings` + `1.65M` others** | **CPU + NVMe-scratch / throughput-bound** | Full backfill + nightly/weekly incremental | **High — already in Rust for curation; JS file hop adds huge NVMe scratch write+read** |
|
||||
| **M2 Bulk Raw-BSON → Parquet / QuestDB ILP v2 (`eodIntraday1M`, `qmIntraday`, `ceoPosts`, `qmFinancials`)** | **`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts` + `2.77M` `qmFinancials`/`-old`** | **CPU + NVMe-scratch + network/ILP throughput-bound** | Multi-billion-row backfill + incremental | **Critical — staging `3.57B` intraday docs through local `.bson` files is an estimated ~499–832 GiB peak capacity (~998–1,664 GiB total write+read I/O) NVMe bottleneck** |
|
||||
|
||||
### Why the Intermediate `.bson` File Hop Hurts at M1/M2 Scale
|
||||
|
||||
Even though `export-raw-bson.ts` avoids JS object deserialization (`3.57M–3.83M docs/s` synthetic), it writes every raw document to `<collection>.bson` on NVMe before `curate-etl` reads the file back (so total NVMe bytes moved is **2×** the peak file size, using binary `1 GiB = 2^30` bytes throughout):
|
||||
|
||||
- **M1 `eodPrices` (`845.7M` docs):** Under the synthetic average frame-size assumption of `161.7–285.6 B/doc` (`bench-curate-bars-cmd` / `bench-bson-eod-prices`), staging `eodPrices.bson` requires roughly **~127–225 GiB peak scratch file capacity** and **~255–450 GiB total NVMe I/O (write + read-back)** before `qmPrices` (`51.5M`) and `qmFilings` (`30.5M`).
|
||||
- **M2 intraday (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` = `3.57B` docs):** Under an assumed synthetic `150–250 B/doc` average frame size, staging both intraday collections to `.bson` files requires roughly **~499–832 GiB peak scratch file capacity** and **~998–1,664 GiB total NVMe I/O (write + read-back)** on `quant`'s 4 TB SN850X NVMe (which also holds the `~638 GB` MongoDB corpus, PostgreSQL, QuestDB, and curated Parquet). Eliminating that intermediate file via direct Rust `RawDocumentBuf` cursors saves that entire scratch file footprint and extra NVMe write+read pass. *(All byte-size figures are extrapolated from synthetic documents; actual live BSON document sizes are unverified — see Section 7.)*
|
||||
|
||||
---
|
||||
|
||||
## 4. Options Comparison
|
||||
|
||||
| Dimension | Option A: Keep Current TS + File-Bridge Rust Split | Option B: Direct Read-Only MongoDB Streaming in `tools/curate-etl` (Recommended) | Option C: Full Port of `apps/stock/data-pipeline` to Rust |
|
||||
| --- | --- | --- | --- |
|
||||
| **Architecture** | Status quo (`PLATFORM-PLAN.md` §4): TS owns security master, TSV export, raw-BSON export, probes, BullMQ/HTTP; Rust `curate-etl` reads local TSV + `.bson` files | TS keeps security master (Passes 1–6), TSV export (`export-curate-inputs.ts`), probes, BullMQ/HTTP. Rust `curate-etl` gains a read-only MongoDB cursor adapter (`--mongo-uri` / `MONGODB_READ_URI`) feeding the existing `RawDocumentBuf` decoders directly, while **retaining** file-based CLI mode for offline/reproducible tests | Rewrite all 42 TS files (`20,349` LOC) + 47 test files (`35,193` LOC) in Rust (security master, Postgres persistence, TSV/direct PG read, probes, BullMQ worker, HTTP `/health`, plus direct Mongo cursors) |
|
||||
| **Estimated Effort** | **0 new files/LOC** for M1 bridge; in M2 must extend `RAW_BSON_EXPORT_COLLECTIONS` and add scratch-space management / chunked export for `3.40B` `eodIntraday1M` | **Two-stage effort:**<br>1. **Cursor-only swap (~4–6 new `.rs` files, ~1,200–1,800 LOC + ~1,000–1,500 test LOC):** Rust `env-safety` URI/host/user read-only guard, sealed `mongodb` read-only `RawDocumentBuf` cursor adapter, and `--mongo-uri` / `--collection` CLI wiring alongside existing file mode.<br>2. **Bounded-memory partitioning & overlapped I/O (additional ~3–5 `.rs` files / runner refactors, ~1,500–2,500 LOC + ~1,500–2,000 test LOC):** Date/year or key-range partitioned streaming in `run_curate_bars.rs` and `run_curate_events.rs` (which currently accumulate all decoded rows in RAM before sorting/curation) plus bounded channel pipelining between MongoDB cursor reads and `rayon` Parquet / ILP writes.<br>**Combined:** ~7–11 files, ~2,700–4,300 LOC + ~2,500–3,500 test LOC | **Very large (~40+ `.rs` files, ~15,000–22,000 LOC + ~25,000–35,000 test LOC):** Re-implement Passes 1–6, `persist.ts`, `bar-spans.ts`, `sample-closes.ts`, `source-field-shapes.ts`, `PipelineSyncRepository`, BullMQ Redis protocol, Hono `/health`, and re-verify all 47 test suites (plus Option B's Stage 1+2 work) |
|
||||
| **New Rust Crates Required** | None (`bson =3.1.0`, `parquet =60.2.0`, `rayon =1.12.0` stay unchanged) | `mongodb` (with `bson-3` feature matching `bson =3.1.0`), `tokio` (minimal `rt-multi-thread`/`net`/`time` for async driver), `url` (or strict custom URI parser for safety guard). *Note: keeps zero Postgres/HTTP/Redis crates in `curate-etl`.* | Everything in Option B **plus** `tokio-postgres` / `sqlx`, `axum` / `hyper` (HTTP `/health`), `redis` + custom BullMQ Lua/stream worker compatibility (no official Rust BullMQ crate), `serde` / `serde_json`, `chrono` / `time` |
|
||||
| **Expected Runtime & NVMe Gain (Evidence-Backed)** | Baseline: TS `export-raw-bson` (`3.57M–3.83M docs/s` synthetic) + Rust `curate-bars-1d` (`1.87M rows/s` with `rayon` write). Pays full NVMe scratch footprint (~127–225 GiB peak / ~255–450 GiB write+read for M1 `eodPrices`; ~499–832 GiB peak / ~998–1,664 GiB write+read for M2 intraday, synthetic estimates) | **Stage 1 (cursor-only):** Eliminates intermediate `.bson` scratch files (~100% of bulk scratch NVMe capacity and the extra write+read pass) and removes the TS process hop, **without** reducing decoded-row RAM or overlapping curation/Parquet writes (since `run_curate_bars.rs` and `run_curate_events.rs` still buffer decoded rows before sorting).<br>**Stage 2 (partitioned streaming + pipelining):** Adds bounded-memory execution (needed for global `845.7M` `eodPrices` on `quant`'s `125 GiB` RAM) and overlaps MongoDB wire reads with Rust decode/Parquet/ILP writes.<br>**End-to-end wall-time speedup is unmeasured** (see Section 7). Zero change to sub-second security-master runs | Same bulk gain as Option B; **< 1–3 seconds saved** on security master (`run.ts` is already `479.6 ms` / `100k` records; `persist.ts` is `2.36 s` / `140k` rows, bound by Postgres `UNNEST` I/O; `export-curate-inputs.ts` is `402.8 ms` / `500k` rows) |
|
||||
| **Key Risks** | 1. NVMe capacity/wear spike on `quant` when exporting `3.57B` intraday docs to `.bson` files.<br>2. Two-step manual/scripted orchestration per bulk collection | 1. **Safety-guard parity:** Bypassing TS `assertEnvironmentSafety()` and `MongoDBClient` `mongoReadOnly: true` requires a battle-tested Rust read-only guard (blocking `trading_admin`, loopback/LAN IPv4 variants, and any write command).<br>2. **Memory scope:** A cursor swap alone does not bound RAM on global `845.7M` `eodPrices` until Stage 2 partitioning lands.<br>3. **Crate/async footprint:** Adds `mongodb` + `tokio` to Cargo workspace (requires crates.io fetch and offline cache refresh). | 1. **Pass 1–6 parity risk:** Re-verifying 17,924 LOC of subtle ISIN/CUSIP/ATS/ticker-reuse/delisting-chain rules against 40 test suites.<br>2. **Shared TS contract loss:** Loses `@stock-bot/types` (`ReferenceDataResetRequest`), `@stock-bot/stock-config`, `@stock-bot/postgres` migrations, and BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue parity with `web-api`.<br>3. **Safety-guard duplication** for both MongoDB and PostgreSQL.<br>4. **Multi-week M2 delay** with no user-visible research value |
|
||||
| **Impact on M2 Work Items** | Slows M2 `bars_1m` (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` → QuestDB ILP v2) because raw `.bson` staging doesn't scale cleanly to multi-billion-row streams; `ceoPosts` (`14.8M`) and `qmFinancials` (`2.77M`) remain workable | **Directly accelerates M2:** `tools/curate-etl` streams `eodIntraday1M` (`3.40B`, **split-unadjusting** retroactively adjusted OHLCV via `qmSplits`) and `qmIntraday` (`173.3M`, taking **already-raw** `open..close` and `sharevolume` directly — **no** split un-adjustment) into multi-socket QuestDB ILP v2 (`bars_1m`, `DEDUP UPSERT KEYS(ts, listing_id)`) with zero `.bson` scratch files, verified by the M2 split-boundary comparison (`NEXM.V` `1:20` and `NVDA.US` `10:1` `bars_1m` session closes within `0.5%` of raw `bars_1d` closes); same cursor adapter serves `ceoPosts` (`14.8M`) and `qmFinancials` | **Blocks M2** for weeks while porting already-working M1 security-master code instead of building MCP, PIT fundamentals, QuestDB `10.2.0` `bars_1m`, and Feature Library |
|
||||
|
||||
*Why Option B keeps `export-curate-inputs.ts` in TypeScript:* Exporting `500k` security-master mappings + `100k` listings takes `402.8 ms` (`17.2 MB`) synthetically and already ships with atomic `<out-dir>/current` generation pinning consumed by `curate-etl --curate-inputs`. Keeping it in TypeScript avoids pulling a PostgreSQL driver and `assertSecurityMasterPersistSafety()` duplication into `tools/curate-etl`.
|
||||
|
||||
---
|
||||
|
||||
## 5. Compliance Check (`D1`–`D12` & QA Database Safety Rules)
|
||||
|
||||
### Locked Decisions `D1`–`D12` (`design/PLATFORM-PLAN.md` §3)
|
||||
|
||||
| Decision | Option A | Option B (Recommended) | Option C |
|
||||
| --- | --- | --- | --- |
|
||||
| **D1** (Parquet+DuckDB daily/PIT; QuestDB `10.2.0` intraday) | Compliant | Compliant (directly enables M2 `3.40B` ILP v2 streaming to QuestDB) | Compliant |
|
||||
| **D2** (Desktop copilot MCP; isolated campaign containers) | Compliant | Compliant | Compliant |
|
||||
| **D3** (US+CA priority + FX; `ttFutures` out of scope) | Compliant | Compliant | Compliant |
|
||||
| **D4** (Incremental `web-app` evolution; no rewrite) | Compliant | Compliant | Risk of `web-api` / `PipelinePage` BullMQ contract drift |
|
||||
| **D5** (Cross-source entity resolution in `data-pipeline`) | Compliant | Compliant — matches `PLATFORM-PLAN.md` §4 (`data-pipeline` TS + `curate-etl` Rust) and `DATA-CONTRACTS.md` §3A (`mongodb::bson::RawDocumentBuf` cursors) | **Reopens §4 layer table** (moves TS entity resolution & orchestration out of TS `data-pipeline` into Rust; requires director sign-off to amend `PLATFORM-PLAN.md`) |
|
||||
| **D6** (IB Margin `USD`/`CAD` on isolated `9900K`) | Compliant (no paper/live touch) | Compliant (no paper/live touch) | Compliant (no paper/live touch) |
|
||||
| **D7** (Multi-strategy scope; no macro surprises / Form 4 $) | Compliant | Compliant | Compliant |
|
||||
| **D8** (Incremental Research Playground) | Compliant | Compliant | Compliant (delays M2 timeline) |
|
||||
| **D9** (`marimo` Python labs) | Compliant | Compliant | Compliant |
|
||||
| **D10** (Rolling 6-month Air-Gapped Vault + Post-2023 Recency) | Compliant | Compliant | Compliant |
|
||||
| **D11** (Materialized batch feature jobs; no Python→TS rewrites) | Compliant | Compliant | Compliant |
|
||||
| **D12** (Read-only Studio `library.yml` + Postgres findings) | Compliant | Compliant | Compliant |
|
||||
|
||||
### QA Database Safety Rules (`AGENTS.md`)
|
||||
|
||||
| Safety Rule | Option A | Option B (Recommended) | Option C |
|
||||
| --- | --- | --- | --- |
|
||||
| **Never drop/reset/write QA MongoDB (`localhost:27017/stock`) from `dev` or tests** | Enforced by `assertEnvironmentSafety()` + `MongoDBClient` `mongoReadOnly: true` + `studio_stock_bot_read` | **Must implement Rust read-only guard parity** before enabling `--mongo-uri`: (1) connect strictly via `MONGODB_READ_URI` with server-side `read@stock` user (`studio_stock_bot_read`); (2) reject `trading_admin` and any non-read-only URI targeting loopback/local-LAN port `27017` (matching `env-safety.ts` IPv4/octal/hex/loopback rules); (3) expose **only** `find` / `RawDocumentBuf` cursor reads in a sealed Rust module with no `insert`/`update`/`delete`/`drop`/`create_index`/`run_command` surface; (4) unit-test all rejected URIs offline | Requires Option B's Rust Mongo guard **plus** full Rust parity for PostgreSQL dev-isolation guards (`assertSecurityMasterPersistSafety`, `NODE_ENV=development` blocking `localhost:5432/trading_bot`, `pg_advisory_xact_lock`, and `rejectDestructiveSync`) |
|
||||
| **Tests never mutate QA Postgres (`trading_bot`) or QA Mongo (`stock`)** | Compliant (`stock_bot_safety*` + in-memory fakes) | Compliant — retain file-based CLI mode so all `cargo test --workspace --lib --offline` tests run with zero DB connections | Compliant only if every ported Postgres test preserves isolated `stock_bot_safety*` schema creation/teardown |
|
||||
| **No `data-ingestion` or `9900K` live/paper side effects** | Compliant | Compliant | Compliant |
|
||||
|
||||
---
|
||||
|
||||
## 6. Recommendation, Implied Follow-Up Tasks & What Not to Port
|
||||
|
||||
### Recommendation
|
||||
|
||||
**Select Option B.** It captures virtually 100% of the real throughput and NVMe-storage benefit of Rust where the data is actually large (`845.7M` `eodPrices`, `51.5M` `qmPrices`, `30.5M` `qmFilings`, and M2's `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`), aligns word-for-word with `design/PLATFORM-PLAN.md` §4 and `design/DATA-CONTRACTS.md` §3A, requires no reopened locked decisions, and avoids risking or delaying M2 to rewrite 20k LOC of already-fast, heavily-tested TypeScript security-master logic.
|
||||
|
||||
### Implied Follow-Up Tasks (Director-Gated — Not Yet Queued or Enacted)
|
||||
|
||||
If the director approves Option B, the concrete follow-up sequence is:
|
||||
|
||||
1. **Add Rust read-only MongoDB safety guard (`tools/curate-etl/src/mongo_safety.rs`):** Port the URI/host/loopback/IPv4-normalization and `trading_admin`-blocking rules from `apps/stock/config/src/env-safety.ts` with offline unit tests mirroring `test/unit/environment-safety*.test.ts`.
|
||||
2. **Add sealed read-only MongoDB `RawDocumentBuf` cursor adapter (`tools/curate-etl/src/mongo_stream.rs`):** Add exact-pinned `mongodb` (`bson-3`) + minimal `tokio` to `tools/curate-etl/Cargo.toml`, exposing only allowlisted read-only `find` streams feeding the existing `bson_*` decoders (zero write/admin methods exposed).
|
||||
3. **Wire `--mongo-uri` / `MONGODB_READ_URI` cursor mode into `curate-bars-1d` and `curate-events` (Stage 1 — cursor swap + adoption parity & provenance checks):** Allow bulk M1 commands to stream directly from read-only QA MongoDB without intermediate `.bson` files while preserving `--eod-prices <path>` file mode for offline fixture replay. **Adoption gate:** assert byte-identical file-versus-cursor output parity on pinned fixtures, and emit a per-run provenance manifest recording the source snapshot or retained input identifier, exact query bounds (`filter`/date bounds and run timestamp), and the pinned `curate-inputs` security-master `generationId` (so production datasets remain traceable even if a provider later corrects a bar or filing).
|
||||
4. **Add partitioned bounded-memory streaming & overlapped read/write pipelining to `curate-bars-1d` and `curate-events` (Stage 2 — global-backfill RAM & I/O):** Partition MongoDB queries by calendar year or listing-key range and pipeline async cursor reads with `rayon` Parquet writes so global `845.7M` `eodPrices` and `30.5M` `qmFilings` runs fit comfortably inside `quant`'s `125 GiB` RAM instead of buffering all decoded rows in memory.
|
||||
5. **Reuse the Rust cursor adapter for M2 `curate-bars-1m` (QuestDB `10.2.0` ILP v2) and `curate-ceo-posts`:** Stream `eodIntraday1M` (`3.40B`, **un-adjusting** retroactively split-adjusted OHLCV via `qmSplits`), `qmIntraday` (`173.3M`, ingesting **already-raw** `open..close` and `sharevolume` directly without split un-adjustment), `CAD.FOREX` `1m` (`5.2M`), and `ceoPosts` (`14.8M`) directly from read-only MongoDB with zero `.bson` scratch files; enforce the M2 exit-criterion split-boundary comparison on `NEXM.V` (`1:20`) and `NVDA.US` (`10:1`) confirming `bars_1m` session closes match raw `bars_1d` closes within `0.5%`.
|
||||
6. **Keep `run-export-raw-bson.ts` as a diagnostic/fixture tool (optional deprecation later):** Retain T-117 for bounded `--limit` fixture captures and offline debugging; remove it from the bulk production path once Step 3 (and Step 4 for global backfills) is verified on `quant`.
|
||||
|
||||
### What Should NOT Be Ported to Rust
|
||||
|
||||
- **Pass 1–6 Security Master (`apps/stock/data-pipeline/src/security-master/` — 17,924 LOC, 40 test files):** Logic- and review-bound, runs in sub-second synthetic time, and has complex domain heuristics (ISIN/CUSIP rescue, IB ATS routing, ticker-reuse spans, OTC delisting chains, override precedence) that are faster to inspect and iterate in TypeScript.
|
||||
- **PostgreSQL Security-Master Persistence (`persist.ts`) & TSV Exporter (`export-curate-inputs.ts`):** Already batched via `UNNEST` / server-side `NO SCROLL` cursor (`2.36 s` / `140k` rows; `0.40 s` / `500k` mappings) and tightly integrated with `@stock-bot/postgres` migrations and `assertSecurityMasterPersistSafety()`.
|
||||
- **Field-Shape Probe (`source-field-shapes.ts` / `probe-source-field-shapes.ts`):** Bounded `<= 10k`-doc diagnostic utility.
|
||||
- **Service Control Plane (`handlers/`, `repositories/`, `routes/`, `index.ts`):** BullMQ `{data-pipeline_exchanges}`/`{data-pipeline_symbols}` queue consumers (`getFullQueueName` in `libs/core/queue/src/service-utils.ts`), `PipelineSyncRepository`, and Hono `GET /health` tightly integrated with `@stock-bot/di`, `@stock-bot/queue`, `@stock-bot/types`, and `web-api`.
|
||||
|
||||
---
|
||||
|
||||
## 7. Not Verified
|
||||
|
||||
The following items were **not measured** in this docs-only spike and can only be verified on the `quant` host (`10.0.0.51`) or against live read-only QA MongoDB / dev PostgreSQL:
|
||||
|
||||
1. **Live MongoDB cursor throughput, WiredTiger contention, and end-to-end Option B wall-time speedup:** All `export-raw-bson.ts` (`3.57M–3.83M docs/s`) and `curate-etl` (`1.87M rows/s` with `rayon` write) numbers are local synthetic benchmarks. Actual `quant` wall time and the net end-to-end speedup of Option B (both Stage 1 cursor-only and Stage 2 overlapped I/O) are **unmeasured** and depend on WiredTiger disk reads (`--wiredTigerCacheSizeGB 16`), localhost TCP framing, BSON wire overhead on `stock` (`~638 GB`), and NVMe contention.
|
||||
2. **Real BSON document sizes & NVMe scratch footprint:** The intermediate `.bson` size estimates — **~127–225 GiB peak file capacity (~255–450 GiB total write+read I/O)** for `845.7M` `eodPrices` at synthetic `161.7–285.6 B/doc`, and **~499–832 GiB peak file capacity (~998–1,664 GiB total write+read I/O)** for `3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` at assumed `150–250 B/doc` (binary `1 GiB = 2^30` bytes) — extrapolate from synthetic document byte sizes; actual uncompressed BSON sizes in QA MongoDB are unmeasured.
|
||||
3. **`quant` 24-thread `rayon` scaling and peak RAM:** The `4.72x` parallel Parquet write speedup (`94.42 ms` vs `445.79 ms`) was measured locally on a 32-thread host on `1,000,000` synthetic rows. Peak RAM and scaling on `quant` (`12900K`, 24 threads, `125 GiB` RAM) for the US+CA subset (~100–150M `eodPrices` rows, estimated `20–30 GiB` peak RAM) vs. full `845.7M` global rows (`> 160 GiB` unsharded, requiring date/key sharding or `--threads 1`) remain unverified.
|
||||
4. **Live `bar-spans.ts` and Pass 4 `sample-closes.ts` wall time:** MongoDB `$group` aggregation time on `845.7M` `eodPrices` and `51.5M` `qmPrices`, plus live 25-date `{ date: { $in: sampleDates } }` index selectivity, have not been timed against live QA MongoDB.
|
||||
5. **Unverified live provider field shapes:** Exact field names and BSON types on live QA MongoDB for `ceoShorts` (`--shares-short-field`, `timestamp` unit), `qmFilings` (`--filings-form-type-field`, `symbol` vs `qmSearchCode`), `qmEarnings` optional fields, `qmDividends` (`amount`/`currency`), `teMarketData` (`t` epoch unit), and `qmPrices.date` string vs `DateTime` format remain pending the first host run of `probe-source-field-shapes.ts`.
|
||||
6. **QuestDB `10.2.0` ILP v2 throughput (M2):** Multi-socket Rust ILP v2 ingestion rate into `bars_1m` (`PARTITION BY MONTH`, `DEDUP UPSERT KEYS(ts, listing_id)`) on `quant` has not been benchmarked.
|
||||
7. **Rust `mongodb` crate compile time and transitive crate count:** Exact transitive dependency footprint and offline build time for `mongodb` (`bson-3`) + `tokio` inside this workspace have not been measured because this spike adds no crates.
|
||||
|
||||
---
|
||||
|
||||
## Addendum: M1 Live Verification & Final Option B Record (`2026-11-30`)
|
||||
|
||||
During Milestone `M1` closure on branch `m1-close-evidence`, the Option B Rust MongoDB driver and CLI wiring (`tools/curate-etl`) were implemented, compiled offline, unit/integration-tested, and executed end-to-end against live read-only QA MongoDB (`studio_stock_bot_read@stock`) on `quant` (`10.0.0.51`) into isolated output directory `/mnt/data/stockbot/m1-isolated/curated`. Every Section 7 unknown applicable to `M1` is now resolved empirically (item 6 — QuestDB `10.2.0` ILP v2 — remains scoped strictly to `M2`):
|
||||
|
||||
### A.1 Dependency Footprint & Offline Build/Test Verification (Resolves §7.7)
|
||||
|
||||
- **Driver pin (`tools/curate-etl/Cargo.toml`):** `mongodb = "=3.10.2"` (`default-features = false`, features `compat-3-3-0`, `bson-3`, `sync`, `rustls-tls`, `dns-resolver`).
|
||||
- **Transitive crate delta:** `123` transitive crates added to `Cargo.lock` (all vendored/cached for `--offline` builds; zero OpenSSL system dependency).
|
||||
- **Offline build & tests:**
|
||||
- `CARGO_BUILD_JOBS=2 cargo build --release -p curate-etl --offline`: **PASSED** (`1m 00s` incremental, `0` compiler warnings, `13 MB` static-TLS release binary).
|
||||
- `CARGO_BUILD_JOBS=2 bun run test:native`: **PASSED** (`150` `apps/stock/engine` lib tests + `582` `curate-etl` unit tests + all `45` `curate-etl` integration/contract suites including `mongo_driver_cli_contract.rs`, `0` failures).
|
||||
- **Read-only safety parity:** `tools/curate-etl/src/mongo_safety.rs` and `tools/curate-etl/src/mongo_stream.rs` enforce `MONGODB_READ_URI`, reject `trading_admin` and writable loopback/LAN URIs, and expose a sealed `ReadOnlyMongoClient` with read-only raw-BSON cursors only (zero write/admin/drop/index methods).
|
||||
|
||||
### A.2 Live Provider Field Shapes & Empirical Findings (Resolves §7.5)
|
||||
|
||||
Measured by `apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts` (`7,435` docs across all `8` M1 collections in `0.7 s`, recorded in `design/data-pipeline/m1-source-field-shapes.md`) plus live curation verification:
|
||||
|
||||
- **`qmSplits` sign convention (critical empirical catch):** Across all `16,892 / 16,892` (`100.00%`) `qmSplits` documents with numeric `forfactor`/`tofactor` (out of `18,751` total), 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`). `tools/curate-etl/src/bson_qm_actions.rs` now converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` (avoiding 6-decimal truncation like `0.142857` for 7:1) or `1.0 / splitratio` when `forfactor`/`tofactor` are blank.
|
||||
- **`ceoShorts` mapping key:** `ceoShorts.symbol` uses exchange-suffixed tickers (`"A.V"`, `"ACB.TO"`) matching `provider_mapping(source='eod')`, with fields `number_of_shares` and `net_change`.
|
||||
- **`qmFilings` Canadian keys:** `qmFilings` omits `:CA` on Canadian `symbol` rows (`symbol: "RY", exchange: "TSX"`); `bson_qm_events.rs` qualifies Canadian exchanges to `"{symbol}:CA"` during `provider_mapping(source='qm')` resolution.
|
||||
- **`qmDividends`:** Confirmed `amount` (`100%` numeric) and `currency` (`92.8%` present; missing-currency rows cleanly counted as decode rejects).
|
||||
|
||||
### A.3 Live `quant` Curation & Security-Master Timings (Resolves §7.1–§7.4)
|
||||
|
||||
| Pipeline Stage | Runtime / Host | Input Streamed (Read-Only QA Mongo) | Curated Output (Isolated Path) | Wall Time |
|
||||
| --- | --- | --- | --- | ---: |
|
||||
| Security-Master Passes 1–6 + dev Postgres persist (`apps/stock/data-pipeline`, TS) | Workstation -> `localhost:5433/trading_bot_dev` | `317.8k` `eodSymbols`, `18.4k` `ibSymbols`, `47.2k` `qmSymbols`, `12.6k` `ceoSymbols`, `230` `eodSymbolChange` + bar-span aggregations + 25-date Pass 4 closes | `63,703` instruments, `64,804` listings, `109,194` mappings, `93` OTC continuities (`eod=100.0%`, `ib=97.9%`, `qm=97.1%`, `ceo=95.8%` gate-eligible) | `7m 23s` total (`2.86 s` idempotent Postgres persist) |
|
||||
| `curate-fx-1d --from-mongo` | `quant` (`10.0.0.51`, Rust) | `CAD.FOREX` + `teMarketData.USDCAD` | `fx_1d/part.parquet`: `12,273` rows (`356 KB`, `2,701/2,701` overlap checks passed, max diff `0.386%`) | **`0.055 s`** |
|
||||
| `curate-corporate-actions --from-mongo` | `quant` (Rust) | `18,751` `qmSplits` + `495,942` `qmDividends` + `1,573` delistings | `corporate_actions/part.parquet`: `355,718` rows (`13,877` listings, `2.47 MB`) | **`0.702 s`** |
|
||||
| `curate-shorts --from-mongo` | `quant` (Rust) | `692,904` `ceoShorts` | `shorts/part.parquet`: `502,610` rows (`5,184` Canadian listings, `3.58 MB`) | **`0.831 s`** |
|
||||
| `curate-adj-factors --from-mongo` (`point_in_time_fenced`, `--vault-cutoff 2025-02-13`, `--date-gte 1976-01-01`) | `quant` (Rust) | `18,738` `qmSplits` + `464,850` `qmDividends` + `103.38M` `bars_1d` `prev_close` index | `adj_factors/part.parquet`: `343,746` rows (`12,512` listings, `3.90 MB`; `443` splits + `9,817` divs fenced) | **`5.976 s`** |
|
||||
| `curate-events --from-mongo --date-gte 2017-01-01` | `quant` (Rust) | `16,829,977` `qmFilings` (`27.06 GB` raw BSON, string `timefiled`) + `218,815` `qmEarnings` (`75.80 MB`, BSON `DateTime` `reportDate`; `8 MB` peak chunk) | `events/year=2017..2025/part.parquet`: `2,771,888` total events (`2,569,808` filings across `11,072` listings + `202,080` earnings across `8,348` listings; `17,284` linked to same-day filings + `201,531` lagged `16:05 ET`; `86.08 MB`) | **`76.466 s`** |
|
||||
| `curate-bars-1d --from-mongo --with-qm-prices --date-gte 2005-01-01 --threads 8` | `quant` (Rust, indexed 250-key `$in` chunks) | `104,009,957` `eodPrices` (`24.63 GB`) + `40,052,628` `qmPrices` (`12.97 GB`) + `18,751` `qmSplits` | `bars_1d/year=2005..2025/part.parquet`: `103,381,236` rows (`60,848` listings, `21` files, `1.106 GB`; `33.50M/38.28M` QM volume checks within 1%; `NVDA 2024-06-07` rel diff `5.82e-8`) | **`492.550 s` (`8m 12s`)** |
|
||||
|
||||
*Index-selectivity finding:* Querying `eodPrices` with a bare `{ date: { $gte: "2005-01-01" } }` selects `date_1_eodSearchCode_1` and causes random WiredTiger seeks (~100 min). Streaming mapped US/CA `eodSearchCode`s in 250-key `$in` chunks (`ChunkedMongoRawDocumentSource`) hits `{"eodSearchCode": 1}` sequentially and streams `37.6 GB` of raw BSON (`144.06M` docs) + writes `1.106 GB` of Zstd Parquet with **zero intermediate `.bson` scratch files** in `8m 12s`.
|
||||
|
||||
### A.4 Final Recommendation (Confirmed)
|
||||
|
||||
**Do NOT move `apps/stock/data-pipeline` itself to Rust. Lock Option B permanently:**
|
||||
1. **Keep `apps/stock/data-pipeline` in TypeScript** for security-master Passes 1–6 (`17.9k` LOC, `40` test files, complex issuer/ATS/delisting heuristics), PostgreSQL persistence, TSV generation (`export-curate-inputs.ts`), field probes, and BullMQ/Hono orchestration.
|
||||
2. **Keep bulk curation in Rust (`tools/curate-etl` with `--from-mongo` raw-BSON cursors)** — now proven end-to-end on `quant` at `103.38M` daily bars (`8m 12s`, `0` scratch `.bson` bytes) and `16.83M` filings + `218.8k` earnings (`76.5 s`).
|
||||
3. **Keep `M2` intraday QuestDB `10.2.0` ILP v2 ingestion (`3.40B` `eodIntraday1M` + `173.3M` `qmIntraday` + `14.8M` `ceoPosts`) scoped to `M2`** inside `tools/curate-etl`, reusing the verified `ReadOnlyMongoClient` + `ChunkedMongoRawDocumentSource` infrastructure built in `M1`.
|
||||
23
libs/data/duckdb/package.json
Normal file
23
libs/data/duckdb/package.json
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
{
|
||||
"name": "@stock-bot/duckdb",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Server-side DuckDB executor and MarketDataStore wiring for curated Hive Parquet datasets",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"test": "bun test"
|
||||
},
|
||||
"dependencies": {
|
||||
"@duckdb/node-api": "^1.4.4-r.1",
|
||||
"@stock-bot/research": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.11.0"
|
||||
}
|
||||
}
|
||||
266
libs/data/duckdb/src/index.ts
Normal file
266
libs/data/duckdb/src/index.ts
Normal file
|
|
@ -0,0 +1,266 @@
|
|||
/**
|
||||
* Concrete server-side DuckDB executor and `MarketDataStore` wiring over
|
||||
* curated Hive-partitioned Parquet datasets (`design/DATA-CONTRACTS.md` §3.A & §4).
|
||||
*
|
||||
* Uses `@duckdb/node-api` (native N-API bindings, works in both Bun and Node)
|
||||
* while keeping `@stock-bot/research` browser-safe and dependency-free.
|
||||
*/
|
||||
|
||||
import { copyFile, link, mkdir, mkdtemp, open, rm, type FileHandle } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DuckDBInstance, type DuckDBConnection, type DuckDBValue } from '@duckdb/node-api';
|
||||
import type { MarketDataStore, TableCell, TableRow } from '@stock-bot/research/market-data-store';
|
||||
import {
|
||||
createDuckDbMarketDataStore,
|
||||
type AdjFactorsArtifactPinner,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbMarketDataStoreOptions,
|
||||
type DuckDbParam,
|
||||
type PinnedAdjFactorsArtifact,
|
||||
} from '@stock-bot/research/market-data-store-duckdb';
|
||||
|
||||
const UTF8_DECODER = new TextDecoder('utf-8', { fatal: false });
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
export interface CreateNodeDuckDbExecutorOptions {
|
||||
/** Optional DuckDB file path; defaults to `':memory:'` for read-only Parquet scans. */
|
||||
readonly databasePath?: string;
|
||||
}
|
||||
|
||||
export interface ClosableDuckDbExecutor extends DuckDbExecutor {
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export interface OpenDuckDbMarketDataStoreOptions
|
||||
extends Omit<DuckDbMarketDataStoreOptions, 'executor'> {
|
||||
/** Optional DuckDB database path; defaults to `':memory:'`. */
|
||||
readonly databasePath?: string;
|
||||
}
|
||||
|
||||
export interface OpenedDuckDbMarketDataStore {
|
||||
readonly store: MarketDataStore;
|
||||
readonly executor: ClosableDuckDbExecutor;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
function formatEpochDaysIso(days: number): string {
|
||||
const date = new Date(days * MS_PER_DAY);
|
||||
const y = String(date.getUTCFullYear()).padStart(4, '0');
|
||||
const m = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const d = String(date.getUTCDate()).padStart(2, '0');
|
||||
return `${y}-${m}-${d}`;
|
||||
}
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return value !== null && typeof value === 'object';
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes a `@duckdb/node-api` cell value into `@stock-bot/research`'s
|
||||
* strict `TableCell` (`string | number | boolean | null`) contract.
|
||||
*/
|
||||
export function normalizeDuckDbCell(value: unknown): TableCell {
|
||||
if (value === null || value === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (typeof value === 'string' || typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
if (typeof value === 'number') {
|
||||
return Object.is(value, -0) ? 0 : value;
|
||||
}
|
||||
if (typeof value === 'bigint') {
|
||||
const asNumber = Number(value);
|
||||
if (!Number.isSafeInteger(asNumber)) {
|
||||
throw new RangeError(
|
||||
`DuckDB BIGINT value ${value.toString()} exceeds JavaScript safe integer range.`
|
||||
);
|
||||
}
|
||||
return asNumber;
|
||||
}
|
||||
if (value instanceof Uint8Array) {
|
||||
return UTF8_DECODER.decode(value);
|
||||
}
|
||||
if (value instanceof Date) {
|
||||
return value.getTime();
|
||||
}
|
||||
if (isRecord(value)) {
|
||||
// DuckDBBlobValue / DuckDBBitValue expose `{ bytes: Uint8Array }` (e.g. parquet_kv_metadata)
|
||||
if (value.bytes instanceof Uint8Array) {
|
||||
return UTF8_DECODER.decode(value.bytes);
|
||||
}
|
||||
// DuckDBDateValue exposes `{ days: number }`
|
||||
if (typeof value.days === 'number' && Number.isFinite(value.days)) {
|
||||
return formatEpochDaysIso(value.days);
|
||||
}
|
||||
// DuckDBTimestampValue / DuckDBTimestampTZValue expose `{ micros: bigint }`
|
||||
if (typeof value.micros === 'bigint') {
|
||||
const ms = Number(value.micros / 1000n);
|
||||
if (!Number.isSafeInteger(ms)) {
|
||||
throw new RangeError(
|
||||
`DuckDB timestamp micros ${value.micros.toString()} exceeds safe millisecond range.`
|
||||
);
|
||||
}
|
||||
return ms;
|
||||
}
|
||||
// DuckDBDecimalValue exposes `{ value: bigint, scale: number }`
|
||||
if (typeof value.value === 'bigint' && typeof value.scale === 'number') {
|
||||
return Number(value.value) / 10 ** value.scale;
|
||||
}
|
||||
}
|
||||
return String(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens an in-process `@duckdb/node-api` connection and adapts it to
|
||||
* {@link DuckDbExecutor}.
|
||||
*/
|
||||
export async function createNodeDuckDbExecutor(
|
||||
options: CreateNodeDuckDbExecutorOptions = {}
|
||||
): Promise<ClosableDuckDbExecutor> {
|
||||
const databasePath = options.databasePath ?? ':memory:';
|
||||
const instance = await DuckDBInstance.create(databasePath);
|
||||
const connection: DuckDBConnection = await instance.connect();
|
||||
let closed = false;
|
||||
|
||||
const assertOpen = (): void => {
|
||||
if (closed) {
|
||||
throw new Error('DuckDbExecutor connection has already been closed.');
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
async run(sql: string): Promise<void> {
|
||||
assertOpen();
|
||||
await connection.run(sql);
|
||||
},
|
||||
|
||||
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
||||
assertOpen();
|
||||
const values: DuckDBValue[] = params.map(param => param as DuckDBValue);
|
||||
const reader =
|
||||
values.length > 0
|
||||
? await connection.runAndReadAll(sql, values)
|
||||
: await connection.runAndReadAll(sql);
|
||||
const rawRows = reader.getRowObjects();
|
||||
const rows: TableRow[] = new Array(rawRows.length);
|
||||
for (let i = 0; i < rawRows.length; i += 1) {
|
||||
const raw = rawRows[i];
|
||||
const clean: Record<string, TableCell> = {};
|
||||
if (raw !== undefined) {
|
||||
for (const [col, cell] of Object.entries(raw)) {
|
||||
clean[col] = normalizeDuckDbCell(cell);
|
||||
}
|
||||
}
|
||||
rows[i] = clean;
|
||||
}
|
||||
return rows;
|
||||
},
|
||||
|
||||
async close(): Promise<void> {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
connection.closeSync();
|
||||
instance.closeSync();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pins a mutable `<curatedRoot>/adj_factors/part.parquet` path to a single
|
||||
* inode/snapshot across footer verification and factor scan so concurrent
|
||||
* atomic replacements by `curate-etl` cannot introduce TOCTOU drift.
|
||||
*
|
||||
* On Linux, opens a read-only file descriptor and exposes `/proc/self/fd/<fd>`.
|
||||
* On platforms without `/proc/self/fd`, falls back to a private hardlink (or
|
||||
* copy across filesystems) inside a temporary directory cleaned up in `release()`.
|
||||
*/
|
||||
export function createFsAdjFactorsPinner(): AdjFactorsArtifactPinner {
|
||||
return async (sourcePath: string): Promise<PinnedAdjFactorsArtifact> => {
|
||||
if (process.platform === 'linux') {
|
||||
const handle: FileHandle = await open(sourcePath, 'r');
|
||||
let released = false;
|
||||
return {
|
||||
pinnedPath: `/proc/self/fd/${handle.fd}`,
|
||||
async release(): Promise<void> {
|
||||
if (released) {
|
||||
return;
|
||||
}
|
||||
released = true;
|
||||
await handle.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const tempDir = await mkdtemp(join(tmpdir(), 'stockbot-adj-pin-'));
|
||||
const pinnedPath = join(tempDir, 'adj_factors.parquet');
|
||||
try {
|
||||
await link(sourcePath, pinnedPath);
|
||||
} catch {
|
||||
await copyFile(sourcePath, pinnedPath);
|
||||
}
|
||||
let released = false;
|
||||
return {
|
||||
pinnedPath,
|
||||
async release(): Promise<void> {
|
||||
if (released) {
|
||||
return;
|
||||
}
|
||||
released = true;
|
||||
await rm(tempDir, { recursive: true, force: true });
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens a ready-to-use DuckDB-backed {@link MarketDataStore} wired with
|
||||
* `@duckdb/node-api` and a filesystem `adj_factors` artifact pinner.
|
||||
*/
|
||||
export async function openDuckDbMarketDataStore(
|
||||
options: OpenDuckDbMarketDataStoreOptions
|
||||
): Promise<OpenedDuckDbMarketDataStore> {
|
||||
const tempDir = options.env?.STOCK_BOT_DUCKDB_TEMP_DIR;
|
||||
if (typeof tempDir === 'string' && tempDir.trim().length > 0) {
|
||||
await mkdir(tempDir, { recursive: true });
|
||||
}
|
||||
|
||||
const executor = await createNodeDuckDbExecutor({
|
||||
databasePath: options.databasePath,
|
||||
});
|
||||
|
||||
const pinAdjFactorsArtifact =
|
||||
options.pinAdjFactorsArtifact ??
|
||||
(options.immutableAdjFactorsPath === undefined ? createFsAdjFactorsPinner() : undefined);
|
||||
|
||||
try {
|
||||
const store = createDuckDbMarketDataStore({
|
||||
...options,
|
||||
executor,
|
||||
...(pinAdjFactorsArtifact !== undefined ? { pinAdjFactorsArtifact } : {}),
|
||||
});
|
||||
|
||||
return {
|
||||
store,
|
||||
executor,
|
||||
async close(): Promise<void> {
|
||||
await executor.close();
|
||||
},
|
||||
};
|
||||
} catch (err) {
|
||||
await executor.close();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
createDuckDbMarketDataStore,
|
||||
type AdjFactorsArtifactPinner,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbMarketDataStoreOptions,
|
||||
type DuckDbParam,
|
||||
type PinnedAdjFactorsArtifact,
|
||||
};
|
||||
250
libs/data/duckdb/test/duckdb-market-data-store.test.ts
Normal file
250
libs/data/duckdb/test/duckdb-market-data-store.test.ts
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import {
|
||||
computeVaultCutoffTs,
|
||||
VaultHoldoutFenceError,
|
||||
type BarRecord,
|
||||
} from '@stock-bot/research/market-data-store';
|
||||
import {
|
||||
createNodeDuckDbExecutor,
|
||||
openDuckDbMarketDataStore,
|
||||
} from '../src/index';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
while (tempDirs.length > 0) {
|
||||
const dir = tempDirs.pop();
|
||||
if (dir !== undefined) {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function buildCuratedFixture(): Promise<{
|
||||
curatedRoot: string;
|
||||
duckTempDir: string;
|
||||
vaultCutoffTs: number;
|
||||
}> {
|
||||
const root = await mkdtemp(join(tmpdir(), 'stockbot-duckdb-mds-'));
|
||||
tempDirs.push(root);
|
||||
const curatedRoot = join(root, 'curated');
|
||||
const duckTempDir = join(root, 'duckdb-tmp');
|
||||
|
||||
await mkdir(join(curatedRoot, 'bars_1d', 'year=2024'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'bars_1d', 'year=2025'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'adj_factors'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'events', 'year=2024'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'shorts'), { recursive: true });
|
||||
await mkdir(join(curatedRoot, 'fx_1d'), { recursive: true });
|
||||
await mkdir(duckTempDir, { recursive: true });
|
||||
|
||||
// Max ingested = 2025-08-13 -> Vault cutoff = 2025-02-13T00:00:00.000Z
|
||||
const vaultCutoffTs = computeVaultCutoffTs('2025-08-13');
|
||||
const vaultCutoffMicros = vaultCutoffTs * 1000;
|
||||
const asOfMicros = vaultCutoffMicros - 1;
|
||||
|
||||
const writer = await createNodeDuckDbExecutor();
|
||||
try {
|
||||
// 2024 bars (pre-Vault): listing 101 (USD, NVDA 10:1 split on 2024-06-10) + listing 202 (CAD)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(101::INTEGER, DATE '2024-06-07', TIMESTAMPTZ '2024-06-07 20:00:00+00', 1200.0::DOUBLE, 1220.0::DOUBLE, 1190.0::DOUBLE, 1208.88::DOUBLE, 41238600.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-07 20:00:00+00'),
|
||||
(101::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 120.37::DOUBLE, 123.10::DOUBLE, 117.01::DOUBLE, 121.79::DOUBLE, 314162700.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00'),
|
||||
(202::INTEGER, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 20:00:00+00', 140.0::DOUBLE, 142.0::DOUBLE, 139.0::DOUBLE, 141.5::DOUBLE, 1200000.0::DOUBLE, NULL::DOUBLE, 'CAD'::VARCHAR, TIMESTAMPTZ '2024-06-10 20:00:00+00')
|
||||
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
|
||||
) TO '${join(curatedRoot, 'bars_1d', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// 2025 bars: one pre-Vault bar (2025-02-12) and one Vault bar (2025-02-14)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(101::INTEGER, DATE '2025-02-12', TIMESTAMPTZ '2025-02-12 20:00:00+00', 130.0::DOUBLE, 132.0::DOUBLE, 129.0::DOUBLE, 131.0::DOUBLE, 200000000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-12 20:00:00+00'),
|
||||
(101::INTEGER, DATE '2025-02-14', TIMESTAMPTZ '2025-02-14 20:00:00+00', 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 999.0::DOUBLE, 1.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, TIMESTAMPTZ '2025-02-14 20:00:00+00')
|
||||
) AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at)
|
||||
) TO '${join(curatedRoot, 'bars_1d', 'year=2025', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// Point-in-time fenced adj_factors snapshot (10:1 split on 2024-06-10)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(101::INTEGER, DATE '2024-06-10', 10.0::DOUBLE, 10.05::DOUBLE, TIMESTAMPTZ '2024-06-10 00:00:00+00')
|
||||
) AS t(listing_id, ex_date, cum_split_factor, cum_total_factor, known_at)
|
||||
) TO '${join(curatedRoot, 'adj_factors', 'part.parquet')}' (
|
||||
FORMAT PARQUET,
|
||||
KV_METADATA {
|
||||
'stock_bot.adj_factors.format_version': '1',
|
||||
'stock_bot.adj_factors.snapshot_kind': 'point_in_time_fenced',
|
||||
'stock_bot.adj_factors.as_of_micros': '${asOfMicros}',
|
||||
'stock_bot.adj_factors.vault_cutoff_micros': '${vaultCutoffMicros}',
|
||||
'stock_bot.adj_factors.rows_written': '1',
|
||||
'stock_bot.adj_factors.snapshot_checksum': '0x0123456789abcdef'
|
||||
}
|
||||
)
|
||||
`);
|
||||
|
||||
// Events (2024 filing)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(202::INTEGER, TIMESTAMPTZ '2024-06-05 14:30:00+00', TIMESTAMPTZ '2024-06-05 14:30:00+00', 'filing_timestamp'::VARCHAR, 'filing'::VARCHAR, 'MD&A'::VARCHAR, '{"filing_id":"f1"}'::VARCHAR)
|
||||
) AS t(listing_id, ts, known_at, known_at_source, kind, subtype, payload_json)
|
||||
) TO '${join(curatedRoot, 'events', 'year=2024', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// Canadian shorts (+4 biz day known_at)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
(202::INTEGER, DATE '2024-06-15', TIMESTAMPTZ '2024-06-21 21:00:00+00', 500000.0::DOUBLE, 25000.0::DOUBLE, NULL::DOUBLE, 'ceo_shorts'::VARCHAR)
|
||||
) AS t(listing_id, report_date, known_at, shares_short, net_change, pct_float, source)
|
||||
) TO '${join(curatedRoot, 'shorts', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
|
||||
// FX 1d (USDCAD)
|
||||
await writer.run(`
|
||||
COPY (
|
||||
SELECT * FROM (VALUES
|
||||
('USDCAD'::VARCHAR, DATE '2024-06-10', TIMESTAMPTZ '2024-06-10 23:59:59.999999+00', 1.375::DOUBLE, 1.378::DOUBLE, 1.372::DOUBLE, 1.376::DOUBLE, 'eod_forex'::VARCHAR, TIMESTAMPTZ '2024-06-10 23:59:59.999999+00')
|
||||
) AS t(pair, session_date, ts, open, high, low, close, source, known_at)
|
||||
) TO '${join(curatedRoot, 'fx_1d', 'part.parquet')}' (FORMAT PARQUET)
|
||||
`);
|
||||
} finally {
|
||||
await writer.close();
|
||||
}
|
||||
|
||||
return { curatedRoot, duckTempDir, vaultCutoffTs };
|
||||
}
|
||||
|
||||
describe('openDuckDbMarketDataStore (@duckdb/node-api)', () => {
|
||||
test('reads real Parquet bars (raw, split, total), events, shorts, fx, universe and enforces Vault fence', async () => {
|
||||
const { curatedRoot, duckTempDir, vaultCutoffTs } = await buildCuratedFixture();
|
||||
const opened = await openDuckDbMarketDataStore({
|
||||
curatedRoot,
|
||||
vaultCutoffTs,
|
||||
env: {
|
||||
STOCK_BOT_DUCKDB_MEMORY_LIMIT: '2GB',
|
||||
STOCK_BOT_DUCKDB_THREADS: '2',
|
||||
STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir,
|
||||
},
|
||||
});
|
||||
|
||||
try {
|
||||
// 1. Raw bars: request through 2025-12-31 must clamp before Vault cutoff (2025-02-13) and never return 2025-02-14!
|
||||
const rawBars: BarRecord[] = [];
|
||||
for await (const batch of opened.store.bars({
|
||||
listingIds: [101],
|
||||
timeframe: '1d',
|
||||
from: '2024-06-01',
|
||||
to: '2025-12-31',
|
||||
adjustment: 'raw',
|
||||
})) {
|
||||
rawBars.push(...batch.rows);
|
||||
}
|
||||
expect(rawBars.length).toBe(3);
|
||||
expect(rawBars.every(r => r.ts < vaultCutoffTs)).toBe(true);
|
||||
expect(rawBars[0]!.close).toBeCloseTo(1208.88, 6);
|
||||
expect(rawBars[0]!.volume).toBeCloseTo(41_238_600, 1);
|
||||
|
||||
// 2. Vault rejection when from >= vaultCutoffTs
|
||||
let rejected = false;
|
||||
try {
|
||||
for await (const _batch of opened.store.bars({
|
||||
listingIds: [101],
|
||||
timeframe: '1d',
|
||||
from: '2025-02-13',
|
||||
to: '2025-08-01',
|
||||
adjustment: 'raw',
|
||||
})) {
|
||||
// should not yield
|
||||
}
|
||||
} catch (err) {
|
||||
rejected = err instanceof VaultHoldoutFenceError;
|
||||
}
|
||||
expect(rejected).toBe(true);
|
||||
|
||||
// 3. Split-adjusted bars via pinned point_in_time_fenced adj_factors snapshot
|
||||
const splitBars: BarRecord[] = [];
|
||||
for await (const batch of opened.store.bars({
|
||||
listingIds: [101],
|
||||
timeframe: '1d',
|
||||
from: '2024-06-01',
|
||||
to: '2024-06-15',
|
||||
adjustment: 'split',
|
||||
})) {
|
||||
splitBars.push(...batch.rows);
|
||||
}
|
||||
expect(splitBars.length).toBe(2);
|
||||
expect(splitBars[0]!.close).toBeCloseTo(120.888, 6);
|
||||
expect(splitBars[0]!.volume).toBeCloseTo(412_386_000, 1);
|
||||
expect(splitBars[1]!.close).toBeCloseTo(121.79, 6);
|
||||
|
||||
// 4. Total-return-adjusted bars (price divided by cum_total_factor, volume scaled by cum_split_factor)
|
||||
const totalBars: BarRecord[] = [];
|
||||
for await (const batch of opened.store.bars({
|
||||
listingIds: [101],
|
||||
timeframe: '1d',
|
||||
from: '2024-06-01',
|
||||
to: '2024-06-15',
|
||||
adjustment: 'total',
|
||||
})) {
|
||||
totalBars.push(...batch.rows);
|
||||
}
|
||||
expect(totalBars.length).toBe(2);
|
||||
expect(totalBars[0]!.close).toBeCloseTo(1208.88 / 10.05, 6);
|
||||
expect(totalBars[0]!.volume).toBeCloseTo(412_386_000, 1);
|
||||
|
||||
// 5. Events
|
||||
const events = await opened.store.events({
|
||||
kinds: ['filing'],
|
||||
listingIds: [202],
|
||||
from: '2024-06-01',
|
||||
to: '2024-06-30',
|
||||
});
|
||||
expect(events.rows.length).toBe(1);
|
||||
expect(events.rows[0]!.subtype).toBe('MD&A');
|
||||
|
||||
// 6. Shorts (known_at fence)
|
||||
const shortsBeforeKnown = await opened.store.shortsAsOf({
|
||||
listingIds: [202],
|
||||
from: '2024-06-01',
|
||||
to: '2024-06-30',
|
||||
asOf: '2024-06-18',
|
||||
});
|
||||
expect(shortsBeforeKnown.rows.length).toBe(0);
|
||||
|
||||
const shortsAfterKnown = await opened.store.shortsAsOf({
|
||||
listingIds: [202],
|
||||
from: '2024-06-01',
|
||||
to: '2024-06-30',
|
||||
asOf: '2024-06-25',
|
||||
});
|
||||
expect(shortsAfterKnown.rows.length).toBe(1);
|
||||
expect(shortsAfterKnown.rows[0]!.shares_short).toBe(500_000);
|
||||
|
||||
// 7. FX
|
||||
const fx = await opened.store.fx({
|
||||
pair: 'USD.CAD',
|
||||
timeframe: '1d',
|
||||
from: '2024-06-01',
|
||||
to: '2024-06-30',
|
||||
});
|
||||
expect(fx.rows.length).toBe(1);
|
||||
expect(fx.rows[0]!.close).toBeCloseTo(1.376, 6);
|
||||
|
||||
// 8. Universe
|
||||
expect(await opened.store.universe({ ref: 'US_EQ', date: '2024-06-10' })).toEqual([101]);
|
||||
expect(await opened.store.universe({ ref: 'CA_EQ', date: '2024-06-10' })).toEqual([202]);
|
||||
expect(await opened.store.universe({ ref: 'US_CA_EQ', date: '2024-06-10' })).toEqual([
|
||||
101, 202,
|
||||
]);
|
||||
} finally {
|
||||
await opened.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
14
libs/data/duckdb/tsconfig.json
Normal file
14
libs/data/duckdb/tsconfig.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"extends": "../../../tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"composite": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../research"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -74,3 +74,125 @@ Fixed-seed (`20260402`) end-to-end `analyzeSignal` benchmark covering `5,040` bu
|
|||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-signal-study.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 1691.13 ms`, `rowsPerSec = 8,940,793 rows/s` (`2,980 dates/s`, `nObs = 5040`, `meanRankIc = 0.057294`, `recencyGatePassed = true`)
|
||||
|
||||
## DuckDB Curated Parquet Query Planner & `MarketDataStore` Adapter
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/market-data-store-duckdb` (`libs/research/src/market-data-store-duckdb.ts`). The module is dependency-free and browser-safe; DuckDB execution is injected via `DuckDbExecutor` (`{ run(sql), query(sql, params) }`) so parameter values are always bound separately from SQL text.
|
||||
|
||||
### API
|
||||
|
||||
- **`planBars1dQuery(q, ctx)`** — Plans a fenced query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) for `timeframe: '1d'` and `adjustment: 'raw' | 'split' | 'total'`. Rejects `'1m' | '5m' | '1h'` with `MarketDataStoreNotImplementedError`. For `'split'` and `'total'`, requires a verified `point_in_time_fenced` `ctx.adjFactorsSnapshot` matching the query's effective `asOf` and Vault fence, and binds `read_parquet(...)` directly to `ctx.adjFactorsSnapshot.path`.
|
||||
- **`planAdjFactorsMetadataQuery(adjPath)`** / **`parseAdjFactorsSnapshotMetadata(adjPath, kvRows)`** — Plans the `parquet_kv_metadata('<adjPath>')` query for `stock_bot.adj_factors.*` footer keys and strictly parses/validates them (mirroring `tools/curate-etl/src/curate_adj.rs`).
|
||||
- **`planEventsQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/events/year=*/part.parquet` (`hive_partitioning = true`) filtered by allow-listed `kinds` and optional `listingIds`, preserving the Parquet writer's total sort order `(listing_id, ts, kind, subtype, payload_json, known_at, known_at_source)`.
|
||||
- **`planShortsAsOfQuery(q, ctx)`** — Plans a `'vault_fenced'` query over `<curatedRoot>/shorts/part.parquet`, binding UTC `YYYY-MM-DD` `report_date` bounds and microsecond UTC ISO-8601 `known_at <= ?`.
|
||||
- **`planFx1dQuery(q, ctx)`** — Plans a `'vault_fenced'` query (with default `asOf = vaultCutoffTs * 1000 - 1` µs) over `<curatedRoot>/fx_1d/part.parquet` for `timeframe: '1d'`, mapping `'USD.CAD'` to the stored bound parameter `'USDCAD'`. Rejects `'1m'` with `MarketDataStoreNotImplementedError`.
|
||||
- **`planUniverseQuery(q, ctx)`** — Plans a `'vault_fenced'`, survivorship-free query over `<curatedRoot>/bars_1d/year=*/part.parquet` (`hive_partitioning = true`) returning `SELECT DISTINCT b.listing_id ... ORDER BY b.listing_id ASC` for supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`) within `[date - lookbackDays, date]` (default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, configurable via `ctx.universeLookbackDays`).
|
||||
- **`createDuckDbMarketDataStore({ executor, curatedRoot, vaultCutoffTs, vaultOperatorAuthorized?, universeLookbackDays?, adjFactorsPath?, pinAdjFactorsArtifact?, immutableAdjFactorsPath?, env?, barBatchSize? })`** — Returns a `MarketDataStore` adapter that eagerly validates options and `resolveDuckDbConnectionBudget(env)`, lazily executes the three budget `SET` statements sequentially and at most once before the first `executor.query(...)` (including under concurrent first calls, with clean retry if initialization fails), pins a single `adj_factors` artifact version across both `parquet_kv_metadata` footer verification and the `read_parquet` factor scan (via `pinAdjFactorsArtifact` handle pinning or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable `<curatedRoot>/adj_factors/part.parquet`, failing closed with `AdjFactorsSnapshotError('unpinned_mutable_path')` if unpinned), validates per-column scalar types and nullability when mapping rows into `BarBatch` / `Table` / strictly ascending INT32 `universe` `number[]`, and rejects out-of-slice methods (`bars` `1m`/`5m`/`1h`, `fx` `1m`, `crossSection`, `fundamentalsAsOf`, `macroAsOf`) with `MarketDataStoreNotImplementedError` and zero executor calls.
|
||||
|
||||
### Mandatory Vault, PIT, Microsecond & Boundary Validation Rules
|
||||
|
||||
- Every planner delegates unconditionally to `applyVaultFence`, binding `ts`/`report_date` bounds and `known_at <= ?` in UTC (`TZ`-invariant). Under `'vault_fenced'`, `from >= vaultCutoffTs` throws `VaultHoldoutFenceError` and `to`/`asOf` clamp strictly below `vaultCutoffTs`; `'vault_evaluation_only'` requires `vaultOperatorAuthorized === true` (only on `bars`; `events`, `shortsAsOf`, and `fx` are always `'vault_fenced'`).
|
||||
- **Microsecond upper-bound precision:** Curated Parquet `ts` and `known_at` columns store UTC microseconds (`curate_fx_1d` stamps `23:59:59.999999Z`). Date-only `YYYY-MM-DD` upper bounds (`to`, `asOf`) and default or clamped Vault upper bounds expand to the last included Parquet microsecond (`.999999Z` / `vaultCutoffTs * 1000 - 1`), while explicit time-of-day bounds preserve their caller-specified precision. Under `'vault_fenced'`, every planned upper bound remains strictly `< vaultCutoffTs`.
|
||||
- `curatedRoot` (and optional `adjFactorsPath`) are the only values embedded in SQL text and must be absolute POSIX paths free of control characters (`<= 0x1f`, `0x7f`), `'`, `;`, and glob metacharacters (`*`, `?`, `[`, `]`).
|
||||
- All caller values (`listingIds` as `INT32` safe integers, allow-listed `kinds`, `'USD.CAD' -> 'USDCAD'`, and UTC date/timestamp bounds) are validated upfront and passed strictly as bound `?` parameters.
|
||||
|
||||
### `bars` 1d Adjustment Formulas & Verified Fenced `adj_factors` Requirement
|
||||
|
||||
`bars_1d` stores raw OHLC, optional `vwap`, and split-unadjusted raw share `volume`. Because `adj_factors` stores right-to-left cumulative suffix products (`cum_split_factor`, `cum_total_factor`), slicing a retrospective `adj_factors` file with `known_at <= asOf` would still embed future or held-out Vault splits/dividends into earlier cumulative factors.
|
||||
|
||||
- **`'raw'`**: OHLC, `vwap`, and `volume` are returned unadjusted (`adj_factors` is not read).
|
||||
- **`'split'` / `'total'`**: Require a verified `point_in_time_fenced` `adj_factors` Parquet artifact (published by `curate_and_write_adj_factors_as_of` with `stock_bot.adj_factors.*` footer metadata) whose effective inclusive microsecond fence matches the query's effective `asOf` and Vault cutoff. Retrospective, unverified, or mismatched-fence files are rejected with `AdjFactorsSnapshotError` before any `bars` query runs. To prevent TOCTOU races when `curate-etl` atomically replaces `<curatedRoot>/adj_factors/part.parquet` between footer verification and the factor scan, `createDuckDbMarketDataStore` requires either `pinAdjFactorsArtifact` (binding a stable handle such as `/proc/self/fd/<fd>`, `/dev/fd/<fd>`, or a private hardlink/copy for both queries and releasing it in `finally`) or an explicit write-once `immutableAdjFactorsPath` distinct from the mutable published path; unpinned mutable paths fail closed with `AdjFactorsSnapshotError('unpinned_mutable_path')`.
|
||||
- Against the verified `adj_factors` file, `bars_1d` is joined via `ASOF LEFT JOIN` (filtered to `listing_id IN (...) AND known_at <= ?`) on `b.listing_id = a.listing_id AND b.session_date < a.ex_date` (matching the first `adj_factors` row with `ex_date > session_date` per `tools/curate-etl/README.md`):
|
||||
- **`'split'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_split_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
- **`'total'`**: `open`, `high`, `low`, `close`, and `vwap` are divided by `COALESCE(a.cum_total_factor, 1.0)`; `volume` is multiplied by `COALESCE(a.cum_split_factor, 1.0)`.
|
||||
|
||||
### `universe`
|
||||
|
||||
`planUniverseQuery` and `createDuckDbMarketDataStore().universe({ ref, date })` resolve the survivorship-free set of active `INT32` `listing_id`s on a UTC calendar `date` (`YYYY-MM-DD`) directly from curated `bars_1d` Parquet (`hive_partitioning = true`):
|
||||
|
||||
- **Provisional M1 bar-currency membership rule:** Supported `UNIVERSE_REFS` (`'US_EQ'`, `'CA_EQ'`, `'US_CA_EQ'`, matching `trial_ledger.universe_market`) filter `bars_1d.currency` using bound `?` parameters (`'USD'`, `'CAD'`, or `IN ('USD', 'CAD')`). Because membership is provisionally determined by bar quote currency before security-master MIC joins are added, USD-quoted TSX listings land in `'US_EQ'`. `'FX'` and any other ref throw `MarketDataStoreValidationError` (`field: 'ref'`) with zero executor calls.
|
||||
- **Active-listing lookback window:** A listing is active on `date` when it has at least one `bars_1d` row with `session_date` in `[date - lookbackDays, date]` (calendar days; default `DEFAULT_UNIVERSE_LOOKBACK_DAYS = 7`, optional positive-integer `universeLookbackDays` on context/store options). No row after `date` is ever read, so delisted listings appear only while they traded.
|
||||
- **Mandatory Vault & PIT fence:** `date` is always routed through `applyVaultFence` under `'vault_fenced'` scope (`date >= vaultCutoffTs` throws `VaultHoldoutFenceError` with zero executor calls, even when `vaultOperatorAuthorized: true`), and every planned query binds both `b.ts <= ?` and `b.known_at <= ?` strictly below `vaultCutoffTs`.
|
||||
|
||||
### Local Query-Planner Benchmark
|
||||
|
||||
Fixed-seed (`20261129`) local benchmark planning `120,000` mixed queries across `bars` 1d (`raw`/`split`/`total`), `events` (with and without `listingIds`), `shortsAsOf`, and `fx` 1d, plus a fixed-seed (`20261129`) `universe` case exercising `createDuckDbMarketDataStore().universe()` (plan + adapter mapping) over `200` calls × `15,000` listing IDs (`3,000,000` mapped IDs) via an in-memory executor (checksums verified outside the timed sections):
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-market-data-store-duckdb.ts`
|
||||
- **Observed (Bun 1.2.16):**
|
||||
- **Mixed planners (`120,000` queries):** `elapsedMs = 225.79 ms`, `queriesPerSec = 531,470 queries/s` (`758,061` bound params, pinned checksum `8606c98c`)
|
||||
- **`universe` plan + adapter mapping (`200` calls × `15,000` listings):** `elapsedMs = 23.44 ms`, `callsPerSec = 8,534 calls/s`, `rowsPerSec = 128,011,137 rows/s` (`3,000,000` mapped IDs, pinned checksum `ef5f1136`)
|
||||
|
||||
## Signal Panel Builder
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/signal-panel` (`libs/research/src/signal-panel.ts`). The module is pure, synchronous (except `collectBars`), dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers).
|
||||
|
||||
### API
|
||||
|
||||
- **`buildForwardReturnPanel({ bars, signals, horizonSessions, vaultCutoffDate, maxSignalAgeSessions? })`** — Joins daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) with point-in-time `SignalObservation[]` (`{ listingId, knownAt, value }`) into Vault-safe `SignalCrossSection[]` slices ready for `analyzeSignal`. Returns `{ panel, sessionDates, diagnostics }` with strictly ascending `date`s, `ids: Int32Array` sorted ascending by `listingId`, and `signal` / `forwardReturn` as `Float64Array`, deterministic under any input permutation and without mutating caller inputs.
|
||||
- **`shortsTableToSignalRows(table, field)`** — Maps a `MarketDataStore.shortsAsOf` `Table` into `SignalObservation[]` for `field: 'shares_short' | 'net_change' | 'pct_float'`, skipping `null` cells, normalizing `-0` to `0`, and rejecting missing columns or malformed rows with `SignalPanelError`.
|
||||
- **`collectBars(iterable)`** — Drains `AsyncIterable<BarBatch>` (such as `MarketDataStore.bars`) into a flat `BarRecord[]` using indexed loops without mutating yielded batches.
|
||||
|
||||
### UTC Session Calendar, PIT Alignment & Vault Rules
|
||||
|
||||
- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`.
|
||||
- **Strict point-in-time (`knownAt <= bar.ts`):** For each listing and session `d`, the active signal is the latest row with `knownAt <= bar.ts` (ties on identical `(listingId, knownAt)` break deterministically by `value ASC` so the highest value wins regardless of input order). A signal known after the close (e.g. `17:00 ET`) is never applied on `d` and first takes effect on `d + 1`.
|
||||
- **Signal staleness (`maxSignalAgeSessions`):** When set (`>= 0`), age is measured in calendar sessions elapsed since the first actionable session where `sessionMaxTs[s] >= knownAt` (so a `17:00 ET` after-close signal has age `0` on the next trading day). Expired observations are dropped and counted in `diagnostics.droppedStaleSignal`.
|
||||
- **Exact horizon alignment & close validation:** `forwardReturn = close[d + h] / close[d] - 1` uses the listing's own bar exactly `horizonSessions` calendar sessions ahead; missing forward bars are dropped (`diagnostics.droppedMissingForwardBar`) and never shifted to `d + h + 1`. Non-positive or non-finite closes (`<= 0`, `NaN`, `±Infinity`) drop cleanly into `diagnostics.droppedNonPositiveClose` without throwing. Exact pre-cutoff duplicate bars (`ts` and `close` identical) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `SignalPanelError('duplicate_bar')`.
|
||||
- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate`. No cross-section is emitted when either `d` or its forward session `d + horizonSessions` reaches or exceeds `vaultCutoffDate` (counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
|
||||
|
||||
### `SignalPanelError` Codes
|
||||
|
||||
| Code | Meaning |
|
||||
| --- | --- |
|
||||
| `'invalid_input'` | Non-object input envelope, non-array `bars`/`signals`, invalid `AsyncIterable`, invalid shorts field, or missing required table columns |
|
||||
| `'invalid_horizon'` | `horizonSessions` is not a safe integer `>= 1` |
|
||||
| `'invalid_option'` | `maxSignalAgeSessions` is defined and not a safe integer `>= 0` |
|
||||
| `'invalid_date'` | `vaultCutoffDate` is not a valid strict calendar `YYYY-MM-DD` date |
|
||||
| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, non-number pre-cutoff `close`, or malformed `BarBatch` |
|
||||
| `'invalid_signal'` | Malformed signal or shorts table row, invalid `listingId`/`knownAt`, or non-finite non-null signal value |
|
||||
| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` |
|
||||
|
||||
### Local In-Memory Benchmark (`buildForwardReturnPanel`)
|
||||
|
||||
Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `720,000` monthly-ish `17:00 ET` signal rows, `horizonSessions = 5`, `vaultCutoffDate = '2025-03-31'`):
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-signal-panel.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 817.24 ms`, `rowsPerSec = 18,501,301 rows/s` (`5,014` emitted panel dates, `15,042,000` emitted observations, `25` Vault-excluded dates, pinned checksum `f0f28bdf`)
|
||||
|
||||
## Event Study Panel Builder
|
||||
|
||||
Exported from both `@stock-bot/research` and `@stock-bot/research/event-panel` (`libs/research/src/event-panel.ts`). The module is pure, synchronous, dependency-free, and browser-safe (zero `node:*` imports, zero bare `process` access, no database drivers).
|
||||
|
||||
### API
|
||||
|
||||
- **`eventsTableToEventRows(table, filter?)`** — Maps a `MarketDataStore.events` `Table` into point-in-time `EventObservation[]` (`{ listingId, knownAt, kind, subtype }`), validating every row upfront (before applying optional exact-match `filter.kinds` / `filter.subtypes` allow-lists), normalizing `-0` to `0`, and rejecting missing columns, empty filter arrays, or malformed rows with `EventPanelError`.
|
||||
- **`buildEventStudyInput({ bars, events, vaultCutoffDate, exchangeCalendars, benchmark? })`** — Transforms daily `BarRecord[]` (caller-supplied `'total'`-adjusted closes in any order) and `EventObservation[]` rows into a Vault-safe `EventStudyInput` (`{ sessionDates, entityReturns, benchmarkReturns?, events }`) plus `EventPanelDiagnostics` ready for `runEventStudy` / `eventStudy`. Output is deterministic under any input permutation (entities inserted in ascending `listingId` order; events sorted by `(dayIndex ASC, entityId ASC)`) without mutating caller inputs.
|
||||
- `exchangeCalendars: { calendars, listingCalendarId }` (**required**): caller-supplied exchange close calendars (`{ date, closeTs }[]` per calendar ID, plus `listingId -> calendarId` mapping). Every pre-Vault listing in `bars` must be mapped to a calendar that covers all of its pre-Vault bar dates (coverage gaps or missing mappings throw `EventPanelError('invalid_option')`). Each listing's events are anchored against its exchange's actual pre-Vault session close timestamps (e.g. `13:00 ET` on NYSE half-days vs `16:00 ET` on TSX) rather than curated `bars_1d.ts` (`16:00 ET`), and the eligible session date is then mapped onto the shared `sessionDates` index.
|
||||
- `benchmark?: 'equal_weight' | 'none'` (default `'none'` when omitted/`undefined`; `null` or any other value throws `EventPanelError('invalid_option')`): `'none'` omits `benchmarkReturns`; `'equal_weight'` sets `benchmarkReturns[d]` to the mean of finite `entityReturns` on session `d` (`NaN` when none).
|
||||
|
||||
### UTC Session Calendar, PIT Anchoring, `NaN` Returns & Vault Rules
|
||||
|
||||
- **UTC session calendar:** Daily curated bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or `21:00 UTC`), so the integer UTC day key `Math.floor(bar.ts / 86_400_000)` maps 1:1 to the exchange session date `YYYY-MM-DD`.
|
||||
- **Consecutive-session returns & `NaN` contract (`eventStudy`):** For each listing, `entityReturns` is a `Float64Array` aligned to `sessionDates`. Simple close-to-close return `close[d] / close[d - 1] - 1` is computed strictly when the listing has bars on consecutive exchange-calendar sessions (`currCalIdx === prevCalIdx + 1`) and both closes are finite and `> 0` with a finite ratio. Session `0`, missing-bar sessions (including an open exchange session missing for all listings), the first resumption session after a gap, and non-positive/non-finite/overflowing transitions (counted in `diagnostics.nonPositiveCloseReturns`) are written as `NaN` (never `±Infinity`), matching `eventStudy`'s contract in `libs/calculations/src/analytics/event-study.ts` (which rejects `±Infinity` with `NON_FINITE_RETURN` and cleanly drops events with any `NaN` in `[-preDays, +postDays]`).
|
||||
- **Duplicate-bar policy:** Exact pre-cutoff duplicate bars (`ts` and `close` identical, including `NaN === NaN`) are deduplicated into `diagnostics.duplicateBars`; conflicting duplicates on the same `(listingId, date)` throw `EventPanelError('duplicate_bar')`.
|
||||
- **Strict PIT event anchoring & drop precedence:** Each event is classified in strict order: (1) `knownAt >= vaultCutoffDate (00:00:00.000Z)` → `diagnostics.vaultExcludedEvents`; (2) listing has no pre-Vault bars → `diagnostics.droppedUnknownListing`; (3) `knownAt` is after the listing's last pre-Vault exchange close (or its eligible calendar date exceeds the last pre-Vault bar date) → `diagnostics.droppedAfterLastSession`; (4) eligible pre-Vault exchange session dates absent from `sessionDates` → `diagnostics.droppedMissingCalendarSession`; (5) lower-bound binary search over the listing's exchange close timestamps, matching `eventDayIndex` semantics so after-close and post-half-day-close filings always anchor to the next trading session. Exact duplicate `(listingId, dayIndex)` events collapse to one (`diagnostics.duplicateEvents`), preserving `events.length === emitted + vaultExcludedEvents + droppedUnknownListing + droppedAfterLastSession + droppedMissingCalendarSession + duplicateEvents`.
|
||||
- **Vault holdout fence:** `sessionDates` contains only dates strictly `< vaultCutoffDate` (post-cutoff dates are counted in `diagnostics.vaultExcludedDates`), and `bar.close` is never accessed for any bar on or after `vaultCutoffDate`.
|
||||
|
||||
### `EventPanelError` Codes
|
||||
|
||||
| Code | Meaning |
|
||||
| --- | --- |
|
||||
| `'invalid_input'` | Non-object input envelope, non-array `bars`/`events`, malformed `Table`, or missing required columns (`listing_id`, `known_at`, `kind`, `subtype`) |
|
||||
| `'invalid_date'` | `vaultCutoffDate` or an `exchangeCalendars` session `date` is not a valid strict calendar `YYYY-MM-DD` date |
|
||||
| `'invalid_bar'` | Malformed bar record, invalid `INT32` `listingId`, invalid epoch-ms `ts`/`knownAt`, or non-number pre-cutoff `close` |
|
||||
| `'invalid_event'` | Malformed event or table row, invalid `listingId`/`knownAt`, `kind` outside `EVENT_KINDS`, or non-string/non-null `subtype` |
|
||||
| `'invalid_option'` | Invalid `benchmark` mode, missing/malformed/incomplete `exchangeCalendars` (including pre-Vault bar coverage gaps), or invalid/empty `eventsTableToEventRows` filter (`kinds`/`subtypes`) |
|
||||
| `'duplicate_bar'` | Two pre-cutoff bars for the same `(listingId, date)` disagree on `ts` or `close` |
|
||||
|
||||
### Local In-Memory Benchmark (`buildEventStudyInput`)
|
||||
|
||||
Fixed-seed (`20261129`) local benchmark covering `5,040` business sessions × `3,000` listings (`15,120,000` input bars, `240,000` after-close `17:00 ET` filing events at stride `63`, `vaultCutoffDate = '2025-03-31'`, `benchmark: 'equal_weight'`, `XNYS`/`XTSE` exchange calendars):
|
||||
|
||||
- **Command:** `bun run libs/research/scripts/benchmark-event-panel.ts`
|
||||
- **Observed (Bun 1.2.16):** `elapsedMs = 731.06 ms`, `barsPerSec = 20,682,279 bars/s`, `eventsPerSec = 328,290 events/s` (`5,020` pre-Vault sessions, `240,000` anchored events, `20` Vault-excluded dates, pinned checksum `01b356d3`)
|
||||
|
|
|
|||
|
|
@ -10,8 +10,11 @@
|
|||
".": "./src/index.ts",
|
||||
"./dataset-contracts": "./src/dataset-contracts.ts",
|
||||
"./datasets": "./src/datasets.ts",
|
||||
"./event-panel": "./src/event-panel.ts",
|
||||
"./market-data-store": "./src/market-data-store.ts",
|
||||
"./market-data-store-duckdb": "./src/market-data-store-duckdb.ts",
|
||||
"./results": "./src/results.ts",
|
||||
"./signal-panel": "./src/signal-panel.ts",
|
||||
"./signal-study": "./src/signal-study.ts",
|
||||
"./strategy-api": "./src/strategy-api.ts",
|
||||
"./trial-ledger": "./src/trial-ledger.ts"
|
||||
|
|
|
|||
230
libs/research/scripts/benchmark-event-panel.ts
Normal file
230
libs/research/scripts/benchmark-event-panel.ts
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
import {
|
||||
type EventObservation,
|
||||
type EventStudyExchangeCalendars,
|
||||
buildEventStudyInput,
|
||||
} from '../src/event-panel';
|
||||
import type { BarRecord } from '../src/market-data-store';
|
||||
|
||||
const SEED = 20261129;
|
||||
const SESSIONS = 5_040;
|
||||
const LISTINGS = 3_000;
|
||||
const EVENT_STRIDE_SESSIONS = 63; // 5040 / 63 = 80 filings/listing -> 240,000 total events
|
||||
const PRE_CUTOFF_SESSIONS = 5_020;
|
||||
|
||||
function createMulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function generateBusinessCalendar(count: number, startYear: number): {
|
||||
dates: string[];
|
||||
closeTs: Float64Array;
|
||||
afterCloseTs: Float64Array;
|
||||
} {
|
||||
const dates: string[] = new Array<string>(count);
|
||||
const closeTs = new Float64Array(count);
|
||||
const afterCloseTs = new Float64Array(count);
|
||||
let year = startYear;
|
||||
let month = 1;
|
||||
let day = 1;
|
||||
// 2006-01-01 was a Sunday (dow = 0)
|
||||
let dow = 0;
|
||||
let produced = 0;
|
||||
|
||||
while (produced < count) {
|
||||
if (dow !== 0 && dow !== 6) {
|
||||
const yyyy = String(year).padStart(4, '0');
|
||||
const mm = String(month).padStart(2, '0');
|
||||
const dd = String(day).padStart(2, '0');
|
||||
dates[produced] = `${yyyy}-${mm}-${dd}`;
|
||||
closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET
|
||||
afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET
|
||||
produced += 1;
|
||||
}
|
||||
|
||||
dow = (dow + 1) % 7;
|
||||
day += 1;
|
||||
const baseDays = DAYS_IN_MONTH[month] ?? 31;
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
|
||||
if (day > maxDay) {
|
||||
day = 1;
|
||||
month += 1;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { dates, closeTs, afterCloseTs };
|
||||
}
|
||||
|
||||
function fnv1aByte(hash: number, byte: number): number {
|
||||
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
|
||||
function fnv1aUint32(hash: number, value: number): number {
|
||||
const v = value >>> 0;
|
||||
let h = fnv1aByte(hash, v & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 8) & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 16) & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 24) & 0xff);
|
||||
return h;
|
||||
}
|
||||
|
||||
function fnv1aBytes(hash: number, bytes: Uint8Array): number {
|
||||
let h = hash >>> 0;
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
const rng = createMulberry32(SEED);
|
||||
const calendar = generateBusinessCalendar(SESSIONS, 2006);
|
||||
const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string;
|
||||
|
||||
const totalBars = SESSIONS * LISTINGS;
|
||||
const bars: BarRecord[] = new Array<BarRecord>(totalBars);
|
||||
const eventsPerListing = Math.ceil(SESSIONS / EVENT_STRIDE_SESSIONS);
|
||||
const totalEvents = LISTINGS * eventsPerListing;
|
||||
const events: EventObservation[] = new Array<EventObservation>(totalEvents);
|
||||
|
||||
let barIdx = 0;
|
||||
let evIdx = 0;
|
||||
|
||||
for (let l = 0; l < LISTINGS; l += 1) {
|
||||
const listingId = l + 1;
|
||||
const subtype = l % 2 === 0 ? '10-q' : 'interim_financial_statements';
|
||||
let price = 10 + (l % 200) * 0.5;
|
||||
for (let t = 0; t < SESSIONS; t += 1) {
|
||||
const ts = calendar.closeTs[t] as number;
|
||||
price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02));
|
||||
bars[barIdx++] = {
|
||||
listingId,
|
||||
ts,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 10_000,
|
||||
vwap: price,
|
||||
knownAt: ts,
|
||||
};
|
||||
if (t % EVENT_STRIDE_SESSIONS === 0) {
|
||||
events[evIdx++] = {
|
||||
listingId,
|
||||
knownAt: calendar.afterCloseTs[t] as number,
|
||||
kind: 'filing',
|
||||
subtype,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const sessionCloses = calendar.dates.map((date, idx) => ({
|
||||
date,
|
||||
closeTs: calendar.closeTs[idx] as number,
|
||||
}));
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (let l = 0; l < LISTINGS; l += 1) {
|
||||
listingCalendarId.set(l + 1, l % 2 === 0 ? 'XNYS' : 'XTSE');
|
||||
}
|
||||
const exchangeCalendars: EventStudyExchangeCalendars = {
|
||||
calendars: new Map([
|
||||
['XNYS', sessionCloses],
|
||||
['XTSE', sessionCloses],
|
||||
]),
|
||||
listingCalendarId,
|
||||
};
|
||||
|
||||
// Timed section: pure buildEventStudyInput execution (no fixture generation or checksum).
|
||||
const started = performance.now();
|
||||
const result = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars,
|
||||
});
|
||||
const elapsedMs = performance.now() - started;
|
||||
|
||||
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, returns, and events.
|
||||
let checksum = 0x811c9dc5;
|
||||
checksum = fnv1aUint32(checksum, result.input.sessionDates.length);
|
||||
checksum = fnv1aUint32(checksum, result.input.entityReturns.size);
|
||||
checksum = fnv1aUint32(checksum, result.input.events.length);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedEvents);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedUnknownListing);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedAfterLastSession);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingCalendarSession);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateEvents);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.nonPositiveCloseReturns);
|
||||
|
||||
if (result.input.benchmarkReturns !== undefined) {
|
||||
const bench = result.input.benchmarkReturns as Float64Array;
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(bench.buffer, bench.byteOffset, bench.byteLength));
|
||||
}
|
||||
|
||||
for (const [entityId, series] of result.input.entityReturns) {
|
||||
checksum = fnv1aUint32(checksum, Number(entityId));
|
||||
const arr = series as Float64Array;
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength));
|
||||
}
|
||||
|
||||
for (let i = 0; i < result.input.events.length; i += 1) {
|
||||
const ev = result.input.events[i];
|
||||
if (ev === undefined) {
|
||||
continue;
|
||||
}
|
||||
checksum = fnv1aUint32(checksum, ev.dayIndex);
|
||||
checksum = fnv1aUint32(checksum, Number(ev.entityId));
|
||||
}
|
||||
|
||||
const checksumHex = checksum.toString(16).padStart(8, '0');
|
||||
|
||||
const EXPECTED_CHECKSUM = '01b356d3';
|
||||
if (checksumHex !== EXPECTED_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
|
||||
);
|
||||
}
|
||||
|
||||
const elapsedSec = elapsedMs / 1000;
|
||||
const barsPerSec = Math.round(totalBars / elapsedSec);
|
||||
const eventsPerSec = Math.round(totalEvents / elapsedSec);
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
seed: SEED,
|
||||
sessions: SESSIONS,
|
||||
listings: LISTINGS,
|
||||
vaultCutoffDate,
|
||||
inputBars: totalBars,
|
||||
inputEvents: totalEvents,
|
||||
sessionDates: result.input.sessionDates.length,
|
||||
anchoredEvents: result.input.events.length,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
barsPerSec,
|
||||
eventsPerSec,
|
||||
diagnostics: result.diagnostics,
|
||||
checksum: checksumHex,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
352
libs/research/scripts/benchmark-market-data-store-duckdb.ts
Normal file
352
libs/research/scripts/benchmark-market-data-store-duckdb.ts
Normal file
|
|
@ -0,0 +1,352 @@
|
|||
import {
|
||||
type AdjFactorsSnapshotMetadata,
|
||||
BARS_ADJUSTMENTS,
|
||||
type BarsQuery,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type DuckDbPlanContext,
|
||||
EVENT_KINDS,
|
||||
type EventsQuery,
|
||||
type FxQuery,
|
||||
type PlannedDuckDbQuery,
|
||||
type ShortsAsOfQuery,
|
||||
UNIVERSE_REFS,
|
||||
type UniverseQuery,
|
||||
createDuckDbMarketDataStore,
|
||||
planBars1dQuery,
|
||||
planEventsQuery,
|
||||
planFx1dQuery,
|
||||
planShortsAsOfQuery,
|
||||
} from '../src/market-data-store-duckdb';
|
||||
import { type TableRow, applyVaultFence } from '../src/market-data-store';
|
||||
|
||||
const SEED = 20261129;
|
||||
const QUERY_COUNT = 120_000;
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const ADJ_PATH = `${CURATED_ROOT}/adj_factors/part.parquet`;
|
||||
const VAULT_CUTOFF_TS = Date.UTC(2026, 4, 28, 0, 0, 0, 0);
|
||||
const VAULT_CUTOFF_MICROS = VAULT_CUTOFF_TS * 1000;
|
||||
const DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
const BASE_CTX: DuckDbPlanContext = {
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
};
|
||||
|
||||
function createMulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
type WorkloadItem =
|
||||
| { readonly kind: 'bars'; readonly q: BarsQuery; readonly ctx: DuckDbPlanContext }
|
||||
| { readonly kind: 'events'; readonly q: EventsQuery }
|
||||
| { readonly kind: 'shorts'; readonly q: ShortsAsOfQuery }
|
||||
| { readonly kind: 'fx'; readonly q: FxQuery };
|
||||
|
||||
const rng = createMulberry32(SEED);
|
||||
const startBaseMs = Date.UTC(2016, 0, 1, 0, 0, 0, 0);
|
||||
const preCutoffSpanMs = VAULT_CUTOFF_TS - startBaseMs - 86_400_000;
|
||||
const postCutoffSpanMs = 180 * 86_400_000;
|
||||
|
||||
function randomDateOrIso(epochMs: number): string {
|
||||
const iso = new Date(epochMs).toISOString();
|
||||
return rng() < 0.5 ? iso.slice(0, 10) : iso;
|
||||
}
|
||||
|
||||
function randomListingIds(): number[] {
|
||||
const count = 1 + Math.floor(rng() * 4);
|
||||
const ids: number[] = new Array(count);
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
ids[i] = 1 + Math.floor(rng() * 50_000);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
function buildVerifiedSnapshotForBarsQuery(
|
||||
from: string,
|
||||
to: string,
|
||||
asOf: string | undefined
|
||||
): AdjFactorsSnapshotMetadata {
|
||||
const fenced = applyVaultFence(
|
||||
{ from, to, asOf, scope: 'vault_fenced' },
|
||||
{ vaultCutoffTs: VAULT_CUTOFF_TS }
|
||||
);
|
||||
const subMs = fenced.clampedAsOf || asOf === undefined || DATE_ONLY_RE.test(asOf) ? 999 : 0;
|
||||
const effectiveAsOfMicros = fenced.asOfMs * 1000 + subMs;
|
||||
return {
|
||||
path: ADJ_PATH,
|
||||
formatVersion: 1,
|
||||
snapshotKind: 'point_in_time_fenced',
|
||||
fence: {
|
||||
asOfMicros: effectiveAsOfMicros,
|
||||
vaultCutoffMicros: VAULT_CUTOFF_MICROS,
|
||||
},
|
||||
rowsWritten: 1000,
|
||||
snapshotChecksum: '0x024ec73a1afe7e6b',
|
||||
};
|
||||
}
|
||||
|
||||
const workload: WorkloadItem[] = new Array(QUERY_COUNT);
|
||||
for (let i = 0; i < QUERY_COUNT; i += 1) {
|
||||
const fromMs = startBaseMs + Math.floor(rng() * preCutoffSpanMs);
|
||||
const toMs = fromMs + Math.floor(rng() * (VAULT_CUTOFF_TS - fromMs + postCutoffSpanMs));
|
||||
const asOfMs =
|
||||
rng() < 0.35
|
||||
? undefined
|
||||
: startBaseMs + Math.floor(rng() * (VAULT_CUTOFF_TS - startBaseMs + postCutoffSpanMs));
|
||||
|
||||
const from = randomDateOrIso(fromMs);
|
||||
const to = randomDateOrIso(toMs);
|
||||
const asOf = asOfMs === undefined ? undefined : randomDateOrIso(asOfMs);
|
||||
|
||||
const slot = i % 7;
|
||||
if (slot < 3) {
|
||||
const adjustment = BARS_ADJUSTMENTS[slot] ?? 'raw';
|
||||
const ctx: DuckDbPlanContext =
|
||||
adjustment === 'raw'
|
||||
? BASE_CTX
|
||||
: {
|
||||
...BASE_CTX,
|
||||
adjFactorsSnapshot: buildVerifiedSnapshotForBarsQuery(from, to, asOf),
|
||||
};
|
||||
workload[i] = {
|
||||
kind: 'bars',
|
||||
q: {
|
||||
listingIds: randomListingIds(),
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
adjustment,
|
||||
asOf,
|
||||
},
|
||||
ctx,
|
||||
};
|
||||
} else if (slot === 3 || slot === 4) {
|
||||
const kindA = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'filing';
|
||||
const kindB = EVENT_KINDS[Math.floor(rng() * EVENT_KINDS.length)] ?? 'earnings';
|
||||
workload[i] = {
|
||||
kind: 'events',
|
||||
q: {
|
||||
kinds: slot === 3 ? [kindA] : [kindA, kindB],
|
||||
listingIds: slot === 3 ? randomListingIds() : undefined,
|
||||
from,
|
||||
to,
|
||||
asOf,
|
||||
},
|
||||
};
|
||||
} else if (slot === 5) {
|
||||
workload[i] = {
|
||||
kind: 'shorts',
|
||||
q: {
|
||||
listingIds: randomListingIds(),
|
||||
from,
|
||||
to,
|
||||
asOf,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
workload[i] = {
|
||||
kind: 'fx',
|
||||
q: {
|
||||
pair: 'USD.CAD',
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function planWorkloadItem(item: WorkloadItem): PlannedDuckDbQuery {
|
||||
switch (item.kind) {
|
||||
case 'bars':
|
||||
return planBars1dQuery(item.q, item.ctx);
|
||||
case 'events':
|
||||
return planEventsQuery(item.q, BASE_CTX);
|
||||
case 'shorts':
|
||||
return planShortsAsOfQuery(item.q, BASE_CTX);
|
||||
case 'fx':
|
||||
return planFx1dQuery(item.q, BASE_CTX);
|
||||
}
|
||||
}
|
||||
|
||||
function fnv1aByte(hash: number, byte: number): number {
|
||||
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
|
||||
function fnv1aString(hash: number, str: string): number {
|
||||
let h = fnv1aByte(hash, str.length & 0xff);
|
||||
h = fnv1aByte(h, (str.length >>> 8) & 0xff);
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
const code = str.charCodeAt(i);
|
||||
h = fnv1aByte(h, code & 0xff);
|
||||
if (code > 0xff) {
|
||||
h = fnv1aByte(h, (code >>> 8) & 0xff);
|
||||
}
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
function fnv1aParam(hash: number, param: DuckDbParam): number {
|
||||
if (param === null) {
|
||||
return fnv1aByte(hash, 0x00);
|
||||
}
|
||||
if (typeof param === 'string') {
|
||||
return fnv1aString(fnv1aByte(hash, 0x01), param);
|
||||
}
|
||||
if (typeof param === 'number') {
|
||||
return fnv1aString(fnv1aByte(hash, 0x02), String(param));
|
||||
}
|
||||
return fnv1aByte(fnv1aByte(hash, 0x03), param ? 1 : 0);
|
||||
}
|
||||
|
||||
// Timed section: pure query planning only (no checksum hashing overhead).
|
||||
let totalParams = 0;
|
||||
const started = performance.now();
|
||||
for (const item of workload) {
|
||||
const planned = planWorkloadItem(item);
|
||||
totalParams += planned.params.length;
|
||||
}
|
||||
const elapsedMs = performance.now() - started;
|
||||
const queriesPerSec = Math.round(QUERY_COUNT / (elapsedMs / 1000));
|
||||
|
||||
// Untimed verification pass: hash full SQL text and ordered parameter values for all queries.
|
||||
let checksum = 0x811c9dc5;
|
||||
for (const item of workload) {
|
||||
const planned = planWorkloadItem(item);
|
||||
checksum = fnv1aString(checksum, planned.sql);
|
||||
checksum = fnv1aByte(checksum, planned.params.length);
|
||||
for (const param of planned.params) {
|
||||
checksum = fnv1aParam(checksum, param);
|
||||
}
|
||||
}
|
||||
const checksumHex = checksum.toString(16).padStart(8, '0');
|
||||
|
||||
const EXPECTED_CHECKSUM = '8606c98c';
|
||||
if (checksumHex !== EXPECTED_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
|
||||
);
|
||||
}
|
||||
|
||||
// Fixed-seed universe benchmark: plan + adapter mapping for 15,000 listing IDs via in-memory executor.
|
||||
const UNIVERSE_LISTING_COUNT = 15_000;
|
||||
const UNIVERSE_CALL_COUNT = 200;
|
||||
|
||||
async function runUniverseBenchmark() {
|
||||
const universeRng = createMulberry32(SEED);
|
||||
const listingRows: TableRow[] = new Array(UNIVERSE_LISTING_COUNT);
|
||||
let nextListingId = 1;
|
||||
for (let i = 0; i < UNIVERSE_LISTING_COUNT; i += 1) {
|
||||
listingRows[i] = { listing_id: nextListingId };
|
||||
nextListingId += 1 + Math.floor(universeRng() * 5);
|
||||
}
|
||||
|
||||
const universeQueries: UniverseQuery[] = new Array(UNIVERSE_CALL_COUNT);
|
||||
for (let i = 0; i < UNIVERSE_CALL_COUNT; i += 1) {
|
||||
const ref = UNIVERSE_REFS[i % UNIVERSE_REFS.length] ?? 'US_EQ';
|
||||
const dateMs = startBaseMs + Math.floor(universeRng() * preCutoffSpanMs);
|
||||
const date = new Date(dateMs).toISOString().slice(0, 10);
|
||||
universeQueries[i] = { ref, date };
|
||||
}
|
||||
|
||||
const timedExecutor: DuckDbExecutor = {
|
||||
async run(): Promise<void> {},
|
||||
async query(): Promise<readonly TableRow[]> {
|
||||
return listingRows;
|
||||
},
|
||||
};
|
||||
const timedStore = createDuckDbMarketDataStore({
|
||||
executor: timedExecutor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
});
|
||||
|
||||
// Timed section: universe query planning + adapter row validation/mapping.
|
||||
let totalListingsMapped = 0;
|
||||
const uStarted = performance.now();
|
||||
for (const q of universeQueries) {
|
||||
const ids = await timedStore.universe(q);
|
||||
totalListingsMapped += ids.length;
|
||||
}
|
||||
const uElapsedMs = performance.now() - uStarted;
|
||||
const uCallsPerSec = Math.round(UNIVERSE_CALL_COUNT / (uElapsedMs / 1000));
|
||||
const uRowsPerSec = Math.round(totalListingsMapped / (uElapsedMs / 1000));
|
||||
|
||||
// Untimed verification pass: hash SQL, ordered params, and mapped listing IDs.
|
||||
let uChecksum = 0x811c9dc5;
|
||||
const verifyExecutor: DuckDbExecutor = {
|
||||
async run(): Promise<void> {},
|
||||
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
||||
uChecksum = fnv1aString(uChecksum, sql);
|
||||
uChecksum = fnv1aByte(uChecksum, params.length);
|
||||
for (const param of params) {
|
||||
uChecksum = fnv1aParam(uChecksum, param);
|
||||
}
|
||||
return listingRows;
|
||||
},
|
||||
};
|
||||
const verifyStore = createDuckDbMarketDataStore({
|
||||
executor: verifyExecutor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: VAULT_CUTOFF_TS,
|
||||
});
|
||||
|
||||
for (const q of universeQueries) {
|
||||
const ids = await verifyStore.universe(q);
|
||||
for (let i = 0; i < ids.length; i += 1) {
|
||||
const id = ids[i] ?? 0;
|
||||
uChecksum = fnv1aByte(uChecksum, id & 0xff);
|
||||
uChecksum = fnv1aByte(uChecksum, (id >>> 8) & 0xff);
|
||||
uChecksum = fnv1aByte(uChecksum, (id >>> 16) & 0xff);
|
||||
uChecksum = fnv1aByte(uChecksum, (id >>> 24) & 0xff);
|
||||
}
|
||||
}
|
||||
const uChecksumHex = uChecksum.toString(16).padStart(8, '0');
|
||||
const EXPECTED_UNIVERSE_CHECKSUM = 'ef5f1136';
|
||||
if (uChecksumHex !== EXPECTED_UNIVERSE_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Universe benchmark checksum mismatch: expected ${EXPECTED_UNIVERSE_CHECKSUM}, got ${uChecksumHex}.`
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
seed: SEED,
|
||||
calls: UNIVERSE_CALL_COUNT,
|
||||
listingsPerCall: UNIVERSE_LISTING_COUNT,
|
||||
totalListingsMapped,
|
||||
elapsedMs: Number(uElapsedMs.toFixed(2)),
|
||||
callsPerSec: uCallsPerSec,
|
||||
rowsPerSec: uRowsPerSec,
|
||||
checksum: uChecksumHex,
|
||||
};
|
||||
}
|
||||
|
||||
runUniverseBenchmark()
|
||||
.then((universe) => {
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
seed: SEED,
|
||||
queries: QUERY_COUNT,
|
||||
totalParams,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
queriesPerSec,
|
||||
checksum: checksumHex,
|
||||
universe,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
console.error(err);
|
||||
process.exitCode = 1;
|
||||
});
|
||||
196
libs/research/scripts/benchmark-signal-panel.ts
Normal file
196
libs/research/scripts/benchmark-signal-panel.ts
Normal file
|
|
@ -0,0 +1,196 @@
|
|||
import type { BarRecord } from '../src/market-data-store';
|
||||
import { type SignalObservation, buildForwardReturnPanel } from '../src/signal-panel';
|
||||
|
||||
const SEED = 20261129;
|
||||
const SESSIONS = 5_040;
|
||||
const LISTINGS = 3_000;
|
||||
const SIGNAL_STRIDE_SESSIONS = 21;
|
||||
const HORIZON_SESSIONS = 5;
|
||||
const PRE_CUTOFF_SESSIONS = 5_020;
|
||||
|
||||
function createMulberry32(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function isLeapYear(year: number): boolean {
|
||||
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
|
||||
}
|
||||
|
||||
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
|
||||
|
||||
function generateBusinessCalendar(count: number, startYear: number): {
|
||||
dates: string[];
|
||||
closeTs: Float64Array;
|
||||
afterCloseTs: Float64Array;
|
||||
} {
|
||||
const dates: string[] = new Array<string>(count);
|
||||
const closeTs = new Float64Array(count);
|
||||
const afterCloseTs = new Float64Array(count);
|
||||
let year = startYear;
|
||||
let month = 1;
|
||||
let day = 1;
|
||||
// 2006-01-01 was a Sunday (dow = 0)
|
||||
let dow = 0;
|
||||
let produced = 0;
|
||||
|
||||
while (produced < count) {
|
||||
if (dow !== 0 && dow !== 6) {
|
||||
const yyyy = String(year).padStart(4, '0');
|
||||
const mm = String(month).padStart(2, '0');
|
||||
const dd = String(day).padStart(2, '0');
|
||||
dates[produced] = `${yyyy}-${mm}-${dd}`;
|
||||
closeTs[produced] = Date.UTC(year, month - 1, day, 21, 0, 0, 0); // 16:00 ET
|
||||
afterCloseTs[produced] = Date.UTC(year, month - 1, day, 22, 0, 0, 0); // 17:00 ET
|
||||
produced += 1;
|
||||
}
|
||||
|
||||
dow = (dow + 1) % 7;
|
||||
day += 1;
|
||||
const baseDays = DAYS_IN_MONTH[month] ?? 31;
|
||||
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
|
||||
if (day > maxDay) {
|
||||
day = 1;
|
||||
month += 1;
|
||||
if (month > 12) {
|
||||
month = 1;
|
||||
year += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { dates, closeTs, afterCloseTs };
|
||||
}
|
||||
|
||||
function fnv1aByte(hash: number, byte: number): number {
|
||||
return Math.imul((hash ^ (byte & 0xff)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
|
||||
function fnv1aUint32(hash: number, value: number): number {
|
||||
const v = value >>> 0;
|
||||
let h = fnv1aByte(hash, v & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 8) & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 16) & 0xff);
|
||||
h = fnv1aByte(h, (v >>> 24) & 0xff);
|
||||
return h;
|
||||
}
|
||||
|
||||
function fnv1aBytes(hash: number, bytes: Uint8Array): number {
|
||||
let h = hash >>> 0;
|
||||
for (let i = 0; i < bytes.length; i += 1) {
|
||||
h = Math.imul((h ^ (bytes[i] as number)) >>> 0, 0x01000193) >>> 0;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
const rng = createMulberry32(SEED);
|
||||
const calendar = generateBusinessCalendar(SESSIONS, 2006);
|
||||
const vaultCutoffDate = calendar.dates[PRE_CUTOFF_SESSIONS] as string;
|
||||
|
||||
const totalBars = SESSIONS * LISTINGS;
|
||||
const bars: BarRecord[] = new Array<BarRecord>(totalBars);
|
||||
const signalsPerListing = Math.ceil(SESSIONS / SIGNAL_STRIDE_SESSIONS);
|
||||
const signals: SignalObservation[] = new Array<SignalObservation>(LISTINGS * signalsPerListing);
|
||||
|
||||
let barIdx = 0;
|
||||
let sigIdx = 0;
|
||||
|
||||
for (let l = 0; l < LISTINGS; l += 1) {
|
||||
const listingId = l + 1;
|
||||
let price = 10 + (l % 200) * 0.5;
|
||||
for (let t = 0; t < SESSIONS; t += 1) {
|
||||
const ts = calendar.closeTs[t] as number;
|
||||
price = Math.max(1, price * (1 + (rng() - 0.4995) * 0.02));
|
||||
bars[barIdx++] = {
|
||||
listingId,
|
||||
ts,
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 10_000,
|
||||
vwap: price,
|
||||
knownAt: ts,
|
||||
};
|
||||
if (t % SIGNAL_STRIDE_SESSIONS === 0) {
|
||||
signals[sigIdx++] = {
|
||||
listingId,
|
||||
knownAt: calendar.afterCloseTs[t] as number,
|
||||
value: rng() * 2 - 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Timed section: pure buildForwardReturnPanel execution (no fixture generation or checksum).
|
||||
const started = performance.now();
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: HORIZON_SESSIONS,
|
||||
vaultCutoffDate,
|
||||
});
|
||||
const elapsedMs = performance.now() - started;
|
||||
|
||||
// Untimed verification pass: FNV-1a 32-bit checksum over lengths, diagnostics, and typed-array bytes.
|
||||
let checksum = 0x811c9dc5;
|
||||
checksum = fnv1aUint32(checksum, result.panel.length);
|
||||
checksum = fnv1aUint32(checksum, result.sessionDates.length);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.vaultExcludedDates);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedNoSignal);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedStaleSignal);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedMissingForwardBar);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.droppedNonPositiveClose);
|
||||
checksum = fnv1aUint32(checksum, result.diagnostics.duplicateBars);
|
||||
|
||||
let emittedObservations = 0;
|
||||
for (let i = 0; i < result.panel.length; i += 1) {
|
||||
const slice = result.panel[i];
|
||||
if (slice === undefined) {
|
||||
continue;
|
||||
}
|
||||
const ids = slice.ids as Int32Array;
|
||||
const sig = slice.signal as Float64Array;
|
||||
const ret = slice.forwardReturn as Float64Array;
|
||||
emittedObservations += ids.length;
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(ids.buffer, ids.byteOffset, ids.byteLength));
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(sig.buffer, sig.byteOffset, sig.byteLength));
|
||||
checksum = fnv1aBytes(checksum, new Uint8Array(ret.buffer, ret.byteOffset, ret.byteLength));
|
||||
}
|
||||
const checksumHex = checksum.toString(16).padStart(8, '0');
|
||||
|
||||
const EXPECTED_CHECKSUM = 'f0f28bdf';
|
||||
if (checksumHex !== EXPECTED_CHECKSUM) {
|
||||
throw new Error(
|
||||
`Benchmark checksum mismatch: expected ${EXPECTED_CHECKSUM}, got ${checksumHex}.`
|
||||
);
|
||||
}
|
||||
|
||||
const rowsPerSec = Math.round(totalBars / (elapsedMs / 1000));
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
seed: SEED,
|
||||
sessions: SESSIONS,
|
||||
listings: LISTINGS,
|
||||
horizonSessions: HORIZON_SESSIONS,
|
||||
vaultCutoffDate,
|
||||
inputBars: totalBars,
|
||||
inputSignals: signals.length,
|
||||
panelDates: result.panel.length,
|
||||
emittedObservations,
|
||||
elapsedMs: Number(elapsedMs.toFixed(2)),
|
||||
rowsPerSec,
|
||||
diagnostics: result.diagnostics,
|
||||
checksum: checksumHex,
|
||||
},
|
||||
null,
|
||||
2
|
||||
)
|
||||
);
|
||||
1069
libs/research/src/event-panel.ts
Normal file
1069
libs/research/src/event-panel.ts
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -1,5 +1,8 @@
|
|||
// The default entrypoint is browser safe; server validation is an explicit subpath.
|
||||
export * from './dataset-contracts';
|
||||
export * from './event-panel';
|
||||
export * from './market-data-store';
|
||||
export * from './market-data-store-duckdb';
|
||||
export * from './signal-panel';
|
||||
export * from './signal-study';
|
||||
export * from './trial-ledger';
|
||||
|
|
|
|||
2056
libs/research/src/market-data-store-duckdb.ts
Normal file
2056
libs/research/src/market-data-store-duckdb.ts
Normal file
File diff suppressed because it is too large
Load diff
172
libs/research/src/panel-shared.ts
Normal file
172
libs/research/src/panel-shared.ts
Normal file
|
|
@ -0,0 +1,172 @@
|
|||
/**
|
||||
* Internal, browser-safe helpers shared by `signal-panel.ts` and `event-panel.ts`.
|
||||
*
|
||||
* Pure, synchronous, and dependency-free: zero `node:*` imports and zero bare
|
||||
* `process` access. Not exported from the package root.
|
||||
*/
|
||||
|
||||
import { MarketDataStoreValidationError, applyVaultFence } from './market-data-store';
|
||||
|
||||
export const INT32_MIN = -2_147_483_648;
|
||||
export const INT32_MAX = 2_147_483_647;
|
||||
export const MAX_ECMASCRIPT_EPOCH_MS = 8_640_000_000_000_000;
|
||||
export const MS_PER_DAY = 86_400_000;
|
||||
export const MAX_DIRECT_DAY_SPAN = 200_000;
|
||||
const DATE_ONLY_PATTERN = /^\d{4}-\d{2}-\d{2}$/;
|
||||
|
||||
export function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
export function normalizeZero(value: number): number {
|
||||
return value === 0 ? 0 : value;
|
||||
}
|
||||
|
||||
export function isValidInt32(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
value >= INT32_MIN &&
|
||||
value <= INT32_MAX
|
||||
);
|
||||
}
|
||||
|
||||
export function isValidEpochMs(value: unknown): value is number {
|
||||
return (
|
||||
typeof value === 'number' &&
|
||||
Number.isSafeInteger(value) &&
|
||||
Math.abs(value) <= MAX_ECMASCRIPT_EPOCH_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a strict `YYYY-MM-DD` calendar date string into an integer UTC day key
|
||||
* (`Math.floor(epochMs / MS_PER_DAY)`), delegating calendar validation to
|
||||
* `applyVaultFence`.
|
||||
*/
|
||||
export function parseCalendarDayKey(
|
||||
value: unknown,
|
||||
field: string,
|
||||
createError: (message: string, cause?: unknown) => Error
|
||||
): number {
|
||||
if (typeof value !== 'string' || !DATE_ONLY_PATTERN.test(value)) {
|
||||
throw createError(
|
||||
`Invalid "${field}": expected strict YYYY-MM-DD date string, got "${String(value)}".`
|
||||
);
|
||||
}
|
||||
try {
|
||||
const fenced = applyVaultFence(
|
||||
{ from: value, to: value, scope: 'vault_evaluation_only' },
|
||||
{ vaultCutoffTs: 0, vaultOperatorAuthorized: true }
|
||||
);
|
||||
return fenced.fromMs / MS_PER_DAY;
|
||||
} catch (error) {
|
||||
if (error instanceof MarketDataStoreValidationError) {
|
||||
throw createError(`Invalid "${field}": ${error.message}`, error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export function formatDayKeyUtc(dayKey: number): string {
|
||||
const date = new Date(dayKey * MS_PER_DAY);
|
||||
const year = String(date.getUTCFullYear()).padStart(4, '0');
|
||||
const month = String(date.getUTCMonth() + 1).padStart(2, '0');
|
||||
const day = String(date.getUTCDate()).padStart(2, '0');
|
||||
return `${year}-${month}-${day}`;
|
||||
}
|
||||
|
||||
export interface BarSortScratch {
|
||||
sessionIdx: Int32Array;
|
||||
ts: Float64Array;
|
||||
close: Float64Array;
|
||||
}
|
||||
|
||||
function ensureBarScratch(scratch: BarSortScratch, len: number): void {
|
||||
if (scratch.sessionIdx.length < len) {
|
||||
scratch.sessionIdx = new Int32Array(len);
|
||||
scratch.ts = new Float64Array(len);
|
||||
scratch.close = new Float64Array(len);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's bar slice `[start, end)` ordered
|
||||
* by `sessionIdx ASC`. Skips sorting when already non-decreasing.
|
||||
*/
|
||||
export function sortBarSliceBySession(
|
||||
sessionIdx: Int32Array,
|
||||
ts: Float64Array,
|
||||
close: Float64Array,
|
||||
start: number,
|
||||
end: number,
|
||||
scratch: BarSortScratch
|
||||
): void {
|
||||
const len = end - start;
|
||||
if (len <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted = true;
|
||||
for (let i = start + 1; i < end; i += 1) {
|
||||
if ((sessionIdx[i] as number) < (sessionIdx[i - 1] as number)) {
|
||||
sorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sorted) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureBarScratch(scratch, len);
|
||||
const tmpSession = scratch.sessionIdx;
|
||||
const tmpTs = scratch.ts;
|
||||
const tmpClose = scratch.close;
|
||||
|
||||
for (let width = 1; width < len; width *= 2) {
|
||||
for (let left = 0; left < len; left += 2 * width) {
|
||||
const mid = Math.min(left + width, len);
|
||||
const right = Math.min(left + 2 * width, len);
|
||||
let i = left;
|
||||
let j = mid;
|
||||
let k = left;
|
||||
|
||||
while (i < mid && j < right) {
|
||||
const si = sessionIdx[start + i] as number;
|
||||
const sj = sessionIdx[start + j] as number;
|
||||
if (si <= sj) {
|
||||
tmpSession[k] = si;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
} else {
|
||||
tmpSession[k] = sj;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
while (i < mid) {
|
||||
tmpSession[k] = sessionIdx[start + i] as number;
|
||||
tmpTs[k] = ts[start + i] as number;
|
||||
tmpClose[k] = close[start + i] as number;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
while (j < right) {
|
||||
tmpSession[k] = sessionIdx[start + j] as number;
|
||||
tmpTs[k] = ts[start + j] as number;
|
||||
tmpClose[k] = close[start + j] as number;
|
||||
j += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < len; k += 1) {
|
||||
sessionIdx[start + k] = tmpSession[k] as number;
|
||||
ts[start + k] = tmpTs[k] as number;
|
||||
close[start + k] = tmpClose[k] as number;
|
||||
}
|
||||
}
|
||||
}
|
||||
825
libs/research/src/signal-panel.ts
Normal file
825
libs/research/src/signal-panel.ts
Normal file
|
|
@ -0,0 +1,825 @@
|
|||
/**
|
||||
* Pure, dependency-free signal-panel builder that transforms `MarketDataStore`
|
||||
* daily bars and point-in-time signal observations into Vault-safe
|
||||
* `SignalCrossSection[]` panels for `analyzeSignal` (`design/MILESTONES.md` M1).
|
||||
*
|
||||
* Browser-safe and dependency-free: zero `node:*` imports, zero bare `process`
|
||||
* access, and no database drivers.
|
||||
*
|
||||
* UTC session-calendar derivation:
|
||||
* - Curated daily bars (`bars_1d.ts`) are stamped at `16:00 ET` (`20:00` or
|
||||
* `21:00 UTC`), so the UTC calendar date `Math.floor(bar.ts / 86_400_000)`
|
||||
* matches the exchange session date without timezone drift.
|
||||
*
|
||||
* Point-in-time (PIT) & Vault rules:
|
||||
* - For each listing and session `d`, only signal rows with
|
||||
* `knownAt <= bar.ts` are eligible; a signal known after the close takes
|
||||
* effect on the next trading session.
|
||||
* - No cross-section is emitted when either `d` or its forward session
|
||||
* `d + horizonSessions` reaches or exceeds `vaultCutoffDate`, and `bar.close`
|
||||
* is never accessed for any bar on or after `vaultCutoffDate`.
|
||||
*/
|
||||
|
||||
import type { SignalCrossSection } from '@stock-bot/calculations';
|
||||
import type { BarBatch, BarRecord, Table } from './market-data-store';
|
||||
import {
|
||||
type BarSortScratch,
|
||||
MAX_DIRECT_DAY_SPAN,
|
||||
MS_PER_DAY,
|
||||
formatDayKeyUtc,
|
||||
isPlainRecord,
|
||||
isValidEpochMs,
|
||||
isValidInt32,
|
||||
normalizeZero,
|
||||
parseCalendarDayKey,
|
||||
sortBarSliceBySession,
|
||||
} from './panel-shared';
|
||||
|
||||
export type SignalPanelErrorCode =
|
||||
| 'invalid_input'
|
||||
| 'invalid_horizon'
|
||||
| 'invalid_option'
|
||||
| 'invalid_date'
|
||||
| 'invalid_bar'
|
||||
| 'invalid_signal'
|
||||
| 'duplicate_bar';
|
||||
|
||||
export interface SignalPanelErrorOptions {
|
||||
readonly cause?: unknown;
|
||||
}
|
||||
|
||||
/** Typed validation and data-integrity error thrown by the signal-panel builder helpers. */
|
||||
export class SignalPanelError extends Error {
|
||||
override readonly name = 'SignalPanelError';
|
||||
readonly code: SignalPanelErrorCode;
|
||||
override readonly cause?: unknown;
|
||||
|
||||
constructor(code: SignalPanelErrorCode, message: string, options?: SignalPanelErrorOptions) {
|
||||
super(message, options?.cause !== undefined ? { cause: options.cause } : undefined);
|
||||
this.code = code;
|
||||
if (options?.cause !== undefined) {
|
||||
this.cause = options.cause;
|
||||
}
|
||||
Object.setPrototypeOf(this, new.target.prototype);
|
||||
}
|
||||
}
|
||||
|
||||
export const SHORTS_SIGNAL_FIELDS = ['shares_short', 'net_change', 'pct_float'] as const;
|
||||
const SHORTS_SIGNAL_FIELD_SET: ReadonlySet<string> = new Set<string>(SHORTS_SIGNAL_FIELDS);
|
||||
|
||||
export type ShortsSignalField = (typeof SHORTS_SIGNAL_FIELDS)[number];
|
||||
|
||||
/** Point-in-time signal observation aligned to a listing ID and UTC epoch-ms `knownAt`. */
|
||||
export interface SignalObservation {
|
||||
readonly listingId: number;
|
||||
readonly knownAt: number;
|
||||
readonly value: number;
|
||||
}
|
||||
|
||||
/** Input contract for {@link buildForwardReturnPanel}. */
|
||||
export interface BuildForwardReturnPanelInput {
|
||||
readonly bars: readonly BarRecord[];
|
||||
readonly signals: readonly SignalObservation[];
|
||||
readonly horizonSessions: number;
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly maxSignalAgeSessions?: number;
|
||||
}
|
||||
|
||||
/** Per-run diagnostic counters reported by {@link buildForwardReturnPanel}. */
|
||||
export interface SignalPanelDiagnostics {
|
||||
readonly vaultExcludedDates: number;
|
||||
readonly droppedNoSignal: number;
|
||||
readonly droppedStaleSignal: number;
|
||||
readonly droppedMissingForwardBar: number;
|
||||
readonly droppedNonPositiveClose: number;
|
||||
readonly duplicateBars: number;
|
||||
}
|
||||
|
||||
/** Output contract returned by {@link buildForwardReturnPanel}. */
|
||||
export interface BuildForwardReturnPanelResult {
|
||||
readonly panel: SignalCrossSection[];
|
||||
readonly sessionDates: string[];
|
||||
readonly diagnostics: SignalPanelDiagnostics;
|
||||
}
|
||||
|
||||
function parseStrictCalendarDayKey(value: unknown, field: string): number {
|
||||
return parseCalendarDayKey(value, field, (message, cause) =>
|
||||
new SignalPanelError('invalid_date', message, cause !== undefined ? { cause } : undefined)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drains an `AsyncIterable<BarBatch>` (such as `MarketDataStore.bars`) into a
|
||||
* flat `BarRecord[]` without mutating any yielded batch or overflowing the call
|
||||
* stack on large batches.
|
||||
*/
|
||||
export async function collectBars(iterable: AsyncIterable<BarBatch>): Promise<BarRecord[]> {
|
||||
if (
|
||||
iterable === null ||
|
||||
(typeof iterable !== 'object' && typeof iterable !== 'function') ||
|
||||
typeof (iterable as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] !== 'function'
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'Expected an AsyncIterable<BarBatch> with a [Symbol.asyncIterator] method.'
|
||||
);
|
||||
}
|
||||
|
||||
const out: BarRecord[] = [];
|
||||
let batchIndex = 0;
|
||||
for await (const batch of iterable) {
|
||||
if (!isPlainRecord(batch) || !Array.isArray(batch.rows)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_bar',
|
||||
`Expected batch[${batchIndex}] to be an object with a rows array.`
|
||||
);
|
||||
}
|
||||
const rows = batch.rows;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
out.push(rows[i] as BarRecord);
|
||||
}
|
||||
batchIndex += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Maps a `MarketDataStore.shortsAsOf` `Table` into point-in-time
|
||||
* {@link SignalObservation} rows for the chosen field, skipping `null` cells
|
||||
* and rejecting malformed rows with {@link SignalPanelError}.
|
||||
*/
|
||||
export function shortsTableToSignalRows(
|
||||
table: Table,
|
||||
field: ShortsSignalField
|
||||
): SignalObservation[] {
|
||||
if (typeof field !== 'string' || !SHORTS_SIGNAL_FIELD_SET.has(field)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
`Invalid shorts signal field "${String(field)}": expected one of ${SHORTS_SIGNAL_FIELDS.join(', ')}.`
|
||||
);
|
||||
}
|
||||
if (!isPlainRecord(table) || !Array.isArray(table.columns) || !Array.isArray(table.rows)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'Expected a Table object with array columns and rows.'
|
||||
);
|
||||
}
|
||||
|
||||
let hasListingIdCol = false;
|
||||
let hasKnownAtCol = false;
|
||||
let hasFieldCol = false;
|
||||
for (let i = 0; i < table.columns.length; i += 1) {
|
||||
const col: unknown = table.columns[i];
|
||||
if (col === 'listing_id') {
|
||||
hasListingIdCol = true;
|
||||
} else if (col === 'known_at') {
|
||||
hasKnownAtCol = true;
|
||||
} else if (col === field) {
|
||||
hasFieldCol = true;
|
||||
}
|
||||
}
|
||||
if (!hasListingIdCol || !hasKnownAtCol || !hasFieldCol) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
`Shorts table is missing required column(s): expected "listing_id", "known_at", and "${field}".`
|
||||
);
|
||||
}
|
||||
|
||||
const out: SignalObservation[] = [];
|
||||
const rows = table.rows;
|
||||
for (let i = 0; i < rows.length; i += 1) {
|
||||
const row: unknown = rows[i];
|
||||
if (!isPlainRecord(row)) {
|
||||
throw new SignalPanelError('invalid_signal', `Shorts table row[${i}] must be a plain object.`);
|
||||
}
|
||||
if (
|
||||
!Object.prototype.hasOwnProperty.call(row, 'listing_id') ||
|
||||
!Object.prototype.hasOwnProperty.call(row, 'known_at') ||
|
||||
!Object.prototype.hasOwnProperty.call(row, field)
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Shorts table row[${i}] is missing required key "listing_id", "known_at", or "${field}".`
|
||||
);
|
||||
}
|
||||
|
||||
const listingId = row.listing_id;
|
||||
if (!isValidInt32(listingId)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid listing_id in shorts table row[${i}]: ${String(listingId)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const knownAt = row.known_at;
|
||||
if (!isValidEpochMs(knownAt)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid known_at in shorts table row[${i}]: ${String(knownAt)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const rawValue = row[field];
|
||||
if (rawValue === null) {
|
||||
continue;
|
||||
}
|
||||
if (typeof rawValue !== 'number' || !Number.isFinite(rawValue)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid "${field}" value in shorts table row[${i}]: ${String(rawValue)}.`
|
||||
);
|
||||
}
|
||||
|
||||
out.push({
|
||||
listingId: normalizeZero(listingId),
|
||||
knownAt: normalizeZero(knownAt),
|
||||
value: normalizeZero(rawValue),
|
||||
});
|
||||
}
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
interface SignalSortScratch {
|
||||
knownAt: Float64Array;
|
||||
value: Float64Array;
|
||||
}
|
||||
|
||||
function ensureSignalScratch(scratch: SignalSortScratch, len: number): void {
|
||||
if (scratch.knownAt.length < len) {
|
||||
scratch.knownAt = new Float64Array(len);
|
||||
scratch.value = new Float64Array(len);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterative bottom-up mergesort for a listing's signal slice `[start, end)`
|
||||
* ordered by `(knownAt ASC, value ASC)` for deterministic tie-breaking.
|
||||
* Skips sorting when already sorted.
|
||||
*/
|
||||
function sortSignalSlice(
|
||||
knownAt: Float64Array,
|
||||
value: Float64Array,
|
||||
start: number,
|
||||
end: number,
|
||||
scratch: SignalSortScratch
|
||||
): void {
|
||||
const len = end - start;
|
||||
if (len <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sorted = true;
|
||||
for (let i = start + 1; i < end; i += 1) {
|
||||
const ka = knownAt[i] as number;
|
||||
const prevKa = knownAt[i - 1] as number;
|
||||
if (ka < prevKa || (ka === prevKa && (value[i] as number) < (value[i - 1] as number))) {
|
||||
sorted = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (sorted) {
|
||||
return;
|
||||
}
|
||||
|
||||
ensureSignalScratch(scratch, len);
|
||||
const tmpKnownAt = scratch.knownAt;
|
||||
const tmpValue = scratch.value;
|
||||
|
||||
for (let width = 1; width < len; width *= 2) {
|
||||
for (let left = 0; left < len; left += 2 * width) {
|
||||
const mid = Math.min(left + width, len);
|
||||
const right = Math.min(left + 2 * width, len);
|
||||
let i = left;
|
||||
let j = mid;
|
||||
let k = left;
|
||||
|
||||
while (i < mid && j < right) {
|
||||
const ki = knownAt[start + i] as number;
|
||||
const kj = knownAt[start + j] as number;
|
||||
const vi = value[start + i] as number;
|
||||
const vj = value[start + j] as number;
|
||||
if (ki < kj || (ki === kj && vi <= vj)) {
|
||||
tmpKnownAt[k] = ki;
|
||||
tmpValue[k] = vi;
|
||||
i += 1;
|
||||
} else {
|
||||
tmpKnownAt[k] = kj;
|
||||
tmpValue[k] = vj;
|
||||
j += 1;
|
||||
}
|
||||
k += 1;
|
||||
}
|
||||
while (i < mid) {
|
||||
tmpKnownAt[k] = knownAt[start + i] as number;
|
||||
tmpValue[k] = value[start + i] as number;
|
||||
i += 1;
|
||||
k += 1;
|
||||
}
|
||||
while (j < right) {
|
||||
tmpKnownAt[k] = knownAt[start + j] as number;
|
||||
tmpValue[k] = value[start + j] as number;
|
||||
j += 1;
|
||||
k += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (let k = 0; k < len; k += 1) {
|
||||
knownAt[start + k] = tmpKnownAt[k] as number;
|
||||
value[start + k] = tmpValue[k] as number;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure, synchronous forward-return signal-panel builder.
|
||||
*
|
||||
* Joins daily bars (caller-supplied `'total'`-adjusted closes in any order)
|
||||
* with point-in-time signal observations (`knownAt <= bar.ts`), enforces the
|
||||
* exclusive `vaultCutoffDate` fence across both the signal date `d` and the
|
||||
* forward session `d + horizonSessions` without ever reading post-cutoff
|
||||
* closes, and emits deterministic `SignalCrossSection[]` slices ready for
|
||||
* `analyzeSignal`.
|
||||
*/
|
||||
export function buildForwardReturnPanel(
|
||||
input: BuildForwardReturnPanelInput
|
||||
): BuildForwardReturnPanelResult {
|
||||
if (!isPlainRecord(input)) {
|
||||
throw new SignalPanelError('invalid_input', 'Input must be a non-null plain object.');
|
||||
}
|
||||
|
||||
const horizonSessions = input.horizonSessions;
|
||||
if (
|
||||
typeof horizonSessions !== 'number' ||
|
||||
!Number.isSafeInteger(horizonSessions) ||
|
||||
horizonSessions < 1
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_horizon',
|
||||
`Invalid horizonSessions "${String(horizonSessions)}": expected a safe integer >= 1.`
|
||||
);
|
||||
}
|
||||
|
||||
const vaultCutoffDayKey = parseStrictCalendarDayKey(input.vaultCutoffDate, 'vaultCutoffDate');
|
||||
|
||||
const maxSignalAgeSessions = input.maxSignalAgeSessions;
|
||||
if (
|
||||
maxSignalAgeSessions !== undefined &&
|
||||
(typeof maxSignalAgeSessions !== 'number' ||
|
||||
!Number.isSafeInteger(maxSignalAgeSessions) ||
|
||||
maxSignalAgeSessions < 0)
|
||||
) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_option',
|
||||
`Invalid maxSignalAgeSessions "${String(maxSignalAgeSessions)}": expected a safe integer >= 0.`
|
||||
);
|
||||
}
|
||||
|
||||
if (!Array.isArray(input.bars)) {
|
||||
throw new SignalPanelError('invalid_input', 'input.bars must be an array of BarRecord.');
|
||||
}
|
||||
if (!Array.isArray(input.signals)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_input',
|
||||
'input.signals must be an array of SignalObservation.'
|
||||
);
|
||||
}
|
||||
|
||||
const bars = input.bars;
|
||||
const signals = input.signals;
|
||||
|
||||
// Pass 1 over bars: validate structure, build pre-cutoff calendar, count bars per listing.
|
||||
// Never access `bar.close` when the bar's UTC dayKey reaches or exceeds `vaultCutoffDayKey`.
|
||||
const postCutoffDays = new Set<number>();
|
||||
const preCutoffDayMaxTs = new Map<number, number>();
|
||||
const listingBarCounts = new Map<number, number>();
|
||||
let preCutoffBarTotal = 0;
|
||||
|
||||
for (let i = 0; i < bars.length; i += 1) {
|
||||
const rawBar: unknown = bars[i];
|
||||
if (!isPlainRecord(rawBar)) {
|
||||
throw new SignalPanelError('invalid_bar', `bars[${i}] must be a non-null plain object.`);
|
||||
}
|
||||
|
||||
const listingId = rawBar.listingId;
|
||||
if (!isValidInt32(listingId)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_bar',
|
||||
`Invalid listingId at bars[${i}]: ${String(listingId)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const ts = rawBar.ts;
|
||||
if (!isValidEpochMs(ts)) {
|
||||
throw new SignalPanelError('invalid_bar', `Invalid ts at bars[${i}]: ${String(ts)}.`);
|
||||
}
|
||||
|
||||
const knownAt = rawBar.knownAt;
|
||||
if (!isValidEpochMs(knownAt)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_bar',
|
||||
`Invalid knownAt at bars[${i}]: ${String(knownAt)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const dayKey = Math.floor(ts / MS_PER_DAY);
|
||||
if (dayKey >= vaultCutoffDayKey) {
|
||||
postCutoffDays.add(dayKey);
|
||||
continue;
|
||||
}
|
||||
|
||||
const close = rawBar.close;
|
||||
if (typeof close !== 'number') {
|
||||
throw new SignalPanelError('invalid_bar', `Invalid close at bars[${i}]: expected a number.`);
|
||||
}
|
||||
|
||||
const prevMaxTs = preCutoffDayMaxTs.get(dayKey);
|
||||
if (prevMaxTs === undefined || ts > prevMaxTs) {
|
||||
preCutoffDayMaxTs.set(dayKey, ts);
|
||||
}
|
||||
|
||||
const normListingId = normalizeZero(listingId);
|
||||
listingBarCounts.set(normListingId, (listingBarCounts.get(normListingId) ?? 0) + 1);
|
||||
preCutoffBarTotal += 1;
|
||||
}
|
||||
|
||||
// Build strictly ascending pre-cutoff session calendar.
|
||||
const preCount = preCutoffDayMaxTs.size;
|
||||
const preDayKeys = new Int32Array(preCount);
|
||||
{
|
||||
let idx = 0;
|
||||
for (const dayKey of preCutoffDayMaxTs.keys()) {
|
||||
preDayKeys[idx] = dayKey;
|
||||
idx += 1;
|
||||
}
|
||||
preDayKeys.sort();
|
||||
}
|
||||
|
||||
const sessionMaxTs = new Float64Array(preCount);
|
||||
const sessionDates: string[] = new Array<string>(preCount);
|
||||
for (let i = 0; i < preCount; i += 1) {
|
||||
const dk = preDayKeys[i] as number;
|
||||
sessionMaxTs[i] = preCutoffDayMaxTs.get(dk) as number;
|
||||
sessionDates[i] = formatDayKeyUtc(dk);
|
||||
}
|
||||
|
||||
const emittableDateLimit = Math.max(0, preCount - horizonSessions);
|
||||
const hasPostCutoff = postCutoffDays.size > 0;
|
||||
const vaultExcludedDates = hasPostCutoff
|
||||
? preCount - emittableDateLimit + postCutoffDays.size
|
||||
: 0;
|
||||
|
||||
// Sort unique listingIds ascending so output cross-section `ids` are strictly ascending
|
||||
// with zero per-date sorting.
|
||||
const listingCount = listingBarCounts.size;
|
||||
const sortedListingIds = new Int32Array(listingCount);
|
||||
{
|
||||
let idx = 0;
|
||||
for (const lid of listingBarCounts.keys()) {
|
||||
sortedListingIds[idx] = lid;
|
||||
idx += 1;
|
||||
}
|
||||
sortedListingIds.sort();
|
||||
}
|
||||
|
||||
const listingIdToIdx = new Map<number, number>();
|
||||
const barOffsets = new Int32Array(listingCount + 1);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const lid = sortedListingIds[l] as number;
|
||||
listingIdToIdx.set(lid, l);
|
||||
barOffsets[l + 1] = (barOffsets[l] as number) + (listingBarCounts.get(lid) as number);
|
||||
}
|
||||
|
||||
// Validate all signals upfront (even if bars is empty) and count signals per known listing.
|
||||
const sigCounts = new Int32Array(listingCount);
|
||||
let matchedSignalTotal = 0;
|
||||
for (let i = 0; i < signals.length; i += 1) {
|
||||
const rawSig: unknown = signals[i];
|
||||
if (!isPlainRecord(rawSig)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`signals[${i}] must be a non-null plain object.`
|
||||
);
|
||||
}
|
||||
|
||||
const listingId = rawSig.listingId;
|
||||
if (!isValidInt32(listingId)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid listingId at signals[${i}]: ${String(listingId)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const knownAt = rawSig.knownAt;
|
||||
if (!isValidEpochMs(knownAt)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid knownAt at signals[${i}]: ${String(knownAt)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const value = rawSig.value;
|
||||
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
||||
throw new SignalPanelError(
|
||||
'invalid_signal',
|
||||
`Invalid signal value at signals[${i}]: ${String(value)}.`
|
||||
);
|
||||
}
|
||||
|
||||
const l = listingIdToIdx.get(normalizeZero(listingId));
|
||||
if (l !== undefined) {
|
||||
sigCounts[l] = (sigCounts[l] as number) + 1;
|
||||
matchedSignalTotal += 1;
|
||||
}
|
||||
}
|
||||
|
||||
if (preCutoffBarTotal === 0) {
|
||||
return {
|
||||
panel: [],
|
||||
sessionDates,
|
||||
diagnostics: {
|
||||
vaultExcludedDates,
|
||||
droppedNoSignal: 0,
|
||||
droppedStaleSignal: 0,
|
||||
droppedMissingForwardBar: 0,
|
||||
droppedNonPositiveClose: 0,
|
||||
duplicateBars: 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Build O(1) dayKey -> sessionIdx lookup (direct Int32Array when span <= 200_000, else Map).
|
||||
const minDayKey = preDayKeys[0] as number;
|
||||
const maxDayKey = preDayKeys[preCount - 1] as number;
|
||||
const daySpan = maxDayKey - minDayKey + 1;
|
||||
let dayKeyToIdxArr: Int32Array | null = null;
|
||||
let dayKeyToIdxMap: Map<number, number> | null = null;
|
||||
if (daySpan <= MAX_DIRECT_DAY_SPAN) {
|
||||
dayKeyToIdxArr = new Int32Array(daySpan);
|
||||
dayKeyToIdxArr.fill(-1);
|
||||
for (let i = 0; i < preCount; i += 1) {
|
||||
dayKeyToIdxArr[(preDayKeys[i] as number) - minDayKey] = i;
|
||||
}
|
||||
} else {
|
||||
dayKeyToIdxMap = new Map<number, number>();
|
||||
for (let i = 0; i < preCount; i += 1) {
|
||||
dayKeyToIdxMap.set(preDayKeys[i] as number, i);
|
||||
}
|
||||
}
|
||||
|
||||
// Scatter pre-cutoff bars into CSR typed arrays grouped by listing index.
|
||||
const barSessionIdx = new Int32Array(preCutoffBarTotal);
|
||||
const barTs = new Float64Array(preCutoffBarTotal);
|
||||
const barClose = new Float64Array(preCutoffBarTotal);
|
||||
const barCursor = new Int32Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
barCursor[l] = barOffsets[l] as number;
|
||||
}
|
||||
|
||||
for (let i = 0; i < bars.length; i += 1) {
|
||||
const bar = bars[i] as BarRecord;
|
||||
const dayKey = Math.floor(bar.ts / MS_PER_DAY);
|
||||
if (dayKey >= vaultCutoffDayKey) {
|
||||
continue;
|
||||
}
|
||||
const l = listingIdToIdx.get(normalizeZero(bar.listingId)) as number;
|
||||
const pos = barCursor[l] as number;
|
||||
barCursor[l] = pos + 1;
|
||||
|
||||
const sIdx =
|
||||
dayKeyToIdxArr !== null
|
||||
? (dayKeyToIdxArr[dayKey - minDayKey] as number)
|
||||
: ((dayKeyToIdxMap as Map<number, number>).get(dayKey) as number);
|
||||
barSessionIdx[pos] = sIdx;
|
||||
barTs[pos] = normalizeZero(bar.ts);
|
||||
barClose[pos] = bar.close;
|
||||
}
|
||||
|
||||
// Scatter matched signals into CSR typed arrays grouped by listing index.
|
||||
const sigOffsets = new Int32Array(listingCount + 1);
|
||||
const sigCursor = new Int32Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
sigOffsets[l + 1] = (sigOffsets[l] as number) + (sigCounts[l] as number);
|
||||
sigCursor[l] = sigOffsets[l] as number;
|
||||
}
|
||||
|
||||
const sigKnownAt = new Float64Array(matchedSignalTotal);
|
||||
const sigValue = new Float64Array(matchedSignalTotal);
|
||||
if (matchedSignalTotal > 0) {
|
||||
for (let i = 0; i < signals.length; i += 1) {
|
||||
const sig = signals[i] as SignalObservation;
|
||||
const l = listingIdToIdx.get(normalizeZero(sig.listingId));
|
||||
if (l === undefined) {
|
||||
continue;
|
||||
}
|
||||
const pos = sigCursor[l] as number;
|
||||
sigCursor[l] = pos + 1;
|
||||
sigKnownAt[pos] = normalizeZero(sig.knownAt);
|
||||
sigValue[pos] = normalizeZero(sig.value);
|
||||
}
|
||||
}
|
||||
|
||||
// Per-date growable typed-array buckets for emitted observations.
|
||||
const initialBucketCap = Math.max(
|
||||
8,
|
||||
Math.min(listingCount, Math.ceil(preCutoffBarTotal / Math.max(1, preCount)))
|
||||
);
|
||||
const bucketLengths = new Int32Array(emittableDateLimit);
|
||||
const bucketIds: (Int32Array | null)[] = new Array<Int32Array | null>(emittableDateLimit).fill(
|
||||
null
|
||||
);
|
||||
const bucketSignals: (Float64Array | null)[] = new Array<Float64Array | null>(
|
||||
emittableDateLimit
|
||||
).fill(null);
|
||||
const bucketReturns: (Float64Array | null)[] = new Array<Float64Array | null>(
|
||||
emittableDateLimit
|
||||
).fill(null);
|
||||
|
||||
const barScratch: BarSortScratch = {
|
||||
sessionIdx: new Int32Array(0),
|
||||
ts: new Float64Array(0),
|
||||
close: new Float64Array(0),
|
||||
};
|
||||
const sigScratch: SignalSortScratch = {
|
||||
knownAt: new Float64Array(0),
|
||||
value: new Float64Array(0),
|
||||
};
|
||||
|
||||
let droppedNoSignal = 0;
|
||||
let droppedStaleSignal = 0;
|
||||
let droppedMissingForwardBar = 0;
|
||||
let droppedNonPositiveClose = 0;
|
||||
let duplicateBars = 0;
|
||||
|
||||
// One linear merge pass per listing in ascending listingId order.
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const listingId = sortedListingIds[l] as number;
|
||||
const bStart = barOffsets[l] as number;
|
||||
const bEnd = barOffsets[l + 1] as number;
|
||||
if (bStart >= bEnd) {
|
||||
continue;
|
||||
}
|
||||
|
||||
sortBarSliceBySession(barSessionIdx, barTs, barClose, bStart, bEnd, barScratch);
|
||||
|
||||
// Compact exact duplicates in place; reject conflicting duplicates on the same (listingId, date).
|
||||
let write = bStart;
|
||||
for (let i = bStart + 1; i < bEnd; i += 1) {
|
||||
if (barSessionIdx[i] === barSessionIdx[write]) {
|
||||
const prevTs = barTs[write] as number;
|
||||
const currTs = barTs[i] as number;
|
||||
const prevClose = barClose[write] as number;
|
||||
const currClose = barClose[i] as number;
|
||||
const sameClose =
|
||||
prevClose === currClose || (Number.isNaN(prevClose) && Number.isNaN(currClose));
|
||||
if (currTs === prevTs && sameClose) {
|
||||
duplicateBars += 1;
|
||||
continue;
|
||||
}
|
||||
const conflictDate = sessionDates[barSessionIdx[i] as number] as string;
|
||||
throw new SignalPanelError(
|
||||
'duplicate_bar',
|
||||
`Conflicting duplicate bars for listingId ${listingId} on session ${conflictDate}.`
|
||||
);
|
||||
}
|
||||
write += 1;
|
||||
if (write !== i) {
|
||||
barSessionIdx[write] = barSessionIdx[i] as number;
|
||||
barTs[write] = barTs[i] as number;
|
||||
barClose[write] = barClose[i] as number;
|
||||
}
|
||||
}
|
||||
const uniqueEnd = write + 1;
|
||||
|
||||
const sStart = sigOffsets[l] as number;
|
||||
const sEnd = sigOffsets[l + 1] as number;
|
||||
sortSignalSlice(sigKnownAt, sigValue, sStart, sEnd, sigScratch);
|
||||
|
||||
let sigPtr = sStart - 1;
|
||||
let fwdPtr = bStart;
|
||||
let ageCalPtr = 0;
|
||||
let firstActionableSessionIdx = -1;
|
||||
|
||||
for (let i = bStart; i < uniqueEnd; i += 1) {
|
||||
const t = barSessionIdx[i] as number;
|
||||
if (hasPostCutoff && t >= emittableDateLimit) {
|
||||
break;
|
||||
}
|
||||
|
||||
const ts = barTs[i] as number;
|
||||
const prevSigPtr = sigPtr;
|
||||
while (sigPtr + 1 < sEnd && (sigKnownAt[sigPtr + 1] as number) <= ts) {
|
||||
sigPtr += 1;
|
||||
}
|
||||
|
||||
if (sigPtr < sStart) {
|
||||
droppedNoSignal += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (maxSignalAgeSessions !== undefined) {
|
||||
if (sigPtr !== prevSigPtr) {
|
||||
const activeKnownAt = sigKnownAt[sigPtr] as number;
|
||||
while (ageCalPtr < preCount && (sessionMaxTs[ageCalPtr] as number) < activeKnownAt) {
|
||||
ageCalPtr += 1;
|
||||
}
|
||||
firstActionableSessionIdx = ageCalPtr;
|
||||
}
|
||||
if (t - firstActionableSessionIdx > maxSignalAgeSessions) {
|
||||
droppedStaleSignal += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const targetSession = t + horizonSessions;
|
||||
if (targetSession >= preCount) {
|
||||
droppedMissingForwardBar += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
while (fwdPtr < uniqueEnd && (barSessionIdx[fwdPtr] as number) < targetSession) {
|
||||
fwdPtr += 1;
|
||||
}
|
||||
if (fwdPtr >= uniqueEnd || (barSessionIdx[fwdPtr] as number) !== targetSession) {
|
||||
droppedMissingForwardBar += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const close0 = barClose[i] as number;
|
||||
const close1 = barClose[fwdPtr] as number;
|
||||
if (!Number.isFinite(close0) || close0 <= 0 || !Number.isFinite(close1) || close1 <= 0) {
|
||||
droppedNonPositiveClose += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
const fwdRet = close1 / close0 - 1;
|
||||
if (!Number.isFinite(fwdRet)) {
|
||||
droppedNonPositiveClose += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Append to bucket `t`.
|
||||
const len = bucketLengths[t] as number;
|
||||
let ids = bucketIds[t] ?? null;
|
||||
let sigs = bucketSignals[t] ?? null;
|
||||
let rets = bucketReturns[t] ?? null;
|
||||
if (ids === null || sigs === null || rets === null) {
|
||||
ids = new Int32Array(initialBucketCap);
|
||||
sigs = new Float64Array(initialBucketCap);
|
||||
rets = new Float64Array(initialBucketCap);
|
||||
bucketIds[t] = ids;
|
||||
bucketSignals[t] = sigs;
|
||||
bucketReturns[t] = rets;
|
||||
} else if (len === ids.length) {
|
||||
const nextCap = Math.min(listingCount, ids.length * 2);
|
||||
const nextIds = new Int32Array(nextCap);
|
||||
const nextSigs = new Float64Array(nextCap);
|
||||
const nextRets = new Float64Array(nextCap);
|
||||
nextIds.set(ids);
|
||||
nextSigs.set(sigs);
|
||||
nextRets.set(rets);
|
||||
ids = nextIds;
|
||||
sigs = nextSigs;
|
||||
rets = nextRets;
|
||||
bucketIds[t] = ids;
|
||||
bucketSignals[t] = sigs;
|
||||
bucketReturns[t] = rets;
|
||||
}
|
||||
|
||||
ids[len] = listingId;
|
||||
sigs[len] = normalizeZero(sigValue[sigPtr] as number);
|
||||
rets[len] = normalizeZero(fwdRet);
|
||||
bucketLengths[t] = len + 1;
|
||||
}
|
||||
}
|
||||
|
||||
const panel: SignalCrossSection[] = [];
|
||||
for (let t = 0; t < emittableDateLimit; t += 1) {
|
||||
const len = bucketLengths[t] as number;
|
||||
if (len === 0) {
|
||||
continue;
|
||||
}
|
||||
const ids = bucketIds[t] as Int32Array;
|
||||
const sigs = bucketSignals[t] as Float64Array;
|
||||
const rets = bucketReturns[t] as Float64Array;
|
||||
panel.push({
|
||||
date: sessionDates[t] as string,
|
||||
ids: len === ids.length ? ids : ids.slice(0, len),
|
||||
signal: len === sigs.length ? sigs : sigs.slice(0, len),
|
||||
forwardReturn: len === rets.length ? rets : rets.slice(0, len),
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
panel,
|
||||
sessionDates,
|
||||
diagnostics: {
|
||||
vaultExcludedDates,
|
||||
droppedNoSignal,
|
||||
droppedStaleSignal,
|
||||
droppedMissingForwardBar,
|
||||
droppedNonPositiveClose,
|
||||
duplicateBars,
|
||||
},
|
||||
};
|
||||
}
|
||||
729
libs/research/test/event-panel-e2e.test.ts
Normal file
729
libs/research/test/event-panel-e2e.test.ts
Normal file
|
|
@ -0,0 +1,729 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
buildEventStudyInput,
|
||||
collectBars,
|
||||
createDuckDbMarketDataStore,
|
||||
eventsTableToEventRows,
|
||||
runEventStudy,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type EventStudyExchangeCalendars,
|
||||
type TableRow,
|
||||
type TrialLedgerExecutor,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const IMMUTABLE_ADJ_PATH = `${CURATED_ROOT}/adj_factors/snapshots/qmfilings_e2e_fenced.parquet`;
|
||||
const SEED = 20261129;
|
||||
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = new Array(count);
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
let written = 0;
|
||||
while (written < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out[written] = current.toISOString().slice(0, 10);
|
||||
written += 1;
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeUtcMs(date: string, hourUtc: number): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
|
||||
}
|
||||
|
||||
interface StoredTrialRow {
|
||||
readonly trial_id: string;
|
||||
readonly created_at: Date;
|
||||
readonly principal_id: string;
|
||||
readonly campaign_id: string | null;
|
||||
readonly stage: string;
|
||||
readonly universe_market: string;
|
||||
readonly horizon_bucket: string;
|
||||
readonly hypothesis_id: string | null;
|
||||
readonly expression_hash: string;
|
||||
readonly sample_start: string;
|
||||
readonly sample_end: string;
|
||||
readonly n_obs: number;
|
||||
readonly sharpe_unann: number;
|
||||
readonly skewness: number;
|
||||
readonly kurtosis: number;
|
||||
readonly daily_series: readonly number[];
|
||||
}
|
||||
|
||||
function createInMemoryTrialExecutor(): {
|
||||
executor: TrialLedgerExecutor;
|
||||
rows: StoredTrialRow[];
|
||||
} {
|
||||
const rows: StoredTrialRow[] = [];
|
||||
let nextTrialId = 1;
|
||||
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
const p = params ?? [];
|
||||
const trialId = nextTrialId++;
|
||||
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
|
||||
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
||||
const stored: StoredTrialRow = {
|
||||
trial_id: String(trialId),
|
||||
created_at: createdAt,
|
||||
principal_id: p[0] as string,
|
||||
campaign_id: (p[1] as string | null) ?? null,
|
||||
stage: p[2] as string,
|
||||
universe_market: p[3] as string,
|
||||
horizon_bucket: p[4] as string,
|
||||
hypothesis_id: (p[5] as string | null) ?? null,
|
||||
expression_hash: p[6] as string,
|
||||
sample_start: p[7] as string,
|
||||
sample_end: p[8] as string,
|
||||
n_obs: p[9] as number,
|
||||
sharpe_unann: p[10] as number,
|
||||
skewness: p[11] as number,
|
||||
kurtosis: p[12] as number,
|
||||
daily_series: dailySeries,
|
||||
};
|
||||
rows.push(stored);
|
||||
return {
|
||||
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const targetId = String(params?.[0]);
|
||||
const matched = rows.filter(r => r.trial_id === targetId);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const market = params?.[0] as string;
|
||||
const bucket = params?.[1] as string;
|
||||
const matched = rows.filter(
|
||||
r => r.universe_market === market && r.horizon_bucket === bucket
|
||||
);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, rows };
|
||||
}
|
||||
|
||||
interface AdjFactorRow {
|
||||
readonly listing_id: number;
|
||||
readonly ex_date: string;
|
||||
readonly cum_split_factor: number;
|
||||
readonly cum_total_factor: number;
|
||||
readonly known_at: number;
|
||||
}
|
||||
|
||||
interface QmFilingsFixture {
|
||||
readonly listingIds: number[];
|
||||
readonly usListingIds: ReadonlySet<number>;
|
||||
readonly caListingIds: ReadonlySet<number>;
|
||||
readonly allDates: string[];
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly barRows: TableRow[];
|
||||
readonly adjFactorRows: AdjFactorRow[];
|
||||
readonly eventRows: TableRow[];
|
||||
readonly exchangeCalendars: EventStudyExchangeCalendars;
|
||||
readonly dividendCase: {
|
||||
readonly listingId: number;
|
||||
readonly exDate: string;
|
||||
readonly exDayIdx: number;
|
||||
readonly expectedTotalReturn: number;
|
||||
readonly rawDropReturn: number;
|
||||
};
|
||||
readonly halfDayCase: {
|
||||
readonly usListingId: number;
|
||||
readonly caListingId: number;
|
||||
readonly halfDayDate: string;
|
||||
readonly halfDayIdx: number;
|
||||
readonly nextSessionDate: string;
|
||||
readonly nextSessionIdx: number;
|
||||
readonly usHalfDayReturn: number;
|
||||
readonly usNextSessionReturn: number;
|
||||
};
|
||||
}
|
||||
|
||||
function makeFencedAdjKvRows(vaultCutoffTs: number, rowsWritten: number): TableRow[] {
|
||||
return [
|
||||
{ key: 'stock_bot.adj_factors.format_version', value: '1' },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' },
|
||||
{ key: 'stock_bot.adj_factors.as_of_micros', value: 'none' },
|
||||
{ key: 'stock_bot.adj_factors.vault_cutoff_micros', value: String(vaultCutoffTs * 1000) },
|
||||
{ key: 'stock_bot.adj_factors.rows_written', value: String(rowsWritten) },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x024ec73a1afe7e6b' },
|
||||
];
|
||||
}
|
||||
|
||||
function buildQmFilingsFixture(poisonPostCutoff: boolean): QmFilingsFixture {
|
||||
const rand = createSeededRng(SEED);
|
||||
const listingCount = 24; // 12 US ('10-q') + 12 CA ('interim_financial_statements')
|
||||
const preCutoffSessions = 160; // spans late 2022 through spring 2023 (pre-2023 & post-2023)
|
||||
const postCutoffSessions = 10;
|
||||
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
|
||||
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
||||
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
||||
|
||||
const listingIds = Array.from({ length: listingCount }, (_, i) =>
|
||||
i < 12 ? 10_001 + i : 50_001 + (i - 12)
|
||||
);
|
||||
const usListingIds = new Set(listingIds.slice(0, 12));
|
||||
const caListingIds = new Set(listingIds.slice(12));
|
||||
const barRows: TableRow[] = [];
|
||||
const adjFactorRows: AdjFactorRow[] = [];
|
||||
const eventRows: TableRow[] = [];
|
||||
|
||||
// Black Friday 2022-11-25: NYSE closes early at 13:00 ET (18:00 UTC) while TSX closes at
|
||||
// 16:00 ET (21:00 UTC), even though curated bars_1d.ts stamps both at 16:00 ET (21:00 UTC).
|
||||
const halfDayDate = '2022-11-25';
|
||||
const halfDayIdx = allDates.indexOf(halfDayDate);
|
||||
if (halfDayIdx < 1 || halfDayIdx + 1 >= preCutoffSessions) {
|
||||
throw new Error(`Expected half-day ${halfDayDate} inside pre-cutoff range.`);
|
||||
}
|
||||
const nextSessionIdx = halfDayIdx + 1;
|
||||
const nextSessionDate = allDates[nextSessionIdx]!;
|
||||
const halfDayUsIdx = 0; // listingId 10_001 (XNYS)
|
||||
const halfDayCaIdx = 12; // listingId 50_001 (XTSE)
|
||||
const halfDayUsListingId = listingIds[halfDayUsIdx]!;
|
||||
const halfDayCaListingId = listingIds[halfDayCaIdx]!;
|
||||
let usHalfDayReturn = 0;
|
||||
let usNextSessionReturn = 0;
|
||||
|
||||
const nyseCalendar = allDates.map(date => ({
|
||||
date,
|
||||
closeTs: makeUtcMs(date, date === halfDayDate ? 18 : 21), // 13:00 ET on Black Friday, else 16:00 ET
|
||||
}));
|
||||
const tsxCalendar = allDates.map(date => ({
|
||||
date,
|
||||
closeTs: makeUtcMs(date, 21), // 16:00 ET on all sessions including Black Friday
|
||||
}));
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
listingCalendarId.set(listingIds[l]!, l < 12 ? 'XNYS' : 'XTSE');
|
||||
}
|
||||
const exchangeCalendars: EventStudyExchangeCalendars = {
|
||||
calendars: new Map([
|
||||
['XNYS', nyseCalendar],
|
||||
['XTSE', tsxCalendar],
|
||||
]),
|
||||
listingCalendarId,
|
||||
};
|
||||
|
||||
// Plant a 10% cash dividend inside a filing window for listing 0 (US, 10-q):
|
||||
// On t = 12, listing l = ((12/4)*2 + 0) % 24 = 6 files after close; choose listing 6
|
||||
// and ex-date t = 15 (day +2 inside its [0..+5] filing window).
|
||||
const divListingIdx = 6;
|
||||
const divListingId = listingIds[divListingIdx]!;
|
||||
const divExIdx = 15;
|
||||
const divExDate = allDates[divExIdx]!;
|
||||
const divYield = 0.1; // 10% cash dividend -> cum_total_factor = 1 / (1 - 0.1) = 10/9
|
||||
let divExpectedTotalReturn = 0;
|
||||
let divRawDropReturn = 0;
|
||||
|
||||
// Track active post-filing drift per listing: zero look-ahead because a filing stamped
|
||||
// after close on session `t` (`22:00 UTC` / `17:00 ET`) only boosts returns starting on
|
||||
// session `t + 1` (the event's anchored `dayIndex`) for 5 sessions.
|
||||
const remainingBoostSessions = new Int32Array(listingCount);
|
||||
const rawPrices = new Float64Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
rawPrices[l] = 15 + l * 1.25;
|
||||
}
|
||||
|
||||
for (let t = 0; t < allDates.length; t += 1) {
|
||||
const date = allDates[t]!;
|
||||
const closeTs = makeUtcMs(date, 21); // 16:00 ET
|
||||
const afterCloseTs = makeUtcMs(date, 22); // 17:00 ET
|
||||
const isPostCutoff = date >= vaultCutoffDate;
|
||||
|
||||
// Emit daily bars using ONLY boosts already active before today's close.
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const boost = remainingBoostSessions[l]! > 0 ? 0.008 : 0;
|
||||
if (remainingBoostSessions[l]! > 0) {
|
||||
remainingBoostSessions[l] = remainingBoostSessions[l]! - 1;
|
||||
}
|
||||
const dailyRet = boost + (rand() * 2 - 1) * 0.006;
|
||||
|
||||
if (l === divListingIdx && t === divExIdx) {
|
||||
const prevRaw = rawPrices[l]!;
|
||||
const exRawBase = prevRaw * (1 - divYield);
|
||||
const nextRaw = exRawBase * (1 + dailyRet);
|
||||
const cumTotalFactor = prevRaw / exRawBase; // 1 / (1 - divYield)
|
||||
adjFactorRows.push({
|
||||
listing_id: divListingId,
|
||||
ex_date: divExDate,
|
||||
cum_split_factor: 1.0,
|
||||
cum_total_factor: cumTotalFactor,
|
||||
known_at: makeUtcMs(allDates[divExIdx - 1]!, 21),
|
||||
});
|
||||
divExpectedTotalReturn = nextRaw / (prevRaw / cumTotalFactor) - 1;
|
||||
divRawDropReturn = nextRaw / prevRaw - 1;
|
||||
rawPrices[l] = nextRaw;
|
||||
} else {
|
||||
const prevRaw = rawPrices[l]!;
|
||||
const nextRaw = Math.max(0.5, prevRaw * (1 + dailyRet));
|
||||
if (l === halfDayUsIdx && t === halfDayIdx) {
|
||||
usHalfDayReturn = nextRaw / prevRaw - 1;
|
||||
} else if (l === halfDayUsIdx && t === nextSessionIdx) {
|
||||
usNextSessionReturn = nextRaw / prevRaw - 1;
|
||||
}
|
||||
rawPrices[l] = nextRaw;
|
||||
}
|
||||
|
||||
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : rawPrices[l]!;
|
||||
barRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
session_date: date,
|
||||
ts: closeTs,
|
||||
open: closeVal,
|
||||
high: closeVal,
|
||||
low: closeVal,
|
||||
close: closeVal,
|
||||
volume: 75_000,
|
||||
vwap: closeVal,
|
||||
known_at: closeTs,
|
||||
});
|
||||
}
|
||||
|
||||
// Schedule staggered after-close filing events across pre-2023 and post-2023 sessions
|
||||
// (plus post-cutoff filings to verify Vault isolation) using exact curator subtypes.
|
||||
if (t >= 12 && (t - 12) % 4 === 0) {
|
||||
for (let k = 0; k < 2; k += 1) {
|
||||
const l = ((t / 4) * 2 + k) % listingCount;
|
||||
const isUs = l < 12;
|
||||
const subtype = isUs ? '10-q' : 'interim_financial_statements';
|
||||
eventRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
ts: afterCloseTs,
|
||||
known_at: afterCloseTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: poisonPostCutoff && isPostCutoff ? 'poison_filing' : subtype,
|
||||
payload_json: JSON.stringify({ market: isUs ? 'US' : 'CA', form: subtype }),
|
||||
});
|
||||
// Activate drift starting on session `t + 1`.
|
||||
remainingBoostSessions[l] = 5;
|
||||
}
|
||||
|
||||
// Also emit a non-matching curated subtype filing on another listing to verify subtype filtering.
|
||||
const otherL = (t + 7) % listingCount;
|
||||
eventRows.push({
|
||||
listing_id: listingIds[otherL]!,
|
||||
ts: afterCloseTs,
|
||||
known_at: afterCloseTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: 'other',
|
||||
payload_json: '{}',
|
||||
});
|
||||
}
|
||||
|
||||
// Emit half-day filings at 14:00 ET (19:00 UTC) on Black Friday 2022-11-25:
|
||||
// - NYSE already closed at 13:00 ET (18:00 UTC) -> anchors to Monday 2022-11-28.
|
||||
// - TSX closes at 16:00 ET (21:00 UTC) -> anchors to Friday 2022-11-25.
|
||||
if (t === halfDayIdx) {
|
||||
const halfDay14EtTs = makeUtcMs(date, 19);
|
||||
eventRows.push({
|
||||
listing_id: halfDayUsListingId,
|
||||
ts: halfDay14EtTs,
|
||||
known_at: halfDay14EtTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: '10-q',
|
||||
payload_json: JSON.stringify({ market: 'US', form: '10-q', halfDay: true }),
|
||||
});
|
||||
eventRows.push({
|
||||
listing_id: halfDayCaListingId,
|
||||
ts: halfDay14EtTs,
|
||||
known_at: halfDay14EtTs,
|
||||
known_at_source: 'exact',
|
||||
kind: 'filing',
|
||||
subtype: 'interim_financial_statements',
|
||||
payload_json: JSON.stringify({
|
||||
market: 'CA',
|
||||
form: 'interim_financial_statements',
|
||||
halfDay: true,
|
||||
}),
|
||||
});
|
||||
remainingBoostSessions[halfDayUsIdx] = 5;
|
||||
remainingBoostSessions[halfDayCaIdx] = 5;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
listingIds,
|
||||
usListingIds,
|
||||
caListingIds,
|
||||
allDates,
|
||||
vaultCutoffDate,
|
||||
vaultCutoffTs,
|
||||
barRows,
|
||||
adjFactorRows,
|
||||
eventRows,
|
||||
exchangeCalendars,
|
||||
dividendCase: {
|
||||
listingId: divListingId,
|
||||
exDate: divExDate,
|
||||
exDayIdx: divExIdx,
|
||||
expectedTotalReturn: divExpectedTotalReturn,
|
||||
rawDropReturn: divRawDropReturn,
|
||||
},
|
||||
halfDayCase: {
|
||||
usListingId: halfDayUsListingId,
|
||||
caListingId: halfDayCaListingId,
|
||||
halfDayDate,
|
||||
halfDayIdx,
|
||||
nextSessionDate,
|
||||
nextSessionIdx,
|
||||
usHalfDayReturn,
|
||||
usNextSessionReturn,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
interface RecordedQuery {
|
||||
readonly sql: string;
|
||||
readonly params: readonly DuckDbParam[];
|
||||
}
|
||||
|
||||
function createFakeDuckDbExecutor(fixture: QmFilingsFixture): {
|
||||
executor: DuckDbExecutor;
|
||||
runStatements: string[];
|
||||
queries: RecordedQuery[];
|
||||
} {
|
||||
const runStatements: string[] = [];
|
||||
const queries: RecordedQuery[] = [];
|
||||
|
||||
const executor: DuckDbExecutor = {
|
||||
async run(sql: string) {
|
||||
runStatements.push(sql);
|
||||
},
|
||||
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
||||
queries.push({ sql, params: [...params] });
|
||||
|
||||
if (sql.includes('parquet_kv_metadata')) {
|
||||
return makeFencedAdjKvRows(fixture.vaultCutoffTs, fixture.adjFactorRows.length);
|
||||
}
|
||||
|
||||
if (sql.includes('bars_1d/year=*/part.parquet')) {
|
||||
const nIds = fixture.listingIds.length;
|
||||
const isAdjusted = sql.includes('ASOF LEFT JOIN');
|
||||
let idSet: Set<number>;
|
||||
let fromMs: number;
|
||||
let toMs: number;
|
||||
let asOfMs: number;
|
||||
let adjAsOfMs: number | null = null;
|
||||
|
||||
if (isAdjusted) {
|
||||
// Bound params: [...listingIds, adjAsOfIso, ...listingIds, fromIso, toIso, asOfIso]
|
||||
adjAsOfMs = Date.parse(params[nIds] as string);
|
||||
idSet = new Set<number>(params.slice(nIds + 1, 2 * nIds + 1) as number[]);
|
||||
fromMs = Date.parse(params[2 * nIds + 1] as string);
|
||||
toMs = Date.parse(params[2 * nIds + 2] as string);
|
||||
asOfMs = Date.parse(params[2 * nIds + 3] as string);
|
||||
} else {
|
||||
// Bound params: [...listingIds, fromIso, toIso, asOfIso]
|
||||
idSet = new Set<number>(params.slice(0, nIds) as number[]);
|
||||
fromMs = Date.parse(params[nIds] as string);
|
||||
toMs = Date.parse(params[nIds + 1] as string);
|
||||
asOfMs = Date.parse(params[nIds + 2] as string);
|
||||
}
|
||||
|
||||
const out: TableRow[] = [];
|
||||
for (const row of fixture.barRows) {
|
||||
const lid = row.listing_id as number;
|
||||
const ts = row.ts as number;
|
||||
const knownAt = row.known_at as number;
|
||||
if (!idSet.has(lid) || ts < fromMs || ts > toMs || knownAt > asOfMs) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let priceDivisor = 1.0;
|
||||
let splitFactor = 1.0;
|
||||
if (isAdjusted && adjAsOfMs !== null) {
|
||||
const sessionDate = row.session_date as string;
|
||||
// ASOF LEFT JOIN: first adj_factors row with ex_date > session_date and known_at <= adjAsOfMs
|
||||
let bestAdj: AdjFactorRow | null = null;
|
||||
for (const adj of fixture.adjFactorRows) {
|
||||
if (
|
||||
adj.listing_id === lid &&
|
||||
adj.known_at <= adjAsOfMs &&
|
||||
sessionDate < adj.ex_date &&
|
||||
(bestAdj === null || adj.ex_date < bestAdj.ex_date)
|
||||
) {
|
||||
bestAdj = adj;
|
||||
}
|
||||
}
|
||||
if (bestAdj !== null) {
|
||||
priceDivisor = sql.includes('cum_total_factor')
|
||||
? bestAdj.cum_total_factor
|
||||
: bestAdj.cum_split_factor;
|
||||
splitFactor = bestAdj.cum_split_factor;
|
||||
}
|
||||
}
|
||||
|
||||
out.push({
|
||||
listing_id: lid,
|
||||
ts,
|
||||
open: (row.open as number) / priceDivisor,
|
||||
high: (row.high as number) / priceDivisor,
|
||||
low: (row.low as number) / priceDivisor,
|
||||
close: (row.close as number) / priceDivisor,
|
||||
volume: (row.volume as number) * splitFactor,
|
||||
vwap: (row.vwap as number) / priceDivisor,
|
||||
known_at: knownAt,
|
||||
});
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
if (sql.includes('events/year=*/part.parquet')) {
|
||||
// Bound params: [...kinds, ...listingIds, fromIso, toIso, asOfIso]
|
||||
const nIds = fixture.listingIds.length;
|
||||
const nKinds = params.length - nIds - 3;
|
||||
const kindSet = new Set<string>(params.slice(0, nKinds) as string[]);
|
||||
const idSet = new Set<number>(params.slice(nKinds, nKinds + nIds) as number[]);
|
||||
const fromMs = Date.parse(params[nKinds + nIds] as string);
|
||||
const toMs = Date.parse(params[nKinds + nIds + 1] as string);
|
||||
const asOfMs = Date.parse(params[nKinds + nIds + 2] as string);
|
||||
return fixture.eventRows.filter(row => {
|
||||
const kind = row.kind as string;
|
||||
const lid = row.listing_id as number;
|
||||
const ts = row.ts as number;
|
||||
const knownAt = row.known_at as number;
|
||||
return (
|
||||
kindSet.has(kind) &&
|
||||
idSet.has(lid) &&
|
||||
ts >= fromMs &&
|
||||
ts <= toMs &&
|
||||
knownAt <= asOfMs
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`);
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, runStatements, queries };
|
||||
}
|
||||
|
||||
describe('qmFilings end-to-end event study (headless, no database)', () => {
|
||||
async function runQmFilingsStudy(poisonPostCutoff: boolean) {
|
||||
const fixture = buildQmFilingsFixture(poisonPostCutoff);
|
||||
const duck = createFakeDuckDbExecutor(fixture);
|
||||
const ledger = createInMemoryTrialExecutor();
|
||||
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: duck.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: fixture.vaultCutoffTs,
|
||||
immutableAdjFactorsPath: IMMUTABLE_ADJ_PATH,
|
||||
barBatchSize: 256,
|
||||
});
|
||||
|
||||
const from = fixture.allDates[0]!;
|
||||
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
||||
|
||||
const bars = await collectBars(
|
||||
store.bars({
|
||||
listingIds: fixture.listingIds,
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
adjustment: 'total',
|
||||
})
|
||||
);
|
||||
const eventsTable = await store.events({
|
||||
kinds: ['filing'],
|
||||
listingIds: fixture.listingIds,
|
||||
from,
|
||||
to,
|
||||
});
|
||||
|
||||
const events = eventsTableToEventRows(eventsTable, {
|
||||
kinds: ['filing'],
|
||||
subtypes: ['10-q', 'interim_financial_statements'],
|
||||
});
|
||||
const built = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: fixture.exchangeCalendars,
|
||||
});
|
||||
|
||||
const studyResult = await runEventStudy(ledger.executor, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'qmfilings_interim_10q_sedar_event_study',
|
||||
params: {
|
||||
kinds: ['filing'],
|
||||
subtypes: ['10-q', 'interim_financial_statements'],
|
||||
preDays: 5,
|
||||
postDays: 5,
|
||||
},
|
||||
universe: 'US_CA_EQ_FIXTURE',
|
||||
horizon: '5d',
|
||||
},
|
||||
input: built.input,
|
||||
options: { preDays: 5, postDays: 5, minEvents: 10 },
|
||||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
});
|
||||
|
||||
return { fixture, duck, ledger, events, built, studyResult };
|
||||
}
|
||||
|
||||
it('flows DuckDbMarketDataStore (total-adjusted) -> buildEventStudyInput -> runEventStudy -> trial_ledger + DSR', async () => {
|
||||
const clean = await runQmFilingsStudy(false);
|
||||
|
||||
// DuckDB connection budget SET statements ran once; 3 queries ran (adj_factors kv metadata + bars + events).
|
||||
expect(clean.duck.runStatements).toHaveLength(3);
|
||||
expect(clean.duck.runStatements[0]).toContain('SET memory_limit');
|
||||
expect(clean.duck.runStatements[1]).toContain('SET threads');
|
||||
expect(clean.duck.runStatements[2]).toContain('SET temp_directory');
|
||||
expect(clean.duck.queries).toHaveLength(3);
|
||||
expect(clean.duck.queries[0]!.sql).toContain('parquet_kv_metadata');
|
||||
expect(clean.duck.queries[1]!.sql).toContain('cum_total_factor');
|
||||
expect(clean.duck.queries[2]!.sql).toContain('events/year=*/part.parquet');
|
||||
|
||||
// Every bound timestamp parameter (`asOfIso`, `fromIso`, `toIso`) in every data query
|
||||
// is strictly `< vaultCutoffTs`.
|
||||
const isoRe = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/;
|
||||
let checkedTimestamps = 0;
|
||||
for (const q of clean.duck.queries) {
|
||||
for (const param of q.params) {
|
||||
if (typeof param === 'string' && isoRe.test(param)) {
|
||||
const parsedMs = Date.parse(param);
|
||||
expect(Number.isFinite(parsedMs)).toBe(true);
|
||||
expect(parsedMs).toBeLessThan(clean.fixture.vaultCutoffTs);
|
||||
checkedTimestamps += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
// bars_1d total-adjusted binds 4 timestamps (adjAsOfIso, fromIso, toIso, barsAsOfIso) + events binds 3.
|
||||
expect(checkedTimestamps).toBe(7);
|
||||
|
||||
// Both curated filing groups ('10-q' for US and 'interim_financial_statements' for CA) contribute events.
|
||||
const usFilteredCount = clean.events.filter(e => e.subtype === '10-q').length;
|
||||
const caFilteredCount = clean.events.filter(
|
||||
e => e.subtype === 'interim_financial_statements'
|
||||
).length;
|
||||
expect(usFilteredCount).toBeGreaterThan(0);
|
||||
expect(caFilteredCount).toBeGreaterThan(0);
|
||||
expect(usFilteredCount + caFilteredCount).toBe(clean.events.length);
|
||||
|
||||
// Total-return adjustment eliminates the raw -10% dividend drop inside the filing window.
|
||||
const divCase = clean.fixture.dividendCase;
|
||||
expect(divCase.rawDropReturn).toBeLessThan(-0.08);
|
||||
expect(divCase.expectedTotalReturn).toBeGreaterThan(-0.02);
|
||||
const divSeries = clean.built.input.entityReturns.get(divCase.listingId)!;
|
||||
expect(divSeries[divCase.exDayIdx]!).toBeCloseTo(divCase.expectedTotalReturn, 10);
|
||||
|
||||
// Half-day anchoring: a US ('10-q') filing published at 14:00 ET on Black Friday 2022-11-25
|
||||
// (after NYSE's 13:00 ET close, even though curated bars_1d.ts stamps 16:00 ET) MUST anchor
|
||||
// to Monday 2022-11-28 (not Friday), while the CA ('interim_financial_statements') filing at
|
||||
// 14:00 ET anchors to Friday 2022-11-25 (before TSX's 16:00 ET close).
|
||||
const halfDay = clean.fixture.halfDayCase;
|
||||
expect(
|
||||
clean.built.input.events.some(
|
||||
e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.halfDayIdx
|
||||
)
|
||||
).toBe(false);
|
||||
expect(
|
||||
clean.built.input.events.some(
|
||||
e => e.entityId === halfDay.usListingId && e.dayIndex === halfDay.nextSessionIdx
|
||||
)
|
||||
).toBe(true);
|
||||
expect(
|
||||
clean.built.input.events.some(
|
||||
e => e.entityId === halfDay.caListingId && e.dayIndex === halfDay.halfDayIdx
|
||||
)
|
||||
).toBe(true);
|
||||
const usHalfDaySeries = clean.built.input.entityReturns.get(halfDay.usListingId)!;
|
||||
expect(clean.built.input.sessionDates[halfDay.nextSessionIdx]).toBe(halfDay.nextSessionDate);
|
||||
expect(usHalfDaySeries[halfDay.nextSessionIdx]!).toBeCloseTo(halfDay.usNextSessionReturn, 12);
|
||||
expect(halfDay.usNextSessionReturn).not.toBeCloseTo(halfDay.usHalfDayReturn, 6);
|
||||
|
||||
// Event study succeeded and appended exactly one `event_study` row to trial_ledger.
|
||||
expect(clean.studyResult.status).toBe('ok');
|
||||
if (clean.studyResult.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
// Both US ('10-q') and CA ('interim_financial_statements') listings contributed usable events to the study.
|
||||
const usedIds = clean.studyResult.study.eventCars.entityIds;
|
||||
const usUsedCount = usedIds.filter(id => clean.fixture.usListingIds.has(Number(id))).length;
|
||||
const caUsedCount = usedIds.filter(id => clean.fixture.caListingIds.has(Number(id))).length;
|
||||
expect(usUsedCount).toBeGreaterThan(0);
|
||||
expect(caUsedCount).toBeGreaterThan(0);
|
||||
|
||||
expect(clean.ledger.rows).toHaveLength(1);
|
||||
const stored = clean.ledger.rows[0]!;
|
||||
expect(stored.stage).toBe('event_study');
|
||||
expect(stored.universe_market).toBe('US_CA_EQ');
|
||||
expect(stored.horizon_bucket).toBe('swing_1_10d');
|
||||
expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
|
||||
// Stored daily_series matches study.clustered.meanCars at float32 precision.
|
||||
const expectedMeanCars = Array.from(clean.studyResult.study.clustered.meanCars, v =>
|
||||
Math.fround(v)
|
||||
);
|
||||
expect(stored.daily_series).toEqual(expectedMeanCars);
|
||||
|
||||
// Finite cluster-deflated Sharpe with effectiveTrials >= 1.
|
||||
expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull();
|
||||
expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true);
|
||||
expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Planted positive post-filing abnormal return produces positive clustered CAR mean.
|
||||
expect(clean.studyResult.study.clustered.carMean).toBeGreaterThan(0);
|
||||
|
||||
// Poisoning post-cutoff bars & events leaves built input, study result, and ledger byte-identical.
|
||||
const poisoned = await runQmFilingsStudy(true);
|
||||
expect(poisoned.built.diagnostics).toEqual(clean.built.diagnostics);
|
||||
expect(poisoned.built.input.sessionDates).toEqual(clean.built.input.sessionDates);
|
||||
expect(poisoned.built.input.events).toEqual(clean.built.input.events);
|
||||
expect(Array.from(poisoned.built.input.entityReturns.keys())).toEqual(
|
||||
Array.from(clean.built.input.entityReturns.keys())
|
||||
);
|
||||
for (const [id, cleanSeries] of clean.built.input.entityReturns) {
|
||||
const a = poisoned.built.input.entityReturns.get(id) as Float64Array;
|
||||
const b = cleanSeries as Float64Array;
|
||||
expect(new Uint8Array(a.buffer, a.byteOffset, a.byteLength)).toEqual(
|
||||
new Uint8Array(b.buffer, b.byteOffset, b.byteLength)
|
||||
);
|
||||
}
|
||||
const cleanBench = clean.built.input.benchmarkReturns as Float64Array;
|
||||
const poisonedBench = poisoned.built.input.benchmarkReturns as Float64Array;
|
||||
expect(
|
||||
new Uint8Array(poisonedBench.buffer, poisonedBench.byteOffset, poisonedBench.byteLength)
|
||||
).toEqual(new Uint8Array(cleanBench.buffer, cleanBench.byteOffset, cleanBench.byteLength));
|
||||
expect(poisoned.studyResult).toEqual(clean.studyResult);
|
||||
expect(poisoned.ledger.rows).toEqual(clean.ledger.rows);
|
||||
});
|
||||
});
|
||||
672
libs/research/test/event-panel-qa.test.ts
Normal file
672
libs/research/test/event-panel-qa.test.ts
Normal file
|
|
@ -0,0 +1,672 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
type BarRecord,
|
||||
type BuildEventStudyInputResult,
|
||||
type EventObservation,
|
||||
type EventStudyExchangeCalendars,
|
||||
type ExchangeSessionClose,
|
||||
type TrialLedgerExecutor,
|
||||
buildEventStudyInput,
|
||||
runEventStudy,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
// QA suite for T-123: compares `buildEventStudyInput` against a deliberately naive reference
|
||||
// model on seeded random panels (two exchange calendars with different holidays and an NYSE
|
||||
// half-day, EDT/EST close stamps, gaps, bad closes, exact duplicate bars, late-listing /
|
||||
// early-delisting, events at/around exact close timestamps, weekends, pre-history and
|
||||
// post-cutoff), plus truncation (prefix-stability) and an end-to-end half-day CAR probe.
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeUtcMs(date: string, hourUtc: number, minuteUtc = 0, ms = 0): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms);
|
||||
}
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = [];
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
while (out.length < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out.push(current.toISOString().slice(0, 10));
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// 16:00 ET in UTC: 20:00 during EDT (before 2022-11-06 / from 2023-03-12), 21:00 during EST.
|
||||
function regularCloseHourUtc(date: string): number {
|
||||
return date < '2022-11-06' || date >= '2023-03-12' ? 20 : 21;
|
||||
}
|
||||
|
||||
function makeBar(listingId: number, ts: number, close: number): BarRecord {
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 1_000,
|
||||
vwap: close,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
function makeTrappedBar(listingId: number, ts: number): BarRecord {
|
||||
const bar = { ...makeBar(listingId, ts, 1) } as Record<string, unknown>;
|
||||
Object.defineProperty(bar, 'close', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
throw new Error(`Vault breach: close read for listing ${listingId} at ${ts}`);
|
||||
},
|
||||
});
|
||||
return bar as unknown as BarRecord;
|
||||
}
|
||||
|
||||
function shuffle<T>(items: readonly T[], seed: number): T[] {
|
||||
const copy = [...items];
|
||||
const rand = createSeededRng(seed);
|
||||
for (let i = copy.length - 1; i > 0; i -= 1) {
|
||||
const j = Math.floor(rand() * (i + 1));
|
||||
[copy[i], copy[j]] = [copy[j]!, copy[i]!];
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
const US_HOLIDAYS = new Set(['2022-11-24', '2022-12-26', '2023-01-02', '2023-01-16', '2023-02-20']);
|
||||
const CA_HOLIDAYS = new Set(['2022-10-10', '2022-12-26', '2022-12-27', '2023-01-02', '2023-02-20']);
|
||||
const NYSE_HALF_DAYS = new Set(['2022-11-25']);
|
||||
|
||||
function buildCalendars(dates: readonly string[]): {
|
||||
xnys: ExchangeSessionClose[];
|
||||
xtse: ExchangeSessionClose[];
|
||||
} {
|
||||
const xnys: ExchangeSessionClose[] = [];
|
||||
const xtse: ExchangeSessionClose[] = [];
|
||||
for (const date of dates) {
|
||||
const regular = regularCloseHourUtc(date);
|
||||
if (!US_HOLIDAYS.has(date)) {
|
||||
xnys.push({ date, closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? regular - 3 : regular) });
|
||||
}
|
||||
if (!CA_HOLIDAYS.has(date)) {
|
||||
xtse.push({ date, closeTs: makeUtcMs(date, regular) });
|
||||
}
|
||||
}
|
||||
return { xnys, xtse };
|
||||
}
|
||||
|
||||
interface RandomPanel {
|
||||
readonly bars: BarRecord[];
|
||||
readonly events: EventObservation[];
|
||||
readonly calendars: EventStudyExchangeCalendars;
|
||||
readonly calendarByListing: Map<number, ExchangeSessionClose[]>;
|
||||
readonly dates: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a seeded random panel. Bars dated on/after `trapFromDate` get a throwing `close`
|
||||
* getter so any Vault breach fails the test.
|
||||
*/
|
||||
function buildRandomPanel(seed: number, trapFromDate: string | null): RandomPanel {
|
||||
const rand = createSeededRng(seed);
|
||||
const dates = makeBusinessDates('2022-10-03', 110);
|
||||
const { xnys, xtse } = buildCalendars(dates);
|
||||
const listingCount = 12;
|
||||
const listingIds = Array.from({ length: listingCount }, (_, i) => 100 + i * 7);
|
||||
const calendarByListing = new Map<number, ExchangeSessionClose[]>();
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
const bars: BarRecord[] = [];
|
||||
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const listingId = listingIds[l]!;
|
||||
const isUs = l % 2 === 0;
|
||||
const cal = isUs ? xnys : xtse;
|
||||
calendarByListing.set(listingId, cal);
|
||||
listingCalendarId.set(listingId, isUs ? 'XNYS' : 'XTSE');
|
||||
|
||||
const startIdx = l % 4 === 3 ? 20 + Math.floor(rand() * 20) : 0;
|
||||
const endIdx = l % 5 === 4 ? cal.length - 30 - Math.floor(rand() * 10) : cal.length;
|
||||
let price = 20 + l;
|
||||
for (let s = startIdx; s < endIdx; s += 1) {
|
||||
const session = cal[s]!;
|
||||
if (rand() < 0.08) {
|
||||
continue; // gap
|
||||
}
|
||||
price *= 1 + (rand() * 2 - 1) * 0.02;
|
||||
const ts = makeUtcMs(session.date, regularCloseHourUtc(session.date)); // curated 16:00 ET
|
||||
const trapped = trapFromDate !== null && session.date >= trapFromDate;
|
||||
if (trapped) {
|
||||
bars.push(makeTrappedBar(listingId, ts));
|
||||
continue;
|
||||
}
|
||||
const u = rand();
|
||||
const close = u < 0.01 ? 0 : u < 0.02 ? -1 : u < 0.025 ? Number.NaN : u < 0.03 ? Number.POSITIVE_INFINITY : price;
|
||||
bars.push(makeBar(listingId, ts, close));
|
||||
if (rand() < 0.03) {
|
||||
bars.push(makeBar(listingId, ts, close)); // exact duplicate
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const events: EventObservation[] = [];
|
||||
const eventCount = 160;
|
||||
for (let i = 0; i < eventCount; i += 1) {
|
||||
const unknown = rand() < 0.05;
|
||||
const listingId = unknown ? 9_999 : listingIds[Math.floor(rand() * listingCount)]!;
|
||||
const cal = calendarByListing.get(listingId) ?? xnys;
|
||||
const anchorSession = cal[Math.floor(rand() * cal.length)]!;
|
||||
const mode = Math.floor(rand() * 7);
|
||||
let knownAt: number;
|
||||
if (mode === 0) {
|
||||
knownAt = anchorSession.closeTs; // exactly at close -> same session
|
||||
} else if (mode === 1) {
|
||||
knownAt = anchorSession.closeTs + 1; // 1 ms after close -> next session
|
||||
} else if (mode === 2) {
|
||||
knownAt = anchorSession.closeTs - 1;
|
||||
} else if (mode === 3) {
|
||||
knownAt = makeUtcMs(anchorSession.date, 19); // 14:00/15:00 ET intraday (after half-day close)
|
||||
} else if (mode === 4) {
|
||||
knownAt = makeUtcMs(anchorSession.date, 22, 30); // after close
|
||||
} else if (mode === 5) {
|
||||
knownAt = makeUtcMs(anchorSession.date, 12) + 2 * MS_PER_DAY; // may land on weekend
|
||||
} else {
|
||||
knownAt = makeUtcMs('2022-09-15', 15) + Math.floor(rand() * 200) * MS_PER_DAY; // pre-history .. post-cutoff
|
||||
}
|
||||
events.push({ listingId, knownAt, kind: 'filing', subtype: rand() < 0.5 ? '10-q' : 'interim_financial_statements' });
|
||||
if (rand() < 0.05) {
|
||||
events.push({ listingId, knownAt, kind: 'filing', subtype: 'other' }); // duplicate anchor
|
||||
}
|
||||
}
|
||||
// Explicit NYSE half-day probe: 14:00 ET on Black Friday for a US and a CA listing.
|
||||
events.push({ listingId: listingIds[0]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' });
|
||||
events.push({ listingId: listingIds[1]!, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: null });
|
||||
|
||||
return {
|
||||
bars,
|
||||
events,
|
||||
calendars: {
|
||||
calendars: new Map([
|
||||
['XNYS', xnys],
|
||||
['XTSE', xtse],
|
||||
]),
|
||||
listingCalendarId,
|
||||
},
|
||||
calendarByListing,
|
||||
dates,
|
||||
};
|
||||
}
|
||||
|
||||
interface ReferenceResult {
|
||||
sessionDates: string[];
|
||||
entityIds: number[];
|
||||
returns: Map<number, number[]>;
|
||||
benchmark: number[];
|
||||
events: { entityId: number; dayIndex: number }[];
|
||||
diagnostics: Record<string, number>;
|
||||
}
|
||||
|
||||
/** Naive O(n^2) reference model of the documented contract. */
|
||||
function referenceBuild(panel: RandomPanel, vaultCutoffDate: string): ReferenceResult {
|
||||
const cutoffMs = makeUtcMs(vaultCutoffDate, 0);
|
||||
const dateOf = (ts: number) => new Date(Math.floor(ts / MS_PER_DAY) * MS_PER_DAY).toISOString().slice(0, 10);
|
||||
const postDates = new Set<string>();
|
||||
const perListing = new Map<number, Map<string, number>>();
|
||||
let duplicateBars = 0;
|
||||
for (const bar of panel.bars) {
|
||||
const date = dateOf(bar.ts);
|
||||
if (date >= vaultCutoffDate) {
|
||||
postDates.add(date);
|
||||
continue;
|
||||
}
|
||||
const m = perListing.get(bar.listingId) ?? new Map<string, number>();
|
||||
perListing.set(bar.listingId, m);
|
||||
if (m.has(date)) {
|
||||
duplicateBars += 1;
|
||||
continue;
|
||||
}
|
||||
m.set(date, bar.close);
|
||||
}
|
||||
const sessionDates = [...new Set([...perListing.values()].flatMap(m => [...m.keys()]))].sort();
|
||||
const entityIds = [...perListing.keys()].sort((a, b) => a - b);
|
||||
const returns = new Map<number, number[]>();
|
||||
const benchSum = new Array<number>(sessionDates.length).fill(0);
|
||||
const benchCount = new Array<number>(sessionDates.length).fill(0);
|
||||
let nonPositiveCloseReturns = 0;
|
||||
for (const id of entityIds) {
|
||||
const closes = perListing.get(id)!;
|
||||
const calDates = panel.calendarByListing.get(id)!.map(s => s.date);
|
||||
const series = sessionDates.map((date, d) => {
|
||||
if (!closes.has(date)) {
|
||||
return Number.NaN;
|
||||
}
|
||||
const c = calDates.indexOf(date);
|
||||
if (c <= 0 || !closes.has(calDates[c - 1]!)) {
|
||||
return Number.NaN;
|
||||
}
|
||||
const prev = closes.get(calDates[c - 1]!)!;
|
||||
const curr = closes.get(date)!;
|
||||
const ret = curr / prev - 1;
|
||||
if (!(prev > 0 && curr > 0 && Number.isFinite(prev) && Number.isFinite(curr) && Number.isFinite(ret))) {
|
||||
nonPositiveCloseReturns += 1;
|
||||
return Number.NaN;
|
||||
}
|
||||
benchSum[d] += ret;
|
||||
benchCount[d] += 1;
|
||||
return ret;
|
||||
});
|
||||
returns.set(id, series);
|
||||
}
|
||||
const benchmark = benchSum.map((s, d) => (benchCount[d]! > 0 ? s / benchCount[d]! : Number.NaN));
|
||||
|
||||
let vaultExcludedEvents = 0;
|
||||
let droppedUnknownListing = 0;
|
||||
let droppedAfterLastSession = 0;
|
||||
let droppedMissingCalendarSession = 0;
|
||||
const cands: { entityId: number; dayIndex: number }[] = [];
|
||||
for (const ev of panel.events) {
|
||||
if (ev.knownAt >= cutoffMs) {
|
||||
vaultExcludedEvents += 1;
|
||||
continue;
|
||||
}
|
||||
if (!perListing.has(ev.listingId)) {
|
||||
droppedUnknownListing += 1;
|
||||
continue;
|
||||
}
|
||||
const preCal = panel.calendarByListing.get(ev.listingId)!.filter(s => s.date < vaultCutoffDate);
|
||||
const eligible = preCal.find(s => s.closeTs >= ev.knownAt);
|
||||
if (eligible === undefined || eligible.date > sessionDates[sessionDates.length - 1]!) {
|
||||
droppedAfterLastSession += 1;
|
||||
continue;
|
||||
}
|
||||
const dayIndex = sessionDates.indexOf(eligible.date);
|
||||
if (dayIndex < 0) {
|
||||
droppedMissingCalendarSession += 1;
|
||||
continue;
|
||||
}
|
||||
cands.push({ entityId: ev.listingId, dayIndex });
|
||||
}
|
||||
cands.sort((a, b) => a.dayIndex - b.dayIndex || a.entityId - b.entityId);
|
||||
const events = cands.filter(
|
||||
(c, i) => i === 0 || c.dayIndex !== cands[i - 1]!.dayIndex || c.entityId !== cands[i - 1]!.entityId
|
||||
);
|
||||
|
||||
return {
|
||||
sessionDates,
|
||||
entityIds,
|
||||
returns,
|
||||
benchmark,
|
||||
events,
|
||||
diagnostics: {
|
||||
vaultExcludedDates: postDates.size,
|
||||
vaultExcludedEvents,
|
||||
droppedUnknownListing,
|
||||
droppedAfterLastSession,
|
||||
droppedMissingCalendarSession,
|
||||
duplicateEvents: cands.length - events.length,
|
||||
duplicateBars,
|
||||
nonPositiveCloseReturns,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function nanSafe(values: ArrayLike<number>): (number | string)[] {
|
||||
return Array.from(values, v => (Number.isNaN(v) ? 'NaN' : v));
|
||||
}
|
||||
|
||||
function expectSameAsReference(actual: BuildEventStudyInputResult, ref: ReferenceResult): void {
|
||||
expect(actual.input.sessionDates).toEqual(ref.sessionDates);
|
||||
expect(Array.from(actual.input.entityReturns.keys())).toEqual(ref.entityIds);
|
||||
for (const id of ref.entityIds) {
|
||||
expect(nanSafe(actual.input.entityReturns.get(id)!)).toEqual(nanSafe(ref.returns.get(id)!));
|
||||
}
|
||||
expect(nanSafe(actual.input.benchmarkReturns!)).toEqual(nanSafe(ref.benchmark));
|
||||
expect(actual.input.events.map(e => ({ entityId: e.entityId, dayIndex: e.dayIndex }))).toEqual(ref.events);
|
||||
expect({ ...actual.diagnostics }).toEqual(ref.diagnostics);
|
||||
}
|
||||
|
||||
describe('buildEventStudyInput QA — seeded reference-model comparison', () => {
|
||||
const VAULT_CUTOFF = '2023-02-01';
|
||||
|
||||
for (const seed of [20261129, 7, 424242, 99]) {
|
||||
it(`matches the naive reference model exactly and never reads vaulted closes (seed ${seed})`, () => {
|
||||
const panel = buildRandomPanel(seed, VAULT_CUTOFF);
|
||||
const ref = referenceBuild(panel, VAULT_CUTOFF);
|
||||
|
||||
const actual = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
|
||||
expectSameAsReference(actual, ref);
|
||||
// Conservation identity.
|
||||
const d = actual.diagnostics;
|
||||
expect(
|
||||
actual.input.events.length +
|
||||
d.vaultExcludedEvents +
|
||||
d.droppedUnknownListing +
|
||||
d.droppedAfterLastSession +
|
||||
d.droppedMissingCalendarSession +
|
||||
d.duplicateEvents
|
||||
).toBe(panel.events.length);
|
||||
// No session date reaches the Vault and no event anchors onto a Vault session.
|
||||
expect(actual.input.sessionDates.every(date => date < VAULT_CUTOFF)).toBe(true);
|
||||
// Fixture actually exercises the interesting branches.
|
||||
expect(d.vaultExcludedEvents).toBeGreaterThan(0);
|
||||
expect(d.droppedUnknownListing).toBeGreaterThan(0);
|
||||
expect(d.vaultExcludedDates).toBeGreaterThan(0);
|
||||
expect(d.nonPositiveCloseReturns).toBeGreaterThan(0);
|
||||
|
||||
// Shuffled inputs give the identical result.
|
||||
const shuffled = buildEventStudyInput({
|
||||
bars: shuffle(panel.bars, seed + 1),
|
||||
events: shuffle(panel.events, seed + 2),
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
expectSameAsReference(shuffled, ref);
|
||||
});
|
||||
}
|
||||
|
||||
it('anchors the NYSE Black Friday 14:00 ET filing to Monday and the TSX one to Friday', () => {
|
||||
const panel = buildRandomPanel(20261129, VAULT_CUTOFF);
|
||||
const actual = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
const usId = 100;
|
||||
const caId = 107;
|
||||
const dates = actual.input.sessionDates;
|
||||
const usDates = actual.input.events.filter(e => e.entityId === usId).map(e => dates[e.dayIndex]);
|
||||
const caDates = actual.input.events.filter(e => e.entityId === caId).map(e => dates[e.dayIndex]);
|
||||
expect(usDates).toContain('2022-11-28');
|
||||
expect(caDates).toContain('2022-11-25');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildEventStudyInput QA — truncation (prefix stability) across Vault cutoffs', () => {
|
||||
it('earlier-cutoff output is an exact prefix of later-cutoff output (no future-dependent values)', () => {
|
||||
const panel = buildRandomPanel(31337, null);
|
||||
const cutoffs = ['2022-11-25', '2022-12-27', '2023-01-17', '2023-02-21'];
|
||||
const results = cutoffs.map(vaultCutoffDate =>
|
||||
buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
})
|
||||
);
|
||||
|
||||
for (let i = 0; i + 1 < results.length; i += 1) {
|
||||
const early = results[i]!.input;
|
||||
const late = results[i + 1]!.input;
|
||||
const n = early.sessionDates.length;
|
||||
expect(n).toBeGreaterThan(0);
|
||||
expect(late.sessionDates.slice(0, n)).toEqual([...early.sessionDates]);
|
||||
for (const [id, series] of early.entityReturns) {
|
||||
const lateSeries = late.entityReturns.get(id)!;
|
||||
expect(nanSafe(Array.from(lateSeries).slice(0, n))).toEqual(nanSafe(series));
|
||||
}
|
||||
expect(nanSafe(Array.from(late.benchmarkReturns!).slice(0, n))).toEqual(
|
||||
nanSafe(early.benchmarkReturns!)
|
||||
);
|
||||
const lateKeys = new Set(late.events.map(e => `${e.entityId}@${e.dayIndex}`));
|
||||
for (const ev of early.events) {
|
||||
expect(lateKeys.has(`${ev.entityId}@${ev.dayIndex}`)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('a poisoned future (absurd closes, extra filings, calendar tail) leaves pre-cutoff output byte-identical', () => {
|
||||
const cutoff = '2023-01-17';
|
||||
const panel = buildRandomPanel(555, null);
|
||||
const base = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
|
||||
const cutoffMs = makeUtcMs(cutoff, 0);
|
||||
const poisonedBars = panel.bars.map(b =>
|
||||
b.ts >= cutoffMs ? makeBar(b.listingId, b.ts, b.close * 1_000_000) : b
|
||||
);
|
||||
const poisonedEvents: EventObservation[] = [
|
||||
...panel.events,
|
||||
...[100, 107, 114].map(listingId => ({
|
||||
listingId,
|
||||
knownAt: cutoffMs,
|
||||
kind: 'filing' as const,
|
||||
subtype: 'poison',
|
||||
})),
|
||||
];
|
||||
const result = buildEventStudyInput({
|
||||
bars: poisonedBars,
|
||||
events: poisonedEvents,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
|
||||
expect(result.input.sessionDates).toEqual(base.input.sessionDates);
|
||||
expect(result.input.events).toEqual(base.input.events);
|
||||
for (const [id, series] of base.input.entityReturns) {
|
||||
expect(nanSafe(result.input.entityReturns.get(id)!)).toEqual(nanSafe(series));
|
||||
}
|
||||
expect(nanSafe(result.input.benchmarkReturns!)).toEqual(nanSafe(base.input.benchmarkReturns!));
|
||||
expect(result.diagnostics.vaultExcludedEvents).toBe(base.diagnostics.vaultExcludedEvents + 3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildEventStudyInput QA — calendar input forms and exact-close boundaries', () => {
|
||||
it('treats plain-object calendars/mappings identically to Maps', () => {
|
||||
const panel = buildRandomPanel(8080, null);
|
||||
const cutoff = '2023-02-01';
|
||||
const cals = panel.calendars.calendars as ReadonlyMap<string, readonly ExchangeSessionClose[]>;
|
||||
const mapping = panel.calendars.listingCalendarId as ReadonlyMap<number, string>;
|
||||
const asMaps = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: panel.calendars,
|
||||
});
|
||||
const asRecords = buildEventStudyInput({
|
||||
bars: panel.bars,
|
||||
events: panel.events,
|
||||
vaultCutoffDate: cutoff,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: {
|
||||
calendars: Object.fromEntries(cals),
|
||||
listingCalendarId: Object.fromEntries(mapping),
|
||||
},
|
||||
});
|
||||
expect(asRecords.input.events).toEqual(asMaps.input.events);
|
||||
expect(asRecords.diagnostics).toEqual(asMaps.diagnostics);
|
||||
for (const [id, series] of asMaps.input.entityReturns) {
|
||||
expect(nanSafe(asRecords.input.entityReturns.get(id)!)).toEqual(nanSafe(series));
|
||||
}
|
||||
});
|
||||
|
||||
it('anchors knownAt == close to that session and close + 1 ms to the next (half-day close included)', () => {
|
||||
const dates = ['2022-11-22', '2022-11-23', '2022-11-25', '2022-11-28'];
|
||||
const xnys = dates.map(date => ({
|
||||
date,
|
||||
closeTs: makeUtcMs(date, NYSE_HALF_DAYS.has(date) ? 18 : 21),
|
||||
}));
|
||||
const bars = dates.map((date, i) => makeBar(1, makeUtcMs(date, 21), 10 + i));
|
||||
const halfClose = makeUtcMs('2022-11-25', 18);
|
||||
const result = buildEventStudyInput({
|
||||
bars,
|
||||
events: [
|
||||
{ listingId: 1, knownAt: halfClose, kind: 'filing', subtype: '10-q' },
|
||||
{ listingId: 1, knownAt: halfClose + 1, kind: 'filing', subtype: '10-q' },
|
||||
// Thanksgiving (NYSE closed) intraday -> Friday half-day session.
|
||||
{ listingId: 1, knownAt: makeUtcMs('2022-11-24', 15), kind: 'filing', subtype: '10-q' },
|
||||
],
|
||||
vaultCutoffDate: '2022-12-01',
|
||||
exchangeCalendars: { calendars: { XNYS: xnys }, listingCalendarId: { 1: 'XNYS' } },
|
||||
});
|
||||
expect(result.input.events).toEqual([
|
||||
{ entityId: 1, dayIndex: 2 },
|
||||
{ entityId: 1, dayIndex: 3 },
|
||||
]);
|
||||
expect(result.diagnostics.duplicateEvents).toBe(1);
|
||||
// Wed -> Fri is consecutive on the NYSE calendar (Thanksgiving closed), so Friday's return is valid.
|
||||
expect(result.input.entityReturns.get(1)![2]).toBeCloseTo(12 / 11 - 1, 15);
|
||||
});
|
||||
});
|
||||
|
||||
function createInMemoryTrialExecutor(): { executor: TrialLedgerExecutor; rows: Record<string, unknown>[] } {
|
||||
const rows: Record<string, unknown>[] = [];
|
||||
let nextTrialId = 1;
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
const p = params ?? [];
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
const trialId = String(nextTrialId++);
|
||||
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, Number(trialId)));
|
||||
const stored = {
|
||||
trial_id: trialId,
|
||||
created_at: createdAt,
|
||||
principal_id: p[0],
|
||||
campaign_id: p[1] ?? null,
|
||||
stage: p[2],
|
||||
universe_market: p[3],
|
||||
horizon_bucket: p[4],
|
||||
hypothesis_id: p[5] ?? null,
|
||||
expression_hash: p[6],
|
||||
sample_start: p[7],
|
||||
sample_end: p[8],
|
||||
n_obs: p[9],
|
||||
sharpe_unann: p[10],
|
||||
skewness: p[11],
|
||||
kurtosis: p[12],
|
||||
daily_series: (p[13] as readonly number[]).map(v => Math.fround(v)),
|
||||
};
|
||||
rows.push(stored);
|
||||
return { rows: [{ trial_id: trialId, created_at: createdAt } as unknown as Row], rowCount: 1 };
|
||||
}
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const matched = rows.filter(r => r.trial_id === String(p[0]));
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const matched = rows.filter(r => r.universe_market === p[0] && r.horizon_bucket === p[1]);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
return { executor, rows };
|
||||
}
|
||||
|
||||
describe('buildEventStudyInput QA — half-day filing reaches runEventStudy eventCars on Monday', () => {
|
||||
it('keeps the NYSE Black Friday filing in study.eventCars dated Monday with the expected benchmark-adjusted CAR', async () => {
|
||||
const rand = createSeededRng(20261129);
|
||||
const dates = makeBusinessDates('2022-10-03', 90);
|
||||
const { xnys, xtse } = buildCalendars(dates);
|
||||
const vaultCutoffDate = dates[80]!;
|
||||
const usIds = [11, 12, 13, 14];
|
||||
const caIds = [21, 22, 23, 24];
|
||||
const bars: BarRecord[] = [];
|
||||
const listingCalendarId = new Map<number, string>();
|
||||
for (const [ids, cal, calId] of [
|
||||
[usIds, xnys, 'XNYS'],
|
||||
[caIds, xtse, 'XTSE'],
|
||||
] as const) {
|
||||
for (const id of ids) {
|
||||
listingCalendarId.set(id, calId);
|
||||
let price = 30 + id;
|
||||
for (const s of cal) {
|
||||
price *= 1 + (rand() * 2 - 1) * 0.015;
|
||||
bars.push(makeBar(id, makeUtcMs(s.date, regularCloseHourUtc(s.date)), price));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Regular after-close filings every 5 sessions in windows that avoid cross-border holidays,
|
||||
// plus the 14:00 ET Black Friday filing for listing 11 (after NYSE's 13:00 ET close).
|
||||
const events: EventObservation[] = [];
|
||||
for (let t = 3; t < 75; t += 5) {
|
||||
const date = dates[t]!;
|
||||
for (const id of [...usIds, ...caIds]) {
|
||||
if ((t + id) % 3 === 0) {
|
||||
events.push({ listingId: id, knownAt: makeUtcMs(date, 23), kind: 'filing', subtype: '10-q' });
|
||||
}
|
||||
}
|
||||
}
|
||||
events.push({ listingId: 11, knownAt: makeUtcMs('2022-11-25', 19), kind: 'filing', subtype: '10-q' });
|
||||
|
||||
const built = buildEventStudyInput({
|
||||
bars,
|
||||
events,
|
||||
vaultCutoffDate,
|
||||
benchmark: 'equal_weight',
|
||||
exchangeCalendars: { calendars: { XNYS: xnys, XTSE: xtse }, listingCalendarId },
|
||||
});
|
||||
|
||||
const postDays = 3;
|
||||
const ledger = createInMemoryTrialExecutor();
|
||||
const result = await runEventStudy(ledger.executor, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'US_CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'qa_half_day_filing_event_study',
|
||||
params: { preDays: 0, postDays },
|
||||
universe: 'US_CA_EQ_QA',
|
||||
horizon: '3d',
|
||||
},
|
||||
input: built.input,
|
||||
options: { preDays: 0, postDays, minEvents: 5 },
|
||||
vaultCutoffDate,
|
||||
});
|
||||
|
||||
expect(result.status).toBe('ok');
|
||||
if (result.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
expect(ledger.rows).toHaveLength(1);
|
||||
|
||||
const cars = result.study.eventCars;
|
||||
const usHalfDayIdx = cars.entityIds.findIndex((id, i) => id === 11 && cars.dates[i] === '2022-11-28');
|
||||
expect(usHalfDayIdx).toBeGreaterThanOrEqual(0);
|
||||
expect(cars.entityIds.some((id, i) => id === 11 && cars.dates[i] === '2022-11-25')).toBe(false);
|
||||
|
||||
const sessionDates = built.input.sessionDates;
|
||||
const d = sessionDates.indexOf('2022-11-28');
|
||||
expect(cars.dayIndices[usHalfDayIdx]).toBe(d);
|
||||
const r = built.input.entityReturns.get(11)!;
|
||||
const b = built.input.benchmarkReturns!;
|
||||
let expectedCar = 0;
|
||||
for (let k = 0; k <= postDays; k += 1) {
|
||||
expectedCar += (r[d + k] as number) - (b[d + k] as number);
|
||||
}
|
||||
expect(cars.cars[usHalfDayIdx]!).toBeCloseTo(expectedCar, 12);
|
||||
expect(Number.isFinite(result.deflatedSharpe.dsr ?? Number.NaN)).toBe(true);
|
||||
});
|
||||
});
|
||||
1181
libs/research/test/event-panel.test.ts
Normal file
1181
libs/research/test/event-panel.test.ts
Normal file
File diff suppressed because it is too large
Load diff
420
libs/research/test/market-data-store-duckdb-universe.qa.test.ts
Normal file
420
libs/research/test/market-data-store-duckdb-universe.qa.test.ts
Normal file
|
|
@ -0,0 +1,420 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
createDuckDbMarketDataStore,
|
||||
MarketDataStoreValidationError,
|
||||
planBars1dQuery,
|
||||
planUniverseQuery,
|
||||
resolveDuckDbConnectionBudget,
|
||||
UNIVERSE_REFS,
|
||||
VaultHoldoutFenceError,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type DuckDbPlanContext,
|
||||
type TableRow,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
// QA edge cases for T-122 (`universe` planner + adapter) not pinned by the primary suite.
|
||||
|
||||
const ROOT = '/data/curated';
|
||||
const CUTOFF_MS = Date.UTC(2026, 4, 28); // 2026-05-28T00:00:00.000Z
|
||||
const CTX: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: CUTOFF_MS };
|
||||
const DAY_MS = 86_400_000;
|
||||
|
||||
interface Recorder {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly log: Array<{ kind: 'run' | 'query'; sql: string; params?: readonly DuckDbParam[] }>;
|
||||
}
|
||||
|
||||
function recorder(
|
||||
onQuery: (
|
||||
sql: string,
|
||||
params: readonly DuckDbParam[]
|
||||
) => Promise<readonly TableRow[]> | readonly TableRow[] = () => [],
|
||||
onRun: (sql: string) => Promise<void> | void = () => {}
|
||||
): Recorder {
|
||||
const log: Recorder['log'] = [];
|
||||
return {
|
||||
log,
|
||||
executor: {
|
||||
async run(sql) {
|
||||
log.push({ kind: 'run', sql });
|
||||
await onRun(sql);
|
||||
},
|
||||
async query(sql, params) {
|
||||
log.push({ kind: 'query', sql, params: [...params] });
|
||||
return onQuery(sql, params);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function mulberry32(seed: number): () => number {
|
||||
let a = seed >>> 0;
|
||||
return () => {
|
||||
a = (a + 0x6d2b79f5) >>> 0;
|
||||
let t = a;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function isoDate(ms: number): string {
|
||||
return new Date(ms).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
interface FixtureBar {
|
||||
readonly listing_id: number;
|
||||
readonly currency: 'USD' | 'CAD';
|
||||
readonly session_date: string;
|
||||
readonly ts: string; // microsecond UTC ISO, same format the planner binds
|
||||
readonly known_at: string;
|
||||
}
|
||||
|
||||
function bar(
|
||||
listingId: number,
|
||||
currency: 'USD' | 'CAD',
|
||||
sessionDate: string,
|
||||
knownAt?: string
|
||||
): FixtureBar {
|
||||
return {
|
||||
listing_id: listingId,
|
||||
currency,
|
||||
session_date: sessionDate,
|
||||
ts: `${sessionDate}T20:00:00.000000Z`,
|
||||
known_at: knownAt ?? `${sessionDate}T22:00:00.000000Z`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory evaluator for the planned universe SQL: applies the bound predicates
|
||||
* positionally (currency list, session_date bounds, ts bound, known_at bound) to a
|
||||
* fixture `bars_1d` table and returns DISTINCT listing_id ASC, the way DuckDB would.
|
||||
* Fixed-width ISO strings compare chronologically, matching DuckDB's typed compare.
|
||||
*/
|
||||
function evaluatingExecutor(bars: readonly FixtureBar[]): Recorder {
|
||||
return recorder((sql, params) => {
|
||||
const inMatch = /b\.currency IN \(([?, ]+)\)/.exec(sql);
|
||||
const currencyCount = inMatch === null ? 1 : (inMatch[1] ?? '').split('?').length - 1;
|
||||
expect(sql).toContain(
|
||||
currencyCount === 1 && inMatch === null ? 'b.currency = ?' : 'b.currency IN ('
|
||||
);
|
||||
const currencies = params.slice(0, currencyCount) as string[];
|
||||
const [lo, hi, tsMax, knownMax] = params.slice(currencyCount) as string[];
|
||||
expect(params).toHaveLength(currencyCount + 4);
|
||||
const ids = new Set<number>();
|
||||
for (const b of bars) {
|
||||
if (
|
||||
currencies.includes(b.currency) &&
|
||||
b.session_date >= (lo as string) &&
|
||||
b.session_date <= (hi as string) &&
|
||||
b.ts <= (tsMax as string) &&
|
||||
b.known_at <= (knownMax as string)
|
||||
) {
|
||||
ids.add(b.listing_id);
|
||||
}
|
||||
}
|
||||
return [...ids].sort((a, b) => a - b).map(listing_id => ({ listing_id }));
|
||||
});
|
||||
}
|
||||
|
||||
describe('T-122 QA: survivorship-free, no-look-ahead semantics over a fixture bars_1d table', () => {
|
||||
const BARS: FixtureBar[] = [
|
||||
// 101: US listing delisted after 2025-03-10.
|
||||
bar(101, 'USD', '2025-03-03'),
|
||||
bar(101, 'USD', '2025-03-10'),
|
||||
// 102: US IPO on 2025-03-14 (future relative to 2025-03-12).
|
||||
bar(102, 'USD', '2025-03-14'),
|
||||
bar(102, 'USD', '2025-03-17'),
|
||||
// 201: CAD TSX line trading throughout.
|
||||
bar(201, 'CAD', '2025-03-05'),
|
||||
bar(201, 'CAD', '2025-03-12'),
|
||||
bar(201, 'CAD', '2025-03-19'),
|
||||
// 202: USD-quoted TSX line (provisional rule -> US_EQ).
|
||||
bar(202, 'USD', '2025-03-11'),
|
||||
// 301: only bar on 2025-03-12 was published (known_at) the next morning.
|
||||
bar(301, 'USD', '2025-03-12', '2025-03-13T09:30:00.000000Z'),
|
||||
// 302: bar known exactly at the last microsecond of 2025-03-12 -> included.
|
||||
bar(302, 'CAD', '2025-03-12', '2025-03-12T23:59:59.999999Z'),
|
||||
// 401: last bar exactly 7 days before 2025-03-12 (inclusive lower bound).
|
||||
bar(401, 'USD', '2025-03-05'),
|
||||
// 402: last bar 8 days before 2025-03-12 (outside default window).
|
||||
bar(402, 'CAD', '2025-03-04'),
|
||||
];
|
||||
|
||||
it('includes a delisted listing only while it traded and never includes a not-yet-listed IPO', async () => {
|
||||
const fx = evaluatingExecutor(BARS);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fx.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
|
||||
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-12' })).toEqual([101, 202, 401]);
|
||||
// 101 last traded 2025-03-10; window for 2025-03-17 is [03-10, 03-17] -> still included on the edge.
|
||||
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-17' })).toEqual([
|
||||
101, 102, 202, 301,
|
||||
]);
|
||||
// One day later 101 drops out (delisted), 102 remains.
|
||||
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-18' })).toEqual([102, 202, 301]);
|
||||
});
|
||||
|
||||
it('excludes bars published after the end of date (known_at fence) and includes the last-microsecond publication', async () => {
|
||||
const fx = evaluatingExecutor(BARS);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fx.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
|
||||
const us = await store.universe({ ref: 'US_EQ', date: '2025-03-12' });
|
||||
expect(us).not.toContain(301);
|
||||
// Next day the restated bar is known -> 301 is active.
|
||||
expect(await store.universe({ ref: 'US_EQ', date: '2025-03-13' })).toContain(301);
|
||||
|
||||
expect(await store.universe({ ref: 'CA_EQ', date: '2025-03-12' })).toEqual([201, 302]);
|
||||
});
|
||||
|
||||
it('applies the provisional bar-currency membership rule and an inclusive 7-day lower bound', async () => {
|
||||
const fx = evaluatingExecutor(BARS);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: fx.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
|
||||
const ca = await store.universe({ ref: 'CA_EQ', date: '2025-03-12' });
|
||||
const us = await store.universe({ ref: 'US_EQ', date: '2025-03-12' });
|
||||
const both = await store.universe({ ref: 'US_CA_EQ', date: '2025-03-12' });
|
||||
|
||||
expect(us).toContain(202); // USD-quoted TSX line lands in US_EQ
|
||||
expect(ca).not.toContain(202);
|
||||
expect(us).toContain(401); // exactly date - 7 days
|
||||
expect(ca).not.toContain(402); // date - 8 days
|
||||
expect(both).toEqual([...new Set([...us, ...ca])].sort((a, b) => a - b));
|
||||
|
||||
// A wider custom lookback picks up the 8-day-old listing and nothing else changes.
|
||||
const wide = createDuckDbMarketDataStore({
|
||||
executor: evaluatingExecutor(BARS).executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
universeLookbackDays: 8,
|
||||
});
|
||||
expect(await wide.universe({ ref: 'CA_EQ', date: '2025-03-12' })).toEqual([201, 302, 402]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-122 QA: store/planner parity and adapter error paths', () => {
|
||||
it('sends exactly the planUniverseQuery SQL and params for default and custom store lookbacks', async () => {
|
||||
for (const lookback of [undefined, 1, 30]) {
|
||||
const rec = recorder();
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
...(lookback === undefined ? {} : { universeLookbackDays: lookback }),
|
||||
});
|
||||
for (const ref of UNIVERSE_REFS) {
|
||||
await store.universe({ ref, date: '2025-11-03' });
|
||||
const expected = planUniverseQuery(
|
||||
{ ref, date: '2025-11-03' },
|
||||
lookback === undefined ? CTX : { ...CTX, universeLookbackDays: lookback }
|
||||
);
|
||||
const last = rec.log[rec.log.length - 1];
|
||||
expect(last?.kind).toBe('query');
|
||||
expect(last?.sql).toBe(expected.sql);
|
||||
expect(last?.params).toEqual(expected.params);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('runs the budget SET statements once and before any query under concurrent first universe calls', async () => {
|
||||
const env = { STOCKBOT_DUCKDB_THREADS: '3', STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB' };
|
||||
const rec = recorder(
|
||||
() => [{ listing_id: 1 }],
|
||||
() => new Promise<void>(resolve => setTimeout(resolve, 0))
|
||||
);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env,
|
||||
});
|
||||
|
||||
const results = await Promise.all([
|
||||
store.universe({ ref: 'US_EQ', date: '2025-06-02' }),
|
||||
store.universe({ ref: 'CA_EQ', date: '2025-06-02' }),
|
||||
store.universe({ ref: 'US_CA_EQ', date: '2025-06-02' }),
|
||||
]);
|
||||
|
||||
expect(results).toEqual([[1], [1], [1]]);
|
||||
expect(rec.log.map(e => e.kind)).toEqual(['run', 'run', 'run', 'query', 'query', 'query']);
|
||||
expect(rec.log.slice(0, 3).map(e => e.sql)).toEqual([
|
||||
...resolveDuckDbConnectionBudget(env).statements,
|
||||
]);
|
||||
});
|
||||
|
||||
it('propagates executor query errors unchanged and retries budget init after a failed SET', async () => {
|
||||
const boom = new Error('duckdb io error');
|
||||
const failingQuery = recorder(() => Promise.reject(boom));
|
||||
const s1 = createDuckDbMarketDataStore({
|
||||
executor: failingQuery.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
await expect(s1.universe({ ref: 'US_EQ', date: '2025-06-02' })).rejects.toBe(boom);
|
||||
|
||||
let failFirstRun = true;
|
||||
const flakyRun = recorder(
|
||||
() => [{ listing_id: 7 }],
|
||||
() => {
|
||||
if (failFirstRun) {
|
||||
failFirstRun = false;
|
||||
throw new Error('SET failed');
|
||||
}
|
||||
}
|
||||
);
|
||||
const s2 = createDuckDbMarketDataStore({
|
||||
executor: flakyRun.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
await expect(s2.universe({ ref: 'US_EQ', date: '2025-06-02' })).rejects.toThrow('SET failed');
|
||||
expect(flakyRun.log.some(e => e.kind === 'query')).toBe(false);
|
||||
expect(await s2.universe({ ref: 'US_EQ', date: '2025-06-02' })).toEqual([7]);
|
||||
});
|
||||
|
||||
it('returns a fresh array per call and does not mutate the caller query object', async () => {
|
||||
const rows: TableRow[] = [{ listing_id: 3 }, { listing_id: 9 }];
|
||||
const rec = recorder(() => rows);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
});
|
||||
const q = Object.freeze({ ref: 'US_CA_EQ', date: '2025-06-02' });
|
||||
|
||||
const first = await store.universe(q);
|
||||
first.push(99);
|
||||
const second = await store.universe(q);
|
||||
|
||||
expect(second).toEqual([3, 9]);
|
||||
expect(q).toEqual({ ref: 'US_CA_EQ', date: '2025-06-02' });
|
||||
expect(rows).toEqual([{ listing_id: 3 }, { listing_id: 9 }]);
|
||||
});
|
||||
|
||||
it('rejects a store-level universeLookbackDays at construction without touching the executor', () => {
|
||||
const rec = recorder();
|
||||
expect(() =>
|
||||
createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
universeLookbackDays: -7,
|
||||
})
|
||||
).toThrow(MarketDataStoreValidationError);
|
||||
expect(rec.log).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-122 QA: seeded fence and lookback invariants', () => {
|
||||
it('holds lookback arithmetic and Vault bounds across 600 seeded (date, lookback, ref, cutoff) cases', async () => {
|
||||
const rng = mulberry32(20261129);
|
||||
const baseMs = Date.UTC(2004, 0, 1);
|
||||
let fencedCount = 0;
|
||||
let plannedCount = 0;
|
||||
|
||||
for (let i = 0; i < 600; i += 1) {
|
||||
// Cutoff anywhere in 2020..2027, sometimes mid-day.
|
||||
const cutoffDayMs = Date.UTC(2020, 0, 1) + Math.floor(rng() * 8 * 365) * DAY_MS;
|
||||
const cutoffMs = rng() < 0.5 ? cutoffDayMs : cutoffDayMs + Math.floor(rng() * DAY_MS);
|
||||
const dateMs = baseMs + Math.floor(rng() * 24 * 365) * DAY_MS;
|
||||
const date = isoDate(dateMs);
|
||||
const lookback = 1 + Math.floor(rng() * 400);
|
||||
const ref = UNIVERSE_REFS[Math.floor(rng() * UNIVERSE_REFS.length)] ?? 'US_EQ';
|
||||
const ctx: DuckDbPlanContext = {
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: cutoffMs,
|
||||
universeLookbackDays: lookback,
|
||||
};
|
||||
|
||||
if (dateMs >= cutoffMs) {
|
||||
fencedCount += 1;
|
||||
expect(() => planUniverseQuery({ ref, date }, ctx)).toThrow(VaultHoldoutFenceError);
|
||||
// Same class bars uses for a vault_fenced range starting on that date.
|
||||
expect(() =>
|
||||
planBars1dQuery(
|
||||
{ listingIds: [1], timeframe: '1d', from: date, to: date, adjustment: 'raw' },
|
||||
ctx
|
||||
)
|
||||
).toThrow(VaultHoldoutFenceError);
|
||||
const rec = recorder();
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: cutoffMs,
|
||||
});
|
||||
await expect(store.universe({ ref, date })).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
||||
expect(rec.log).toHaveLength(0);
|
||||
continue;
|
||||
}
|
||||
|
||||
plannedCount += 1;
|
||||
const planned = planUniverseQuery({ ref, date }, ctx);
|
||||
const n = ref === 'US_CA_EQ' ? 2 : 1;
|
||||
expect(planned.params).toHaveLength(n + 4);
|
||||
const [lo, hi, tsMax, knownMax] = planned.params.slice(n) as string[];
|
||||
expect(lo).toBe(isoDate(dateMs - lookback * DAY_MS));
|
||||
expect(hi).toBe(date);
|
||||
const endOfDateMs = dateMs + DAY_MS - 1;
|
||||
const expectedUpperMs = Math.min(endOfDateMs, cutoffMs - 1);
|
||||
expect(Date.parse(tsMax as string)).toBe(expectedUpperMs);
|
||||
expect(tsMax).toBe(knownMax);
|
||||
expect(Date.parse(tsMax as string)).toBeLessThan(cutoffMs);
|
||||
// Never reads past the end of `date`.
|
||||
expect((tsMax as string).slice(0, 10)).toBe(date);
|
||||
expect(planned.fenced.clampedTo).toBe(endOfDateMs >= cutoffMs);
|
||||
expect(planned.sql).not.toContain(date);
|
||||
expect(planned.sql).not.toContain(lo as string);
|
||||
}
|
||||
|
||||
// Both branches must actually be exercised by the seed.
|
||||
expect(fencedCount).toBeGreaterThan(50);
|
||||
expect(plannedCount).toBeGreaterThan(50);
|
||||
});
|
||||
|
||||
it('clamps to the first microsecond window when the cutoff is 1 ms after midnight of date', () => {
|
||||
const cutoff = Date.UTC(2025, 2, 12, 0, 0, 0, 1);
|
||||
const planned = planUniverseQuery(
|
||||
{ ref: 'US_EQ', date: '2025-03-12' },
|
||||
{ curatedRoot: ROOT, vaultCutoffTs: cutoff }
|
||||
);
|
||||
expect(planned.params).toEqual([
|
||||
'USD',
|
||||
'2025-03-05',
|
||||
'2025-03-12',
|
||||
'2025-03-12T00:00:00.000999Z',
|
||||
'2025-03-12T00:00:00.000999Z',
|
||||
]);
|
||||
expect(planned.fenced.clampedTo).toBe(true);
|
||||
expect(planned.fenced.clampedAsOf).toBe(true);
|
||||
});
|
||||
|
||||
it('produces identical SQL and params under TZ=UTC and TZ=America/Toronto', () => {
|
||||
const prev = process.env.TZ;
|
||||
try {
|
||||
process.env.TZ = 'UTC';
|
||||
const a = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-03-09' }, CTX); // DST switch in Toronto
|
||||
process.env.TZ = 'America/Toronto';
|
||||
const b = planUniverseQuery({ ref: 'US_CA_EQ', date: '2025-03-09' }, CTX);
|
||||
expect(b).toEqual(a);
|
||||
expect(a.params[2]).toBe('2025-03-02');
|
||||
} finally {
|
||||
if (prev === undefined) {
|
||||
delete process.env.TZ;
|
||||
} else {
|
||||
process.env.TZ = prev;
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
318
libs/research/test/market-data-store-duckdb.qa.test.ts
Normal file
318
libs/research/test/market-data-store-duckdb.qa.test.ts
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
AdjFactorsSnapshotError,
|
||||
type BarBatch,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type DuckDbPlanContext,
|
||||
MarketDataStoreValidationError,
|
||||
type TableRow,
|
||||
VaultHoldoutFenceError,
|
||||
createDuckDbMarketDataStore,
|
||||
planBars1dQuery,
|
||||
planEventsQuery,
|
||||
planFx1dQuery,
|
||||
planShortsAsOfQuery,
|
||||
resolveDuckDbConnectionBudget,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
// QA edge cases for T-119 that the primary suite does not pin down.
|
||||
|
||||
const ROOT = '/data/curated';
|
||||
const CUTOFF_MS = Date.UTC(2026, 4, 28); // 2026-05-28T00:00:00.000Z
|
||||
const CTX: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: CUTOFF_MS };
|
||||
const BUDGET_ENV = { STOCKBOT_DUCKDB_THREADS: '3', STOCKBOT_DUCKDB_MEMORY_LIMIT: '2GB' };
|
||||
|
||||
interface Recorder {
|
||||
readonly executor: DuckDbExecutor;
|
||||
readonly log: Array<{ kind: 'run' | 'query'; sql: string; params?: readonly DuckDbParam[] }>;
|
||||
}
|
||||
|
||||
function recorder(
|
||||
onQuery: (sql: string, params: readonly DuckDbParam[]) => readonly TableRow[] = () => []
|
||||
): Recorder {
|
||||
const log: Recorder['log'] = [];
|
||||
return {
|
||||
log,
|
||||
executor: {
|
||||
async run(sql) {
|
||||
log.push({ kind: 'run', sql });
|
||||
},
|
||||
async query(sql, params) {
|
||||
log.push({ kind: 'query', sql, params: [...params] });
|
||||
return onQuery(sql, params);
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fencedKv(asOfMicros: number | null, vaultCutoffMicros: number | null): TableRow[] {
|
||||
return [
|
||||
{ key: 'stock_bot.adj_factors.format_version', value: '1' },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_kind', value: 'point_in_time_fenced' },
|
||||
{ key: 'stock_bot.adj_factors.as_of_micros', value: asOfMicros === null ? 'none' : String(asOfMicros) },
|
||||
{
|
||||
key: 'stock_bot.adj_factors.vault_cutoff_micros',
|
||||
value: vaultCutoffMicros === null ? 'none' : String(vaultCutoffMicros),
|
||||
},
|
||||
{ key: 'stock_bot.adj_factors.rows_written', value: '2' },
|
||||
{ key: 'stock_bot.adj_factors.snapshot_checksum', value: '0x0123456789abcdef' },
|
||||
];
|
||||
}
|
||||
|
||||
async function drain(it: AsyncIterable<BarBatch>): Promise<BarBatch[]> {
|
||||
const out: BarBatch[] = [];
|
||||
for await (const b of it) {
|
||||
out.push(b);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe('T-119 QA: listingIds boundaries and caller-input immutability', () => {
|
||||
it('accepts exact INT32 bounds and binds them as numbers, never in SQL text', () => {
|
||||
const planned = planBars1dQuery(
|
||||
{
|
||||
listingIds: [-2_147_483_648, 2_147_483_647],
|
||||
timeframe: '1d',
|
||||
from: '2025-01-02',
|
||||
to: '2025-01-03',
|
||||
adjustment: 'raw',
|
||||
},
|
||||
CTX
|
||||
);
|
||||
|
||||
expect(planned.params.slice(0, 2)).toEqual([-2_147_483_648, 2_147_483_647]);
|
||||
expect(planned.sql).not.toContain('2147483647');
|
||||
expect(planned.sql).not.toContain('2147483648');
|
||||
expect(planned.sql).toContain('b.listing_id IN (?, ?)');
|
||||
});
|
||||
|
||||
it('deduplicates frozen listingIds and kinds (including -0 vs 0) without mutating caller arrays', () => {
|
||||
const listingIds = Object.freeze([7, 0, -0, 7, 9]);
|
||||
const kinds = Object.freeze(['filing', 'earnings', 'filing'] as const);
|
||||
|
||||
const planned = planEventsQuery(
|
||||
{ kinds: [...kinds], listingIds: listingIds as number[], from: '2025-01-02', to: '2025-01-03' },
|
||||
CTX
|
||||
);
|
||||
|
||||
expect(listingIds).toEqual([7, 0, -0, 7, 9]);
|
||||
expect(planned.sql).toContain('e.kind IN (?, ?) AND e.listing_id IN (?, ?, ?)');
|
||||
expect(planned.params.slice(0, 5)).toEqual(['filing', 'earnings', 7, 0, 9]);
|
||||
expect(Object.is(planned.params[3], 0)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: timestamp precision and offsets', () => {
|
||||
it('preserves explicit microsecond from/to/asOf digits and normalises offsets to UTC', () => {
|
||||
const planned = planBars1dQuery(
|
||||
{
|
||||
listingIds: [1],
|
||||
timeframe: '1d',
|
||||
from: '2025-01-02T09:30:00.123456-05:00',
|
||||
to: '2025-01-03T16:00:00.654321-05:00',
|
||||
asOf: '2025-01-03T21:00:00.000001Z',
|
||||
adjustment: 'raw',
|
||||
},
|
||||
CTX
|
||||
);
|
||||
|
||||
expect(planned.params).toEqual([
|
||||
1,
|
||||
'2025-01-02T14:30:00.123456Z',
|
||||
'2025-01-03T21:00:00.654321Z',
|
||||
'2025-01-03T21:00:00.000001Z',
|
||||
]);
|
||||
});
|
||||
|
||||
it('binds a single-millisecond window with explicit micros ordered correctly and rejects inverted micros', () => {
|
||||
const ok = planEventsQuery(
|
||||
{
|
||||
kinds: ['filing'],
|
||||
from: '2025-01-02T10:00:00.000100Z',
|
||||
to: '2025-01-02T10:00:00.000900Z',
|
||||
},
|
||||
CTX
|
||||
);
|
||||
expect(ok.params.slice(1, 3)).toEqual(['2025-01-02T10:00:00.000100Z', '2025-01-02T10:00:00.000900Z']);
|
||||
|
||||
expect(() =>
|
||||
planEventsQuery(
|
||||
{ kinds: ['filing'], from: '2025-01-02T10:00:00.000900Z', to: '2025-01-02T10:00:00.000100Z' },
|
||||
CTX
|
||||
)
|
||||
).toThrow(MarketDataStoreValidationError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: Vault bounds under a non-midnight cutoff', () => {
|
||||
// computeVaultCutoffTs preserves the time-of-day of the max ingested ts, so cutoffs need not be midnight.
|
||||
const cutoff = Date.UTC(2026, 4, 28, 14, 30, 0, 0);
|
||||
const ctx: DuckDbPlanContext = { curatedRoot: ROOT, vaultCutoffTs: cutoff };
|
||||
const cutoffMinusOneMicroIso = '2026-05-28T14:29:59.999999Z';
|
||||
|
||||
it('clamps bars/events/fx upper ts and known_at bounds to cutoff - 1µs', () => {
|
||||
const bars = planBars1dQuery(
|
||||
{ listingIds: [1], timeframe: '1d', from: '2026-05-01', to: '2026-12-31', asOf: '2027-01-01', adjustment: 'raw' },
|
||||
ctx
|
||||
);
|
||||
expect(bars.params.slice(-2)).toEqual([cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]);
|
||||
|
||||
const events = planEventsQuery({ kinds: ['ceo_post'], from: '2026-05-01', to: '2026-05-28' }, ctx);
|
||||
expect(events.params.slice(-2)).toEqual([cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]);
|
||||
|
||||
const fx = planFx1dQuery({ pair: 'USD.CAD', timeframe: '1d', from: '2026-05-01', to: '2026-06-30' }, ctx);
|
||||
expect(fx.params).toEqual(['USDCAD', '2026-05-01T00:00:00.000Z', cutoffMinusOneMicroIso, cutoffMinusOneMicroIso]);
|
||||
});
|
||||
|
||||
it('keeps shortsAsOf known_at strictly before the cutoff even when the report_date bound lands on the cutoff day', () => {
|
||||
const shorts = planShortsAsOfQuery({ listingIds: [5], from: '2026-05-01', to: '2026-09-01' }, ctx);
|
||||
|
||||
expect(shorts.params).toEqual([5, '2026-05-01', '2026-05-28', cutoffMinusOneMicroIso]);
|
||||
expect(shorts.fenced.toMs).toBe(cutoff - 1);
|
||||
expect(shorts.fenced.asOfMs).toBe(cutoff - 1);
|
||||
});
|
||||
|
||||
it('rejects from exactly at a non-midnight cutoff but accepts from one millisecond earlier', () => {
|
||||
expect(() =>
|
||||
planShortsAsOfQuery({ listingIds: [5], from: '2026-05-28T14:30:00Z', to: '2026-06-01' }, ctx)
|
||||
).toThrow(VaultHoldoutFenceError);
|
||||
const planned = planShortsAsOfQuery(
|
||||
{ listingIds: [5], from: '2026-05-28T14:29:59.999Z', to: '2026-06-01' },
|
||||
ctx
|
||||
);
|
||||
expect(planned.params.slice(1, 3)).toEqual(['2026-05-28', '2026-05-28']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: adapter immutable-path flow and budget ordering', () => {
|
||||
const IMMUTABLE = '/data/snapshots/adj_factors_2026-05-27.parquet';
|
||||
|
||||
it('runs env-derived budget SETs, then the footer query, then the bars query bound to the immutable path', async () => {
|
||||
const asOfMicros = CUTOFF_MS * 1000 - 1;
|
||||
const rec = recorder((sql) => {
|
||||
if (sql.includes('parquet_kv_metadata')) {
|
||||
return fencedKv(asOfMicros, CUTOFF_MS * 1000);
|
||||
}
|
||||
return [
|
||||
{ listing_id: 42, ts: Date.UTC(2025, 0, 2, 21), open: 50, high: 51, low: 49, close: 50, volume: 2000, vwap: null, known_at: Date.UTC(2025, 0, 2, 22) },
|
||||
];
|
||||
});
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
immutableAdjFactorsPath: IMMUTABLE,
|
||||
env: BUDGET_ENV,
|
||||
});
|
||||
|
||||
const batches = await drain(
|
||||
store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'split' })
|
||||
);
|
||||
|
||||
const budget = resolveDuckDbConnectionBudget(BUDGET_ENV).statements;
|
||||
expect(rec.log.map((c) => c.kind)).toEqual(['run', 'run', 'run', 'query', 'query']);
|
||||
expect(rec.log.slice(0, 3).map((c) => c.sql)).toEqual([...budget]);
|
||||
expect(rec.log[3]?.sql).toContain(`parquet_kv_metadata('${IMMUTABLE}')`);
|
||||
expect(rec.log[4]?.sql).toContain(`read_parquet('${IMMUTABLE}')`);
|
||||
expect(rec.log[4]?.sql).not.toContain(`${ROOT}/adj_factors/part.parquet`);
|
||||
expect(batches).toEqual([
|
||||
{
|
||||
rows: [
|
||||
{ listingId: 42, ts: Date.UTC(2025, 0, 2, 21), open: 50, high: 51, low: 49, close: 50, volume: 2000, vwap: null, knownAt: Date.UTC(2025, 0, 2, 22) },
|
||||
],
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails closed with incompatible_fence when the immutable snapshot fence differs from the query asOf, issuing no bars scan', async () => {
|
||||
const rec = recorder((sql) =>
|
||||
sql.includes('parquet_kv_metadata') ? fencedKv(Date.UTC(2025, 5, 30) * 1000, CUTOFF_MS * 1000) : []
|
||||
);
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
immutableAdjFactorsPath: IMMUTABLE,
|
||||
env: BUDGET_ENV,
|
||||
});
|
||||
|
||||
const err = await drain(
|
||||
store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'total' })
|
||||
).catch((e: unknown) => e);
|
||||
|
||||
expect(err).toBeInstanceOf(AdjFactorsSnapshotError);
|
||||
expect((err as AdjFactorsSnapshotError).code).toBe('incompatible_fence');
|
||||
expect(rec.log.filter((c) => c.kind === 'query')).toHaveLength(1);
|
||||
expect(rec.log.some((c) => c.sql.includes('bars_1d'))).toBe(false);
|
||||
});
|
||||
|
||||
it('does not run budget SETs when the first call fails validation, then runs them once on the next valid call', async () => {
|
||||
const rec = recorder();
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: BUDGET_ENV,
|
||||
});
|
||||
|
||||
await expect(
|
||||
store.events({ kinds: ['filing'], listingIds: [1.5], from: '2025-01-01', to: '2025-01-02' })
|
||||
).rejects.toBeInstanceOf(MarketDataStoreValidationError);
|
||||
expect(rec.log).toHaveLength(0);
|
||||
|
||||
await store.events({ kinds: ['filing'], from: '2025-01-01', to: '2025-01-02' });
|
||||
await store.fx({ pair: 'USD.CAD', timeframe: '1d', from: '2025-01-01', to: '2025-01-02' });
|
||||
expect(rec.log.map((c) => c.kind)).toEqual(['run', 'run', 'run', 'query', 'query']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-119 QA: pinned-artifact release failures', () => {
|
||||
it('propagates a release() failure after a successful scan and still releases exactly once', async () => {
|
||||
const asOfMicros = CUTOFF_MS * 1000 - 1;
|
||||
const rec = recorder((sql) => (sql.includes('parquet_kv_metadata') ? fencedKv(asOfMicros, CUTOFF_MS * 1000) : []));
|
||||
let releases = 0;
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: BUDGET_ENV,
|
||||
pinAdjFactorsArtifact: () => ({
|
||||
pinnedPath: '/proc/self/fd/17',
|
||||
release() {
|
||||
releases += 1;
|
||||
throw new Error('close failed');
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
const err = await drain(
|
||||
store.bars({ listingIds: [42], timeframe: '1d', from: '2025-01-01', to: '2025-01-31', adjustment: 'split' })
|
||||
).catch((e: unknown) => e);
|
||||
|
||||
expect((err as Error).message).toBe('close failed');
|
||||
expect(releases).toBe(1);
|
||||
expect(rec.log.filter((c) => c.kind === 'query').map((c) => c.sql.includes('/proc/self/fd/17'))).toEqual([true, true]);
|
||||
});
|
||||
|
||||
it('never calls the pinner for an adjusted query that fails the Vault fence', async () => {
|
||||
const rec = recorder();
|
||||
let pins = 0;
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: rec.executor,
|
||||
curatedRoot: ROOT,
|
||||
vaultCutoffTs: CUTOFF_MS,
|
||||
env: BUDGET_ENV,
|
||||
pinAdjFactorsArtifact: () => {
|
||||
pins += 1;
|
||||
return { pinnedPath: '/proc/self/fd/17', release() {} };
|
||||
},
|
||||
});
|
||||
|
||||
await expect(
|
||||
drain(store.bars({ listingIds: [42], timeframe: '1d', from: '2026-05-28', to: '2026-06-30', adjustment: 'split' }))
|
||||
).rejects.toBeInstanceOf(VaultHoldoutFenceError);
|
||||
expect(pins).toBe(0);
|
||||
expect(rec.log).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
2870
libs/research/test/market-data-store-duckdb.test.ts
Normal file
2870
libs/research/test/market-data-store-duckdb.test.ts
Normal file
File diff suppressed because it is too large
Load diff
403
libs/research/test/signal-panel-e2e.test.ts
Normal file
403
libs/research/test/signal-panel-e2e.test.ts
Normal file
|
|
@ -0,0 +1,403 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
analyzeSignal,
|
||||
buildForwardReturnPanel,
|
||||
collectBars,
|
||||
createDuckDbMarketDataStore,
|
||||
shortsTableToSignalRows,
|
||||
type DuckDbExecutor,
|
||||
type DuckDbParam,
|
||||
type TableRow,
|
||||
type TrialLedgerExecutor,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
const CURATED_ROOT = '/mnt/data/stockbot/curated';
|
||||
const SEED = 20261129;
|
||||
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = new Array(count);
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
let written = 0;
|
||||
while (written < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out[written] = current.toISOString().slice(0, 10);
|
||||
written += 1;
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeUtcMs(date: string, hourUtc: number): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
|
||||
}
|
||||
|
||||
interface StoredTrialRow {
|
||||
readonly trial_id: string;
|
||||
readonly created_at: Date;
|
||||
readonly principal_id: string;
|
||||
readonly campaign_id: string | null;
|
||||
readonly stage: string;
|
||||
readonly universe_market: string;
|
||||
readonly horizon_bucket: string;
|
||||
readonly hypothesis_id: string | null;
|
||||
readonly expression_hash: string;
|
||||
readonly sample_start: string;
|
||||
readonly sample_end: string;
|
||||
readonly n_obs: number;
|
||||
readonly sharpe_unann: number;
|
||||
readonly skewness: number;
|
||||
readonly kurtosis: number;
|
||||
readonly daily_series: readonly number[];
|
||||
}
|
||||
|
||||
function createInMemoryTrialExecutor(): {
|
||||
executor: TrialLedgerExecutor;
|
||||
rows: StoredTrialRow[];
|
||||
} {
|
||||
const rows: StoredTrialRow[] = [];
|
||||
let nextTrialId = 1;
|
||||
|
||||
const executor: TrialLedgerExecutor = {
|
||||
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
||||
const trimmed = text.trimStart();
|
||||
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
||||
const p = params ?? [];
|
||||
const trialId = nextTrialId++;
|
||||
const createdAt = new Date(Date.UTC(2024, 5, 1, 12, 0, trialId));
|
||||
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
||||
const stored: StoredTrialRow = {
|
||||
trial_id: String(trialId),
|
||||
created_at: createdAt,
|
||||
principal_id: p[0] as string,
|
||||
campaign_id: (p[1] as string | null) ?? null,
|
||||
stage: p[2] as string,
|
||||
universe_market: p[3] as string,
|
||||
horizon_bucket: p[4] as string,
|
||||
hypothesis_id: (p[5] as string | null) ?? null,
|
||||
expression_hash: p[6] as string,
|
||||
sample_start: p[7] as string,
|
||||
sample_end: p[8] as string,
|
||||
n_obs: p[9] as number,
|
||||
sharpe_unann: p[10] as number,
|
||||
skewness: p[11] as number,
|
||||
kurtosis: p[12] as number,
|
||||
daily_series: dailySeries,
|
||||
};
|
||||
rows.push(stored);
|
||||
return {
|
||||
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
||||
rowCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('SELECT')) {
|
||||
if (text.includes('WHERE trial_id = $1::bigint')) {
|
||||
const targetId = String(params?.[0]);
|
||||
const matched = rows.filter(r => r.trial_id === targetId);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
if (text.includes('WHERE universe_market = $1')) {
|
||||
const market = params?.[0] as string;
|
||||
const bucket = params?.[1] as string;
|
||||
const matched = rows.filter(
|
||||
r => r.universe_market === market && r.horizon_bucket === bucket
|
||||
);
|
||||
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
||||
}
|
||||
}
|
||||
|
||||
return { rows: [], rowCount: 0 };
|
||||
},
|
||||
};
|
||||
|
||||
return { executor, rows };
|
||||
}
|
||||
|
||||
interface CeoShortsFixture {
|
||||
readonly listingIds: number[];
|
||||
readonly allDates: string[];
|
||||
readonly vaultCutoffDate: string;
|
||||
readonly vaultCutoffTs: number;
|
||||
readonly barRows: TableRow[];
|
||||
readonly shortsRows: TableRow[];
|
||||
}
|
||||
|
||||
function buildCeoShortsFixture(poisonPostCutoff: boolean): CeoShortsFixture {
|
||||
const rand = createSeededRng(SEED);
|
||||
const listingCount = 28;
|
||||
const preCutoffSessions = 140; // spans late 2022 through early 2023 (pre-2023 & post-2023)
|
||||
const postCutoffSessions = 10;
|
||||
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
|
||||
const vaultCutoffDate = allDates[preCutoffSessions]!;
|
||||
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
|
||||
|
||||
const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i);
|
||||
const barRows: TableRow[] = [];
|
||||
const shortsRows: TableRow[] = [];
|
||||
|
||||
// Semi-monthly ceoShorts reports (every 10 trading sessions). Publication follows the CIRO
|
||||
// working assumption: 17:00 ET (22:00 UTC) four business days after `report_date`. A report
|
||||
// only drives prices from the session AFTER its publication close, so no close ever reflects
|
||||
// a report before its `known_at` (QA fix for the reviewer's look-ahead note).
|
||||
// Plant a negative relationship: higher net_change predicts lower subsequent 5-session return.
|
||||
const PUBLICATION_LAG_SESSIONS = 4;
|
||||
const activeNetChange = new Float64Array(listingCount);
|
||||
const pendingByPublishIdx = new Map<number, (number | null)[]>();
|
||||
const prices = new Float64Array(listingCount);
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
prices[l] = 10 + l * 1.5;
|
||||
}
|
||||
|
||||
for (let t = 0; t < allDates.length; t += 1) {
|
||||
const date = allDates[t]!;
|
||||
const closeTs = makeUtcMs(date, 21); // 16:00 ET close
|
||||
|
||||
// Reports published after the previous close become tradeable information today.
|
||||
const released = pendingByPublishIdx.get(t - 1);
|
||||
if (released !== undefined) {
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const v = released[l];
|
||||
if (v !== null && v !== undefined) {
|
||||
activeNetChange[l] = v / 20_000; // normalized in [-1, 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const publishIdx = t + PUBLICATION_LAG_SESSIONS;
|
||||
if (t % 10 === 0 && publishIdx < allDates.length) {
|
||||
const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4
|
||||
const pending: (number | null)[] = [];
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const isNullCell = t > 0 && (t + l) % 19 === 0;
|
||||
const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000);
|
||||
pending.push(netChange);
|
||||
shortsRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
report_date: date,
|
||||
known_at: reportKnownAt,
|
||||
shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000),
|
||||
net_change: netChange,
|
||||
pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)),
|
||||
source: 'ceoShorts',
|
||||
});
|
||||
}
|
||||
pendingByPublishIdx.set(publishIdx, pending);
|
||||
}
|
||||
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
// Drift driven negatively by prior known short-interest change + idiosyncratic noise.
|
||||
const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008;
|
||||
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
|
||||
|
||||
const isPostCutoff = date >= vaultCutoffDate;
|
||||
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6));
|
||||
barRows.push({
|
||||
listing_id: listingIds[l]!,
|
||||
ts: closeTs,
|
||||
open: closeVal,
|
||||
high: closeVal,
|
||||
low: closeVal,
|
||||
close: closeVal,
|
||||
volume: 50_000,
|
||||
vwap: closeVal,
|
||||
known_at: closeTs,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
listingIds,
|
||||
allDates,
|
||||
vaultCutoffDate,
|
||||
vaultCutoffTs,
|
||||
barRows,
|
||||
shortsRows,
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeDuckDbExecutor(fixture: CeoShortsFixture): {
|
||||
executor: DuckDbExecutor;
|
||||
runStatements: string[];
|
||||
queryCount: () => number;
|
||||
} {
|
||||
const runStatements: string[] = [];
|
||||
let queries = 0;
|
||||
|
||||
const executor: DuckDbExecutor = {
|
||||
async run(sql: string) {
|
||||
runStatements.push(sql);
|
||||
},
|
||||
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
|
||||
queries += 1;
|
||||
|
||||
if (sql.includes('bars_1d/year=*/part.parquet')) {
|
||||
// Bound params: [...listingIds, fromIso, toIso, asOfIso]
|
||||
const nIds = fixture.listingIds.length;
|
||||
const idSet = new Set<number>(params.slice(0, nIds) as number[]);
|
||||
const fromMs = Date.parse(params[nIds] as string);
|
||||
const toMs = Date.parse(params[nIds + 1] as string);
|
||||
const asOfMs = Date.parse(params[nIds + 2] as string);
|
||||
return fixture.barRows.filter(row => {
|
||||
const lid = row.listing_id as number;
|
||||
const ts = row.ts as number;
|
||||
const knownAt = row.known_at as number;
|
||||
return idSet.has(lid) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs;
|
||||
});
|
||||
}
|
||||
|
||||
if (sql.includes('shorts/part.parquet')) {
|
||||
// Bound params: [...listingIds, fromDate, toDate, asOfIso]
|
||||
const nIds = fixture.listingIds.length;
|
||||
const idSet = new Set<number>(params.slice(0, nIds) as number[]);
|
||||
const fromDate = params[nIds] as string;
|
||||
const toDate = params[nIds + 1] as string;
|
||||
const asOfMs = Date.parse(params[nIds + 2] as string);
|
||||
return fixture.shortsRows.filter(row => {
|
||||
const lid = row.listing_id as number;
|
||||
const reportDate = row.report_date as string;
|
||||
const knownAt = row.known_at as number;
|
||||
return idSet.has(lid) && reportDate >= fromDate && reportDate <= toDate && knownAt <= asOfMs;
|
||||
});
|
||||
}
|
||||
|
||||
throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`);
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
executor,
|
||||
runStatements,
|
||||
queryCount: () => queries,
|
||||
};
|
||||
}
|
||||
|
||||
describe('ceoShorts end-to-end signal study (headless, no database)', () => {
|
||||
async function runCeoShortsStudy(poisonPostCutoff: boolean) {
|
||||
const fixture = buildCeoShortsFixture(poisonPostCutoff);
|
||||
const duck = createFakeDuckDbExecutor(fixture);
|
||||
const ledger = createInMemoryTrialExecutor();
|
||||
|
||||
const store = createDuckDbMarketDataStore({
|
||||
executor: duck.executor,
|
||||
curatedRoot: CURATED_ROOT,
|
||||
vaultCutoffTs: fixture.vaultCutoffTs,
|
||||
barBatchSize: 256,
|
||||
});
|
||||
|
||||
const from = fixture.allDates[0]!;
|
||||
const to = fixture.allDates[fixture.allDates.length - 1]!;
|
||||
|
||||
const bars = await collectBars(
|
||||
store.bars({
|
||||
listingIds: fixture.listingIds,
|
||||
timeframe: '1d',
|
||||
from,
|
||||
to,
|
||||
adjustment: 'raw',
|
||||
})
|
||||
);
|
||||
const shortsTable = await store.shortsAsOf({
|
||||
listingIds: fixture.listingIds,
|
||||
from,
|
||||
to,
|
||||
});
|
||||
|
||||
const signals = shortsTableToSignalRows(shortsTable, 'net_change');
|
||||
const built = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: 5,
|
||||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
});
|
||||
|
||||
const studyResult = await analyzeSignal(ledger.executor, {
|
||||
principalId: 'operator',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expression: {
|
||||
expression: 'ceoshorts_net_change_5d',
|
||||
params: { field: 'net_change', horizonSessions: 5 },
|
||||
universe: 'CA_EQ_FIXTURE',
|
||||
horizon: '5d',
|
||||
},
|
||||
panel: built.panel,
|
||||
vaultCutoffDate: fixture.vaultCutoffDate,
|
||||
});
|
||||
|
||||
return { fixture, duck, ledger, built, studyResult };
|
||||
}
|
||||
|
||||
it('fixture publishes each ceoShorts report after the close four sessions past report_date', () => {
|
||||
const fixture = buildCeoShortsFixture(false);
|
||||
expect(fixture.shortsRows.length).toBeGreaterThan(0);
|
||||
for (const row of fixture.shortsRows) {
|
||||
const reportIdx = fixture.allDates.indexOf(row.report_date as string);
|
||||
const publishDate = fixture.allDates[reportIdx + 4]!;
|
||||
expect(row.known_at).toBe(makeUtcMs(publishDate, 22));
|
||||
expect(row.known_at as number).toBeGreaterThan(makeUtcMs(publishDate, 21));
|
||||
}
|
||||
});
|
||||
|
||||
it('flows DuckDbMarketDataStore -> buildForwardReturnPanel -> analyzeSignal -> trial_ledger + DSR', async () => {
|
||||
const clean = await runCeoShortsStudy(false);
|
||||
|
||||
// DuckDB connection budget SET statements ran exactly once.
|
||||
expect(clean.duck.runStatements).toHaveLength(3);
|
||||
expect(clean.duck.runStatements[0]).toContain('SET memory_limit');
|
||||
expect(clean.duck.runStatements[1]).toContain('SET threads');
|
||||
expect(clean.duck.runStatements[2]).toContain('SET temp_directory');
|
||||
expect(clean.duck.queryCount()).toBe(2); // 1 bars query + 1 shortsAsOf query
|
||||
|
||||
// Panel Vault safety: no emitted date or forward session >= vaultCutoffDate.
|
||||
expect(clean.built.panel.length).toBeGreaterThan(100);
|
||||
for (const slice of clean.built.panel) {
|
||||
expect(slice.date < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
const idx = clean.built.sessionDates.indexOf(slice.date);
|
||||
expect(idx).toBeGreaterThanOrEqual(0);
|
||||
expect(idx + 5).toBeLessThan(clean.built.sessionDates.length);
|
||||
expect(clean.built.sessionDates[idx + 5]! < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
}
|
||||
|
||||
// Signal study succeeded and inserted exactly one `signal_ic` row for CA_EQ.
|
||||
expect(clean.studyResult.status).toBe('ok');
|
||||
if (clean.studyResult.status !== 'ok') {
|
||||
return;
|
||||
}
|
||||
|
||||
expect(clean.ledger.rows).toHaveLength(1);
|
||||
const stored = clean.ledger.rows[0]!;
|
||||
expect(stored.stage).toBe('signal_ic');
|
||||
expect(stored.universe_market).toBe('CA_EQ');
|
||||
expect(stored.horizon_bucket).toBe('swing_1_10d');
|
||||
expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true);
|
||||
|
||||
// Finite DSR with effectiveTrials >= 1.
|
||||
expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull();
|
||||
expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true);
|
||||
expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Planted negative short-interest change -> next-5-session return relationship yields negative mean rank-IC.
|
||||
expect(clean.studyResult.analysis.rankIc.mean).not.toBeNull();
|
||||
expect(clean.studyResult.analysis.rankIc.mean!).toBeLessThan(0);
|
||||
|
||||
// Poisoning post-cutoff fixture bars leaves study result and trial_ledger row byte-identical.
|
||||
const poisoned = await runCeoShortsStudy(true);
|
||||
expect(poisoned.studyResult).toEqual(clean.studyResult);
|
||||
expect(poisoned.ledger.rows).toEqual(clean.ledger.rows);
|
||||
expect(poisoned.built).toEqual(clean.built);
|
||||
});
|
||||
});
|
||||
540
libs/research/test/signal-panel-qa.test.ts
Normal file
540
libs/research/test/signal-panel-qa.test.ts
Normal file
|
|
@ -0,0 +1,540 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import {
|
||||
SignalPanelError,
|
||||
buildForwardReturnPanel,
|
||||
type BarRecord,
|
||||
type BuildForwardReturnPanelResult,
|
||||
type SignalObservation,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
// QA suite for T-121: compares `buildForwardReturnPanel` against a deliberately naive
|
||||
// O(n^2) reference model on seeded random panels (gaps, mixed EST/EDT close stamps,
|
||||
// exact-close and after-close signals, bad closes, exact duplicates, post-cutoff bars),
|
||||
// plus targeted PIT/Vault probes the authored suite does not pin down.
|
||||
|
||||
const MS_PER_DAY = 86_400_000;
|
||||
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, ms = 0): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, 0, ms);
|
||||
}
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = [];
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
while (out.length < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out.push(current.toISOString().slice(0, 10));
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeBarAt(listingId: number, ts: number, close: number): BarRecord {
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 1_000,
|
||||
vwap: close,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
function shuffle<T>(items: readonly T[], seed: number): T[] {
|
||||
const copy = [...items];
|
||||
const rand = createSeededRng(seed);
|
||||
for (let i = copy.length - 1; i > 0; i -= 1) {
|
||||
const j = Math.floor(rand() * (i + 1));
|
||||
const tmp = copy[i]!;
|
||||
copy[i] = copy[j]!;
|
||||
copy[j] = tmp;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
interface ReferenceObservation {
|
||||
readonly date: string;
|
||||
readonly listingId: number;
|
||||
readonly signal: number;
|
||||
readonly forwardReturn: number;
|
||||
}
|
||||
|
||||
interface ReferenceResult {
|
||||
readonly observations: ReferenceObservation[];
|
||||
readonly sessionDates: string[];
|
||||
readonly diagnostics: BuildForwardReturnPanelResult['diagnostics'];
|
||||
}
|
||||
|
||||
/**
|
||||
* Naive reference implementation of the documented contract. Intentionally written
|
||||
* with linear scans and plain objects so it shares no code paths with the optimized
|
||||
* CSR / merge-pass implementation.
|
||||
*/
|
||||
function referencePanel(
|
||||
bars: readonly BarRecord[],
|
||||
signals: readonly SignalObservation[],
|
||||
horizon: number,
|
||||
vaultCutoffDate: string,
|
||||
maxAge: number | undefined
|
||||
): ReferenceResult {
|
||||
const cutoffDayKey = Date.parse(`${vaultCutoffDate}T00:00:00.000Z`) / MS_PER_DAY;
|
||||
const preBars = bars.filter(b => Math.floor(b.ts / MS_PER_DAY) < cutoffDayKey);
|
||||
const postDays = new Set(
|
||||
bars.map(b => Math.floor(b.ts / MS_PER_DAY)).filter(dk => dk >= cutoffDayKey)
|
||||
);
|
||||
const dayKeys = [...new Set(preBars.map(b => Math.floor(b.ts / MS_PER_DAY)))].sort(
|
||||
(a, b) => a - b
|
||||
);
|
||||
const sessionDates = dayKeys.map(dk => new Date(dk * MS_PER_DAY).toISOString().slice(0, 10));
|
||||
const sessionMaxTs = dayKeys.map(dk =>
|
||||
Math.max(...preBars.filter(b => Math.floor(b.ts / MS_PER_DAY) === dk).map(b => b.ts))
|
||||
);
|
||||
const preCount = dayKeys.length;
|
||||
const emittable = Math.max(0, preCount - horizon);
|
||||
const hasPost = postDays.size > 0;
|
||||
|
||||
let duplicateBars = 0;
|
||||
let droppedNoSignal = 0;
|
||||
let droppedStaleSignal = 0;
|
||||
let droppedMissingForwardBar = 0;
|
||||
let droppedNonPositiveClose = 0;
|
||||
const observations: ReferenceObservation[] = [];
|
||||
|
||||
const listingIds = [...new Set(preBars.map(b => b.listingId))].sort((a, b) => a - b);
|
||||
for (const lid of listingIds) {
|
||||
const bySession = new Map<number, BarRecord>();
|
||||
for (const b of preBars.filter(x => x.listingId === lid)) {
|
||||
const s = dayKeys.indexOf(Math.floor(b.ts / MS_PER_DAY));
|
||||
const prev = bySession.get(s);
|
||||
if (prev !== undefined) {
|
||||
const same =
|
||||
prev.ts === b.ts && (Object.is(prev.close, b.close) || prev.close === b.close);
|
||||
if (!same) {
|
||||
throw new Error('reference: conflicting duplicate');
|
||||
}
|
||||
duplicateBars += 1;
|
||||
continue;
|
||||
}
|
||||
bySession.set(s, b);
|
||||
}
|
||||
const listingSignals = signals.filter(s => s.listingId === lid);
|
||||
|
||||
for (const [t, bar] of [...bySession.entries()].sort((a, b) => a[0] - b[0])) {
|
||||
if (hasPost && t >= emittable) {
|
||||
continue;
|
||||
}
|
||||
let active: SignalObservation | undefined;
|
||||
for (const s of listingSignals) {
|
||||
if (s.knownAt > bar.ts) {
|
||||
continue;
|
||||
}
|
||||
if (
|
||||
active === undefined ||
|
||||
s.knownAt > active.knownAt ||
|
||||
(s.knownAt === active.knownAt && s.value > active.value)
|
||||
) {
|
||||
active = s;
|
||||
}
|
||||
}
|
||||
if (active === undefined) {
|
||||
droppedNoSignal += 1;
|
||||
continue;
|
||||
}
|
||||
if (maxAge !== undefined) {
|
||||
let first = sessionMaxTs.findIndex(mx => mx >= active!.knownAt);
|
||||
if (first < 0) {
|
||||
first = preCount;
|
||||
}
|
||||
if (t - first > maxAge) {
|
||||
droppedStaleSignal += 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
const fwd = bySession.get(t + horizon);
|
||||
if (t + horizon >= preCount || fwd === undefined) {
|
||||
droppedMissingForwardBar += 1;
|
||||
continue;
|
||||
}
|
||||
const c0 = bar.close;
|
||||
const c1 = fwd.close;
|
||||
if (!Number.isFinite(c0) || c0 <= 0 || !Number.isFinite(c1) || c1 <= 0) {
|
||||
droppedNonPositiveClose += 1;
|
||||
continue;
|
||||
}
|
||||
observations.push({
|
||||
date: sessionDates[t]!,
|
||||
listingId: lid,
|
||||
signal: active.value === 0 ? 0 : active.value,
|
||||
forwardReturn: c1 / c0 - 1 === 0 ? 0 : c1 / c0 - 1,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
observations.sort((a, b) => (a.date < b.date ? -1 : a.date > b.date ? 1 : a.listingId - b.listingId));
|
||||
return {
|
||||
observations,
|
||||
sessionDates,
|
||||
diagnostics: {
|
||||
vaultExcludedDates: hasPost ? preCount - emittable + postDays.size : 0,
|
||||
droppedNoSignal,
|
||||
droppedStaleSignal,
|
||||
droppedMissingForwardBar,
|
||||
droppedNonPositiveClose,
|
||||
duplicateBars,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function flattenPanel(result: BuildForwardReturnPanelResult): ReferenceObservation[] {
|
||||
const out: ReferenceObservation[] = [];
|
||||
for (const slice of result.panel) {
|
||||
for (let i = 0; i < slice.ids.length; i += 1) {
|
||||
out.push({
|
||||
date: slice.date,
|
||||
listingId: slice.ids[i]!,
|
||||
signal: slice.signal[i]!,
|
||||
forwardReturn: slice.forwardReturn[i]!,
|
||||
});
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
interface RandomPanel {
|
||||
readonly bars: BarRecord[];
|
||||
readonly signals: SignalObservation[];
|
||||
readonly dates: string[];
|
||||
}
|
||||
|
||||
function buildRandomPanel(seed: number): RandomPanel {
|
||||
const rand = createSeededRng(seed);
|
||||
const sessionCount = 30 + Math.floor(rand() * 30);
|
||||
const listingCount = 3 + Math.floor(rand() * 8);
|
||||
const dates = makeBusinessDates('2023-02-20', sessionCount); // straddles the March DST switch
|
||||
const bars: BarRecord[] = [];
|
||||
const signals: SignalObservation[] = [];
|
||||
|
||||
for (let l = 0; l < listingCount; l += 1) {
|
||||
const listingId = 1_000 - l * 37; // descending ids to exercise id sorting
|
||||
let price = 20 + l;
|
||||
for (let t = 0; t < sessionCount; t += 1) {
|
||||
price *= 1 + (rand() - 0.5) * 0.04;
|
||||
if (rand() < 0.12) {
|
||||
continue; // gap
|
||||
}
|
||||
const closeHourUtc = rand() < 0.5 ? 20 : 21; // EDT vs EST close stamp
|
||||
const ts = makeUtcMs(dates[t]!, closeHourUtc);
|
||||
const roll = rand();
|
||||
const close =
|
||||
roll < 0.03 ? 0 : roll < 0.05 ? Number.NaN : roll < 0.06 ? -1 : Number(price.toFixed(4));
|
||||
const bar = makeBarAt(listingId, ts, close);
|
||||
bars.push(bar);
|
||||
if (rand() < 0.05) {
|
||||
bars.push({ ...bar }); // exact duplicate
|
||||
}
|
||||
|
||||
const sigRoll = rand();
|
||||
if (sigRoll < 0.15) {
|
||||
signals.push({ listingId, knownAt: ts, value: Math.round(rand() * 100) / 10 }); // exactly at close
|
||||
} else if (sigRoll < 0.3) {
|
||||
signals.push({ listingId, knownAt: ts + 1, value: Math.round(rand() * 100) / 10 }); // 1 ms after
|
||||
} else if (sigRoll < 0.4) {
|
||||
signals.push({ listingId, knownAt: ts + 3_600_000, value: -Math.round(rand() * 100) / 10 });
|
||||
} else if (sigRoll < 0.45) {
|
||||
// Equal-knownAt tie pair.
|
||||
const knownAt = makeUtcMs(dates[t]!, 13);
|
||||
signals.push({ listingId, knownAt, value: 1 }, { listingId, knownAt, value: 2 });
|
||||
}
|
||||
}
|
||||
}
|
||||
// Signals for an unknown listing must be ignored.
|
||||
signals.push({ listingId: 7, knownAt: makeUtcMs(dates[0]!, 10), value: 99 });
|
||||
return { bars, signals, dates };
|
||||
}
|
||||
|
||||
describe('buildForwardReturnPanel vs naive reference model (seeded)', () => {
|
||||
it('matches the reference panel, sessionDates and diagnostics across random panels', () => {
|
||||
let totalEmitted = 0;
|
||||
let totalStale = 0;
|
||||
let totalExcluded = 0;
|
||||
for (let seed = 1; seed <= 60; seed += 1) {
|
||||
const { bars, signals, dates } = buildRandomPanel(seed);
|
||||
const rand = createSeededRng(seed * 7919);
|
||||
const horizon = [1, 2, 5, 20][seed % 4]!;
|
||||
const maxAge = seed % 3 === 0 ? undefined : Math.floor(rand() * 6);
|
||||
// Cutoff either inside the sample (post-cutoff bars exist) or after it.
|
||||
const cutoff =
|
||||
seed % 5 === 0 ? '2030-01-01' : dates[Math.floor(dates.length * (0.6 + rand() * 0.3))]!;
|
||||
|
||||
const actual = buildForwardReturnPanel({
|
||||
bars: shuffle(bars, seed),
|
||||
signals: shuffle(signals, seed + 1),
|
||||
horizonSessions: horizon,
|
||||
vaultCutoffDate: cutoff,
|
||||
maxSignalAgeSessions: maxAge,
|
||||
});
|
||||
const expected = referencePanel(bars, signals, horizon, cutoff, maxAge);
|
||||
|
||||
expect(actual.sessionDates).toEqual(expected.sessionDates);
|
||||
expect(actual.diagnostics).toEqual(expected.diagnostics);
|
||||
const flat = flattenPanel(actual);
|
||||
expect(flat.length).toBe(expected.observations.length);
|
||||
for (let i = 0; i < flat.length; i += 1) {
|
||||
const a = flat[i]!;
|
||||
const e = expected.observations[i]!;
|
||||
expect(a.date).toBe(e.date);
|
||||
expect(a.listingId).toBe(e.listingId);
|
||||
expect(a.signal).toBe(e.signal);
|
||||
expect(a.forwardReturn).toBe(e.forwardReturn);
|
||||
}
|
||||
|
||||
// Structural invariants on the emitted panel.
|
||||
for (let p = 0; p < actual.panel.length; p += 1) {
|
||||
const slice = actual.panel[p]!;
|
||||
expect(slice.ids.length).toBeGreaterThan(0);
|
||||
expect(slice.date < cutoff).toBe(true);
|
||||
const t = actual.sessionDates.indexOf(slice.date);
|
||||
expect(t + horizon).toBeLessThan(actual.sessionDates.length);
|
||||
if (p > 0) {
|
||||
expect(actual.panel[p - 1]!.date < slice.date).toBe(true);
|
||||
}
|
||||
for (let i = 1; i < slice.ids.length; i += 1) {
|
||||
expect(slice.ids[i]!).toBeGreaterThan(slice.ids[i - 1]!);
|
||||
}
|
||||
}
|
||||
totalEmitted += flat.length;
|
||||
totalStale += actual.diagnostics.droppedStaleSignal;
|
||||
totalExcluded += actual.diagnostics.vaultExcludedDates;
|
||||
}
|
||||
// Guard against a vacuous fixture: every branch was actually exercised.
|
||||
expect(totalEmitted).toBeGreaterThan(1_000);
|
||||
expect(totalStale).toBeGreaterThan(0);
|
||||
expect(totalExcluded).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildForwardReturnPanel point-in-time probes', () => {
|
||||
it('activates a signal published 1 ms after a close on the very next session (not superseded)', () => {
|
||||
const dates = makeBusinessDates('2024-03-04', 6);
|
||||
const bars = dates.map((d, i) => makeBarAt(1, makeUtcMs(d), 100 + i));
|
||||
const day0Close = makeUtcMs(dates[0]!);
|
||||
const day2Close = makeUtcMs(dates[2]!);
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals: [
|
||||
{ listingId: 1, knownAt: day0Close + 1, value: 10 },
|
||||
{ listingId: 1, knownAt: day2Close, value: 20 },
|
||||
],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
expect(result.panel.map(s => [s.date, s.signal[0]])).toEqual([
|
||||
[dates[1], 10],
|
||||
[dates[2], 20],
|
||||
[dates[3], 20],
|
||||
[dates[4], 20],
|
||||
]);
|
||||
expect(result.diagnostics.droppedNoSignal).toBe(1);
|
||||
});
|
||||
|
||||
it('adding future signals never changes the signal used on earlier dates (poison test)', () => {
|
||||
for (let seed = 101; seed <= 115; seed += 1) {
|
||||
const { bars, signals, dates } = buildRandomPanel(seed);
|
||||
const base = { bars, horizonSessions: 1, vaultCutoffDate: '2030-01-01' } as const;
|
||||
const pivot = Math.floor(dates.length / 2);
|
||||
// Truncate to signals known on or before the pivot close, then poison with absurd
|
||||
// values published 1 ms after the pivot session's latest close.
|
||||
const pivotMaxTs = Math.max(
|
||||
...bars.filter(b => new Date(b.ts).toISOString().slice(0, 10) === dates[pivot]).map(b => b.ts)
|
||||
);
|
||||
const truncated = signals.filter(s => s.knownAt <= pivotMaxTs);
|
||||
const poison: SignalObservation[] = [...new Set(bars.map(b => b.listingId))].map(lid => ({
|
||||
listingId: lid,
|
||||
knownAt: pivotMaxTs + 1,
|
||||
value: 1e12,
|
||||
}));
|
||||
|
||||
const clean = buildForwardReturnPanel({ ...base, signals: truncated });
|
||||
const poisoned = buildForwardReturnPanel({ ...base, signals: [...truncated, ...poison] });
|
||||
const pivotDate = dates[pivot]!;
|
||||
const pick = (r: BuildForwardReturnPanelResult) =>
|
||||
flattenPanel(r).filter(o => o.date <= pivotDate);
|
||||
expect(pick(poisoned)).toEqual(pick(clean));
|
||||
expect(pick(clean).length).toBeGreaterThan(0);
|
||||
expect(flattenPanel(poisoned).some(o => o.signal === 1e12)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('uses each listing’s own close time for PIT, not the latest close across listings', () => {
|
||||
// Listing 1 closes 20:00 UTC, listing 2 closes 21:00 UTC on the same session date.
|
||||
const dates = makeBusinessDates('2024-04-01', 4);
|
||||
const bars = dates.flatMap((d, i) => [
|
||||
makeBarAt(1, makeUtcMs(d, 20), 100 + i),
|
||||
makeBarAt(2, makeUtcMs(d, 21), 200 + i),
|
||||
]);
|
||||
const knownAt = makeUtcMs(dates[0]!, 20, 30);
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals: [
|
||||
{ listingId: 1, knownAt, value: 1 },
|
||||
{ listingId: 2, knownAt, value: 2 },
|
||||
],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
// Day 0: listing 1 bar at 20:00 precedes knownAt 20:30 -> dropped; listing 2 at 21:00 -> used.
|
||||
expect(result.panel[0]!.date).toBe(dates[0]);
|
||||
expect(Array.from(result.panel[0]!.ids)).toEqual([2]);
|
||||
expect(Array.from(result.panel[1]!.ids)).toEqual([1, 2]);
|
||||
expect(result.diagnostics.droppedNoSignal).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildForwardReturnPanel Vault fence probes', () => {
|
||||
it('treats a bar at 00:00 UTC on the cutoff date as Vault and 23:59:59.999 the day before as pre-cutoff', () => {
|
||||
const cutoff = '2024-06-10';
|
||||
const preTs = Date.parse('2024-06-09T23:59:59.999Z');
|
||||
const postTs = Date.parse('2024-06-10T00:00:00.000Z');
|
||||
let postReads = 0;
|
||||
const trapped = { ...makeBarAt(1, postTs, 1) } as Record<string, unknown>;
|
||||
Object.defineProperty(trapped, 'close', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
postReads += 1;
|
||||
return 1;
|
||||
},
|
||||
});
|
||||
const result = buildForwardReturnPanel({
|
||||
bars: [
|
||||
makeBarAt(1, Date.parse('2024-06-07T20:00:00.000Z'), 100),
|
||||
makeBarAt(1, preTs, 110),
|
||||
trapped as unknown as BarRecord,
|
||||
],
|
||||
signals: [{ listingId: 1, knownAt: 0, value: 1 }],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: cutoff,
|
||||
});
|
||||
expect(postReads).toBe(0);
|
||||
expect(result.sessionDates).toEqual(['2024-06-07', '2024-06-09']);
|
||||
expect(result.panel).toHaveLength(1);
|
||||
expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12);
|
||||
// h = 1 tail session + 1 post-cutoff day.
|
||||
expect(result.diagnostics.vaultExcludedDates).toBe(2);
|
||||
});
|
||||
|
||||
it('never emits a date whose forward session is in the Vault, even when only another listing reaches the cutoff', () => {
|
||||
// Listing 1 stops trading well before the cutoff; listing 2 continues into the Vault.
|
||||
const dates = makeBusinessDates('2024-01-02', 20);
|
||||
const cutoff = dates[15]!;
|
||||
const bars: BarRecord[] = [];
|
||||
for (let t = 0; t < dates.length; t += 1) {
|
||||
if (t < 10) {
|
||||
bars.push(makeBarAt(1, makeUtcMs(dates[t]!), 100 + t));
|
||||
}
|
||||
bars.push(makeBarAt(2, makeUtcMs(dates[t]!), 50 + t));
|
||||
}
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals: [
|
||||
{ listingId: 1, knownAt: 0, value: 1 },
|
||||
{ listingId: 2, knownAt: 0, value: 2 },
|
||||
],
|
||||
horizonSessions: 3,
|
||||
vaultCutoffDate: cutoff,
|
||||
});
|
||||
const last = result.panel[result.panel.length - 1]!;
|
||||
expect(last.date).toBe(dates[11]); // 15 pre-cutoff sessions, last emittable index 15 - 1 - 3
|
||||
for (const slice of result.panel) {
|
||||
const t = dates.indexOf(slice.date);
|
||||
expect(dates[t + 3]! < cutoff).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects conflicting duplicates only before the cutoff and ignores them inside the Vault', () => {
|
||||
const dates = makeBusinessDates('2024-01-02', 4);
|
||||
const cutoff = dates[2]!;
|
||||
const vaultBar = makeBarAt(1, makeUtcMs(dates[3]!), 100);
|
||||
const ok = buildForwardReturnPanel({
|
||||
bars: [
|
||||
makeBarAt(1, makeUtcMs(dates[0]!), 100),
|
||||
makeBarAt(1, makeUtcMs(dates[1]!), 101),
|
||||
vaultBar,
|
||||
{ ...vaultBar, close: 999 },
|
||||
],
|
||||
signals: [{ listingId: 1, knownAt: 0, value: 1 }],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: cutoff,
|
||||
});
|
||||
expect(ok.panel).toHaveLength(1);
|
||||
|
||||
expect(() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [makeBarAt(1, makeUtcMs(dates[0]!), 100), makeBarAt(1, makeUtcMs(dates[0]!, 20), 100)],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: cutoff,
|
||||
})
|
||||
).toThrow(SignalPanelError);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildForwardReturnPanel calendar edge cases', () => {
|
||||
it('uses the sparse Map calendar path for spans above 200,000 days and stays exact', () => {
|
||||
// ~600 years apart -> day span > 200,000 forces the Map lookup branch.
|
||||
const ancient = Date.UTC(1500, 0, 3, 21);
|
||||
const bars = [
|
||||
makeBarAt(1, ancient, 10),
|
||||
makeBarAt(1, Date.UTC(2100, 0, 4, 21), 20),
|
||||
makeBarAt(1, Date.UTC(2100, 0, 5, 21), 30),
|
||||
];
|
||||
const result = buildForwardReturnPanel({
|
||||
bars: shuffle(bars, 3),
|
||||
signals: [{ listingId: 1, knownAt: ancient, value: 5 }],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2200-01-01',
|
||||
});
|
||||
expect(result.sessionDates).toEqual(['1500-01-03', '2100-01-04', '2100-01-05']);
|
||||
expect(result.panel.map(s => [s.date, s.forwardReturn[0]])).toEqual([
|
||||
['1500-01-03', 1],
|
||||
['2100-01-04', 0.5],
|
||||
]);
|
||||
});
|
||||
|
||||
it('measures horizon in shared calendar sessions, so a holiday for one listing is a missing forward bar', () => {
|
||||
const dates = makeBusinessDates('2024-07-01', 5);
|
||||
const bars = [
|
||||
...dates.map((d, i) => makeBarAt(1, makeUtcMs(d), 100 + i)),
|
||||
// Listing 2 is closed on dates[2] (e.g. a cross-listed holiday).
|
||||
...dates.filter((_, i) => i !== 2).map((d, i) => makeBarAt(2, makeUtcMs(d), 200 + i)),
|
||||
];
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals: [
|
||||
{ listingId: 1, knownAt: 0, value: 1 },
|
||||
{ listingId: 2, knownAt: 0, value: 2 },
|
||||
],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
const day1 = result.panel.find(s => s.date === dates[1])!;
|
||||
expect(Array.from(day1.ids)).toEqual([1]);
|
||||
// Listing 2 has no bar on dates[2]: dropped as entry (no row) and as exit for dates[1].
|
||||
expect(result.panel.find(s => s.date === dates[2])!.ids.length).toBe(1);
|
||||
});
|
||||
});
|
||||
766
libs/research/test/signal-panel.test.ts
Normal file
766
libs/research/test/signal-panel.test.ts
Normal file
|
|
@ -0,0 +1,766 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import {
|
||||
SHORTS_SIGNAL_FIELDS,
|
||||
SignalPanelError,
|
||||
buildForwardReturnPanel,
|
||||
collectBars,
|
||||
shortsTableToSignalRows,
|
||||
type BarBatch,
|
||||
type BarRecord,
|
||||
type SignalObservation,
|
||||
type SignalPanelErrorCode,
|
||||
type Table,
|
||||
} from '@stock-bot/research';
|
||||
import {
|
||||
SHORTS_SIGNAL_FIELDS as SubpathShortsSignalFields,
|
||||
SignalPanelError as SubpathSignalPanelError,
|
||||
buildForwardReturnPanel as subpathBuildForwardReturnPanel,
|
||||
collectBars as subpathCollectBars,
|
||||
shortsTableToSignalRows as subpathShortsTableToSignalRows,
|
||||
} from '@stock-bot/research/signal-panel';
|
||||
|
||||
function makeUtcMs(date: string, hourUtc = 21, minuteUtc = 0, secondUtc = 0, ms = 0): number {
|
||||
const [y, m, d] = date.split('-').map(Number);
|
||||
return Date.UTC(y!, m! - 1, d!, hourUtc, minuteUtc, secondUtc, ms);
|
||||
}
|
||||
|
||||
function makeBusinessDates(startDate: string, count: number): string[] {
|
||||
const out: string[] = new Array(count);
|
||||
const current = new Date(`${startDate}T00:00:00.000Z`);
|
||||
let written = 0;
|
||||
while (written < count) {
|
||||
const day = current.getUTCDay();
|
||||
if (day !== 0 && day !== 6) {
|
||||
out[written] = current.toISOString().slice(0, 10);
|
||||
written += 1;
|
||||
}
|
||||
current.setUTCDate(current.getUTCDate() + 1);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function makeBar(listingId: number, date: string, close: number, hourUtc = 21): BarRecord {
|
||||
const ts = makeUtcMs(date, hourUtc, 0, 0, 0);
|
||||
return {
|
||||
listingId,
|
||||
ts,
|
||||
open: close,
|
||||
high: close,
|
||||
low: close,
|
||||
close,
|
||||
volume: 1_000,
|
||||
vwap: close,
|
||||
knownAt: ts,
|
||||
};
|
||||
}
|
||||
|
||||
function createSeededRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = Math.imul(state ^ (state >>> 15), 1 | state);
|
||||
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4_294_967_296;
|
||||
};
|
||||
}
|
||||
|
||||
function shuffle<T>(items: readonly T[], seed: number): T[] {
|
||||
const copy = [...items];
|
||||
const rand = createSeededRng(seed);
|
||||
for (let i = copy.length - 1; i > 0; i -= 1) {
|
||||
const j = Math.floor(rand() * (i + 1));
|
||||
const tmp = copy[i]!;
|
||||
copy[i] = copy[j]!;
|
||||
copy[j] = tmp;
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
function expectSignalPanelError(fn: () => unknown, code: SignalPanelErrorCode): SignalPanelError {
|
||||
try {
|
||||
fn();
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(SignalPanelError);
|
||||
const typed = err as SignalPanelError;
|
||||
expect(typed.code).toBe(code);
|
||||
return typed;
|
||||
}
|
||||
throw new Error(`Expected SignalPanelError(${code}), but function did not throw.`);
|
||||
}
|
||||
|
||||
async function expectSignalPanelErrorAsync(
|
||||
fn: () => Promise<unknown>,
|
||||
code: SignalPanelErrorCode
|
||||
): Promise<SignalPanelError> {
|
||||
try {
|
||||
await fn();
|
||||
} catch (err) {
|
||||
expect(err).toBeInstanceOf(SignalPanelError);
|
||||
const typed = err as SignalPanelError;
|
||||
expect(typed.code).toBe(code);
|
||||
return typed;
|
||||
}
|
||||
throw new Error(`Expected async SignalPanelError(${code}), but promise resolved.`);
|
||||
}
|
||||
|
||||
describe('@stock-bot/research signal-panel exports and browser safety', () => {
|
||||
it('exposes identical symbols from root and ./signal-panel subpath', () => {
|
||||
expect(buildForwardReturnPanel).toBe(subpathBuildForwardReturnPanel);
|
||||
expect(shortsTableToSignalRows).toBe(subpathShortsTableToSignalRows);
|
||||
expect(collectBars).toBe(subpathCollectBars);
|
||||
expect(SignalPanelError).toBe(SubpathSignalPanelError);
|
||||
expect(SHORTS_SIGNAL_FIELDS).toBe(SubpathShortsSignalFields);
|
||||
});
|
||||
|
||||
it('has zero node:* imports, zero bare process access, and no new package dependencies', () => {
|
||||
const src = readFileSync(new URL('../src/signal-panel.ts', import.meta.url), 'utf8');
|
||||
expect(src).not.toMatch(/from\s+['"]node:/);
|
||||
expect(src).not.toMatch(/require\s*\(\s*['"]node:/);
|
||||
expect(src).not.toMatch(/\bprocess\./);
|
||||
|
||||
const pkg = JSON.parse(
|
||||
readFileSync(new URL('../package.json', import.meta.url), 'utf8')
|
||||
) as {
|
||||
exports: Record<string, string>;
|
||||
dependencies: Record<string, string>;
|
||||
};
|
||||
expect(pkg.exports['./signal-panel']).toBe('./src/signal-panel.ts');
|
||||
expect(Object.keys(pkg.dependencies).sort()).toEqual([
|
||||
'@stock-bot/calculations',
|
||||
'@stock-bot/stock-config',
|
||||
'@stock-bot/types',
|
||||
'zod',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildForwardReturnPanel', () => {
|
||||
it('computes exact hand-verified forward returns for horizons 1, 5, and 20', () => {
|
||||
const dates = makeBusinessDates('2024-01-02', 25);
|
||||
const bars: BarRecord[] = [];
|
||||
const signals: SignalObservation[] = [];
|
||||
|
||||
// Listing 20 and Listing 10 intentionally inserted out of order to verify ascending ids.
|
||||
for (let i = 0; i < dates.length; i += 1) {
|
||||
bars.push(makeBar(20, dates[i]!, 100 + i * 2));
|
||||
bars.push(makeBar(10, dates[i]!, 50 + i));
|
||||
}
|
||||
signals.push(
|
||||
{ listingId: 10, knownAt: makeUtcMs(dates[0]!, 20), value: 1.5 },
|
||||
{ listingId: 20, knownAt: makeUtcMs(dates[0]!, 20), value: -2.5 }
|
||||
);
|
||||
|
||||
for (const horizon of [1, 5, 20] as const) {
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: horizon,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
|
||||
const expectedEmittedDates = dates.length - horizon;
|
||||
expect(result.sessionDates).toEqual(dates);
|
||||
expect(result.panel).toHaveLength(expectedEmittedDates);
|
||||
expect(result.diagnostics.vaultExcludedDates).toBe(0);
|
||||
expect(result.diagnostics.droppedNoSignal).toBe(0);
|
||||
expect(result.diagnostics.droppedStaleSignal).toBe(0);
|
||||
expect(result.diagnostics.droppedMissingForwardBar).toBe(horizon * 2);
|
||||
expect(result.diagnostics.droppedNonPositiveClose).toBe(0);
|
||||
expect(result.diagnostics.duplicateBars).toBe(0);
|
||||
|
||||
let emittedObs = 0;
|
||||
for (let t = 0; t < expectedEmittedDates; t += 1) {
|
||||
const slice = result.panel[t]!;
|
||||
expect(slice.date).toBe(dates[t]);
|
||||
expect(slice.ids).toBeInstanceOf(Int32Array);
|
||||
expect(slice.signal).toBeInstanceOf(Float64Array);
|
||||
expect(slice.forwardReturn).toBeInstanceOf(Float64Array);
|
||||
expect(Array.from(slice.ids)).toEqual([10, 20]);
|
||||
expect(Array.from(slice.signal)).toEqual([1.5, -2.5]);
|
||||
|
||||
const expectedRet10 = (50 + t + horizon) / (50 + t) - 1;
|
||||
const expectedRet20 = (100 + (t + horizon) * 2) / (100 + t * 2) - 1;
|
||||
expect(slice.forwardReturn[0]).toBeCloseTo(expectedRet10, 12);
|
||||
expect(slice.forwardReturn[1]).toBeCloseTo(expectedRet20, 12);
|
||||
emittedObs += slice.ids.length;
|
||||
}
|
||||
|
||||
// Conservation identity: emitted + all drops === unique pre-cutoff bars.
|
||||
const totalDrops =
|
||||
result.diagnostics.droppedNoSignal +
|
||||
result.diagnostics.droppedStaleSignal +
|
||||
result.diagnostics.droppedMissingForwardBar +
|
||||
result.diagnostics.droppedNonPositiveClose;
|
||||
expect(emittedObs + totalDrops).toBe(bars.length);
|
||||
}
|
||||
});
|
||||
|
||||
it('enforces strict knownAt <= bar.ts point-in-time rule and deterministic tie-breaking', () => {
|
||||
const dates = makeBusinessDates('2024-03-04', 5);
|
||||
const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx * 10));
|
||||
|
||||
const day0CloseTs = makeUtcMs(dates[0]!, 21, 0, 0, 0);
|
||||
const day1CloseTs = makeUtcMs(dates[1]!, 21, 0, 0, 0);
|
||||
const signals: SignalObservation[] = [
|
||||
// Known 1 ms AFTER day 0 close -> must NOT apply on day 0, MUST apply on day 1.
|
||||
{ listingId: 1, knownAt: day0CloseTs + 1, value: 10 },
|
||||
// Known EXACTLY at day 1 close -> MUST apply on day 1, overriding the day0+1ms signal.
|
||||
{ listingId: 1, knownAt: day1CloseTs, value: 20 },
|
||||
// Tie at exact same knownAt on day 1 close -> deterministic max value (25) regardless of order.
|
||||
{ listingId: 1, knownAt: day1CloseTs, value: 25 },
|
||||
];
|
||||
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
|
||||
expect(result.diagnostics.droppedNoSignal).toBe(1); // day 0 had no eligible signal
|
||||
expect(result.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]);
|
||||
expect(result.panel[0]!.signal[0]).toBe(25);
|
||||
expect(result.panel[1]!.signal[0]).toBe(25);
|
||||
expect(result.panel[2]!.signal[0]).toBe(25);
|
||||
|
||||
// Reverse signal order must produce the exact same tie-break value.
|
||||
const reversed = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals: [...signals].reverse(),
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
expect(reversed.panel.map(s => s.signal[0])).toEqual([25, 25, 25]);
|
||||
});
|
||||
|
||||
it('drops observations whose forward bar at d + h is missing instead of shifting to d + h + 1', () => {
|
||||
const dates = makeBusinessDates('2024-04-01', 6);
|
||||
// Listing 1 has all 6 sessions; Listing 2 is missing dates[3].
|
||||
const bars: BarRecord[] = [];
|
||||
for (let i = 0; i < dates.length; i += 1) {
|
||||
bars.push(makeBar(1, dates[i]!, 100 + i));
|
||||
if (i !== 3) {
|
||||
bars.push(makeBar(2, dates[i]!, 200 + i));
|
||||
}
|
||||
}
|
||||
const signals: SignalObservation[] = [
|
||||
{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 },
|
||||
{ listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 },
|
||||
];
|
||||
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: 2,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
|
||||
// On dates[1], target is dates[3]. Listing 2 has no bar on dates[3], so it must be dropped
|
||||
// rather than using dates[4].
|
||||
const sliceDay1 = result.panel.find(s => s.date === dates[1])!;
|
||||
expect(Array.from(sliceDay1.ids)).toEqual([1]);
|
||||
// On dates[2], target is dates[4], which Listing 2 DOES have.
|
||||
const sliceDay2 = result.panel.find(s => s.date === dates[2])!;
|
||||
expect(Array.from(sliceDay2.ids)).toEqual([1, 2]);
|
||||
expect(sliceDay2.forwardReturn[1]).toBeCloseTo(204 / 202 - 1, 12);
|
||||
|
||||
// Missing forward bars: Listing 1 misses dates[4], dates[5] (2);
|
||||
// Listing 2 misses dates[1] (-> dates[3]), dates[4], dates[5] (3). Total = 5.
|
||||
expect(result.diagnostics.droppedMissingForwardBar).toBe(5);
|
||||
});
|
||||
|
||||
it('enforces maxSignalAgeSessions including age 0 and after-close 17:00 ET signals', () => {
|
||||
const dates = makeBusinessDates('2024-05-06', 6);
|
||||
const bars: BarRecord[] = dates.map((d, idx) => makeBar(1, d, 100 + idx, 20)); // 16:00 EDT = 20:00 UTC
|
||||
|
||||
// Signal published at 17:00 EDT (21:00 UTC) on dates[0] -> first actionable session is dates[1] (age 0).
|
||||
const signals: SignalObservation[] = [
|
||||
{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 21, 0), value: 3.14 },
|
||||
];
|
||||
|
||||
// maxSignalAgeSessions = 0: only dates[1] is emitted; dates[2], dates[3], dates[4], dates[5] are stale.
|
||||
const age0 = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
maxSignalAgeSessions: 0,
|
||||
});
|
||||
expect(age0.panel.map(s => s.date)).toEqual([dates[1]]);
|
||||
expect(age0.diagnostics.droppedNoSignal).toBe(1); // dates[0]
|
||||
expect(age0.diagnostics.droppedStaleSignal).toBe(4); // dates[2..5]
|
||||
|
||||
// maxSignalAgeSessions = 2: dates[1] (age 0), dates[2] (age 1), dates[3] (age 2) emitted;
|
||||
// dates[4] (age 3) and dates[5] (age 4) dropped as stale.
|
||||
const age2 = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
maxSignalAgeSessions: 2,
|
||||
});
|
||||
expect(age2.panel.map(s => s.date)).toEqual([dates[1], dates[2], dates[3]]);
|
||||
expect(age2.diagnostics.droppedNoSignal).toBe(1);
|
||||
expect(age2.diagnostics.droppedStaleSignal).toBe(2);
|
||||
});
|
||||
|
||||
it('drops non-positive and non-finite entry/exit closes into droppedNonPositiveClose without throwing', () => {
|
||||
const dates = makeBusinessDates('2024-06-03', 6);
|
||||
const closes = [100, 0, -5, Number.NaN, Number.POSITIVE_INFINITY, 120];
|
||||
const bars: BarRecord[] = dates.map((d, i) => makeBar(1, d, closes[i]!));
|
||||
// Add a clean listing so we also verify normal rows survive alongside bad closes.
|
||||
for (let i = 0; i < dates.length; i += 1) {
|
||||
bars.push(makeBar(2, dates[i]!, 50 + i));
|
||||
}
|
||||
|
||||
const signals: SignalObservation[] = [
|
||||
{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 },
|
||||
{ listingId: 2, knownAt: makeUtcMs(dates[0]!, 10), value: 2 },
|
||||
];
|
||||
|
||||
const result = buildForwardReturnPanel({
|
||||
bars,
|
||||
signals,
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
|
||||
// Every pair for listing 1 touches a non-positive/non-finite close (0->1, 1->2, 2->3, 3->4, 4->5).
|
||||
expect(result.diagnostics.droppedNonPositiveClose).toBe(5);
|
||||
expect(result.panel).toHaveLength(5);
|
||||
for (const slice of result.panel) {
|
||||
expect(Array.from(slice.ids)).toEqual([2]);
|
||||
}
|
||||
});
|
||||
|
||||
it('deduplicates exact pre-cutoff bars and rejects conflicting duplicates', () => {
|
||||
const dates = makeBusinessDates('2024-07-01', 3);
|
||||
const b0 = makeBar(1, dates[0]!, 100);
|
||||
const b1 = makeBar(1, dates[1]!, 110);
|
||||
const b2 = makeBar(1, dates[2]!, 121);
|
||||
const bNaN = makeBar(2, dates[0]!, Number.NaN);
|
||||
|
||||
const result = buildForwardReturnPanel({
|
||||
bars: [b0, { ...b0 }, b1, b2, bNaN, { ...bNaN }],
|
||||
signals: [{ listingId: 1, knownAt: makeUtcMs(dates[0]!, 10), value: 1 }],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
|
||||
expect(result.diagnostics.duplicateBars).toBe(2);
|
||||
expect(result.panel).toHaveLength(2);
|
||||
expect(result.panel[0]!.forwardReturn[0]).toBeCloseTo(0.1, 12);
|
||||
|
||||
// Conflicting close on same (listingId, date) must throw duplicate_bar.
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [b0, { ...b0, close: 101 }, b1],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'duplicate_bar'
|
||||
);
|
||||
|
||||
// Conflicting ts on same (listingId, date) must throw duplicate_bar.
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [b0, { ...b0, ts: b0.ts + 1_000 }, b1],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'duplicate_bar'
|
||||
);
|
||||
});
|
||||
|
||||
it('enforces strict Vault cutoff across both d and d + h and never reads post-cutoff closes', () => {
|
||||
const preCutoffCount = 30;
|
||||
const postCutoffCount = 6;
|
||||
const allDates = makeBusinessDates('2024-01-02', preCutoffCount + postCutoffCount);
|
||||
const vaultCutoffDate = allDates[preCutoffCount]!;
|
||||
|
||||
const baseBars: BarRecord[] = [];
|
||||
for (let i = 0; i < allDates.length; i += 1) {
|
||||
baseBars.push(makeBar(1, allDates[i]!, 100 + i));
|
||||
baseBars.push(makeBar(2, allDates[i]!, 200 + i * 2));
|
||||
}
|
||||
const signals: SignalObservation[] = [
|
||||
{ listingId: 1, knownAt: makeUtcMs(allDates[0]!, 10), value: 0.5 },
|
||||
{ listingId: 2, knownAt: makeUtcMs(allDates[0]!, 10), value: -0.5 },
|
||||
];
|
||||
|
||||
for (const horizon of [1, 5, 20] as const) {
|
||||
const clean = buildForwardReturnPanel({
|
||||
bars: baseBars,
|
||||
signals,
|
||||
horizonSessions: horizon,
|
||||
vaultCutoffDate,
|
||||
});
|
||||
|
||||
const expectedEmittable = preCutoffCount - horizon;
|
||||
expect(clean.sessionDates).toEqual(allDates.slice(0, preCutoffCount));
|
||||
expect(clean.sessionDates.every(d => d < vaultCutoffDate)).toBe(true);
|
||||
expect(clean.panel).toHaveLength(expectedEmittable);
|
||||
expect(clean.panel[clean.panel.length - 1]!.date).toBe(allDates[preCutoffCount - 1 - horizon]);
|
||||
expect(clean.diagnostics.vaultExcludedDates).toBe(horizon + postCutoffCount);
|
||||
|
||||
for (const slice of clean.panel) {
|
||||
const idx = clean.sessionDates.indexOf(slice.date);
|
||||
expect(idx).toBeGreaterThanOrEqual(0);
|
||||
expect(slice.date < vaultCutoffDate).toBe(true);
|
||||
const fwdDate = allDates[idx + horizon]!;
|
||||
expect(fwdDate < vaultCutoffDate).toBe(true);
|
||||
}
|
||||
|
||||
// Poison every post-cutoff close with NaN -> output must be byte-identical.
|
||||
const poisonedBars: BarRecord[] = baseBars.map(b => {
|
||||
const date = new Date(b.ts).toISOString().slice(0, 10);
|
||||
return date >= vaultCutoffDate ? { ...b, close: Number.NaN } : b;
|
||||
});
|
||||
const poisoned = buildForwardReturnPanel({
|
||||
bars: poisonedBars,
|
||||
signals,
|
||||
horizonSessions: horizon,
|
||||
vaultCutoffDate,
|
||||
});
|
||||
expect(poisoned).toEqual(clean);
|
||||
|
||||
// Getter trap on every post-cutoff bar's `close` -> must never be accessed.
|
||||
let closeReadsPostCutoff = 0;
|
||||
const trappedBars: BarRecord[] = baseBars.map(b => {
|
||||
const date = new Date(b.ts).toISOString().slice(0, 10);
|
||||
if (date < vaultCutoffDate) {
|
||||
return b;
|
||||
}
|
||||
const trapped = {
|
||||
listingId: b.listingId,
|
||||
ts: b.ts,
|
||||
open: b.open,
|
||||
high: b.high,
|
||||
low: b.low,
|
||||
volume: b.volume,
|
||||
vwap: b.vwap,
|
||||
knownAt: b.knownAt,
|
||||
} as Record<string, unknown>;
|
||||
Object.defineProperty(trapped, 'close', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
closeReadsPostCutoff += 1;
|
||||
throw new Error('Post-cutoff close must never be read!');
|
||||
},
|
||||
});
|
||||
return trapped as unknown as BarRecord;
|
||||
});
|
||||
|
||||
const trappedResult = buildForwardReturnPanel({
|
||||
bars: trappedBars,
|
||||
signals,
|
||||
horizonSessions: horizon,
|
||||
vaultCutoffDate,
|
||||
});
|
||||
expect(closeReadsPostCutoff).toBe(0);
|
||||
expect(trappedResult).toEqual(clean);
|
||||
}
|
||||
});
|
||||
|
||||
it('produces byte-identical output for shuffled bars and signals and never mutates frozen inputs', () => {
|
||||
const dates = makeBusinessDates('2024-08-01', 15);
|
||||
const bars: BarRecord[] = [];
|
||||
const signals: SignalObservation[] = [];
|
||||
|
||||
for (const lid of [101, 202, 303, 404]) {
|
||||
for (let i = 0; i < dates.length; i += 1) {
|
||||
bars.push(makeBar(lid, dates[i]!, 50 + lid * 0.1 + i * 0.5));
|
||||
}
|
||||
signals.push(
|
||||
{ listingId: lid, knownAt: makeUtcMs(dates[0]!, 18), value: lid * 0.01 },
|
||||
{ listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * -0.02 },
|
||||
{ listingId: lid, knownAt: makeUtcMs(dates[4]!, 21), value: lid * 0.03 } // intentional tie
|
||||
);
|
||||
}
|
||||
|
||||
const frozenInput = Object.freeze({
|
||||
bars: Object.freeze(bars.map(b => Object.freeze({ ...b }))),
|
||||
signals: Object.freeze(signals.map(s => Object.freeze({ ...s }))),
|
||||
horizonSessions: 3,
|
||||
vaultCutoffDate: dates[12]!,
|
||||
maxSignalAgeSessions: 6,
|
||||
});
|
||||
|
||||
const baseline = buildForwardReturnPanel(frozenInput);
|
||||
|
||||
for (const seed of [1, 2, 3, 42]) {
|
||||
const shuffledResult = buildForwardReturnPanel({
|
||||
bars: shuffle(bars, seed),
|
||||
signals: shuffle(signals, seed + 100),
|
||||
horizonSessions: 3,
|
||||
vaultCutoffDate: dates[12]!,
|
||||
maxSignalAgeSessions: 6,
|
||||
});
|
||||
expect(shuffledResult).toEqual(baseline);
|
||||
}
|
||||
});
|
||||
|
||||
it('handles empty bars and post-cutoff-only bars cleanly', () => {
|
||||
const empty = buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: 1 }],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
expect(empty.panel).toEqual([]);
|
||||
expect(empty.sessionDates).toEqual([]);
|
||||
expect(empty.diagnostics).toEqual({
|
||||
vaultExcludedDates: 0,
|
||||
droppedNoSignal: 0,
|
||||
droppedStaleSignal: 0,
|
||||
droppedMissingForwardBar: 0,
|
||||
droppedNonPositiveClose: 0,
|
||||
duplicateBars: 0,
|
||||
});
|
||||
|
||||
const postOnly = buildForwardReturnPanel({
|
||||
bars: [makeBar(1, '2025-01-02', 100), makeBar(1, '2025-01-03', 101)],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
});
|
||||
expect(postOnly.panel).toEqual([]);
|
||||
expect(postOnly.sessionDates).toEqual([]);
|
||||
expect(postOnly.diagnostics.vaultExcludedDates).toBe(2);
|
||||
});
|
||||
|
||||
it('throws typed SignalPanelError for every invalid input, option, date, bar, and signal', () => {
|
||||
expectSignalPanelError(
|
||||
() => buildForwardReturnPanel(null as unknown as Parameters<typeof buildForwardReturnPanel>[0]),
|
||||
'invalid_input'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: 'not-an-array' as unknown as BarRecord[],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_input'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: 'not-an-array' as unknown as SignalObservation[],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_input'
|
||||
);
|
||||
|
||||
for (const badHorizon of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: [],
|
||||
horizonSessions: badHorizon,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_horizon'
|
||||
);
|
||||
}
|
||||
|
||||
for (const badAge of [-1, 0.5, Number.NaN, Number.POSITIVE_INFINITY]) {
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
maxSignalAgeSessions: badAge,
|
||||
}),
|
||||
'invalid_option'
|
||||
);
|
||||
}
|
||||
|
||||
for (const badDate of ['', '2025-02-29', '2025-13-01', '2025-01-01T00:00:00Z']) {
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: badDate,
|
||||
}),
|
||||
'invalid_date'
|
||||
);
|
||||
}
|
||||
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [null as unknown as BarRecord],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_bar'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [{ ...makeBar(1, '2024-01-02', 100), listingId: 1.5 }],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_bar'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [{ ...makeBar(1, '2024-01-02', 100), close: '100' as unknown as number }],
|
||||
signals: [],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_bar'
|
||||
);
|
||||
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: [null as unknown as SignalObservation],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_signal'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
buildForwardReturnPanel({
|
||||
bars: [],
|
||||
signals: [{ listingId: 1, knownAt: makeUtcMs('2024-01-02', 10), value: Number.NaN }],
|
||||
horizonSessions: 1,
|
||||
vaultCutoffDate: '2025-01-01',
|
||||
}),
|
||||
'invalid_signal'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('shortsTableToSignalRows and collectBars', () => {
|
||||
it('maps shortsAsOf table fields, skips nulls, normalizes -0, and rejects malformed inputs', () => {
|
||||
const knownAt1 = makeUtcMs('2024-02-01', 22, 0);
|
||||
const knownAt2 = makeUtcMs('2024-02-15', 22, 0);
|
||||
const table: Table = {
|
||||
columns: ['listing_id', 'report_date', 'known_at', 'shares_short', 'net_change', 'pct_float', 'source'],
|
||||
rows: [
|
||||
{
|
||||
listing_id: 10,
|
||||
report_date: '2024-01-31',
|
||||
known_at: knownAt1,
|
||||
shares_short: 50_000,
|
||||
net_change: -0,
|
||||
pct_float: 0.042,
|
||||
source: 'ceoShorts',
|
||||
},
|
||||
{
|
||||
listing_id: 20,
|
||||
report_date: '2024-02-15',
|
||||
known_at: knownAt2,
|
||||
shares_short: 12_000,
|
||||
net_change: null,
|
||||
pct_float: null,
|
||||
source: 'ceoShorts',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
expect(shortsTableToSignalRows(table, 'shares_short')).toEqual([
|
||||
{ listingId: 10, knownAt: knownAt1, value: 50_000 },
|
||||
{ listingId: 20, knownAt: knownAt2, value: 12_000 },
|
||||
]);
|
||||
|
||||
const netChangeRows = shortsTableToSignalRows(table, 'net_change');
|
||||
expect(netChangeRows).toEqual([{ listingId: 10, knownAt: knownAt1, value: 0 }]);
|
||||
expect(Object.is(netChangeRows[0]!.value, 0)).toBe(true);
|
||||
|
||||
expect(shortsTableToSignalRows(table, 'pct_float')).toEqual([
|
||||
{ listingId: 10, knownAt: knownAt1, value: 0.042 },
|
||||
]);
|
||||
|
||||
expectSignalPanelError(
|
||||
() => shortsTableToSignalRows(table, 'bad_field' as unknown as 'net_change'),
|
||||
'invalid_input'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
shortsTableToSignalRows(
|
||||
{ columns: ['listing_id', 'known_at'], rows: [] },
|
||||
'net_change'
|
||||
),
|
||||
'invalid_input'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
shortsTableToSignalRows(
|
||||
{
|
||||
columns: ['listing_id', 'known_at', 'net_change'],
|
||||
rows: [{ listing_id: 1, known_at: knownAt1, net_change: Number.POSITIVE_INFINITY }],
|
||||
},
|
||||
'net_change'
|
||||
),
|
||||
'invalid_signal'
|
||||
);
|
||||
expectSignalPanelError(
|
||||
() =>
|
||||
shortsTableToSignalRows(
|
||||
{
|
||||
columns: ['listing_id', 'known_at', 'net_change'],
|
||||
rows: [{ listing_id: 1, known_at: knownAt1 }],
|
||||
},
|
||||
'net_change'
|
||||
),
|
||||
'invalid_signal'
|
||||
);
|
||||
});
|
||||
|
||||
it('collects multi-batch async iterables without mutating batches and rejects invalid inputs', async () => {
|
||||
const b1 = makeBar(1, '2024-01-02', 100);
|
||||
const b2 = makeBar(1, '2024-01-03', 101);
|
||||
const b3 = makeBar(2, '2024-01-02', 50);
|
||||
|
||||
const batch1: BarBatch = Object.freeze({ rows: Object.freeze([b1, b2]) });
|
||||
const batch2: BarBatch = Object.freeze({ rows: Object.freeze([b3]) });
|
||||
|
||||
async function* gen(): AsyncIterable<BarBatch> {
|
||||
yield batch1;
|
||||
yield { rows: [] };
|
||||
yield batch2;
|
||||
}
|
||||
|
||||
const collected = await collectBars(gen());
|
||||
expect(collected).toEqual([b1, b2, b3]);
|
||||
|
||||
async function* emptyGen(): AsyncIterable<BarBatch> {
|
||||
// empty
|
||||
}
|
||||
expect(await collectBars(emptyGen())).toEqual([]);
|
||||
|
||||
await expectSignalPanelErrorAsync(
|
||||
() => collectBars(null as unknown as AsyncIterable<BarBatch>),
|
||||
'invalid_input'
|
||||
);
|
||||
|
||||
async function* badBatchGen(): AsyncIterable<BarBatch> {
|
||||
yield { rows: 'not-array' } as unknown as BarBatch;
|
||||
}
|
||||
await expectSignalPanelErrorAsync(() => collectBars(badBatchGen()), 'invalid_bar');
|
||||
});
|
||||
});
|
||||
599
python/benchmarks/m1_quant_scan_benchmark.py
Normal file
599
python/benchmarks/m1_quant_scan_benchmark.py
Normal file
|
|
@ -0,0 +1,599 @@
|
|||
"""M1 Exit Criterion 2 benchmark & NVDA pre-split verification on quant.
|
||||
|
||||
Measures a real 20-year (2005-01-01 .. 2025-02-12) US + CA daily scan plus one
|
||||
cross-sectional signal evaluation (IC, Q5-Q1 quantile spread, Q5 turnover,
|
||||
pre/post-2023 recency split, Newey-West t-stat, and N-hat deflated Sharpe) via
|
||||
DuckDB + Polars over curated Hive-partitioned Parquet (`bars_1d/year=*/part.parquet`),
|
||||
strictly enforcing the rolling 6-month Vault cutoff (`2025-02-13`).
|
||||
|
||||
Parquet-scan-level Vault verification (not post-filter row counting):
|
||||
1. Parses `EXPLAIN (ANALYZE, FORMAT JSON)` physical plan `READ_PARQUET` operator
|
||||
nodes to verify Vault predicates (`session_date < cutoff`, `ts < cutoff`,
|
||||
`known_at < cutoff`) are pushed into `READ_PARQUET` and records exact
|
||||
`operator_cardinality` (`parquet_scan_rows_emitted`) and `total_files_read`.
|
||||
2. Runs a poisoned-Vault canary invariance test in a temporary overlay directory
|
||||
(symlinking `year=2005..2024`, overwriting every `year=2025` Vault row
|
||||
`session_date >= 2025-02-13` with sentinel `close = 999_999_999.0`, and adding
|
||||
a `year=2026/part.parquet` Vault-only partition) proving:
|
||||
- `year=2026` is 100% file-pruned (`total_files_read == 21`, not `22`),
|
||||
- `READ_PARQUET` `operator_cardinality` is unchanged, and
|
||||
- all evaluated signal metrics are bit-for-bit identical.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import shutil
|
||||
import tempfile
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import duckdb
|
||||
import numpy as np
|
||||
import polars as pl
|
||||
|
||||
from stockbot.calculations import (
|
||||
deflated_sharpe_ratio,
|
||||
evaluate_recency_gate,
|
||||
newey_west_mean_test,
|
||||
trial_moments,
|
||||
)
|
||||
from stockbot.vault import (
|
||||
DEFAULT_DUCKDB_MEMORY_LIMIT,
|
||||
DEFAULT_DUCKDB_THREADS,
|
||||
compute_vault_cutoff_ts,
|
||||
)
|
||||
|
||||
|
||||
def _open_duckdb(temp_dir: Path) -> duckdb.DuckDBPyConnection:
|
||||
con = duckdb.connect(":memory:")
|
||||
con.execute(f"SET memory_limit = '{DEFAULT_DUCKDB_MEMORY_LIMIT}'")
|
||||
con.execute(f"SET threads = {DEFAULT_DUCKDB_THREADS}")
|
||||
con.execute(f"SET temp_directory = '{temp_dir}'")
|
||||
con.execute("SET preserve_insertion_order = false")
|
||||
return con
|
||||
|
||||
|
||||
def _build_signal_sql(bars_glob: str) -> str:
|
||||
return f"""
|
||||
WITH fenced AS (
|
||||
SELECT
|
||||
listing_id,
|
||||
session_date,
|
||||
close,
|
||||
volume
|
||||
FROM read_parquet('{bars_glob}', hive_partitioning = true)
|
||||
WHERE year <= 2025
|
||||
AND session_date >= CAST(? AS DATE)
|
||||
AND session_date < CAST(? AS DATE)
|
||||
AND ts < CAST(? AS TIMESTAMPTZ)
|
||||
AND known_at < CAST(? AS TIMESTAMPTZ)
|
||||
AND currency IN ('USD', 'CAD')
|
||||
AND close > 0
|
||||
AND volume > 0
|
||||
),
|
||||
lagged AS (
|
||||
SELECT
|
||||
listing_id,
|
||||
session_date,
|
||||
close,
|
||||
volume,
|
||||
LAG(close, 20) OVER w AS prev_close,
|
||||
LEAD(close, 5) OVER w AS fwd_close
|
||||
FROM fenced
|
||||
WINDOW w AS (PARTITION BY listing_id ORDER BY session_date)
|
||||
),
|
||||
liquid AS MATERIALIZED (
|
||||
SELECT
|
||||
listing_id,
|
||||
session_date,
|
||||
-LN(close / prev_close) AS signal,
|
||||
GREATEST(LEAST((fwd_close / close) - 1.0, 1.0), -0.95) AS fwd_ret
|
||||
FROM lagged
|
||||
WHERE prev_close > 0
|
||||
AND fwd_close > 0
|
||||
AND close >= 2.0
|
||||
AND close * volume >= 1000000
|
||||
AND ABS(LN(close / prev_close)) < 2.0
|
||||
),
|
||||
daily_raw AS (
|
||||
SELECT
|
||||
session_date,
|
||||
COUNT(*)::BIGINT AS n_names,
|
||||
CORR(signal, fwd_ret) AS ic,
|
||||
QUANTILE_CONT(signal, 0.2) AS q20,
|
||||
QUANTILE_CONT(signal, 0.8) AS q80
|
||||
FROM liquid
|
||||
GROUP BY session_date
|
||||
HAVING COUNT(*) >= 50 AND NOT ISNAN(CORR(signal, fwd_ret))
|
||||
),
|
||||
prev_dates AS (
|
||||
SELECT
|
||||
session_date,
|
||||
n_names,
|
||||
ic,
|
||||
q20,
|
||||
q80,
|
||||
LAG(session_date) OVER (ORDER BY session_date) AS prev_session_date
|
||||
FROM daily_raw
|
||||
),
|
||||
extremes AS (
|
||||
SELECT
|
||||
l.session_date,
|
||||
l.listing_id,
|
||||
l.fwd_ret,
|
||||
p.prev_session_date,
|
||||
(l.signal >= p.q80) AS is_q5,
|
||||
(l.signal <= p.q20) AS is_q1
|
||||
FROM liquid l
|
||||
JOIN prev_dates p ON p.session_date = l.session_date
|
||||
WHERE l.signal >= p.q80 OR l.signal <= p.q20
|
||||
),
|
||||
q5_tagged AS (
|
||||
SELECT
|
||||
session_date,
|
||||
fwd_ret,
|
||||
prev_session_date,
|
||||
is_q5,
|
||||
is_q1,
|
||||
CASE
|
||||
WHEN is_q5 THEN LAG(session_date) OVER (
|
||||
PARTITION BY listing_id, is_q5 ORDER BY session_date
|
||||
)
|
||||
ELSE NULL
|
||||
END AS prev_q5_date
|
||||
FROM extremes
|
||||
),
|
||||
daily_stats AS (
|
||||
SELECT
|
||||
session_date,
|
||||
AVG(fwd_ret) FILTER (WHERE is_q5) - AVG(fwd_ret) FILTER (WHERE is_q1) AS q5_q1_spread,
|
||||
1.0 - AVG(CASE WHEN prev_q5_date = prev_session_date THEN 1.0 ELSE 0.0 END)
|
||||
FILTER (WHERE is_q5 AND prev_session_date IS NOT NULL) AS q5_turnover
|
||||
FROM q5_tagged
|
||||
GROUP BY session_date
|
||||
)
|
||||
SELECT
|
||||
p.session_date::VARCHAR AS session_date,
|
||||
p.n_names,
|
||||
p.ic,
|
||||
d.q5_q1_spread,
|
||||
d.q5_turnover
|
||||
FROM prev_dates p
|
||||
JOIN daily_stats d ON d.session_date = p.session_date
|
||||
ORDER BY p.session_date
|
||||
"""
|
||||
|
||||
|
||||
def _extract_parquet_scan_nodes(node: dict[str, Any]) -> list[dict[str, Any]]:
|
||||
found: list[dict[str, Any]] = []
|
||||
if node.get("operator_type") == "TABLE_SCAN" or node.get("operator_name") == "READ_PARQUET":
|
||||
extra = node.get("extra_info") or {}
|
||||
found.append(
|
||||
{
|
||||
"operator_name": node.get("operator_name"),
|
||||
"operator_cardinality": int(node.get("operator_cardinality", 0)),
|
||||
"operator_rows_scanned": int(node.get("operator_rows_scanned", 0)),
|
||||
"total_files_read": int(extra.get("Total Files Read", 0))
|
||||
if str(extra.get("Total Files Read", "")).isdigit()
|
||||
else extra.get("Total Files Read"),
|
||||
"pushed_filters": extra.get("Filters", []),
|
||||
"projections": extra.get("Projections", []),
|
||||
}
|
||||
)
|
||||
for child in node.get("children", []):
|
||||
found.extend(_extract_parquet_scan_nodes(child))
|
||||
return found
|
||||
|
||||
|
||||
def _evaluate_signal_once(
|
||||
con: duckdb.DuckDBPyConnection,
|
||||
bars_glob: str,
|
||||
start_date: str,
|
||||
vault_cutoff_iso_date: str,
|
||||
vault_cutoff_iso_ts: str,
|
||||
) -> dict[str, Any]:
|
||||
sql = _build_signal_sql(bars_glob)
|
||||
params = [
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
vault_cutoff_iso_ts,
|
||||
]
|
||||
t0 = time.perf_counter()
|
||||
daily_df = con.execute(sql, params).pl()
|
||||
t_sql = time.perf_counter()
|
||||
|
||||
session_dates = daily_df["session_date"].to_list()
|
||||
spreads = daily_df["q5_q1_spread"].drop_nulls().to_list()
|
||||
ics = daily_df["ic"].drop_nulls().to_list()
|
||||
turnovers = daily_df["q5_turnover"].drop_nulls().to_list()
|
||||
|
||||
moments = trial_moments(spreads)
|
||||
nw_res = newey_west_mean_test(spreads, lag=5)
|
||||
recency = evaluate_recency_gate(session_dates, daily_df["ic"].to_list())
|
||||
dsr_res = deflated_sharpe_ratio(
|
||||
sharpe_unann=moments.sharpe_unann,
|
||||
n_obs=moments.n_obs,
|
||||
skewness=moments.skewness,
|
||||
kurtosis=moments.kurtosis,
|
||||
n_hat=1.0,
|
||||
cluster_sharpes=[moments.sharpe_unann],
|
||||
)
|
||||
t_end = time.perf_counter()
|
||||
|
||||
return {
|
||||
"wall_secs": round(t_end - t0, 4),
|
||||
"sql_secs": round(t_sql - t0, 4),
|
||||
"post_secs": round(t_end - t_sql, 4),
|
||||
"under_5s": (t_end - t0) < 5.0,
|
||||
"min_date": session_dates[0] if session_dates else None,
|
||||
"max_date": session_dates[-1] if session_dates else None,
|
||||
"vault_cutoff_date": vault_cutoff_iso_date,
|
||||
"n_sessions_evaluated": int(daily_df.height),
|
||||
"mean_ic": round(float(np.mean(ics)), 6) if ics else 0.0,
|
||||
"mean_q5_q1_spread": round(float(nw_res.mean), 6),
|
||||
"mean_q5_turnover": round(float(np.mean(turnovers)), 6) if turnovers else 0.0,
|
||||
"recency_gate": recency,
|
||||
"sharpe_unann": round(moments.sharpe_unann, 6),
|
||||
"sharpe_ann": round(moments.sharpe_unann * math.sqrt(252.0), 4),
|
||||
"newey_west_t_stat": round(float(nw_res.t_stat), 4),
|
||||
"newey_west_p_value": round(float(nw_res.p_value), 6),
|
||||
"dsr": round(float(dsr_res.dsr), 6),
|
||||
}
|
||||
|
||||
|
||||
def _profile_parquet_scan(
|
||||
con: duckdb.DuckDBPyConnection,
|
||||
bars_glob: str,
|
||||
start_date: str,
|
||||
vault_cutoff_iso_date: str,
|
||||
vault_cutoff_iso_ts: str,
|
||||
) -> dict[str, Any]:
|
||||
sql = "EXPLAIN (ANALYZE, FORMAT JSON)\n" + _build_signal_sql(bars_glob)
|
||||
params = [
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
vault_cutoff_iso_ts,
|
||||
]
|
||||
raw_json = con.execute(sql, params).fetchall()[0][1]
|
||||
plan = json.loads(raw_json)
|
||||
scans = _extract_parquet_scan_nodes(plan)
|
||||
assert len(scans) == 1, f"Expected single READ_PARQUET scan, got {len(scans)}"
|
||||
scan = scans[0]
|
||||
filters_joined = " | ".join(str(f) for f in scan["pushed_filters"])
|
||||
return {
|
||||
"explain_analyze_latency_secs": round(float(plan.get("latency", 0.0)), 4),
|
||||
"total_files_read": scan["total_files_read"],
|
||||
"parquet_scan_rows_emitted": scan["operator_cardinality"],
|
||||
"pushed_filters": scan["pushed_filters"],
|
||||
"vault_session_date_pushed": vault_cutoff_iso_date in filters_joined,
|
||||
"vault_ts_pushed": "ts<" in filters_joined.replace(" ", ""),
|
||||
"vault_known_at_pushed": "known_at<" in filters_joined.replace(" ", ""),
|
||||
}
|
||||
|
||||
|
||||
def _run_poisoned_vault_canary(
|
||||
curated_root: Path,
|
||||
temp_dir: Path,
|
||||
start_date: str,
|
||||
vault_cutoff_iso_date: str,
|
||||
vault_cutoff_iso_ts: str,
|
||||
baseline_result: dict[str, Any],
|
||||
baseline_scan: dict[str, Any],
|
||||
) -> dict[str, Any]:
|
||||
"""Mutates all Vault rows (>= cutoff) and adds a year=2026 partition in an isolated overlay.
|
||||
|
||||
Proves at the Parquet-scan and signal-output level that:
|
||||
1. A post-cutoff Hive partition (`year=2026`) is 100% file-pruned (`total_files_read` unchanged).
|
||||
2. Mutating all 3.36M Vault rows in `year=2025` to sentinel `close=999_999_999.0` leaves
|
||||
`READ_PARQUET` `operator_cardinality` and every signal metric bit-for-bit identical.
|
||||
"""
|
||||
overlay_dir = Path(tempfile.mkdtemp(prefix="vault-canary-", dir=str(temp_dir)))
|
||||
try:
|
||||
overlay_bars = overlay_dir / "bars_1d"
|
||||
overlay_bars.mkdir(parents=True, exist_ok=True)
|
||||
src_bars = curated_root / "bars_1d"
|
||||
for child in sorted(src_bars.iterdir()):
|
||||
if child.name == "year=2025":
|
||||
continue
|
||||
(overlay_bars / child.name).symlink_to(child)
|
||||
|
||||
# Build poisoned year=2025 (mutating every row >= vault_cutoff_date) and year=2026
|
||||
(overlay_bars / "year=2025").mkdir()
|
||||
(overlay_bars / "year=2026").mkdir()
|
||||
pcon = _open_duckdb(temp_dir)
|
||||
try:
|
||||
src_2025 = str(src_bars / "year=2025" / "part.parquet")
|
||||
dst_2025 = str(overlay_bars / "year=2025" / "part.parquet")
|
||||
dst_2026 = str(overlay_bars / "year=2026" / "part.parquet")
|
||||
pcon.execute(
|
||||
f"""
|
||||
COPY (
|
||||
SELECT
|
||||
listing_id,
|
||||
session_date,
|
||||
ts,
|
||||
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE open END AS open,
|
||||
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE high END AS high,
|
||||
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE low END AS low,
|
||||
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999.0::DOUBLE ELSE close END AS close,
|
||||
CASE WHEN session_date >= CAST(? AS DATE) THEN 999999999999.0::DOUBLE ELSE volume END AS volume,
|
||||
vwap,
|
||||
currency,
|
||||
source,
|
||||
known_at
|
||||
FROM read_parquet('{src_2025}')
|
||||
) TO '{dst_2025}' (FORMAT PARQUET, COMPRESSION ZSTD)
|
||||
""",
|
||||
[vault_cutoff_iso_date] * 5,
|
||||
)
|
||||
pcon.execute(
|
||||
f"""
|
||||
COPY (
|
||||
SELECT
|
||||
listing_id,
|
||||
DATE '2026-01-15' AS session_date,
|
||||
TIMESTAMPTZ '2026-01-15 21:00:00+00' AS ts,
|
||||
999999999.0::DOUBLE AS open,
|
||||
999999999.0::DOUBLE AS high,
|
||||
999999999.0::DOUBLE AS low,
|
||||
999999999.0::DOUBLE AS close,
|
||||
999999999999.0::DOUBLE AS volume,
|
||||
vwap,
|
||||
currency,
|
||||
source,
|
||||
TIMESTAMPTZ '2026-01-15 21:00:00+00' AS known_at
|
||||
FROM read_parquet('{src_2025}')
|
||||
LIMIT 10000
|
||||
) TO '{dst_2026}' (FORMAT PARQUET, COMPRESSION ZSTD)
|
||||
"""
|
||||
)
|
||||
|
||||
overlay_glob = str(overlay_bars / "year=*" / "part.parquet")
|
||||
poisoned_vault_rows_on_disk = int(
|
||||
pcon.execute(
|
||||
f"SELECT COUNT(*) FROM read_parquet('{overlay_glob}', hive_partitioning = true) WHERE close = 999999999.0"
|
||||
).fetchone()[0]
|
||||
)
|
||||
overlay_files_on_disk = len(list(overlay_bars.glob("year=*/part.parquet")))
|
||||
canary_result = _evaluate_signal_once(
|
||||
pcon,
|
||||
overlay_glob,
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
)
|
||||
canary_scan = _profile_parquet_scan(
|
||||
pcon,
|
||||
overlay_glob,
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
)
|
||||
finally:
|
||||
pcon.close()
|
||||
|
||||
keys_to_match = [
|
||||
"n_sessions_evaluated",
|
||||
"mean_ic",
|
||||
"mean_q5_q1_spread",
|
||||
"mean_q5_turnover",
|
||||
"sharpe_unann",
|
||||
"newey_west_t_stat",
|
||||
"dsr",
|
||||
]
|
||||
bit_identical = all(canary_result[k] == baseline_result[k] for k in keys_to_match)
|
||||
year_2026_pruned = (
|
||||
overlay_files_on_disk == int(baseline_scan["total_files_read"]) + 1
|
||||
and canary_scan["total_files_read"] == baseline_scan["total_files_read"]
|
||||
)
|
||||
scan_cardinality_identical = (
|
||||
canary_scan["parquet_scan_rows_emitted"]
|
||||
== baseline_scan["parquet_scan_rows_emitted"]
|
||||
)
|
||||
|
||||
return {
|
||||
"overlay_files_on_disk": overlay_files_on_disk,
|
||||
"overlay_files_read_by_parquet_scan": canary_scan["total_files_read"],
|
||||
"year_2026_partition_pruned": year_2026_pruned,
|
||||
"poisoned_vault_rows_on_disk": poisoned_vault_rows_on_disk,
|
||||
"canary_parquet_scan_rows_emitted": canary_scan["parquet_scan_rows_emitted"],
|
||||
"scan_cardinality_identical": scan_cardinality_identical,
|
||||
"signal_metrics_bit_identical": bit_identical,
|
||||
"pass": bool(
|
||||
poisoned_vault_rows_on_disk > 0
|
||||
and year_2026_pruned
|
||||
and scan_cardinality_identical
|
||||
and bit_identical
|
||||
),
|
||||
}
|
||||
finally:
|
||||
shutil.rmtree(overlay_dir, ignore_errors=True)
|
||||
|
||||
|
||||
def run_benchmark(
|
||||
curated_root: Path,
|
||||
temp_dir: Path,
|
||||
max_ingested_date: str = "2025-08-13",
|
||||
start_date: str = "2005-01-01",
|
||||
nvda_listing_id: int | None = None,
|
||||
qm_nvda_dollar_vol: float | None = None,
|
||||
) -> dict[str, object]:
|
||||
temp_dir.mkdir(parents=True, exist_ok=True)
|
||||
vault_cutoff_ms = compute_vault_cutoff_ts(max_ingested_date)
|
||||
vault_cutoff_dt = datetime.fromtimestamp(vault_cutoff_ms / 1000.0, tz=timezone.utc)
|
||||
vault_cutoff_iso_date = vault_cutoff_dt.strftime("%Y-%m-%d")
|
||||
vault_cutoff_iso_ts = vault_cutoff_dt.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
|
||||
|
||||
bars_glob = str(curated_root / "bars_1d" / "year=*" / "part.parquet")
|
||||
|
||||
# 1. Run 1 on a fresh DuckDB connection (before any warmup query on bars_1d)
|
||||
con_cold = _open_duckdb(temp_dir)
|
||||
try:
|
||||
run1 = _evaluate_signal_once(
|
||||
con_cold,
|
||||
bars_glob,
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
)
|
||||
# Run 2 on the same warm DuckDB connection
|
||||
run2 = _evaluate_signal_once(
|
||||
con_cold,
|
||||
bars_glob,
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
)
|
||||
# Parquet-scan-level physical plan inspection (EXPLAIN ANALYZE FORMAT JSON)
|
||||
scan_audit = _profile_parquet_scan(
|
||||
con_cold,
|
||||
bars_glob,
|
||||
start_date,
|
||||
vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts,
|
||||
)
|
||||
|
||||
# NVDA pre-split 2024-06-07 dollar volume verification
|
||||
nvda_check: dict[str, object] | None = None
|
||||
if nvda_listing_id is not None:
|
||||
nvda_row = con_cold.execute(
|
||||
f"""
|
||||
SELECT session_date::VARCHAR, open, high, low, close, volume, close * volume AS dollar_volume, currency
|
||||
FROM read_parquet('{bars_glob}', hive_partitioning = true)
|
||||
WHERE listing_id = ? AND session_date IN (DATE '2024-06-07', DATE '2024-06-10')
|
||||
ORDER BY session_date
|
||||
""",
|
||||
[nvda_listing_id],
|
||||
).fetchall()
|
||||
pre_split = next((r for r in nvda_row if r[0] == "2024-06-07"), None)
|
||||
post_split = next((r for r in nvda_row if r[0] == "2024-06-10"), None)
|
||||
rel_diff: float | None = None
|
||||
if pre_split is not None and qm_nvda_dollar_vol is not None and qm_nvda_dollar_vol > 0:
|
||||
rel_diff = abs(float(pre_split[6]) - qm_nvda_dollar_vol) / qm_nvda_dollar_vol
|
||||
nvda_check = {
|
||||
"listing_id": nvda_listing_id,
|
||||
"pre_split_2024_06_07": (
|
||||
{
|
||||
"close": float(pre_split[4]),
|
||||
"raw_volume": float(pre_split[5]),
|
||||
"dollar_volume": float(pre_split[6]),
|
||||
"currency": pre_split[7],
|
||||
}
|
||||
if pre_split
|
||||
else None
|
||||
),
|
||||
"post_split_2024_06_10": (
|
||||
{
|
||||
"close": float(post_split[4]),
|
||||
"raw_volume": float(post_split[5]),
|
||||
"dollar_volume": float(post_split[6]),
|
||||
"currency": post_split[7],
|
||||
}
|
||||
if post_split
|
||||
else None
|
||||
),
|
||||
"qm_pre_split_dollar_volume": qm_nvda_dollar_vol,
|
||||
"rel_diff": rel_diff,
|
||||
"within_1pct": rel_diff is not None and rel_diff <= 0.01,
|
||||
}
|
||||
|
||||
# Exact dataset totals on disk
|
||||
vault_rows_on_disk = int(
|
||||
con_cold.execute(
|
||||
f"SELECT COUNT(*) FROM read_parquet('{bars_glob}', hive_partitioning = true) WHERE session_date >= CAST(? AS DATE)",
|
||||
[vault_cutoff_iso_date],
|
||||
).fetchone()[0]
|
||||
)
|
||||
scan_stats = con_cold.execute(
|
||||
f"""
|
||||
SELECT COUNT(*)::BIGINT, COUNT(DISTINCT listing_id)::BIGINT, MIN(session_date)::VARCHAR, MAX(session_date)::VARCHAR
|
||||
FROM read_parquet('{bars_glob}', hive_partitioning = true)
|
||||
WHERE session_date >= CAST(? AS DATE)
|
||||
AND session_date < CAST(? AS DATE)
|
||||
AND currency IN ('USD', 'CAD')
|
||||
AND close > 0 AND volume > 0
|
||||
""",
|
||||
[start_date, vault_cutoff_iso_date],
|
||||
).fetchone()
|
||||
total_rows_in_scan = int(scan_stats[0])
|
||||
distinct_listings_in_scan = int(scan_stats[1])
|
||||
finally:
|
||||
con_cold.close()
|
||||
|
||||
# Poisoned-Vault canary test proving scan-level & signal-level Vault isolation
|
||||
vault_canary = _run_poisoned_vault_canary(
|
||||
curated_root=curated_root,
|
||||
temp_dir=temp_dir,
|
||||
start_date=start_date,
|
||||
vault_cutoff_iso_date=vault_cutoff_iso_date,
|
||||
vault_cutoff_iso_ts=vault_cutoff_iso_ts,
|
||||
baseline_result=run1,
|
||||
baseline_scan=scan_audit,
|
||||
)
|
||||
|
||||
return {
|
||||
"host": os.uname().nodename,
|
||||
"curated_root": str(curated_root),
|
||||
"duckdb_version": duckdb.__version__,
|
||||
"polars_version": pl.__version__,
|
||||
"duckdb_budget": {
|
||||
"memory_limit": DEFAULT_DUCKDB_MEMORY_LIMIT,
|
||||
"threads": DEFAULT_DUCKDB_THREADS,
|
||||
"temp_directory": str(temp_dir),
|
||||
},
|
||||
"cache_state_note": (
|
||||
"run1_fresh_conn runs on a brand-new DuckDB process/connection with no prior queries; "
|
||||
"run2_warm_conn reuses the warm DuckDB connection. Unprivileged execution does not "
|
||||
"drop Linux kernel OS page cache (/proc/sys/vm/drop_caches requires root)."
|
||||
),
|
||||
"vault_cutoff_date": vault_cutoff_iso_date,
|
||||
"vault_rows_on_disk": vault_rows_on_disk,
|
||||
"total_rows_in_scan": total_rows_in_scan,
|
||||
"distinct_listings_in_scan": distinct_listings_in_scan,
|
||||
"scan_date_min": scan_stats[2],
|
||||
"scan_date_max": scan_stats[3],
|
||||
"nvda_pre_split_check": nvda_check,
|
||||
"parquet_scan_vault_audit": scan_audit,
|
||||
"poisoned_vault_canary": vault_canary,
|
||||
"run1_fresh_conn": run1,
|
||||
"run2_warm_conn": run2,
|
||||
"both_runs_under_5s": bool(run1["under_5s"] and run2["under_5s"]),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description="M1 quant 20y US/CA scan + signal benchmark")
|
||||
parser.add_argument("--curated-root", type=Path, required=True)
|
||||
parser.add_argument("--temp-dir", type=Path, required=True)
|
||||
parser.add_argument("--max-ingested-date", default="2025-08-13")
|
||||
parser.add_argument("--start-date", default="2005-01-01")
|
||||
parser.add_argument("--nvda-listing-id", type=int, default=None)
|
||||
parser.add_argument("--qm-nvda-dollar-vol", type=float, default=None)
|
||||
parser.add_argument("--out-json", type=Path, default=None)
|
||||
args = parser.parse_args()
|
||||
|
||||
result = run_benchmark(
|
||||
curated_root=args.curated_root,
|
||||
temp_dir=args.temp_dir,
|
||||
max_ingested_date=args.max_ingested_date,
|
||||
start_date=args.start_date,
|
||||
nvda_listing_id=args.nvda_listing_id,
|
||||
qm_nvda_dollar_vol=args.qm_nvda_dollar_vol,
|
||||
)
|
||||
rendered = json.dumps(result, indent=2)
|
||||
print(rendered)
|
||||
if args.out_json is not None:
|
||||
args.out_json.parent.mkdir(parents=True, exist_ok=True)
|
||||
args.out_json.write_text(rendered + "\n", encoding="utf-8")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
29
python/pyproject.toml
Normal file
29
python/pyproject.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
[project]
|
||||
name = "stockbot"
|
||||
version = "0.1.0"
|
||||
description = "Stock Bot Python Research SDK (Vault-fenced DuckDB/Parquet MarketDataStore, Signal Analyzer, Event Study, trial_ledger DSR)"
|
||||
requires-python = ">=3.11"
|
||||
dependencies = [
|
||||
"duckdb>=1.2.0,<2.0.0",
|
||||
"polars>=1.20.0,<2.0.0",
|
||||
"marimo>=0.11.0,<1.0.0",
|
||||
"psycopg[binary]>=3.2.0,<4.0.0",
|
||||
"numpy>=1.26.0,<3.0.0",
|
||||
"scipy>=1.13.0,<2.0.0",
|
||||
"pyarrow>=18.0.0,<22.0.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest>=8.0.0,<9.0.0",
|
||||
]
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling>=1.25.0"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["stockbot"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
80
python/stockbot/__init__.py
Normal file
80
python/stockbot/__init__.py
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
"""Stock Bot Python Research SDK (`stockbot`)."""
|
||||
|
||||
from . import data
|
||||
from .calculations import (
|
||||
DSR_VALIDATION_GATE,
|
||||
EULER_MASCHERONI,
|
||||
RECENCY_MIN_RATIO,
|
||||
RECENCY_SPLIT_DATE,
|
||||
DeflatedSharpeResult,
|
||||
EffectiveTrialsResult,
|
||||
NeweyWestResult,
|
||||
TrialMoments,
|
||||
analyze_signal_panel,
|
||||
compute_event_study,
|
||||
deflated_sharpe_ratio,
|
||||
effective_independent_trials,
|
||||
evaluate_recency_gate,
|
||||
newey_west_mean_test,
|
||||
trial_moments,
|
||||
)
|
||||
from .data import MarketDataStore
|
||||
from .ledger import (
|
||||
ClusterDsrSummary,
|
||||
RecordedTrial,
|
||||
TrialLedgerClient,
|
||||
canonical_expression_hash,
|
||||
)
|
||||
from .signals import run_event_study_trial, run_signal_study
|
||||
from .vault import (
|
||||
DEFAULT_DUCKDB_MEMORY_LIMIT,
|
||||
DEFAULT_DUCKDB_TEMP_DIRECTORY,
|
||||
DEFAULT_DUCKDB_THREADS,
|
||||
DuckDbConnectionBudget,
|
||||
FencedTimeRange,
|
||||
MarketDataStoreValidationError,
|
||||
VaultHoldoutFenceError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
apply_vault_fence,
|
||||
compute_vault_cutoff_ts,
|
||||
resolve_duckdb_budget,
|
||||
vault_cutoff_date_str,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"data",
|
||||
"MarketDataStore",
|
||||
"TrialLedgerClient",
|
||||
"RecordedTrial",
|
||||
"ClusterDsrSummary",
|
||||
"canonical_expression_hash",
|
||||
"run_signal_study",
|
||||
"run_event_study_trial",
|
||||
"analyze_signal_panel",
|
||||
"compute_event_study",
|
||||
"trial_moments",
|
||||
"effective_independent_trials",
|
||||
"deflated_sharpe_ratio",
|
||||
"newey_west_mean_test",
|
||||
"evaluate_recency_gate",
|
||||
"TrialMoments",
|
||||
"EffectiveTrialsResult",
|
||||
"DeflatedSharpeResult",
|
||||
"NeweyWestResult",
|
||||
"DSR_VALIDATION_GATE",
|
||||
"EULER_MASCHERONI",
|
||||
"RECENCY_SPLIT_DATE",
|
||||
"RECENCY_MIN_RATIO",
|
||||
"DEFAULT_DUCKDB_MEMORY_LIMIT",
|
||||
"DEFAULT_DUCKDB_THREADS",
|
||||
"DEFAULT_DUCKDB_TEMP_DIRECTORY",
|
||||
"DuckDbConnectionBudget",
|
||||
"FencedTimeRange",
|
||||
"MarketDataStoreValidationError",
|
||||
"VaultHoldoutFenceError",
|
||||
"VaultScopeNotAuthorizedError",
|
||||
"apply_vault_fence",
|
||||
"compute_vault_cutoff_ts",
|
||||
"resolve_duckdb_budget",
|
||||
"vault_cutoff_date_str",
|
||||
]
|
||||
494
python/stockbot/calculations.py
Normal file
494
python/stockbot/calculations.py
Normal file
|
|
@ -0,0 +1,494 @@
|
|||
"""Canonical quantitative validation metrics matching `@stock-bot/calculations`.
|
||||
|
||||
Exact formulas from `design/VALIDATION-AND-RIGOR.md` §1, §2.B, §2.C, §3.2:
|
||||
- `trial_moments`: sample std (N - 1), plugin skewness m3/m2^(3/2), Pearson kurtosis m4/m2^2
|
||||
- `effective_independent_trials`: Bailey & Lopez de Prado N-hat
|
||||
- `deflated_sharpe_ratio`: non-normal DSR with Euler-Mascheroni gamma = 0.5772156649015329
|
||||
- `newey_west_mean_test`: Bartlett kernel HAC t-stat and two-sided normal p-value
|
||||
- `analyze_signal_panel`: fast vectorized Polars/NumPy IC, Rank-IC, quantiles, turnover, recency
|
||||
- `compute_event_study`: zero-look-ahead AAR/CAAR, R-7 CAR fans, date-clustered HAC t-stat, recency
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from dataclasses import dataclass
|
||||
from typing import Sequence
|
||||
|
||||
import numpy as np
|
||||
import polars as pl
|
||||
from scipy.stats import norm
|
||||
|
||||
EULER_MASCHERONI = 0.5772156649015329
|
||||
DSR_VALIDATION_GATE = 0.95
|
||||
RECENCY_SPLIT_DATE = "2023-01-01"
|
||||
RECENCY_MIN_RATIO = 0.5
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class TrialMoments:
|
||||
n_obs: int
|
||||
sharpe_unann: float
|
||||
skewness: float
|
||||
kurtosis: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class EffectiveTrialsResult:
|
||||
k: int
|
||||
pairs_used: int
|
||||
pairs_skipped: int
|
||||
mean_correlation: float | None
|
||||
n_hat: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DeflatedSharpeResult:
|
||||
sr0: float
|
||||
standard_error: float
|
||||
dsr: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class NeweyWestResult:
|
||||
n_obs: int
|
||||
lag: int
|
||||
mean: float
|
||||
standard_error: float
|
||||
t_stat: float
|
||||
p_value: float
|
||||
|
||||
|
||||
def trial_moments(series: Sequence[float] | np.ndarray, daily_risk_free: float = 0.0) -> TrialMoments:
|
||||
"""Computes canonical per-trial moments matching `trialMoments` in `@stock-bot/calculations`."""
|
||||
arr = np.asarray(series, dtype=np.float64)
|
||||
finite = arr[np.isfinite(arr)]
|
||||
n = int(finite.size)
|
||||
if n < 2:
|
||||
raise ValueError(f"trial_moments requires at least 2 finite observations (got {n}).")
|
||||
|
||||
mean_val = float(np.mean(finite))
|
||||
centered = finite - mean_val
|
||||
m2 = float(np.mean(centered * centered))
|
||||
if m2 <= 0.0:
|
||||
raise ValueError("trial_moments requires non-zero variance.")
|
||||
|
||||
sample_std = math.sqrt(float(np.sum(centered * centered)) / (n - 1))
|
||||
sharpe_unann = (mean_val - daily_risk_free) / sample_std
|
||||
m3 = float(np.mean(centered ** 3))
|
||||
m4 = float(np.mean(centered ** 4))
|
||||
skewness = m3 / (m2 ** 1.5)
|
||||
kurtosis = m4 / (m2 * m2)
|
||||
return TrialMoments(
|
||||
n_obs=n,
|
||||
sharpe_unann=float(sharpe_unann),
|
||||
skewness=float(skewness),
|
||||
kurtosis=float(kurtosis),
|
||||
)
|
||||
|
||||
|
||||
def newey_west_mean_test(
|
||||
series: Sequence[float] | np.ndarray, lag: int | None = None
|
||||
) -> NeweyWestResult:
|
||||
"""Bartlett-kernel Newey-West HAC test for H0: mean == 0."""
|
||||
arr = np.asarray(series, dtype=np.float64)
|
||||
arr = arr[np.isfinite(arr)]
|
||||
n = int(arr.size)
|
||||
if n < 2:
|
||||
return NeweyWestResult(
|
||||
n_obs=n, lag=0, mean=float("nan"), standard_error=float("nan"), t_stat=float("nan"), p_value=float("nan")
|
||||
)
|
||||
max_lag = lag if lag is not None else max(1, int(math.floor(4.0 * ((n / 100.0) ** (2.0 / 9.0)))))
|
||||
max_lag = min(max_lag, n - 1)
|
||||
mean_val = float(np.mean(arr))
|
||||
u = arr - mean_val
|
||||
gamma0 = float(np.dot(u, u)) / n
|
||||
lrv = gamma0
|
||||
for l in range(1, max_lag + 1):
|
||||
weight = 1.0 - l / (max_lag + 1.0)
|
||||
gamma_l = float(np.dot(u[l:], u[:-l])) / n
|
||||
lrv += 2.0 * weight * gamma_l
|
||||
lrv = max(lrv, 0.0)
|
||||
se = math.sqrt(lrv / n) if lrv > 0.0 else 0.0
|
||||
if se == 0.0:
|
||||
t_stat = 0.0 if mean_val == 0.0 else math.copysign(float("inf"), mean_val)
|
||||
p_val = 1.0 if mean_val == 0.0 else 0.0
|
||||
else:
|
||||
t_stat = mean_val / se
|
||||
p_val = float(2.0 * (1.0 - norm.cdf(abs(t_stat))))
|
||||
return NeweyWestResult(
|
||||
n_obs=n, lag=max_lag, mean=mean_val, standard_error=se, t_stat=float(t_stat), p_value=p_val
|
||||
)
|
||||
|
||||
|
||||
def effective_independent_trials(
|
||||
aligned_series_by_id: Sequence[tuple[int, dict[str, float]]]
|
||||
) -> EffectiveTrialsResult:
|
||||
"""Computes Bailey & Lopez de Prado effective independent trials N-hat."""
|
||||
k = len(aligned_series_by_id)
|
||||
if k <= 1:
|
||||
return EffectiveTrialsResult(k=k, pairs_used=0, pairs_skipped=0, mean_correlation=None, n_hat=1.0)
|
||||
|
||||
corr_sum = 0.0
|
||||
pairs_used = 0
|
||||
pairs_skipped = 0
|
||||
|
||||
for i in range(k):
|
||||
_, map_i = aligned_series_by_id[i]
|
||||
keys_i = set(map_i.keys())
|
||||
for j in range(i + 1, k):
|
||||
_, map_j = aligned_series_by_id[j]
|
||||
common = sorted(keys_i.intersection(map_j.keys()))
|
||||
if len(common) < 2:
|
||||
pairs_skipped += 1
|
||||
continue
|
||||
xi = np.array([map_i[d] for d in common], dtype=np.float64)
|
||||
xj = np.array([map_j[d] for d in common], dtype=np.float64)
|
||||
xi -= xi.mean()
|
||||
xj -= xj.mean()
|
||||
denom = math.sqrt(float(np.dot(xi, xi) * np.dot(xj, xj)))
|
||||
if denom <= 0.0 or not math.isfinite(denom):
|
||||
pairs_skipped += 1
|
||||
continue
|
||||
rho = max(-1.0, min(1.0, float(np.dot(xi, xj)) / denom))
|
||||
corr_sum += rho
|
||||
pairs_used += 1
|
||||
|
||||
if pairs_used == 0:
|
||||
return EffectiveTrialsResult(
|
||||
k=k, pairs_used=0, pairs_skipped=pairs_skipped, mean_correlation=None, n_hat=float(k)
|
||||
)
|
||||
|
||||
mean_corr = corr_sum / pairs_used
|
||||
n_hat = max(1.0, 1.0 + (k - 1.0) * (1.0 - max(0.0, mean_corr)))
|
||||
return EffectiveTrialsResult(
|
||||
k=k,
|
||||
pairs_used=pairs_used,
|
||||
pairs_skipped=pairs_skipped,
|
||||
mean_correlation=float(mean_corr),
|
||||
n_hat=float(n_hat),
|
||||
)
|
||||
|
||||
|
||||
def deflated_sharpe_ratio(
|
||||
*,
|
||||
sharpe_unann: float,
|
||||
n_obs: int,
|
||||
skewness: float,
|
||||
kurtosis: float,
|
||||
n_hat: float,
|
||||
cluster_sharpes: Sequence[float],
|
||||
) -> DeflatedSharpeResult:
|
||||
"""Computes non-normal Deflated Sharpe Ratio (DSR) per VALIDATION-AND-RIGOR.md §2.C."""
|
||||
if n_obs < 2:
|
||||
raise ValueError("n_obs must be >= 2.")
|
||||
sr_arr = np.asarray(cluster_sharpes, dtype=np.float64)
|
||||
sr_arr = sr_arr[np.isfinite(sr_arr)]
|
||||
|
||||
if n_hat <= 1.0 or sr_arr.size < 2:
|
||||
sr0 = 0.0
|
||||
else:
|
||||
sigma_sr = float(np.std(sr_arr, ddof=1))
|
||||
if sigma_sr <= 0.0:
|
||||
sr0 = 0.0
|
||||
else:
|
||||
z1 = float(norm.ppf(1.0 - 1.0 / n_hat))
|
||||
z2 = float(norm.ppf(1.0 - 1.0 / (n_hat * math.e)))
|
||||
sr0 = sigma_sr * ((1.0 - EULER_MASCHERONI) * z1 + EULER_MASCHERONI * z2)
|
||||
|
||||
se_num = 1.0 - skewness * sharpe_unann + ((kurtosis - 1.0) / 4.0) * (sharpe_unann ** 2)
|
||||
if se_num <= 0.0:
|
||||
raise ValueError("Non-positive Sharpe standard-error variance term.")
|
||||
se = math.sqrt(se_num / (n_obs - 1.0))
|
||||
dsr = float(norm.cdf((sharpe_unann - sr0) / se))
|
||||
return DeflatedSharpeResult(sr0=float(sr0), standard_error=float(se), dsr=dsr)
|
||||
|
||||
|
||||
def evaluate_recency_gate(
|
||||
dates: Sequence[str],
|
||||
series: Sequence[float] | np.ndarray,
|
||||
*,
|
||||
split_date: str = RECENCY_SPLIT_DATE,
|
||||
min_ratio: float = RECENCY_MIN_RATIO,
|
||||
) -> dict[str, object]:
|
||||
"""Post-2023 Recency Gate: post mean > 0 and >= min_ratio * pre mean (sign-preserving)."""
|
||||
arr = np.asarray(series, dtype=np.float64)
|
||||
pre_vals = np.array([v for d, v in zip(dates, arr) if d < split_date and math.isfinite(v)], dtype=np.float64)
|
||||
post_vals = np.array([v for d, v in zip(dates, arr) if d >= split_date and math.isfinite(v)], dtype=np.float64)
|
||||
pre_mean = float(pre_vals.mean()) if pre_vals.size > 0 else float("nan")
|
||||
post_mean = float(post_vals.mean()) if post_vals.size > 0 else float("nan")
|
||||
|
||||
if pre_vals.size == 0:
|
||||
return {"pass": False, "reason": "empty_pre_window", "pre_n": 0, "post_n": int(post_vals.size), "pre_mean": None, "post_mean": post_mean if post_vals.size else None, "ratio": None}
|
||||
if post_vals.size == 0:
|
||||
return {"pass": False, "reason": "empty_post_window", "pre_n": int(pre_vals.size), "post_n": 0, "pre_mean": pre_mean, "post_mean": None, "ratio": None}
|
||||
if pre_mean == 0.0:
|
||||
return {"pass": False, "reason": "zero_pre_mean", "pre_n": int(pre_vals.size), "post_n": int(post_vals.size), "pre_mean": pre_mean, "post_mean": post_mean, "ratio": None}
|
||||
|
||||
ratio = post_mean / pre_mean
|
||||
same_sign = (pre_mean > 0 and post_mean > 0) or (pre_mean < 0 and post_mean < 0)
|
||||
passed = same_sign and ratio >= min_ratio
|
||||
reason = "passed" if passed else ("sign_flipped" if not same_sign else "post_below_ratio_threshold")
|
||||
return {
|
||||
"pass": passed,
|
||||
"reason": reason,
|
||||
"pre_n": int(pre_vals.size),
|
||||
"post_n": int(post_vals.size),
|
||||
"pre_mean": pre_mean,
|
||||
"post_mean": post_mean,
|
||||
"ratio": float(ratio),
|
||||
}
|
||||
|
||||
|
||||
def analyze_signal_panel(
|
||||
panel: pl.DataFrame,
|
||||
*,
|
||||
vault_cutoff_date: str,
|
||||
n_quantiles: int = 5,
|
||||
min_cross_section: int = 10,
|
||||
recency_split_date: str = RECENCY_SPLIT_DATE,
|
||||
) -> dict[str, object]:
|
||||
"""Vectorized Polars/NumPy cross-sectional Signal Analyzer.
|
||||
|
||||
Expects columns: `session_date` (str YYYY-MM-DD or Date), `listing_id` (int),
|
||||
`signal` (float), `forward_return` (float).
|
||||
Enforces strict Vault cutoff `session_date < vault_cutoff_date`.
|
||||
"""
|
||||
df = panel.with_columns(
|
||||
pl.col("session_date").cast(pl.String).alias("session_date"),
|
||||
pl.col("signal").cast(pl.Float64),
|
||||
pl.col("forward_return").cast(pl.Float64),
|
||||
).filter(
|
||||
pl.col("signal").is_finite() & pl.col("forward_return").is_finite()
|
||||
)
|
||||
|
||||
vault_excluded = int(df.filter(pl.col("session_date") >= vault_cutoff_date).height)
|
||||
fenced = df.filter(pl.col("session_date") < vault_cutoff_date)
|
||||
|
||||
# Filter dates with enough listings and compute cross-sectional Pearson IC, Rank IC, and Q_top - Q_bot
|
||||
ranked = (
|
||||
fenced.with_columns(pl.len().over("session_date").alias("_n"))
|
||||
.filter(pl.col("_n") >= min_cross_section)
|
||||
.with_columns(
|
||||
pl.col("signal").rank("average").over("session_date").alias("_sig_rank"),
|
||||
pl.col("forward_return").rank("average").over("session_date").alias("_ret_rank"),
|
||||
(
|
||||
((pl.col("signal").rank("ordinal").over("session_date") - 1) * n_quantiles // pl.col("_n"))
|
||||
.clip(0, n_quantiles - 1)
|
||||
.alias("_q")
|
||||
),
|
||||
)
|
||||
)
|
||||
|
||||
daily_ic = (
|
||||
ranked.group_by("session_date")
|
||||
.agg(
|
||||
pl.len().alias("n_listings"),
|
||||
pl.corr("signal", "forward_return").alias("ic"),
|
||||
pl.corr("_sig_rank", "_ret_rank").alias("rank_ic"),
|
||||
pl.col("forward_return").filter(pl.col("_q") == (n_quantiles - 1)).mean().alias("q_top"),
|
||||
pl.col("forward_return").filter(pl.col("_q") == 0).mean().alias("q_bot"),
|
||||
)
|
||||
.with_columns((pl.col("q_top") - pl.col("q_bot")).alias("spread"))
|
||||
.filter(pl.col("rank_ic").is_finite() & pl.col("spread").is_finite())
|
||||
.sort("session_date")
|
||||
)
|
||||
|
||||
# Top-quantile membership turnover across consecutive dates
|
||||
top_members = (
|
||||
ranked.filter(pl.col("_q") == (n_quantiles - 1))
|
||||
.group_by("session_date")
|
||||
.agg(pl.col("listing_id").implode().alias("ids"))
|
||||
.sort("session_date")
|
||||
)
|
||||
prev_set: set[int] | None = None
|
||||
turnovers: list[float] = []
|
||||
for row in top_members.iter_rows():
|
||||
cur_set = set(row[1])
|
||||
if prev_set is not None and len(cur_set) > 0 and len(prev_set) > 0:
|
||||
overlap = len(cur_set.intersection(prev_set))
|
||||
turnovers.append(1.0 - overlap / max(len(cur_set), len(prev_set)))
|
||||
prev_set = cur_set
|
||||
|
||||
dates = daily_ic["session_date"].to_list()
|
||||
rank_ic_series = daily_ic["rank_ic"].to_numpy()
|
||||
ic_series = daily_ic["ic"].to_numpy()
|
||||
spread_series = daily_ic["spread"].to_numpy()
|
||||
|
||||
rank_ic_nw = newey_west_mean_test(rank_ic_series)
|
||||
spread_nw = newey_west_mean_test(spread_series)
|
||||
recency_ic = evaluate_recency_gate(dates, rank_ic_series, split_date=recency_split_date)
|
||||
recency_spread = evaluate_recency_gate(dates, spread_series, split_date=recency_split_date)
|
||||
|
||||
return {
|
||||
"n_dates": len(dates),
|
||||
"total_observations": int(ranked.height),
|
||||
"vault_excluded_rows": vault_excluded,
|
||||
"dates": dates,
|
||||
"ic_series": ic_series.tolist(),
|
||||
"rank_ic_series": rank_ic_series.tolist(),
|
||||
"spread_series": spread_series.tolist(),
|
||||
"mean_ic": float(np.nanmean(ic_series)) if len(dates) else float("nan"),
|
||||
"mean_rank_ic": rank_ic_nw.mean,
|
||||
"rank_ic_nw_t": rank_ic_nw.t_stat,
|
||||
"rank_ic_nw_p": rank_ic_nw.p_value,
|
||||
"mean_quantile_spread": spread_nw.mean,
|
||||
"spread_nw_t": spread_nw.t_stat,
|
||||
"mean_top_quantile_turnover": float(np.mean(turnovers)) if turnovers else float("nan"),
|
||||
"recency_rank_ic": recency_ic,
|
||||
"recency_spread": recency_spread,
|
||||
}
|
||||
|
||||
|
||||
def compute_event_study(
|
||||
bars_df: pl.DataFrame,
|
||||
events_df: pl.DataFrame,
|
||||
*,
|
||||
vault_cutoff_date: str,
|
||||
pre_days: int = 5,
|
||||
post_days: int = 10,
|
||||
min_events: int = 5,
|
||||
recency_split_date: str = RECENCY_SPLIT_DATE,
|
||||
) -> dict[str, object]:
|
||||
"""Zero-look-ahead Event Study over curated daily bars and point-in-time events.
|
||||
|
||||
Events anchor to the first trading session with `bar.ts >= event.known_at`.
|
||||
All events whose event session or `event + post_days` session >= `vault_cutoff_date`
|
||||
are strictly excluded before computing returns.
|
||||
"""
|
||||
bars = (
|
||||
bars_df.select(["listing_id", "session_date", "ts", "close"])
|
||||
.with_columns(
|
||||
pl.col("session_date").cast(pl.String),
|
||||
pl.col("close").cast(pl.Float64),
|
||||
)
|
||||
.filter((pl.col("session_date") < vault_cutoff_date) & (pl.col("close") > 0))
|
||||
.sort(["listing_id", "session_date"])
|
||||
)
|
||||
|
||||
# Build shared session calendar and per-listing daily returns
|
||||
session_dates = bars["session_date"].unique().sort().to_list()
|
||||
date_to_idx = {d: i for i, d in enumerate(session_dates)}
|
||||
n_sessions = len(session_dates)
|
||||
|
||||
# Compute close-to-close simple returns per listing and equal-weight market benchmark
|
||||
ret_df = (
|
||||
bars.with_columns(
|
||||
(pl.col("close") / pl.col("close").shift(1).over("listing_id") - 1.0).alias("ret")
|
||||
)
|
||||
.filter(pl.col("ret").is_finite())
|
||||
)
|
||||
bench_df = (
|
||||
ret_df.group_by("session_date")
|
||||
.agg(pl.col("ret").mean().alias("bench_ret"))
|
||||
)
|
||||
abn_df = (
|
||||
ret_df.join(bench_df, on="session_date", how="left")
|
||||
.with_columns((pl.col("ret") - pl.col("bench_ret")).alias("abn_ret"))
|
||||
)
|
||||
|
||||
# Index returns per listing into dense arrays for fast window slicing
|
||||
listing_abn: dict[int, dict[int, float]] = {}
|
||||
listing_close_ts: dict[int, tuple[np.ndarray, np.ndarray]] = {}
|
||||
|
||||
for lid, grp in bars.group_by("listing_id", maintain_order=False):
|
||||
lid_int = int(lid[0])
|
||||
ts_arr = grp["ts"].cast(pl.Int64).to_numpy()
|
||||
idx_arr = np.array([date_to_idx[d] for d in grp["session_date"].to_list()], dtype=np.int32)
|
||||
listing_close_ts[lid_int] = (ts_arr, idx_arr)
|
||||
|
||||
for lid, grp in abn_df.group_by("listing_id", maintain_order=False):
|
||||
lid_int = int(lid[0])
|
||||
d_map: dict[int, float] = {}
|
||||
for s_date, abn in zip(grp["session_date"].to_list(), grp["abn_ret"].to_list()):
|
||||
d_map[date_to_idx[s_date]] = float(abn)
|
||||
listing_abn[lid_int] = d_map
|
||||
|
||||
ev_ts_col = events_df.select(["listing_id", "known_at"]).with_columns(
|
||||
pl.col("known_at").cast(pl.Int64)
|
||||
)
|
||||
|
||||
seen_pairs: set[tuple[int, int]] = set()
|
||||
cars_by_date: dict[str, list[float]] = {}
|
||||
window_matrix: list[list[float]] = []
|
||||
vault_excluded_events = 0
|
||||
|
||||
cutoff_ts_micros = int(
|
||||
datetime_from_ymd(vault_cutoff_date)
|
||||
)
|
||||
|
||||
for lid_raw, known_at_us in ev_ts_col.iter_rows():
|
||||
if known_at_us >= cutoff_ts_micros:
|
||||
vault_excluded_events += 1
|
||||
continue
|
||||
lid = int(lid_raw)
|
||||
if lid not in listing_close_ts or lid not in listing_abn:
|
||||
continue
|
||||
ts_arr, idx_arr = listing_close_ts[lid]
|
||||
pos = int(np.searchsorted(ts_arr, known_at_us, side="left"))
|
||||
if pos >= ts_arr.size:
|
||||
continue
|
||||
day_idx = int(idx_arr[pos])
|
||||
if day_idx - pre_days < 0 or day_idx + post_days >= n_sessions:
|
||||
continue
|
||||
key = (lid, day_idx)
|
||||
if key in seen_pairs:
|
||||
continue
|
||||
seen_pairs.add(key)
|
||||
|
||||
abn_map = listing_abn[lid]
|
||||
window_vals: list[float] = []
|
||||
complete = True
|
||||
for offset in range(-pre_days, post_days + 1):
|
||||
val = abn_map.get(day_idx + offset)
|
||||
if val is None or not math.isfinite(val):
|
||||
complete = False
|
||||
break
|
||||
window_vals.append(val)
|
||||
if not complete:
|
||||
continue
|
||||
|
||||
window_matrix.append(window_vals)
|
||||
post_car = float(sum(window_vals[pre_days:]))
|
||||
cars_by_date.setdefault(session_dates[day_idx], []).append(post_car)
|
||||
|
||||
events_used = len(window_matrix)
|
||||
if events_used < min_events or len(cars_by_date) < 2:
|
||||
return {
|
||||
"status": "insufficient_data",
|
||||
"events_used": events_used,
|
||||
"n_dates": len(cars_by_date),
|
||||
"vault_excluded_events": vault_excluded_events,
|
||||
}
|
||||
|
||||
mat = np.asarray(window_matrix, dtype=np.float64)
|
||||
aar = mat.mean(axis=0)
|
||||
caar = np.cumsum(aar)
|
||||
clustered_dates = sorted(cars_by_date.keys())
|
||||
mean_cars = np.array([float(np.mean(cars_by_date[d])) for d in clustered_dates], dtype=np.float64)
|
||||
nw = newey_west_mean_test(mean_cars)
|
||||
recency = evaluate_recency_gate(clustered_dates, mean_cars, split_date=recency_split_date)
|
||||
|
||||
return {
|
||||
"status": "ok",
|
||||
"pre_days": pre_days,
|
||||
"post_days": post_days,
|
||||
"events_used": events_used,
|
||||
"n_dates": len(clustered_dates),
|
||||
"vault_excluded_events": vault_excluded_events,
|
||||
"clustered_dates": clustered_dates,
|
||||
"mean_cars": mean_cars.tolist(),
|
||||
"car_mean": nw.mean,
|
||||
"car_nw_t": nw.t_stat,
|
||||
"car_nw_p": nw.p_value,
|
||||
"aar": aar.tolist(),
|
||||
"caar": caar.tolist(),
|
||||
"recency": recency,
|
||||
}
|
||||
|
||||
|
||||
def datetime_from_ymd(ymd: str) -> int:
|
||||
from datetime import datetime, timezone
|
||||
|
||||
dt = datetime.strptime(ymd, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
||||
return int(dt.timestamp() * 1_000_000)
|
||||
295
python/stockbot/data.py
Normal file
295
python/stockbot/data.py
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
"""Vault-fenced DuckDB + Polars `MarketDataStore` for curated Hive Parquet."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from datetime import date, datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Literal, Sequence
|
||||
|
||||
import duckdb
|
||||
import polars as pl
|
||||
|
||||
from .vault import (
|
||||
DataScope,
|
||||
DuckDbConnectionBudget,
|
||||
MarketDataStoreValidationError,
|
||||
apply_vault_fence,
|
||||
resolve_duckdb_budget,
|
||||
)
|
||||
|
||||
EventKind = Literal["filing", "earnings", "ceo_post", "corporate_action"]
|
||||
AdjustmentMode = Literal["raw", "split", "total"]
|
||||
UniverseRef = Literal["US_EQ", "CA_EQ", "US_CA_EQ"]
|
||||
|
||||
_UNIVERSE_CURRENCIES: dict[str, tuple[str, ...]] = {
|
||||
"US_EQ": ("USD",),
|
||||
"CA_EQ": ("CAD",),
|
||||
"US_CA_EQ": ("USD", "CAD"),
|
||||
}
|
||||
|
||||
|
||||
class MarketDataStore:
|
||||
"""Vault-fenced DuckDB + Parquet reader enforcing `known_at <= as_of` and `ts < vault_cutoff_ts`."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
curated_root: str | Path,
|
||||
*,
|
||||
vault_cutoff_ts: int,
|
||||
vault_operator_authorized: bool = False,
|
||||
budget: DuckDbConnectionBudget | None = None,
|
||||
adj_factors_path: str | Path | None = None,
|
||||
) -> None:
|
||||
self.curated_root = str(Path(curated_root).resolve())
|
||||
self.vault_cutoff_ts = vault_cutoff_ts
|
||||
self.vault_operator_authorized = vault_operator_authorized
|
||||
self.budget = budget or resolve_duckdb_budget()
|
||||
self.adj_factors_path = (
|
||||
str(Path(adj_factors_path).resolve())
|
||||
if adj_factors_path is not None
|
||||
else str(Path(self.curated_root) / "adj_factors" / "part.parquet")
|
||||
)
|
||||
os.makedirs(self.budget.temp_directory, exist_ok=True)
|
||||
self._con = duckdb.connect(":memory:")
|
||||
for stmt in self.budget.statements:
|
||||
self._con.execute(stmt)
|
||||
|
||||
def close(self) -> None:
|
||||
self._con.close()
|
||||
|
||||
def __enter__(self) -> "MarketDataStore":
|
||||
return self
|
||||
|
||||
def __exit__(self, *_: object) -> None:
|
||||
self.close()
|
||||
|
||||
def _bars_glob(self) -> str:
|
||||
return f"{self.curated_root}/bars_1d/year=*/part.parquet"
|
||||
|
||||
def _events_glob(self) -> str:
|
||||
return f"{self.curated_root}/events/year=*/part.parquet"
|
||||
|
||||
def _shorts_path(self) -> str:
|
||||
return f"{self.curated_root}/shorts/part.parquet"
|
||||
|
||||
def _fx_path(self) -> str:
|
||||
return f"{self.curated_root}/fx_1d/part.parquet"
|
||||
|
||||
def _verify_fenced_adj_factors(self, as_of_micros: int, scope: DataScope) -> str:
|
||||
rows = self._con.execute(
|
||||
f"SELECT key::VARCHAR AS k, value::VARCHAR AS v FROM parquet_kv_metadata('{self.adj_factors_path}')"
|
||||
).fetchall()
|
||||
kv = {str(k): str(v) for k, v in rows if str(k).startswith("stock_bot.adj_factors.")}
|
||||
kind = kv.get("stock_bot.adj_factors.snapshot_kind")
|
||||
if kind != "point_in_time_fenced":
|
||||
raise MarketDataStoreValidationError(
|
||||
f"Adjusted bars require point_in_time_fenced adj_factors snapshot (got {kind!r} at {self.adj_factors_path})."
|
||||
)
|
||||
if scope == "vault_fenced":
|
||||
raw_vc = kv.get("stock_bot.adj_factors.vault_cutoff_micros")
|
||||
expected_vc = self.vault_cutoff_ts * 1000
|
||||
if raw_vc is None or raw_vc == "none" or int(raw_vc) > expected_vc:
|
||||
raise MarketDataStoreValidationError(
|
||||
f"adj_factors vault_cutoff_micros ({raw_vc}) incompatible with store cutoff ({expected_vc})."
|
||||
)
|
||||
raw_as_of = kv.get("stock_bot.adj_factors.as_of_micros")
|
||||
if raw_as_of is not None and raw_as_of != "none" and int(raw_as_of) > as_of_micros:
|
||||
raise MarketDataStoreValidationError(
|
||||
f"adj_factors as_of_micros ({raw_as_of}) exceeds query as_of_micros ({as_of_micros})."
|
||||
)
|
||||
return self.adj_factors_path
|
||||
|
||||
def bars(
|
||||
self,
|
||||
*,
|
||||
listing_ids: Sequence[int] | None = None,
|
||||
currencies: Sequence[str] | None = None,
|
||||
timeframe: str = "1d",
|
||||
from_date: str,
|
||||
to_date: str,
|
||||
adjustment: AdjustmentMode = "raw",
|
||||
as_of: str | None = None,
|
||||
scope: DataScope = "vault_fenced",
|
||||
) -> pl.DataFrame:
|
||||
if timeframe != "1d":
|
||||
raise NotImplementedError(f"Timeframe {timeframe!r} is reserved for QuestDB (M2).")
|
||||
fenced = apply_vault_fence(
|
||||
from_date,
|
||||
to_date,
|
||||
self.vault_cutoff_ts,
|
||||
as_of=as_of,
|
||||
scope=scope,
|
||||
vault_operator_authorized=self.vault_operator_authorized,
|
||||
)
|
||||
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
|
||||
where = ["b.ts >= ?", "b.ts <= ?", "b.known_at <= ?"]
|
||||
params: list[object] = [from_ts, to_ts, as_of_ts]
|
||||
if listing_ids is not None:
|
||||
if len(listing_ids) == 0:
|
||||
return pl.DataFrame()
|
||||
placeholders = ", ".join(["?"] * len(listing_ids))
|
||||
where.append(f"b.listing_id IN ({placeholders})")
|
||||
params.extend(int(x) for x in listing_ids)
|
||||
if currencies is not None:
|
||||
placeholders = ", ".join(["?"] * len(currencies))
|
||||
where.append(f"b.currency IN ({placeholders})")
|
||||
params.extend(str(c) for c in currencies)
|
||||
|
||||
where_sql = " AND ".join(where)
|
||||
if adjustment == "raw":
|
||||
sql = f"""
|
||||
SELECT
|
||||
b.listing_id,
|
||||
b.session_date,
|
||||
b.ts,
|
||||
b.open,
|
||||
b.high,
|
||||
b.low,
|
||||
b.close,
|
||||
b.volume,
|
||||
b.vwap,
|
||||
b.currency,
|
||||
b.source,
|
||||
b.known_at
|
||||
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b
|
||||
WHERE {where_sql}
|
||||
ORDER BY b.listing_id ASC, b.session_date ASC
|
||||
"""
|
||||
return self._con.execute(sql, params).pl()
|
||||
|
||||
adj_path = self._verify_fenced_adj_factors(fenced.as_of_micros, fenced.scope)
|
||||
price_col = "cum_split_factor" if adjustment == "split" else "cum_total_factor"
|
||||
sql = f"""
|
||||
WITH adj AS (
|
||||
SELECT listing_id, ex_date, cum_split_factor, cum_total_factor
|
||||
FROM read_parquet('{adj_path}')
|
||||
WHERE known_at <= ?
|
||||
)
|
||||
SELECT
|
||||
b.listing_id,
|
||||
b.session_date,
|
||||
b.ts,
|
||||
b.open / COALESCE(a.{price_col}, 1.0) AS open,
|
||||
b.high / COALESCE(a.{price_col}, 1.0) AS high,
|
||||
b.low / COALESCE(a.{price_col}, 1.0) AS low,
|
||||
b.close / COALESCE(a.{price_col}, 1.0) AS close,
|
||||
b.volume * COALESCE(a.cum_split_factor, 1.0) AS volume,
|
||||
CASE WHEN b.vwap IS NULL THEN NULL ELSE b.vwap / COALESCE(a.{price_col}, 1.0) END AS vwap,
|
||||
b.currency,
|
||||
b.source,
|
||||
b.known_at
|
||||
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true) b
|
||||
ASOF LEFT JOIN adj a
|
||||
ON b.listing_id = a.listing_id AND b.session_date < a.ex_date
|
||||
WHERE {where_sql}
|
||||
ORDER BY b.listing_id ASC, b.session_date ASC
|
||||
"""
|
||||
return self._con.execute(sql, [as_of_ts, *params]).pl()
|
||||
|
||||
def shorts_as_of(
|
||||
self,
|
||||
*,
|
||||
listing_ids: Sequence[int] | None = None,
|
||||
from_date: str,
|
||||
to_date: str,
|
||||
as_of: str | None = None,
|
||||
) -> pl.DataFrame:
|
||||
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced")
|
||||
from_d = datetime.fromtimestamp(fenced.from_ms / 1000.0, tz=timezone.utc).date()
|
||||
to_d = datetime.fromtimestamp(fenced.to_ms / 1000.0, tz=timezone.utc).date()
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
|
||||
where = ["report_date >= ?", "report_date <= ?", "known_at <= ?"]
|
||||
params: list[object] = [from_d, to_d, as_of_ts]
|
||||
if listing_ids is not None:
|
||||
if len(listing_ids) == 0:
|
||||
return pl.DataFrame()
|
||||
placeholders = ", ".join(["?"] * len(listing_ids))
|
||||
where.append(f"listing_id IN ({placeholders})")
|
||||
params.extend(int(x) for x in listing_ids)
|
||||
|
||||
sql = f"""
|
||||
SELECT listing_id, report_date, known_at, shares_short, net_change, pct_float, source
|
||||
FROM read_parquet('{self._shorts_path()}')
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY listing_id ASC, report_date ASC
|
||||
"""
|
||||
return self._con.execute(sql, params).pl()
|
||||
|
||||
def events(
|
||||
self,
|
||||
*,
|
||||
kinds: Sequence[EventKind],
|
||||
listing_ids: Sequence[int] | None = None,
|
||||
from_date: str,
|
||||
to_date: str,
|
||||
as_of: str | None = None,
|
||||
) -> pl.DataFrame:
|
||||
if not kinds:
|
||||
raise MarketDataStoreValidationError("events requires at least one kind.")
|
||||
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, as_of=as_of, scope="vault_fenced")
|
||||
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
|
||||
kind_ph = ", ".join(["?"] * len(kinds))
|
||||
where = [f"kind IN ({kind_ph})", "ts >= ?", "ts <= ?", "known_at <= ?"]
|
||||
params: list[object] = [*kinds, from_ts, to_ts, as_of_ts]
|
||||
if listing_ids is not None:
|
||||
if len(listing_ids) == 0:
|
||||
return pl.DataFrame()
|
||||
lid_ph = ", ".join(["?"] * len(listing_ids))
|
||||
where.append(f"listing_id IN ({lid_ph})")
|
||||
params.extend(int(x) for x in listing_ids)
|
||||
|
||||
sql = f"""
|
||||
SELECT listing_id, ts, known_at, known_at_source, kind, subtype, payload_json
|
||||
FROM read_parquet('{self._events_glob()}', hive_partitioning = true)
|
||||
WHERE {' AND '.join(where)}
|
||||
ORDER BY listing_id ASC, ts ASC
|
||||
"""
|
||||
return self._con.execute(sql, params).pl()
|
||||
|
||||
def fx(self, *, pair: str = "USD.CAD", timeframe: str = "1d", from_date: str, to_date: str) -> pl.DataFrame:
|
||||
if timeframe != "1d":
|
||||
raise NotImplementedError("FX intraday 1m is reserved for QuestDB (M2).")
|
||||
if pair != "USD.CAD":
|
||||
raise MarketDataStoreValidationError(f"Unsupported FX pair: {pair!r}")
|
||||
fenced = apply_vault_fence(from_date, to_date, self.vault_cutoff_ts, scope="vault_fenced")
|
||||
from_ts = datetime.fromtimestamp(fenced.from_micros / 1_000_000, tz=timezone.utc)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
sql = f"""
|
||||
SELECT pair, session_date, ts, open, high, low, close, source, known_at
|
||||
FROM read_parquet('{self._fx_path()}')
|
||||
WHERE pair = 'USDCAD' AND ts >= ? AND ts <= ? AND known_at <= ?
|
||||
ORDER BY session_date ASC
|
||||
"""
|
||||
return self._con.execute(sql, [from_ts, to_ts, as_of_ts]).pl()
|
||||
|
||||
def universe(self, *, ref: UniverseRef, on_date: str, lookback_days: int = 7) -> list[int]:
|
||||
if ref not in _UNIVERSE_CURRENCIES:
|
||||
raise MarketDataStoreValidationError(f"Unsupported universe ref: {ref!r}")
|
||||
fenced = apply_vault_fence(on_date, on_date, self.vault_cutoff_ts, as_of=on_date, scope="vault_fenced")
|
||||
end_d = date.fromisoformat(on_date)
|
||||
start_d = end_d - timedelta(days=lookback_days)
|
||||
to_ts = datetime.fromtimestamp(fenced.to_micros / 1_000_000, tz=timezone.utc)
|
||||
as_of_ts = datetime.fromtimestamp(fenced.as_of_micros / 1_000_000, tz=timezone.utc)
|
||||
currencies = _UNIVERSE_CURRENCIES[ref]
|
||||
ph = ", ".join(["?"] * len(currencies))
|
||||
sql = f"""
|
||||
SELECT DISTINCT listing_id
|
||||
FROM read_parquet('{self._bars_glob()}', hive_partitioning = true)
|
||||
WHERE currency IN ({ph})
|
||||
AND session_date >= ?
|
||||
AND session_date <= ?
|
||||
AND ts <= ?
|
||||
AND known_at <= ?
|
||||
ORDER BY listing_id ASC
|
||||
"""
|
||||
rows = self._con.execute(sql, [*currencies, start_d, end_d, to_ts, as_of_ts]).fetchall()
|
||||
return [int(r[0]) for r in rows]
|
||||
269
python/stockbot/ledger.py
Normal file
269
python/stockbot/ledger.py
Normal file
|
|
@ -0,0 +1,269 @@
|
|||
"""Append-only PostgreSQL `trial_ledger` client and cluster N-hat DSR evaluator."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import math
|
||||
import struct
|
||||
from dataclasses import dataclass
|
||||
from typing import Any, Literal, Mapping, Sequence
|
||||
|
||||
import numpy as np
|
||||
import psycopg
|
||||
|
||||
from .calculations import (
|
||||
DSR_VALIDATION_GATE,
|
||||
DeflatedSharpeResult,
|
||||
EffectiveTrialsResult,
|
||||
deflated_sharpe_ratio,
|
||||
effective_independent_trials,
|
||||
trial_moments,
|
||||
)
|
||||
from .vault import VaultHoldoutFenceError, parse_timestamp_ms
|
||||
|
||||
TrialStage = Literal["signal_ic", "event_study", "screen", "engine_backtest"]
|
||||
UniverseMarket = Literal["US_EQ", "CA_EQ", "US_CA_EQ", "FX"]
|
||||
HorizonBucket = Literal["intraday", "swing_1_10d", "position_10d_plus"]
|
||||
|
||||
|
||||
def _normalize_json_value(value: Any) -> Any:
|
||||
if value is None or isinstance(value, (bool, str)):
|
||||
return value
|
||||
if isinstance(value, (int, float)):
|
||||
if isinstance(value, float):
|
||||
if not math.isfinite(value):
|
||||
raise ValueError(f"Non-finite number forbidden in expression hash: {value!r}")
|
||||
if value == 0.0:
|
||||
return 0
|
||||
return value
|
||||
if isinstance(value, Mapping):
|
||||
out: dict[str, Any] = {}
|
||||
for k in sorted(value.keys()):
|
||||
v = value[k]
|
||||
if v is not None:
|
||||
out[str(k)] = _normalize_json_value(v)
|
||||
return out
|
||||
if isinstance(value, (list, tuple)):
|
||||
return [_normalize_json_value(v) for v in value]
|
||||
raise TypeError(f"Unsupported value type for canonical_expression_hash: {type(value)!r}")
|
||||
|
||||
|
||||
def canonical_expression_hash(
|
||||
*,
|
||||
expression: str,
|
||||
params: Mapping[str, Any],
|
||||
universe: str,
|
||||
sample_start: str,
|
||||
sample_end: str,
|
||||
horizon: str,
|
||||
) -> str:
|
||||
"""64-hex SHA-256 over canonical ASCII-sorted JSON matching `@stock-bot/research`."""
|
||||
collapsed_expr = " ".join(expression.strip().split())
|
||||
payload = _normalize_json_value(
|
||||
{
|
||||
"expression": collapsed_expr,
|
||||
"horizon": horizon,
|
||||
"params": params,
|
||||
"sampleEnd": sample_end,
|
||||
"sampleStart": sample_start,
|
||||
"universe": universe,
|
||||
}
|
||||
)
|
||||
encoded = json.dumps(payload, separators=(",", ":"), sort_keys=True, ensure_ascii=False).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class RecordedTrial:
|
||||
trial_id: int
|
||||
created_at: str
|
||||
expression_hash: str
|
||||
n_obs: int
|
||||
sharpe_unann: float
|
||||
skewness: float
|
||||
kurtosis: float
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ClusterDsrSummary:
|
||||
trial_id: int
|
||||
cluster_size: int
|
||||
effective_trials: float
|
||||
mean_correlation: float | None
|
||||
pairs_used: int
|
||||
pairs_skipped: int
|
||||
sr0: float
|
||||
standard_error: float
|
||||
dsr: float
|
||||
passes_gate: bool
|
||||
|
||||
|
||||
class TrialLedgerClient:
|
||||
"""Append-only writer and cluster DSR reader for PostgreSQL `trial_ledger`."""
|
||||
|
||||
def __init__(self, dsn: str) -> None:
|
||||
self._dsn = dsn
|
||||
|
||||
def record_trial(
|
||||
self,
|
||||
*,
|
||||
principal_id: str,
|
||||
stage: TrialStage,
|
||||
universe_market: UniverseMarket,
|
||||
horizon_bucket: HorizonBucket,
|
||||
expression_hash: str,
|
||||
sample_start: str,
|
||||
sample_end: str,
|
||||
vault_cutoff_date: str,
|
||||
daily_series: Sequence[float],
|
||||
campaign_id: str | None = None,
|
||||
hypothesis_id: str | None = None,
|
||||
) -> RecordedTrial:
|
||||
"""Validates Vault fence + float32 precision and inserts into `trial_ledger`."""
|
||||
start_ms = parse_timestamp_ms(sample_start, "start", "sample_start")
|
||||
end_ms = parse_timestamp_ms(sample_end, "end", "sample_end")
|
||||
cutoff_ms = parse_timestamp_ms(vault_cutoff_date, "start", "vault_cutoff_date")
|
||||
if end_ms < start_ms:
|
||||
raise ValueError(f"sample_end ({sample_end}) precedes sample_start ({sample_start}).")
|
||||
if start_ms >= cutoff_ms:
|
||||
raise VaultHoldoutFenceError(sample_start, start_ms, cutoff_ms)
|
||||
if end_ms >= cutoff_ms:
|
||||
raise VaultHoldoutFenceError(sample_end, end_ms, cutoff_ms)
|
||||
|
||||
# Quantize to IEEE-754 REAL (float32) before moment calculation so stored values match moments
|
||||
f32_values: list[float] = []
|
||||
for x in daily_series:
|
||||
fx = float(x)
|
||||
if not math.isfinite(fx):
|
||||
raise ValueError("daily_series contains non-finite value.")
|
||||
packed = struct.unpack("<f", struct.pack("<f", fx))[0]
|
||||
if not math.isfinite(packed):
|
||||
raise ValueError(f"Value {fx} overflows float32 REAL precision.")
|
||||
f32_values.append(0.0 if packed == 0.0 else float(packed))
|
||||
|
||||
moments = trial_moments(f32_values)
|
||||
|
||||
with psycopg.connect(self._dsn) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO trial_ledger (
|
||||
principal_id,
|
||||
campaign_id,
|
||||
stage,
|
||||
universe_market,
|
||||
horizon_bucket,
|
||||
hypothesis_id,
|
||||
expression_hash,
|
||||
sample_start,
|
||||
sample_end,
|
||||
n_obs,
|
||||
sharpe_unann,
|
||||
skewness,
|
||||
kurtosis,
|
||||
daily_series
|
||||
) VALUES (
|
||||
%s, %s, %s, %s, %s, %s, %s, %s::date, %s::date, %s, %s, %s, %s, %s::real[]
|
||||
)
|
||||
RETURNING trial_id, created_at
|
||||
""",
|
||||
(
|
||||
principal_id,
|
||||
campaign_id,
|
||||
stage,
|
||||
universe_market,
|
||||
horizon_bucket,
|
||||
hypothesis_id,
|
||||
expression_hash,
|
||||
sample_start,
|
||||
sample_end,
|
||||
moments.n_obs,
|
||||
moments.sharpe_unann,
|
||||
moments.skewness,
|
||||
moments.kurtosis,
|
||||
f32_values,
|
||||
),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
assert row is not None
|
||||
trial_id, created_at = int(row[0]), row[1].isoformat()
|
||||
conn.commit()
|
||||
|
||||
return RecordedTrial(
|
||||
trial_id=trial_id,
|
||||
created_at=created_at,
|
||||
expression_hash=expression_hash,
|
||||
n_obs=moments.n_obs,
|
||||
sharpe_unann=moments.sharpe_unann,
|
||||
skewness=moments.skewness,
|
||||
kurtosis=moments.kurtosis,
|
||||
)
|
||||
|
||||
def cluster_deflated_sharpe(
|
||||
self,
|
||||
*,
|
||||
trial_id: int,
|
||||
observation_dates_by_trial_id: Mapping[int, Sequence[str]] | None = None,
|
||||
dsr_gate: float = DSR_VALIDATION_GATE,
|
||||
) -> ClusterDsrSummary:
|
||||
"""Loads target trial and its `(universe_market, horizon_bucket)` cluster and computes DSR."""
|
||||
with psycopg.connect(self._dsn) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT trial_id, universe_market, horizon_bucket, n_obs,
|
||||
sharpe_unann, skewness, kurtosis, daily_series
|
||||
FROM trial_ledger
|
||||
WHERE trial_id = %s
|
||||
""",
|
||||
(trial_id,),
|
||||
)
|
||||
target = cur.fetchone()
|
||||
if target is None:
|
||||
raise LookupError(f"trial_id={trial_id} not found in trial_ledger.")
|
||||
|
||||
_, universe_market, horizon_bucket, n_obs, sr, skew, kurt, _ = target
|
||||
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT trial_id, sharpe_unann, daily_series
|
||||
FROM trial_ledger
|
||||
WHERE universe_market = %s AND horizon_bucket = %s
|
||||
ORDER BY trial_id ASC
|
||||
""",
|
||||
(universe_market, horizon_bucket),
|
||||
)
|
||||
cluster_rows = cur.fetchall()
|
||||
|
||||
cluster_sharpes = [float(r[1]) for r in cluster_rows]
|
||||
aligned_items: list[tuple[int, dict[str, float]]] = []
|
||||
for r_id, _, r_series in cluster_rows:
|
||||
tid = int(r_id)
|
||||
dates = (observation_dates_by_trial_id or {}).get(tid)
|
||||
if dates is not None and len(dates) == len(r_series):
|
||||
aligned_items.append((tid, {d: float(v) for d, v in zip(dates, r_series)}))
|
||||
else:
|
||||
aligned_items.append((tid, {}))
|
||||
|
||||
eff: EffectiveTrialsResult = effective_independent_trials(aligned_items)
|
||||
dsr_res: DeflatedSharpeResult = deflated_sharpe_ratio(
|
||||
sharpe_unann=float(sr),
|
||||
n_obs=int(n_obs),
|
||||
skewness=float(skew),
|
||||
kurtosis=float(kurt),
|
||||
n_hat=eff.n_hat,
|
||||
cluster_sharpes=cluster_sharpes,
|
||||
)
|
||||
return ClusterDsrSummary(
|
||||
trial_id=trial_id,
|
||||
cluster_size=eff.k,
|
||||
effective_trials=eff.n_hat,
|
||||
mean_correlation=eff.mean_correlation,
|
||||
pairs_used=eff.pairs_used,
|
||||
pairs_skipped=eff.pairs_skipped,
|
||||
sr0=dsr_res.sr0,
|
||||
standard_error=dsr_res.standard_error,
|
||||
dsr=dsr_res.dsr,
|
||||
passes_gate=dsr_res.dsr >= dsr_gate,
|
||||
)
|
||||
137
python/stockbot/signals.py
Normal file
137
python/stockbot/signals.py
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
"""High-level Signal Analyzer & Event Study runners with write-before-return trial logging."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Mapping
|
||||
|
||||
import polars as pl
|
||||
|
||||
from .calculations import analyze_signal_panel, compute_event_study
|
||||
from .ledger import (
|
||||
ClusterDsrSummary,
|
||||
HorizonBucket,
|
||||
RecordedTrial,
|
||||
TrialLedgerClient,
|
||||
UniverseMarket,
|
||||
canonical_expression_hash,
|
||||
)
|
||||
|
||||
|
||||
def run_signal_study(
|
||||
*,
|
||||
panel: pl.DataFrame,
|
||||
ledger: TrialLedgerClient,
|
||||
principal_id: str = "operator",
|
||||
universe_market: UniverseMarket,
|
||||
horizon_bucket: HorizonBucket,
|
||||
horizon_label: str,
|
||||
expression: str,
|
||||
params: Mapping[str, Any],
|
||||
vault_cutoff_date: str,
|
||||
n_quantiles: int = 5,
|
||||
min_cross_section: int = 10,
|
||||
ledger_series: str = "rank_ic",
|
||||
) -> dict[str, Any]:
|
||||
"""Runs Signal Analyzer under the Vault fence, writes to `trial_ledger`, and computes cluster DSR."""
|
||||
analysis = analyze_signal_panel(
|
||||
panel,
|
||||
vault_cutoff_date=vault_cutoff_date,
|
||||
n_quantiles=n_quantiles,
|
||||
min_cross_section=min_cross_section,
|
||||
)
|
||||
dates: list[str] = analysis["dates"] # type: ignore[assignment]
|
||||
if len(dates) < 2:
|
||||
return {"status": "insufficient_data", "analysis": analysis, "trial": None, "dsr": None}
|
||||
|
||||
series: list[float] = (
|
||||
analysis["rank_ic_series"] if ledger_series == "rank_ic" else analysis["spread_series"]
|
||||
) # type: ignore[assignment]
|
||||
expr_hash = canonical_expression_hash(
|
||||
expression=expression,
|
||||
params=params,
|
||||
universe=universe_market,
|
||||
sample_start=dates[0],
|
||||
sample_end=dates[-1],
|
||||
horizon=horizon_label,
|
||||
)
|
||||
recorded: RecordedTrial = ledger.record_trial(
|
||||
principal_id=principal_id,
|
||||
stage="signal_ic",
|
||||
universe_market=universe_market,
|
||||
horizon_bucket=horizon_bucket,
|
||||
expression_hash=expr_hash,
|
||||
sample_start=dates[0],
|
||||
sample_end=dates[-1],
|
||||
vault_cutoff_date=vault_cutoff_date,
|
||||
daily_series=series,
|
||||
)
|
||||
dsr: ClusterDsrSummary = ledger.cluster_deflated_sharpe(
|
||||
trial_id=recorded.trial_id,
|
||||
observation_dates_by_trial_id={recorded.trial_id: dates},
|
||||
)
|
||||
return {
|
||||
"status": "ok",
|
||||
"analysis": analysis,
|
||||
"trial": recorded,
|
||||
"dsr": dsr,
|
||||
}
|
||||
|
||||
|
||||
def run_event_study_trial(
|
||||
*,
|
||||
bars_df: pl.DataFrame,
|
||||
events_df: pl.DataFrame,
|
||||
ledger: TrialLedgerClient,
|
||||
principal_id: str = "operator",
|
||||
universe_market: UniverseMarket,
|
||||
horizon_bucket: HorizonBucket,
|
||||
expression: str,
|
||||
params: Mapping[str, Any],
|
||||
vault_cutoff_date: str,
|
||||
pre_days: int = 5,
|
||||
post_days: int = 10,
|
||||
min_events: int = 5,
|
||||
) -> dict[str, Any]:
|
||||
"""Runs Event Study under the Vault fence, writes to `trial_ledger`, and computes cluster DSR."""
|
||||
study = compute_event_study(
|
||||
bars_df,
|
||||
events_df,
|
||||
vault_cutoff_date=vault_cutoff_date,
|
||||
pre_days=pre_days,
|
||||
post_days=post_days,
|
||||
min_events=min_events,
|
||||
)
|
||||
if study.get("status") != "ok":
|
||||
return {"status": "insufficient_data", "study": study, "trial": None, "dsr": None}
|
||||
|
||||
dates: list[str] = study["clustered_dates"] # type: ignore[assignment]
|
||||
series: list[float] = study["mean_cars"] # type: ignore[assignment]
|
||||
expr_hash = canonical_expression_hash(
|
||||
expression=expression,
|
||||
params=params,
|
||||
universe=universe_market,
|
||||
sample_start=dates[0],
|
||||
sample_end=dates[-1],
|
||||
horizon=f"event_-{pre_days}_+{post_days}d",
|
||||
)
|
||||
recorded = ledger.record_trial(
|
||||
principal_id=principal_id,
|
||||
stage="event_study",
|
||||
universe_market=universe_market,
|
||||
horizon_bucket=horizon_bucket,
|
||||
expression_hash=expr_hash,
|
||||
sample_start=dates[0],
|
||||
sample_end=dates[-1],
|
||||
vault_cutoff_date=vault_cutoff_date,
|
||||
daily_series=series,
|
||||
)
|
||||
dsr = ledger.cluster_deflated_sharpe(
|
||||
trial_id=recorded.trial_id,
|
||||
observation_dates_by_trial_id={recorded.trial_id: dates},
|
||||
)
|
||||
return {
|
||||
"status": "ok",
|
||||
"study": study,
|
||||
"trial": recorded,
|
||||
"dsr": dsr,
|
||||
}
|
||||
226
python/stockbot/vault.py
Normal file
226
python/stockbot/vault.py
Normal file
|
|
@ -0,0 +1,226 @@
|
|||
"""Rolling 6-month UTC Vault holdout fence & DuckDB connection budget."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import calendar
|
||||
import os
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime, timezone
|
||||
from typing import Literal, Mapping
|
||||
|
||||
DataScope = Literal["vault_fenced", "vault_evaluation_only"]
|
||||
|
||||
DEFAULT_DUCKDB_MEMORY_LIMIT = "6GB"
|
||||
DEFAULT_DUCKDB_THREADS = 4
|
||||
DEFAULT_DUCKDB_TEMP_DIRECTORY = "/mnt/data/stockbot/tmp/duckdb"
|
||||
|
||||
_DATE_ONLY_RE = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
|
||||
_MEM_LIMIT_RE = re.compile(r"^(\d+(?:\.\d+)?)(MB|GB|MiB|GiB)$")
|
||||
|
||||
|
||||
class MarketDataStoreValidationError(ValueError):
|
||||
"""Raised when market-data query bounds, timestamps, or budgets are invalid."""
|
||||
|
||||
|
||||
class VaultHoldoutFenceError(PermissionError):
|
||||
"""Raised when a fenced query reaches or exceeds the rolling 6-month Vault cutoff."""
|
||||
|
||||
def __init__(self, from_bound: str, from_ms: int, vault_cutoff_ts: int) -> None:
|
||||
super().__init__(
|
||||
f'Query start "{from_bound}" ({from_ms}) reaches or exceeds Vault cutoff ({vault_cutoff_ts}).'
|
||||
)
|
||||
self.from_bound = from_bound
|
||||
self.from_ms = from_ms
|
||||
self.vault_cutoff_ts = vault_cutoff_ts
|
||||
|
||||
|
||||
class VaultScopeNotAuthorizedError(PermissionError):
|
||||
"""Raised when vault_evaluation_only is requested without operator authorization."""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class FencedTimeRange:
|
||||
from_ms: int
|
||||
to_ms: int
|
||||
as_of_ms: int
|
||||
scope: DataScope
|
||||
clamped_to: bool
|
||||
clamped_as_of: bool
|
||||
|
||||
@property
|
||||
def from_micros(self) -> int:
|
||||
return self.from_ms * 1000
|
||||
|
||||
@property
|
||||
def to_micros(self) -> int:
|
||||
# Expand end-of-ms inclusive boundary to last microsecond (.999999) when ms ends in 999
|
||||
return self.to_ms * 1000 + (999 if self.to_ms % 1000 == 999 else 0)
|
||||
|
||||
@property
|
||||
def as_of_micros(self) -> int:
|
||||
return self.as_of_ms * 1000 + (999 if self.as_of_ms % 1000 == 999 else 0)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class DuckDbConnectionBudget:
|
||||
memory_limit: str
|
||||
threads: int
|
||||
temp_directory: str
|
||||
|
||||
@property
|
||||
def statements(self) -> tuple[str, str, str]:
|
||||
escaped = self.temp_directory.replace("'", "''")
|
||||
return (
|
||||
f"SET memory_limit = '{self.memory_limit}';",
|
||||
f"SET threads = {self.threads};",
|
||||
f"SET temp_directory = '{escaped}';",
|
||||
)
|
||||
|
||||
|
||||
def parse_timestamp_ms(raw: str, bound_kind: Literal["start", "end"], field: str) -> int:
|
||||
if not isinstance(raw, str) or not raw:
|
||||
raise MarketDataStoreValidationError(f'Expected non-empty ISO-8601 string for "{field}".')
|
||||
m = _DATE_ONLY_RE.match(raw)
|
||||
if m:
|
||||
year, month, day = int(m.group(1)), int(m.group(2)), int(m.group(3))
|
||||
if bound_kind == "start":
|
||||
dt = datetime(year, month, day, 0, 0, 0, 0, tzinfo=timezone.utc)
|
||||
else:
|
||||
dt = datetime(year, month, day, 23, 59, 59, 999000, tzinfo=timezone.utc)
|
||||
return int(dt.timestamp() * 1000)
|
||||
|
||||
try:
|
||||
dt = datetime.fromisoformat(raw.replace("Z", "+00:00"))
|
||||
except ValueError as exc:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Invalid ISO-8601 date or UTC timestamp for "{field}": "{raw}".'
|
||||
) from exc
|
||||
if dt.tzinfo is None:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Naive timestamp without timezone offset is forbidden for "{field}": "{raw}".'
|
||||
)
|
||||
dt_utc = dt.astimezone(timezone.utc)
|
||||
return int(dt_utc.timestamp() * 1000)
|
||||
|
||||
|
||||
def compute_vault_cutoff_ts(max_ingested_ts: int | str | datetime) -> int:
|
||||
"""Computes rolling 6-month Vault cutoff (`max_ingested_ts - 6 calendar months` UTC)."""
|
||||
if isinstance(max_ingested_ts, int) and not isinstance(max_ingested_ts, bool):
|
||||
epoch_ms = max_ingested_ts
|
||||
elif isinstance(max_ingested_ts, str):
|
||||
epoch_ms = parse_timestamp_ms(max_ingested_ts, "start", "max_ingested_ts")
|
||||
elif isinstance(max_ingested_ts, datetime):
|
||||
if max_ingested_ts.tzinfo is None:
|
||||
raise MarketDataStoreValidationError("max_ingested_ts datetime must be timezone-aware.")
|
||||
epoch_ms = int(max_ingested_ts.astimezone(timezone.utc).timestamp() * 1000)
|
||||
else:
|
||||
raise MarketDataStoreValidationError("Invalid max_ingested_ts type.")
|
||||
|
||||
dt = datetime.fromtimestamp(epoch_ms / 1000.0, tz=timezone.utc)
|
||||
total_months = dt.year * 12 + (dt.month - 1) - 6
|
||||
target_year, target_month_zero = divmod(total_months, 12)
|
||||
target_month = target_month_zero + 1
|
||||
max_day = calendar.monthrange(target_year, target_month)[1]
|
||||
target_day = min(dt.day, max_day)
|
||||
cutoff_dt = datetime(
|
||||
target_year,
|
||||
target_month,
|
||||
target_day,
|
||||
dt.hour,
|
||||
dt.minute,
|
||||
dt.second,
|
||||
dt.microsecond,
|
||||
tzinfo=timezone.utc,
|
||||
)
|
||||
return int(cutoff_dt.timestamp() * 1000)
|
||||
|
||||
|
||||
def vault_cutoff_date_str(vault_cutoff_ts: int) -> str:
|
||||
return datetime.fromtimestamp(vault_cutoff_ts / 1000.0, tz=timezone.utc).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def apply_vault_fence(
|
||||
from_bound: str,
|
||||
to_bound: str,
|
||||
vault_cutoff_ts: int,
|
||||
as_of: str | None = None,
|
||||
scope: DataScope = "vault_fenced",
|
||||
vault_operator_authorized: bool = False,
|
||||
) -> FencedTimeRange:
|
||||
from_ms = parse_timestamp_ms(from_bound, "start", "from")
|
||||
to_ms = parse_timestamp_ms(to_bound, "end", "to")
|
||||
if to_ms < from_ms:
|
||||
raise MarketDataStoreValidationError(
|
||||
f'Query end "{to_bound}" ({to_ms}) precedes start "{from_bound}" ({from_ms}).'
|
||||
)
|
||||
|
||||
if scope == "vault_evaluation_only":
|
||||
if not vault_operator_authorized:
|
||||
raise VaultScopeNotAuthorizedError(
|
||||
"Data scope 'vault_evaluation_only' requires explicit human operator authorization."
|
||||
)
|
||||
as_of_ms = parse_timestamp_ms(as_of, "end", "as_of") if as_of is not None else to_ms
|
||||
return FencedTimeRange(
|
||||
from_ms=from_ms,
|
||||
to_ms=to_ms,
|
||||
as_of_ms=as_of_ms,
|
||||
scope=scope,
|
||||
clamped_to=False,
|
||||
clamped_as_of=False,
|
||||
)
|
||||
|
||||
if scope != "vault_fenced":
|
||||
raise MarketDataStoreValidationError(f"Unsupported scope: {scope!r}")
|
||||
|
||||
if from_ms >= vault_cutoff_ts:
|
||||
raise VaultHoldoutFenceError(from_bound, from_ms, vault_cutoff_ts)
|
||||
|
||||
clamped_to = False
|
||||
if to_ms >= vault_cutoff_ts:
|
||||
to_ms = vault_cutoff_ts - 1
|
||||
clamped_to = True
|
||||
|
||||
clamped_as_of = False
|
||||
if as_of is None:
|
||||
as_of_ms = vault_cutoff_ts - 1
|
||||
else:
|
||||
as_of_ms = parse_timestamp_ms(as_of, "end", "as_of")
|
||||
if as_of_ms >= vault_cutoff_ts:
|
||||
as_of_ms = vault_cutoff_ts - 1
|
||||
clamped_as_of = True
|
||||
|
||||
return FencedTimeRange(
|
||||
from_ms=from_ms,
|
||||
to_ms=to_ms,
|
||||
as_of_ms=as_of_ms,
|
||||
scope="vault_fenced",
|
||||
clamped_to=clamped_to,
|
||||
clamped_as_of=clamped_as_of,
|
||||
)
|
||||
|
||||
|
||||
def resolve_duckdb_budget(
|
||||
env: Mapping[str, str] | None = None,
|
||||
*,
|
||||
memory_limit: str | None = None,
|
||||
threads: int | None = None,
|
||||
temp_directory: str | None = None,
|
||||
) -> DuckDbConnectionBudget:
|
||||
source = env if env is not None else os.environ
|
||||
mem = memory_limit or source.get("STOCK_BOT_DUCKDB_MEMORY_LIMIT") or DEFAULT_DUCKDB_MEMORY_LIMIT
|
||||
if not _MEM_LIMIT_RE.match(mem):
|
||||
raise MarketDataStoreValidationError(f"Invalid DuckDB memory_limit: {mem!r}")
|
||||
raw_threads = threads if threads is not None else int(
|
||||
source.get("STOCK_BOT_DUCKDB_THREADS", str(DEFAULT_DUCKDB_THREADS))
|
||||
)
|
||||
if not isinstance(raw_threads, int) or raw_threads < 1 or raw_threads > 64:
|
||||
raise MarketDataStoreValidationError(f"Invalid DuckDB threads: {raw_threads!r}")
|
||||
tmp_dir = (
|
||||
temp_directory
|
||||
or source.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY")
|
||||
or DEFAULT_DUCKDB_TEMP_DIRECTORY
|
||||
)
|
||||
if not tmp_dir or not tmp_dir.startswith("/"):
|
||||
raise MarketDataStoreValidationError(f"Invalid DuckDB temp_directory: {tmp_dir!r}")
|
||||
return DuckDbConnectionBudget(memory_limit=mem, threads=raw_threads, temp_directory=tmp_dir)
|
||||
153
python/tests/test_stockbot_sdk.py
Normal file
153
python/tests/test_stockbot_sdk.py
Normal file
|
|
@ -0,0 +1,153 @@
|
|||
"""Unit tests for the `stockbot` Python SDK (Vault fence, DSR parity, DuckDB/Parquet store)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from datetime import date, datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import polars as pl
|
||||
import pytest
|
||||
|
||||
from stockbot import (
|
||||
MarketDataStore,
|
||||
VaultHoldoutFenceError,
|
||||
VaultScopeNotAuthorizedError,
|
||||
analyze_signal_panel,
|
||||
apply_vault_fence,
|
||||
canonical_expression_hash,
|
||||
compute_vault_cutoff_ts,
|
||||
deflated_sharpe_ratio,
|
||||
effective_independent_trials,
|
||||
resolve_duckdb_budget,
|
||||
trial_moments,
|
||||
)
|
||||
|
||||
|
||||
def test_vault_cutoff_and_fencing_rules() -> None:
|
||||
cutoff = compute_vault_cutoff_ts("2025-08-13")
|
||||
expected = int(datetime(2025, 2, 13, 0, 0, 0, tzinfo=timezone.utc).timestamp() * 1000)
|
||||
assert cutoff == expected
|
||||
|
||||
# Clamps to and as_of strictly below cutoff
|
||||
fenced = apply_vault_fence("2020-01-01", "2025-08-13", cutoff)
|
||||
assert fenced.clamped_to is True
|
||||
assert fenced.to_ms == cutoff - 1
|
||||
assert fenced.as_of_ms == cutoff - 1
|
||||
|
||||
# Rejects start >= cutoff
|
||||
with pytest.raises(VaultHoldoutFenceError):
|
||||
apply_vault_fence("2025-02-13", "2025-05-01", cutoff)
|
||||
|
||||
# Rejects unauthorized vault_evaluation_only
|
||||
with pytest.raises(VaultScopeNotAuthorizedError):
|
||||
apply_vault_fence("2025-02-13", "2025-05-01", cutoff, scope="vault_evaluation_only")
|
||||
|
||||
|
||||
def test_trial_moments_and_dsr_match_canonical_math() -> None:
|
||||
series = [0.01, 0.02, -0.005, 0.015, 0.008, -0.002, 0.012, 0.004]
|
||||
m = trial_moments(series)
|
||||
assert m.n_obs == 8
|
||||
assert m.sharpe_unann > 0.0
|
||||
assert m.kurtosis >= m.skewness ** 2 + 1.0
|
||||
|
||||
# Identical series -> rho = 1.0 -> N_hat = 1.0
|
||||
dates = [f"2024-01-0{i+1}" for i in range(len(series))]
|
||||
eff_dup = effective_independent_trials(
|
||||
[(1, dict(zip(dates, series))), (2, dict(zip(dates, series)))]
|
||||
)
|
||||
assert math.isclose(eff_dup.mean_correlation or 0.0, 1.0, rel_tol=1e-9)
|
||||
assert math.isclose(eff_dup.n_hat, 1.0, rel_tol=1e-9)
|
||||
|
||||
dsr = deflated_sharpe_ratio(
|
||||
sharpe_unann=m.sharpe_unann,
|
||||
n_obs=m.n_obs,
|
||||
skewness=m.skewness,
|
||||
kurtosis=m.kurtosis,
|
||||
n_hat=2.0,
|
||||
cluster_sharpes=[m.sharpe_unann, 0.1],
|
||||
)
|
||||
assert 0.0 <= dsr.dsr <= 1.0
|
||||
assert dsr.standard_error > 0.0
|
||||
|
||||
|
||||
def test_canonical_expression_hash_is_deterministic() -> None:
|
||||
h1 = canonical_expression_hash(
|
||||
expression=" ca_shorts neg_shares_short ",
|
||||
params={"b": 2, "a": 1, "skip": None},
|
||||
universe="CA_EQ",
|
||||
sample_start="2018-01-01",
|
||||
sample_end="2025-01-31",
|
||||
horizon="5d",
|
||||
)
|
||||
h2 = canonical_expression_hash(
|
||||
expression="ca_shorts neg_shares_short",
|
||||
params={"a": 1, "b": 2},
|
||||
universe="CA_EQ",
|
||||
sample_start="2018-01-01",
|
||||
sample_end="2025-01-31",
|
||||
horizon="5d",
|
||||
)
|
||||
assert len(h1) == 64
|
||||
assert h1 == h2
|
||||
|
||||
|
||||
def test_duckdb_market_data_store_enforces_vault_fence(tmp_path: Path) -> None:
|
||||
bars_dir = tmp_path / "bars_1d" / "year=2025"
|
||||
bars_dir.mkdir(parents=True)
|
||||
df = pl.DataFrame(
|
||||
{
|
||||
"listing_id": pl.Series([1, 1], dtype=pl.Int32),
|
||||
"ts": pl.Series(
|
||||
[
|
||||
datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc),
|
||||
datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc),
|
||||
],
|
||||
dtype=pl.Datetime("us", "UTC"),
|
||||
),
|
||||
"session_date": pl.Series([date(2025, 2, 10), date(2025, 2, 20)], dtype=pl.Date),
|
||||
"open": [10.0, 11.0],
|
||||
"high": [10.5, 11.5],
|
||||
"low": [9.8, 10.8],
|
||||
"close": [10.2, 11.2],
|
||||
"volume": [1000.0, 2000.0],
|
||||
"vwap": [None, None],
|
||||
"currency": ["CAD", "CAD"],
|
||||
"source": ["eod", "eod"],
|
||||
"known_at": pl.Series(
|
||||
[
|
||||
datetime(2025, 2, 10, 21, 0, 0, tzinfo=timezone.utc),
|
||||
datetime(2025, 2, 20, 21, 0, 0, tzinfo=timezone.utc),
|
||||
],
|
||||
dtype=pl.Datetime("us", "UTC"),
|
||||
),
|
||||
}
|
||||
)
|
||||
df.write_parquet(bars_dir / "part.parquet")
|
||||
|
||||
cutoff = compute_vault_cutoff_ts("2025-08-13") # 2025-02-13
|
||||
budget = resolve_duckdb_budget(memory_limit="1GB", threads=2, temp_directory=str(tmp_path / "tmp"))
|
||||
with MarketDataStore(tmp_path, vault_cutoff_ts=cutoff, budget=budget) as store:
|
||||
out = store.bars(from_date="2025-01-01", to_date="2025-08-13", adjustment="raw")
|
||||
assert out.height == 1
|
||||
assert str(out["session_date"][0]) == "2025-02-10"
|
||||
|
||||
|
||||
def test_signal_panel_analyzer_excludes_vault_rows() -> None:
|
||||
rows = []
|
||||
for day_idx in range(1, 20):
|
||||
d = f"2025-02-{day_idx:02d}"
|
||||
for lid in range(1, 15):
|
||||
rows.append(
|
||||
{
|
||||
"session_date": d,
|
||||
"listing_id": lid,
|
||||
"signal": float(lid),
|
||||
"forward_return": 0.001 * lid + (0.0001 * day_idx),
|
||||
}
|
||||
)
|
||||
panel = pl.DataFrame(rows)
|
||||
res = analyze_signal_panel(panel, vault_cutoff_date="2025-02-13", min_cross_section=10)
|
||||
assert res["vault_excluded_rows"] > 0
|
||||
assert all(d < "2025-02-13" for d in res["dates"]) # type: ignore[union-attr]
|
||||
assert res["mean_rank_ic"] > 0.9 # type: ignore[operator]
|
||||
1308
python/uv.lock
generated
Normal file
1308
python/uv.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
251
research/notebooks/ca_shorts_filings_study.py
Normal file
251
research/notebooks/ca_shorts_filings_study.py
Normal file
|
|
@ -0,0 +1,251 @@
|
|||
import marimo
|
||||
|
||||
__generated_with = "0.26.0"
|
||||
app = marimo.App(width="medium")
|
||||
|
||||
|
||||
@app.cell
|
||||
def _():
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import marimo as mo
|
||||
import polars as pl
|
||||
|
||||
from stockbot import (
|
||||
MarketDataStore,
|
||||
TrialLedgerClient,
|
||||
compute_vault_cutoff_ts,
|
||||
resolve_duckdb_budget,
|
||||
run_event_study_trial,
|
||||
run_signal_study,
|
||||
vault_cutoff_date_str,
|
||||
)
|
||||
|
||||
curated_root = Path(os.environ.get("STOCK_BOT_CURATED_ROOT", "/mnt/data/stockbot/m1-curated"))
|
||||
max_ingested_date = os.environ.get("STOCK_BOT_MAX_INGESTED_DATE", "2025-08-13")
|
||||
vault_cutoff_ts = compute_vault_cutoff_ts(max_ingested_date)
|
||||
vault_cutoff_date = vault_cutoff_date_str(vault_cutoff_ts)
|
||||
trial_ledger_dsn = os.environ.get("STOCK_BOT_TRIAL_LEDGER_DSN", "")
|
||||
temp_dir = os.environ.get("STOCK_BOT_DUCKDB_TEMP_DIRECTORY", "/tmp/stockbot-duckdb")
|
||||
|
||||
mo.md(
|
||||
f"""
|
||||
# Canadian `ceoShorts` & `qmFilings` Signal Lab Study (M1)
|
||||
|
||||
- **Curated Root:** `{curated_root}`
|
||||
- **Max Ingested Date:** `{max_ingested_date}`
|
||||
- **Rolling 6-Month Vault Cutoff (exclusive):** `{vault_cutoff_date}`
|
||||
- **Trial Ledger Configured:** `{"yes" if bool(trial_ledger_dsn) else "no"}`
|
||||
"""
|
||||
)
|
||||
return (
|
||||
MarketDataStore,
|
||||
TrialLedgerClient,
|
||||
curated_root,
|
||||
mo,
|
||||
pl,
|
||||
resolve_duckdb_budget,
|
||||
run_event_study_trial,
|
||||
run_signal_study,
|
||||
temp_dir,
|
||||
trial_ledger_dsn,
|
||||
vault_cutoff_date,
|
||||
vault_cutoff_ts,
|
||||
)
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(
|
||||
MarketDataStore,
|
||||
curated_root,
|
||||
mo,
|
||||
pl,
|
||||
resolve_duckdb_budget,
|
||||
temp_dir,
|
||||
vault_cutoff_date,
|
||||
vault_cutoff_ts,
|
||||
):
|
||||
_budget = resolve_duckdb_budget(
|
||||
memory_limit="4GB",
|
||||
threads=4,
|
||||
temp_directory=temp_dir,
|
||||
)
|
||||
_adj_fenced = curated_root / "adj_factors_fenced" / "part.parquet"
|
||||
if not _adj_fenced.exists():
|
||||
_adj_fenced = curated_root / "adj_factors" / "part.parquet"
|
||||
_adj_mode = "total" if _adj_fenced.exists() else "raw"
|
||||
|
||||
with MarketDataStore(
|
||||
curated_root,
|
||||
vault_cutoff_ts=vault_cutoff_ts,
|
||||
budget=_budget,
|
||||
adj_factors_path=_adj_fenced if _adj_fenced.exists() else None,
|
||||
) as _store:
|
||||
_ca_bars = _store.bars(
|
||||
currencies=["CAD"],
|
||||
from_date="2017-01-01",
|
||||
to_date=vault_cutoff_date,
|
||||
adjustment=_adj_mode,
|
||||
)
|
||||
_ca_shorts = _store.shorts_as_of(
|
||||
from_date="2017-01-01",
|
||||
to_date=vault_cutoff_date,
|
||||
)
|
||||
_ca_events = _store.events(
|
||||
kinds=["filing"],
|
||||
from_date="2017-01-01",
|
||||
to_date=vault_cutoff_date,
|
||||
)
|
||||
|
||||
_ca_listing_ids = _ca_bars.select("listing_id").unique()
|
||||
_ca_events = _ca_events.join(_ca_listing_ids, on="listing_id", how="semi")
|
||||
_ca_shorts = _ca_shorts.join(_ca_listing_ids, on="listing_id", how="semi")
|
||||
|
||||
# Confirm zero Vault rows leaked into any frame
|
||||
_vault_bar_leaks = int(
|
||||
_ca_bars.filter(pl.col("session_date").cast(pl.String) >= vault_cutoff_date).height
|
||||
)
|
||||
assert _vault_bar_leaks == 0, f"Vault fence breach: {_vault_bar_leaks} bars >= {vault_cutoff_date}"
|
||||
|
||||
# Build strict PIT ceoShorts signal panel (join_asof known_at <= bar.ts) with 5-session forward return
|
||||
_bars_fwd = (
|
||||
_ca_bars.sort(["listing_id", "session_date"])
|
||||
.with_columns(
|
||||
(pl.col("close").shift(-5).over("listing_id") / pl.col("close") - 1.0).alias(
|
||||
"forward_return"
|
||||
),
|
||||
(pl.col("close") * pl.col("volume")).alias("dollar_vol"),
|
||||
)
|
||||
.filter(pl.col("forward_return").is_finite() & (pl.col("close") > 0.10))
|
||||
)
|
||||
|
||||
_shorts_sorted = (
|
||||
_ca_shorts.select(["listing_id", "known_at", "shares_short", "net_change"])
|
||||
.filter(pl.col("shares_short") > 0)
|
||||
.sort(["listing_id", "known_at"])
|
||||
)
|
||||
|
||||
shorts_panel = (
|
||||
_bars_fwd.sort(["listing_id", "ts"])
|
||||
.join_asof(
|
||||
_shorts_sorted,
|
||||
left_on="ts",
|
||||
right_on="known_at",
|
||||
by="listing_id",
|
||||
strategy="backward",
|
||||
)
|
||||
.filter(pl.col("shares_short").is_not_null())
|
||||
.with_columns(
|
||||
(-(pl.col("shares_short") / (pl.col("volume").clip(lower_bound=1.0)))).alias("signal")
|
||||
)
|
||||
.select(["session_date", "listing_id", "signal", "forward_return"])
|
||||
)
|
||||
|
||||
ca_bars_summary = {
|
||||
"adjustment": _adj_mode,
|
||||
"ca_bars_rows": int(_ca_bars.height),
|
||||
"ca_shorts_rows": int(_ca_shorts.height),
|
||||
"ca_filings_rows": int(_ca_events.height),
|
||||
"shorts_panel_rows": int(shorts_panel.height),
|
||||
"vault_bar_leaks": _vault_bar_leaks,
|
||||
}
|
||||
ca_bars_slim = _ca_bars.filter(pl.col("close") >= 0.10).select(["listing_id", "session_date", "ts", "close"])
|
||||
ca_filings_slim = _ca_events.select(["listing_id", "known_at", "subtype"])
|
||||
|
||||
mo.md(
|
||||
f"""
|
||||
## Loaded Curated Canadian Datasets (Zero Vault Rows)
|
||||
|
||||
- **Adjustment mode:** `{ca_bars_summary['adjustment']}`
|
||||
- **Canadian `bars_1d` rows:** `{ca_bars_summary['ca_bars_rows']:,}` (`vault_bar_leaks = {ca_bars_summary['vault_bar_leaks']}`)
|
||||
- **Canadian `shorts` (`ceoShorts`, +4bd lag) rows:** `{ca_bars_summary['ca_shorts_rows']:,}`
|
||||
- **Canadian `events` (`qmFilings`) rows:** `{ca_bars_summary['ca_filings_rows']:,}`
|
||||
- **Joined PIT `ceoShorts` panel rows:** `{ca_bars_summary['shorts_panel_rows']:,}`
|
||||
"""
|
||||
)
|
||||
return ca_bars_slim, ca_bars_summary, ca_filings_slim, shorts_panel
|
||||
|
||||
|
||||
@app.cell
|
||||
def _(
|
||||
TrialLedgerClient,
|
||||
ca_bars_slim,
|
||||
ca_filings_slim,
|
||||
mo,
|
||||
run_event_study_trial,
|
||||
run_signal_study,
|
||||
shorts_panel,
|
||||
trial_ledger_dsn,
|
||||
vault_cutoff_date,
|
||||
):
|
||||
if not trial_ledger_dsn:
|
||||
mo.stop(True, mo.md("Set `STOCK_BOT_TRIAL_LEDGER_DSN` to write trials to `trial_ledger`."))
|
||||
|
||||
_ledger = TrialLedgerClient(trial_ledger_dsn)
|
||||
|
||||
shorts_study = run_signal_study(
|
||||
panel=shorts_panel,
|
||||
ledger=_ledger,
|
||||
principal_id="operator",
|
||||
universe_market="CA_EQ",
|
||||
horizon_bucket="swing_1_10d",
|
||||
horizon_label="5d",
|
||||
expression="neg_ciro_short_interest_to_volume_5d",
|
||||
params={"lag_bd": 4, "horizon_sessions": 5, "min_price_cad": 0.10, "n_quantiles": 5},
|
||||
vault_cutoff_date=vault_cutoff_date,
|
||||
n_quantiles=5,
|
||||
min_cross_section=10,
|
||||
ledger_series="rank_ic",
|
||||
)
|
||||
|
||||
filings_study = run_event_study_trial(
|
||||
bars_df=ca_bars_slim,
|
||||
events_df=ca_filings_slim,
|
||||
ledger=_ledger,
|
||||
principal_id="operator",
|
||||
universe_market="CA_EQ",
|
||||
horizon_bucket="swing_1_10d",
|
||||
expression="ca_qm_filings_abnormal_return_event_study",
|
||||
params={"pre_days": 5, "post_days": 10, "benchmark": "equal_weight"},
|
||||
vault_cutoff_date=vault_cutoff_date,
|
||||
pre_days=5,
|
||||
post_days=10,
|
||||
min_events=5,
|
||||
)
|
||||
|
||||
_s_trial = shorts_study["trial"]
|
||||
_s_dsr = shorts_study["dsr"]
|
||||
_s_ana = shorts_study["analysis"]
|
||||
_f_trial = filings_study["trial"]
|
||||
_f_dsr = filings_study["dsr"]
|
||||
_f_stu = filings_study["study"]
|
||||
|
||||
mo.md(
|
||||
f"""
|
||||
## Study Results & `trial_ledger` Deflated Sharpe
|
||||
|
||||
### 1. Canadian `ceoShorts` 5-Day Forward Return Signal
|
||||
- **Status:** `{shorts_study['status']}`
|
||||
- **Trial ID:** `{_s_trial.trial_id if _s_trial else None}` | **n_obs:** `{_s_trial.n_obs if _s_trial else 0}`
|
||||
- **Mean Rank-IC:** `{_s_ana['mean_rank_ic']:.6f}` (Newey-West t = `{_s_ana['rank_ic_nw_t']:.3f}`)
|
||||
- **Mean Q5-Q1 Spread:** `{_s_ana['mean_quantile_spread']:.6f}` (Turnover = `{_s_ana['mean_top_quantile_turnover']:.3f}`)
|
||||
- **Recency Gate (Post-2023):** `{_s_ana['recency_rank_ic']}`
|
||||
- **Unannualized Sharpe:** `{_s_trial.sharpe_unann if _s_trial else float('nan'):.6f}`
|
||||
- **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_s_dsr.cluster_size if _s_dsr else 0}` / `{_s_dsr.effective_trials if _s_dsr else 0.0:.4f}`
|
||||
- **Deflated Sharpe Ratio (DSR):** `{_s_dsr.dsr if _s_dsr else float('nan'):.6f}` (`passes_gate = {_s_dsr.passes_gate if _s_dsr else False}`)
|
||||
|
||||
### 2. Canadian `qmFilings` Event Study (`[-5, +10]` sessions)
|
||||
- **Status:** `{filings_study['status']}`
|
||||
- **Trial ID:** `{_f_trial.trial_id if _f_trial else None}` | **Events Used:** `{_f_stu.get('events_used', 0)}` | **Event Dates:** `{_f_stu.get('n_dates', 0)}`
|
||||
- **Mean Post-Event CAR:** `{_f_stu.get('car_mean', float('nan')):.6f}` (Newey-West t = `{_f_stu.get('car_nw_t', float('nan')):.3f}`)
|
||||
- **Recency Gate (Post-2023):** `{_f_stu.get('recency')}`
|
||||
- **Cluster Size ($K$) / Effective Trials ($\\hat{{N}}$):** `{_f_dsr.cluster_size if _f_dsr else 0}` / `{_f_dsr.effective_trials if _f_dsr else 0.0:.4f}`
|
||||
- **Deflated Sharpe Ratio (DSR):** `{_f_dsr.dsr if _f_dsr else float('nan'):.6f}` (`passes_gate = {_f_dsr.passes_gate if _f_dsr else False}`)
|
||||
"""
|
||||
)
|
||||
return filings_study, shorts_study
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
app.run()
|
||||
493
test/postgres/security-master-export-curate-inputs.test.ts
Normal file
493
test/postgres/security-master-export-curate-inputs.test.ts
Normal file
|
|
@ -0,0 +1,493 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool, type PoolClient } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import {
|
||||
exportCurateInputs,
|
||||
pinCurateInputSnapshot,
|
||||
type SecurityMasterQueryable,
|
||||
type SecurityMasterQueryResult,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('security-master-export-curate-inputs-pg-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
|
||||
const cleanup: (() => Promise<void> | void)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function makeTempDir(prefix = 'curate-inputs-pg-'): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), prefix));
|
||||
cleanup.push(() => rm(dir, { recursive: true, force: true }));
|
||||
return dir;
|
||||
}
|
||||
|
||||
async function createIsolatedFixture(statementTimeoutMs = 15_000) {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
options: `-c search_path=${schema} -c statement_timeout=${statementTimeoutMs} -c lock_timeout=15000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({
|
||||
connect: () => pool.connect(),
|
||||
}),
|
||||
});
|
||||
|
||||
await runPostgresMigrations(postgres, { track: 'master' });
|
||||
|
||||
return { pool, schema, postgres };
|
||||
}
|
||||
|
||||
async function withRecordingClient<T>(
|
||||
pool: Pool,
|
||||
fn: (queryable: SecurityMasterQueryable, recordedSql: string[]) => Promise<T>
|
||||
): Promise<T> {
|
||||
const client: PoolClient = await pool.connect();
|
||||
const recordedSql: string[] = [];
|
||||
const queryable: SecurityMasterQueryable = {
|
||||
query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
recordedSql.push(text.replace(/\s+/g, ' ').trim());
|
||||
return client.query(
|
||||
text,
|
||||
values === undefined ? undefined : [...values]
|
||||
) as unknown as Promise<SecurityMasterQueryResult<Row>>;
|
||||
},
|
||||
release: () => {
|
||||
client.release();
|
||||
},
|
||||
};
|
||||
try {
|
||||
return await fn(queryable, recordedSql);
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
async function seedFixtureData(pool: Pool) {
|
||||
const client = await pool.connect();
|
||||
try {
|
||||
await client.query('BEGIN');
|
||||
|
||||
// Ensure required MICs exist (migration 35 seeds them, ON CONFLICT DO NOTHING keeps idempotent).
|
||||
await client.query(`
|
||||
INSERT INTO exchange (mic, operating_mic, name, country_iso, currency, timezone, calendar_code, board_lot_policy)
|
||||
VALUES
|
||||
('XNAS', 'XNAS', 'NASDAQ', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
|
||||
('XNYS', 'XNYS', 'NYSE', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100'),
|
||||
('XTSE', 'XTSE', 'TSX', 'CA', 'CAD', 'America/Toronto', 'XTSE', 'tsx_tiered'),
|
||||
('OTCM', 'OTCM', 'OTC Markets', 'US', 'USD', 'America/New_York', 'XNYS', 'us_100')
|
||||
ON CONFLICT (mic) DO NOTHING
|
||||
`);
|
||||
|
||||
const insertInstrument = async (
|
||||
isin: string,
|
||||
cusip: string,
|
||||
name: string,
|
||||
securityType: string,
|
||||
country: string
|
||||
): Promise<number> => {
|
||||
const res = await client.query<{ instrument_id: number }>(
|
||||
`INSERT INTO instrument (primary_isin, primary_cusip, canonical_name, security_type, issuer_country)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING instrument_id`,
|
||||
[isin, cusip, name, securityType, country]
|
||||
);
|
||||
return res.rows[0]!.instrument_id;
|
||||
};
|
||||
|
||||
const instAapl = await insertInstrument('US0378331005', '037833100', 'Apple Inc.', 'common', 'US');
|
||||
const instShop = await insertInstrument('CA82509L1076', '82509L107', 'Shopify Inc.', 'common', 'CA');
|
||||
const instFbOld = await insertInstrument('US30303M1027', '30303M102', 'Meta Platforms', 'common', 'US');
|
||||
const instFbNew = await insertInstrument('US4642872000', '464287200', 'FB Thematic ETF', 'etf', 'US');
|
||||
const instSivb = await insertInstrument('US78486Q1013', '78486Q101', 'SVB Financial Group', 'common', 'US');
|
||||
const instSivbReuse = await insertInstrument('US0000000019', '000000001', 'SIVB Reused Corp', 'common', 'US');
|
||||
const instDel30 = await insertInstrument('US0000000027', '000000002', 'Delisted 30 Corp', 'common', 'US');
|
||||
const instNoListedTo = await insertInstrument('US0000000035', '000000003', 'No ListedTo Corp', 'common', 'US');
|
||||
const instNoQm = await insertInstrument('US0000000043', '000000004', 'No QM Mapping Corp', 'common', 'US');
|
||||
const instNoSuccQm = await insertInstrument('US0000000050', '000000005', 'No Succ QM Corp', 'common', 'US');
|
||||
|
||||
const insertListing = async (params: {
|
||||
instrumentId: number;
|
||||
mic: string;
|
||||
tickerRoot: string;
|
||||
currency: string;
|
||||
listedFrom: string | null;
|
||||
listedTo: string | null;
|
||||
delistReason: string | null;
|
||||
terminalReturn: string | null;
|
||||
}): Promise<number> => {
|
||||
const res = await client.query<{ listing_id: number }>(
|
||||
`INSERT INTO listing (
|
||||
instrument_id, mic, ticker_root, class_suffix, currency,
|
||||
listed_from, listed_to, delist_reason, terminal_return
|
||||
)
|
||||
VALUES ($1, $2, $3, '', $4, $5::date, $6::date, $7, $8::numeric)
|
||||
RETURNING listing_id`,
|
||||
[
|
||||
params.instrumentId,
|
||||
params.mic,
|
||||
params.tickerRoot,
|
||||
params.currency,
|
||||
params.listedFrom,
|
||||
params.listedTo,
|
||||
params.delistReason,
|
||||
params.terminalReturn,
|
||||
]
|
||||
);
|
||||
return res.rows[0]!.listing_id;
|
||||
};
|
||||
|
||||
const aaplId = await insertListing({
|
||||
instrumentId: instAapl,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'AAPL',
|
||||
currency: 'USD',
|
||||
listedFrom: '1980-12-12',
|
||||
listedTo: null,
|
||||
delistReason: 'active',
|
||||
terminalReturn: null,
|
||||
});
|
||||
const shopId = await insertListing({
|
||||
instrumentId: instShop,
|
||||
mic: 'XTSE',
|
||||
tickerRoot: 'SHOP',
|
||||
currency: 'CAD',
|
||||
listedFrom: '2015-05-21',
|
||||
listedTo: null,
|
||||
delistReason: 'active',
|
||||
terminalReturn: null,
|
||||
});
|
||||
const fbOldId = await insertListing({
|
||||
instrumentId: instFbOld,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'FB',
|
||||
currency: 'USD',
|
||||
listedFrom: '2012-05-18',
|
||||
listedTo: '2022-06-08',
|
||||
delistReason: null,
|
||||
terminalReturn: null,
|
||||
});
|
||||
const fbNewId = await insertListing({
|
||||
instrumentId: instFbNew,
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'FB',
|
||||
currency: 'USD',
|
||||
listedFrom: '2022-06-09',
|
||||
listedTo: null,
|
||||
delistReason: 'active',
|
||||
terminalReturn: null,
|
||||
});
|
||||
const sivbId = await insertListing({
|
||||
instrumentId: instSivb,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'SIVB',
|
||||
currency: 'USD',
|
||||
listedFrom: '1988-01-04',
|
||||
listedTo: '2023-03-10',
|
||||
delistReason: 'moved_to_otc',
|
||||
terminalReturn: null,
|
||||
});
|
||||
const sivbReuseId = await insertListing({
|
||||
instrumentId: instSivbReuse,
|
||||
mic: 'XNAS',
|
||||
tickerRoot: 'SIVB',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-20',
|
||||
listedTo: null,
|
||||
delistReason: 'active',
|
||||
terminalReturn: null,
|
||||
});
|
||||
const sivbqId = await insertListing({
|
||||
instrumentId: instSivb,
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'SIVBQ',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-28',
|
||||
listedTo: '2024-11-07',
|
||||
delistReason: 'bankruptcy_cancelled',
|
||||
terminalReturn: '-1.000000',
|
||||
});
|
||||
const del30Id = await insertListing({
|
||||
instrumentId: instDel30,
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'DEL30',
|
||||
currency: 'USD',
|
||||
listedFrom: '2018-01-02',
|
||||
listedTo: '2023-06-15',
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: '-0.300000',
|
||||
});
|
||||
const noListedToId = await insertListing({
|
||||
instrumentId: instNoListedTo,
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'NLDT',
|
||||
currency: 'USD',
|
||||
listedFrom: '2019-01-02',
|
||||
listedTo: null,
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: '-0.300000',
|
||||
});
|
||||
const noQmId = await insertListing({
|
||||
instrumentId: instNoQm,
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'NOQM',
|
||||
currency: 'USD',
|
||||
listedFrom: '2019-01-02',
|
||||
listedTo: '2023-07-01',
|
||||
delistReason: 'unknown_involuntary',
|
||||
terminalReturn: '-0.300000',
|
||||
});
|
||||
const noSuccQmFromId = await insertListing({
|
||||
instrumentId: instNoSuccQm,
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'NOSU',
|
||||
currency: 'USD',
|
||||
listedFrom: '2019-01-02',
|
||||
listedTo: '2023-03-10',
|
||||
delistReason: 'moved_to_otc',
|
||||
terminalReturn: null,
|
||||
});
|
||||
const noSuccQmToId = await insertListing({
|
||||
instrumentId: instNoSuccQm,
|
||||
mic: 'OTCM',
|
||||
tickerRoot: 'NOSUQ',
|
||||
currency: 'USD',
|
||||
listedFrom: '2023-03-28',
|
||||
listedTo: null,
|
||||
delistReason: null,
|
||||
terminalReturn: null,
|
||||
});
|
||||
|
||||
const insertMapping = async (
|
||||
source: string,
|
||||
sourceId: string,
|
||||
validFrom: string,
|
||||
validTo: string | null,
|
||||
listingId: number
|
||||
) => {
|
||||
await client.query(
|
||||
`INSERT INTO provider_mapping (source, source_id, valid_from, valid_to, listing_id, method, confidence)
|
||||
VALUES ($1, $2, $3::date, $4::date, $5, 'tier1_isin', 0.990)`,
|
||||
[source, sourceId, validFrom, validTo, listingId]
|
||||
);
|
||||
};
|
||||
|
||||
// Active US + CA
|
||||
await insertMapping('eod', 'AAPL.US', '1980-12-12', null, aaplId);
|
||||
await insertMapping('qm', 'AAPL', '1980-12-12', null, aaplId);
|
||||
await insertMapping('eod', 'SHOP.TO', '2015-05-21', null, shopId);
|
||||
await insertMapping('qm', 'SHOP:CA', '2015-05-21', null, shopId);
|
||||
|
||||
// Ticker reuse FB across two date ranges
|
||||
await insertMapping('eod', 'FB.US', '2012-05-18', '2022-06-08', fbOldId);
|
||||
await insertMapping('eod', 'FB.US', '2022-06-09', null, fbNewId);
|
||||
await insertMapping('qm', 'FB', '2012-05-18', '2022-06-08', fbOldId);
|
||||
await insertMapping('qm', 'FB', '2022-06-09', null, fbNewId);
|
||||
|
||||
// SIVB -> SIVBQ across ticker reuse
|
||||
await insertMapping('eod', 'SIVB.US', '1988-01-04', '2023-03-10', sivbId);
|
||||
await insertMapping('eod', 'SIVB.US', '2023-03-20', null, sivbReuseId);
|
||||
await insertMapping('eod', 'SIVBQ.US', '2023-03-28', '2024-11-07', sivbqId);
|
||||
await insertMapping('qm', 'SIVB', '1988-01-04', '2023-03-10', sivbId);
|
||||
await insertMapping('qm', 'SIVB', '2023-03-20', null, sivbReuseId);
|
||||
await insertMapping('qm', 'SIVBQ', '2023-03-28', '2024-11-07', sivbqId);
|
||||
|
||||
// DEL30 -0.3 terminal delisting
|
||||
await insertMapping('eod', 'DEL30.US', '2018-01-02', '2023-06-15', del30Id);
|
||||
await insertMapping('qm', 'DEL30', '2018-01-02', '2023-06-15', del30Id);
|
||||
|
||||
// Skipped-row mappings: noQm has only eod; noSuccQmFrom has qm, successor has no qm
|
||||
await insertMapping('eod', 'NOQM.US', '2019-01-02', '2023-07-01', noQmId);
|
||||
await insertMapping('qm', 'NOSU', '2019-01-02', '2023-03-10', noSuccQmFromId);
|
||||
|
||||
// Continuities
|
||||
await client.query(
|
||||
`INSERT INTO corporate_action_continuity (from_listing_id, to_listing_id, effective_date, kind)
|
||||
VALUES
|
||||
($1, $2, '2023-03-28'::date, 'otc_delist_transfer'),
|
||||
($3, $4, '2023-03-28'::date, 'otc_delist_transfer')`,
|
||||
[sivbId, sivbqId, noSuccQmFromId, noSuccQmToId]
|
||||
);
|
||||
|
||||
await client.query('COMMIT');
|
||||
|
||||
return {
|
||||
aaplId,
|
||||
shopId,
|
||||
fbOldId,
|
||||
fbNewId,
|
||||
sivbId,
|
||||
sivbReuseId,
|
||||
sivbqId,
|
||||
del30Id,
|
||||
noListedToId,
|
||||
noQmId,
|
||||
noSuccQmFromId,
|
||||
noSuccQmToId,
|
||||
};
|
||||
} catch (error) {
|
||||
await client.query('ROLLBACK').catch(() => {});
|
||||
throw error;
|
||||
} finally {
|
||||
client.release();
|
||||
}
|
||||
}
|
||||
|
||||
describe('exportCurateInputs PostgreSQL integration (isolated stock_bot_safety_*)', () => {
|
||||
test('exports exact TSV bytes read-only and matches across chunkSize=1 and chunkSize=5000', async () => {
|
||||
const { pool } = await createIsolatedFixture();
|
||||
const ids = await seedFixtureData(pool);
|
||||
|
||||
const outDir5000 = await makeTempDir('curate-inputs-pg-5000-');
|
||||
const outDir1 = await makeTempDir('curate-inputs-pg-1-');
|
||||
|
||||
const { result: res5000, sql: sql5000 } = await withRecordingClient(
|
||||
pool,
|
||||
async (queryable, recordedSql) => ({
|
||||
result: await exportCurateInputs(queryable, { outDir: outDir5000, chunkSize: 5000 }),
|
||||
sql: recordedSql,
|
||||
})
|
||||
);
|
||||
|
||||
const { result: res1, sql: sql1 } = await withRecordingClient(
|
||||
pool,
|
||||
async (queryable, recordedSql) => ({
|
||||
result: await exportCurateInputs(queryable, { outDir: outDir1, chunkSize: 1 }),
|
||||
sql: recordedSql,
|
||||
})
|
||||
);
|
||||
|
||||
// Read-only SQL verification: REPEATABLE READ READ ONLY transaction + server-side cursor + zero writes/DDL.
|
||||
for (const sqlLog of [sql5000, sql1]) {
|
||||
expect(sqlLog[0]).toBe('BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
|
||||
expect(sqlLog[sqlLog.length - 1]).toBe('COMMIT');
|
||||
expect(sqlLog.some(s => s.startsWith('DECLARE curate_export_pm_cursor NO SCROLL CURSOR FOR'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(sqlLog.some(s => s === 'CLOSE curate_export_pm_cursor')).toBe(true);
|
||||
for (const stmt of sqlLog) {
|
||||
expect(stmt).not.toMatch(/\b(INSERT|UPDATE|DELETE|CREATE|ALTER|DROP|TRUNCATE|GRANT|REVOKE)\b/i);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify snapshot pinning resolves to the published immutable generation.
|
||||
const pinned5000 = await pinCurateInputSnapshot(outDir5000);
|
||||
expect(pinned5000.generationId).toBe(res5000.generationId);
|
||||
expect(pinned5000.providerMapping).toBe(res5000.providerMapping.path);
|
||||
expect(pinned5000.listingCurrencies).toBe(res5000.listingCurrencies.path);
|
||||
expect(pinned5000.delistings).toBe(res5000.delistings.path);
|
||||
|
||||
// Verify chunkSize=1 actually paginated across multiple queries.
|
||||
expect(sql1.length).toBeGreaterThan(sql5000.length);
|
||||
|
||||
// Byte-identical outputs between chunkSize=1 and chunkSize=5000.
|
||||
const pm5000 = await readFile(res5000.providerMapping.path, 'utf8');
|
||||
const lc5000 = await readFile(res5000.listingCurrencies.path, 'utf8');
|
||||
const dl5000 = await readFile(res5000.delistings.path, 'utf8');
|
||||
|
||||
expect(await readFile(res1.providerMapping.path, 'utf8')).toBe(pm5000);
|
||||
expect(await readFile(res1.listingCurrencies.path, 'utf8')).toBe(lc5000);
|
||||
expect(await readFile(res1.delistings.path, 'utf8')).toBe(dl5000);
|
||||
|
||||
// Assert exact provider_mapping.tsv content (COLLATE "C" ASCII order).
|
||||
expect(pm5000).toBe(
|
||||
[
|
||||
`eod\tAAPL.US\t1980-12-12\t\t${ids.aaplId}`,
|
||||
`eod\tDEL30.US\t2018-01-02\t2023-06-15\t${ids.del30Id}`,
|
||||
`eod\tFB.US\t2012-05-18\t2022-06-08\t${ids.fbOldId}`,
|
||||
`eod\tFB.US\t2022-06-09\t\t${ids.fbNewId}`,
|
||||
`eod\tNOQM.US\t2019-01-02\t2023-07-01\t${ids.noQmId}`,
|
||||
`eod\tSHOP.TO\t2015-05-21\t\t${ids.shopId}`,
|
||||
`eod\tSIVB.US\t1988-01-04\t2023-03-10\t${ids.sivbId}`,
|
||||
`eod\tSIVB.US\t2023-03-20\t\t${ids.sivbReuseId}`,
|
||||
`eod\tSIVBQ.US\t2023-03-28\t2024-11-07\t${ids.sivbqId}`,
|
||||
`qm\tAAPL\t1980-12-12\t\t${ids.aaplId}`,
|
||||
`qm\tDEL30\t2018-01-02\t2023-06-15\t${ids.del30Id}`,
|
||||
`qm\tFB\t2012-05-18\t2022-06-08\t${ids.fbOldId}`,
|
||||
`qm\tFB\t2022-06-09\t\t${ids.fbNewId}`,
|
||||
`qm\tNOSU\t2019-01-02\t2023-03-10\t${ids.noSuccQmFromId}`,
|
||||
`qm\tSHOP:CA\t2015-05-21\t\t${ids.shopId}`,
|
||||
`qm\tSIVB\t1988-01-04\t2023-03-10\t${ids.sivbId}`,
|
||||
`qm\tSIVB\t2023-03-20\t\t${ids.sivbReuseId}`,
|
||||
`qm\tSIVBQ\t2023-03-28\t2024-11-07\t${ids.sivbqId}`,
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
// Assert exact listing_currencies.tsv content (btrim(CHAR(3)), ascending listing_id).
|
||||
expect(lc5000).toBe(
|
||||
[
|
||||
`${ids.aaplId}\tUSD`,
|
||||
`${ids.shopId}\tCAD`,
|
||||
`${ids.fbOldId}\tUSD`,
|
||||
`${ids.fbNewId}\tUSD`,
|
||||
`${ids.sivbId}\tUSD`,
|
||||
`${ids.sivbReuseId}\tUSD`,
|
||||
`${ids.sivbqId}\tUSD`,
|
||||
`${ids.del30Id}\tUSD`,
|
||||
`${ids.noListedToId}\tUSD`,
|
||||
`${ids.noQmId}\tUSD`,
|
||||
`${ids.noSuccQmFromId}\tUSD`,
|
||||
`${ids.noSuccQmToId}\tUSD`,
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
// Assert exact delistings.tsv content.
|
||||
expect(dl5000).toBe(
|
||||
[
|
||||
`DEL30\t2023-06-15\t${ids.del30Id}\t\t-0.3`,
|
||||
`SIVB\t2023-03-28\t${ids.sivbId}\tSIVBQ\t`,
|
||||
`SIVBQ\t2024-11-07\t${ids.sivbqId}\t\t-1`,
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
|
||||
// Assert exact stats reconciliation.
|
||||
const stats = res5000.delistings.stats;
|
||||
expect(stats).toEqual({
|
||||
rowsIn: 12,
|
||||
rowsOut: 3,
|
||||
otcTransfersOut: 1,
|
||||
terminalDelistingsOut: 2,
|
||||
skippedTotal: 9,
|
||||
skipped: {
|
||||
active: 4, // AAPL, SHOP, FB new, SIVB reuse
|
||||
noOutcome: 2, // FB old, NOSUQ
|
||||
missingListedTo: 1, // NLDT
|
||||
missingOutgoingQmMapping: 1, // NOQM
|
||||
missingSuccessorQmMapping: 1, // NOSU -> NOSUQ
|
||||
nonOtcContinuity: 0,
|
||||
},
|
||||
});
|
||||
expect(stats.rowsIn).toBe(stats.rowsOut + stats.skippedTotal);
|
||||
expect(res1.delistings.stats).toEqual(stats);
|
||||
});
|
||||
});
|
||||
192
test/unit/data-pipeline-rust-evaluation-doc.test.ts
Normal file
192
test/unit/data-pipeline-rust-evaluation-doc.test.ts
Normal file
|
|
@ -0,0 +1,192 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
|
||||
// Guards the T-124 decision brief (design/data-pipeline/rust-migration-evaluation.md) against
|
||||
// silent drift: it must stay linked, keep its seven required sections, keep internally consistent
|
||||
// totals and derived figures, and every quoted benchmark figure must still appear verbatim in the
|
||||
// README it cites. Live file counts are deliberately not pinned here (they change with every
|
||||
// data-pipeline task); the document's own reproducible commands cover that at its commit.
|
||||
const repoRoot = join(import.meta.dir, '..', '..');
|
||||
const evalRel = 'design/data-pipeline/rust-migration-evaluation.md';
|
||||
const evalPath = join(repoRoot, evalRel);
|
||||
const designReadmePath = join(repoRoot, 'design/README.md');
|
||||
const curateReadme = readFileSync(join(repoRoot, 'tools/curate-etl/README.md'), 'utf8');
|
||||
const pipelineReadme = readFileSync(join(repoRoot, 'apps/stock/data-pipeline/README.md'), 'utf8');
|
||||
const doc = readFileSync(evalPath, 'utf8');
|
||||
|
||||
function num(text: string): number {
|
||||
return Number(text.replace(/[`,*]/g, '').trim());
|
||||
}
|
||||
|
||||
function section(title: RegExp): string {
|
||||
const lines = doc.split('\n');
|
||||
const start = lines.findIndex(line => /^## /.test(line) && title.test(line));
|
||||
expect(start).toBeGreaterThan(-1);
|
||||
const rest = lines.slice(start + 1);
|
||||
const end = rest.findIndex(line => /^## /.test(line));
|
||||
return rest.slice(0, end === -1 ? undefined : end).join('\n');
|
||||
}
|
||||
|
||||
function tableRows(body: string, firstCell: RegExp): string[][] {
|
||||
return body
|
||||
.split('\n')
|
||||
.filter(line => line.startsWith('|'))
|
||||
.map(line => line.split('|').slice(1, -1).map(cell => cell.trim()))
|
||||
.filter(cells => firstCell.test(cells[0] ?? ''));
|
||||
}
|
||||
|
||||
describe('data-pipeline Rust migration evaluation document', () => {
|
||||
test('design/README.md links to the evaluation and the link resolves', () => {
|
||||
const readme = readFileSync(designReadmePath, 'utf8');
|
||||
expect(readme).toContain('](data-pipeline/rust-migration-evaluation.md)');
|
||||
expect(existsSync(evalPath)).toBe(true);
|
||||
});
|
||||
|
||||
test('contains all seven required sections in order', () => {
|
||||
const headings = doc.split('\n').filter(line => /^## \d\./.test(line));
|
||||
expect(headings.map(h => h.match(/^## (\d)\./)![1])).toEqual(['1', '2', '3', '4', '5', '6', '7']);
|
||||
expect(headings[0]).toMatch(/Inventory/);
|
||||
expect(headings[1]).toMatch(/Rust/);
|
||||
expect(headings[2]).toMatch(/Workload Classification/);
|
||||
expect(headings[3]).toMatch(/Options Comparison/);
|
||||
expect(headings[4]).toMatch(/Compliance/);
|
||||
expect(headings[5]).toMatch(/Recommendation/);
|
||||
expect(headings[6]).toMatch(/Not Verified/);
|
||||
});
|
||||
|
||||
test('inventory covers the T-89/T-105 CLI, T-116 TSV exporter, T-117 raw-BSON exporter and web-api coupling', () => {
|
||||
const inventory = section(/^## 1\./);
|
||||
for (const needle of ['T-89', 'T-105', 'T-116', 'T-117', 'run-security-master.ts', 'export-curate-inputs.ts', 'export-raw-bson.ts', '{data-pipeline_exchanges}', '{data-pipeline_symbols}', 'getFullQueueName', '@stock-bot/types', 'mongoReadOnly: true', 'assertEnvironmentSafety()']) {
|
||||
expect(inventory).toContain(needle);
|
||||
}
|
||||
// The commands that make the counts reproducible are printed verbatim.
|
||||
expect(inventory).toContain("find \"apps/stock/data-pipeline/src/$area\" -type f -name '*.ts'");
|
||||
});
|
||||
|
||||
test('every path referenced by the inventory commands exists', () => {
|
||||
const inventory = section(/^## 1\./);
|
||||
const block = inventory.match(/```bash\n([\s\S]*?)```/)![1]!;
|
||||
for (const area of ['security-master', 'normalization', 'handlers', 'repositories', 'routes', 'types']) {
|
||||
expect(existsSync(join(repoRoot, 'apps/stock/data-pipeline/src', area))).toBe(true);
|
||||
}
|
||||
const paths = new Set(block.match(/(?:apps|test|tools)\/[\w./-]+/g) ?? []);
|
||||
expect(paths.size).toBeGreaterThan(0);
|
||||
for (const path of paths) {
|
||||
expect({ path, exists: existsSync(join(repoRoot, path)) }).toEqual({ path, exists: true });
|
||||
}
|
||||
});
|
||||
|
||||
test('per-area inventory rows sum to the stated src/ total', () => {
|
||||
const rows = tableRows(section(/^## 1\./), /^`(security-master|normalization|handlers|repositories|routes|types)\/`$|^`index\.ts`$|Total/);
|
||||
const areas = rows.filter(r => !/Total/.test(r[0]!));
|
||||
const total = rows.find(r => /Total/.test(r[0]!))!;
|
||||
expect(areas).toHaveLength(7);
|
||||
const sum = (col: number) => areas.reduce((acc, r) => acc + (Number.isNaN(num(r[col]!)) ? 0 : num(r[col]!)), 0);
|
||||
expect(sum(1)).toBe(num(total[1]!));
|
||||
expect(sum(2)).toBe(num(total[2]!));
|
||||
// pipeline-safety.test.ts is attributed to handlers/ and shared with repositories/ (counted once).
|
||||
expect(sum(3)).toBe(num(total[3]!));
|
||||
expect(sum(4)).toBe(num(total[4]!));
|
||||
});
|
||||
|
||||
test('curate-etl module groups sum to the stated Rust total and the non-test/test split', () => {
|
||||
const rows = tableRows(section(/^## 2\./), /./).filter(r => /^\d/.test(r[1]?.replace(/\*/g, '') ?? ''));
|
||||
const total = rows.find(r => /Total/.test(r[0]!))!;
|
||||
const groups = rows.filter(r => r !== total);
|
||||
const tests = groups.find(r => /test modules/.test(r[0]!))!;
|
||||
const files = groups.reduce((acc, r) => acc + num(r[1]!), 0);
|
||||
const loc = groups.reduce((acc, r) => acc + num(r[2]!), 0);
|
||||
expect(files).toBe(num(total[1]!));
|
||||
expect(loc).toBe(num(total[2]!));
|
||||
expect(total[3]).toContain(`${files - num(tests[1]!)} non-test files (${(loc - num(tests[2]!)).toLocaleString('en-US')} LOC)`);
|
||||
expect(total[3]).toContain(`${num(tests[1]!)} test files (${num(tests[2]!).toLocaleString('en-US')} LOC)`);
|
||||
});
|
||||
|
||||
test('derived figures in the brief are arithmetically consistent', () => {
|
||||
// 88.1% of src/ LOC is security-master/.
|
||||
expect(doc).toContain('88.1%');
|
||||
expect(((17_924 / 20_349) * 100).toFixed(1)).toBe('88.1');
|
||||
// rayon write speedup from the dated local re-run.
|
||||
expect(doc).toContain('4.72x');
|
||||
expect((445.79 / 94.42).toFixed(2)).toBe('4.72');
|
||||
// Scratch estimates are binary GiB: docs x bytes/doc / 2^30, total I/O = 2x peak.
|
||||
const gib = (docs: number, bytes: number) => Math.round((docs * bytes) / 2 ** 30);
|
||||
expect([gib(845.7e6, 161.7), gib(845.7e6, 285.6)]).toEqual([127, 225]);
|
||||
expect([gib(3.40e9 + 173.3e6, 150), gib(3.40e9 + 173.3e6, 250)]).toEqual([499, 832]);
|
||||
expect(doc).toContain('~127–225 GiB');
|
||||
expect(doc).toContain('~255–450 GiB');
|
||||
expect(doc).toContain('~499–832 GiB');
|
||||
expect(doc).toContain('~998–1,664 GiB');
|
||||
expect(doc).not.toMatch(/\d\s?GB peak/);
|
||||
});
|
||||
|
||||
test('every README-sourced benchmark row quotes figures present in the cited README', () => {
|
||||
const rows = tableRows(section(/^## 2\./), /./).filter(r => /README\.md/.test(r[1] ?? ''));
|
||||
expect(rows.length).toBeGreaterThanOrEqual(15);
|
||||
for (const [name, source, command, result] of rows) {
|
||||
const readme = source!.includes('tools/curate-etl/README.md') ? curateReadme : pipelineReadme;
|
||||
// Each row states a date or explicitly says the README omits one.
|
||||
expect({ name, dated: /\d{4}-\d{2}-\d{2}|date omitted/.test(source!) }).toEqual({ name, dated: true });
|
||||
// The command is copied in full (no ellipsis abbreviations) and appears in the README.
|
||||
const cmd = command!.replace(/`/g, '');
|
||||
expect({ name, abbreviated: cmd.includes('...') || cmd.includes('…') }).toEqual({ name, abbreviated: false });
|
||||
const bin = cmd.match(/-- (\S+)/)?.[1] ?? cmd.match(/(\S+\.(?:test\.)?ts)/)?.[1];
|
||||
expect({ name, bin, inReadme: readme.includes(bin!) }).toEqual({ name, bin, inReadme: true });
|
||||
// Every millisecond figure in the bolded result appears verbatim in the README.
|
||||
const bold = (result!.match(/\*\*([^*]+)\*\*/g) ?? []).join(' ');
|
||||
for (const ms of bold.match(/[\d,]+\.\d+(?= ms)/g) ?? []) {
|
||||
expect({ name, ms, inReadme: readme.includes(ms) || readme.includes(ms.replace(/,/g, '')) }).toEqual({ name, ms, inReadme: true });
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('the only non-README benchmark is a labelled local synthetic re-run, never quant or live Mongo', () => {
|
||||
const rows = tableRows(section(/^## 2\./), /^`/).filter(r => r.length === 4 && !/README\.md/.test(r[1]!));
|
||||
expect(rows).toHaveLength(1);
|
||||
const [, source, command] = rows[0]!;
|
||||
expect(source).toMatch(/Local sandbox re-run/);
|
||||
expect(source).toMatch(/2026-11-29/);
|
||||
expect(source).toMatch(/synthetic/);
|
||||
expect(command).toContain('--offline');
|
||||
expect(section(/^## 2\./)).toContain('Zero Live QA MongoDB or `quant` Runs');
|
||||
});
|
||||
|
||||
test('options table compares at least three options across the required dimensions', () => {
|
||||
const body = section(/^## 4\./);
|
||||
const header = body.split('\n').find(line => line.startsWith('| Dimension'))!;
|
||||
expect(header.match(/Option [A-Z]/g)!.length).toBeGreaterThanOrEqual(3);
|
||||
for (const dim of ['Estimated Effort', 'New Rust Crates Required', 'Expected Runtime', 'Key Risks', 'Impact on M2']) {
|
||||
expect(body).toContain(dim);
|
||||
}
|
||||
expect(body).toMatch(/End-to-end wall-time speedup is unmeasured/);
|
||||
});
|
||||
|
||||
test('compliance matrix covers D1–D12 and QA safety rules for every option', () => {
|
||||
const body = section(/^## 5\./);
|
||||
for (let d = 1; d <= 12; d++) {
|
||||
const row = tableRows(body, new RegExp(`^\\*\\*D${d}\\*\\*`));
|
||||
expect({ d, rows: row.length, cells: row[0]?.length }).toEqual({ d, rows: 1, cells: 4 });
|
||||
}
|
||||
expect(body).toMatch(/Reopens §4 layer table/);
|
||||
for (const needle of ['studio_stock_bot_read', 'trading_admin', 'stock_bot_safety*']) {
|
||||
expect(body).toContain(needle);
|
||||
}
|
||||
});
|
||||
|
||||
test('gives exactly one recommendation, director-gated follow-ups and a non-port list', () => {
|
||||
const body = section(/^## 6\./);
|
||||
expect(body.match(/\*\*Select Option [A-C]\.\*\*/g)).toEqual(['**Select Option B.**']);
|
||||
expect(body).toMatch(/Director-Gated — Not Yet Queued or Enacted/);
|
||||
expect(body.match(/^\d+\. \*\*/gm)!.length).toBeGreaterThanOrEqual(3);
|
||||
expect(body).toContain('### What Should NOT Be Ported to Rust');
|
||||
});
|
||||
|
||||
test('every relative Markdown link in the brief resolves', () => {
|
||||
const links = [...doc.matchAll(/\]\(([^)#\s]+)(?:#[^)]*)?\)/g)].map(m => m[1]!).filter(l => !/^[a-z]+:/i.test(l));
|
||||
for (const link of links) {
|
||||
const target = resolve(dirname(evalPath), link);
|
||||
expect({ link, exists: existsSync(target) }).toEqual({ link, exists: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
@ -1,5 +1,5 @@
|
|||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import { MongoClient } from 'mongodb';
|
||||
import { BSON, MongoClient } from 'mongodb';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
|
||||
|
|
@ -1196,4 +1196,82 @@ describe('MongoDBClient read-only mode (offline)', () => {
|
|||
expect(collectionStub.insertOne).toHaveBeenCalledTimes(2);
|
||||
expect(dbStub.createCollection).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('forwards find(filter, { raw: true, batchSize, limit }) through read-only collection/cursor and yields raw BSON buffers untouched', async () => {
|
||||
const logger = getLogger('mongodb-read-only-raw-find-test');
|
||||
const rawFrames = [
|
||||
Buffer.from(BSON.serialize({ eodSearchCode: 'AAPL.US', date: '2025-01-02', close: 250.5 })),
|
||||
Buffer.from(BSON.serialize({ eodSearchCode: 'RY.TO', date: '2025-01-02', close: 175.25 })),
|
||||
];
|
||||
const closeMock = mock(async () => {});
|
||||
const rawCursorStub = {
|
||||
close: closeMock,
|
||||
[Symbol.asyncIterator]: async function* () {
|
||||
for (const frame of rawFrames) {
|
||||
yield frame;
|
||||
}
|
||||
},
|
||||
};
|
||||
const findCalls: Array<{ filter: unknown; options: unknown }> = [];
|
||||
const collectionStub = {
|
||||
collectionName: 'eodPrices',
|
||||
dbName: 'stock',
|
||||
namespace: 'stock.eodPrices',
|
||||
find: mock((filter: unknown, options: unknown) => {
|
||||
findCalls.push({ filter, options });
|
||||
return rawCursorStub;
|
||||
}),
|
||||
insertOne: mock(async () => ({ insertedId: 'id-1' })),
|
||||
drop: mock(async () => true),
|
||||
};
|
||||
const dbStub = {
|
||||
databaseName: 'stock',
|
||||
namespace: 'stock',
|
||||
collection: mock(() => collectionStub),
|
||||
};
|
||||
|
||||
const client = new MongoDBClient(
|
||||
{ host: '127.0.0.1', port: 1, database: 'stock', readOnly: true },
|
||||
logger
|
||||
);
|
||||
Object.assign(client, {
|
||||
client: { db: mock(() => dbStub) },
|
||||
db: dbStub,
|
||||
isConnected: true,
|
||||
});
|
||||
|
||||
const collection = client.getCollection('eodPrices');
|
||||
const cursor = collection.find(
|
||||
{ eodSearchCode: 'CAD.FOREX' },
|
||||
{ raw: true, batchSize: 128, limit: 2 }
|
||||
);
|
||||
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
filter: { eodSearchCode: 'CAD.FOREX' },
|
||||
options: { raw: true, batchSize: 128, limit: 2 },
|
||||
},
|
||||
]);
|
||||
|
||||
const yielded: unknown[] = [];
|
||||
try {
|
||||
for await (const frame of cursor) {
|
||||
yielded.push(frame);
|
||||
}
|
||||
} finally {
|
||||
await cursor.close();
|
||||
}
|
||||
|
||||
expect(yielded).toHaveLength(2);
|
||||
expect(yielded[0]).toBe(rawFrames[0]);
|
||||
expect(yielded[1]).toBe(rawFrames[1]);
|
||||
expect(yielded[0]).toBeInstanceOf(Uint8Array);
|
||||
expect(closeMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Write and DDL guards remain intact on the same read-only collection wrapper
|
||||
expect(() => collection.insertOne({ a: 1 })).toThrow(/read-only mode/);
|
||||
expect(() => collection.drop()).toThrow(/read-only mode/);
|
||||
expect(collectionStub.insertOne).not.toHaveBeenCalled();
|
||||
expect(collectionStub.drop).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
740
test/unit/security-master-export-curate-inputs-parity.test.ts
Normal file
740
test/unit/security-master-export-curate-inputs-parity.test.ts
Normal file
|
|
@ -0,0 +1,740 @@
|
|||
/**
|
||||
* QA differential tests for the curate-etl TSV exporter (T-116).
|
||||
*
|
||||
* - The streaming PostgreSQL exporter (`exportCurateInputs`) and the pure core
|
||||
* (`formatProviderMappingTsv`, `formatListingCurrenciesTsv`, `buildDelistingExportRows` +
|
||||
* `formatDelistingsTsv`) must produce byte-identical TSVs and identical skip stats on the same
|
||||
* seeded random security master, for every chunk size (including exact chunk-boundary sizes).
|
||||
* - Every emitted `delistings.tsv` row must resolve under the exact Rust `curate-corporate-actions`
|
||||
* lookup rules (`cursor.resolve(delist_date) == from_listing_id` for terminal rows,
|
||||
* `resolve_for_listing_on_or_before` + successor `resolve(effective_date)` for OTC rows) against the
|
||||
* emitted `provider_mapping.tsv`, so the exporter never feeds Rust a row it would drop.
|
||||
*/
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
buildDelistingExportRows,
|
||||
CURATE_INPUT_FILES,
|
||||
exportCurateInputs,
|
||||
formatDelistingsTsv,
|
||||
formatListingCurrenciesTsv,
|
||||
formatProviderMappingTsv,
|
||||
type ContinuityExportSourceRow,
|
||||
type ListingDelistingSourceRow,
|
||||
type ProviderMappingExportRow,
|
||||
type SecurityMasterQueryable,
|
||||
type SecurityMasterQueryResult,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
import { compareAscii } from '../../apps/stock/data-pipeline/src/security-master/exchange-pass1';
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
afterEach(async () => {
|
||||
for (const dir of tempDirs.splice(0).reverse()) {
|
||||
await rm(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
async function makeTempDir(): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'curate-inputs-parity-'));
|
||||
tempDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
|
||||
/** mulberry32: small deterministic PRNG so every run sees the same dataset. */
|
||||
function createRng(seed: number): () => number {
|
||||
let state = seed >>> 0;
|
||||
return () => {
|
||||
state = (state + 0x6d2b79f5) >>> 0;
|
||||
let t = state;
|
||||
t = Math.imul(t ^ (t >>> 15), t | 1);
|
||||
t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
|
||||
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
||||
};
|
||||
}
|
||||
|
||||
const DAY_MS = 86_400_000;
|
||||
const EPOCH_2010 = Date.UTC(2010, 0, 1);
|
||||
|
||||
function dayToYmd(day: number): string {
|
||||
return new Date(EPOCH_2010 + day * DAY_MS).toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function ymdToDay(ymd: string): number {
|
||||
return Math.round((Date.parse(`${ymd}T00:00:00Z`) - EPOCH_2010) / DAY_MS);
|
||||
}
|
||||
|
||||
interface DbListing {
|
||||
listing_id: number;
|
||||
currency: string;
|
||||
listed_to: string | null;
|
||||
delist_reason: string | null;
|
||||
terminal_return: string | null;
|
||||
}
|
||||
|
||||
interface DbContinuity {
|
||||
from_listing_id: number;
|
||||
to_listing_id: number;
|
||||
effective_date: string;
|
||||
kind: string;
|
||||
}
|
||||
|
||||
interface DbMapping {
|
||||
source: string;
|
||||
source_id: string;
|
||||
valid_from: string;
|
||||
valid_to: string | null;
|
||||
listing_id: number;
|
||||
}
|
||||
|
||||
interface Dataset {
|
||||
listings: DbListing[];
|
||||
continuities: DbContinuity[];
|
||||
mappings: DbMapping[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds a seeded random security master that satisfies the DB invariants the exporter relies on
|
||||
* (unique PKs, non-overlapping `(source, source_id)` ranges, at most one OTC continuity per
|
||||
* `from_listing_id`), with ticker reuse, OTC chains, terminal returns as PG `numeric::text`,
|
||||
* missing mappings, mappings that end before `listed_to`, and successors starting late.
|
||||
*/
|
||||
function buildRandomDataset(seed: number, listingCount: number): Dataset {
|
||||
const rng = createRng(seed);
|
||||
const pick = <T>(items: readonly T[]): T => items[Math.floor(rng() * items.length)] as T;
|
||||
const listings: DbListing[] = [];
|
||||
const continuities: DbContinuity[] = [];
|
||||
const mappings: DbMapping[] = [];
|
||||
// Per (source, source_id): last occupied end day (null = open-ended) to keep ranges disjoint.
|
||||
const tickerEnds = new Map<string, number | null>();
|
||||
const tickerPool = Array.from(
|
||||
{ length: Math.max(4, Math.floor(listingCount / 3)) },
|
||||
(_, i) => `T${String(i).padStart(3, '0')}${pick(['', '.A', '-B', 'Q'])}`
|
||||
);
|
||||
|
||||
const addMapping = (
|
||||
source: string,
|
||||
listingId: number,
|
||||
fromDay: number,
|
||||
toDay: number | null
|
||||
): boolean => {
|
||||
for (let attempt = 0; attempt < 6; attempt++) {
|
||||
const sourceId = pick(tickerPool);
|
||||
const key = `${source}\u0000${sourceId}`;
|
||||
if (tickerEnds.has(key)) {
|
||||
const end = tickerEnds.get(key);
|
||||
if (end === null || end === undefined || end >= fromDay) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
tickerEnds.set(key, toDay);
|
||||
mappings.push({
|
||||
source,
|
||||
source_id: sourceId,
|
||||
valid_from: dayToYmd(fromDay),
|
||||
valid_to: toDay === null ? null : dayToYmd(toDay),
|
||||
listing_id: listingId,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
// Allocate listing ids with gaps so keyset pagination over non-contiguous ids is exercised.
|
||||
const ids: number[] = [];
|
||||
let nextId = 1;
|
||||
for (let i = 0; i < listingCount; i++) {
|
||||
nextId += 1 + Math.floor(rng() * 3);
|
||||
ids.push(nextId);
|
||||
}
|
||||
|
||||
// Listings are generated in chronological "start" order so reuse can find free tickers.
|
||||
const otcSuccessorIds = new Set<number>();
|
||||
for (let i = 0; i < ids.length; i++) {
|
||||
const listingId = ids[i] as number;
|
||||
if (otcSuccessorIds.has(listingId)) {
|
||||
continue;
|
||||
}
|
||||
const startDay = Math.floor(rng() * 3000);
|
||||
const roll = rng();
|
||||
const currency = pick(['USD', 'USD', 'CAD']);
|
||||
|
||||
if (roll < 0.35) {
|
||||
listings.push({
|
||||
listing_id: listingId,
|
||||
currency,
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
});
|
||||
addMapping('qm', listingId, startDay, null);
|
||||
addMapping('eod', listingId, startDay, null);
|
||||
continue;
|
||||
}
|
||||
|
||||
const endDay = startDay + 30 + Math.floor(rng() * 400);
|
||||
if (roll < 0.55 && i + 1 < ids.length) {
|
||||
// OTC transfer to the next id (successor), possibly ending in a terminal cancellation.
|
||||
const successorId = ids[i + 1] as number;
|
||||
otcSuccessorIds.add(successorId);
|
||||
const gap = Math.floor(rng() * 20);
|
||||
const effectiveDay = endDay + gap;
|
||||
listings.push({
|
||||
listing_id: listingId,
|
||||
currency,
|
||||
listed_to: dayToYmd(endDay),
|
||||
delist_reason: 'moved_to_otc',
|
||||
terminal_return: null,
|
||||
});
|
||||
continuities.push({
|
||||
from_listing_id: listingId,
|
||||
to_listing_id: successorId,
|
||||
effective_date: dayToYmd(effectiveDay),
|
||||
kind: 'otc_delist_transfer',
|
||||
});
|
||||
if (rng() < 0.9) {
|
||||
addMapping('qm', listingId, startDay, endDay);
|
||||
}
|
||||
addMapping('eod', listingId, startDay, endDay);
|
||||
|
||||
const successorEnd = effectiveDay + 50 + Math.floor(rng() * 200);
|
||||
const successorCancelled = rng() < 0.6;
|
||||
listings.push({
|
||||
listing_id: successorId,
|
||||
currency,
|
||||
listed_to: successorCancelled ? dayToYmd(successorEnd) : null,
|
||||
delist_reason: successorCancelled ? 'bankruptcy_cancelled' : 'active',
|
||||
terminal_return: successorCancelled ? '-1.000000' : null,
|
||||
});
|
||||
const successorRoll = rng();
|
||||
if (successorRoll < 0.8) {
|
||||
addMapping('qm', successorId, effectiveDay, successorCancelled ? successorEnd : null);
|
||||
} else if (successorRoll < 0.9) {
|
||||
// Successor mapping starts after effective_date -> missingSuccessorQmMapping.
|
||||
addMapping('qm', successorId, effectiveDay + 3, successorCancelled ? successorEnd : null);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (roll < 0.85) {
|
||||
const terminalReturn = pick([
|
||||
'-0.300000',
|
||||
'-1.000000',
|
||||
'0.000000',
|
||||
'-0.000001',
|
||||
'-0.550000',
|
||||
'-0.123456',
|
||||
]);
|
||||
const missingDate = rng() < 0.08;
|
||||
listings.push({
|
||||
listing_id: listingId,
|
||||
currency,
|
||||
listed_to: missingDate ? null : dayToYmd(endDay),
|
||||
delist_reason: pick(['unknown_involuntary', 'bankruptcy_cancelled', 'merger_cash']),
|
||||
terminal_return: terminalReturn,
|
||||
});
|
||||
const mappingRoll = rng();
|
||||
if (mappingRoll < 0.8) {
|
||||
addMapping('qm', listingId, startDay, endDay);
|
||||
} else if (mappingRoll < 0.9) {
|
||||
// qm mapping ends before listed_to -> not valid on delist_date.
|
||||
addMapping('qm', listingId, startDay, endDay - 5);
|
||||
}
|
||||
addMapping('eod', listingId, startDay, endDay);
|
||||
continue;
|
||||
}
|
||||
|
||||
listings.push({
|
||||
listing_id: listingId,
|
||||
currency,
|
||||
listed_to: dayToYmd(endDay),
|
||||
delist_reason: rng() < 0.5 ? null : 'unknown',
|
||||
terminal_return: null,
|
||||
});
|
||||
addMapping('qm', listingId, startDay, endDay);
|
||||
}
|
||||
|
||||
// Non-OTC continuities must be ignored by the DB query (`WHERE kind = 'otc_delist_transfer'`).
|
||||
continuities.push({
|
||||
from_listing_id: ids[0] as number,
|
||||
to_listing_id: ids[1] as number,
|
||||
effective_date: '2015-01-02',
|
||||
kind: 'ticker_change',
|
||||
});
|
||||
|
||||
return { listings, continuities, mappings };
|
||||
}
|
||||
|
||||
function shuffle<T>(items: readonly T[], rng: () => number): T[] {
|
||||
const out = [...items];
|
||||
for (let i = out.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(rng() * (i + 1));
|
||||
[out[i], out[j]] = [out[j] as T, out[i] as T];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** In-memory PostgreSQL stand-in honouring the exporter's SQL contract (keyset + NO SCROLL cursor). */
|
||||
function createQueryable(data: Dataset, recordedSql: string[]): SecurityMasterQueryable {
|
||||
const otc = data.continuities
|
||||
.filter(c => c.kind === 'otc_delist_transfer')
|
||||
.sort(
|
||||
(a, b) =>
|
||||
a.from_listing_id - b.from_listing_id || compareAscii(a.effective_date, b.effective_date)
|
||||
);
|
||||
const listings = [...data.listings].sort((a, b) => a.listing_id - b.listing_id);
|
||||
const mappings = [...data.mappings].sort(
|
||||
(a, b) =>
|
||||
compareAscii(a.source, b.source) ||
|
||||
compareAscii(a.source_id, b.source_id) ||
|
||||
compareAscii(a.valid_from, b.valid_from)
|
||||
);
|
||||
let cursorOffset = -1;
|
||||
|
||||
return {
|
||||
async query<Row = Record<string, unknown>>(
|
||||
text: string,
|
||||
values?: readonly unknown[]
|
||||
): Promise<SecurityMasterQueryResult<Row>> {
|
||||
const sql = text.replace(/\s+/g, ' ').trim();
|
||||
recordedSql.push(sql);
|
||||
const rows = (r: unknown[]) => ({ rows: r as Row[] });
|
||||
if (sql.startsWith('BEGIN') || sql === 'COMMIT' || sql === 'ROLLBACK') {
|
||||
return rows([]);
|
||||
}
|
||||
if (sql.startsWith('DECLARE ')) {
|
||||
cursorOffset = 0;
|
||||
return rows([]);
|
||||
}
|
||||
const fetch = /^FETCH FORWARD (\d+) FROM \S+$/.exec(sql);
|
||||
if (fetch) {
|
||||
if (cursorOffset < 0) {
|
||||
throw new Error('FETCH without DECLARE');
|
||||
}
|
||||
const slice = mappings.slice(cursorOffset, cursorOffset + Number(fetch[1]));
|
||||
cursorOffset += slice.length;
|
||||
return rows(slice);
|
||||
}
|
||||
if (sql.startsWith('CLOSE ')) {
|
||||
cursorOffset = -1;
|
||||
return rows([]);
|
||||
}
|
||||
if (sql.includes('FROM corporate_action_continuity')) {
|
||||
if (values?.length === 1) {
|
||||
return rows(otc.slice(0, values[0] as number));
|
||||
}
|
||||
const [lastFrom, lastEff, limit] = values as [number, string, number];
|
||||
return rows(
|
||||
otc
|
||||
.filter(
|
||||
c =>
|
||||
c.from_listing_id > lastFrom ||
|
||||
(c.from_listing_id === lastFrom && c.effective_date > lastEff)
|
||||
)
|
||||
.slice(0, limit)
|
||||
);
|
||||
}
|
||||
if (sql.includes('FROM listing')) {
|
||||
if (values?.length === 1) {
|
||||
return rows(listings.slice(0, values[0] as number));
|
||||
}
|
||||
const [lastId, limit] = values as [number, number];
|
||||
return rows(listings.filter(l => l.listing_id > lastId).slice(0, limit));
|
||||
}
|
||||
throw new Error(`Unexpected SQL: ${sql}`);
|
||||
},
|
||||
release: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
function toPure(data: Dataset): {
|
||||
providerMappings: ProviderMappingExportRow[];
|
||||
delistingListings: ListingDelistingSourceRow[];
|
||||
continuities: ContinuityExportSourceRow[];
|
||||
} {
|
||||
return {
|
||||
providerMappings: data.mappings.map(m => ({
|
||||
source: m.source,
|
||||
sourceId: m.source_id,
|
||||
validFrom: m.valid_from,
|
||||
validTo: m.valid_to,
|
||||
listingId: m.listing_id,
|
||||
})),
|
||||
delistingListings: data.listings.map(l => ({
|
||||
listingId: l.listing_id,
|
||||
listedTo: l.listed_to,
|
||||
delistReason: l.delist_reason,
|
||||
terminalReturn: l.terminal_return,
|
||||
})),
|
||||
continuities: data.continuities
|
||||
.filter(c => c.kind === 'otc_delist_transfer')
|
||||
.map(c => ({
|
||||
fromListingId: c.from_listing_id,
|
||||
toListingId: c.to_listing_id,
|
||||
effectiveDate: c.effective_date,
|
||||
kind: c.kind,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
interface RustRange {
|
||||
validFrom: number;
|
||||
validTo: number | null;
|
||||
listingId: number;
|
||||
}
|
||||
|
||||
/** Parses emitted `provider_mapping.tsv` into Rust `ProviderMappingTable` shape (sorted by valid_from). */
|
||||
function parseMappingTable(tsv: string): Map<string, RustRange[]> {
|
||||
const table = new Map<string, RustRange[]>();
|
||||
for (const line of tsv.split('\n')) {
|
||||
if (line.length === 0) {
|
||||
continue;
|
||||
}
|
||||
const [source, sourceId, from, to, listingId] = line.split('\t') as [
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
];
|
||||
const key = `${source}\u0000${sourceId}`;
|
||||
const list = table.get(key) ?? [];
|
||||
list.push({
|
||||
validFrom: ymdToDay(from),
|
||||
validTo: to === '' ? null : ymdToDay(to),
|
||||
listingId: Number(listingId),
|
||||
});
|
||||
table.set(key, list);
|
||||
}
|
||||
for (const list of table.values()) {
|
||||
list.sort((a, b) => a.validFrom - b.validFrom);
|
||||
}
|
||||
return table;
|
||||
}
|
||||
|
||||
/** Mirror of `ProviderMappingTable::resolve` (provider_mapping.rs). */
|
||||
function rustResolve(ranges: readonly RustRange[], day: number): number | null {
|
||||
let idx = 0;
|
||||
while (idx < ranges.length && (ranges[idx] as RustRange).validFrom <= day) {
|
||||
idx += 1;
|
||||
}
|
||||
if (idx === 0) {
|
||||
return null;
|
||||
}
|
||||
const candidate = ranges[idx - 1] as RustRange;
|
||||
return candidate.validTo === null || candidate.validTo >= day ? candidate.listingId : null;
|
||||
}
|
||||
|
||||
/** Mirror of `resolve_for_listing_on_or_before` (curate_corporate_actions.rs). */
|
||||
function rustResolveForListingOnOrBefore(
|
||||
ranges: readonly RustRange[],
|
||||
day: number,
|
||||
expected: number
|
||||
): number | null {
|
||||
for (let i = ranges.length - 1; i >= 0; i--) {
|
||||
const r = ranges[i] as RustRange;
|
||||
if (r.validFrom <= day && r.listingId === expected) {
|
||||
return r.listingId;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async function runExport(data: Dataset, chunkSize: number) {
|
||||
const outDir = await makeTempDir();
|
||||
const recordedSql: string[] = [];
|
||||
const result = await exportCurateInputs(createQueryable(data, recordedSql), {
|
||||
outDir,
|
||||
chunkSize,
|
||||
});
|
||||
const read = (file: string) => readFile(join(outDir, file), 'utf8');
|
||||
return {
|
||||
result,
|
||||
recordedSql,
|
||||
providerMapping: await read(CURATE_INPUT_FILES.providerMapping),
|
||||
listingCurrencies: await read(CURATE_INPUT_FILES.listingCurrencies),
|
||||
delistings: await read(CURATE_INPUT_FILES.delistings),
|
||||
};
|
||||
}
|
||||
|
||||
describe('exportCurateInputs streaming vs pure core parity (seeded random security master)', () => {
|
||||
for (const seed of [11, 4242, 90210]) {
|
||||
test(`seed ${seed}: streamed TSV bytes and skip stats equal the pure formatters for every chunk size`, async () => {
|
||||
// Arrange
|
||||
const data = buildRandomDataset(seed, 160);
|
||||
const pure = toPure(data);
|
||||
const rng = createRng(seed ^ 0x5eed);
|
||||
const expectedProviderMapping = formatProviderMappingTsv(shuffle(pure.providerMappings, rng));
|
||||
const expectedListingCurrencies = formatListingCurrenciesTsv(
|
||||
shuffle(
|
||||
data.listings.map(l => ({ listingId: l.listing_id, currency: l.currency })),
|
||||
rng
|
||||
)
|
||||
);
|
||||
const built = buildDelistingExportRows(
|
||||
shuffle(pure.delistingListings, rng),
|
||||
shuffle(pure.continuities, rng),
|
||||
shuffle(pure.providerMappings, rng)
|
||||
);
|
||||
const expectedDelistings = formatDelistingsTsv(shuffle(built.rows, rng));
|
||||
const mappingRows = data.mappings.length;
|
||||
const listingRows = data.listings.length;
|
||||
|
||||
// Sanity: the generator really exercises every branch, otherwise parity proves little.
|
||||
expect(built.stats.otcTransfersOut).toBeGreaterThan(0);
|
||||
expect(built.stats.terminalDelistingsOut).toBeGreaterThan(0);
|
||||
expect(built.stats.skipped.active).toBeGreaterThan(0);
|
||||
expect(built.stats.skipped.noOutcome).toBeGreaterThan(0);
|
||||
expect(built.stats.skipped.missingOutgoingQmMapping).toBeGreaterThan(0);
|
||||
|
||||
// Act + Assert: chunk sizes include 1, a prime, exact divisors of the row counts, and max.
|
||||
for (const chunkSize of [1, 7, listingRows, mappingRows, 5000]) {
|
||||
const out = await runExport(data, Math.min(chunkSize, 5000));
|
||||
expect(out.providerMapping).toBe(expectedProviderMapping);
|
||||
expect(out.listingCurrencies).toBe(expectedListingCurrencies);
|
||||
expect(out.delistings).toBe(expectedDelistings);
|
||||
|
||||
const s = out.result.delistings.stats;
|
||||
expect(s.rowsOut).toBe(built.stats.rowsOut);
|
||||
expect(s.otcTransfersOut).toBe(built.stats.otcTransfersOut);
|
||||
expect(s.terminalDelistingsOut).toBe(built.stats.terminalDelistingsOut);
|
||||
expect({ ...s.skipped, nonOtcContinuity: 0 }).toEqual({
|
||||
...built.stats.skipped,
|
||||
nonOtcContinuity: 0,
|
||||
});
|
||||
expect(s.skipped.nonOtcContinuity).toBe(0);
|
||||
const skipSum = Object.values(s.skipped).reduce((acc, n) => acc + n, 0);
|
||||
expect(s.skippedTotal).toBe(skipSum);
|
||||
expect(s.rowsIn).toBe(s.rowsOut + s.skippedTotal);
|
||||
// Every non-OTC-transferred listing is accounted for exactly once, plus OTC sources.
|
||||
expect(s.rowsIn).toBe(listingRows);
|
||||
|
||||
expect(out.result.providerMapping.rowsIn).toBe(mappingRows);
|
||||
expect(out.result.providerMapping.rowsOut).toBe(mappingRows);
|
||||
expect(out.result.listingCurrencies.rowsOut).toBe(listingRows);
|
||||
expect(out.result.totalBytesWritten).toBe(
|
||||
Buffer.byteLength(out.providerMapping) +
|
||||
Buffer.byteLength(out.listingCurrencies) +
|
||||
Buffer.byteLength(out.delistings)
|
||||
);
|
||||
|
||||
// Read-only contract: SELECT/cursor statements only, all inside one READ ONLY transaction.
|
||||
expect(out.recordedSql[0]).toBe(
|
||||
'BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY'
|
||||
);
|
||||
expect(out.recordedSql.at(-1)).toBe('COMMIT');
|
||||
for (const sql of out.recordedSql) {
|
||||
expect(sql).not.toMatch(
|
||||
/\b(INSERT|UPDATE|DELETE|TRUNCATE|CREATE|ALTER|DROP|GRANT|COPY)\b/i
|
||||
);
|
||||
}
|
||||
const fetches = out.recordedSql.filter(sql => sql.startsWith('FETCH FORWARD'));
|
||||
expect(fetches.length).toBeGreaterThanOrEqual(
|
||||
Math.ceil(mappingRows / Math.min(chunkSize, 5000))
|
||||
);
|
||||
for (const fetch of fetches) {
|
||||
const n = Number(/FETCH FORWARD (\d+)/.exec(fetch)?.[1]);
|
||||
expect(n).toBeLessThanOrEqual(5000);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test('every emitted delisting resolves under the Rust curate-corporate-actions lookup rules (0 drops)', async () => {
|
||||
for (const seed of [11, 4242, 90210, 7]) {
|
||||
// Arrange
|
||||
const data = buildRandomDataset(seed, 200);
|
||||
|
||||
// Act
|
||||
const out = await runExport(data, 13);
|
||||
const table = parseMappingTable(out.providerMapping);
|
||||
|
||||
// Assert
|
||||
const lines = out.delistings.split('\n').filter(line => line.length > 0);
|
||||
expect(lines.length).toBe(out.result.delistings.rowsOut);
|
||||
for (const line of lines) {
|
||||
const fields = line.split('\t');
|
||||
expect(fields.length).toBe(5);
|
||||
const [sourceId, delistDate, fromListingId, successorSourceId, terminalReturn] = fields as [
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
];
|
||||
const day = ymdToDay(delistDate);
|
||||
const expectedId = Number(fromListingId);
|
||||
expect(Number.isInteger(expectedId) && expectedId > 0).toBe(true);
|
||||
const ranges = table.get(`qm\u0000${sourceId}`) ?? [];
|
||||
|
||||
if (successorSourceId === '') {
|
||||
// Terminal: cursor.resolve(ex_date).filter(id == from_listing_id); terminal_return parses in [-1, 0].
|
||||
expect(rustResolve(ranges, day)).toBe(expectedId);
|
||||
const parsed = Number(terminalReturn);
|
||||
expect(terminalReturn).toMatch(/^-?\d+(\.\d+)?$/);
|
||||
expect(parsed >= -1 && parsed <= 0).toBe(true);
|
||||
const listing = data.listings.find(l => l.listing_id === expectedId);
|
||||
expect(listing?.listed_to).toBe(delistDate);
|
||||
expect(parsed).toBe(Number(listing?.terminal_return));
|
||||
} else {
|
||||
expect(terminalReturn).toBe('');
|
||||
expect(rustResolveForListingOnOrBefore(ranges, day, expectedId)).toBe(expectedId);
|
||||
const successorId = rustResolve(table.get(`qm\u0000${successorSourceId}`) ?? [], day);
|
||||
const continuity = data.continuities.find(
|
||||
c => c.kind === 'otc_delist_transfer' && c.from_listing_id === expectedId
|
||||
);
|
||||
expect(continuity?.effective_date).toBe(delistDate);
|
||||
expect(successorId).toBe(continuity?.to_listing_id ?? -1);
|
||||
expect(successorId).not.toBe(expectedId);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('terminal returns from PostgreSQL numeric::text are normalized to plain decimals Rust parses identically', async () => {
|
||||
// Arrange
|
||||
const data: Dataset = {
|
||||
listings: [
|
||||
{
|
||||
listing_id: 1,
|
||||
currency: 'USD',
|
||||
listed_to: '2023-01-03',
|
||||
delist_reason: 'x',
|
||||
terminal_return: '0.000000',
|
||||
},
|
||||
{
|
||||
listing_id: 2,
|
||||
currency: 'USD',
|
||||
listed_to: '2023-01-03',
|
||||
delist_reason: 'x',
|
||||
terminal_return: '-0.000000',
|
||||
},
|
||||
{
|
||||
listing_id: 3,
|
||||
currency: 'USD',
|
||||
listed_to: '2023-01-03',
|
||||
delist_reason: 'x',
|
||||
terminal_return: '-0.000001',
|
||||
},
|
||||
{
|
||||
listing_id: 4,
|
||||
currency: 'USD',
|
||||
listed_to: '2023-01-03',
|
||||
delist_reason: 'x',
|
||||
terminal_return: '-1.000000',
|
||||
},
|
||||
{
|
||||
listing_id: 5,
|
||||
currency: 'USD',
|
||||
listed_to: '2023-01-03',
|
||||
delist_reason: 'x',
|
||||
terminal_return: '-0.300000',
|
||||
},
|
||||
],
|
||||
continuities: [],
|
||||
mappings: [1, 2, 3, 4, 5].map(id => ({
|
||||
source: 'qm',
|
||||
source_id: `L${id}`,
|
||||
valid_from: '2020-01-01',
|
||||
valid_to: '2023-01-03',
|
||||
listing_id: id,
|
||||
})),
|
||||
};
|
||||
|
||||
// Act
|
||||
const out = await runExport(data, 2);
|
||||
|
||||
// Assert
|
||||
expect(out.delistings).toBe(
|
||||
[
|
||||
'L1\t2023-01-03\t1\t\t0',
|
||||
'L2\t2023-01-03\t2\t\t0',
|
||||
'L3\t2023-01-03\t3\t\t-0.000001',
|
||||
'L4\t2023-01-03\t4\t\t-1',
|
||||
'L5\t2023-01-03\t5\t\t-0.3',
|
||||
'',
|
||||
].join('\n')
|
||||
);
|
||||
});
|
||||
|
||||
test('exact chunk-boundary row counts neither drop nor duplicate the last page', async () => {
|
||||
// Arrange: 4 listings, 4 mappings, 2 OTC continuities with chunkSize 2 (two full pages each).
|
||||
const data: Dataset = {
|
||||
listings: [
|
||||
{
|
||||
listing_id: 10,
|
||||
currency: 'USD',
|
||||
listed_to: '2023-03-10',
|
||||
delist_reason: 'moved_to_otc',
|
||||
terminal_return: null,
|
||||
},
|
||||
{
|
||||
listing_id: 11,
|
||||
currency: 'USD',
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
},
|
||||
{
|
||||
listing_id: 20,
|
||||
currency: 'CAD',
|
||||
listed_to: '2023-03-10',
|
||||
delist_reason: 'moved_to_otc',
|
||||
terminal_return: null,
|
||||
},
|
||||
{
|
||||
listing_id: 21,
|
||||
currency: 'CAD',
|
||||
listed_to: null,
|
||||
delist_reason: 'active',
|
||||
terminal_return: null,
|
||||
},
|
||||
],
|
||||
continuities: [
|
||||
{
|
||||
from_listing_id: 10,
|
||||
to_listing_id: 11,
|
||||
effective_date: '2023-03-28',
|
||||
kind: 'otc_delist_transfer',
|
||||
},
|
||||
{
|
||||
from_listing_id: 20,
|
||||
to_listing_id: 21,
|
||||
effective_date: '2023-03-28',
|
||||
kind: 'otc_delist_transfer',
|
||||
},
|
||||
],
|
||||
mappings: [
|
||||
{
|
||||
source: 'qm',
|
||||
source_id: 'A',
|
||||
valid_from: '2000-01-03',
|
||||
valid_to: '2023-03-10',
|
||||
listing_id: 10,
|
||||
},
|
||||
{ source: 'qm', source_id: 'AQ', valid_from: '2023-03-28', valid_to: null, listing_id: 11 },
|
||||
{
|
||||
source: 'qm',
|
||||
source_id: 'B',
|
||||
valid_from: '2000-01-03',
|
||||
valid_to: '2023-03-10',
|
||||
listing_id: 20,
|
||||
},
|
||||
{ source: 'qm', source_id: 'BQ', valid_from: '2023-03-28', valid_to: null, listing_id: 21 },
|
||||
],
|
||||
};
|
||||
|
||||
// Act
|
||||
const out = await runExport(data, 2);
|
||||
|
||||
// Assert
|
||||
expect(out.listingCurrencies).toBe('10\tUSD\n11\tUSD\n20\tCAD\n21\tCAD\n');
|
||||
expect(out.providerMapping).toBe(
|
||||
'qm\tA\t2000-01-03\t2023-03-10\t10\nqm\tAQ\t2023-03-28\t\t11\nqm\tB\t2000-01-03\t2023-03-10\t20\nqm\tBQ\t2023-03-28\t\t21\n'
|
||||
);
|
||||
expect(out.delistings).toBe('A\t2023-03-28\t10\tAQ\t\nB\t2023-03-28\t20\tBQ\t\n');
|
||||
expect(out.result.delistings.stats.rowsIn).toBe(4);
|
||||
expect(out.result.delistings.stats.skipped.active).toBe(2);
|
||||
});
|
||||
});
|
||||
1619
test/unit/security-master-export-curate-inputs.test.ts
Normal file
1619
test/unit/security-master-export-curate-inputs.test.ts
Normal file
File diff suppressed because it is too large
Load diff
288
test/unit/security-master-m1-gate-denominator.test.ts
Normal file
288
test/unit/security-master-m1-gate-denominator.test.ts
Normal file
|
|
@ -0,0 +1,288 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
buildMatchReport,
|
||||
composeSecurityMasterRun,
|
||||
matchListingsStageB,
|
||||
renderMatchReportMarkdown,
|
||||
sourceCountryKey,
|
||||
type StageBInput,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
import { SYNTHETIC_EOD_ISIN_PREFIX } from '../../apps/stock/data-pipeline/src/security-master/instrument-stage-a';
|
||||
import type { GateOutOfScopeReason } from '../../apps/stock/data-pipeline/src/security-master/match-report';
|
||||
|
||||
describe('M1 security-master IB disambiguation, CEO crawl-only fallback, and gate denominator', () => {
|
||||
test('enableIbTickerDisambiguation resolves ambiguous active/delisted listings and links identifier-less & reverse-split EOD listings', () => {
|
||||
const input: StageBInput = {
|
||||
instruments: [
|
||||
{
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc',
|
||||
members: [
|
||||
{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' },
|
||||
{ source: 'eod', sourceId: 'AAPL_OLD.US', currency: 'USD', method: 'tier1_isin' },
|
||||
{ source: 'ib', sourceId: '265598', currency: 'USD', method: 'tier1_isin' },
|
||||
],
|
||||
},
|
||||
{
|
||||
primaryIsin: `${SYNTHETIC_EOD_ISIN_PREFIX}NOISIN.US`,
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'No ISIN EOD Corp',
|
||||
members: [
|
||||
{
|
||||
source: 'eod',
|
||||
sourceId: 'NOISIN.US',
|
||||
currency: 'USD',
|
||||
method: 'tier3_ticker_span',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US9999991009',
|
||||
primaryCusip: '999999100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'No ISIN EOD Corp',
|
||||
members: [{ source: 'ib', sourceId: '999001', currency: 'USD', method: 'tier1_isin' }],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US00091F1066',
|
||||
primaryCusip: '00091F106',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'ABVC Biopharma Pre-Split',
|
||||
members: [{ source: 'eod', sourceId: 'ABVC.US', currency: 'USD', method: 'tier1_isin' }],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'US00091F3047',
|
||||
primaryCusip: '00091F304',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'ABVC Biopharma Post-Reverse-Split',
|
||||
members: [{ source: 'ib', sourceId: '555001', currency: 'USD', method: 'tier1_isin' }],
|
||||
},
|
||||
],
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'AAPL.US',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2005-01-03', lastBarDate: '2025-08-13' },
|
||||
},
|
||||
{
|
||||
sourceId: 'AAPL_OLD.US',
|
||||
ticker: 'AAPLOLD',
|
||||
mic: 'OTCM',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2000-01-03', lastBarDate: '2010-01-04' },
|
||||
},
|
||||
{
|
||||
sourceId: 'NOISIN.US',
|
||||
ticker: 'NOISIN',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-08-13' },
|
||||
},
|
||||
{
|
||||
sourceId: 'ABVC.US',
|
||||
ticker: 'ABVC',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2018-01-02', lastBarDate: '2025-08-13' },
|
||||
},
|
||||
],
|
||||
ibContracts: [
|
||||
{ sourceId: '265598', conid: 265598, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'AAPL' },
|
||||
{ sourceId: '999001', conid: 999001, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'NOISIN' },
|
||||
{ sourceId: '555001', conid: 555001, currency: 'USD', primaryExchange: 'NASDAQ', ticker: 'ABVC' },
|
||||
],
|
||||
tickerSources: [],
|
||||
};
|
||||
|
||||
const res = matchListingsStageB(input, { enableIbTickerDisambiguation: true });
|
||||
expect(res.conflicts).toEqual([]);
|
||||
expect(res.stats.bySource.ib.matched).toBe(3);
|
||||
expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '265598')?.listingKey.mic).toBe('XNAS');
|
||||
expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '999001')?.listingKey.tickerRoot).toBe('NOISIN');
|
||||
expect(res.providerMappings.find(m => m.source === 'ib' && m.sourceId === '555001')?.listingKey.tickerRoot).toBe('ABVC');
|
||||
});
|
||||
|
||||
test('allowUniqueTickerFallbackForCrawlOnlyCeo links unique delisted listing but never links reused tickers', () => {
|
||||
const input: StageBInput = {
|
||||
instruments: [
|
||||
{
|
||||
primaryIsin: 'CA1111111111',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'CA',
|
||||
canonicalName: 'Unique Delisted TSX',
|
||||
members: [{ source: 'eod', sourceId: 'DELIST.TO', currency: 'CAD', method: 'tier1_isin' }],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'CA2222222222',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'CA',
|
||||
canonicalName: 'Reused Ticker Old',
|
||||
members: [{ source: 'eod', sourceId: 'REUSE_OLD.TO', currency: 'CAD', method: 'tier1_isin' }],
|
||||
},
|
||||
{
|
||||
primaryIsin: 'CA3333333333',
|
||||
primaryCusip: null,
|
||||
issuerCountry: 'CA',
|
||||
canonicalName: 'Reused Ticker New',
|
||||
members: [{ source: 'eod', sourceId: 'REUSE_NEW.TO', currency: 'CAD', method: 'tier1_isin' }],
|
||||
},
|
||||
],
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'DELIST.TO',
|
||||
ticker: 'DELIST',
|
||||
mic: 'XTSE',
|
||||
role: 'primary_venue',
|
||||
currency: 'CAD',
|
||||
span: { firstBarDate: '2012-01-03', lastBarDate: '2021-06-30' },
|
||||
},
|
||||
{
|
||||
sourceId: 'REUSE_OLD.TO',
|
||||
ticker: 'REUSE',
|
||||
mic: 'XTSE',
|
||||
role: 'primary_venue',
|
||||
currency: 'CAD',
|
||||
span: { firstBarDate: '2010-01-04', lastBarDate: '2018-12-31' },
|
||||
},
|
||||
{
|
||||
sourceId: 'REUSE_NEW.TO',
|
||||
ticker: 'REUSE',
|
||||
mic: 'XTSE',
|
||||
role: 'primary_venue',
|
||||
currency: 'CAD',
|
||||
span: { firstBarDate: '2020-01-02', lastBarDate: '2023-12-29' },
|
||||
},
|
||||
],
|
||||
ibContracts: [],
|
||||
tickerSources: [
|
||||
{
|
||||
source: 'ceo',
|
||||
sourceId: 'ceo:delist',
|
||||
ticker: 'DELIST',
|
||||
mic: 'XTSE',
|
||||
role: 'primary_venue',
|
||||
currency: 'CAD',
|
||||
span: { firstBarDate: '2025-07-01', lastBarDate: '2025-07-01' },
|
||||
},
|
||||
{
|
||||
source: 'ceo',
|
||||
sourceId: 'ceo:reuse',
|
||||
ticker: 'REUSE',
|
||||
mic: 'XTSE',
|
||||
role: 'primary_venue',
|
||||
currency: 'CAD',
|
||||
span: { firstBarDate: '2025-07-01', lastBarDate: '2025-07-01' },
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const res = matchListingsStageB(input, { allowUniqueTickerFallbackForCrawlOnlyCeo: true });
|
||||
expect(res.providerMappings.filter(m => m.source === 'ceo' && m.sourceId === 'ceo:delist')).toHaveLength(1);
|
||||
expect(res.unresolved.find(u => u.source === 'ceo' && u.sourceId === 'ceo:reuse')?.reason).toBe('no_span_overlap');
|
||||
});
|
||||
|
||||
test('buildMatchReport and composeSecurityMasterRun transparently itemize Out of Gate Scope without hiding raw totals', () => {
|
||||
const stageB = matchListingsStageB({
|
||||
instruments: [
|
||||
{
|
||||
primaryIsin: 'US0378331005',
|
||||
primaryCusip: '037833100',
|
||||
issuerCountry: 'US',
|
||||
canonicalName: 'Apple Inc',
|
||||
members: [{ source: 'eod', sourceId: 'AAPL.US', currency: 'USD', method: 'tier1_isin' }],
|
||||
},
|
||||
],
|
||||
eodListings: [
|
||||
{
|
||||
sourceId: 'AAPL.US',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2020-01-02', lastBarDate: '2025-08-13' },
|
||||
},
|
||||
],
|
||||
ibContracts: [],
|
||||
tickerSources: [
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'AAPL',
|
||||
ticker: 'AAPL',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: { firstBarDate: '2021-01-04', lastBarDate: '2025-08-13' },
|
||||
},
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'GHOST',
|
||||
ticker: 'GHOST',
|
||||
mic: 'XNAS',
|
||||
role: 'primary_venue',
|
||||
currency: 'USD',
|
||||
span: null,
|
||||
},
|
||||
{
|
||||
source: 'qm',
|
||||
sourceId: 'CSE1:CA',
|
||||
ticker: 'CSE1',
|
||||
mic: 'XCNQ',
|
||||
role: 'primary_venue',
|
||||
currency: 'CAD',
|
||||
span: { firstBarDate: '2021-01-04', lastBarDate: '2025-08-13' },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const gateOutOfScope = new Map<string, GateOutOfScopeReason>([
|
||||
[sourceCountryKey('qm', 'GHOST'), 'zero_bar_catalog_ghost'],
|
||||
[sourceCountryKey('qm', 'CSE1:CA'), 'uncovered_venue'],
|
||||
]);
|
||||
|
||||
const report = buildMatchReport({
|
||||
stageA: {
|
||||
instruments: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalRecords: 1,
|
||||
totalInstruments: 1,
|
||||
bySource: {
|
||||
eod: { total: 1, tier1Isin: 1, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
},
|
||||
},
|
||||
},
|
||||
stageB,
|
||||
gateOutOfScope,
|
||||
gateDenominatorNote: 'Custom test gate note.',
|
||||
});
|
||||
|
||||
const qmRow = report.resolutionBySource.find(r => r.source === 'qm');
|
||||
expect(qmRow?.total).toBe(3);
|
||||
expect(qmRow?.matched).toBe(1);
|
||||
expect(qmRow?.outOfGateScope).toBe(2);
|
||||
expect(qmRow?.eligibleTotal).toBe(1);
|
||||
expect(qmRow?.eligibleResolvedPct).toBe(1);
|
||||
expect(report.meetsExitThresholds.equitiesResolved95).toBe(true);
|
||||
|
||||
const md = renderMatchReportMarkdown(report);
|
||||
expect(md).toContain('## Gate Denominator Definition');
|
||||
expect(md).toContain('Out of Gate Scope');
|
||||
expect(md).toContain('## Out-of-Gate-Scope Breakdown');
|
||||
expect(md).toContain('| qm | zero_bar_catalog_ghost | 1 |');
|
||||
expect(md).toContain('| qm | uncovered_venue | 1 |');
|
||||
|
||||
// Ensure composeSecurityMasterRun default without applyUsCaEquityGateDenominator remains unchanged
|
||||
expect(typeof composeSecurityMasterRun).toBe('function');
|
||||
});
|
||||
});
|
||||
|
|
@ -7,5 +7,7 @@ license.workspace = true
|
|||
|
||||
[dependencies]
|
||||
bson = { version = "=3.1.0", default-features = false, features = ["compat-3-0-0"] }
|
||||
mongodb = { version = "=3.10.2", default-features = false, features = ["compat-3-3-0", "bson-3", "sync", "rustls-tls", "dns-resolver"] }
|
||||
parquet = { version = "=60.2.0", default-features = false, features = ["zstd"] }
|
||||
rayon = "=1.12.0"
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
# `curate-etl`
|
||||
|
||||
Dedicated Rust crate (two exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]` and `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, and the `M1.2o` zero-copy raw BSON decoder for `eodPrices`.
|
||||
Dedicated Rust crate (three exact-pinned direct dependencies: `bson` `=3.1.0` with `default-features = false, features = ["compat-3-0-0"]`, `parquet` `=60.2.0` with `default-features = false, features = ["zstd"]`, and `rayon` `=1.12.0`) for the `M1.2a` split-factor lookup table / bar un-adjustment core, the `M1.2b` pure `adj_factors` builder, the `M1.2c` pure `corporate_actions` event-log builder, the `M1.2d` pure `bars_1d` daily bar builder + `qmPrices.sharevolume` cross-check, the `M1.2e` pure `fx_1d` USD/CAD builder + carry-forward lookup, the `M1.2f` pure `shorts` (`ceoShorts`) point-in-time builder + Canadian TSX business-day / `America/Toronto` DST calendar, the `M1.2g` pure `events` (`qmFilings` + `qmEarnings`) point-in-time builder, the `M1.2h` pure in-RAM `provider_mapping` `(source, source_id, bar_date) -> listing_id` lookup table, the `M1.2i` streaming Zstd Parquet writer for `bars_1d`, the `M1.2j` streaming Zstd Parquet writer for `shorts`, the `M1.2k` streaming Zstd Parquet writer for `events`, the `M1.2l` streaming Zstd Parquet writer for `fx_1d`, the `M1.2m` streaming Zstd Parquet writer for `adj_factors`, the `M1.2n` streaming Zstd Parquet writer for `corporate_actions`, the `M1.2o` zero-copy raw BSON decoder for `eodPrices`, the `M1.2w` zero-copy raw BSON decoders for `qmSplits` and `qmDividends`, the `M1.2y` bounded-memory streaming reader for concatenated raw BSON (`bson_stream`), the `M1.2ad` `ceoShorts` decoder + `curate-shorts` command, the `M1.2ae` `qmFilings` / `qmEarnings` decoders + `curate-events` command, the `M1.2ah` zero-copy `qmPrices` decoder + optional `--qm-prices` volume cross-check in `curate-bars-1d`, the `M1.2ai` `rayon` year-sharded parallel Zstd Parquet writer (`--threads`) for `curate-bars-1d`, the `M1.2ak` read-only MongoDB URI safety guard (`mongo_safety`), and the `M1.2al` driver-independent read-only MongoDB raw-BSON cursor seam (`mongo_stream`).
|
||||
|
||||
## Scope & Sign Conventions
|
||||
|
||||
|
|
@ -158,7 +158,7 @@ Rules:
|
|||
- Exact duplicate filings collapse (`filings_duplicate_collapsed`); identical normalized `(key, report_date)` earnings collapse (`earnings_duplicate_collapsed`) and conflicting `(key, report_date)` groups drop entirely (`earnings_duplicate_conflict_dropped`).
|
||||
- Output rows are sorted deterministically by `(key, ts_micros, kind, subtype, payload_json, known_at_micros, known_at_source)` and `EventsStats` reconciles exactly per kind (`filings_in == filings_out + skips + dup`, `earnings_in == earnings_out + oor + dup + conflict`, `earnings_out == linked + lagged`, `rows_out == filings_out + earnings_out`).
|
||||
|
||||
Deferred out of `src/events.rs`: MongoDB `qmFilings` / `qmEarnings` BSON cursors, `provider_mapping` `listing_id` resolution, Zstd Parquet writing, and M2 `fundamentals_pit` joins.
|
||||
Deferred out of `src/events.rs`: live MongoDB `qmFilings` / `qmEarnings` cursors and M2 `fundamentals_pit` joins (concatenated-BSON decoding, `provider_mapping` resolution, and Zstd Parquet publishing are wired in `src/bson_qm_events.rs` + `src/run_curate_events.rs`).
|
||||
|
||||
## `provider_mapping` Table (`M1.2h`)
|
||||
|
||||
|
|
@ -192,13 +192,17 @@ Rules:
|
|||
- Writes `<out_dir>/bars_1d/year=YYYY/part.parquet` lazily per observed `session_date` calendar year (`1900..=2200`); empty input and empty years create no directories or files.
|
||||
- Zstd compression on every column chunk (`DEFAULT_ZSTD_LEVEL = 3`, configurable via `Bars1dWriteOptions::zstd_level`).
|
||||
- Bounded streaming buffers (`DEFAULT_ROW_GROUP_ROWS = 1_000_000`, configurable via `Bars1dWriteOptions::row_group_rows`): each active year buffers at most one row group of columnar data (with string interning for `currency`/`source`), flushing and clearing buffers on every row-group boundary.
|
||||
- Deterministic `created_by` metadata so identical inputs produce byte-identical `part.parquet` files.
|
||||
- **Year-sharded `rayon` parallel write (`M1.2ai`):** configurable via `Bars1dWriteOptions::threads` (`DEFAULT_WRITE_THREADS = 1` in `Bars1dWriteOptions::default()` to keep bounded streaming memory for library callers; `default_parallel_threads()` returns `std::thread::available_parallelism()`, falling back to `1`). When `threads == 1`, runs the unchanged single-pass streaming path. When `threads > 1`, runs one sequential validation + order-preserving year-bucketing pass, encodes and Zstd-compresses each `year=YYYY` staging file on a local `rayon::ThreadPool` sized to `threads.min(years).max(1)` (never the global pool), catches worker panics (`WorkerPanicked`), sorts outcomes by ascending year (returning the lowest failing year's error deterministically on failure after unlinking only this run's staging files), and publishes sequentially in ascending year order.
|
||||
- **Byte-identical determinism guarantee:** identical inputs produce byte-for-byte identical `bars_1d/year=YYYY/part.parquet` files regardless of `threads` (same row order per year, same `row_group_rows` flush boundaries, same schema, dictionary interning order, and `created_by` metadata).
|
||||
3. **Sort, concurrency & atomicity rules:**
|
||||
- Input must already be sorted strictly ascending by `(listing_id, session_date)`; within each year file rows remain in `(listing_id, session_date)` order.
|
||||
- Concurrent writers targeting the same `<out_dir>/bars_1d` directory are serialized via an in-process per-dataset mutex and a bounded-wait exclusive `.write.lock` file (30 s default timeout returning `ParquetBarsError::LockTimeout` with the lock path if a crashed process left a stale lock behind). Every year partition writes to an exclusively created per-run staging file (`part.parquet.<run>.tmp`), flushes, and calls `File::sync_all()` before publication. During publication, pre-existing `part.parquet` files are backed up in place (hard link with exclusive copy fallback) so the live path remains readable until replaced by a single atomic `rename`; on any error, all open writers are dropped, replaced partitions are restored from backup, newly published partitions are removed (reporting any rollback failures alongside the original error via `RollbackFailed`), and only staging files owned by the current run are unlinked.
|
||||
4. **Typed errors (`ParquetBarsError`):**
|
||||
- `InvalidRowGroupRows` (`row_group_rows == 0`)
|
||||
- `InvalidZstdLevel { level }`
|
||||
- `InvalidThreads` (`threads == 0`)
|
||||
- `ThreadPoolBuild { threads, detail }`
|
||||
- `WorkerPanicked { year, detail }`
|
||||
- `UnsortedInput { prev_listing_id, prev_session_date, listing_id, session_date }`
|
||||
- `DuplicateKey { listing_id, session_date }`
|
||||
- `SessionYearOutOfRange { listing_id, session_date, year, min_year, max_year }`
|
||||
|
|
@ -453,7 +457,29 @@ Rules:
|
|||
- `iter_raw_bson_docs` walks concatenated 4-byte little-endian length-prefixed BSON documents (wire / `mongodump` layout), terminating cleanly on unrecoverable framing errors (`TruncatedDocument`, `CorruptDocumentLength`) while skipping validly framed corrupt documents (`CorruptBson`).
|
||||
- `decode_eod_price_buffer` reports and skips per-document errors without aborting the stream, reconciling `BsonEodDecodeStats` with `decoded + rejected_total() == docs_in`.
|
||||
5. **Deferred out of `M1.2o`:**
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, end-to-end `curate bars_1d` CLI command, and decoders for other collections (`qmPrices`, `qmSplits`, `qmDividends`, `ceoShorts`, `qmFilings`, `qmEarnings`, `eodIntraday1M`).
|
||||
- MongoDB driver (`mongodb` crate) read-only cursor streaming, `rayon` parallel sharding, `provider_mapping` PostgreSQL preload wiring, and decoders for remaining collections (`eodIntraday1M`). (`qmSplits`/`qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, and `qmFilings`/`qmEarnings` decoders are now implemented alongside all six M1 `curate-*` file-to-Parquet commands.)
|
||||
|
||||
## `qmSplits` / `qmDividends` Raw BSON Decoders (`M1.2w`)
|
||||
|
||||
`decode_qm_split_doc`, `decode_qm_split_bytes`, `decode_qm_split_buffer`, `decode_qm_dividend_doc`, `decode_qm_dividend_bytes`, and `decode_qm_dividend_buffer` (`src/bson_qm_actions.rs`) decode raw MongoDB `qmSplits` and `qmDividends` BSON documents in a single forward pass over `RawDocument::iter_elements()` into borrowed `RawQmSplit<'a>` and `RawQmDividend<'a>` views without allocating a `String` or `bson::Document` per row, reusing `bson_eod_prices::iter_raw_bson_docs` for concatenated length-prefixed buffers.
|
||||
|
||||
1. **Field contract & cited in-repo sources:**
|
||||
- `qmSearchCode` (`FIELD_QM_SEARCH_CODE`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:98,118`.
|
||||
- `date` (`FIELD_DATE`): strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via `split::ymd_to_epoch_days`) or BSON `DateTime` (UTC epoch day via `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check so pre-1970 timestamps floor accurately). Cited: `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:99,119`, `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `declared` (`FIELD_DECLARED`, optional): absent, BSON `Null`, or empty/whitespace-only `String` maps to `None`; strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`; malformed strings/out-of-range `DateTime` return `MalformedDate { field: "declared" }` and other types return `WrongType { field: "declared", .. }`. Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `splitratio` (`FIELD_SPLIT_RATIO`), `forfactor` (`FIELD_FOR_FACTOR`), `tofactor` (`FIELD_TO_FACTOR`): BSON `Double`, `Int32`, or `Int64`; `splitratio` must be finite and `> 0.0`. Empirically across all `18,751` live `qmSplits` documents (`16,892/16,892` with numeric `forfactor`/`tofactor`), QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares` (e.g., `0.1` for NVDA's `2024-06-10` 10:1 forward split; `8` for GE's `2021-08-02` 1:8 reverse split). `decode_qm_split_doc` converts to canonical `new_shares / old_shares` via exact `tofactor / forfactor` when both are positive numbers (avoiding 6-decimal truncation like `0.142857` for 7:1), or `1.0 / splitratio` otherwise. `ratio == 1.0` no-ops are **decoded, not dropped** here (downstream builders drop them) and counted in `BsonQmActionDecodeStats::split_noop_ratio_one` (a subset of `decoded`, never added to `rejected_total()`). Cited: `design/DATA-CONTRACTS.md` §1 (line 25).
|
||||
- `usdFxRate` (`FIELD_USD_FX_RATE`): explicitly ignored without calling `elem.value()` per `design/DATA-CONTRACTS.md` §1 (line 25: bogus `usdFxRate: 1` on CAD dividend rows). All other unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, nested objects/arrays) are likewise skipped without decoding.
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0` (`-0.0` normalized to `+0.0`). See **Unverified field names** below.
|
||||
- `currency` (`FIELD_DIVIDEND_CURRENCY`): BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only is rejected). See **Unverified field names** below.
|
||||
2. **Zero-allocation key mapping & builder conversions:**
|
||||
- `RawQmSplit::to_split_event` → `SplitEvent`, `to_split_action_event` → `SplitActionEvent`; `RawQmDividend::to_dividend_event` → `DividendEvent`, `to_dividend_action_event` → `DividendActionEvent`.
|
||||
- `try_map_key(|code, ex_date| ...)` and `try_into_*` helpers mirror `RawEodDailyBar::try_into_eod_daily_bar` so callers can resolve `("qm", qmSearchCode, ex_date)` through `ProviderMappingTable` before allocating `currency` on dividends.
|
||||
3. **Typed errors & stream accounting policy:**
|
||||
- Never panics on untrusted input. `BsonQmActionError` names the offending field on every field-level error (`MissingField`, `EmptyField`, `WrongType`, `MalformedDate`, `InvalidNumber`, plus framing variants `TruncatedDocument`, `CorruptDocumentLength`, `CorruptBson`).
|
||||
- Buffer decoders report and skip per-document errors without aborting the stream, always reconciling `decoded + rejected_total() == docs_in`.
|
||||
4. **Unverified field names:**
|
||||
- `amount` (`FIELD_DIVIDEND_CASH`) and `currency` (`FIELD_DIVIDEND_CURRENCY`) could not be proven from any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped and `design/DATA-CONTRACTS.md` names only `date`, `declared`, and `usdFxRate` for `qmDividends`). Both are isolated in single `pub const` constants so the live MongoDB cursor task can confirm or adjust them in one place before touching QA data.
|
||||
- Numeric strings (e.g. `"10.0"`, `"1.42"`) are currently rejected as `WrongType` because no in-repo source proves QuoteMedia sends `splitratio` or dividend cash as strings; live schema inspection should confirm whether string coercion is needed.
|
||||
|
||||
## Local Benchmarks
|
||||
|
||||
|
|
@ -669,6 +695,54 @@ Command (`2026-11-28`, two back-to-back runs with identical checksum `0x05af9d27
|
|||
- Run 2: `elapsed=217.38 ms`, `throughput=4600307 rows/s`, `scan=1253.15 MB/s`, `latency=217.38 ns/row`, `checksum=0x05af9d2746d1b5e3`
|
||||
- Extrapolation to full `846,000,000` `eodPrices` documents on one core (decode-only, excluding MongoDB cursor I/O and Parquet writes): `183.9 s`–`187.7 s` (`3.07`–`3.13 min`).
|
||||
|
||||
### `bench-bson-qm-actions`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) zero-copy raw BSON decode benchmark over `1,000,000` realistic synthetic QuoteMedia corporate-action documents (~4% `qmSplits`, ~96% `qmDividends`, with extra metadata `_id`, `symbol`, `exchange`, `reportDate`, `created_at`, `updated_at`, bogus `usdFxRate: 1`, `declared` present/missing/`Null`, ~5% BSON `DateTime` dates, mixed `Double`/`Int32`/`Int64` numerics, ~1.5% `splitratio == 1` no-ops, and ~0.5% deterministic rejected rows) pre-encoded into two contiguous length-prefixed buffers up front, timing decode-only via `decode_qm_split_buffer` and `decode_qm_dividend_buffer`:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-qm-actions [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x6d48cd59e46dc9dc`): `cargo run --release -p curate-etl --offline -- bench-bson-qm-actions`
|
||||
|
||||
- Input: `rows=1000000`, `splits=40146`, `dividends=959854`, `bytes=236043886` (~225.1 MiB, ~236.0 bytes/doc)
|
||||
- Splits: `decoded=39937`, `noop_ratio_one=616`, `rejected=209` (`missing=93`, `empty=0`, `wrong_type=45`, `malformed_date=38`, `invalid_number=33`, `corrupt=0`)
|
||||
- Dividends: `decoded=954952`, `rejected=4902` (`missing=1952`, `empty=0`, `wrong_type=1009`, `malformed_date=946`, `invalid_number=995`, `corrupt=0`)
|
||||
- Run 1: `elapsed=275.12 ms`, `throughput=3634828 docs/s`, `scan=818.23 MB/s`, `latency=275.12 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
- Run 2: `elapsed=282.92 ms`, `throughput=3534598 docs/s`, `scan=795.67 MB/s`, `latency=282.92 ns/doc`, `checksum=0x6d48cd59e46dc9dc`
|
||||
|
||||
## Raw BSON Streaming Reader (`bson_stream`, `M1.2y`)
|
||||
|
||||
`RawBsonChunkReader<R: std::io::Read>` (`src/bson_stream.rs`) frames arbitrary concatenated length-prefixed raw BSON streams (files, stdin pipes, or future cursor adapters) into whole-document [`RawBsonChunk`] slices using a single reused buffer, feeding the existing zero-copy decoders (`decode_eod_price_buffer`, `decode_qm_split_buffer`, `decode_qm_dividend_buffer`) unchanged without requiring the full dataset to fit in memory.
|
||||
|
||||
1. **Bounded memory & exact growth:**
|
||||
- Defaults: `DEFAULT_CHUNK_CAPACITY_BYTES = 8 MiB`, `DEFAULT_MAX_DOC_BYTES = 16 MiB + 16 KiB` (MongoDB max document size plus headroom). `BsonStreamOptions::validate` rejects `chunk_capacity_bytes == 0` (`InvalidChunkCapacity`) and `max_doc_bytes < 5` (`InvalidMaxDocBytes`).
|
||||
- Reuses one internal `Vec<u8>` buffer across chunks, compacting any trailing partial document to the front via `copy_within`. Grows only via `reserve_exact` + `resize` when a single document exceeds the current buffer length (or to 4 bytes when `chunk_capacity_bytes < 4`), and never beyond `max_doc_bytes`. `buffer_capacity()` exposes the current allocation ceiling.
|
||||
- Retries `ErrorKind::Interrupted` transparently and handles arbitrary short reads down to 1 byte at a time.
|
||||
2. **Error semantics & sticky terminal state:**
|
||||
- Complete prefix documents already buffered are always yielded before surfacing a trailing framing or I/O error.
|
||||
- Terminal errors carry the absolute byte `offset: u64` of the offending document: declared length `< 5` or `> max_doc_bytes` → `CorruptDocumentLength`; EOF mid-header or mid-document → `TruncatedDocument`; underlying read error → `Io`. After any terminal error, subsequent `next_chunk()` calls keep returning an error without panicking, looping, or re-reading the underlying source.
|
||||
3. **Streaming decode helpers (`for<'a>` callbacks):**
|
||||
- `decode_eod_price_stream` / `decode_eod_price_chunks` → `Result<BsonEodDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_split_stream` / `decode_qm_split_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- `decode_qm_dividend_stream` / `decode_qm_dividend_chunks` → `Result<BsonQmActionDecodeStats, BsonStreamError>`
|
||||
- Because borrowed zero-copy views (`RawEodDailyBar<'a>`, `RawQmSplit<'a>`, `RawQmDividend<'a>`) borrow from the reused chunk buffer, callbacks are higher-ranked (`for<'a> FnMut(...)`). Per-document decode errors are skipped and reported with absolute `u64` stream offsets (rebasing embedded `offset` fields on `CorruptBson` errors), and chunk stats sum via `AddAssign` so `decoded + rejected_total() == docs_in` holds across the entire stream.
|
||||
|
||||
### `bench-bson-stream`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) streaming vs in-memory buffer decode benchmark over `2,000,000` synthetic `eodPrices` documents (reusing the exact `bench-bson-eod-prices` generator), decoding once via `decode_eod_price_buffer` and once via `RawBsonChunkReader` + `decode_eod_price_chunks` over an irregular short-read adapter (`257 B`..`128 KiB` prime steps straddling document and 4-byte header boundaries), asserting identical stats and checksum:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-bson-stream [rows]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`): `cargo run --release -p curate-etl --offline -- bench-bson-stream`
|
||||
|
||||
- Input: `rows=2000000`, `bytes=571280190` (~544.8 MiB)
|
||||
- Decode: `decoded=1989987`, `rejected=10013` (`missing=3964`, `empty=0`, `wrong_type=2033`, `malformed_date=2027`, `invalid_number=1989`, `corrupt=0`), `checksum=0x94f87c60c9d3fbc6`
|
||||
- Buffer baseline: `elapsed=524.54 ms`, `throughput=3812856 rows/s`, `scan=1038.65 MiB/s`
|
||||
- Streamed short-read: `elapsed=544.59 ms`, `throughput=3672494 rows/s`, `scan=1000.42 MiB/s`, `ratio=0.963x`, `peak_buffer_capacity=8388608 bytes` (8 MiB)
|
||||
|
||||
## Deferred Follow-Ups (`M1.3+` / `M2`)
|
||||
|
||||
This crate currently depends only on `bson` (`=3.1.0`, `default-features = false, features = ["compat-3-0-0"]`) and `parquet` (`=60.2.0`, Zstd-only, no Arrow/async) so all tests and benchmarks run strictly offline. Follow-up tasks will add:
|
||||
|
|
@ -841,3 +915,649 @@ cargo run --release -p curate-etl --offline -- bench-curate-fx [rows]
|
|||
- Parquet write: `files=1`, `row_groups=1`, `bytes=27440094`, `read_back_rows=859916`, `elapsed=215.804 ms`, `throughput=3984706 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=275.456 ms`, `throughput=3630342 rows/s`
|
||||
- Overlap: `te_superseded=103169`, `checked=103169`, `within_tol=97958`, `mismatched=5211`, `max_overlap_rel=0.025000`
|
||||
|
||||
## `adj_factors` Curation Stage (`M1.2v`)
|
||||
|
||||
`curate_adj_factors`, `curate_adj_factors_as_of`, `curate_and_write_adj_factors`, `curate_and_write_adj_factors_as_of`, `read_adj_factors_dataset`, `read_adj_factors_dataset_as_of`, and `adj_factors_for_bar` (`src/curate_adj.rs`) join `ProviderMappingTable`, `build_adj_factors`, `session_close::et_session_close_utc_micros`, and `write_adj_factors_dataset` into contract `AdjFactorsParquetRow` records sorted and unique by `(listing_id, ex_date)`.
|
||||
|
||||
1. **Map-before-build rule:**
|
||||
- Resolves every source-keyed `qmSplits` and `qmDividends` event via `(mapping_source, source_key, ex_date) -> listing_id: i32` (using a cached per-key `ProviderMappingCursor`) *before* invoking `build_adj_factors::<i32, _, _>` unchanged.
|
||||
- Cumulative factors (`cum_split_factor`, `cum_total_factor`) therefore chain continuously per permanent `listing_id` across ticker renames (two adjacent source-key ranges mapping to one `listing_id`), while ticker reuse across distinct `listing_id`s (e.g. `FB` 2012–2022 vs `FB` 2025+) produces two independent chains with no cross-listing bleed.
|
||||
- Unmapped splits and dividends are dropped and counted separately (`splits_dropped_unmapped`, `dividends_dropped_unmapped`).
|
||||
2. **Collision policy (fail closed on cross-key conflict):**
|
||||
- Single-source-key groups on `(listing_id, ex_date)` pass through unchanged to `build_adj_factors` (preserving same-day multi-dividend summation, same-day split multiplication, `1:1` no-op drops, and zero-cash dividend drops).
|
||||
- Multi-source-key groups with bitwise-identical split ratios (or bitwise-identical dividend `cash`/`currency`/`prev_close`/`prev_close_currency`) collapse to one event and are counted in `splits_collision_collapsed`, `dividends_collision_collapsed`, and `listing_collision_collapsed`.
|
||||
- Multi-source-key groups with conflicting split ratios or differing dividend payloads fail closed with `CurateAdjError::ConflictingCrossKeySplit` / `CurateAdjError::ConflictingCrossKeyDividend` (silently dropping or doubling an event would corrupt every earlier cumulative factor).
|
||||
3. **Conservative `known_at` & point-in-time / vault-fence policy:**
|
||||
- Stamps every curated row with `known_at_micros = session_close::et_session_close_utc_micros(ex_date)` (`16:00:00 America/New_York` / `America/Toronto`: `21:00 UTC` in EST, `20:00 UTC` in EDT) because `qmSplits` / `qmDividends` adj builder inputs carry no announcement timestamp.
|
||||
- Any mapped row whose `ex_date` lies outside `1976-01-01..=2030-12-31` returns `CurateAdjError::ExDateOutOfRange` naming `(listing_id, ex_date)` without panicking (dropping a row would break the cumulative chain).
|
||||
- **Retrospective vs. Point-in-Time snapshots:** because `cum_split_factor` and `cum_total_factor` are right-to-left suffix products, later splits and dividends are embedded in earlier rows. `curate_adj_factors` / `curate_and_write_adj_factors` explicitly tag their output as `AdjSnapshotKind::RetrospectiveSnapshot` — slicing a retrospective snapshot with a bare `known_at <= as_of` filter would still leak future or held-out vault actions into earlier bars.
|
||||
- **Point-in-time & Vault fencing:** `curate_adj_factors_as_of` / `curate_and_write_adj_factors_as_of` accept an `AdjPointInTimeFence { as_of_micros, vault_cutoff_micros }` (`known_at <= as_of_micros` inclusive and `known_at < vault_cutoff_micros` strictly exclusive, matching `design/DATA-CONTRACTS.md` §4) and fence mapped source events *before* compaction and compounding, tagging the output as `AdjSnapshotKind::PointInTimeFenced(fence)`. Appending any future or vault-held action leaves earlier rows and `adj_factors_for_bar` reads bitwise identical.
|
||||
- **Persisted Parquet footer metadata & verified readers:** `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` publish `<out_dir>/adj_factors/part.parquet` in a single atomic file commit (one dataset lock, exclusive staging, live-preserving backup, single `rename`) embedding `stock_bot.adj_factors.{format_version, snapshot_kind, as_of_micros, vault_cutoff_micros, rows_written, snapshot_checksum}` directly in the Parquet footer `key_value_metadata` (where `snapshot_checksum` binds `format_version`, `snapshot_kind` / exact fence, row count, and all 8 columns of every row). When a run produces 0 rows (e.g. a fence excludes every event), an explicit 0-row Zstd Parquet file with the contract schema and embedded footer metadata is atomically published so any previous `part.parquet` is superseded rather than left stale. `read_adj_factors_dataset_as_of` requires a non-retrospective fence, fails closed on missing/corrupt/unsupported footer metadata, rejects retrospective snapshots (`RetrospectiveSnapshotRejected`) or any mismatched fence (`IncompatibleFence`), checks every row's `known_at` against the fence (`RowOutsideFence`), verifies per-listing `cum_split_factor` reverse suffix products, and verifies the bound `snapshot_checksum` (`SnapshotIntegrityMismatch`).
|
||||
4. **Accounting & error handling:**
|
||||
- Exact conservation invariants in `CurateAdjFactorsStats`:
|
||||
- `splits_in == splits_dropped_unmapped + splits_dropped_fenced + splits_collision_collapsed + builder.split_events_in`
|
||||
- `dividends_in == dividends_dropped_unmapped + dividends_dropped_fenced + dividends_collision_collapsed + builder.dividend_events_in`
|
||||
- `listing_collision_collapsed == splits_collision_collapsed + dividends_collision_collapsed`
|
||||
- `rows_out == builder.rows_out` and `listings_out == builder.keys_out`
|
||||
- For `AdjSnapshotKind::RetrospectiveSnapshot`, `splits_dropped_fenced == 0` and `dividends_dropped_fenced == 0`.
|
||||
- `curate_and_write_adj_factors` / `curate_and_write_adj_factors_as_of` run curation before touching `out_dir`, so any `CurateAdjError` leaves `out_dir` untouched and publishes no `adj_factors/part.parquet` (surfacing via `CurateAdjWriteError::{Curate, Parquet}`).
|
||||
5. **Deferred items:**
|
||||
- Live MongoDB cursor streaming and BSON decoders for `qmSplits` / `qmDividends`
|
||||
- PostgreSQL `provider_mapping` preload
|
||||
- Sourcing `DividendEvent.prev_close` from `bars_1d` (currently supplied by the caller)
|
||||
- `rayon` parallel sharding and end-to-end `curate` CLI command
|
||||
|
||||
### `bench-curate-adj`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `1,000,000` (default) or `[events]` source-keyed `qmSplits` (~4%) and `qmDividends` (~96%) events across `20,000` `String` source keys spanning `1990..=2025` (single-range keys, ticker-rename pairs, ticker-reuse keys with an H2-2018 gap, unmapped keys, and explicit bitwise-identical alias keys), separately timing in-memory `curate_adj_factors` and Zstd Parquet `write_adj_factors_dataset` into a temp directory with footer row-count verification and cleanup:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-curate-adj [events]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x024ec73a1afe7e6b`): `cargo run --release -p curate-etl --offline -- bench-curate-adj`
|
||||
|
||||
- Input: `events=1000000`, `splits=40221`, `dividends=959779`, `keys=20000`
|
||||
- Builder: `rows_out=946414`, `keys_out=19500`, `split_noops=1938`, `zero_div=9234`, `missing_prev_close=18458`, `currency_mismatch=18461`, `not_below_prev_close=9193`
|
||||
- Output: `rows_out=946414` (`94.64%` retained), `listings_out=19500`, `files=1`, `row_groups=1`, `bytes=11872037`, `read_back_rows=946414`
|
||||
- Curation stats: `splits_unmapped=1486`, `divs_unmapped=34220`, `splits_coll_collapsed=213`, `divs_coll_collapsed=4717`, `coll_collapsed=4930`
|
||||
- Run 1:
|
||||
- Stage (in-memory): `elapsed=930.92 ms`, `throughput=1074206 events/s`, `latency=930.92 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.42 ms`, `throughput=3606439 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1193.34 ms`, `throughput=837982 events/s`
|
||||
- Run 2:
|
||||
- Stage (in-memory): `elapsed=933.02 ms`, `throughput=1071785 events/s`, `latency=933.02 ns/event`, `checksum=0x024ec73a1afe7e6b`
|
||||
- Parquet write: `elapsed=262.81 ms`, `throughput=3601091 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=1195.84 ms`, `throughput=836235 events/s`
|
||||
|
||||
## `corporate_actions` Curation Stage (`M1.2u`)
|
||||
|
||||
`curate_corporate_actions` and `curate_and_write_corporate_actions` (`src/curate_corporate_actions.rs`) join `build_corporate_actions`, `ProviderMappingTable`, `session_close::et_session_close_utc_micros`, and `write_corporate_actions_dataset` into contract `CorporateActionsParquetRow` records sorted deterministically with non-decreasing `(listing_id, ex_date, kind)`.
|
||||
|
||||
1. **Field & timestamp rules:**
|
||||
- Calls `build_corporate_actions` unchanged (`1:1` split no-ops, `0.0` cash dividends, and delistings without an outcome drop inside the builder; same-key multi-dividends stay separate; late declarations clamp to `ex_date` with `KnownAtSource::ExDateFallback`; local `currency` is preserved).
|
||||
- Resolves `(mapping_source, key, ex_date) -> listing_id` via `ProviderMappingTable::cursor_for` / `ProviderMappingCursor::resolve` (one cursor per contiguous `key` run) for `split`, `dividend`, and terminal `delisting` rows.
|
||||
- For `otc_delist_transfer` rows, Pass 6 anchors `ex_date` (and `known_at`) to `effectiveDate` (the successor's first OTC trading date), which normally falls after the outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US` starts `2023-03-28`) and may coincide with ticker reuse. `otc_delist_transfer` therefore requires Pass 6's outgoing listing identity via `CurateDelistingInput::from_listing_id` (`Some(id)`): curation selects only a `provider_mapping` range for `(mapping_source, key)` with `valid_from <= ex_date` and `listing_id == id` (never attaching to an unrelated ticker occupant), and any identity-less `otc_delist_transfer` (`from_listing_id = None`) drops into `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to `successor_listing_id`. Never emits an `otc_delist_transfer` with `successor_listing_id = None` or `successor_listing_id == listing_id`.
|
||||
- Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source corporate-action records carry no intraday announcement time) and carries `known_at_source` through unchanged.
|
||||
- Carries `ex_date`, `declared_date`, `kind`, `ratio`, `cash_amount`, `currency`, and `terminal_return` through bit-exactly (`"USD"`/`"CAD"` interned as `Cow::Borrowed`).
|
||||
2. **Drop & collision policy (never panics or aborts on bad rows):**
|
||||
- Strict drop priority per built row:
|
||||
1. `dropped_unmapped`: no covering `provider_mapping` range for `(mapping_source, key, ex_date)` (or, for `otc_delist_transfer`, missing `from_listing_id = None` or no range with `valid_from <= ex_date` matching `from_listing_id = Some(id)`; or, for terminal `delisting` with `from_listing_id = Some(id)`, active occupant does not match `id`).
|
||||
2. `dropped_unmapped_successor`: `otc_delist_transfer` whose `successor_key` has no covering range on `ex_date`.
|
||||
3. `dropped_self_successor`: `otc_delist_transfer` whose `successor_key` resolves to the row's own `listing_id`.
|
||||
4. `dropped_known_at_out_of_range`: `known_at_date` falls outside `et_session_close_utc_micros`'s `1976-01-01..=2030-12-31` window.
|
||||
- After re-sorting deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`):
|
||||
- Cross-key conflicting `split` ratios on the same `(listing_id, ex_date)` (`> 1` source key and `> 1` distinct `ratio` bit pattern) drop the entire group (`listing_collision_dropped`).
|
||||
- Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount same-day regular + special dividends) while collapsing cross-key aliases.
|
||||
- Exact conservation invariant in `CurateCorporateActionsStats`: `rows_in == builder.rows_out` and `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`.
|
||||
- Typed caller errors: `CurateCorporateActionsError` (`CorporateAction(CorporateActionError)`, `EmptyMappingSource`) and `CurateCorporateActionsWriteError` (`Curate(CurateCorporateActionsError)`, `Parquet(ParquetCorporateActionsError)`). A curate error in `curate_and_write_corporate_actions` returns before invoking `write_corporate_actions_dataset`, leaving `out_dir` untouched.
|
||||
|
||||
### `bench-curate-corporate-actions`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) benchmark over `520,000` source-keyed corporate-action events (~3.6% splits ≈20.3k incl. `1:1` no-ops and alias collisions, ~95.4% USD/CAD dividends ≈494.6k incl. `0.0` drops and same-day multi-dividends, ~1.0% delisting outcomes ≈5.1k incl. OTC transfers and `-0.3`/`-1.0`/no-outcome) across `20,000` `String` keys with multi-range `provider_mapping` reuse gaps, aliases, unmapped/self successors, and pre-1976 dates, separately timing in-memory `curate_corporate_actions` and Zstd Parquet `write_corporate_actions_dataset` into a temp directory with footer row-count verification and cleanup:
|
||||
|
||||
```bash
|
||||
cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions [events]
|
||||
```
|
||||
|
||||
Command (`2026-11-28`, two back-to-back runs with identical checksum `0x0c22a1a1ab7caad4`): `cargo run --release -p curate-etl --offline -- bench-curate-corporate-actions`
|
||||
|
||||
- Input: `events=520000`, `splits=20262`, `dividends=494624`, `delistings=5114`, `keys=20000`
|
||||
- Builder: `rows_out=514224`, `splits_out=19938`, `split_noops=324`, `divs_out=489671`, `zero_div=4953`, `otc_out=2856`, `delist_out=1759`, `delist_no_outcome=499`
|
||||
- Output: `rows_out=494518` (`95.10%` retained), `listings_out=19996`, `files=1`, `row_groups=1`, `bytes=3802001`, `read_back_rows=494518`
|
||||
- Curation stats: `unmapped=12886`, `unmapped_succ=511`, `self_succ=531`, `known_at_oor=2526`, `coll_collapsed=1398`, `coll_dropped=1854`
|
||||
- Run 1:
|
||||
- Stage (in-memory): `elapsed=278.66 ms`, `throughput=1866040 events/s`, `latency=535.89 ns/event`, `checksum=0x0c22a1a1ab7caad4`
|
||||
- Parquet write: `elapsed=84.14 ms`, `throughput=5877527 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=362.80 ms`, `throughput=1433288 events/s`
|
||||
- Run 2:
|
||||
- Stage (in-memory): `elapsed=284.33 ms`, `throughput=1828877 events/s`, `latency=546.78 ns/event`, `checksum=0x0c22a1a1ab7caad4`
|
||||
- Parquet write: `elapsed=87.57 ms`, `throughput=5647404 rows/s`
|
||||
- Combined (stage → Parquet): `elapsed=371.89 ms`, `throughput=1398252 events/s`
|
||||
|
||||
## `curate-bars-1d` Command (`M1.2z` / `M1.2ah` / `M1.2ai`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_bars.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, `decode_qm_split_chunks`, optional `decode_qm_price_chunks` (`src/bson_qm_prices.rs`), `ProviderMappingTable`, `SplitTable`, and `curate_and_write_bars_1d` (with `rayon` year-sharded parallel Zstd Parquet encoding) into `<out>/bars_1d/year=YYYY/part.parquet` with no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-bars-1d \
|
||||
--eod-prices <path> # concatenated raw BSON (mongodump eodPrices.bson)
|
||||
--qm-splits <path> # concatenated raw BSON (mongodump qmSplits.bson)
|
||||
[--qm-prices <path>] # optional concatenated raw BSON (qmPrices.bson) for read-only sharevolume cross-check
|
||||
--curate-inputs <dir> # exporter output dir (pins <dir>/current once before opening TSVs)
|
||||
--out <dir> # dataset root -> bars_1d/year=YYYY/part.parquet
|
||||
[--rel-tolerance <f64>] # default: 0.01
|
||||
[--threads <N>] # default: available_parallelism() (1 = bounded-RAM sequential write)
|
||||
```
|
||||
|
||||
Instead of `--curate-inputs <dir>`, standalone TSV files may be passed directly with `--provider-mapping <path> --listing-currencies <path>` (mutually exclusive with `--curate-inputs`). When reading from a live exporter output directory, always prefer `--curate-inputs <dir>` so `curate-bars-1d` pins `<dir>/current` once before opening either TSV and cannot mix generations across a concurrent refresh.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid/missing/duplicate flags exit non-zero with usage on stderr. Runtime errors (missing files, truncated or oversized BSON documents, malformed TSV lines, overlapping mapping ranges, conflicting cross-key QM splits, unwritable `--out`) print a single-line stderr message naming the offending path (and 1-based line number for TSV errors), exit non-zero, and leave no partial `bars_1d` files under `--out`. Volume cross-check mismatches never fail the run (exit code `0`) and never modify emitted Parquet bytes.
|
||||
|
||||
### `qmPrices` Raw BSON Decoder (`src/bson_qm_prices.rs`)
|
||||
|
||||
- **Documented field names & raw-volume semantics** (`prices.action.ts:97-109`, `bar-spans.ts:19-24`, `sample-closes.ts:300-303`, `design/DATA-CONTRACTS.md` §1): `qmPrices` stores QuoteMedia daily bars keyed by `qmSearchCode` with provider date field `date` (and a separate BSON `Date` in `dateTime`) and unadjusted share volume in `sharevolume`.
|
||||
- **Accepted BSON types (live `qmPrices` date format and numeric type distribution remain unverified against QA MongoDB):**
|
||||
- `qmSearchCode`: BSON UTF-8 `String` borrowed verbatim (never trimmed; empty/whitespace-only rejected as `EmptyField`).
|
||||
- `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via `parse_ymd_strict_days` (non-string `date` — including BSON `DateTime` — is rejected as `WrongType` and counted in `qm_bson.rejected`; bad format/calendar strings are rejected as `MalformedDate`).
|
||||
- `sharevolume`: BSON `Double`, `Int32`, or `Int64` converted to `f64`. Numeric domain validity (negative / non-finite) is passed through to `build_bars_1d` (`qm_invalid_volume_dropped`); missing, `Null`, or non-numeric types are rejected with counted reasons.
|
||||
- All extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, nested docs/arrays) are skipped without calling `elem.value()`.
|
||||
- **Accounting invariant:** `docs_in == decoded + rejected_total()` (`rejected_missing_field + rejected_empty_field + rejected_wrong_type + rejected_malformed_date + rejected_corrupt_document`).
|
||||
|
||||
### TSV Formats (strict, headerless, `\t`-separated)
|
||||
|
||||
- `provider_mapping`: `source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
||||
- `source` and `source_id` are preserved verbatim (never trimmed); blank/whitespace-only values are rejected.
|
||||
- Dates are parsed strictly with `YYYY-MM-DD` Gregorian validation; `listing_id` must be a strict positive ASCII integer.
|
||||
- `listing_currencies`: `listing_id \t currency`
|
||||
- Unique positive `listing_id` per row; non-blank currency code (`"USD"` and `"CAD"` are interned).
|
||||
- Both files accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number.
|
||||
|
||||
### Split Re-Keying, `qmPrices` Re-Keying, Early Filter & Missing-Currency Policy
|
||||
|
||||
1. **Split re-keying (`qmSearchCode` → `eodSearchCode`):** Each decoded `qmSplits` row with `ratio != 1.0` resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable`. Before fanning out to `"eod"` partners, mapped splits are compacted by `(listing_id, ex_date)` using the same cross-key policy as `curate_adj_factors`: single-QM-key same-day groups pass through unchanged, multi-QM-key alias groups with bitwise-identical ratios collapse to one event (`splits_collision_collapsed`), and multi-QM-key groups with conflicting ratios fail closed (`ConflictingCrossKeySplit`). Surviving events are attached to every deduplicated `"eod"` `source_id` pointing at that `listing_id` (preventing ratio squaring when one `(listing_id, eod_source_id)` spans multiple date ranges). No ticker-text guessing is performed.
|
||||
2. **Date-aware `qmPrices` volume re-keying (optional `--qm-prices`):** Each decoded `qmPrices` row resolves `("qm", qmSearchCode, session_date) -> listing_id` via `ProviderMappingTable`, then fans out only to `"eod"` `source_id`s whose mapping range covers `session_date` (reusing interned `Arc<str>` EOD keys; no ticker-text guessing, so reused EOD tickers never receive volumes from another occupant). Unmapped QM keys and QM rows whose `listing_id` has no date-covering `"eod"` partner are early-filtered before buffering into `qm_unmapped_qm` and `qm_no_eod_partner`. When `--qm-prices` is omitted, no reverse range index is built and `qm_volumes` stays empty.
|
||||
3. **Early filter & key interning:** While streaming `eodPrices`, bars whose `eodSearchCode` has no `"eod"` range in `provider_mapping` are dropped before buffering (`bars_unmapped_source_dropped`). Retained bars share interned `Arc<str>` keys rather than allocating a `String` per bar.
|
||||
4. **Missing-currency behavior:** Delegated unchanged to `curate_bars_1d` — mapped listings absent from `--listing-currencies` (or blank) are dropped into `dropped_missing_currency` without failing the run.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-bars-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `splits_bson`, `splits`, `filter`, `builder`, `curate`, `write`, ascending `years`, `qm_check: qm_prices=absent` when `--qm-prices` is omitted or `qm_bson` / `qm_rekey` / `qm_check` + up to `100` `qm_mismatch` lines when supplied, `config: threads=<N>`, and `timing`):
|
||||
|
||||
- `splits_in == splits_applied + splits_collision_collapsed + splits_unmapped_qm + splits_no_eod_partner + splits_noop_dropped + splits_bson.rejected`
|
||||
- `eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
|
||||
- `eod_bson.decoded == write.rows_written + bars_unmapped_source_dropped + builder.(invalid_ohlc + inconsistent_ohlc + invalid_vol + dup_collapsed + dup_conflict_dropped) + curate.(dropped_unmapped + dropped_missing_currency + dropped_ts_out_of_range + listing_collision_collapsed + listing_collision_dropped)`
|
||||
- When `--qm-prices` is provided:
|
||||
- `qm_bson.docs_framed == qm_bson.docs_in == qm_bson.decoded + qm_bson.rejected`
|
||||
- `qm_rekey.qm_in == qm_rekey.qm_attached + qm_rekey.qm_unmapped_qm + qm_rekey.qm_no_eod_partner + qm_bson.rejected`
|
||||
- `qm_rekey.qm_volumes_attached == qm_check.qm_rows_in`
|
||||
- `qm_check.volume_checked + qm_check.volume_unchecked == builder.rows_out`
|
||||
- `qm_check.volume_within_tolerance + qm_check.volume_mismatched == qm_check.volume_checked`
|
||||
|
||||
### `bench-curate-bars-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson`, `qmSplits.bson`, `qmPrices.bson` (matching `Double`/`Int32`/`Int64` `sharevolume` partners, unmapped QM keys, QM keys with no EOD partner, wrong-typed `sharevolume` rejects, and exact injected >1% divergences), `provider_mapping.tsv`, and `listing_currencies.tsv` into a temp dir, timing decode / qm decode+rekey / curate / sequential (`threads=1`, `write_1`) vs parallel (`threads=available_parallelism()`, `write` + `speedup`) Parquet writes on the exact same curated rows, verifying Parquet footer row counts for both outputs, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd [rows]
|
||||
```
|
||||
|
||||
Single-threaded baseline measured locally (`2026-11-29`, prior to `rayon` parallel write; multi-thread `write_1` vs `write` numbers pending first unsandboxed release run after `rayon = "=1.12.0"` is fetched):
|
||||
|
||||
1. **1,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 1000000`):
|
||||
- Input: `rows=1000000`, `eod_bytes=161690000` (154.2 MiB), `splits_docs=2040`, `splits_bytes=188080`, `qm_docs=227439`, `qm_bytes=20815907` (19.9 MiB), `keys=2000`
|
||||
- Decode (all inputs): `elapsed=234.63 ms`, `throughput=4262081 rows/s`, `scan=742.58 MB/s`, `unmapped_dropped=20000`, `buffered_bars=980000`, `buffered_bytes=67161784` (`68.5 bytes/bar`)
|
||||
- QM decode + rekey: `elapsed=31.93 ms`, `throughput=7123258 docs/s`, `scan=621.74 MB/s`, `attached=224939`, `unmapped=1000`, `no_eod_partner=1000`, `rejected=500`, `checked=224939`, `within_tol=222689`, `mismatched=2250 (injected=2250)`, `unchecked=755021`, `samples=100`
|
||||
- Curate: `elapsed=208.07 ms`, `throughput=4709887 rows/s`, `rows_out=938023` (`93.80%` retained), `listings_out=1941`, `unmapped=595`, `missing_curr=9500`, `ts_oor=1842`, `coll_collapsed=10000`, `coll_dropped=20000`
|
||||
- Write: `elapsed=456.39 ms`, `throughput=2055293 rows/s`, `write=53.70 MB/s`, `files=36`, `row_groups=36`, `bytes=25699104`, `read_back_rows=938023`
|
||||
- Total: `elapsed=899.09 ms`, `throughput=1112231 rows/s`, `throughput_mb=193.78 MB/s`, `splits_applied=1699`, `splits_coll_collapsed=40`, `splits_unmapped_qm=101`, `splits_no_eod_partner=100`, `splits_noop=100`
|
||||
2. **5,000,000 rows** (`cargo run -p curate-etl --release --offline -- bench-curate-bars-cmd 5000000`):
|
||||
- Input: `rows=5000000`, `eod_bytes=808449920` (771.0 MiB), `splits_docs=4080`, `splits_bytes=376160`, `qm_docs=1138361`, `qm_bytes=104186437` (99.4 MiB), `keys=6000`
|
||||
- Decode (all inputs): `elapsed=1167.06 ms`, `throughput=4284272 rows/s`, `scan=746.08 MB/s`, `unmapped_dropped=99960`, `buffered_bars=4900040`, `buffered_bytes=537029672` (`109.6 bytes/bar`)
|
||||
- QM decode + rekey: `elapsed=171.72 ms`, `throughput=6629277 docs/s`, `scan=578.63 MB/s`, `attached=1125861`, `unmapped=5000`, `no_eod_partner=5000`, `rejected=2500`, `checked=1125861`, `within_tol=1114602`, `mismatched=11259 (injected=11259)`, `unchecked=3773805`, `samples=100`
|
||||
- Curate: `elapsed=1119.70 ms`, `throughput=4376207 rows/s`, `rows_out=4691865` (`93.84%` retained), `listings_out=5822`, `unmapped=2879`, `missing_curr=48328`, `ts_oor=9132`, `coll_collapsed=49206`, `coll_dropped=98256`
|
||||
- Write: `elapsed=1238.26 ms`, `throughput=3789066 rows/s`, `write=79.75 MB/s`, `files=36`, `row_groups=36`, `bytes=103552480`, `read_back_rows=4691865`
|
||||
- Total: `elapsed=3525.02 ms`, `throughput=1418430 rows/s`, `throughput_mb=247.01 MB/s`, `splits_applied=3399`, `splits_coll_collapsed=80`, `splits_unmapped_qm=201`, `splits_no_eod_partner=200`, `splits_noop=200`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Full in-RAM buffering of mapped bars (and optional QM volumes) + parallel year-bucketing RAM:** `curate-bars-1d` buffers every mapped bar in `Vec<EodDailyBar<Arc<str>>>` before sorting (`64 B/bar` struct size; measured `68.5–109.6 B/bar` including `Vec` geometric growth headroom, plus ~200 B/row peak during `curate_bars_1d` while `built.rows` and `Bars1dParquetRow` briefly coexist), plus `32 B/row` for mapped `QmRawVolume<Arc<str>>` when `--qm-prices` is supplied (~1.6 GiB worst case if all 51.5M QM rows map). When `--threads > 1`, Pass 1 of `write_bars_1d_dataset` buckets validated `Bars1dParquetRow`s by year (`~136 B/row` struct size plus `Vec` growth slack, `~180–200 B/row` transient overhead before the caller's `curated.rows` vector drops) and holds up to `min(threads, years)` concurrent `RowGroupBuffer`s during parallel Zstd encoding (each year's bucket drops as soon as its worker finishes). Pass `--threads 1` to use the bounded-RAM single-pass streaming writer. For the US+CA subset (~100–150M rows of the 846M-row `eodPrices` collection), this implies roughly **20–30 GiB peak RAM** (viable on a 64 GiB workstation, tight on 32 GiB); running all 846M global rows unsharded would exceed 160 GiB.
|
||||
- **Parallelism scope & direct MongoDB cursors:** `rayon` year-sharded parallelism currently covers the `curate-bars-1d` Parquet write stage (`--threads`); parallel BSON decode, parallel curate/sort, other `curate-*` commands, and direct MongoDB cursors remain deferred to follow-up tasks.
|
||||
- **Ticker-reuse split keying caveat:** because `curate_bars_1d` takes `SplitTable<K>` keyed by `eodSearchCode` rather than `listing_id`, attaching a split to every `"eod"` `source_id` pointing at a `listing_id` means a later split on a reused `eodSearchCode` could affect an earlier listing that previously held that same `eodSearchCode`.
|
||||
- **Partition-level replacement on `--out` reuse:** `write_bars_1d_dataset` atomically replaces only the `bars_1d/year=YYYY/part.parquet` partitions emitted by the current run. Reusing an existing `--out` directory for a narrower year range leaves older year partitions intact on disk; use a fresh `--out` directory for a complete rebuild.
|
||||
|
||||
## `curate-adj-factors` Command (`M1.2aa`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_adj.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a column-projected `bars_1d` Parquet reader for strict pre-ex-date `prev_close`, and `curate_and_write_adj_factors` into an atomically published `<out>/adj_factors/part.parquet` retrospective snapshot with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-adj-factors \
|
||||
--qm-splits qmSplits.bson \
|
||||
--qm-dividends qmDividends.bson \
|
||||
--provider-mapping provider_mapping.tsv \
|
||||
--bars-1d ./out/bars_1d \
|
||||
--out ./out
|
||||
```
|
||||
|
||||
Inputs and output:
|
||||
- `--qm-splits <path>`: concatenated raw BSON (`mongodump` `qmSplits.bson`).
|
||||
- `--qm-dividends <path>`: concatenated raw BSON (`mongodump` `qmDividends.bson`).
|
||||
- `--provider-mapping <path>`: headerless 5-column TSV (same format as `curate-bars-1d`).
|
||||
- `--bars-1d <dir>`: `bars_1d` directory containing `year=YYYY/part.parquet` (or parent root containing `bars_1d/`).
|
||||
- `--out <dir>`: dataset root where `adj_factors/part.parquet` is atomically published.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate, or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, missing/invalid `--bars-1d` directory, missing/wrong-schema/corrupt `part.parquet`, duplicate `(listing_id, session_date)` in `bars_1d`, malformed `provider_mapping.tsv` reporting 1-based line number, truncated/oversized BSON stream, or cross-key split/dividend curation conflict) prints a single-line stderr message naming the offending path, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/adj_factors/part.parquet` byte-identical).
|
||||
|
||||
### `prev_close` Lookup & Contract Rules
|
||||
|
||||
- **Column-projected `bars_1d` reader:** validates every discovered `year=YYYY/part.parquet` against `bars_1d_parquet_schema()` and reads only 4 of the 12 columns (`listing_id`, `session_date`, `close`, `currency`) in bounded `65,536`-row batches into a compact in-RAM index (`16 bytes/bar`, currency strings interned to `u16`).
|
||||
- **Strict pre-ex-date boundary:** for each decoded `qmDividends` document, resolves `("qm", qmSearchCode, ex_date) -> listing_id` via `ProviderMappingTable` and attaches the raw `close` and `currency` of the last `bars_1d` session strictly before `ex_date` (`session_date < ex_date`; a bar on `ex_date` itself is never used). When no earlier bar exists (or the dividend is unmapped), `prev_close` and `prev_close_currency` are `None`.
|
||||
- **`usdFxRate` & `splitratio == 1`:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1` no-op handling and cross-key collision rules stay delegated unchanged to `curate_and_write_adj_factors`. Per-document BSON decode rejects are counted without aborting the run.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-adj-factors` prints deterministic `key=value` lines to stdout (`bars_1d`, `splits_bson`, `dividends_bson`, `prev_close`, `builder`, `curate`, `write`, and `timing`):
|
||||
|
||||
- **Splits:** `splits_bson.docs_framed == splits_bson.docs_in == splits_bson.rejected + curate.splits_unmapped + curate.splits_fenced + curate.splits_coll_collapsed + builder.splits_in`
|
||||
- **Dividends:** `dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.rejected + curate.divs_unmapped + curate.divs_fenced + curate.divs_coll_collapsed + builder.dividends_in`
|
||||
- **Dividend `prev_close` partition:** `dividends_bson.decoded == prev_close.with_prev_close + prev_close.without_prev_close + curate.divs_unmapped`
|
||||
|
||||
### `bench-curate-adj-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv`, a 16-year `bars_1d` Parquet dataset (`2010..=2025`, `62,720` bars across `3,920` mapped listings), `qmSplits.bson` (~4% of events incl. `1:1` no-ops, unmapped, identical cross-key aliases, and ~0.5% malformed decode rejects), and `qmDividends.bson` (~96% of events incl. USD/CAD with bogus `usdFxRate: 1`, `cash == 0.0`, unmapped, identical cross-key aliases, pre-first-bar dates for missing `prev_close`, currency mismatches, and ~0.5% malformed decode rejects) into a temp dir, timing `bars_load` / `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd [events]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`):
|
||||
|
||||
1. **100,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd 100000`):
|
||||
- Input: `events=100000`, `splits_docs=4000` (`422,398 B`), `dividends_docs=96000` (`11,592,112 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000`
|
||||
- `bars_load`: `elapsed=3.69 ms`, `throughput=17006461 bars/s` (`listings=3920`)
|
||||
- `decode`: `elapsed=31.13 ms`, `throughput=3211920 events/s`, `scan=368.02 MB/s`, `splits_rejected=20`, `divs_rejected=453`, `with_prev_close=89914`, `without_prev_close=2792`
|
||||
- `curate`: `elapsed=36.62 ms`, `throughput=2717561 events/s`, `rows_out=88215` (`88.22%` retained), `listings_out=3920`, `checksum=0xdacf704be0642aff`
|
||||
- `write`: `elapsed=24.36 ms`, `throughput=3621493 rows/s`, `write=49.47 MB/s`, `files=1`, `row_groups=1`, `bytes=1263546`, `read_back_rows=88215`
|
||||
- `total`: `elapsed=95.80 ms`, `throughput=1043793 events/s`, `checksum=0xdacf704be0642aff`
|
||||
2. **500,000 events** (default; two back-to-back runs with identical checksum `0x16b8d07222f35849`): `cargo run -p curate-etl --release --offline -- bench-curate-adj-cmd`
|
||||
- Input: `events=500000`, `splits_docs=20000` (`2,112,208 B`), `dividends_docs=480000` (`57,960,382 B`), `bars_files=16`, `bars_rows=62720`, `keys=4000`
|
||||
- Output: `rows_out=431459` (`86.29%` retained), `listings_out=3920`, `files=1`, `row_groups=1`, `bytes=5539481`, `read_back_rows=431459`
|
||||
- Run 1: `bars_load=3.76 ms` (`16,702,636 bars/s`), `decode=129.61 ms` (`3,857,829 events/s`, `442.03 MB/s`), `curate=283.10 ms` (`1,758,001 events/s`), `write=84.42 ms` (`5,111,126 rows/s`, `62.58 MB/s`), `total=500.88 ms` (`998,252 events/s`), `checksum=0x16b8d07222f35849`
|
||||
- Run 2: `bars_load=3.73 ms` (`16,832,966 bars/s`), `decode=125.40 ms` (`3,987,232 events/s`, `456.85 MB/s`), `curate=228.61 ms` (`2,177,036 events/s`), `write=79.17 ms` (`5,449,842 rows/s`, `66.73 MB/s`), `total=436.90 ms` (`1,144,419 events/s`), `checksum=0x16b8d07222f35849`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Retrospective snapshot only:** `curate-adj-factors` publishes an unfenced `AdjSnapshotKind::RetrospectiveSnapshot` whose earlier cumulative factors embed later splits/dividends. Point-in-time readers (`read_adj_factors_dataset_as_of`) reject retrospective snapshots automatically; use `curate_and_write_adj_factors_as_of` when a point-in-time or vault-fenced snapshot is required.
|
||||
- **In-RAM `bars_1d` close index:** loading `bars_1d` into `PrevCloseIndex` takes `16 bytes/bar` (plus `Vec` growth slack, ~1.6–2.5 GiB for 100M bars).
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding or direct MongoDB/PostgreSQL connections yet.
|
||||
|
||||
## `curate-corporate-actions` Command (`M1.2ab`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_corporate_actions.rs`) wiring `RawBsonChunkReader`, `decode_qm_split_chunks`, `decode_qm_dividend_chunks`, `load_provider_mapping_tsv`, a strict Pass 6 `delistings.tsv` loader (`load_delistings_tsv`), and `curate_and_write_corporate_actions` into an atomically published `<out>/corporate_actions/part.parquet` dataset with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-corporate-actions \
|
||||
--qm-splits qmSplits.bson \
|
||||
--qm-dividends qmDividends.bson \
|
||||
--curate-inputs ./tmp/curate-inputs \
|
||||
--out ./out
|
||||
```
|
||||
|
||||
Inputs and output:
|
||||
- `--qm-splits <path>`: concatenated raw BSON (`mongodump` `qmSplits.bson`).
|
||||
- `--qm-dividends <path>`: concatenated raw BSON (`mongodump` `qmDividends.bson`).
|
||||
- `--curate-inputs <dir>`: exporter output directory containing a committed `current` link. Requires `<dir>/current` and resolves it once via `canonicalize` before opening `provider_mapping.tsv` and `delistings.tsv` so both files always come from the same atomic PostgreSQL snapshot even if an export refreshes `current` concurrently. Fails closed if `current` is absent (use `--provider-mapping` / `--delistings` for standalone files or direct generation paths). Mutually exclusive with `--provider-mapping` and `--delistings`.
|
||||
- `--provider-mapping <path>` / `--delistings <path>` *(alternative to `--curate-inputs`)*: standalone headerless 5-column TSVs (`--delistings` is optional when using explicit TSV paths; when omitted, zero delisting rows are loaded).
|
||||
- `--out <dir>`: dataset root where `corporate_actions/part.parquet` is atomically published.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--delistings`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, malformed `provider_mapping.tsv` or `delistings.tsv` reporting path + 1-based line number, overlapping mapping ranges, truncated/corrupt/oversized BSON stream carrying byte offset, or unwritable `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/corporate_actions/part.parquet` byte-identical).
|
||||
|
||||
### TSV Formats (strict, headerless, `\t`-separated)
|
||||
|
||||
- `provider_mapping` (5 columns; identical to `curate-bars-1d`):
|
||||
`source \t source_id \t valid_from(YYYY-MM-DD) \t valid_to(YYYY-MM-DD or empty) \t listing_id`
|
||||
- `delistings` (optional file; 5 columns when supplied):
|
||||
`source_id \t delist_date(YYYY-MM-DD) \t from_listing_id(int or empty) \t successor_source_id(or empty) \t terminal_return(float or empty)`
|
||||
- `source_id` is preserved verbatim (never trimmed) and must not be empty or whitespace-only.
|
||||
- `delist_date` is parsed strictly with `YYYY-MM-DD` Gregorian validation.
|
||||
- `from_listing_id` is empty (`None`) or a strict positive ASCII base-10 `i32`.
|
||||
- `successor_source_id` is empty (`None`) or a non-blank string preserved verbatim.
|
||||
- `terminal_return` is empty (`None`) or a finite `f64` in `[-1.0, 0.0]` with no leading/trailing whitespace (`-0.0` is normalized to `0.0`).
|
||||
- Exactly one of `successor_source_id` or `terminal_return` must be set on every row.
|
||||
- Any row with `successor_source_id` set (OTC transfer) requires `from_listing_id` to be set.
|
||||
- Both TSVs accept `\n` or `\r\n` line endings and at most one trailing blank line. Header rows, wrong column counts, interior blank lines, multiple trailing blank lines, interior `\r`, and invalid UTF-8 are rejected with the 1-based line number.
|
||||
|
||||
### `declared_date` / `known_at`, `usdFxRate` & Empty-Input Rules
|
||||
|
||||
- **`declared_date` & `known_at`:** `RawQmSplit::to_split_action_event` and `RawQmDividend::to_dividend_action_event` carry `declared_date` from the raw BSON `declared` field when present. Downstream `build_corporate_actions` clamps late declarations (`declared_date > ex_date`) to `ex_date` with `KnownAtSource::ExDateFallback`, and `curate_corporate_actions` stamps `known_at = 16:00:00 ET` of `known_at_date` (`1976-01-01..=2030-12-31`).
|
||||
- **`usdFxRate` & no-ops:** `usdFxRate` stays ignored per `design/DATA-CONTRACTS.md` §1; `splitratio == 1.0` no-op drops, `cash == 0.0` dividend drops, and cross-key collision rules stay delegated unchanged to `curate_and_write_corporate_actions`. Per-document BSON decode rejects are counted without aborting the run.
|
||||
- **Empty-input behavior:** delegated unchanged to `curate_and_write_corporate_actions` / `write_corporate_actions_dataset`, which returns `Ok` with `rows_written == 0` and `files_written == 0` without creating `<out>/corporate_actions` or modifying any pre-existing `part.parquet` (matching `curate-bars-1d`).
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-corporate-actions` prints deterministic `key=value` lines to stdout (`splits_bson`, `dividends_bson`, `delistings_tsv`, `builder`, `curate`, `write`, and `timing`):
|
||||
|
||||
- **Splits:**
|
||||
`splits_bson.docs_framed == splits_bson.docs_in == splits_bson.decoded + splits_bson.rejected`
|
||||
`splits_bson.decoded == builder.splits_in == builder.splits_out + builder.split_noops`
|
||||
- **Dividends:**
|
||||
`dividends_bson.docs_framed == dividends_bson.docs_in == dividends_bson.decoded + dividends_bson.rejected`
|
||||
`dividends_bson.decoded == builder.dividends_in == builder.dividends_out + builder.zero_div`
|
||||
- **Delistings:**
|
||||
`delistings_tsv.rows_loaded == builder.delistings_in == builder.otc_out + builder.delistings_out` (`builder.delist_no_outcome == 0` under strict TSV validation)
|
||||
- **Stage & Write:**
|
||||
`curate.rows_in == builder.rows_out == curate.rows_out + curate.unmapped + curate.unmapped_succ + curate.self_succ + curate.known_at_oor + curate.coll_collapsed + curate.coll_dropped`
|
||||
`write.rows_written == curate.rows_out`
|
||||
|
||||
### `bench-curate-corporate-actions-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (20,000 keys with single-range, ended primary-venue listings for OTC transfer testing, ticker-reuse gaps, aliases, unmapped keys, and 500 OTC successors), `qmSplits.bson` (~3.6% incl. forward/reverse splits, `declared` variants, `1:1` no-ops, unmapped, identical + conflicting alias collisions, and ~0.5% malformed rejects), `qmDividends.bson` (~95.4% incl. USD/CAD with bogus `usdFxRate: 1`, `declared` variants, `0.0` cash, same-day multi-dividends, identical alias duplicates, unmapped, and ~0.5% malformed rejects), and `delistings.tsv` (~1.0% incl. valid OTC transfers with `from_listing_id`, unmapped/self successors, and `-0.3`/`-1.0` terminal delistings) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd [events]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`):
|
||||
|
||||
1. **200,000 events** (`cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 200000`):
|
||||
- Input: `events=200000`, `splits_docs=7986` (`1,014,335 B`), `dividends_docs=190038` (`26,806,832 B`), `delistings_rows=1976` (`72,436 B`), `keys=20000`
|
||||
- `decode`: `elapsed=50.15 ms`, `throughput=3987987 events/s`, `scan=530.43 MB/s`, `splits_rejected=38`, `divs_rejected=921`
|
||||
- `curate`: `elapsed=65.24 ms`, `throughput=3051003 events/s`, `rows_out=188558` (`94.28%` retained), `listings_out=19850`, `unmapped=5809`, `unmapped_succ=193`, `self_succ=189`, `known_at_oor=967`, `coll_collapsed=542`, `coll_dropped=720`, `split_noops=154`, `zero_div=1909`, `checksum=0x29f0c9ec1451e7c5`
|
||||
- `write`: `elapsed=40.53 ms`, `throughput=4652522 rows/s`, `write=39.23 MB/s`, `files=1`, `row_groups=1`, `bytes=1667357`, `read_back_rows=188558`
|
||||
- `total`: `elapsed=155.92 ms`, `throughput=1282737 events/s`, `checksum=0x29f0c9ec1451e7c5`
|
||||
2. **1,000,000 events** (two back-to-back runs with identical checksum `0xa0fb2bf8e2710d67`): `cargo run -p curate-etl --release --offline -- bench-curate-corporate-actions-cmd 1000000`
|
||||
- Input: `events=1000000`, `splits_docs=39186` (`4,979,926 B`), `dividends_docs=950896` (`134,135,512 B`), `delistings_rows=9918` (`364,087 B`), `keys=20000`
|
||||
- Output: `rows_out=944029` (`94.40%` retained), `listings_out=20000`, `files=1`, `row_groups=1`, `bytes=6890801`, `read_back_rows=944029`
|
||||
- Curation stats: `unmapped=28446`, `unmapped_succ=986`, `self_succ=977`, `known_at_oor=4736`, `coll_collapsed=2555`, `coll_dropped=3392`, `split_noops=738`, `zero_div=9233`
|
||||
- Run 1: `decode=222.11 ms` (`4,502,250 events/s`, `598.88 MB/s`), `curate=406.07 ms` (`2,450,553 events/s`), `write=147.49 ms` (`6,400,505 rows/s`, `44.56 MB/s`), `total=775.67 ms` (`1,289,204 events/s`), `checksum=0xa0fb2bf8e2710d67`
|
||||
- Run 2: `decode=211.87 ms` (`4,719,887 events/s`, `627.83 MB/s`), `curate=396.55 ms` (`2,509,369 events/s`), `write=144.29 ms` (`6,542,758 rows/s`, `45.55 MB/s`), `total=752.71 ms` (`1,328,540 events/s`), `checksum=0xa0fb2bf8e2710d67`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Unverified MongoDB `qmDividends` field names:** `bson_qm_actions::FIELD_DIVIDEND_CASH` (`"amount"`) and `FIELD_DIVIDEND_CURRENCY` (`"currency"`) remain isolated constants pending verification against live `mongodump` `qmDividends` exports.
|
||||
- **In-RAM buffering of decoded events:** the single-threaded runner buffers decoded splits, dividends, and delistings in RAM (with `Arc<str>` key interning) before curation — small for real `qmSplits` (~19k) + `qmDividends` (~500k) + Pass 6 delistings, unlike `eodPrices`.
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding and no direct MongoDB/PostgreSQL connections. The TypeScript read-only PostgreSQL → TSV exporter (`apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts`) generates `provider_mapping.tsv`, `listing_currencies.tsv`, and Pass 6 `delistings.tsv` for all `curate-etl` commands.
|
||||
|
||||
## `curate-fx-1d` Command (`M1.2ac`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_fx.rs`) wiring `RawBsonChunkReader`, `decode_eod_price_chunks`, the zero-copy `teMarketData` decoder (`src/bson_te_market_data.rs`, `decode_te_market_data_chunks`), and `curate_and_write_fx_1d` into an atomically published `<out>/fx_1d/part.parquet` dataset with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-fx-1d \
|
||||
--eod-prices eodPrices.bson \
|
||||
--te-market-data teMarketData.bson \
|
||||
[--te-symbol USDCAD] \
|
||||
--out ./out
|
||||
```
|
||||
|
||||
Inputs and output:
|
||||
- `--eod-prices <path>`: concatenated raw BSON (`mongodump` `eodPrices.bson`). Streams through `decode_eod_price_chunks` and keeps only documents whose `eodSearchCode` is **exact** `"CAD.FOREX"` (other symbols are counted in `eod_other_symbol_skipped`; `eodPrices.volume` is ignored when mapping to `FxDailyBar`).
|
||||
- `--te-market-data <path>`: concatenated raw BSON (`mongodump` `teMarketData.bson`). Streams through `decode_te_market_data_chunks` and keeps only documents whose `teSymbol` matches `--te-symbol` (ASCII case-insensitive, default `USDCAD`).
|
||||
- `--te-symbol <sym>` *(optional)*: target `teMarketData.teSymbol` to match (default: `USDCAD`; must match the USD/CAD allowlist `ALLOWED_TE_SYMBOLS` = `["USDCAD"]` ASCII case-insensitively so non-USD/CAD instruments cannot enter `fx_1d`).
|
||||
- `--out <dir>`: dataset root where `fx_1d/part.parquet` is atomically published.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Invalid, missing, duplicate (including duplicate `--te-symbol`), or unknown flags exit non-zero with usage on stderr. Any runtime error (missing input file, invalid `--out`, unsupported/blank `--te-symbol`, truncated/corrupt/oversized BSON framing or element bytes in either input, zero decoded bars across both inputs, or zero publishable rows after FX curation) prints a single-line stderr message, exits non-zero, and leaves any pre-existing `<out>/fx_1d/part.parquet` byte-identical.
|
||||
|
||||
### `teMarketData` Input Contract & `t` Epoch Unit Rule
|
||||
|
||||
- Document shape (derived from `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`; field names isolated as `pub const FIELD_*` in `src/bson_te_market_data.rs`):
|
||||
- Top-level `teSymbol: string` and `daily: [{ t, o, h, l, c, pc, ac }]`.
|
||||
- `monthly`, `pc`, `ac`, and all unknown fields are skipped without decoding their values.
|
||||
- `daily` is captured lazily as a raw element and only decoded after `teSymbol` matches `--te-symbol`, so field ordering (`daily` before `teSymbol`) never causes false rejects on non-target symbols.
|
||||
- Numeric fields `t`, `o`, `h`, `l`, `c` accept BSON `Int32`, `Int64`, or `Double`. Malformed points (non-document element, missing field, wrong type, `NaN`/`±Inf`, out-of-`i32`-range date) are counted under per-reason reject counters and skipped without panicking.
|
||||
- **`t` epoch unit rule** (`TE_EPOCH_MILLIS_THRESHOLD = 100_000_000_000`):
|
||||
- `|t| >= 100_000_000_000` → treated as Unix **milliseconds** (`session_date = floor(t / 86_400_000)` UTC).
|
||||
- `|t| < 100_000_000_000` → treated as Unix **seconds** (`session_date = floor(t / 86_400)` UTC).
|
||||
- Uses `unsigned_abs()` + `div_euclid` (flooring pre-1970 negative timestamps to the earlier UTC day) and checked `i32::try_from` bounds checking.
|
||||
- Merge precedence (`CAD.FOREX` wins on overlap, `teMarketData` fills interior gaps and post-EOD tail), read-only 1% overlap cross-check, and conservative `23:59:59.999999 UTC` `ts`/`known_at` stamping stay delegated unchanged to `curate_and_write_fx_1d`.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-fx-1d` prints deterministic `key=value` lines to stdout (`eod_bson`, `te_bson`, `builder`, `curate`, `write`, and `timing`):
|
||||
|
||||
- **EOD BSON:**
|
||||
`eod_bson.docs_framed == eod_bson.docs_in == eod_bson.decoded + eod_bson.rejected`
|
||||
`eod_bson.decoded == eod_bson.cad_forex_kept + eod_bson.other_symbol_skipped`
|
||||
`eod_bson.cad_forex_kept == builder.eod_in`
|
||||
- **TE BSON:**
|
||||
`te_bson.docs_framed == te_bson.docs_in == te_bson.matched + te_bson.other_symbol + te_bson.docs_rejected`
|
||||
`te_bson.points_in == te_bson.points_decoded + te_bson.points_rejected`
|
||||
`te_bson.points_decoded == builder.te_in`
|
||||
- **Stage & Write:**
|
||||
`curate.rows_in == curate.rows_out == write.rows_written`
|
||||
|
||||
### `bench-curate-fx-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `eodPrices.bson` (`CAD.FOREX` with interior gaps, invalid/inconsistent/duplicate bars, skipped other symbols, and malformed docs) and `teMarketData.bson` (`USDCAD` with overlap including >1% cross-check mismatches, interior gap fills, post-EOD tail, mixed seconds/ms `t` across `Int32`/`Int64`/`Double`, malformed points, ignored `monthly`, and skipped other symbols) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-fx-cmd [rows]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`, post-fix `curate-fx-1d` with full-document corruption scanning, default `20,000` rows; two back-to-back runs with identical checksum `0x45ac34f4ddf4407c`):
|
||||
|
||||
- Input: `rows=20000`, `eod_docs=18936` (`2,706,485 B`), `te_docs=3`, `te_points=5000` (`443,498 B`)
|
||||
- Decode counts: `eod_kept=14918`, `eod_other=3936`, `eod_rejected=82`, `te_matched=1`, `te_other=2`, `te_decoded=4925`, `te_rejected=75`
|
||||
- Output: `rows_out=17524` (`eod_out=14569`, `te_out=2955`, `te_superseded=1970`), `files=1`, `row_groups=1`, `bytes=733752`, `read_back_rows=17524`, `overlap: checked=1970 within_tol=1870 mismatched=100 max_rel=0.025000`
|
||||
- Run 1: `decode=4.33 ms` (`4,614,470 rows/s`, `693.11 MB/s`), `curate=0.64 ms` (`30,806,515 rows/s`), `write=24.99 ms` (`701,274 rows/s`, `28.00 MB/s`), `total=29.97 ms` (`667,398 rows/s`), `checksum=0x45ac34f4ddf4407c`
|
||||
- Run 2: `decode=4.26 ms` (`4,694,381 rows/s`, `705.11 MB/s`), `curate=0.67 ms` (`29,800,156 rows/s`), `write=15.27 ms` (`1,147,886 rows/s`, `45.84 MB/s`), `total=20.19 ms` (`990,462 rows/s`), `checksum=0x45ac34f4ddf4407c`
|
||||
|
||||
### Known Limits
|
||||
|
||||
- **Unverified live `teMarketData` schema & `t` unit:** `bson_te_market_data::FIELD_*` constants and the `|t| >= 100_000_000_000` ms/s threshold are derived from `market-data-fetch.action.ts` and have not yet been verified against a live `mongodump` export.
|
||||
- **`eodPrices` `volume` field:** `decode_eod_price_chunks` still requires a non-negative `volume` field on `CAD.FOREX` documents (ignored when mapping to `FxDailyBar`); if a live `CAD.FOREX` dump omits `volume`, those docs will surface in `eod_bson.rejected (missing=...)`.
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB connection, and `fx_1m` is out of scope.
|
||||
|
||||
## `curate-shorts` Command (`M1.2ad`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_shorts.rs`) wiring `RawBsonChunkReader`, the zero-copy `ceoShorts` decoder (`src/bson_ceo_shorts.rs`, `decode_ceo_shorts_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_shorts` into an atomically published `<out>/shorts/part.parquet` dataset (`+4` Canadian TSX business days at `17:00 America/Toronto`, `source = "ceo_shorts"`) with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-shorts \
|
||||
--ceo-shorts ceoShorts.bson \
|
||||
--provider-mapping provider_mapping.tsv \
|
||||
--out ./out \
|
||||
--shares-short-field <name> \
|
||||
[--key-field symbol] \
|
||||
[--report-date-field timestamp] \
|
||||
[--net-change-field <name>] \
|
||||
[--pct-float-field <name>] \
|
||||
[--mapping-source ceo]
|
||||
```
|
||||
|
||||
Inputs and output:
|
||||
- `--ceo-shorts <path>` *(required)*: concatenated raw BSON (`mongodump` `ceoShorts.bson`).
|
||||
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
|
||||
- `--out <dir>` *(required)*: dataset root where `shorts/part.parquet` is atomically published.
|
||||
- `--shares-short-field <name>` *(required, no default)*: BSON field name holding the short-share count (intentionally has no default because live `ceoShorts` value field names are unverified in the repo).
|
||||
- `--key-field <name>` *(optional, default `symbol`)*: BSON field name holding the security key (passed verbatim to `provider_mapping` without trimming or suffix stripping).
|
||||
- `--report-date-field <name>` *(optional, default `timestamp`)*: BSON field name holding the report period date.
|
||||
- `--net-change-field <name>` *(optional)*: BSON field name holding optional net change vs. prior report.
|
||||
- `--pct-float-field <name>` *(optional)*: BSON field name holding optional percent-of-float short.
|
||||
- `--mapping-source <name>` *(optional, default `ceo`)*: `provider_mapping` source name used to resolve `(mapping_source, key, report_date) -> listing_id`.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted (in the separated `--flag value` form, a following `--...` token is rejected as a missing value; use `--flag=value` for literal paths starting with `--`). Missing required flags (including `--shares-short-field`), duplicate flags, unknown flags, empty/blank field names or `--mapping-source`, positional arguments, and any two configured roles resolving to the same BSON field name (checked after applying defaults) exit non-zero with usage on stderr. Any runtime error (missing input file, malformed or overlapping `provider_mapping.tsv`, truncated/corrupt/oversized BSON framing or element bytes, out-of-range `report_date`, or obstructed `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/shorts/part.parquet` byte-identical).
|
||||
|
||||
### `ceoShorts` Decoder Rules
|
||||
|
||||
- Scans and validates every element and nested raw value (including unused strings, embedded documents, and arrays) of each `RawDocument` to completion before applying semantic skip priority (`key` → `report_date` → `shares_short`) so structural BSON corruption always fails closed with a typed error carrying the absolute byte offset.
|
||||
- `key`: BSON UTF-8 `String` passed through verbatim (empty/whitespace-only, missing, or wrong type skipped and counted).
|
||||
- `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)` checked to `i32`), or `Int32` / `Int64` / integral finite `Double` via `te_epoch_i64_to_session_date` (seconds vs. milliseconds UTC). Non-finite or fractional `Double`s skip under `invalid_date`; values overflowing `i64`/`i32` skip under `date_oor`.
|
||||
- `shares_short`: strict BSON `Double`, `Int32`, or `Int64` (numeric strings are rejected as `wrong_shares_type`). Sign and finiteness validation remains in `build_shorts`.
|
||||
- `net_change` / `pct_float`: unconfigured, absent, or BSON `Null` → `None`; wrong BSON type → `None` and counted in `nulled_wrong_type` (only on emitted rows).
|
||||
- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0`, leaving any pre-existing `shorts/part.parquet` untouched.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-shorts` prints deterministic `key=value` lines to stdout (`ceo_bson`, `builder`, `curate`, `write`, and `timing`):
|
||||
|
||||
- **BSON Decode:** `ceo_bson.docs_framed == ceo_bson.docs_in == ceo_bson.rows_out + ceo_bson.skipped`
|
||||
- **Builder:** `ceo_bson.rows_out == builder.rows_in == builder.rows_out + builder.invalid_shares + builder.dup_collapsed + builder.dup_conflict`
|
||||
- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.coll_collapsed + curate.coll_dropped`, and `write.rows_written == curate.rows_out`
|
||||
|
||||
### `bench-curate-shorts-command`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing a concatenated-BSON `ceoShorts` file (default `700,000` docs, `12,500` keys distributed across all 218 semi-monthly dates `2017-04-15..=2026-04-30`, mixing `DateTime`/`Int32`/`Int64`/`Double` dates, optional fields with nulls and wrong types, ~0.5% semantically skipped docs, invalid `shares_short`, explicit identical/conflicting same-key duplicates, explicit identical/conflicting primary+alias collisions, ticker-reuse gap dates, and unmapped keys) plus `provider_mapping.tsv` into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row count, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-shorts-command [rows]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`, Linux `6.8.0-151-generic`, AMD Ryzen 9 9950X3D 16-Core Processor, default `700,000` rows; two back-to-back runs with identical checksum `0xa759372dd4476f50`):
|
||||
|
||||
- Input: `rows=700000`, `docs_framed=700000`, `bytes_read=67925127` (`64.78 MiB`), `keys=12500`, `peak_chunk_bytes=8388608` (`8 MiB`)
|
||||
- Decode counts: `rows_out=696570`, `skipped=3430`, `nulled_net_change=6860`, `nulled_pct_float=5717`
|
||||
- Output: `rows_out=656911` (`93.84%` retained), `listings_out=12345`, `dropped_unmapped=15229`, `dup_collapsed=3500`, `dup_conflict=7000`, `coll_collapsed=3500`, `coll_dropped=7000`, `invalid_shares=3430`, `files=1`, `row_groups=1`, `bytes=5791000`, `read_back_rows=656911`
|
||||
- Run 1: `decode=141.29 ms` (`4,954,433 rows/s`, `458.49 MB/s`), `curate=130.95 ms` (`5,319,222 rows/s`), `write=93.49 ms` (`7,026,896 rows/s`, `59.08 MB/s`), `total=365.73 ms` (`1,914,000 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xa759372dd4476f50`
|
||||
- Run 2: `decode=152.15 ms` (`4,600,763 rows/s`, `425.76 MB/s`), `curate=130.95 ms` (`5,319,464 rows/s`), `write=86.38 ms` (`7,604,711 rows/s`, `63.93 MB/s`), `total=369.48 ms` (`1,894,564 rows/s`), `peak_chunk_bytes=8388608`, `checksum=0xa759372dd4476f50`
|
||||
|
||||
### Known Limitations
|
||||
|
||||
- **Unverified live `ceoShorts` field names and `timestamp` unit/timezone:** `ceoShorts` value field names (`--shares-short-field`, `--net-change-field`, `--pct-float-field`, `--key-field`) and `timestamp` unit/timezone are unverified against live QA MongoDB data. Confirm them before the first real run with the read-only field-shape probe:
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections ceoShorts --out <path>
|
||||
```
|
||||
- **Single-threaded file-to-file execution:** no `rayon` sharding, no direct MongoDB/PostgreSQL connection, and `pct_float` is passed through as supplied rather than derived from shares outstanding.
|
||||
|
||||
## `curate-events` Command (`M1.2ae`)
|
||||
|
||||
End-to-end file-to-Parquet CLI command (`src/run_curate_events.rs`) wiring `RawBsonChunkReader`, the zero-copy `qmFilings` + `qmEarnings` decoders (`src/bson_qm_events.rs`, `decode_qm_filings_chunks`, `decode_qm_earnings_chunks`), `load_provider_mapping_tsv`, and `curate_and_write_events` into atomically published `<out>/events/year=YYYY/part.parquet` partitions with zero extra crates and no database connections.
|
||||
|
||||
### Invocation
|
||||
|
||||
```bash
|
||||
curate-etl curate-events \
|
||||
--qm-filings qmFilings.bson \
|
||||
--qm-earnings qmEarnings.bson \
|
||||
--provider-mapping provider_mapping.tsv \
|
||||
--out ./out \
|
||||
--filings-form-type-field <name> \
|
||||
[--filings-key-field symbol] \
|
||||
[--filings-timefiled-field timefiled] \
|
||||
[--filings-filing-id-field <name>] \
|
||||
[--filings-url-field <name>] \
|
||||
[--earnings-key-field qmSearchCode] \
|
||||
[--earnings-report-date-field reportDate] \
|
||||
[--earnings-announce-time-field announceTime] \
|
||||
[--earnings-fiscal-period-end-field <name>] \
|
||||
[--earnings-actual-eps-field <name>] \
|
||||
[--earnings-revenue-field <name>] \
|
||||
[--mapping-source qm]
|
||||
```
|
||||
|
||||
Inputs and verified vs. configured field names:
|
||||
- `--qm-filings <path>` *(required)*: concatenated raw BSON (`mongodump` `qmFilings.bson`).
|
||||
- `--qm-earnings <path>` *(required)*: concatenated raw BSON (`mongodump` `qmEarnings.bson`).
|
||||
- `--provider-mapping <path>` *(required)*: headerless 5-column TSV (same format as `curate-bars-1d`).
|
||||
- `--out <dir>` *(required)*: dataset root where `events/year=YYYY/part.parquet` is atomically published. Upfront path validation rejects `--out` or `<out>/events` being a regular file, or any input path resolving to `--out` or inside `<out>/events/...` (preventing input clobbering).
|
||||
- **Verified defaults** (grounded in `apps/stock/data-ingestion/src/handlers/qm/actions/filings.action.ts`, `events.action.ts`, and `design/DATA-CONTRACTS.md` §1):
|
||||
- `qmFilings`: `--filings-key-field` (`symbol`; note `filings.action.ts` does **not** add `qmSearchCode` to stored docs despite the upsert key), `--filings-timefiled-field` (`timefiled`).
|
||||
- `qmEarnings`: `--earnings-key-field` (`qmSearchCode`), `--earnings-report-date-field` (`reportDate`), `--earnings-announce-time-field` (`announceTime`).
|
||||
- **Caller-configured fields (no defaults):**
|
||||
- `--filings-form-type-field <name>` *(required, no default)*: BSON field holding the EDGAR/SEDAR+ form type string.
|
||||
- Optional: `--filings-filing-id-field`, `--filings-url-field`, `--earnings-fiscal-period-end-field`, `--earnings-actual-eps-field`, `--earnings-revenue-field`.
|
||||
- `--mapping-source <name>` *(optional, default `qm`)*: `provider_mapping` source name used to resolve `(mapping_source, key, event_date) -> listing_id` on each event's exact Eastern local calendar date.
|
||||
- **`consensusEps` exclusion:** `consensusEps` is structurally omitted from `RawQmEarning` / `QmEarning` and explicitly rejected (case-insensitively as `consensusEps` / `consensus_eps`) on any earnings field flag per `design/DATA-CONTRACTS.md` §1.
|
||||
|
||||
Both `--flag value` and `--flag=value` forms are accepted. Missing required flags (including `--filings-form-type-field`), duplicate flags, unknown flags, blank field names or `--mapping-source`, colliding role mappings within a collection, or any `consensusEps` mapping exit non-zero with usage on stderr. Any runtime error (missing input file, malformed/overlapping `provider_mapping.tsv`, truncated/corrupt BSON in either stream, or obstructed/overlapping `--out`) prints a single-line stderr message, exits non-zero, and returns before touching `--out` (leaving any pre-existing `<out>/events/` partitions byte-identical).
|
||||
|
||||
### `qmFilings` & `qmEarnings` Decoder Rules
|
||||
|
||||
- Scans and structurally validates every element and nested document/array/JS-with-scope (depth limit `128`) of each `RawDocument` before applying semantic skip rules so structural corruption always fails closed with a typed error carrying the absolute byte offset.
|
||||
- `qmFilings` deterministic skip priority: `key` → `timefiled` → `form_type` (all required non-blank UTF-8 `String`s passed verbatim; timestamp syntax remains in `events::build_events`). Optional `filing_id` / `url`: unconfigured, absent, `Null`, or blank string → `None`; wrong BSON type → `None` + `nulled_wrong_type_*` (emitted rows only).
|
||||
- `qmEarnings` deterministic skip priority: `key` → `report_date` → `announce_time`. `report_date` accepts BSON `DateTime` (UTC epoch day checked to `i32`) or strict `YYYY-MM-DD` `String`. Optional `fiscal_period_end` accepts absent/`Null`/blank (`None`), `DateTime` or strict `YYYY-MM-DD` (`Some(i32)`), wrong BSON type (`nulled_wrong_type_fiscal_period_end`), or malformed/out-of-range (`nulled_invalid_fiscal_period_end`, emitted rows only). Optional `actual_eps` / `revenue` accept absent/`Null` (`None`), `Double`/`Int32`/`Int64` (`Some(f64)`), or wrong BSON type (`nulled_wrong_type_*`, emitted rows only).
|
||||
- Empty or all-unmapped inputs return `Ok` with `rows_written=0` and `files=0` without creating `<out>/events` or modifying any pre-existing partitions.
|
||||
|
||||
### Report Counters & Conservation Invariants
|
||||
|
||||
On success, `curate-events` prints deterministic `key=value` lines to stdout (`filings_bson`, `earnings_bson`, `builder`, `curate`, `write`, ascending `years`, and `timing`):
|
||||
|
||||
- **Filings BSON:** `filings_bson.docs_framed == filings_bson.docs_in == filings_bson.rows_out + filings_bson.skipped`, and `filings_bson.rows_out == builder.filings_in`.
|
||||
- **Earnings BSON:** `earnings_bson.docs_framed == earnings_bson.docs_in == earnings_bson.rows_out + earnings_bson.skipped`, and `earnings_bson.rows_out == builder.earnings_in`.
|
||||
- **Builder:** `builder.filings_in == builder.filings_out + malformed_ts + unknown_zone + invalid_dt + filing_dup`, `builder.earnings_in == builder.earnings_out + earnings_oor + earnings_dup + earnings_conflict`, `builder.earnings_out == linked + lagged_1605`, and `builder.rows_out == builder.filings_out + builder.earnings_out`.
|
||||
- **Stage & Write:** `curate.rows_in == builder.rows_out == curate.rows_out + curate.dropped_unmapped + curate.listing_dup_collapsed`, and `write.rows_written == curate.rows_out`.
|
||||
|
||||
### `bench-curate-events-cmd`
|
||||
|
||||
Fixed-seed (`std`-only SplitMix64) end-to-end file→Parquet benchmark synthesizing `provider_mapping.tsv` (`5,000` keys with ~2% unmapped), `qmFilings.bson` (~98.5% of `rows`, mixed EST/EDT `2015..=2025`, EDGAR + SEDAR+ form types, ~0.5% skips/wrong-type optionals), and `qmEarnings.bson` (~1.5% of `rows`, mixed `DateTime`/`YYYY-MM-DD`, linked & unlinked rows, `consensusEps` present and ignored, ~0.5% skips/wrong-type optionals) into a temp dir, timing `decode` / `curate` / `write` separately, verifying Parquet footer row counts across all UTC year partitions, extrapolating to the full `30.52M + 444.9k` (`30,964,900` rows) QA MongoDB dataset, and cleaning up on drop:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-curate-events-cmd [rows]
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-29`, default `500,000` rows; two back-to-back runs with identical checksum `0x2076c3a54dc2403e`):
|
||||
|
||||
- Input: `rows=500000`, `filings_docs=492500` (`71,019,899 B`), `earnings_docs=7500` (`1,233,791 B`), `keys=5000`, `peak_chunk_bytes=8388608` (`8 MiB`)
|
||||
- Decode counts: `filings_out=490021`, `filings_skipped=2479`, `earnings_out=7462`, `earnings_skipped=38`
|
||||
- Output: `rows_out=487589` (`97.52%` retained; `filings_out=480258`, `earnings_out=7331`), `listings_out=4900`, `linked=3008`, `lagged_1605=4452`, `unmapped=9892`, `files=12`, `row_groups=12`, `bytes=14125012`, `read_back_rows=487589`
|
||||
- Run 1: `decode=136.07 ms` (`3,674,605 rows/s`, `506.41 MB/s`), `curate=278.55 ms` (`1,786,003 rows/s`), `write=446.48 ms` (`1,092,064 rows/s`, `30.17 MB/s`), `total=861.10 ms` (`580,654 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `53.3 s` (`0.89 min`) single-core**, `checksum=0x2076c3a54dc2403e`
|
||||
- Run 2: `decode=136.68 ms` (`3,658,115 rows/s`, `504.14 MB/s`), `curate=264.16 ms` (`1,883,251 rows/s`), `write=437.86 ms` (`1,113,564 rows/s`, `30.76 MB/s`), `total=838.71 ms` (`596,155 rows/s`), **extrapolation to `30.52M` filings + `444.9k` earnings (`30.96M` rows): `51.9 s` (`0.87 min`) single-core**, `checksum=0x2076c3a54dc2403e`
|
||||
|
||||
### Known Limitations
|
||||
|
||||
- **Unverified live `qmFilings` / `qmEarnings` field names:** `--filings-form-type-field`, optional filings fields (`filing_id`, `url`), optional earnings fields (`fiscal_period_end`, `actual_eps`, `revenue`), and whether live `qmFilings` documents carry `qmSearchCode` vs. `symbol` are unverified against live QA MongoDB. Confirm them before the first real run with the read-only field-shape probe:
|
||||
```bash
|
||||
bun run apps/stock/data-pipeline/src/security-master/probe-source-field-shapes.ts --collections qmFilings,qmEarnings --out <path>
|
||||
```
|
||||
- **Key-namespace alignment between `qmFilings` and `qmEarnings`:** `qmFilings` defaults to `symbol` while `qmEarnings` defaults to `qmSearchCode`. Both exports must carry an unambiguous key in the `provider_mapping` namespace (for example, the QuoteMedia security ID, not a bare ticker — the security master records distinct QuoteMedia IDs such as `VOY:CNX` and `VOY:CC` for the same symbol and exchange, so switching earnings to bare `symbol` can merge distinct identities or drop rows). If a live `qmFilings` export lacks that unambiguous key, prepare the export with verified QuoteMedia IDs and exclude unresolved rows rather than downgrading `qmEarnings` to bare tickers.
|
||||
- **In-RAM buffering & single-threaded execution:** decoded filings and earnings are buffered in RAM (with shared `Arc<str>` key interning) before sorting/curation; `rayon` key-sharded streaming, direct MongoDB/PostgreSQL connections, and M2 `fundamentals_pit` joins remain out of scope.
|
||||
|
||||
## Read-Only MongoDB URI Safety Guard (`M1.2ak`)
|
||||
|
||||
Pure, offline, `std`-only MongoDB URI safety guard (`src/mongo_safety.rs`, zero new crates, no sockets, no DNS resolution, no subprocesses) that ports the QA MongoDB target-classification rules from `apps/stock/config/src/env-safety.ts` before any Rust code may open a MongoDB connection.
|
||||
|
||||
### Public API
|
||||
|
||||
- `parse_mongo_target(uri: &str) -> Result<MongoTarget, MongoSafetyError>` — parses `mongodb://` and `mongodb+srv://` URIs, splits authority at `/` or `?` (never `#`), percent-decodes usernames (strict UTF-8, without converting `+` to space), iteratively percent-decodes seed hosts up to `8` passes (handling bracketed IPv6 with zone IDs and `mongodb://` `.sock` Unix domain sockets), and rejects control characters, Unicode whitespace, unencoded `#` or multiple `@` in authority, `@` in path/query when authority has no credentials, invalid percent-encoding, and forbidden decoded host characters.
|
||||
- `is_qa_mongo_target(target: &MongoTarget, local_hosts: &LocalHosts) -> bool` — returns `true` when any seed host is loopback (`localhost`, trailing-dot/case variants, `0.0.0.0`, `127.0.0.0/8` in dotted, shorthand `127.1`, decimal `2130706433`, hex `0x7f000001`, octal `0177.0.0.1`, leading-zero decimal `0127.0.0.1`, IPv6 `::` / `::1` with optional zone ID, and IPv4-mapped `::ffff:127.0.0.0/8` / `::ffff:0.0.0.0`) or matches an injected `LocalHosts` entry on port `27017` (or omitted/default port), regardless of database path.
|
||||
- `LocalHosts` — deterministic injected set (`LocalHosts::empty()`, `new(...)`, `from_hostname_and_ips(...)`, `with_host(...)`, `contains(...)`) plus `LocalHosts::detect()`, which is **best-effort** and `std`-only (reads `HOSTNAME` and `/etc/hostname` without NIC enumeration or DNS lookups; multi-homed callers should inject LAN IPs via `LocalHosts::from_hostname_and_ips`).
|
||||
- `assert_read_only_mongo_uri(uri, policy: &ReadOnlyPolicy, local_hosts) -> Result<ValidatedReadOnlyMongoUri, MongoSafetyError>` — fail-closed guard returning a `ValidatedReadOnlyMongoUri` proof token whose fields are private and whose only public constructor is `assert_read_only_mongo_uri`.
|
||||
- **Password redaction:** `ValidatedReadOnlyMongoUri`'s `Display`, `Debug`, and `redacted()` always replace the password between the first `:` and `@` in userinfo with `[REDACTED]`. `MongoSafetyError` variants never store raw URIs, raw authorities, or passwords.
|
||||
- **No URI query-option parsing:** beyond authority/remainder splitting and the no-credentials remainder-`@` check, URI query options are intentionally not parsed or validated (matching `apps/stock/config/src/env-safety.ts`).
|
||||
- **Unix domain sockets:** `.sock` Unix-socket hosts (e.g. `%2Ftmp%2Fmongodb-27017.sock`) are never classified as QA targets (same as `env-safety.ts`).
|
||||
|
||||
### Intentional Stricter-than-`env-safety.ts` Differences
|
||||
|
||||
Target classification (`parse_mongo_target` + `is_qa_mongo_target`) mirrors all five `test/unit/environment-safety*.test.ts` suites (including the 42-case `hostSpellings × ports` matrix, the 3,000-iteration seeded percent-encoding sweep, and all 30,000 cases per authority-split fuzz seed `0x7e28` / `0x28e7`) with identical QA / not-QA / rejected outcomes **except for the intentional stricter rules listed below**. `parse_mongo_target`, `is_qa_mongo_target`, and `assert_read_only_mongo_uri` are deliberately stricter than `env-safety.ts` in eight ways for read-only ETL safety:
|
||||
|
||||
1. **Global case-insensitive `trading_admin` ban:** rejects percent-decoded `trading_admin` (ASCII case-insensitive) on **any** host (QA, dev, or remote), even if a caller adds it to `ReadOnlyPolicy::allowed_read_users` (whereas `env-safety.ts` only checks `username === 'trading_admin'` on QA targets for dev `dataPipeline`).
|
||||
2. **Mandatory QA credentials & allowlist:** any QA target must provide a username present in `ReadOnlyPolicy::allowed_read_users` (default: `["studio_stock_bot_read"]`, exact match after percent-decoding); missing credentials and non-allowlisted users are rejected.
|
||||
3. **Rejection of empty, malformed, or invalid bracketed-IPv6 host segments:** URIs like `mongodb://u:p@bad:port,localhost:27017/stock`, `mongodb://u:p@localhost:27018,,localhost:27017/stock`, or `mongodb://u:p@[fe80::g]:27017,localhost:27017/stock` still classify as QA in `parse_mongo_target` / `is_qa_mongo_target` (matching `env-safety.ts`), and are rejected fail-closed with `MalformedHostSegment` by `assert_read_only_mongo_uri` (matching `libs/core/config/src/schemas/database.schema.ts`). Single-seed malformed bracketed IPv6 literals such as `[fe80::g]:27017` are rejected with `NoValidHosts`.
|
||||
4. **Strict `mongodb+srv://` seed rules:** `assert_read_only_mongo_uri` rejects `mongodb+srv://` URIs with multiple hosts or any explicit `:` port suffix (`InvalidSrvTarget`), matching `database.schema.ts`.
|
||||
5. **No-credentials remainder-`@` check and strict username percent-decoding:** rejects unencoded `@` in path/query when authority has no `@` (matching `database.schema.ts`), and rejects invalid percent-encoding in the username (e.g. `%ff`, failing closed with `InvalidUsernameEncoding` instead of falling back to the raw username string).
|
||||
6. **No silent trimming of leading/trailing whitespace:** `env-safety.ts` calls `uri.trim()` before checking `/\s/`, whereas `parse_mongo_target` rejects any Unicode whitespace anywhere in the URI (including leading or trailing spaces) with `ForbiddenWhitespace`.
|
||||
7. **Leading-zero decimal LAN IPs matched against `LocalHosts`:** `is_qa_mongo_target` normalizes 4-part decimal IPv4 spellings with leading zeros (e.g. `192.168.001.050:27017`) before checking `LocalHosts`, flagging them as QA even where `env-safety.ts` does not.
|
||||
8. **Machine's own zoned link-local IPv6 matched against `LocalHosts`:** `is_qa_mongo_target` strips `%zone` suffixes when matching bracketed IPv6 hosts against `LocalHosts` (e.g. `[fe80::1234:5678%25eth0]:27017`), flagging the machine's own link-local IPv6 on port `27017` as QA even where `env-safety.ts` misses it.
|
||||
|
||||
## Driver-Independent MongoDB Raw-BSON Cursor Seam (`M1.2al`)
|
||||
|
||||
Library-only, driver-independent read-only MongoDB raw-BSON cursor seam (`src/mongo_stream.rs`, tested offline in `src/mongo_stream_tests.rs`) bridging the read-only safety model (`src/mongo_safety.rs`) into the existing `bson_stream` zero-copy decoders (`RawBsonChunkReader` and `decode_*_stream`) with zero new dependencies and zero CLI/command wiring yet.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- **No new dependency added:** `tools/curate-etl/Cargo.toml` and `Cargo.lock` are unchanged (still three exact-pinned direct dependencies: `bson = "=3.1.0"`, `parquet = "=60.2.0"`, and `rayon = "=1.12.0"`). `src/mongo_stream.rs` contains no `mongodb::` driver paths yet.
|
||||
|
||||
### Public API & Sealing Guarantees
|
||||
|
||||
- **Closed collection allowlist (`SourceCollection`):** 8 variants matching `RAW_BSON_EXPORT_COLLECTIONS` in `apps/stock/data-pipeline/src/security-master/export-raw-bson.ts` in exact order (`eodPrices`, `qmSplits`, `qmDividends`, `qmPrices`, `teMarketData`, `ceoShorts`, `qmFilings`, `qmEarnings`). No API accepts a free-form collection name string.
|
||||
- **Typed read spec (`MongoReadSpec`, `MongoDateRange`, `FilterDateValue`, `build_filter_document`):** validates `batch_size` (`1..=100_000`, default `4_096`), `limit` (`1..=i64::MAX`), `max_doc_bytes` (`>= 5`, default `16 MiB + 16 KiB`), non-blank `key_eq`, and half-open `[gte, lt)` `date_range` (rejected on `teMarketData`; `qmFilings.timefiled` server-side string ranges require Eastern calendar-day boundaries `YYYY-MM-DD` so neither UTC offsets nor fall-back DST local-string inversions can silently miss filings), building `bson::Document` via `Document::from_iter(...)`.
|
||||
- **Driver-independent seam (`RawDocumentSource`, `SliceRawDocumentSource`, `VecRawDocumentSource`) + bounded-memory `io::Read` adapter (`RawBsonCursorReader<S>`):** validates every raw BSON frame (`len >= 5`, `len <= max_doc_bytes`, 4-byte LE length prefix `== len`, trailing `0x00`), copies directly into the caller's buffer when it fits, spills only the unread tail of a single current document into a reused `pending` buffer, tracks `docs_read()` / `bytes_read()` / `pending_capacity()`, and surfaces mid-stream errors as sticky `io::Error`s carrying `MongoStreamError`.
|
||||
- **Error redaction (`MongoStreamError`, `MongoStreamError::redacted_source`):** never stores raw URIs or passwords; sanitizes raw URI, raw password, percent-decoded password, and embedded `mongodb://` / `mongodb+srv://` userinfo passwords (including passwords containing punctuation such as `,`, `;`, quotes, brackets, or `@`) to `[REDACTED]` (reusing `mongo_safety::redact_mongo_uri_password`).
|
||||
|
||||
### `bench-mongo-stream`
|
||||
|
||||
Offline fixed-seed benchmark comparing decoding `1,000,000` synthetic `eodPrices` documents (`285,639,152` bytes) through plain `io::Cursor<&[u8]>` → `decode_eod_price_stream` vs. `SliceRawDocumentSource` → `RawBsonCursorReader` → `decode_eod_price_stream`:
|
||||
|
||||
```bash
|
||||
cargo run -p curate-etl --release --offline -- bench-mongo-stream 1000000
|
||||
```
|
||||
|
||||
Measured locally (`2026-11-30`, two back-to-back offline runs on the final code with identical stats `decoded=995008`, `rejected=4992`, and checksum `0x05af9d2746d1b5e3`):
|
||||
|
||||
- **Run 1:** plain `264.49 ms` (`3,780,816 docs/s`, `1,029.92 MiB/s`) vs. `RawBsonCursorReader` `263.32 ms` (`3,797,634 docs/s`, `1,034.50 MiB/s`, ratio `1.004x`, `peak_pending_capacity=271 bytes`)
|
||||
- **Run 2:** plain `281.99 ms` (`3,546,241 docs/s`, `966.02 MiB/s`) vs. `RawBsonCursorReader` `270.90 ms` (`3,691,390 docs/s`, `1,005.56 MiB/s`, ratio `1.041x`, `peak_pending_capacity=271 bytes`)
|
||||
|
||||
### Not Done / Not Verified
|
||||
|
||||
- **Deferred `mongodb`-backed `MongoRawDocumentSource`:** the `mongodb` crate could not be fetched into the offline Cargo cache from the sandbox (`cargo fetch` failed with `failed to download from https://index.crates.io/config.json: [6] Could not resolve hostname (Could not resolve host: index.crates.io)`), and its driver-backed code has never been compiled. Adding exact-pinned `mongodb` (`Cargo.toml` / `Cargo.lock`) and `MongoRawDocumentSource::open(&ValidatedReadOnlyMongoUri, ...)` is deferred to a follow-up task once `mongodb` and its transitive crates are cached via a host-side `cargo fetch` or working crates.io egress.
|
||||
- **Live QA MongoDB cursor throughput on `quant`:** not run (all tests and benchmarks run 100% offline with zero network connections; live cursor throughput against read-only QA MongoDB on `quant` is deferred to the driver/CLI wiring and live-host verification tasks).
|
||||
|
||||
## Exporting Input Files (`data-pipeline`)
|
||||
|
||||
All `curate-*` commands read local TSV and concatenated raw-BSON files produced by the read-only exporters in `@stock-bot/data-pipeline`:
|
||||
|
||||
- **PostgreSQL security-master TSVs (`provider_mapping.tsv`, `listing_currencies.tsv`, `delistings.tsv`):** `apps/stock/data-pipeline/src/security-master/run-export-curate-inputs.ts`
|
||||
- **MongoDB concatenated raw-BSON files (`<collection>.bson`):** `apps/stock/data-pipeline/src/security-master/run-export-raw-bson.ts`
|
||||
|
||||
See [apps/stock/data-pipeline/README.md](../../apps/stock/data-pipeline/README.md#read-only-raw-bson-exporter-export-raw-bsonts) for flags, read-only safety guards, and the full M1 Step 2 execution order (`run-export-curate-inputs.ts` → `run-export-raw-bson.ts` → `curate-etl curate-*`).
|
||||
|
|
|
|||
File diff suppressed because it is too large
Load diff
627
tools/curate-etl/src/bson_ceo_shorts.rs
Normal file
627
tools/curate-etl/src/bson_ceo_shorts.rs
Normal file
|
|
@ -0,0 +1,627 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `ceoShorts` documents (`M1.2ad`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
|
||||
//! allocating a `bson::Document` or per-row `String`s, emitting borrowed [`CeoShortReport<&str>`]
|
||||
//! rows via a caller-supplied callback.
|
||||
//!
|
||||
//! # Unverified Live Schema & Explicit Field Configuration
|
||||
//!
|
||||
//! `apps/stock/data-ingestion/src/handlers/ceo/actions/get-shorts.action.ts` stores the upstream
|
||||
//! `positions[]` payload verbatim, and `design/DATA-CONTRACTS.md` §1 only establishes `timestamp`
|
||||
//! (the report period date). The value field names are not recorded anywhere in the repository, so
|
||||
//! callers must supply all field names explicitly via [`CeoShortsFieldNames`] (and the CLI
|
||||
//! requires `--shares-short-field` with no default).
|
||||
//!
|
||||
//! # Decoding & Validation Rules
|
||||
//! - Every element of each [`RawDocument`] is scanned to completion before applying semantic skip
|
||||
//! rules so structural BSON corruption always returns `Err(BsonCeoShortsError::CorruptBson)`
|
||||
//! rather than being masked by an earlier semantic skip.
|
||||
//! - `key`: BSON UTF-8 `String` passed through verbatim (no trimming, no suffix stripping); empty
|
||||
//! or whitespace-only strings are skipped (`skipped_empty_key`).
|
||||
//! - `report_date`: BSON `DateTime` (UTC calendar day via `timestamp_millis().div_euclid(86_400_000)`
|
||||
//! checked to `i32`), or `Int32` / `Int64` / integral finite `Double` converted via
|
||||
//! [`crate::bson_te_market_data::te_epoch_i64_to_session_date`] (seconds vs. milliseconds UTC).
|
||||
//! Non-finite or fractional `Double`s are skipped under `skipped_invalid_report_date`; values
|
||||
//! outside `i64`/`i32` epoch-day range are skipped under `skipped_report_date_out_of_range`.
|
||||
//! - `shares_short`: BSON `Double`, `Int32`, or `Int64` (strings are rejected as wrong type per
|
||||
//! crate convention). Sign and finiteness validation remains in [`crate::shorts::build_shorts`].
|
||||
//! - `net_change` and `pct_float`: optional; unconfigured, absent, or BSON `Null` yields `None`;
|
||||
//! wrong BSON type yields `None` and increments `nulled_wrong_type_*` (only on emitted rows).
|
||||
//! - Deterministic semantic skip priority: `key` → `report_date` → `shares_short`.
|
||||
//! - Conservation invariant: `docs_in == rows_out + skipped_total()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument};
|
||||
|
||||
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
|
||||
use crate::bson_te_market_data::{te_epoch_i64_to_session_date, MILLIS_PER_DAY};
|
||||
use crate::shorts::CeoShortReport;
|
||||
|
||||
/// Default BSON field name for the `ceoShorts` security key (`--key-field`).
|
||||
pub const DEFAULT_KEY_FIELD: &str = "symbol";
|
||||
/// Default BSON field name for the `ceoShorts` report period date (`--report-date-field`).
|
||||
pub const DEFAULT_REPORT_DATE_FIELD: &str = "timestamp";
|
||||
|
||||
/// Borrowed BSON field-name configuration for decoding `ceoShorts` documents.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CeoShortsFieldNames<'a> {
|
||||
pub key: &'a str,
|
||||
pub report_date: &'a str,
|
||||
pub shares_short: &'a str,
|
||||
pub net_change: Option<&'a str>,
|
||||
pub pct_float: Option<&'a str>,
|
||||
}
|
||||
|
||||
impl<'a> CeoShortsFieldNames<'a> {
|
||||
/// Validates that every configured field name is non-empty/non-blank and that no two
|
||||
/// configured roles point to the same BSON field name.
|
||||
pub fn validate(&self) -> Result<(), BsonCeoShortsError> {
|
||||
let mut roles: [(&'static str, Option<&str>); 5] = [
|
||||
("key", Some(self.key)),
|
||||
("report_date", Some(self.report_date)),
|
||||
("shares_short", Some(self.shares_short)),
|
||||
("net_change", self.net_change),
|
||||
("pct_float", self.pct_float),
|
||||
];
|
||||
|
||||
for &(role, name_opt) in &roles {
|
||||
if let Some(name) = name_opt {
|
||||
if name.trim().is_empty() {
|
||||
return Err(BsonCeoShortsError::InvalidFieldNames {
|
||||
detail: format!("field name for '{role}' must not be empty or blank"),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for i in 0..roles.len() {
|
||||
let (role_a, Some(name_a)) = roles[i] else {
|
||||
continue;
|
||||
};
|
||||
for &(role_b, name_b_opt) in &roles[i + 1..] {
|
||||
if let Some(name_b) = name_b_opt {
|
||||
if name_a == name_b {
|
||||
return Err(BsonCeoShortsError::InvalidFieldNames {
|
||||
detail: format!(
|
||||
"roles '{role_a}' and '{role_b}' cannot share BSON field '{name_a}'"
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Keep `roles` binding clean without unused_mut warnings.
|
||||
let _ = &mut roles;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while validating field configuration or decoding raw `ceoShorts` BSON.
|
||||
///
|
||||
/// Structural BSON framing or element errors fail closed and carry a `u64` byte offset;
|
||||
/// every variant's `Display` output is a single line.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum BsonCeoShortsError {
|
||||
/// Invalid [`CeoShortsFieldNames`] configuration (empty/blank name or duplicate role mapping).
|
||||
InvalidFieldNames { detail: String },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: u64,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: u64, declared_len: i32 },
|
||||
/// Underlying BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: u64, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonCeoShortsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::InvalidFieldNames { detail } => {
|
||||
write!(f, "invalid ceoShorts field configuration: {detail}")
|
||||
}
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonCeoShortsError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonCeoShortsError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonCeoShortsError::TruncatedDocument {
|
||||
offset: offset as u64,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonCeoShortsError::CorruptDocumentLength {
|
||||
offset: offset as u64,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => BsonCeoShortsError::CorruptBson {
|
||||
offset: offset as u64,
|
||||
detail,
|
||||
},
|
||||
other => BsonCeoShortsError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: other.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode accounting for `ceoShorts`.
|
||||
///
|
||||
/// Conservation invariant:
|
||||
/// `docs_in == rows_out + skipped_total()`
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonCeoShortsDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub skipped_missing_key: usize,
|
||||
pub skipped_wrong_key_type: usize,
|
||||
pub skipped_empty_key: usize,
|
||||
pub skipped_missing_report_date: usize,
|
||||
pub skipped_wrong_report_date_type: usize,
|
||||
pub skipped_invalid_report_date: usize,
|
||||
pub skipped_report_date_out_of_range: usize,
|
||||
pub skipped_missing_shares_short: usize,
|
||||
pub skipped_wrong_shares_short_type: usize,
|
||||
pub nulled_wrong_type_net_change: usize,
|
||||
pub nulled_wrong_type_pct_float: usize,
|
||||
}
|
||||
|
||||
impl BsonCeoShortsDecodeStats {
|
||||
/// Total number of semantically skipped documents across all skip categories.
|
||||
#[inline]
|
||||
pub fn skipped_total(&self) -> usize {
|
||||
self.skipped_missing_key
|
||||
+ self.skipped_wrong_key_type
|
||||
+ self.skipped_empty_key
|
||||
+ self.skipped_missing_report_date
|
||||
+ self.skipped_wrong_report_date_type
|
||||
+ self.skipped_invalid_report_date
|
||||
+ self.skipped_report_date_out_of_range
|
||||
+ self.skipped_missing_shares_short
|
||||
+ self.skipped_wrong_shares_short_type
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.rows_out += other.rows_out;
|
||||
self.skipped_missing_key += other.skipped_missing_key;
|
||||
self.skipped_wrong_key_type += other.skipped_wrong_key_type;
|
||||
self.skipped_empty_key += other.skipped_empty_key;
|
||||
self.skipped_missing_report_date += other.skipped_missing_report_date;
|
||||
self.skipped_wrong_report_date_type += other.skipped_wrong_report_date_type;
|
||||
self.skipped_invalid_report_date += other.skipped_invalid_report_date;
|
||||
self.skipped_report_date_out_of_range += other.skipped_report_date_out_of_range;
|
||||
self.skipped_missing_shares_short += other.skipped_missing_shares_short;
|
||||
self.skipped_wrong_shares_short_type += other.skipped_wrong_shares_short_type;
|
||||
self.nulled_wrong_type_net_change += other.nulled_wrong_type_net_change;
|
||||
self.nulled_wrong_type_pct_float += other.nulled_wrong_type_pct_float;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonCeoShortsDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
enum KeyState<'a> {
|
||||
Missing,
|
||||
WrongType,
|
||||
Empty,
|
||||
Valid(&'a str),
|
||||
}
|
||||
|
||||
enum DateState {
|
||||
Missing,
|
||||
WrongType,
|
||||
Invalid,
|
||||
OutOfRange,
|
||||
Valid(i32),
|
||||
}
|
||||
|
||||
enum SharesState {
|
||||
Missing,
|
||||
WrongType,
|
||||
Valid(f64),
|
||||
}
|
||||
|
||||
enum OptionalNumState {
|
||||
None,
|
||||
WrongType,
|
||||
Valid(f64),
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_report_date_val(val: RawBsonRef<'_>) -> DateState {
|
||||
match val {
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
match i32::try_from(days) {
|
||||
Ok(d) => DateState::Valid(d),
|
||||
Err(_) => DateState::OutOfRange,
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => match te_epoch_i64_to_session_date(i64::from(v)) {
|
||||
Some(d) => DateState::Valid(d),
|
||||
None => DateState::OutOfRange,
|
||||
},
|
||||
RawBsonRef::Int64(v) => match te_epoch_i64_to_session_date(v) {
|
||||
Some(d) => DateState::Valid(d),
|
||||
None => DateState::OutOfRange,
|
||||
},
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v.fract() != 0.0 {
|
||||
return DateState::Invalid;
|
||||
}
|
||||
// Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`).
|
||||
if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&v) {
|
||||
return DateState::OutOfRange;
|
||||
}
|
||||
match te_epoch_i64_to_session_date(v as i64) {
|
||||
Some(d) => DateState::Valid(d),
|
||||
None => DateState::OutOfRange,
|
||||
}
|
||||
}
|
||||
_ => DateState::WrongType,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_required_number(val: RawBsonRef<'_>) -> SharesState {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => SharesState::Valid(v),
|
||||
RawBsonRef::Int32(v) => SharesState::Valid(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => SharesState::Valid(v as f64),
|
||||
_ => SharesState::WrongType,
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_optional_number(val: RawBsonRef<'_>) -> OptionalNumState {
|
||||
match val {
|
||||
RawBsonRef::Null => OptionalNumState::None,
|
||||
RawBsonRef::Double(v) => OptionalNumState::Valid(v),
|
||||
RawBsonRef::Int32(v) => OptionalNumState::Valid(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => OptionalNumState::Valid(v as f64),
|
||||
_ => OptionalNumState::WrongType,
|
||||
}
|
||||
}
|
||||
|
||||
/// Maximum recursive nesting depth accepted while validating raw BSON documents and arrays.
|
||||
const MAX_BSON_VALIDATION_DEPTH: usize = 128;
|
||||
|
||||
#[inline]
|
||||
fn is_exact_array_index(key: &str, expected: usize) -> bool {
|
||||
let bytes = key.as_bytes();
|
||||
if bytes.is_empty() || (bytes.len() > 1 && bytes[0] == b'0') {
|
||||
return false;
|
||||
}
|
||||
let mut parsed: usize = 0;
|
||||
for &b in bytes {
|
||||
if !b.is_ascii_digit() {
|
||||
return false;
|
||||
}
|
||||
let digit = usize::from(b - b'0');
|
||||
match parsed.checked_mul(10).and_then(|n| n.checked_add(digit)) {
|
||||
Some(next) => parsed = next,
|
||||
None => return false,
|
||||
}
|
||||
}
|
||||
parsed == expected
|
||||
}
|
||||
|
||||
fn validate_raw_bson_value(
|
||||
val: RawBsonRef<'_>,
|
||||
doc_offset: u64,
|
||||
field_name: &str,
|
||||
depth: usize,
|
||||
) -> Result<(), BsonCeoShortsError> {
|
||||
match val {
|
||||
RawBsonRef::Document(subdoc) => {
|
||||
validate_raw_document(subdoc, doc_offset, field_name, depth + 1)
|
||||
}
|
||||
RawBsonRef::Array(arr) => {
|
||||
if depth >= MAX_BSON_VALIDATION_DEPTH {
|
||||
return Err(BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!(
|
||||
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
|
||||
),
|
||||
});
|
||||
}
|
||||
for (expected_idx, elem_res) in arr.iter_elements().enumerate() {
|
||||
let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{field_name}': {err}"),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
if !is_exact_array_index(key, expected_idx) {
|
||||
return Err(BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!(
|
||||
"field '{field_name}': invalid BSON array index '{key}' at position {expected_idx}"
|
||||
),
|
||||
});
|
||||
}
|
||||
let item = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{field_name}': {err}"),
|
||||
})?;
|
||||
validate_raw_bson_value(item, doc_offset, field_name, depth + 1)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
RawBsonRef::JavaScriptCodeWithScope(code_with_scope) => {
|
||||
validate_raw_document(code_with_scope.scope, doc_offset, field_name, depth + 1)
|
||||
}
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
fn validate_raw_document(
|
||||
doc: &RawDocument,
|
||||
doc_offset: u64,
|
||||
field_name: &str,
|
||||
depth: usize,
|
||||
) -> Result<(), BsonCeoShortsError> {
|
||||
if depth > MAX_BSON_VALIDATION_DEPTH {
|
||||
return Err(BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!(
|
||||
"field '{field_name}': nested BSON depth exceeds limit {MAX_BSON_VALIDATION_DEPTH}"
|
||||
),
|
||||
});
|
||||
}
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{field_name}': {err}"),
|
||||
})?;
|
||||
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{field_name}': {err}"),
|
||||
})?;
|
||||
validate_raw_bson_value(val, doc_offset, field_name, depth)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn decode_ceo_shorts_doc_at<'a, F>(
|
||||
doc: &'a RawDocument,
|
||||
doc_offset: u64,
|
||||
fields: &CeoShortsFieldNames<'_>,
|
||||
mut on_row: F,
|
||||
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
|
||||
where
|
||||
F: FnMut(CeoShortReport<&'a str>),
|
||||
{
|
||||
let mut stats = BsonCeoShortsDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonCeoShortsDecodeStats::default()
|
||||
};
|
||||
|
||||
let mut key_state = KeyState::Missing;
|
||||
let mut date_state = DateState::Missing;
|
||||
let mut shares_state = SharesState::Missing;
|
||||
let mut net_change_state = OptionalNumState::None;
|
||||
let mut pct_float_state = OptionalNumState::None;
|
||||
|
||||
// Scan and validate every element and nested raw value to completion so structural BSON
|
||||
// corruption (including invalid UTF-8 in unused fields or malformed nested documents/arrays)
|
||||
// always fails closed and is never masked by an earlier semantic skip.
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let name = elem.key().as_str();
|
||||
let val = elem.value().map_err(|err| BsonCeoShortsError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{name}': {err}"),
|
||||
})?;
|
||||
validate_raw_bson_value(val, doc_offset, name, 0)?;
|
||||
|
||||
if name == fields.key {
|
||||
key_state = match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
KeyState::Empty
|
||||
} else {
|
||||
KeyState::Valid(s)
|
||||
}
|
||||
}
|
||||
_ => KeyState::WrongType,
|
||||
};
|
||||
} else if name == fields.report_date {
|
||||
date_state = decode_report_date_val(val);
|
||||
} else if name == fields.shares_short {
|
||||
shares_state = decode_required_number(val);
|
||||
} else if fields.net_change == Some(name) {
|
||||
net_change_state = decode_optional_number(val);
|
||||
} else if fields.pct_float == Some(name) {
|
||||
pct_float_state = decode_optional_number(val);
|
||||
}
|
||||
}
|
||||
|
||||
// Apply deterministic semantic skip priority: key -> report_date -> shares_short.
|
||||
let key = match key_state {
|
||||
KeyState::Valid(s) => s,
|
||||
KeyState::Missing => {
|
||||
stats.skipped_missing_key += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
KeyState::WrongType => {
|
||||
stats.skipped_wrong_key_type += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
KeyState::Empty => {
|
||||
stats.skipped_empty_key += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
};
|
||||
|
||||
let report_date = match date_state {
|
||||
DateState::Valid(d) => d,
|
||||
DateState::Missing => {
|
||||
stats.skipped_missing_report_date += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
DateState::WrongType => {
|
||||
stats.skipped_wrong_report_date_type += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
DateState::Invalid => {
|
||||
stats.skipped_invalid_report_date += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
DateState::OutOfRange => {
|
||||
stats.skipped_report_date_out_of_range += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
};
|
||||
|
||||
let shares_short = match shares_state {
|
||||
SharesState::Valid(v) => v,
|
||||
SharesState::Missing => {
|
||||
stats.skipped_missing_shares_short += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
SharesState::WrongType => {
|
||||
stats.skipped_wrong_shares_short_type += 1;
|
||||
return Ok(stats);
|
||||
}
|
||||
};
|
||||
|
||||
let net_change = match net_change_state {
|
||||
OptionalNumState::Valid(v) => Some(v),
|
||||
OptionalNumState::None => None,
|
||||
OptionalNumState::WrongType => {
|
||||
stats.nulled_wrong_type_net_change += 1;
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
let pct_float = match pct_float_state {
|
||||
OptionalNumState::Valid(v) => Some(v),
|
||||
OptionalNumState::None => None,
|
||||
OptionalNumState::WrongType => {
|
||||
stats.nulled_wrong_type_pct_float += 1;
|
||||
None
|
||||
}
|
||||
};
|
||||
|
||||
stats.rows_out += 1;
|
||||
on_row(CeoShortReport {
|
||||
key,
|
||||
report_date,
|
||||
shares_short,
|
||||
net_change,
|
||||
pct_float,
|
||||
});
|
||||
Ok(stats)
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `ceoShorts` MongoDB document in one forward
|
||||
/// pass without allocating a `bson::Document` or per-row `String`s.
|
||||
pub fn decode_ceo_shorts_doc<'a, F>(
|
||||
doc: &'a RawDocument,
|
||||
fields: &CeoShortsFieldNames<'_>,
|
||||
on_row: F,
|
||||
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
|
||||
where
|
||||
F: FnMut(CeoShortReport<&'a str>),
|
||||
{
|
||||
fields.validate()?;
|
||||
decode_ceo_shorts_doc_at(doc, 0, fields, on_row)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice representing a `ceoShorts`
|
||||
/// document.
|
||||
pub fn decode_ceo_shorts_bytes<'a, F>(
|
||||
bytes: &'a [u8],
|
||||
fields: &CeoShortsFieldNames<'_>,
|
||||
on_row: F,
|
||||
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
|
||||
where
|
||||
F: FnMut(CeoShortReport<&'a str>),
|
||||
{
|
||||
fields.validate()?;
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_ceo_shorts_doc_at(doc, 0, fields, on_row)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_ceo_shorts_doc`],
|
||||
/// emitting every valid [`CeoShortReport<&str>`] to `on_row` and failing closed on any structural
|
||||
/// BSON framing or element corruption.
|
||||
///
|
||||
/// Always maintains `stats.docs_in == stats.rows_out + stats.skipped_total()`.
|
||||
pub fn decode_ceo_shorts_buffer<'a, F>(
|
||||
buf: &'a [u8],
|
||||
fields: &CeoShortsFieldNames<'_>,
|
||||
mut on_row: F,
|
||||
) -> Result<BsonCeoShortsDecodeStats, BsonCeoShortsError>
|
||||
where
|
||||
F: FnMut(CeoShortReport<&'a str>),
|
||||
{
|
||||
fields.validate()?;
|
||||
let mut total = BsonCeoShortsDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
match item {
|
||||
Ok((offset, doc)) => {
|
||||
let doc_stats = decode_ceo_shorts_doc_at(doc, offset as u64, fields, &mut on_row)?;
|
||||
total += doc_stats;
|
||||
}
|
||||
Err((_, err)) => return Err(map_framing_error(err)),
|
||||
}
|
||||
}
|
||||
Ok(total)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_ceo_shorts_tests.rs"]
|
||||
mod tests;
|
||||
732
tools/curate-etl/src/bson_ceo_shorts_tests.rs
Normal file
732
tools/curate-etl/src/bson_ceo_shorts_tests.rs
Normal file
|
|
@ -0,0 +1,732 @@
|
|||
use bson::raw::{cstr, RawBson, RawDocumentBuf};
|
||||
use bson::DateTime as BsonDateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn default_fields() -> CeoShortsFieldNames<'static> {
|
||||
CeoShortsFieldNames {
|
||||
key: DEFAULT_KEY_FIELD,
|
||||
report_date: DEFAULT_REPORT_DATE_FIELD,
|
||||
shares_short: "sharesShort",
|
||||
net_change: Some("netChange"),
|
||||
pct_float: Some("pctFloat"),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_conservation(stats: &BsonCeoShortsDecodeStats) {
|
||||
assert_eq!(
|
||||
stats.docs_in,
|
||||
stats.rows_out + stats.skipped_total(),
|
||||
"conservation invariant failed: {stats:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_field_names_rejecting_empty_blank_and_duplicates() {
|
||||
assert!(default_fields().validate().is_ok());
|
||||
|
||||
let no_opt = CeoShortsFieldNames {
|
||||
key: "k",
|
||||
report_date: "d",
|
||||
shares_short: "s",
|
||||
net_change: None,
|
||||
pct_float: None,
|
||||
};
|
||||
assert!(no_opt.validate().is_ok());
|
||||
|
||||
let bad_configs = [
|
||||
CeoShortsFieldNames {
|
||||
key: "",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
key: " \t ",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
report_date: "",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
shares_short: " ",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
net_change: Some(""),
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
pct_float: Some(" "),
|
||||
..default_fields()
|
||||
},
|
||||
// Duplicate roles
|
||||
CeoShortsFieldNames {
|
||||
key: "same",
|
||||
report_date: "same",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
key: "symbol",
|
||||
shares_short: "symbol",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
report_date: "timestamp",
|
||||
shares_short: "timestamp",
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
net_change: Some("sharesShort"),
|
||||
..default_fields()
|
||||
},
|
||||
CeoShortsFieldNames {
|
||||
pct_float: Some("netChange"),
|
||||
..default_fields()
|
||||
},
|
||||
];
|
||||
|
||||
for cfg in bad_configs {
|
||||
let err = cfg.validate().unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::InvalidFieldNames { .. }),
|
||||
"expected InvalidFieldNames for {cfg:?}, got {err:?}"
|
||||
);
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "single-line display expected: {msg}");
|
||||
|
||||
// Entry points also reject invalid config before touching bytes.
|
||||
assert!(matches!(
|
||||
decode_ceo_shorts_buffer(&[], &cfg, |_| {}),
|
||||
Err(BsonCeoShortsError::InvalidFieldNames { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_report_date_across_datetime_int32_int64_and_integral_double() {
|
||||
let fields = default_fields();
|
||||
let d_2024_03_15 = day(2024, 3, 15);
|
||||
let secs_2024_03_15 = i64::from(d_2024_03_15) * 86_400 + 3_600; // 01:00 UTC
|
||||
let millis_2024_03_15 = secs_2024_03_15 * 1_000 + 500;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
|
||||
// 1. BSON DateTime
|
||||
let mut doc1 = RawDocumentBuf::new();
|
||||
doc1.append(cstr!("symbol"), "RY");
|
||||
doc1.append(
|
||||
cstr!("timestamp"),
|
||||
BsonDateTime::from_millis(millis_2024_03_15),
|
||||
);
|
||||
doc1.append(cstr!("sharesShort"), 100_000_i32);
|
||||
doc1.append(cstr!("netChange"), -5_000_i32);
|
||||
doc1.append(cstr!("pctFloat"), 1.25_f64);
|
||||
buf.extend_from_slice(doc1.as_bytes());
|
||||
|
||||
// 2. Int32 seconds
|
||||
let mut doc2 = RawDocumentBuf::new();
|
||||
doc2.append(cstr!("symbol"), "TD");
|
||||
doc2.append(cstr!("timestamp"), secs_2024_03_15 as i32);
|
||||
doc2.append(cstr!("sharesShort"), 250_000_i64);
|
||||
doc2.append(cstr!("netChange"), 10_000_i64);
|
||||
doc2.append(cstr!("pctFloat"), 2_i32);
|
||||
buf.extend_from_slice(doc2.as_bytes());
|
||||
|
||||
// 3. Int64 seconds
|
||||
let mut doc3 = RawDocumentBuf::new();
|
||||
doc3.append(cstr!("symbol"), "BNS");
|
||||
doc3.append(cstr!("timestamp"), secs_2024_03_15);
|
||||
doc3.append(cstr!("sharesShort"), 300_000.5_f64);
|
||||
buf.extend_from_slice(doc3.as_bytes());
|
||||
|
||||
// 4. Int64 millis
|
||||
let mut doc4 = RawDocumentBuf::new();
|
||||
doc4.append(cstr!("symbol"), "BMO");
|
||||
doc4.append(cstr!("timestamp"), millis_2024_03_15);
|
||||
doc4.append(cstr!("sharesShort"), 400_000.0_f64);
|
||||
buf.extend_from_slice(doc4.as_bytes());
|
||||
|
||||
// 5. Integral finite Double (seconds)
|
||||
let mut doc5 = RawDocumentBuf::new();
|
||||
doc5.append(cstr!("symbol"), "CM");
|
||||
doc5.append(cstr!("timestamp"), secs_2024_03_15 as f64);
|
||||
doc5.append(cstr!("sharesShort"), 500_000.0_f64);
|
||||
buf.extend_from_slice(doc5.as_bytes());
|
||||
|
||||
// 6. Integral finite Double (millis)
|
||||
let mut doc6 = RawDocumentBuf::new();
|
||||
doc6.append(cstr!("symbol"), "NA");
|
||||
doc6.append(cstr!("timestamp"), millis_2024_03_15 as f64);
|
||||
doc6.append(cstr!("sharesShort"), 600_000.0_f64);
|
||||
buf.extend_from_slice(doc6.as_bytes());
|
||||
|
||||
// 7. Pre-1970 negative floor via DateTime (-1 ms -> 1969-12-31 == -1)
|
||||
let mut doc7 = RawDocumentBuf::new();
|
||||
doc7.append(cstr!("symbol"), "PRE_DT");
|
||||
doc7.append(cstr!("timestamp"), BsonDateTime::from_millis(-1));
|
||||
doc7.append(cstr!("sharesShort"), 700_i32);
|
||||
buf.extend_from_slice(doc7.as_bytes());
|
||||
|
||||
// 8. Pre-1970 negative floor via integral Double (-1.0 sec -> 1969-12-31 == -1)
|
||||
let mut doc8 = RawDocumentBuf::new();
|
||||
doc8.append(cstr!("symbol"), "PRE_DBL");
|
||||
doc8.append(cstr!("timestamp"), -1.0_f64);
|
||||
doc8.append(cstr!("sharesShort"), 800_i32);
|
||||
buf.extend_from_slice(doc8.as_bytes());
|
||||
|
||||
// 9. -0.0 Double -> epoch day 0 (1970-01-01)
|
||||
let mut doc9 = RawDocumentBuf::new();
|
||||
doc9.append(cstr!("symbol"), "NEG_ZERO");
|
||||
doc9.append(cstr!("timestamp"), -0.0_f64);
|
||||
doc9.append(cstr!("sharesShort"), 900_i32);
|
||||
buf.extend_from_slice(doc9.as_bytes());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_ceo_shorts_buffer(&buf, &fields, |r| {
|
||||
rows.push(CeoShortReport {
|
||||
key: r.key.to_string(),
|
||||
report_date: r.report_date,
|
||||
shares_short: r.shares_short,
|
||||
net_change: r.net_change,
|
||||
pct_float: r.pct_float,
|
||||
});
|
||||
})
|
||||
.expect("decode buffer");
|
||||
|
||||
assert_conservation(&stats);
|
||||
assert_eq!(stats.docs_in, 9);
|
||||
assert_eq!(stats.rows_out, 9);
|
||||
assert_eq!(stats.skipped_total(), 0);
|
||||
|
||||
for row in &rows[..6] {
|
||||
assert_eq!(row.report_date, d_2024_03_15);
|
||||
}
|
||||
assert_eq!(rows[0].net_change, Some(-5_000.0));
|
||||
assert_eq!(rows[0].pct_float, Some(1.25));
|
||||
assert_eq!(rows[1].net_change, Some(10_000.0));
|
||||
assert_eq!(rows[1].pct_float, Some(2.0));
|
||||
assert_eq!(rows[2].net_change, None);
|
||||
assert_eq!(rows[2].pct_float, None);
|
||||
assert_eq!(rows[6].report_date, -1);
|
||||
assert_eq!(rows[7].report_date, -1);
|
||||
assert_eq!(rows[8].report_date, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_custom_field_names_and_preserves_verbatim_key_and_unconfigured_optionals() {
|
||||
let fields = CeoShortsFieldNames {
|
||||
key: "tickerCode",
|
||||
report_date: "asOfDate",
|
||||
shares_short: "shortPos",
|
||||
net_change: None,
|
||||
pct_float: None,
|
||||
};
|
||||
|
||||
let d = day(2024, 6, 30);
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("_id"), "ignored_id");
|
||||
doc.append(cstr!("tickerCode"), " SHOP.TO "); // verbatim, not trimmed
|
||||
doc.append(cstr!("asOfDate"), i64::from(d) * 86_400);
|
||||
doc.append(cstr!("shortPos"), 42_000_i64);
|
||||
// Even if unrelated fields exist with wrong types, unconfigured optionals stay None without counting.
|
||||
doc.append(cstr!("netChange"), "not-a-number");
|
||||
doc.append(cstr!("pctFloat"), true);
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_ceo_shorts_bytes(doc.as_bytes(), &fields, |r| {
|
||||
rows.push((
|
||||
r.key.to_string(),
|
||||
r.report_date,
|
||||
r.shares_short,
|
||||
r.net_change,
|
||||
r.pct_float,
|
||||
));
|
||||
})
|
||||
.expect("decode bytes");
|
||||
|
||||
assert_conservation(&stats);
|
||||
assert_eq!(stats.rows_out, 1);
|
||||
assert_eq!(stats.nulled_wrong_type_net_change, 0);
|
||||
assert_eq!(stats.nulled_wrong_type_pct_float, 0);
|
||||
assert_eq!(rows, vec![(" SHOP.TO ".to_string(), d, 42_000.0, None, None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_bad_required_fields_with_exact_counters_and_priority() {
|
||||
let fields = default_fields();
|
||||
let d_secs = i64::from(day(2024, 3, 15)) * 86_400;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
|
||||
// 1. Missing key (also missing date & shares -> key wins priority)
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("extra"), 1_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 2. Wrong key type (Int32)
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), 123_i32);
|
||||
doc.append(cstr!("timestamp"), d_secs);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 3. Empty/blank key (and wrong-typed optionals must NOT increment nulled_wrong_type_*)
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), " ");
|
||||
doc.append(cstr!("timestamp"), d_secs);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
doc.append(cstr!("netChange"), "bad");
|
||||
doc.append(cstr!("pctFloat"), false);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 4. Missing report_date (also missing shares -> report_date wins priority)
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 5. Wrong report_date type (String)
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), "2024-03-15");
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 6. Invalid report_date: fractional Double
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), 1_710_460_800.5_f64);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 7. Invalid report_date: NaN Double
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), f64::NAN);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 8. Invalid report_date: +Inf Double
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), f64::INFINITY);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 9. Out-of-range report_date: Double > 2^63
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), 1e30_f64);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 10. Out-of-range report_date: DateTime overflowing i32 days
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), BsonDateTime::from_millis(i64::MAX));
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 11. Out-of-range report_date: Int64 overflowing i32 days
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), i64::MAX);
|
||||
doc.append(cstr!("sharesShort"), 10_i32);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 12. Missing shares_short
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), d_secs);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
// 13. Wrong shares_short type: numeric string is rejected, not parsed
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "A");
|
||||
doc.append(cstr!("timestamp"), d_secs);
|
||||
doc.append(cstr!("sharesShort"), "12345");
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
|
||||
let mut emitted = 0usize;
|
||||
let stats = decode_ceo_shorts_buffer(&buf, &fields, |_| emitted += 1).expect("decode buffer");
|
||||
assert_conservation(&stats);
|
||||
assert_eq!(emitted, 0);
|
||||
assert_eq!(stats.docs_in, 13);
|
||||
assert_eq!(stats.rows_out, 0);
|
||||
assert_eq!(stats.skipped_missing_key, 1);
|
||||
assert_eq!(stats.skipped_wrong_key_type, 1);
|
||||
assert_eq!(stats.skipped_empty_key, 1);
|
||||
assert_eq!(stats.skipped_missing_report_date, 1);
|
||||
assert_eq!(stats.skipped_wrong_report_date_type, 1);
|
||||
assert_eq!(stats.skipped_invalid_report_date, 3);
|
||||
assert_eq!(stats.skipped_report_date_out_of_range, 3);
|
||||
assert_eq!(stats.skipped_missing_shares_short, 1);
|
||||
assert_eq!(stats.skipped_wrong_shares_short_type, 1);
|
||||
assert_eq!(stats.nulled_wrong_type_net_change, 0);
|
||||
assert_eq!(stats.nulled_wrong_type_pct_float, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_negative_and_nan_shares_through_and_handles_null_and_wrong_type_optionals() {
|
||||
let fields = default_fields();
|
||||
let d_secs = i64::from(day(2024, 3, 15)) * 86_400;
|
||||
|
||||
let mut buf = Vec::new();
|
||||
|
||||
// 1. Negative shares_short + Null optionals (not counted as wrong type)
|
||||
let mut doc1 = RawDocumentBuf::new();
|
||||
doc1.append(cstr!("symbol"), "NEG");
|
||||
doc1.append(cstr!("timestamp"), d_secs);
|
||||
doc1.append(cstr!("sharesShort"), -50.0_f64);
|
||||
doc1.append(cstr!("netChange"), RawBson::Null);
|
||||
doc1.append(cstr!("pctFloat"), RawBson::Null);
|
||||
buf.extend_from_slice(doc1.as_bytes());
|
||||
|
||||
// 2. NaN shares_short + wrong-type optionals (counted on emitted row)
|
||||
let mut doc2 = RawDocumentBuf::new();
|
||||
doc2.append(cstr!("symbol"), "NAN");
|
||||
doc2.append(cstr!("timestamp"), d_secs);
|
||||
doc2.append(cstr!("sharesShort"), f64::NAN);
|
||||
doc2.append(cstr!("netChange"), "123");
|
||||
doc2.append(cstr!("pctFloat"), true);
|
||||
buf.extend_from_slice(doc2.as_bytes());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_ceo_shorts_buffer(&buf, &fields, |r| {
|
||||
rows.push((
|
||||
r.key.to_string(),
|
||||
r.shares_short,
|
||||
r.net_change,
|
||||
r.pct_float,
|
||||
));
|
||||
})
|
||||
.expect("decode buffer");
|
||||
|
||||
assert_conservation(&stats);
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.rows_out, 2);
|
||||
assert_eq!(stats.nulled_wrong_type_net_change, 1);
|
||||
assert_eq!(stats.nulled_wrong_type_pct_float, 1);
|
||||
assert_eq!(rows[0].0, "NEG");
|
||||
assert_eq!(rows[0].1, -50.0);
|
||||
assert_eq!(rows[0].2, None);
|
||||
assert_eq!(rows[0].3, None);
|
||||
assert_eq!(rows[1].0, "NAN");
|
||||
assert!(rows[1].1.is_nan());
|
||||
assert_eq!(rows[1].2, None);
|
||||
assert_eq!(rows[1].3, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_bson_corruption_fails_closed_even_after_semantic_skip() {
|
||||
let fields = default_fields();
|
||||
|
||||
// Build a doc with a bad key (semantic skip) followed by a corrupt trailing element type byte.
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), ""); // would be skipped_empty_key
|
||||
doc.append(cstr!("z"), 1_i32);
|
||||
let mut bytes = doc.into_bytes();
|
||||
// Corrupt the element type byte of "z" (which is 0x10 = Int32) to an invalid BSON type 0x7e.
|
||||
let z_pos = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'z', 0x00])
|
||||
.expect("locate z element");
|
||||
bytes[z_pos] = 0x7e;
|
||||
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson at offset 0, got {err:?}"
|
||||
);
|
||||
|
||||
// Also test second document in a buffer has accurate byte offset.
|
||||
let mut good = RawDocumentBuf::new();
|
||||
good.append(cstr!("symbol"), "OK");
|
||||
good.append(cstr!("timestamp"), i64::from(day(2024, 3, 15)) * 86_400);
|
||||
good.append(cstr!("sharesShort"), 100_i32);
|
||||
let good_len = good.as_bytes().len() as u64;
|
||||
|
||||
let mut combined = Vec::new();
|
||||
combined.extend_from_slice(good.as_bytes());
|
||||
combined.extend_from_slice(&bytes);
|
||||
|
||||
let err = decode_ceo_shorts_buffer(&combined, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset, .. } if offset == good_len),
|
||||
"expected CorruptBson at offset {good_len}, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn framing_errors_return_typed_errors_with_offsets() {
|
||||
let fields = default_fields();
|
||||
|
||||
// Truncated header (< 4 bytes)
|
||||
let err = decode_ceo_shorts_buffer(&[0x10, 0x00], &fields, |_| {}).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
BsonCeoShortsError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 2,
|
||||
declared_len: None
|
||||
}
|
||||
));
|
||||
|
||||
// Truncated body
|
||||
let err = decode_ceo_shorts_buffer(&[20, 0, 0, 0, 0, 0], &fields, |_| {}).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
BsonCeoShortsError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 6,
|
||||
declared_len: Some(20)
|
||||
}
|
||||
));
|
||||
|
||||
// Corrupt length (< 5)
|
||||
let err = decode_ceo_shorts_buffer(&[3, 0, 0, 0, 0], &fields, |_| {}).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
BsonCeoShortsError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 3
|
||||
}
|
||||
));
|
||||
|
||||
// Trailing bytes on decode_ceo_shorts_bytes
|
||||
let mut good = RawDocumentBuf::new();
|
||||
good.append(cstr!("symbol"), "OK");
|
||||
let mut extra = good.into_bytes();
|
||||
extra.push(0x00);
|
||||
let err = decode_ceo_shorts_bytes(&extra, &fields, |_| {}).unwrap_err();
|
||||
assert!(matches!(err, BsonCeoShortsError::CorruptDocumentLength { .. }));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_unused_string_embedded_doc_and_array_fail_closed() {
|
||||
use bson::raw::RawArrayBuf;
|
||||
|
||||
let fields = default_fields();
|
||||
let d_secs = i64::from(day(2024, 3, 15)) * 86_400;
|
||||
|
||||
// 1. Valid unused nested doc & array still decode cleanly.
|
||||
let mut inner = RawDocumentBuf::new();
|
||||
inner.append(cstr!("tag"), "clean");
|
||||
let mut arr = RawArrayBuf::new();
|
||||
arr.push("ok");
|
||||
arr.push(inner.clone());
|
||||
|
||||
let mut valid_doc = RawDocumentBuf::new();
|
||||
valid_doc.append(cstr!("symbol"), "RY");
|
||||
valid_doc.append(cstr!("timestamp"), d_secs);
|
||||
valid_doc.append(cstr!("sharesShort"), 100_i32);
|
||||
valid_doc.append(cstr!("note"), "hello");
|
||||
valid_doc.append(cstr!("meta"), inner.clone());
|
||||
valid_doc.append(cstr!("tags"), arr);
|
||||
|
||||
let mut emitted = 0usize;
|
||||
let stats = decode_ceo_shorts_bytes(valid_doc.as_bytes(), &fields, |_| emitted += 1)
|
||||
.expect("valid nested doc/array should decode");
|
||||
assert_conservation(&stats);
|
||||
assert_eq!(emitted, 1);
|
||||
|
||||
// 2. Invalid UTF-8 in an unused string field fails closed (0 rows emitted).
|
||||
let mut bad_utf8_doc = RawDocumentBuf::new();
|
||||
bad_utf8_doc.append(cstr!("symbol"), "RY");
|
||||
bad_utf8_doc.append(cstr!("timestamp"), d_secs);
|
||||
bad_utf8_doc.append(cstr!("sharesShort"), 100_i32);
|
||||
bad_utf8_doc.append(cstr!("unusedNote"), "MARKER");
|
||||
let mut bytes = bad_utf8_doc.into_bytes();
|
||||
let pos = bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"MARKER")
|
||||
.expect("locate MARKER");
|
||||
bytes[pos] = 0xff;
|
||||
bytes[pos + 1] = 0xfe;
|
||||
|
||||
let mut emitted = 0usize;
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| emitted += 1).unwrap_err();
|
||||
assert_eq!(emitted, 0);
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for invalid UTF-8 in unused string, got {err:?}"
|
||||
);
|
||||
|
||||
// 3. Malformed element inside an unused embedded document fails closed.
|
||||
let mut bad_inner = RawDocumentBuf::new();
|
||||
bad_inner.append(cstr!("nestedText"), "INNER!");
|
||||
let mut bad_nested_doc = RawDocumentBuf::new();
|
||||
bad_nested_doc.append(cstr!("symbol"), "RY");
|
||||
bad_nested_doc.append(cstr!("timestamp"), d_secs);
|
||||
bad_nested_doc.append(cstr!("sharesShort"), 100_i32);
|
||||
bad_nested_doc.append(cstr!("meta"), bad_inner);
|
||||
let mut bytes = bad_nested_doc.into_bytes();
|
||||
let pos = bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"INNER!")
|
||||
.expect("locate INNER!");
|
||||
bytes[pos] = 0xff;
|
||||
|
||||
let mut emitted = 0usize;
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| emitted += 1).unwrap_err();
|
||||
assert_eq!(emitted, 0);
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for invalid UTF-8 in embedded doc, got {err:?}"
|
||||
);
|
||||
|
||||
// 4. Corrupt element type byte inside an unused embedded document fails closed.
|
||||
let mut bad_type_inner = RawDocumentBuf::new();
|
||||
bad_type_inner.append(cstr!("k"), 42_i32);
|
||||
let mut bad_type_doc = RawDocumentBuf::new();
|
||||
bad_type_doc.append(cstr!("symbol"), "RY");
|
||||
bad_type_doc.append(cstr!("timestamp"), d_secs);
|
||||
bad_type_doc.append(cstr!("sharesShort"), 100_i32);
|
||||
bad_type_doc.append(cstr!("meta"), bad_type_inner);
|
||||
let mut bytes = bad_type_doc.into_bytes();
|
||||
let k_pos = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'k', 0x00])
|
||||
.expect("locate nested int32 element");
|
||||
bytes[k_pos] = 0x7e;
|
||||
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for corrupt element type in embedded doc, got {err:?}"
|
||||
);
|
||||
|
||||
// 5. Invalid UTF-8 inside an unused array element fails closed.
|
||||
let mut bad_arr = RawArrayBuf::new();
|
||||
bad_arr.push("ARRVAL");
|
||||
let mut bad_arr_doc = RawDocumentBuf::new();
|
||||
bad_arr_doc.append(cstr!("symbol"), "RY");
|
||||
bad_arr_doc.append(cstr!("timestamp"), d_secs);
|
||||
bad_arr_doc.append(cstr!("sharesShort"), 100_i32);
|
||||
bad_arr_doc.append(cstr!("tags"), bad_arr);
|
||||
let mut bytes = bad_arr_doc.into_bytes();
|
||||
let pos = bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"ARRVAL")
|
||||
.expect("locate ARRVAL");
|
||||
bytes[pos] = 0xff;
|
||||
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for invalid UTF-8 in unused array, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_array_indexes_fail_closed() {
|
||||
use bson::raw::RawArrayBuf;
|
||||
|
||||
let fields = default_fields();
|
||||
let d_secs = i64::from(day(2024, 3, 15)) * 86_400;
|
||||
|
||||
// Valid multi-element unused array succeeds.
|
||||
let mut good_arr = RawArrayBuf::new();
|
||||
good_arr.push("first");
|
||||
good_arr.push("second");
|
||||
good_arr.push("third");
|
||||
let mut good_doc = RawDocumentBuf::new();
|
||||
good_doc.append(cstr!("symbol"), "RY");
|
||||
good_doc.append(cstr!("timestamp"), d_secs);
|
||||
good_doc.append(cstr!("sharesShort"), 100_i32);
|
||||
good_doc.append(cstr!("tags"), good_arr);
|
||||
let mut rows = 0usize;
|
||||
let stats = decode_ceo_shorts_bytes(good_doc.as_bytes(), &fields, |_| rows += 1).unwrap();
|
||||
assert_eq!(rows, 1);
|
||||
assert_conservation(&stats);
|
||||
|
||||
// Helper: build a doc with an unused 2-element array [10, 20] and mutate the array keys.
|
||||
let build_two_elem_array_doc = || {
|
||||
let mut arr = RawArrayBuf::new();
|
||||
arr.push(10_i32);
|
||||
arr.push(20_i32);
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "RY");
|
||||
doc.append(cstr!("timestamp"), d_secs);
|
||||
doc.append(cstr!("sharesShort"), 100_i32);
|
||||
doc.append(cstr!("tags"), arr);
|
||||
doc.into_bytes()
|
||||
};
|
||||
|
||||
// 1. First index mutated from "0" to "8".
|
||||
let mut bytes = build_two_elem_array_doc();
|
||||
let idx0 = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'0', 0x00])
|
||||
.expect("locate index 0 element");
|
||||
bytes[idx0 + 1] = b'8';
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for non-zero starting array index, got {err:?}"
|
||||
);
|
||||
|
||||
// 2. Repeated index ("0", "0").
|
||||
let mut bytes = build_two_elem_array_doc();
|
||||
let idx1 = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'1', 0x00])
|
||||
.expect("locate index 1 element");
|
||||
bytes[idx1 + 1] = b'0';
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for repeated array index, got {err:?}"
|
||||
);
|
||||
|
||||
// 3. Skipped/out-of-order index ("0", "2").
|
||||
let mut bytes = build_two_elem_array_doc();
|
||||
let idx1 = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'1', 0x00])
|
||||
.expect("locate index 1 element");
|
||||
bytes[idx1 + 1] = b'2';
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for skipped array index, got {err:?}"
|
||||
);
|
||||
|
||||
// 4. Non-numeric index ("a", "1").
|
||||
let mut bytes = build_two_elem_array_doc();
|
||||
let idx0 = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == [0x10, b'0', 0x00])
|
||||
.expect("locate index 0 element");
|
||||
bytes[idx0 + 1] = b'a';
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for non-numeric array index, got {err:?}"
|
||||
);
|
||||
|
||||
// 5. Leading-zero index ("00") constructed as raw document bytes placed in an array field.
|
||||
let mut fake_arr = RawDocumentBuf::new();
|
||||
fake_arr.append(cstr!("00"), 10_i32);
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("symbol"), "RY");
|
||||
doc.append(cstr!("timestamp"), d_secs);
|
||||
doc.append(cstr!("sharesShort"), 100_i32);
|
||||
doc.append(cstr!("tags"), fake_arr);
|
||||
let mut bytes = doc.into_bytes();
|
||||
// Change field 'tags' element type from EmbeddedDocument (0x03) to Array (0x04).
|
||||
let tags_pos = bytes
|
||||
.windows(6)
|
||||
.position(|w| w == [0x03, b't', b'a', b'g', b's', 0x00])
|
||||
.expect("locate tags document element");
|
||||
bytes[tags_pos] = 0x04;
|
||||
let err = decode_ceo_shorts_bytes(&bytes, &fields, |_| {}).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonCeoShortsError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson for leading-zero array index, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
|
@ -42,7 +42,7 @@ use bson::spec::ElementType;
|
|||
use crate::bars::EodDailyBar;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
pub(crate) const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
const MIN_BSON_DOC_LEN: i32 = 5;
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `eodPrices` BSON document.
|
||||
|
|
@ -235,6 +235,26 @@ impl BsonEodDecodeStats {
|
|||
| BsonEodPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonEodDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -250,22 +270,20 @@ fn parse_ascii_digits_u32(bytes: &[u8]) -> Option<u32> {
|
|||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
pub(crate) fn parse_ymd_strict_days(s: &str) -> Option<i32> {
|
||||
let bytes = s.as_bytes();
|
||||
if bytes.len() != 10 || bytes[4] != b'-' || bytes[7] != b'-' {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
return None;
|
||||
}
|
||||
let Some(year_u32) = parse_ascii_digits_u32(&bytes[0..4]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(month) = parse_ascii_digits_u32(&bytes[5..7]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
let Some(day) = parse_ascii_digits_u32(&bytes[8..10]) else {
|
||||
return Err(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
};
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })
|
||||
let year_u32 = parse_ascii_digits_u32(&bytes[0..4])?;
|
||||
let month = parse_ascii_digits_u32(&bytes[5..7])?;
|
||||
let day = parse_ascii_digits_u32(&bytes[8..10])?;
|
||||
ymd_to_epoch_days(year_u32 as i32, month, day).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn parse_ymd_strict(s: &str) -> Result<i32, BsonEodPriceError> {
|
||||
parse_ymd_strict_days(s).ok_or(BsonEodPriceError::MalformedDate { field: "date" })
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
|
@ -332,6 +350,7 @@ fn decode_eod_price_doc_at<'a>(
|
|||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
let mut adj_volume: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonEodPriceError> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
|
|
@ -344,56 +363,113 @@ fn decode_eod_price_doc_at<'a>(
|
|||
match decode_element_value("eodSearchCode", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonEodPriceError::EmptyField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodPriceError::EmptyField {
|
||||
field: "eodSearchCode",
|
||||
});
|
||||
}
|
||||
} else {
|
||||
eod_search_code = Some(s);
|
||||
}
|
||||
eod_search_code = Some(s);
|
||||
}
|
||||
other => {
|
||||
return Err(BsonEodPriceError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodPriceError::WrongType {
|
||||
field: "eodSearchCode",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("date") {
|
||||
match decode_element_value("date", elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
session_date = Some(parse_ymd_strict(s)?);
|
||||
}
|
||||
RawBsonRef::String(s) => match parse_ymd_strict(s) {
|
||||
Ok(d) => session_date = Some(d),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
},
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
let day_i32 = i32::try_from(days)
|
||||
.map_err(|_| BsonEodPriceError::MalformedDate { field: "date" })?;
|
||||
session_date = Some(day_i32);
|
||||
match i32::try_from(days) {
|
||||
Ok(day_i32) => session_date = Some(day_i32),
|
||||
Err(_) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err =
|
||||
Some(BsonEodPriceError::MalformedDate { field: "date" });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
other => {
|
||||
return Err(BsonEodPriceError::WrongType {
|
||||
field: "date",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonEodPriceError::WrongType {
|
||||
field: "date",
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("open") {
|
||||
let val = decode_element_value("open", elem, offset)?;
|
||||
open = Some(decode_non_negative_number("open", val)?);
|
||||
match decode_non_negative_number("open", val) {
|
||||
Ok(v) => open = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("high") {
|
||||
let val = decode_element_value("high", elem, offset)?;
|
||||
high = Some(decode_non_negative_number("high", val)?);
|
||||
match decode_non_negative_number("high", val) {
|
||||
Ok(v) => high = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("low") {
|
||||
let val = decode_element_value("low", elem, offset)?;
|
||||
low = Some(decode_non_negative_number("low", val)?);
|
||||
match decode_non_negative_number("low", val) {
|
||||
Ok(v) => low = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("close") {
|
||||
let val = decode_element_value("close", elem, offset)?;
|
||||
close = Some(decode_non_negative_number("close", val)?);
|
||||
match decode_non_negative_number("close", val) {
|
||||
Ok(v) => close = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("volume") {
|
||||
let val = decode_element_value("volume", elem, offset)?;
|
||||
adj_volume = Some(decode_non_negative_number("volume", val)?);
|
||||
match decode_non_negative_number("volume", val) {
|
||||
Ok(v) => adj_volume = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(eod_search_code) = eod_search_code else {
|
||||
return Err(BsonEodPriceError::MissingField {
|
||||
field: "eodSearchCode",
|
||||
|
|
@ -438,11 +514,7 @@ pub fn decode_eod_price_doc<'a>(
|
|||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
pub(crate) fn parse_single_raw_doc(bytes: &[u8]) -> Result<&RawDocument, BsonEodPriceError> {
|
||||
if bytes.len() < 4 {
|
||||
return Err(BsonEodPriceError::TruncatedDocument {
|
||||
offset: 0,
|
||||
|
|
@ -471,10 +543,18 @@ pub fn decode_eod_price_bytes<'a>(
|
|||
declared_len,
|
||||
});
|
||||
}
|
||||
let doc = RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
RawDocument::from_bytes(bytes).map_err(|err| BsonEodPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawEodDailyBar`].
|
||||
pub fn decode_eod_price_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawEodDailyBar<'a>, BsonEodPriceError> {
|
||||
let doc = parse_single_raw_doc(bytes)?;
|
||||
decode_eod_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -783,3 +783,20 @@ fn corrupt_length_prefix_in_middle_stops_stream_cleanly() {
|
|||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_corruption_after_semantic_reject_takes_precedence() {
|
||||
let doc = make_valid_doc("CAD.FOREX", "2025-01-02", f64::NAN, 1.44, 1.42, 1.435, 0.0);
|
||||
let mut bytes = doc.as_bytes().to_vec();
|
||||
let close_elem_pos = bytes
|
||||
.windows(7)
|
||||
.position(|w| w == b"\x01close\0")
|
||||
.expect("find double element 'close'");
|
||||
bytes[close_elem_pos] = 0xFF;
|
||||
|
||||
let err = decode_eod_price_bytes(&bytes).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonEodPriceError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson to take precedence over InvalidNumber, got {err:?}"
|
||||
);
|
||||
}
|
||||
|
|
|
|||
863
tools/curate-etl/src/bson_qm_actions.rs
Normal file
863
tools/curate-etl/src/bson_qm_actions.rs
Normal file
|
|
@ -0,0 +1,863 @@
|
|||
//! Zero-copy raw BSON decoders for MongoDB `qmSplits` and `qmDividends` documents (`M1.2w`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawQmSplit`] and [`RawQmDividend`] views without allocating a `String` or
|
||||
//! `bson::Document` per row. Callers convert borrowed views into [`SplitEvent`], [`DividendEvent`],
|
||||
//! [`SplitActionEvent`], or [`DividendActionEvent`], optionally resolving `("qm", qmSearchCode, ex_date)`
|
||||
//! through a caller-supplied key mapper (such as [`crate::provider_mapping::ProviderMappingTable::resolve`]).
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! - `apps/stock/data-ingestion/src/handlers/qm/actions/events.action.ts:92-124`: writes
|
||||
//! `qmSearchCode`, `symbol`, `exchange`, `reportDate: new Date(x.date)` plus the spread
|
||||
//! QuoteMedia API payload into `qmDividends` and `qmSplits`.
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 25): documents `date`, `declared`, `splitratio`
|
||||
//! (`258` rows have `splitratio == 1`), and `usdFxRate` (bogus `usdFxRate: 1` on CAD dividend
|
||||
//! rows; contract rule: ignore `usdFxRate`).
|
||||
//! - **Unverified field names:** the raw MongoDB dividend cash and currency field names are not
|
||||
//! proven by any in-repo schema or fixture (`events.action.ts` spreads `...dividend` untyped).
|
||||
//! They are isolated in [`FIELD_DIVIDEND_CASH`] (`"amount"`) and [`FIELD_DIVIDEND_CURRENCY`]
|
||||
//! (`"currency"`) and explicitly listed under "Unverified field names" in `tools/curate-etl/README.md`.
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `qmSearchCode`, `currency`: BSON UTF-8 `String` (borrowed verbatim; empty or whitespace-only
|
||||
//! is rejected).
|
||||
//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` (validated via
|
||||
//! [`crate::split::ymd_to_epoch_days`]) or BSON `DateTime` (UTC epoch day via
|
||||
//! `timestamp_millis().div_euclid(86_400_000)` with `i32` bounds check).
|
||||
//! - `declared` (optional): absent, BSON `Null`, or empty/whitespace `String` maps to `None`;
|
||||
//! otherwise strict `YYYY-MM-DD` `String` or BSON `DateTime` maps to `Some(i32)`.
|
||||
//! - `splitratio`: BSON `Double`, `Int32`, or `Int64`; must be finite and `> 0.0`. `ratio == 1.0`
|
||||
//! no-ops are **decoded, not dropped** (downstream builders drop them) and counted in
|
||||
//! [`BsonQmActionDecodeStats::split_noop_ratio_one`].
|
||||
//! - `amount` (dividend cash): BSON `Double`, `Int32`, or `Int64`; must be finite and `>= 0.0`
|
||||
//! (`-0.0` is normalized to `+0.0`).
|
||||
//! - `usdFxRate` and all unknown extra fields (`_id`, `symbol`, `exchange`, `reportDate`,
|
||||
//! `created_at`, `updated_at`, nested objects/arrays, etc.) are skipped without calling
|
||||
//! `elem.value()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::adj::DividendEvent;
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
MILLIS_PER_DAY,
|
||||
};
|
||||
use crate::corporate_actions::{DividendActionEvent, SplitActionEvent};
|
||||
use crate::split::SplitEvent;
|
||||
|
||||
/// MongoDB field name for the QuoteMedia security key (`events.action.ts:98,118`).
|
||||
pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode";
|
||||
/// MongoDB field name for the ex-split / ex-dividend date (`events.action.ts:99,119`, `DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DATE: &str = "date";
|
||||
/// MongoDB field name for the optional declaration date (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_DECLARED: &str = "declared";
|
||||
/// MongoDB field name for the split ratio (`DATA-CONTRACTS.md:25`).
|
||||
///
|
||||
/// Empirically verified across all `18,751` documents in `qmSplits` (`16,892/16,892` with numeric
|
||||
/// `forfactor`/`tofactor`): QuoteMedia stores `splitratio = forfactor / tofactor = old_shares /
|
||||
/// new_shares` (e.g. `0.1` for a 10:1 forward split such as `NVDA 2024-06-10`, `8.0` for a 1:8
|
||||
/// reverse split such as `GE 2021-08-02`). [`decode_qm_split_doc`] converts this to canonical
|
||||
/// `new_shares / old_shares` via `tofactor / forfactor` when both are positive numbers (avoiding
|
||||
/// QuoteMedia's 6-decimal truncation such as `0.142857` for 7:1), or `1.0 / splitratio` otherwise.
|
||||
pub const FIELD_SPLIT_RATIO: &str = "splitratio";
|
||||
/// MongoDB field name for QuoteMedia's `old_shares` factor (`forfactor`).
|
||||
pub const FIELD_FOR_FACTOR: &str = "forfactor";
|
||||
/// MongoDB field name for QuoteMedia's `new_shares` factor (`tofactor`).
|
||||
pub const FIELD_TO_FACTOR: &str = "tofactor";
|
||||
/// MongoDB field name for the bogus FX field explicitly ignored per contract (`DATA-CONTRACTS.md:25`).
|
||||
pub const FIELD_USD_FX_RATE: &str = "usdFxRate";
|
||||
/// MongoDB field name for dividend cash amount (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CASH: &str = "amount";
|
||||
/// MongoDB field name for dividend currency code (**unverified in repo**; QuoteMedia convention).
|
||||
pub const FIELD_DIVIDEND_CURRENCY: &str = "currency";
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmSplits` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `ratio == 1.0` no-op rows are preserved here so downstream builders (`SplitTable`,
|
||||
/// `build_adj_factors`, `build_corporate_actions`) apply their own filtering and accounting.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmSplit<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-split date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// `new_shares / old_shares` (finite and `> 0.0`).
|
||||
pub ratio: f64,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmSplit<'a> {
|
||||
/// Converts this borrowed split into a [`SplitEvent`] for [`crate::split::SplitTable`] or
|
||||
/// [`crate::adj::build_adj_factors`].
|
||||
#[inline]
|
||||
pub fn to_split_event(self) -> SplitEvent {
|
||||
SplitEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed split into a [`SplitActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_split_action_event(self) -> SplitActionEvent {
|
||||
SplitActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
ratio: self.ratio,
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_event<K, F>(self, map_key: F) -> Option<(K, SplitEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_event()))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key and pairs it with [`SplitActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_split_action_event<K, F>(self, map_key: F) -> Option<(K, SplitActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_split_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmDividends` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` and `currency` directly from the underlying `&RawDocument` byte slice.
|
||||
/// Deliberately omits `usdFxRate` per `design/DATA-CONTRACTS.md` §1.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmDividend<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Ex-dividend date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub ex_date: i32,
|
||||
/// Cash dividend amount per share (finite and `>= 0.0`, with `-0.0` normalized to `+0.0`).
|
||||
pub cash: f64,
|
||||
/// Local dividend currency code (e.g. `"USD"`, `"CAD"`).
|
||||
pub currency: &'a str,
|
||||
/// Optional declaration date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub declared_date: Option<i32>,
|
||||
}
|
||||
|
||||
impl<'a> RawQmDividend<'a> {
|
||||
/// Converts this borrowed dividend into a [`DividendEvent`] for
|
||||
/// [`crate::adj::build_adj_factors`], attaching caller-supplied `prev_close` context.
|
||||
#[inline]
|
||||
pub fn to_dividend_event(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
) -> DividendEvent {
|
||||
DividendEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
prev_close,
|
||||
prev_close_currency,
|
||||
}
|
||||
}
|
||||
|
||||
/// Converts this borrowed dividend into a [`DividendActionEvent`] for
|
||||
/// [`crate::corporate_actions::build_corporate_actions`].
|
||||
#[inline]
|
||||
pub fn to_dividend_action_event(self) -> DividendActionEvent {
|
||||
DividendActionEvent {
|
||||
ex_date: self.ex_date,
|
||||
cash: self.cash,
|
||||
currency: self.currency.to_owned(),
|
||||
declared_date: self.declared_date,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves `(qm_search_code, ex_date)` via a caller-supplied key mapper
|
||||
/// (for example `|code, date| mapping.resolve("qm", code, date)`).
|
||||
#[inline]
|
||||
pub fn try_map_key<K, F>(self, map_key: F) -> Option<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
map_key(self.qm_search_code, self.ex_date)
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with [`DividendEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_event<K, F>(
|
||||
self,
|
||||
prev_close: Option<f64>,
|
||||
prev_close_currency: Option<String>,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_event(prev_close, prev_close_currency)))
|
||||
}
|
||||
|
||||
/// Fallibly resolves the key before allocating `currency` and pairs it with
|
||||
/// [`DividendActionEvent`].
|
||||
#[inline]
|
||||
pub fn try_into_dividend_action_event<K, F>(
|
||||
self,
|
||||
map_key: F,
|
||||
) -> Option<(K, DividendActionEvent)>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = self.try_map_key(map_key)?;
|
||||
Some((key, self.to_dividend_action_event()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `qmSplits` or `qmDividends` BSON documents or
|
||||
/// length-prefixed buffers.
|
||||
///
|
||||
/// Every field-level error names the offending BSON field in both its structure and `Display`
|
||||
/// output; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonQmActionError {
|
||||
/// A required field was absent from the document.
|
||||
MissingField { field: &'static str },
|
||||
/// A required string field was empty or contained only whitespace.
|
||||
EmptyField { field: &'static str },
|
||||
/// A decoded field had an unexpected BSON element type.
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A date field was not a valid strict `YYYY-MM-DD` Gregorian date or BSON `DateTime`
|
||||
/// overflowed `i32` epoch days.
|
||||
MalformedDate { field: &'static str },
|
||||
/// A numeric field was non-finite (`NaN`, `±inf`) or violated its domain bound (`> 0` for
|
||||
/// `splitratio`, `>= 0` for dividend cash).
|
||||
InvalidNumber { field: &'static str, value: f64 },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonQmActionError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "qm action BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(f, "qm action BSON field '{field}' must not be empty or blank")
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' is not a valid YYYY-MM-DD date or in-range DateTime"
|
||||
)
|
||||
}
|
||||
Self::InvalidNumber { field, value } => {
|
||||
write!(
|
||||
f,
|
||||
"qm action BSON field '{field}' has invalid numeric value {value}"
|
||||
)
|
||||
}
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonQmActionError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonQmActionError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmActionError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmActionError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonQmActionError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonQmActionError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonQmActionError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonQmActionError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => BsonQmActionError::MalformedDate { field },
|
||||
BsonEodPriceError::InvalidNumber { field, value } => {
|
||||
BsonQmActionError::InvalidNumber { field, value }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_qm_split_buffer`] and
|
||||
/// [`decode_qm_dividend_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
/// `split_noop_ratio_one` counts decoded `qmSplits` documents with `ratio == 1.0` (a subset of
|
||||
/// `decoded`, never added to `rejected_total()`).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonQmActionDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub decoded: usize,
|
||||
/// Decoded `qmSplits` rows with `splitratio == 1.0` (subset of `decoded`).
|
||||
pub split_noop_ratio_one: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_malformed_date: usize,
|
||||
pub rejected_invalid_number: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonQmActionDecodeStats {
|
||||
/// Total number of rejected documents across all error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_missing_field
|
||||
+ self.rejected_empty_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_malformed_date
|
||||
+ self.rejected_invalid_number
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonQmActionError) {
|
||||
match err {
|
||||
BsonQmActionError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonQmActionError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonQmActionError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonQmActionError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonQmActionError::InvalidNumber { .. } => self.rejected_invalid_number += 1,
|
||||
BsonQmActionError::TruncatedDocument { .. }
|
||||
| BsonQmActionError::CorruptDocumentLength { .. }
|
||||
| BsonQmActionError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.split_noop_ratio_one += other.split_noop_ratio_one;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_invalid_number += other.rejected_invalid_number;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonQmActionDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonQmActionError> {
|
||||
elem.value().map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_empty_str<'a>(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'a>,
|
||||
) -> Result<&'a str, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Err(BsonQmActionError::EmptyField { field });
|
||||
}
|
||||
Ok(s)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_required_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<i32, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
parse_ymd_strict_days(s).ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days).map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_optional_date(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<Option<i32>, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Null => Ok(None),
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
parse_ymd_strict_days(s)
|
||||
.map(Some)
|
||||
.ok_or(BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
RawBsonRef::DateTime(dt) => {
|
||||
let days = dt.timestamp_millis().div_euclid(MILLIS_PER_DAY);
|
||||
i32::try_from(days)
|
||||
.map(Some)
|
||||
.map_err(|_| BsonQmActionError::MalformedDate { field })
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_positive_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v <= 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v <= 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_non_negative_number(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmActionError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() || v < 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber { field, value: v });
|
||||
}
|
||||
if v == 0.0 {
|
||||
Ok(0.0)
|
||||
} else {
|
||||
Ok(v)
|
||||
}
|
||||
}
|
||||
RawBsonRef::Int32(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: f64::from(v),
|
||||
});
|
||||
}
|
||||
Ok(f64::from(v))
|
||||
}
|
||||
RawBsonRef::Int64(v) => {
|
||||
if v < 0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field,
|
||||
value: v as f64,
|
||||
});
|
||||
}
|
||||
Ok(v as f64)
|
||||
}
|
||||
other => Err(BsonQmActionError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_optional_positive_factor(val: RawBsonRef<'_>) -> Option<f64> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) if v.is_finite() && v > 0.0 => Some(v),
|
||||
RawBsonRef::Int32(v) if v > 0 => Some(f64::from(v)),
|
||||
RawBsonRef::Int64(v) if v > 0 => Some(v as f64),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_qm_split_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut raw_split_ratio: Option<f64> = None;
|
||||
let mut for_factor: Option<f64> = None;
|
||||
let mut to_factor: Option<f64> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_SPLIT_RATIO {
|
||||
let val = decode_element_value(FIELD_SPLIT_RATIO, elem, offset)?;
|
||||
raw_split_ratio = Some(decode_positive_number(FIELD_SPLIT_RATIO, val)?);
|
||||
} else if key == FIELD_FOR_FACTOR {
|
||||
let val = decode_element_value(FIELD_FOR_FACTOR, elem, offset)?;
|
||||
for_factor = decode_optional_positive_factor(val);
|
||||
} else if key == FIELD_TO_FACTOR {
|
||||
let val = decode_element_value(FIELD_TO_FACTOR, elem, offset)?;
|
||||
to_factor = decode_optional_positive_factor(val);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(raw_split_ratio) = raw_split_ratio else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
});
|
||||
};
|
||||
|
||||
// QuoteMedia stores `splitratio = forfactor / tofactor = old_shares / new_shares`.
|
||||
// Convert to canonical `new_shares / old_shares`, preferring exact `tofactor / forfactor`
|
||||
// when both are present and positive.
|
||||
let ratio = match (for_factor, to_factor) {
|
||||
(Some(f), Some(t)) => {
|
||||
let exact = t / f;
|
||||
if exact.is_finite() && exact > 0.0 {
|
||||
exact
|
||||
} else {
|
||||
1.0 / raw_split_ratio
|
||||
}
|
||||
}
|
||||
_ => 1.0 / raw_split_ratio,
|
||||
};
|
||||
if !ratio.is_finite() || ratio <= 0.0 {
|
||||
return Err(BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
value: raw_split_ratio,
|
||||
});
|
||||
}
|
||||
|
||||
Ok(RawQmSplit {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
ratio,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_qm_dividend_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut ex_date: Option<i32> = None;
|
||||
let mut cash: Option<f64> = None;
|
||||
let mut currency: Option<&'a str> = None;
|
||||
let mut declared_date: Option<i32> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmActionError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_QM_SEARCH_CODE {
|
||||
let val = decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)?;
|
||||
qm_search_code = Some(decode_non_empty_str(FIELD_QM_SEARCH_CODE, val)?);
|
||||
} else if key == FIELD_DATE {
|
||||
let val = decode_element_value(FIELD_DATE, elem, offset)?;
|
||||
ex_date = Some(decode_required_date(FIELD_DATE, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CASH {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CASH, elem, offset)?;
|
||||
cash = Some(decode_non_negative_number(FIELD_DIVIDEND_CASH, val)?);
|
||||
} else if key == FIELD_DIVIDEND_CURRENCY {
|
||||
let val = decode_element_value(FIELD_DIVIDEND_CURRENCY, elem, offset)?;
|
||||
currency = Some(decode_non_empty_str(FIELD_DIVIDEND_CURRENCY, val)?);
|
||||
} else if key == FIELD_DECLARED {
|
||||
let val = decode_element_value(FIELD_DECLARED, elem, offset)?;
|
||||
declared_date = decode_optional_date(FIELD_DECLARED, val)?;
|
||||
}
|
||||
// `FIELD_USD_FX_RATE` and all unknown extra fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(ex_date) = ex_date else {
|
||||
return Err(BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(cash) = cash else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
});
|
||||
};
|
||||
let Some(currency) = currency else {
|
||||
return Err(BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmDividend {
|
||||
qm_search_code,
|
||||
ex_date,
|
||||
cash,
|
||||
currency,
|
||||
declared_date,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmSplits` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_split_doc<'a>(doc: &'a RawDocument) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmSplit`].
|
||||
pub fn decode_qm_split_bytes<'a>(bytes: &'a [u8]) -> Result<RawQmSplit<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_split_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmDividends` MongoDB document in one forward
|
||||
/// pass without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_dividend_doc<'a>(
|
||||
doc: &'a RawDocument,
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed
|
||||
/// [`RawQmDividend`].
|
||||
pub fn decode_qm_dividend_bytes<'a>(
|
||||
bytes: &'a [u8],
|
||||
) -> Result<RawQmDividend<'a>, BsonQmActionError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_dividend_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_split_doc`], invoking
|
||||
/// `on_split` for every valid document (including `splitratio == 1.0`, counted in
|
||||
/// `stats.split_noop_ratio_one`) and `on_error(byte_offset, err)` for every rejected document
|
||||
/// without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_split_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_split: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmSplit<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_split_doc_at(doc, doc_offset) {
|
||||
Ok(split) => {
|
||||
stats.decoded += 1;
|
||||
if split.ratio == 1.0 {
|
||||
stats.split_noop_ratio_one += 1;
|
||||
}
|
||||
on_split(split);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_dividend_doc`], invoking
|
||||
/// `on_dividend` for every valid document and `on_error(byte_offset, err)` for every rejected
|
||||
/// document without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_dividend_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_dividend: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmActionDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmDividend<'a>),
|
||||
E: FnMut(usize, BsonQmActionError),
|
||||
{
|
||||
let mut stats = BsonQmActionDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_dividend_doc_at(doc, doc_offset) {
|
||||
Ok(dividend) => {
|
||||
stats.decoded += 1;
|
||||
on_dividend(dividend);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_qm_actions_tests.rs"]
|
||||
mod tests;
|
||||
918
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
918
tools/curate-etl/src/bson_qm_actions_tests.rs
Normal file
|
|
@ -0,0 +1,918 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::corporate_actions::{build_corporate_actions, CorporateActionKind, KnownAtSource};
|
||||
use crate::curate_adj::curate_adj_factors;
|
||||
use crate::provider_mapping::{ProviderMappingRow, ProviderMappingTable};
|
||||
use crate::split::{ymd_to_epoch_days, SplitTable};
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_split_doc(code: &str, date: &str, ratio: f64, declared: Option<&str>) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
if ratio.is_finite() && ratio > 0.0 {
|
||||
doc.append(cstr!("splitratio"), 1.0 / ratio);
|
||||
doc.append(cstr!("forfactor"), 1.0_f64);
|
||||
doc.append(cstr!("tofactor"), ratio);
|
||||
} else {
|
||||
doc.append(cstr!("splitratio"), ratio);
|
||||
}
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
fn make_dividend_doc(
|
||||
code: &str,
|
||||
date: &str,
|
||||
cash: f64,
|
||||
currency: &str,
|
||||
declared: Option<&str>,
|
||||
) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("amount"), cash);
|
||||
doc.append(cstr!("currency"), currency);
|
||||
if let Some(decl) = declared {
|
||||
doc.append(cstr!("declared"), decl);
|
||||
}
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_qm_split_and_dividend_docs_and_ignores_extra_and_usd_fx_rate() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "quotemedia");
|
||||
nested.append(cstr!("version"), 1_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("ca");
|
||||
tags.push("equity");
|
||||
|
||||
// Realistic qmSplits document with extra metadata and bogus usdFxRate.
|
||||
let mut split_doc = RawDocumentBuf::new();
|
||||
split_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
split_doc.append(cstr!("symbol"), "NVDA");
|
||||
split_doc.append(cstr!("exchange"), "NASDAQ");
|
||||
split_doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
split_doc.append(cstr!("date"), "2024-06-10");
|
||||
split_doc.append(cstr!("declared"), "2024-05-22");
|
||||
split_doc.append(cstr!("forfactor"), 1_i32);
|
||||
split_doc.append(cstr!("tofactor"), 10_i32);
|
||||
split_doc.append(cstr!("splitratio"), 0.1_f64);
|
||||
split_doc.append(cstr!("usdFxRate"), "bogus-ignored-type");
|
||||
split_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 10)) * MILLIS_PER_DAY),
|
||||
);
|
||||
split_doc.append(cstr!("created_at"), DateTime::from_millis(1_718_000_000_000));
|
||||
split_doc.append(cstr!("updated_at"), DateTime::from_millis(1_718_000_060_000));
|
||||
split_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
split_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let split = decode_qm_split_doc(&split_doc).unwrap();
|
||||
assert_eq!(split.qm_search_code, "NVDA");
|
||||
assert_eq!(split.ex_date, day(2024, 6, 10));
|
||||
assert_eq!(split.ratio.to_bits(), 10.0_f64.to_bits());
|
||||
assert_eq!(split.declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(decode_qm_split_bytes(split_doc.as_bytes()).unwrap(), split);
|
||||
|
||||
// Realistic qmDividends document with bogus usdFxRate: 1 on CAD row.
|
||||
let mut div_doc = RawDocumentBuf::new();
|
||||
div_doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1]),
|
||||
);
|
||||
div_doc.append(cstr!("symbol"), "RY");
|
||||
div_doc.append(cstr!("exchange"), "TSX");
|
||||
div_doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
div_doc.append(cstr!("date"), "2024-11-15");
|
||||
div_doc.append(cstr!("declared"), "2024-10-30");
|
||||
div_doc.append(cstr!("amount"), 1.42_f64);
|
||||
div_doc.append(cstr!("currency"), "CAD");
|
||||
div_doc.append(cstr!("usdFxRate"), 1_i32);
|
||||
div_doc.append(
|
||||
cstr!("reportDate"),
|
||||
DateTime::from_millis(i64::from(day(2024, 11, 15)) * MILLIS_PER_DAY),
|
||||
);
|
||||
div_doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
div_doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_doc).unwrap();
|
||||
assert_eq!(div.qm_search_code, "RY:CA");
|
||||
assert_eq!(div.ex_date, day(2024, 11, 15));
|
||||
assert_eq!(div.cash.to_bits(), 1.42_f64.to_bits());
|
||||
assert_eq!(div.currency, "CAD");
|
||||
assert_eq!(div.declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(decode_qm_dividend_bytes(div_doc.as_bytes()).unwrap(), div);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_date_and_declared_as_string_and_datetime_including_pre_1970_and_leap_day() {
|
||||
// Pre-1970 mid-day: 1969-12-31T12:34:56.789Z must floor to epoch day -1 (not 0).
|
||||
let pre_1970_ex_ms: i64 = -MILLIS_PER_DAY + (12 * 3600 + 34 * 60 + 56) * 1000 + 789;
|
||||
let pre_1970_decl_ms: i64 = -10 * MILLIS_PER_DAY + 43_200_000;
|
||||
|
||||
let mut split_dt = RawDocumentBuf::new();
|
||||
split_dt.append(cstr!("qmSearchCode"), "IBM");
|
||||
split_dt.append(cstr!("date"), DateTime::from_millis(pre_1970_ex_ms));
|
||||
split_dt.append(cstr!("declared"), DateTime::from_millis(pre_1970_decl_ms));
|
||||
split_dt.append(cstr!("splitratio"), 0.5_f64);
|
||||
|
||||
let split = decode_qm_split_doc(&split_dt).unwrap();
|
||||
assert_eq!(split.ex_date, -1);
|
||||
assert_eq!(split.declared_date, Some(-10));
|
||||
assert_eq!(split.ratio, 2.0);
|
||||
|
||||
// Leap day string + DateTime declared.
|
||||
let mut div_leap = RawDocumentBuf::new();
|
||||
div_leap.append(cstr!("qmSearchCode"), "TD:CA");
|
||||
div_leap.append(cstr!("date"), "2024-02-29");
|
||||
div_leap.append(
|
||||
cstr!("declared"),
|
||||
DateTime::from_millis(i64::from(day(2024, 2, 1)) * MILLIS_PER_DAY + 36_000_000),
|
||||
);
|
||||
div_leap.append(cstr!("amount"), 1.02_f64);
|
||||
div_leap.append(cstr!("currency"), "CAD");
|
||||
|
||||
let div = decode_qm_dividend_doc(&div_leap).unwrap();
|
||||
assert_eq!(div.ex_date, day(2024, 2, 29));
|
||||
assert_eq!(div.declared_date, Some(day(2024, 2, 1)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_double_int32_int64_numerics_and_normalizes_negative_zero_cash() {
|
||||
// Splits: Double, Int32, Int64 (QuoteMedia stores old_shares / new_shares, inverted to new/old).
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(20.0), 0.05_f64),
|
||||
(RawBsonRef::Int32(4), 0.25_f64),
|
||||
(RawBsonRef::Int64(10), 0.1_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
let decoded = decode_qm_split_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.ratio.to_bits(), expected.to_bits());
|
||||
}
|
||||
|
||||
// Exact forfactor / tofactor precedence over truncated splitratio (e.g. AAPL 7:1, GE 1:8, NVDA 2:1 empty).
|
||||
{
|
||||
let mut aapl = RawDocumentBuf::new();
|
||||
aapl.append(cstr!("qmSearchCode"), "AAPL");
|
||||
aapl.append(cstr!("date"), "2014-06-09");
|
||||
aapl.append(cstr!("forfactor"), 1_i32);
|
||||
aapl.append(cstr!("tofactor"), 7_i32);
|
||||
aapl.append(cstr!("splitratio"), 0.142857_f64);
|
||||
assert_eq!(decode_qm_split_doc(&aapl).unwrap().ratio, 7.0);
|
||||
|
||||
let mut ge = RawDocumentBuf::new();
|
||||
ge.append(cstr!("qmSearchCode"), "GE");
|
||||
ge.append(cstr!("date"), "2021-08-02");
|
||||
ge.append(cstr!("forfactor"), 8_i32);
|
||||
ge.append(cstr!("tofactor"), 1_i32);
|
||||
ge.append(cstr!("splitratio"), 8_i32);
|
||||
assert_eq!(decode_qm_split_doc(&ge).unwrap().ratio, 0.125);
|
||||
|
||||
let mut nvda_legacy = RawDocumentBuf::new();
|
||||
nvda_legacy.append(cstr!("qmSearchCode"), "NVDA");
|
||||
nvda_legacy.append(cstr!("date"), "2000-06-27");
|
||||
nvda_legacy.append(cstr!("forfactor"), "");
|
||||
nvda_legacy.append(cstr!("tofactor"), "");
|
||||
nvda_legacy.append(cstr!("splitratio"), 0.5_f64);
|
||||
assert_eq!(decode_qm_split_doc(&nvda_legacy).unwrap().ratio, 2.0);
|
||||
}
|
||||
|
||||
// Dividends: Double, Int32, Int64, 0, and -0.0 -> +0.0.
|
||||
for (val, expected) in [
|
||||
(RawBsonRef::Double(0.25), 0.25_f64),
|
||||
(RawBsonRef::Double(-0.0), 0.0_f64),
|
||||
(RawBsonRef::Double(0.0), 0.0_f64),
|
||||
(RawBsonRef::Int32(0), 0.0_f64),
|
||||
(RawBsonRef::Int32(2), 2.0_f64),
|
||||
(RawBsonRef::Int64(0), 0.0_f64),
|
||||
(RawBsonRef::Int64(5), 5.0_f64),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "TEST");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), val);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let decoded = decode_qm_dividend_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.cash.to_bits(), expected.to_bits());
|
||||
assert!(!decoded.cash.is_sign_negative());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handles_optional_declared_missing_null_empty_malformed_and_wrong_type() {
|
||||
// Missing declared -> None.
|
||||
let s_missing = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
assert_eq!(decode_qm_split_doc(&s_missing).unwrap().declared_date, None);
|
||||
|
||||
// Null declared -> None.
|
||||
let mut s_null = make_split_doc("AAPL", "2020-08-31", 4.0, None);
|
||||
s_null.append(cstr!("declared"), RawBsonRef::Null);
|
||||
assert_eq!(decode_qm_split_doc(&s_null).unwrap().declared_date, None);
|
||||
|
||||
// Empty and whitespace-only declared -> None.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let d_blank = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", Some(blank));
|
||||
assert_eq!(
|
||||
decode_qm_dividend_doc(&d_blank).unwrap().declared_date,
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
// Malformed declared -> MalformedDate naming "declared".
|
||||
let s_bad = make_split_doc("AAPL", "2020-08-31", 4.0, Some("2023-02-29"));
|
||||
let err = decode_qm_split_doc(&s_bad).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
|
||||
// Wrong type on declared -> WrongType naming "declared".
|
||||
let mut d_wrong = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
d_wrong.append(cstr!("declared"), 20240801_i32);
|
||||
let err = decode_qm_dividend_doc(&d_wrong).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DECLARED,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DECLARED));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_ratio_one_is_decoded_not_dropped_and_counted_as_noop() {
|
||||
let mut buf = Vec::new();
|
||||
for val in [
|
||||
RawBsonRef::Double(1.0),
|
||||
RawBsonRef::Int32(1),
|
||||
RawBsonRef::Int64(1),
|
||||
RawBsonRef::Double(0.5),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NOOP");
|
||||
doc.append(cstr!("date"), "2024-03-15");
|
||||
doc.append(cstr!("splitratio"), val);
|
||||
buf.extend_from_slice(doc.as_bytes());
|
||||
}
|
||||
|
||||
let mut decoded_ratios = Vec::new();
|
||||
let stats = decode_qm_split_buffer(
|
||||
&buf,
|
||||
|s| decoded_ratios.push(s.ratio),
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
assert_eq!(decoded_ratios, vec![1.0, 1.0, 1.0, 2.0]);
|
||||
assert_eq!(stats.docs_in, 4);
|
||||
assert_eq!(stats.decoded, 4);
|
||||
assert_eq!(stats.split_noop_ratio_one, 3);
|
||||
assert_eq!(stats.rejected_total(), 0);
|
||||
assert_eq!(stats.decoded + stats.rejected_total(), stats.docs_in);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_every_error_variant_and_names_offending_field() {
|
||||
// 1. Missing required fields on splits.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_SPLIT_RATIO
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 2. Missing required fields on dividends.
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "USD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MissingField { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CASH
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 0.5_f64);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MissingField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 3. Empty / whitespace-only string fields.
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let s = make_split_doc(blank, "2024-06-10", 2.0, None);
|
||||
let err = decode_qm_split_doc(&s).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
|
||||
let d = make_dividend_doc("RY:CA", "2024-06-10", 0.5, blank, None);
|
||||
let err = decode_qm_dividend_doc(&d).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::EmptyField {
|
||||
field: FIELD_DIVIDEND_CURRENCY
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 4. Wrong BSON types (including string-encoded numerics).
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), 123_i32);
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), 20240610_i32);
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::Int32,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), "10.0");
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), "1.42");
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
actual: ElementType::String,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), 1.42_f64);
|
||||
doc.append(cstr!("currency"), true);
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::WrongType {
|
||||
field: FIELD_DIVIDEND_CURRENCY,
|
||||
actual: ElementType::Boolean,
|
||||
}
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CURRENCY));
|
||||
}
|
||||
|
||||
// 5. Malformed dates (bad calendar date, bad format, and DateTime overflowing i32 days).
|
||||
for bad_date in ["2023-02-29", "2024/06/10", "2024-6-10", "not-a-date"] {
|
||||
let doc = make_split_doc("NVDA", bad_date, 2.0, None);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
assert!(err.to_string().contains(FIELD_DATE));
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), DateTime::from_millis(i64::MAX));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(err, BsonQmActionError::MalformedDate { field: FIELD_DATE });
|
||||
}
|
||||
{
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("declared"), DateTime::from_millis(i64::MIN));
|
||||
doc.append(cstr!("splitratio"), 2.0_f64);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert_eq!(
|
||||
err,
|
||||
BsonQmActionError::MalformedDate {
|
||||
field: FIELD_DECLARED
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// 6. Invalid numeric values for splitratio (<= 0 or non-finite).
|
||||
for bad_ratio in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(0.0),
|
||||
RawBsonRef::Double(-0.0),
|
||||
RawBsonRef::Double(-2.0),
|
||||
RawBsonRef::Int32(0),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(0),
|
||||
RawBsonRef::Int64(-5),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("splitratio"), bad_ratio);
|
||||
let err = decode_qm_split_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_SPLIT_RATIO,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_ratio:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_SPLIT_RATIO));
|
||||
}
|
||||
|
||||
// 7. Invalid numeric values for dividend cash (< 0 or non-finite).
|
||||
for bad_cash in [
|
||||
RawBsonRef::Double(f64::NAN),
|
||||
RawBsonRef::Double(f64::INFINITY),
|
||||
RawBsonRef::Double(f64::NEG_INFINITY),
|
||||
RawBsonRef::Double(-0.01),
|
||||
RawBsonRef::Int32(-1),
|
||||
RawBsonRef::Int64(-10),
|
||||
] {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc.append(cstr!("date"), "2024-06-10");
|
||||
doc.append(cstr!("amount"), bad_cash);
|
||||
doc.append(cstr!("currency"), "CAD");
|
||||
let err = decode_qm_dividend_doc(&doc).unwrap_err();
|
||||
assert!(
|
||||
matches!(
|
||||
err,
|
||||
BsonQmActionError::InvalidNumber {
|
||||
field: FIELD_DIVIDEND_CASH,
|
||||
..
|
||||
}
|
||||
),
|
||||
"expected InvalidNumber for {bad_cash:?}, got {err:?}"
|
||||
);
|
||||
assert!(err.to_string().contains(FIELD_DIVIDEND_CASH));
|
||||
}
|
||||
|
||||
// 8. Truncated and corrupt documents (zero panics).
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&[]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 0,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_dividend_bytes(&[1, 2, 3]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
remaining: 3,
|
||||
declared_len: None
|
||||
})
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&4_i32.to_le_bytes()),
|
||||
Err(BsonQmActionError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
})
|
||||
));
|
||||
let valid_bytes = make_split_doc("NVDA", "2024-06-10", 10.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&valid_bytes[..valid_bytes.len() - 1]),
|
||||
Err(BsonQmActionError::TruncatedDocument {
|
||||
offset: 0,
|
||||
declared_len: Some(_),
|
||||
..
|
||||
})
|
||||
));
|
||||
let mut with_trailing = valid_bytes.clone();
|
||||
with_trailing.push(0);
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&with_trailing),
|
||||
Err(BsonQmActionError::CorruptDocumentLength { offset: 0, .. })
|
||||
));
|
||||
let mut bad_terminator = valid_bytes;
|
||||
*bad_terminator.last_mut().unwrap() = 0xFF;
|
||||
assert!(matches!(
|
||||
decode_qm_split_bytes(&bad_terminator),
|
||||
Err(BsonQmActionError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Invalid UTF-8 inside a known string field (`qmSearchCode`).
|
||||
let mut invalid_utf8_doc: Vec<u8> = Vec::new();
|
||||
// Placeholder 4-byte length.
|
||||
invalid_utf8_doc.extend_from_slice(&0_i32.to_le_bytes());
|
||||
invalid_utf8_doc.push(0x02); // UTF-8 String element
|
||||
invalid_utf8_doc.extend_from_slice(b"qmSearchCode\0");
|
||||
invalid_utf8_doc.extend_from_slice(&3_i32.to_le_bytes()); // 2 bytes + NUL
|
||||
invalid_utf8_doc.extend_from_slice(&[0xFF, 0xFE, 0x00]);
|
||||
invalid_utf8_doc.push(0x00); // doc terminator
|
||||
let total_len = invalid_utf8_doc.len() as i32;
|
||||
invalid_utf8_doc[0..4].copy_from_slice(&total_len.to_le_bytes());
|
||||
let err = decode_qm_split_bytes(&invalid_utf8_doc).unwrap_err();
|
||||
assert!(matches!(err, BsonQmActionError::CorruptBson { offset: 0, .. }));
|
||||
assert!(err.to_string().contains(FIELD_QM_SEARCH_CODE));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn buffer_decoders_survive_per_doc_errors_and_reconcile_stats_for_both_collections() {
|
||||
// 1. qmSplits mixed valid/invalid buffer.
|
||||
let s1 = make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22"));
|
||||
let s_noop = make_split_doc("NOOP", "2024-06-11", 1.0, None);
|
||||
let mut s_missing = RawDocumentBuf::new();
|
||||
s_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
s_missing.append(cstr!("date"), "2024-06-12");
|
||||
let s_empty = make_split_doc(" ", "2024-06-13", 2.0, None);
|
||||
let mut s_wrong = RawDocumentBuf::new();
|
||||
s_wrong.append(cstr!("qmSearchCode"), "WRNG");
|
||||
s_wrong.append(cstr!("date"), "2024-06-14");
|
||||
s_wrong.append(cstr!("splitratio"), "2.0");
|
||||
let s_bad_date = make_split_doc("DATE", "2023-02-29", 2.0, None);
|
||||
let s_bad_num = make_split_doc("NUM", "2024-06-15", 0.0, None);
|
||||
let mut s_corrupt = make_split_doc("CORR", "2024-06-16", 2.0, None)
|
||||
.as_bytes()
|
||||
.to_vec();
|
||||
*s_corrupt.last_mut().unwrap() = 0xAA;
|
||||
let s2 = make_split_doc("NEXM:CA", "2025-06-18", 0.05, None);
|
||||
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(s1.as_bytes());
|
||||
split_buf.extend_from_slice(s_noop.as_bytes());
|
||||
split_buf.extend_from_slice(s_missing.as_bytes());
|
||||
split_buf.extend_from_slice(s_empty.as_bytes());
|
||||
split_buf.extend_from_slice(s_wrong.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_date.as_bytes());
|
||||
split_buf.extend_from_slice(s_bad_num.as_bytes());
|
||||
split_buf.extend_from_slice(&s_corrupt);
|
||||
split_buf.extend_from_slice(s2.as_bytes());
|
||||
|
||||
let mut split_codes = Vec::new();
|
||||
let mut split_errors = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| split_codes.push(s.qm_search_code.to_owned()),
|
||||
|off, err| split_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(split_codes, vec!["NVDA", "NOOP", "NEXM:CA"]);
|
||||
assert_eq!(split_errors.len(), 6);
|
||||
assert_eq!(split_stats.docs_in, 9);
|
||||
assert_eq!(split_stats.decoded, 3);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
assert_eq!(split_stats.rejected_missing_field, 1);
|
||||
assert_eq!(split_stats.rejected_empty_field, 1);
|
||||
assert_eq!(split_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(split_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(split_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(split_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
split_stats.decoded + split_stats.rejected_total(),
|
||||
split_stats.docs_in
|
||||
);
|
||||
|
||||
// 2. qmDividends mixed valid/invalid buffer ending with a corrupt length prefix.
|
||||
let d1 = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
let mut d_missing = RawDocumentBuf::new();
|
||||
d_missing.append(cstr!("qmSearchCode"), "MISS");
|
||||
d_missing.append(cstr!("date"), "2024-11-15");
|
||||
d_missing.append(cstr!("amount"), 0.5_f64);
|
||||
let d_empty = make_dividend_doc("RY:CA", "2024-11-15", 0.5, " ", None);
|
||||
let mut d_wrong = RawDocumentBuf::new();
|
||||
d_wrong.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_wrong.append(cstr!("date"), "2024-11-15");
|
||||
d_wrong.append(cstr!("amount"), "0.5");
|
||||
d_wrong.append(cstr!("currency"), "CAD");
|
||||
let d_bad_date = make_dividend_doc("RY:CA", "2024-11-15", 0.5, "CAD", Some("bad"));
|
||||
let d_bad_num = make_dividend_doc("RY:CA", "2024-11-15", -0.1, "CAD", None);
|
||||
let d2 = make_dividend_doc("AAPL", "2024-08-12", 0.25, "USD", None);
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
div_buf.extend_from_slice(d1.as_bytes());
|
||||
div_buf.extend_from_slice(d_missing.as_bytes());
|
||||
div_buf.extend_from_slice(d_empty.as_bytes());
|
||||
div_buf.extend_from_slice(d_wrong.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_date.as_bytes());
|
||||
div_buf.extend_from_slice(d_bad_num.as_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
// Trailing corrupt length < 5 stops cleanly.
|
||||
div_buf.extend_from_slice(&2_i32.to_le_bytes());
|
||||
div_buf.extend_from_slice(d2.as_bytes());
|
||||
|
||||
let mut div_codes = Vec::new();
|
||||
let mut div_errors = Vec::new();
|
||||
let div_stats = decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| div_codes.push(d.qm_search_code.to_owned()),
|
||||
|off, err| div_errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(div_codes, vec!["RY:CA", "AAPL"]);
|
||||
assert_eq!(div_errors.len(), 6);
|
||||
assert_eq!(div_stats.docs_in, 8);
|
||||
assert_eq!(div_stats.decoded, 2);
|
||||
assert_eq!(div_stats.split_noop_ratio_one, 0);
|
||||
assert_eq!(div_stats.rejected_missing_field, 1);
|
||||
assert_eq!(div_stats.rejected_empty_field, 1);
|
||||
assert_eq!(div_stats.rejected_wrong_type, 1);
|
||||
assert_eq!(div_stats.rejected_malformed_date, 1);
|
||||
assert_eq!(div_stats.rejected_invalid_number, 1);
|
||||
assert_eq!(div_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(
|
||||
div_stats.decoded + div_stats.rejected_total(),
|
||||
div_stats.docs_in
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decoded_events_feed_split_table_curate_adj_factors_and_corporate_actions_unchanged() {
|
||||
// 1. SplitTable interoperability (NVDA 10:1 forward, NEXM:CA 1:20 reverse, 1:1 no-op).
|
||||
let mut split_buf = Vec::new();
|
||||
split_buf.extend_from_slice(
|
||||
make_split_doc("NVDA", "2024-06-10", 10.0, Some("2024-05-22")).as_bytes(),
|
||||
);
|
||||
split_buf.extend_from_slice(make_split_doc("NVDA", "2024-07-01", 1.0, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("NEXM:CA", "2025-06-18", 0.05, None).as_bytes());
|
||||
split_buf.extend_from_slice(make_split_doc("UNMAPPED", "2024-06-10", 2.0, None).as_bytes());
|
||||
|
||||
let mut div_buf = Vec::new();
|
||||
let mut ry_div = make_dividend_doc("RY:CA", "2024-11-15", 1.42, "CAD", Some("2024-10-30"));
|
||||
ry_div.append(cstr!("usdFxRate"), 1_i32); // bogus usdFxRate must have zero effect
|
||||
div_buf.extend_from_slice(ry_div.as_bytes());
|
||||
let mut unmapped_div = make_dividend_doc("UNMAPPED", "2024-11-15", 0.50, "USD", None);
|
||||
unmapped_div.append(cstr!("usdFxRate"), 999.0_f64);
|
||||
div_buf.extend_from_slice(unmapped_div.as_bytes());
|
||||
|
||||
let mut source_splits = Vec::new();
|
||||
let split_stats = decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| source_splits.push((s.qm_search_code.to_owned(), s.to_split_event())),
|
||||
|_, err| panic!("unexpected split decode error: {err}"),
|
||||
);
|
||||
assert_eq!(split_stats.split_noop_ratio_one, 1);
|
||||
|
||||
let table = SplitTable::from_events(source_splits.iter().cloned()).unwrap();
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 7)), 10.0);
|
||||
assert_eq!(table.cum_factor_after("NVDA", day(2024, 6, 10)), 1.0);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 17)), 0.05);
|
||||
assert_eq!(table.cum_factor_after("NEXM:CA", day(2025, 6, 18)), 1.0);
|
||||
|
||||
// 2. ProviderMappingTable + curate_adj_factors interoperability.
|
||||
let mapping = ProviderMappingTable::from_rows([
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NVDA".to_string(),
|
||||
listing_id: 101,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "NEXM:CA".to_string(),
|
||||
listing_id: 202,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
ProviderMappingRow {
|
||||
source: "qm".to_string(),
|
||||
source_id: "RY:CA".to_string(),
|
||||
listing_id: 303,
|
||||
valid_from: day(2020, 1, 1),
|
||||
valid_to: None,
|
||||
},
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
let mut source_divs = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
source_divs.push((
|
||||
d.qm_search_code.to_owned(),
|
||||
d.to_dividend_event(Some(142.0), Some("CAD".to_string())),
|
||||
));
|
||||
},
|
||||
|_, err| panic!("unexpected dividend decode error: {err}"),
|
||||
);
|
||||
|
||||
let curated = curate_adj_factors(&mapping, "qm", source_splits, source_divs).unwrap();
|
||||
// 1:1 NVDA split dropped by builder; UNMAPPED split & dividend dropped by mapping.
|
||||
assert_eq!(curated.rows.len(), 3);
|
||||
assert_eq!(curated.stats.builder.split_noops_dropped, 1);
|
||||
assert_eq!(curated.stats.splits_dropped_unmapped, 1);
|
||||
assert_eq!(curated.stats.dividends_dropped_unmapped, 1);
|
||||
|
||||
// Row 0: listing 101 (NVDA) 10:1 split
|
||||
assert_eq!(curated.rows[0].listing_id, 101);
|
||||
assert_eq!(curated.rows[0].ex_date, day(2024, 6, 10));
|
||||
assert_eq!(curated.rows[0].split_factor, 10.0);
|
||||
assert_eq!(curated.rows[0].cum_split_factor, 10.0);
|
||||
|
||||
// Row 1: listing 202 (NEXM:CA) 1:20 reverse split
|
||||
assert_eq!(curated.rows[1].listing_id, 202);
|
||||
assert_eq!(curated.rows[1].ex_date, day(2025, 6, 18));
|
||||
assert_eq!(curated.rows[1].split_factor, 0.05);
|
||||
|
||||
// Row 2: listing 303 (RY:CA) CAD dividend with usdFxRate ignored
|
||||
assert_eq!(curated.rows[2].listing_id, 303);
|
||||
assert_eq!(curated.rows[2].ex_date, day(2024, 11, 15));
|
||||
assert_eq!(curated.rows[2].div_cash, 1.42);
|
||||
assert_eq!(curated.rows[2].div_currency.as_deref(), Some("CAD"));
|
||||
let expected_div_factor = 142.0 / (142.0 - 1.42);
|
||||
assert!((curated.rows[2].cum_total_factor - expected_div_factor).abs() < 1e-12);
|
||||
|
||||
// 3. try_map_key / try_into_*_action_event -> build_corporate_actions.
|
||||
let mut mapped_split_actions = Vec::new();
|
||||
decode_qm_split_buffer(
|
||||
&split_buf,
|
||||
|s| {
|
||||
if let Some(pair) =
|
||||
s.try_into_split_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_split_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
let mut mapped_div_actions = Vec::new();
|
||||
decode_qm_dividend_buffer(
|
||||
&div_buf,
|
||||
|d| {
|
||||
if let Some(pair) =
|
||||
d.try_into_dividend_action_event(|code, date| mapping.resolve("qm", code, date))
|
||||
{
|
||||
mapped_div_actions.push(pair);
|
||||
}
|
||||
},
|
||||
|_, err| panic!("unexpected error: {err}"),
|
||||
);
|
||||
|
||||
// Also verify try_into_split_event & try_into_dividend_event filter unmapped keys.
|
||||
let unmapped_split_doc = make_split_doc("UNMAPPED", "2024-06-10", 2.0, None);
|
||||
let unmapped_split = decode_qm_split_doc(&unmapped_split_doc).unwrap();
|
||||
assert_eq!(
|
||||
unmapped_split.try_into_split_event(|code, date| mapping.resolve("qm", code, date)),
|
||||
None
|
||||
);
|
||||
let mapped_div = decode_qm_dividend_doc(&ry_div).unwrap();
|
||||
let (lid, div_ev) = mapped_div
|
||||
.try_into_dividend_event(Some(142.0), Some("CAD".to_string()), |code, date| {
|
||||
mapping.resolve("qm", code, date)
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(lid, 303);
|
||||
assert_eq!(div_ev.currency, "CAD");
|
||||
|
||||
let ca = build_corporate_actions(
|
||||
mapped_split_actions,
|
||||
mapped_div_actions,
|
||||
std::iter::empty(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(ca.rows.len(), 3);
|
||||
assert_eq!(ca.stats.split_noops_dropped, 1);
|
||||
|
||||
// NVDA split has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[0].key, 101);
|
||||
assert_eq!(ca.rows[0].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[0].declared_date, Some(day(2024, 5, 22)));
|
||||
assert_eq!(ca.rows[0].known_at_source, KnownAtSource::DeclaredDate);
|
||||
|
||||
// NEXM split has no declared_date -> ExDateFallback.
|
||||
assert_eq!(ca.rows[1].key, 202);
|
||||
assert_eq!(ca.rows[1].kind, CorporateActionKind::Split);
|
||||
assert_eq!(ca.rows[1].declared_date, None);
|
||||
assert_eq!(ca.rows[1].known_at_source, KnownAtSource::ExDateFallback);
|
||||
|
||||
// RY:CA dividend has declared_date -> DeclaredDate.
|
||||
assert_eq!(ca.rows[2].key, 303);
|
||||
assert_eq!(ca.rows[2].kind, CorporateActionKind::Dividend);
|
||||
assert_eq!(ca.rows[2].cash_amount, Some(1.42));
|
||||
assert_eq!(ca.rows[2].currency.as_deref(), Some("CAD"));
|
||||
assert_eq!(ca.rows[2].declared_date, Some(day(2024, 10, 30)));
|
||||
assert_eq!(ca.rows[2].known_at_source, KnownAtSource::DeclaredDate);
|
||||
}
|
||||
1072
tools/curate-etl/src/bson_qm_events.rs
Normal file
1072
tools/curate-etl/src/bson_qm_events.rs
Normal file
File diff suppressed because it is too large
Load diff
500
tools/curate-etl/src/bson_qm_events_tests.rs
Normal file
500
tools/curate-etl/src/bson_qm_events_tests.rs
Normal file
|
|
@ -0,0 +1,500 @@
|
|||
use bson::{rawdoc, DateTime, RawDocumentBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn dt_from_ymd(y: i32, m: u32, d: u32) -> DateTime {
|
||||
DateTime::from_millis(i64::from(day(y, m, d)) * MILLIS_PER_DAY)
|
||||
}
|
||||
|
||||
fn default_filings_fields() -> QmFilingsFieldNames<'static> {
|
||||
QmFilingsFieldNames {
|
||||
key: DEFAULT_FILINGS_KEY_FIELD,
|
||||
timefiled: DEFAULT_FILINGS_TIMEFILED_FIELD,
|
||||
form_type: "formtype",
|
||||
filing_id: Some("filingId"),
|
||||
url: Some("url"),
|
||||
}
|
||||
}
|
||||
|
||||
fn default_earnings_fields() -> QmEarningsFieldNames<'static> {
|
||||
QmEarningsFieldNames {
|
||||
key: DEFAULT_EARNINGS_KEY_FIELD,
|
||||
report_date: DEFAULT_EARNINGS_REPORT_DATE_FIELD,
|
||||
announce_time: DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD,
|
||||
fiscal_period_end: Some("periodEndDate"),
|
||||
actual_eps: Some("actualEps"),
|
||||
revenue: Some("revenue"),
|
||||
}
|
||||
}
|
||||
|
||||
fn make_raw_doc_with_invalid_utf8_unused_field(include_required: bool) -> Vec<u8> {
|
||||
let mut body = Vec::new();
|
||||
if include_required {
|
||||
// String field "symbol": "AAPL"
|
||||
body.push(0x02);
|
||||
body.extend_from_slice(b"symbol\0");
|
||||
body.extend_from_slice(&5_i32.to_le_bytes());
|
||||
body.extend_from_slice(b"AAPL\0");
|
||||
// String field "timefiled": "2025-01-31T06:01:27 EST"
|
||||
let ts = b"2025-01-31T06:01:27 EST";
|
||||
body.push(0x02);
|
||||
body.extend_from_slice(b"timefiled\0");
|
||||
body.extend_from_slice(&((ts.len() + 1) as i32).to_le_bytes());
|
||||
body.extend_from_slice(ts);
|
||||
body.push(0);
|
||||
// String field "formtype": "10-K"
|
||||
body.push(0x02);
|
||||
body.extend_from_slice(b"formtype\0");
|
||||
body.extend_from_slice(&5_i32.to_le_bytes());
|
||||
body.extend_from_slice(b"10-K\0");
|
||||
}
|
||||
// Unused string field "extra" with invalid UTF-8 bytes [0xFF, 0xFE]
|
||||
body.push(0x02);
|
||||
body.extend_from_slice(b"extra\0");
|
||||
body.extend_from_slice(&3_i32.to_le_bytes());
|
||||
body.extend_from_slice(&[0xFF, 0xFE, 0x00]);
|
||||
body.push(0x00); // doc terminator
|
||||
|
||||
let total_len = (4 + body.len()) as i32;
|
||||
let mut out = Vec::with_capacity(total_len as usize);
|
||||
out.extend_from_slice(&total_len.to_le_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
out
|
||||
}
|
||||
|
||||
fn make_raw_doc_with_bad_array_index() -> Vec<u8> {
|
||||
// Nested array "badArr" with key "1" instead of "0"
|
||||
let mut arr_body = Vec::new();
|
||||
arr_body.push(0x10); // Int32
|
||||
arr_body.extend_from_slice(b"1\0");
|
||||
arr_body.extend_from_slice(&42_i32.to_le_bytes());
|
||||
arr_body.push(0x00);
|
||||
let arr_len = (4 + arr_body.len()) as i32;
|
||||
|
||||
let mut body = Vec::new();
|
||||
body.push(0x04); // Array
|
||||
body.extend_from_slice(b"badArr\0");
|
||||
body.extend_from_slice(&arr_len.to_le_bytes());
|
||||
body.extend_from_slice(&arr_body);
|
||||
body.push(0x00);
|
||||
|
||||
let total_len = (4 + body.len()) as i32;
|
||||
let mut out = Vec::with_capacity(total_len as usize);
|
||||
out.extend_from_slice(&total_len.to_le_bytes());
|
||||
out.extend_from_slice(&body);
|
||||
out
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_name_validation_rejects_blank_colliding_and_consensus_eps() {
|
||||
assert!(default_filings_fields().validate().is_ok());
|
||||
assert!(default_earnings_fields().validate().is_ok());
|
||||
|
||||
// Blank required / optional filings fields
|
||||
let mut f = default_filings_fields();
|
||||
f.form_type = " ";
|
||||
let err = f.validate().unwrap_err();
|
||||
assert!(matches!(err, BsonQmEventsError::InvalidFieldNames { .. }));
|
||||
assert!(!err.to_string().contains('\n'));
|
||||
|
||||
let mut f = default_filings_fields();
|
||||
f.url = Some("");
|
||||
assert!(matches!(
|
||||
f.validate(),
|
||||
Err(BsonQmEventsError::InvalidFieldNames { .. })
|
||||
));
|
||||
|
||||
// Colliding filings fields
|
||||
let mut f = default_filings_fields();
|
||||
f.form_type = DEFAULT_FILINGS_KEY_FIELD;
|
||||
assert!(matches!(
|
||||
f.validate(),
|
||||
Err(BsonQmEventsError::InvalidFieldNames { .. })
|
||||
));
|
||||
|
||||
// Blank earnings field
|
||||
let mut e = default_earnings_fields();
|
||||
e.actual_eps = Some(" \t ");
|
||||
assert!(matches!(
|
||||
e.validate(),
|
||||
Err(BsonQmEventsError::InvalidFieldNames { .. })
|
||||
));
|
||||
|
||||
// Colliding earnings fields
|
||||
let mut e = default_earnings_fields();
|
||||
e.revenue = Some("actualEps");
|
||||
assert!(matches!(
|
||||
e.validate(),
|
||||
Err(BsonQmEventsError::InvalidFieldNames { .. })
|
||||
));
|
||||
|
||||
// Forbidden consensusEps / consensus_eps (case-insensitive) on any role
|
||||
for bad in ["consensusEps", "CONSENSUSEPS", "consensus_eps", " Consensus_Eps "] {
|
||||
let mut e = default_earnings_fields();
|
||||
e.actual_eps = Some(bad);
|
||||
let err = e.validate().unwrap_err();
|
||||
assert!(matches!(err, BsonQmEventsError::InvalidFieldNames { .. }));
|
||||
assert!(err.to_string().contains("consensusEps"));
|
||||
assert!(!err.to_string().contains('\n'));
|
||||
|
||||
let mut e2 = default_earnings_fields();
|
||||
e2.revenue = Some(bad);
|
||||
assert!(matches!(
|
||||
e2.validate(),
|
||||
Err(BsonQmEventsError::InvalidFieldNames { .. })
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_filings_happy_path_and_optionals() {
|
||||
let fields = default_filings_fields();
|
||||
let doc1 = rawdoc! {
|
||||
"symbol": " AAPL ", // preserved verbatim
|
||||
"timefiled": "2025-01-31T06:01:27 EST",
|
||||
"formtype": "10-Q",
|
||||
"filingId": "0000320193-25-000008",
|
||||
"url": "https://www.sec.gov/Archives/edgar/data/320193/10q.htm",
|
||||
"extra": { "nested": [1, 2, 3] },
|
||||
};
|
||||
let doc2 = rawdoc! {
|
||||
"symbol": "SHOP:CA",
|
||||
"timefiled": "2025-07-15T17:05:00 EDT",
|
||||
"formtype": "News release",
|
||||
"filingId": null,
|
||||
"url": " ",
|
||||
};
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(doc1.as_bytes());
|
||||
buf.extend_from_slice(doc2.as_bytes());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_qm_filing_buffer(&buf, &fields, |r| {
|
||||
rows.push(r.to_qm_filing(r.key.to_string()));
|
||||
})
|
||||
.expect("decode succeeds");
|
||||
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.rows_out, 2);
|
||||
assert_eq!(stats.skipped_total(), 0);
|
||||
assert_eq!(stats.nulled_wrong_type_filing_id, 0);
|
||||
assert_eq!(stats.nulled_wrong_type_url, 0);
|
||||
assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total());
|
||||
|
||||
assert_eq!(rows[0].key, " AAPL ");
|
||||
assert_eq!(rows[0].timefiled, "2025-01-31T06:01:27 EST");
|
||||
assert_eq!(rows[0].form_type, "10-Q");
|
||||
assert_eq!(rows[0].filing_id.as_deref(), Some("0000320193-25-000008"));
|
||||
assert_eq!(
|
||||
rows[0].url.as_deref(),
|
||||
Some("https://www.sec.gov/Archives/edgar/data/320193/10q.htm")
|
||||
);
|
||||
|
||||
assert_eq!(rows[1].key, "SHOP:CA");
|
||||
assert_eq!(rows[1].filing_id, None);
|
||||
assert_eq!(rows[1].url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_filings_skip_reasons_priority_and_optional_wrong_type_counters() {
|
||||
let fields = default_filings_fields();
|
||||
let docs: Vec<RawDocumentBuf> = vec![
|
||||
// 1. missing key (even though timefiled & formtype are also missing + optional wrong type)
|
||||
rawdoc! { "filingId": 123, "url": false },
|
||||
// 2. wrong key type (priority over missing timefiled)
|
||||
rawdoc! { "symbol": 42 },
|
||||
// 3. empty key (priority over missing formtype)
|
||||
rawdoc! { "symbol": " ", "timefiled": "2025-01-31T06:01:27 EST" },
|
||||
// 4. missing timefiled (priority over missing formtype)
|
||||
rawdoc! { "symbol": "AAPL" },
|
||||
// 5. wrong timefiled type
|
||||
rawdoc! { "symbol": "AAPL", "timefiled": 12345, "formtype": "8-K" },
|
||||
// 6. empty timefiled
|
||||
rawdoc! { "symbol": "AAPL", "timefiled": "", "formtype": "8-K" },
|
||||
// 7. missing formtype
|
||||
rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-31T06:01:27 EST" },
|
||||
// 8. wrong formtype type
|
||||
rawdoc! { "symbol": "AAPL", "timefiled": "2025-01-31T06:01:27 EST", "formtype": 10 },
|
||||
// 9. empty formtype (with wrong-type optionals that must NOT increment nulled counters)
|
||||
rawdoc! {
|
||||
"symbol": "AAPL",
|
||||
"timefiled": "2025-01-31T06:01:27 EST",
|
||||
"formtype": " \t ",
|
||||
"filingId": 999,
|
||||
"url": 888,
|
||||
},
|
||||
// 10. valid row with wrong-type optionals -> emitted with None + nulled counters incremented
|
||||
rawdoc! {
|
||||
"symbol": "MSFT",
|
||||
"timefiled": "2025-02-01T16:30:00 EST",
|
||||
"formtype": "8-K",
|
||||
"filingId": 999,
|
||||
"url": true,
|
||||
},
|
||||
];
|
||||
|
||||
let mut buf = Vec::new();
|
||||
for d in &docs {
|
||||
buf.extend_from_slice(d.as_bytes());
|
||||
}
|
||||
|
||||
let mut emitted = Vec::new();
|
||||
let stats = decode_qm_filing_buffer(&buf, &fields, |r| {
|
||||
emitted.push(r.to_qm_filing(r.key.to_string()));
|
||||
})
|
||||
.expect("decode succeeds");
|
||||
|
||||
assert_eq!(stats.docs_in, 10);
|
||||
assert_eq!(stats.rows_out, 1);
|
||||
assert_eq!(stats.skipped_missing_key, 1);
|
||||
assert_eq!(stats.skipped_wrong_key_type, 1);
|
||||
assert_eq!(stats.skipped_empty_key, 1);
|
||||
assert_eq!(stats.skipped_missing_timefiled, 1);
|
||||
assert_eq!(stats.skipped_wrong_timefiled_type, 1);
|
||||
assert_eq!(stats.skipped_empty_timefiled, 1);
|
||||
assert_eq!(stats.skipped_missing_form_type, 1);
|
||||
assert_eq!(stats.skipped_wrong_form_type_type, 1);
|
||||
assert_eq!(stats.skipped_empty_form_type, 1);
|
||||
assert_eq!(stats.skipped_total(), 9);
|
||||
assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total());
|
||||
assert_eq!(stats.nulled_wrong_type_filing_id, 1);
|
||||
assert_eq!(stats.nulled_wrong_type_url, 1);
|
||||
|
||||
assert_eq!(emitted.len(), 1);
|
||||
assert_eq!(emitted[0].key, "MSFT");
|
||||
assert_eq!(emitted[0].filing_id, None);
|
||||
assert_eq!(emitted[0].url, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_earnings_happy_path_types_and_ignores_consensus_eps() {
|
||||
let fields = default_earnings_fields();
|
||||
let doc1 = rawdoc! {
|
||||
"qmSearchCode": "AAPL",
|
||||
"reportDate": dt_from_ymd(2025, 1, 30),
|
||||
"announceTime": "AMC",
|
||||
"periodEndDate": dt_from_ymd(2024, 12, 28),
|
||||
"actualEps": 2.40_f64,
|
||||
"revenue": 124_300_000_000_i64,
|
||||
"consensusEps": 2.35_f64,
|
||||
};
|
||||
let doc2 = rawdoc! {
|
||||
"qmSearchCode": "SHOP:CA",
|
||||
"reportDate": "2025-02-11",
|
||||
"announceTime": "N/A",
|
||||
"periodEndDate": "2024-12-31",
|
||||
"actualEps": 1_i32,
|
||||
"revenue": 2_810_000_000.5_f64,
|
||||
"consensusEps": 0.99_f64,
|
||||
};
|
||||
let doc3 = rawdoc! {
|
||||
"qmSearchCode": "TD:CA",
|
||||
"reportDate": "2025-02-27",
|
||||
"announceTime": "BTO",
|
||||
"periodEndDate": null,
|
||||
"actualEps": null,
|
||||
"revenue": null,
|
||||
};
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(doc1.as_bytes());
|
||||
buf.extend_from_slice(doc2.as_bytes());
|
||||
buf.extend_from_slice(doc3.as_bytes());
|
||||
|
||||
let mut rows = Vec::new();
|
||||
let stats = decode_qm_earning_buffer(&buf, &fields, |r| {
|
||||
rows.push(r.to_qm_earning(r.key.to_string()));
|
||||
})
|
||||
.expect("decode succeeds");
|
||||
|
||||
assert_eq!(stats.docs_in, 3);
|
||||
assert_eq!(stats.rows_out, 3);
|
||||
assert_eq!(stats.skipped_total(), 0);
|
||||
assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total());
|
||||
|
||||
assert_eq!(rows[0].key, "AAPL");
|
||||
assert_eq!(rows[0].report_date, day(2025, 1, 30));
|
||||
assert_eq!(rows[0].announce_time, "AMC");
|
||||
assert_eq!(rows[0].fiscal_period_end, Some(day(2024, 12, 28)));
|
||||
assert_eq!(rows[0].actual_eps, Some(2.40));
|
||||
assert_eq!(rows[0].revenue, Some(124_300_000_000.0));
|
||||
|
||||
assert_eq!(rows[1].key, "SHOP:CA");
|
||||
assert_eq!(rows[1].report_date, day(2025, 2, 11));
|
||||
assert_eq!(rows[1].announce_time, "N/A");
|
||||
assert_eq!(rows[1].fiscal_period_end, Some(day(2024, 12, 31)));
|
||||
assert_eq!(rows[1].actual_eps, Some(1.0));
|
||||
assert_eq!(rows[1].revenue, Some(2_810_000_000.5));
|
||||
|
||||
assert_eq!(rows[2].key, "TD:CA");
|
||||
assert_eq!(rows[2].fiscal_period_end, None);
|
||||
assert_eq!(rows[2].actual_eps, None);
|
||||
assert_eq!(rows[2].revenue, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn qm_earnings_skip_reasons_priority_and_optional_nulling_counters() {
|
||||
let fields = default_earnings_fields();
|
||||
let oor_dt = DateTime::from_millis(i64::MAX);
|
||||
let docs: Vec<RawDocumentBuf> = vec![
|
||||
// 1. missing key (with bad optionals that must not increment nulled counters)
|
||||
rawdoc! { "periodEndDate": 123, "actualEps": "bad", "revenue": false },
|
||||
// 2. wrong key type
|
||||
rawdoc! { "qmSearchCode": 100 },
|
||||
// 3. empty key
|
||||
rawdoc! { "qmSearchCode": " ", "reportDate": "2025-01-30", "announceTime": "AMC" },
|
||||
// 4. missing reportDate
|
||||
rawdoc! { "qmSearchCode": "AAPL", "announceTime": "AMC" },
|
||||
// 5. wrong reportDate type
|
||||
rawdoc! { "qmSearchCode": "AAPL", "reportDate": 20250130, "announceTime": "AMC" },
|
||||
// 6. invalid reportDate string
|
||||
rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-02-30", "announceTime": "AMC" },
|
||||
// 7. out-of-range reportDate DateTime
|
||||
rawdoc! { "qmSearchCode": "AAPL", "reportDate": oor_dt, "announceTime": "AMC" },
|
||||
// 8. missing announceTime
|
||||
rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-01-30" },
|
||||
// 9. wrong announceTime type
|
||||
rawdoc! { "qmSearchCode": "AAPL", "reportDate": "2025-01-30", "announceTime": 1 },
|
||||
// 10. empty announceTime (bad optionals must NOT increment nulled counters)
|
||||
rawdoc! {
|
||||
"qmSearchCode": "AAPL",
|
||||
"reportDate": "2025-01-30",
|
||||
"announceTime": " ",
|
||||
"periodEndDate": "not-a-date",
|
||||
"actualEps": "1.2",
|
||||
"revenue": "500",
|
||||
},
|
||||
// 11. valid row with wrong-type optionals
|
||||
rawdoc! {
|
||||
"qmSearchCode": "NVDA",
|
||||
"reportDate": "2025-02-26",
|
||||
"announceTime": "AMC",
|
||||
"periodEndDate": 20250126,
|
||||
"actualEps": "0.89",
|
||||
"revenue": true,
|
||||
},
|
||||
// 12. valid row with invalid string fiscal_period_end
|
||||
rawdoc! {
|
||||
"qmSearchCode": "AMD",
|
||||
"reportDate": "2025-02-04",
|
||||
"announceTime": "AMC",
|
||||
"periodEndDate": "2024-13-01",
|
||||
"actualEps": 1.09,
|
||||
"revenue": 7_658_000_000_i64,
|
||||
},
|
||||
// 13. valid row with out-of-range DateTime fiscal_period_end
|
||||
rawdoc! {
|
||||
"qmSearchCode": "INTC",
|
||||
"reportDate": "2025-01-30",
|
||||
"announceTime": "AMC",
|
||||
"periodEndDate": oor_dt,
|
||||
},
|
||||
];
|
||||
|
||||
let mut buf = Vec::new();
|
||||
for d in &docs {
|
||||
buf.extend_from_slice(d.as_bytes());
|
||||
}
|
||||
|
||||
let mut emitted = Vec::new();
|
||||
let stats = decode_qm_earning_buffer(&buf, &fields, |r| {
|
||||
emitted.push(r.to_qm_earning(r.key.to_string()));
|
||||
})
|
||||
.expect("decode succeeds");
|
||||
|
||||
assert_eq!(stats.docs_in, 13);
|
||||
assert_eq!(stats.rows_out, 3);
|
||||
assert_eq!(stats.skipped_missing_key, 1);
|
||||
assert_eq!(stats.skipped_wrong_key_type, 1);
|
||||
assert_eq!(stats.skipped_empty_key, 1);
|
||||
assert_eq!(stats.skipped_missing_report_date, 1);
|
||||
assert_eq!(stats.skipped_wrong_report_date_type, 1);
|
||||
assert_eq!(stats.skipped_invalid_report_date, 1);
|
||||
assert_eq!(stats.skipped_report_date_out_of_range, 1);
|
||||
assert_eq!(stats.skipped_missing_announce_time, 1);
|
||||
assert_eq!(stats.skipped_wrong_announce_time_type, 1);
|
||||
assert_eq!(stats.skipped_empty_announce_time, 1);
|
||||
assert_eq!(stats.skipped_total(), 10);
|
||||
assert_eq!(stats.docs_in, stats.rows_out + stats.skipped_total());
|
||||
|
||||
assert_eq!(stats.nulled_wrong_type_fiscal_period_end, 1);
|
||||
assert_eq!(stats.nulled_invalid_fiscal_period_end, 2);
|
||||
assert_eq!(stats.nulled_wrong_type_actual_eps, 1);
|
||||
assert_eq!(stats.nulled_wrong_type_revenue, 1);
|
||||
|
||||
assert_eq!(emitted.len(), 3);
|
||||
assert_eq!(emitted[0].fiscal_period_end, None);
|
||||
assert_eq!(emitted[0].actual_eps, None);
|
||||
assert_eq!(emitted[0].revenue, None);
|
||||
assert_eq!(emitted[1].fiscal_period_end, None);
|
||||
assert_eq!(emitted[1].actual_eps, Some(1.09));
|
||||
assert_eq!(emitted[2].fiscal_period_end, None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_and_truncated_bson_fail_closed_even_when_required_fields_missing() {
|
||||
let f_fields = default_filings_fields();
|
||||
let e_fields = default_earnings_fields();
|
||||
|
||||
// Invalid UTF-8 in unused field with NO required fields present -> must still Err(CorruptBson)
|
||||
let corrupt_no_req = make_raw_doc_with_invalid_utf8_unused_field(false);
|
||||
assert!(matches!(
|
||||
decode_qm_filing_bytes(&corrupt_no_req, &f_fields, |_| {}),
|
||||
Err(BsonQmEventsError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_earning_bytes(&corrupt_no_req, &e_fields, |_| {}),
|
||||
Err(BsonQmEventsError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Invalid UTF-8 in unused field with required fields present -> must Err(CorruptBson)
|
||||
let corrupt_with_req = make_raw_doc_with_invalid_utf8_unused_field(true);
|
||||
assert!(matches!(
|
||||
decode_qm_filing_bytes(&corrupt_with_req, &f_fields, |_| {}),
|
||||
Err(BsonQmEventsError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Bad nested array index -> Err(CorruptBson)
|
||||
let bad_arr = make_raw_doc_with_bad_array_index();
|
||||
assert!(matches!(
|
||||
decode_qm_filing_bytes(&bad_arr, &f_fields, |_| {}),
|
||||
Err(BsonQmEventsError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_earning_bytes(&bad_arr, &e_fields, |_| {}),
|
||||
Err(BsonQmEventsError::CorruptBson { offset: 0, .. })
|
||||
));
|
||||
|
||||
// Truncated BSON buffer after one valid doc -> Err(TruncatedDocument) with exact offset
|
||||
let valid_doc = rawdoc! {
|
||||
"symbol": "AAPL",
|
||||
"timefiled": "2025-01-31T06:01:27 EST",
|
||||
"formtype": "10-K",
|
||||
};
|
||||
let mut trunc_buf = valid_doc.as_bytes().to_vec();
|
||||
let expected_offset = trunc_buf.len() as u64;
|
||||
trunc_buf.extend_from_slice(&valid_doc.as_bytes()[..10]);
|
||||
|
||||
let err = decode_qm_filing_buffer(&trunc_buf, &f_fields, |_| {}).unwrap_err();
|
||||
assert!(matches!(
|
||||
err,
|
||||
BsonQmEventsError::TruncatedDocument { offset, .. } if offset == expected_offset
|
||||
));
|
||||
assert!(!err.to_string().contains('\n'));
|
||||
|
||||
// Corrupt document length (< 5) -> Err(CorruptDocumentLength)
|
||||
let bad_len = 3_i32.to_le_bytes();
|
||||
assert!(matches!(
|
||||
decode_qm_earning_buffer(&bad_len, &e_fields, |_| {}),
|
||||
Err(BsonQmEventsError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 3
|
||||
})
|
||||
));
|
||||
}
|
||||
458
tools/curate-etl/src/bson_qm_prices.rs
Normal file
458
tools/curate-etl/src/bson_qm_prices.rs
Normal file
|
|
@ -0,0 +1,458 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `qmPrices` documents (`M1.2ah`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` into
|
||||
//! borrowed [`RawQmPrice`] views without allocating a `String` or `bson::Document` per row.
|
||||
//! Callers convert borrowed views into [`crate::bars::QmRawVolume<K>`] via a caller-supplied key
|
||||
//! mapper (such as date-aware `provider_mapping` re-keying into interned `"eod"` keys).
|
||||
//!
|
||||
//! # Empirical Field Contract & Cited Sources
|
||||
//!
|
||||
//! - `apps/stock/data-ingestion/src/handlers/qm/actions/prices.action.ts:97-109`: writes
|
||||
//! `...price` (the raw QuoteMedia EOD payload including `date` and `sharevolume`), `symbol`,
|
||||
//! `exchange`, `qmSearchCode`, and `dateTime: new Date(price.date)` into `qmPrices`, keyed by
|
||||
//! `['qmSearchCode', 'date']`.
|
||||
//! - `apps/stock/data-pipeline/src/normalization/bar-spans.ts:19-24`: `qmPrices` uses
|
||||
//! `qmSearchCode` and `date`.
|
||||
//! - `apps/stock/data-pipeline/src/security-master/sample-closes.ts:300-303`: documents `qmPrices`
|
||||
//! copying the provider's `date` string verbatim (`YYYY-MM-DD`, with BSON `Date` stored
|
||||
//! separately in `dateTime`).
|
||||
//! - `design/DATA-CONTRACTS.md` §1 (line 14): `qmPrices` (`51.5M` docs) stores genuinely raw
|
||||
//! `unadjustedopen..unadjustedclose` and `sharevolume` for `eodPrices` volume cross-checking.
|
||||
//!
|
||||
//! Accepted BSON field representations:
|
||||
//! - `qmSearchCode`: BSON UTF-8 `String` (borrowed verbatim — never trimmed; empty or
|
||||
//! whitespace-only is rejected as [`BsonQmPriceError::EmptyField`]).
|
||||
//! - `date`: strict 10-byte ASCII `YYYY-MM-DD` BSON `String` validated via
|
||||
//! [`crate::bson_eod_prices::parse_ymd_strict_days`]; BSON `DateTime` and other types are
|
||||
//! rejected as [`BsonQmPriceError::WrongType`], and malformed/non-calendar strings as
|
||||
//! [`BsonQmPriceError::MalformedDate`].
|
||||
//! - `sharevolume`: BSON `Double`, `Int32`, or `Int64` decoded to `f64`. Numeric value validity
|
||||
//! (non-finite / negative) is intentionally left to [`crate::bars::build_bars_1d`]
|
||||
//! (`qm_invalid_volume_dropped`). Missing, `Null`, or non-numeric types are rejected with
|
||||
//! counted reasons.
|
||||
//! - Unknown extra fields (`_id`, `symbol`, `exchange`, `dateTime`,
|
||||
//! `unadjustedopen..unadjustedclose`, nested objects/arrays, etc.) are skipped without calling
|
||||
//! `elem.value()`.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{cstr, RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bars::QmRawVolume;
|
||||
use crate::bson_eod_prices::{
|
||||
iter_raw_bson_docs, parse_single_raw_doc, parse_ymd_strict_days, BsonEodPriceError,
|
||||
};
|
||||
|
||||
/// MongoDB field name for the QuoteMedia security key (`prices.action.ts:101,108`).
|
||||
pub const FIELD_QM_SEARCH_CODE: &str = "qmSearchCode";
|
||||
/// MongoDB field name for the verbatim `YYYY-MM-DD` session date string (`prices.action.ts:102,108`).
|
||||
pub const FIELD_DATE: &str = "date";
|
||||
/// MongoDB field name for the genuinely raw QuoteMedia share volume (`DATA-CONTRACTS.md` §1).
|
||||
pub const FIELD_SHARE_VOLUME: &str = "sharevolume";
|
||||
|
||||
/// Borrowed zero-copy view of a single decoded `qmPrices` BSON document.
|
||||
///
|
||||
/// Borrows `qm_search_code` directly from the underlying `&RawDocument` byte slice.
|
||||
/// `share_volume` is passed through without domain filtering so downstream [`crate::bars::build_bars_1d`]
|
||||
/// accounts for negative or non-finite values under `qm_invalid_volume_dropped`.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct RawQmPrice<'a> {
|
||||
pub qm_search_code: &'a str,
|
||||
/// Session date as days since `1970-01-01` (UTC Gregorian).
|
||||
pub session_date: i32,
|
||||
/// Raw `qmPrices.sharevolume` converted from BSON `Double`, `Int32`, or `Int64`.
|
||||
pub share_volume: f64,
|
||||
}
|
||||
|
||||
impl<'a> RawQmPrice<'a> {
|
||||
/// Converts this borrowed view into a [`QmRawVolume<K>`] using a caller-supplied key mapper.
|
||||
#[inline]
|
||||
pub fn into_qm_raw_volume<K, F>(self, map_key: F) -> QmRawVolume<K>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> K,
|
||||
{
|
||||
QmRawVolume {
|
||||
key: map_key(self.qm_search_code, self.session_date),
|
||||
session_date: self.session_date,
|
||||
share_volume: self.share_volume,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fallible conversion into [`QmRawVolume<K>`] using a caller-supplied key resolver.
|
||||
#[inline]
|
||||
pub fn try_into_qm_raw_volume<K, F>(self, map_key: F) -> Option<QmRawVolume<K>>
|
||||
where
|
||||
F: FnOnce(&'a str, i32) -> Option<K>,
|
||||
{
|
||||
let key = map_key(self.qm_search_code, self.session_date)?;
|
||||
Some(QmRawVolume {
|
||||
key,
|
||||
session_date: self.session_date,
|
||||
share_volume: self.share_volume,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `qmPrices` BSON documents or length-prefixed buffers.
|
||||
///
|
||||
/// Every field-level error names the offending BSON field in both its structure and `Display`
|
||||
/// output; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonQmPriceError {
|
||||
/// A required field was absent from the document.
|
||||
MissingField { field: &'static str },
|
||||
/// A required string field was empty or contained only whitespace.
|
||||
EmptyField { field: &'static str },
|
||||
/// A required field had an unexpected BSON element type.
|
||||
WrongType {
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// `date` string was not a valid strict `YYYY-MM-DD` Gregorian calendar date.
|
||||
MalformedDate { field: &'static str },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonQmPriceError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingField { field } => {
|
||||
write!(f, "qmPrices BSON missing required field '{field}'")
|
||||
}
|
||||
Self::EmptyField { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qmPrices BSON field '{field}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongType { field, actual } => {
|
||||
write!(
|
||||
f,
|
||||
"qmPrices BSON field '{field}' has unexpected BSON type {actual:?}"
|
||||
)
|
||||
}
|
||||
Self::MalformedDate { field } => {
|
||||
write!(
|
||||
f,
|
||||
"qmPrices BSON field '{field}' is not a valid strict YYYY-MM-DD date"
|
||||
)
|
||||
}
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonQmPriceError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonQmPriceError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonQmPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonQmPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonQmPriceError::CorruptBson { offset, detail }
|
||||
}
|
||||
BsonEodPriceError::MissingField { field } => BsonQmPriceError::MissingField { field },
|
||||
BsonEodPriceError::EmptyField { field } => BsonQmPriceError::EmptyField { field },
|
||||
BsonEodPriceError::WrongType { field, actual } => {
|
||||
BsonQmPriceError::WrongType { field, actual }
|
||||
}
|
||||
BsonEodPriceError::MalformedDate { field } => BsonQmPriceError::MalformedDate { field },
|
||||
BsonEodPriceError::InvalidNumber { field, .. } => BsonQmPriceError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: format!("unexpected numeric framing error on field '{field}'"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch decode and rejection accounting for [`decode_qm_price_buffer`].
|
||||
///
|
||||
/// Conservation invariant: `decoded + rejected_total() == docs_in`.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonQmPriceDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub decoded: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_empty_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_malformed_date: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
}
|
||||
|
||||
impl BsonQmPriceDecodeStats {
|
||||
/// Total number of rejected documents across all error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_missing_field
|
||||
+ self.rejected_empty_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_malformed_date
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Increments the rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
pub fn record_error(&mut self, err: &BsonQmPriceError) {
|
||||
match err {
|
||||
BsonQmPriceError::MissingField { .. } => self.rejected_missing_field += 1,
|
||||
BsonQmPriceError::EmptyField { .. } => self.rejected_empty_field += 1,
|
||||
BsonQmPriceError::WrongType { .. } => self.rejected_wrong_type += 1,
|
||||
BsonQmPriceError::MalformedDate { .. } => self.rejected_malformed_date += 1,
|
||||
BsonQmPriceError::TruncatedDocument { .. }
|
||||
| BsonQmPriceError::CorruptDocumentLength { .. }
|
||||
| BsonQmPriceError::CorruptBson { .. } => self.rejected_corrupt_document += 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.decoded += other.decoded;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_empty_field += other.rejected_empty_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_malformed_date += other.rejected_malformed_date;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonQmPriceDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_element_value<'a>(
|
||||
field: &'static str,
|
||||
elem: RawElement<'a>,
|
||||
offset: usize,
|
||||
) -> Result<RawBsonRef<'a>, BsonQmPriceError> {
|
||||
elem.value().map_err(|err| BsonQmPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: format!("field '{field}': {err}"),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_numeric_passthrough(
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonQmPriceError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => Ok(v),
|
||||
RawBsonRef::Int32(v) => Ok(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => Ok(v as f64),
|
||||
other => Err(BsonQmPriceError::WrongType {
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_qm_price_doc_at<'a>(
|
||||
doc: &'a RawDocument,
|
||||
offset: usize,
|
||||
) -> Result<RawQmPrice<'a>, BsonQmPriceError> {
|
||||
let mut qm_search_code: Option<&'a str> = None;
|
||||
let mut session_date: Option<i32> = None;
|
||||
let mut share_volume: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonQmPriceError> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonQmPriceError::CorruptBson {
|
||||
offset,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key();
|
||||
|
||||
if key == cstr!("qmSearchCode") {
|
||||
match decode_element_value(FIELD_QM_SEARCH_CODE, elem, offset)? {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonQmPriceError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
qm_search_code = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonQmPriceError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("date") {
|
||||
match decode_element_value(FIELD_DATE, elem, offset)? {
|
||||
RawBsonRef::String(s) => match parse_ymd_strict_days(s) {
|
||||
Some(d) => session_date = Some(d),
|
||||
None => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err =
|
||||
Some(BsonQmPriceError::MalformedDate { field: FIELD_DATE });
|
||||
}
|
||||
}
|
||||
},
|
||||
other => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(BsonQmPriceError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == cstr!("sharevolume") {
|
||||
let val = decode_element_value(FIELD_SHARE_VOLUME, elem, offset)?;
|
||||
match decode_numeric_passthrough(FIELD_SHARE_VOLUME, val) {
|
||||
Ok(v) => share_volume = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Unknown extra fields (`_id`, `dateTime`, `unadjustedopen..unadjustedclose`, etc.)
|
||||
// are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(qm_search_code) = qm_search_code else {
|
||||
return Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
});
|
||||
};
|
||||
let Some(session_date) = session_date else {
|
||||
return Err(BsonQmPriceError::MissingField { field: FIELD_DATE });
|
||||
};
|
||||
let Some(share_volume) = share_volume else {
|
||||
return Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(RawQmPrice {
|
||||
qm_search_code,
|
||||
session_date,
|
||||
share_volume,
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `qmPrices` MongoDB document in one forward pass
|
||||
/// without allocating a `String` or owned `bson::Document`.
|
||||
#[inline]
|
||||
pub fn decode_qm_price_doc<'a>(doc: &'a RawDocument) -> Result<RawQmPrice<'a>, BsonQmPriceError> {
|
||||
decode_qm_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice into a borrowed [`RawQmPrice`].
|
||||
pub fn decode_qm_price_bytes<'a>(bytes: &'a [u8]) -> Result<RawQmPrice<'a>, BsonQmPriceError> {
|
||||
let doc = parse_single_raw_doc(bytes).map_err(map_framing_error)?;
|
||||
decode_qm_price_doc_at(doc, 0)
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_qm_price_doc`], invoking
|
||||
/// `on_price` for every valid document and `on_error(byte_offset, err)` for every rejected
|
||||
/// document without aborting the stream on per-document errors.
|
||||
///
|
||||
/// Always maintains `stats.decoded + stats.rejected_total() == stats.docs_in`.
|
||||
pub fn decode_qm_price_buffer<'a, F, E>(
|
||||
buf: &'a [u8],
|
||||
mut on_price: F,
|
||||
mut on_error: E,
|
||||
) -> BsonQmPriceDecodeStats
|
||||
where
|
||||
F: FnMut(RawQmPrice<'a>),
|
||||
E: FnMut(usize, BsonQmPriceError),
|
||||
{
|
||||
let mut stats = BsonQmPriceDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
stats.docs_in += 1;
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => match decode_qm_price_doc_at(doc, doc_offset) {
|
||||
Ok(price) => {
|
||||
stats.decoded += 1;
|
||||
on_price(price);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_error(&err);
|
||||
on_error(doc_offset, err);
|
||||
}
|
||||
},
|
||||
Err((doc_offset, err)) => {
|
||||
let mapped = map_framing_error(err);
|
||||
stats.record_error(&mapped);
|
||||
on_error(doc_offset, mapped);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_qm_prices_tests.rs"]
|
||||
mod tests;
|
||||
413
tools/curate-etl/src/bson_qm_prices_tests.rs
Normal file
413
tools/curate-etl/src/bson_qm_prices_tests.rs
Normal file
|
|
@ -0,0 +1,413 @@
|
|||
use bson::oid::ObjectId;
|
||||
use bson::raw::{cstr, RawArrayBuf, RawBsonRef, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
use bson::DateTime;
|
||||
|
||||
use super::*;
|
||||
use crate::bson_eod_prices::MILLIS_PER_DAY;
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).unwrap()
|
||||
}
|
||||
|
||||
fn make_qm_price_doc_f64(code: &str, date: &str, share_volume: f64) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), code);
|
||||
doc.append(cstr!("date"), date);
|
||||
doc.append(cstr!("sharevolume"), share_volume);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_realistic_qm_price_doc_and_ignores_extra_fields() {
|
||||
let mut nested = RawDocumentBuf::new();
|
||||
nested.append(cstr!("provider"), "quotemedia");
|
||||
nested.append(cstr!("version"), 2_i32);
|
||||
|
||||
let mut tags = RawArrayBuf::new();
|
||||
tags.push("eod");
|
||||
tags.push("raw");
|
||||
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(
|
||||
cstr!("_id"),
|
||||
ObjectId::from_bytes([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]),
|
||||
);
|
||||
doc.append(cstr!("symbol"), "NVDA");
|
||||
doc.append(cstr!("exchange"), "NASDAQ");
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(
|
||||
cstr!("dateTime"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 7)) * MILLIS_PER_DAY),
|
||||
);
|
||||
doc.append(cstr!("unadjustedopen"), 1197.7_f64);
|
||||
doc.append(cstr!("unadjustedhigh"), 1216.92_f64);
|
||||
doc.append(cstr!("unadjustedlow"), 1180.22_f64);
|
||||
doc.append(cstr!("unadjustedclose"), 1208.88_f64);
|
||||
doc.append(cstr!("sharevolume"), 41_239_000.0_f64);
|
||||
doc.append(cstr!("meta"), RawBsonRef::Document(nested.as_ref()));
|
||||
doc.append(cstr!("tags"), RawBsonRef::Array(tags.as_ref()));
|
||||
|
||||
let decoded = decode_qm_price_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.qm_search_code, "NVDA");
|
||||
assert_eq!(decoded.session_date, day(2024, 6, 7));
|
||||
assert_eq!(decoded.share_volume.to_bits(), 41_239_000.0_f64.to_bits());
|
||||
assert_eq!(decode_qm_price_bytes(doc.as_bytes()).unwrap(), decoded);
|
||||
|
||||
let mapped = decoded.into_qm_raw_volume(|code, _d| format!("{code}.US"));
|
||||
assert_eq!(mapped.key, "NVDA.US");
|
||||
assert_eq!(mapped.session_date, day(2024, 6, 7));
|
||||
assert_eq!(mapped.share_volume.to_bits(), 41_239_000.0_f64.to_bits());
|
||||
|
||||
let maybe_mapped = decoded.try_into_qm_raw_volume(|code, _d| Some(code.to_owned()));
|
||||
assert_eq!(
|
||||
maybe_mapped,
|
||||
Some(QmRawVolume {
|
||||
key: "NVDA".to_string(),
|
||||
session_date: day(2024, 6, 7),
|
||||
share_volume: 41_239_000.0,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
decoded.try_into_qm_raw_volume::<String, _>(|_, _| None),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn accepts_sharevolume_as_double_int32_and_int64() {
|
||||
let mut doc_f64 = RawDocumentBuf::new();
|
||||
doc_f64.append(cstr!("qmSearchCode"), "AAPL");
|
||||
doc_f64.append(cstr!("date"), "2024-06-07");
|
||||
doc_f64.append(cstr!("sharevolume"), 12_345_678.5_f64);
|
||||
|
||||
let mut doc_i32 = RawDocumentBuf::new();
|
||||
doc_i32.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
doc_i32.append(cstr!("date"), "2024-06-07");
|
||||
doc_i32.append(cstr!("sharevolume"), 500_000_i32);
|
||||
|
||||
let mut doc_i64 = RawDocumentBuf::new();
|
||||
doc_i64.append(cstr!("qmSearchCode"), "SHOP:CA");
|
||||
doc_i64.append(cstr!("date"), "2024-06-07");
|
||||
doc_i64.append(cstr!("sharevolume"), 3_000_000_000_i64);
|
||||
|
||||
let p_f64 = decode_qm_price_doc(&doc_f64).unwrap();
|
||||
assert_eq!(p_f64.share_volume.to_bits(), 12_345_678.5_f64.to_bits());
|
||||
|
||||
let p_i32 = decode_qm_price_doc(&doc_i32).unwrap();
|
||||
assert_eq!(p_i32.share_volume.to_bits(), 500_000.0_f64.to_bits());
|
||||
|
||||
let p_i64 = decode_qm_price_doc(&doc_i64).unwrap();
|
||||
assert_eq!(p_i64.share_volume.to_bits(), 3_000_000_000.0_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn passes_through_negative_nan_inf_and_neg_zero_sharevolume_to_builder() {
|
||||
let cases = [
|
||||
(-100.0_f64, true),
|
||||
(f64::NAN, false),
|
||||
(f64::INFINITY, true),
|
||||
(f64::NEG_INFINITY, true),
|
||||
(-0.0_f64, true),
|
||||
];
|
||||
|
||||
for (val, compare_bits) in cases {
|
||||
let doc = make_qm_price_doc_f64("NVDA", "2024-06-07", val);
|
||||
let decoded = decode_qm_price_doc(&doc).unwrap();
|
||||
if compare_bits {
|
||||
assert_eq!(decoded.share_volume.to_bits(), val.to_bits());
|
||||
} else {
|
||||
assert!(decoded.share_volume.is_nan());
|
||||
}
|
||||
}
|
||||
|
||||
let mut neg_i32 = RawDocumentBuf::new();
|
||||
neg_i32.append(cstr!("qmSearchCode"), "NVDA");
|
||||
neg_i32.append(cstr!("date"), "2024-06-07");
|
||||
neg_i32.append(cstr!("sharevolume"), -42_i32);
|
||||
assert_eq!(decode_qm_price_doc(&neg_i32).unwrap().share_volume, -42.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preserves_qm_search_code_verbatim_including_leading_and_trailing_spaces() {
|
||||
let doc = make_qm_price_doc_f64(" NVDA ", "2024-06-07", 1_000.0);
|
||||
let decoded = decode_qm_price_doc(&doc).unwrap();
|
||||
assert_eq!(decoded.qm_search_code, " NVDA ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_missing_null_empty_and_wrong_typed_fields() {
|
||||
// Missing qmSearchCode
|
||||
let mut missing_code = RawDocumentBuf::new();
|
||||
missing_code.append(cstr!("date"), "2024-06-07");
|
||||
missing_code.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&missing_code),
|
||||
Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
})
|
||||
);
|
||||
|
||||
// Missing date
|
||||
let mut missing_date = RawDocumentBuf::new();
|
||||
missing_date.append(cstr!("qmSearchCode"), "NVDA");
|
||||
missing_date.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&missing_date),
|
||||
Err(BsonQmPriceError::MissingField { field: FIELD_DATE })
|
||||
);
|
||||
|
||||
// Missing sharevolume
|
||||
let mut missing_vol = RawDocumentBuf::new();
|
||||
missing_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
missing_vol.append(cstr!("date"), "2024-06-07");
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&missing_vol),
|
||||
Err(BsonQmPriceError::MissingField {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
})
|
||||
);
|
||||
|
||||
// Empty / whitespace-only qmSearchCode
|
||||
for blank in ["", " ", "\t\n"] {
|
||||
let doc = make_qm_price_doc_f64(blank, "2024-06-07", 100.0);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&doc),
|
||||
Err(BsonQmPriceError::EmptyField {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// Null / wrong-typed qmSearchCode
|
||||
let mut null_code = RawDocumentBuf::new();
|
||||
null_code.append(cstr!("qmSearchCode"), RawBsonRef::Null);
|
||||
null_code.append(cstr!("date"), "2024-06-07");
|
||||
null_code.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&null_code),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Null,
|
||||
})
|
||||
);
|
||||
|
||||
let mut int_code = RawDocumentBuf::new();
|
||||
int_code.append(cstr!("qmSearchCode"), 42_i32);
|
||||
int_code.append(cstr!("date"), "2024-06-07");
|
||||
int_code.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&int_code),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_QM_SEARCH_CODE,
|
||||
actual: ElementType::Int32,
|
||||
})
|
||||
);
|
||||
|
||||
// Null / BSON DateTime / int date
|
||||
let mut null_date = RawDocumentBuf::new();
|
||||
null_date.append(cstr!("qmSearchCode"), "NVDA");
|
||||
null_date.append(cstr!("date"), RawBsonRef::Null);
|
||||
null_date.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&null_date),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::Null,
|
||||
})
|
||||
);
|
||||
|
||||
let mut dt_date = RawDocumentBuf::new();
|
||||
dt_date.append(cstr!("qmSearchCode"), "NVDA");
|
||||
dt_date.append(
|
||||
cstr!("date"),
|
||||
DateTime::from_millis(i64::from(day(2024, 6, 7)) * MILLIS_PER_DAY),
|
||||
);
|
||||
dt_date.append(cstr!("sharevolume"), 100.0_f64);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&dt_date),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_DATE,
|
||||
actual: ElementType::DateTime,
|
||||
})
|
||||
);
|
||||
|
||||
// Null / string / bool sharevolume
|
||||
let mut null_vol = RawDocumentBuf::new();
|
||||
null_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
null_vol.append(cstr!("date"), "2024-06-07");
|
||||
null_vol.append(cstr!("sharevolume"), RawBsonRef::Null);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&null_vol),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
actual: ElementType::Null,
|
||||
})
|
||||
);
|
||||
|
||||
let mut str_vol = RawDocumentBuf::new();
|
||||
str_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
str_vol.append(cstr!("date"), "2024-06-07");
|
||||
str_vol.append(cstr!("sharevolume"), "1000");
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&str_vol),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
actual: ElementType::String,
|
||||
})
|
||||
);
|
||||
|
||||
let mut bool_vol = RawDocumentBuf::new();
|
||||
bool_vol.append(cstr!("qmSearchCode"), "NVDA");
|
||||
bool_vol.append(cstr!("date"), "2024-06-07");
|
||||
bool_vol.append(cstr!("sharevolume"), true);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&bool_vol),
|
||||
Err(BsonQmPriceError::WrongType {
|
||||
field: FIELD_SHARE_VOLUME,
|
||||
actual: ElementType::Boolean,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_malformed_and_non_calendar_date_strings() {
|
||||
let bad_dates = [
|
||||
"",
|
||||
"2023-02-29",
|
||||
"2024-04-31",
|
||||
"2024-00-10",
|
||||
"2024-13-01",
|
||||
"2024/06/07",
|
||||
" 2024-06-07",
|
||||
"2024-06-07 ",
|
||||
"2024-06-07T00:00:00Z",
|
||||
"24-06-07",
|
||||
];
|
||||
for bad in bad_dates {
|
||||
let doc = make_qm_price_doc_f64("NVDA", bad, 100.0);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&doc),
|
||||
Err(BsonQmPriceError::MalformedDate { field: FIELD_DATE }),
|
||||
"expected MalformedDate for '{bad}'"
|
||||
);
|
||||
}
|
||||
|
||||
// Leap day 2024-02-29 is valid.
|
||||
let leap = make_qm_price_doc_f64("NVDA", "2024-02-29", 100.0);
|
||||
assert_eq!(
|
||||
decode_qm_price_doc(&leap).unwrap().session_date,
|
||||
day(2024, 2, 29)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_and_truncated_buffers_never_panic_and_preserve_accounting() {
|
||||
assert!(matches!(
|
||||
decode_qm_price_bytes(&[1, 2]),
|
||||
Err(BsonQmPriceError::TruncatedDocument { offset: 0, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
decode_qm_price_bytes(&4_i32.to_le_bytes()),
|
||||
Err(BsonQmPriceError::CorruptDocumentLength {
|
||||
offset: 0,
|
||||
declared_len: 4
|
||||
})
|
||||
));
|
||||
|
||||
// Mixed buffer: 3 valid (Double, Int32, Int64), 1 missing field, 1 empty field,
|
||||
// 1 wrong type, 1 malformed date, 1 trailing truncated doc.
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(make_qm_price_doc_f64("NVDA", "2024-06-07", 41_239_000.0).as_bytes());
|
||||
|
||||
let mut d_i32 = RawDocumentBuf::new();
|
||||
d_i32.append(cstr!("qmSearchCode"), "RY:CA");
|
||||
d_i32.append(cstr!("date"), "2024-06-07");
|
||||
d_i32.append(cstr!("sharevolume"), 2_500_000_i32);
|
||||
buf.extend_from_slice(d_i32.as_bytes());
|
||||
|
||||
let mut d_i64 = RawDocumentBuf::new();
|
||||
d_i64.append(cstr!("qmSearchCode"), "AAPL");
|
||||
d_i64.append(cstr!("date"), "2024-06-07");
|
||||
d_i64.append(cstr!("sharevolume"), 50_000_000_i64);
|
||||
buf.extend_from_slice(d_i64.as_bytes());
|
||||
|
||||
let mut missing = RawDocumentBuf::new();
|
||||
missing.append(cstr!("qmSearchCode"), "MSFT");
|
||||
missing.append(cstr!("date"), "2024-06-07");
|
||||
buf.extend_from_slice(missing.as_bytes());
|
||||
|
||||
buf.extend_from_slice(make_qm_price_doc_f64(" ", "2024-06-07", 10.0).as_bytes());
|
||||
|
||||
let mut wrong_type = RawDocumentBuf::new();
|
||||
wrong_type.append(cstr!("qmSearchCode"), "AMZN");
|
||||
wrong_type.append(cstr!("date"), "2024-06-07");
|
||||
wrong_type.append(cstr!("sharevolume"), "not-a-number");
|
||||
buf.extend_from_slice(wrong_type.as_bytes());
|
||||
|
||||
buf.extend_from_slice(make_qm_price_doc_f64("GOOG", "2023-02-29", 10.0).as_bytes());
|
||||
|
||||
let truncated_offset = buf.len();
|
||||
buf.extend_from_slice(&50_i32.to_le_bytes());
|
||||
buf.extend_from_slice(&[0x02, b'a', 0x00]);
|
||||
|
||||
let mut decoded_rows: Vec<(String, i32, f64)> = Vec::new();
|
||||
let mut errors: Vec<(usize, BsonQmPriceError)> = Vec::new();
|
||||
let stats = decode_qm_price_buffer(
|
||||
&buf,
|
||||
|p| decoded_rows.push((p.qm_search_code.to_owned(), p.session_date, p.share_volume)),
|
||||
|off, err| errors.push((off, err)),
|
||||
);
|
||||
|
||||
assert_eq!(stats.docs_in, 8);
|
||||
assert_eq!(stats.decoded, 3);
|
||||
assert_eq!(stats.rejected_missing_field, 1);
|
||||
assert_eq!(stats.rejected_empty_field, 1);
|
||||
assert_eq!(stats.rejected_wrong_type, 1);
|
||||
assert_eq!(stats.rejected_malformed_date, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stats.rejected_total(), 5);
|
||||
assert_eq!(stats.docs_in, stats.decoded + stats.rejected_total());
|
||||
assert_eq!(decoded_rows.len(), 3);
|
||||
assert_eq!(errors.len(), 5);
|
||||
assert_eq!(errors.last().unwrap().0, truncated_offset);
|
||||
assert!(matches!(
|
||||
errors.last().unwrap().1,
|
||||
BsonQmPriceError::TruncatedDocument { .. }
|
||||
));
|
||||
|
||||
// Verify merge / AddAssign.
|
||||
let mut merged = BsonQmPriceDecodeStats::default();
|
||||
merged += stats;
|
||||
merged += stats;
|
||||
assert_eq!(merged.docs_in, 16);
|
||||
assert_eq!(merged.decoded, 6);
|
||||
assert_eq!(merged.rejected_total(), 10);
|
||||
assert_eq!(merged.docs_in, merged.decoded + merged.rejected_total());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_bson_later_in_doc_surfaces_before_semantic_error() {
|
||||
// Build a doc with a semantic error (wrong-typed sharevolume) followed by corrupt trailing bytes.
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("qmSearchCode"), "NVDA");
|
||||
doc.append(cstr!("date"), "2024-06-07");
|
||||
doc.append(cstr!("sharevolume"), "bad-type");
|
||||
doc.append(cstr!("extra"), "hello");
|
||||
let mut bytes = doc.into_bytes();
|
||||
// Corrupt the type byte of "extra" (change string element type 0x02 to invalid 0x7E)
|
||||
// Locate "extra\0" in bytes; the type byte is right before it.
|
||||
let pos = bytes
|
||||
.windows(6)
|
||||
.position(|w| w == b"extra\0")
|
||||
.expect("extra key");
|
||||
bytes[pos - 1] = 0x7E;
|
||||
|
||||
let err = decode_qm_price_bytes(&bytes).unwrap_err();
|
||||
assert!(
|
||||
matches!(err, BsonQmPriceError::CorruptBson { offset: 0, .. }),
|
||||
"expected CorruptBson, got {err:?}"
|
||||
);
|
||||
}
|
||||
1082
tools/curate-etl/src/bson_stream.rs
Normal file
1082
tools/curate-etl/src/bson_stream.rs
Normal file
File diff suppressed because it is too large
Load diff
2115
tools/curate-etl/src/bson_stream_tests.rs
Normal file
2115
tools/curate-etl/src/bson_stream_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
839
tools/curate-etl/src/bson_te_market_data.rs
Normal file
839
tools/curate-etl/src/bson_te_market_data.rs
Normal file
|
|
@ -0,0 +1,839 @@
|
|||
//! Zero-copy raw BSON decoder for MongoDB `teMarketData` documents (`M1.2ac`).
|
||||
//!
|
||||
//! Decodes `&bson::RawDocument` slices in a single forward pass over `iter_elements()` without
|
||||
//! allocating a `bson::Document` or per-point heap memory, emitting [`FxDailyBar`] values via a
|
||||
//! caller-supplied callback.
|
||||
//!
|
||||
//! # Empirical Field Contract & Unverified Assumptions
|
||||
//!
|
||||
//! - Field names are derived from the ingestion writer in
|
||||
//! `apps/stock/data-ingestion/src/handlers/te/actions/market-data-fetch.action.ts`
|
||||
//! (`teSymbol`, `daily: [{ t, o, h, l, c, pc, ac }]`, `monthly`), and isolated in the
|
||||
//! `pub const FIELD_*` constants below. They have **not** yet been verified against a live
|
||||
//! `mongodump` of `teMarketData`.
|
||||
//! - **`t` epoch unit rule (unverified in repo):** TradingEconomics CDN series timestamps may be
|
||||
//! stored in either Unix seconds or Unix milliseconds. This decoder converts numeric `t` via
|
||||
//! [`TE_EPOCH_MILLIS_THRESHOLD`] (`100_000_000_000`):
|
||||
//! - `|t| >= 100_000_000_000` → treated as Unix **milliseconds**
|
||||
//! (`session_date = floor(t / 86_400_000)` UTC).
|
||||
//! - `|t| < 100_000_000_000` → treated as Unix **seconds**
|
||||
//! (`session_date = floor(t / 86_400)` UTC).
|
||||
//! - Floor division (`div_euclid`) ensures pre-1970 negative timestamps round down to the
|
||||
//! earlier UTC calendar day rather than truncating toward zero.
|
||||
//! - `monthly`, `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
||||
//! - `daily` is captured lazily as a raw [`RawElement`] during the top-level scan and only decoded
|
||||
//! after `teSymbol` matches `target_symbol` (ASCII case-insensitive), so non-target symbols pay
|
||||
//! zero array-scan cost and never emit false `daily` errors even when `daily` precedes `teSymbol`
|
||||
//! in raw BSON field order.
|
||||
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
|
||||
use bson::raw::{RawBsonRef, RawDocument, RawElement};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use crate::bson_eod_prices::{iter_raw_bson_docs, parse_single_raw_doc, BsonEodPriceError};
|
||||
use crate::fx::FxDailyBar;
|
||||
|
||||
/// MongoDB field name for the TradingEconomics symbol key (`market-data-fetch.action.ts:133`).
|
||||
pub const FIELD_TE_SYMBOL: &str = "teSymbol";
|
||||
/// MongoDB field name for the daily OHLC array (`market-data-fetch.action.ts:144`).
|
||||
pub const FIELD_DAILY: &str = "daily";
|
||||
/// MongoDB field name for the monthly OHLC array, explicitly ignored (`market-data-fetch.action.ts:145`).
|
||||
pub const FIELD_MONTHLY: &str = "monthly";
|
||||
/// Point field name for the Unix epoch timestamp (`market-data-fetch.action.ts:15`).
|
||||
pub const FIELD_POINT_T: &str = "t";
|
||||
/// Point field name for open price (`market-data-fetch.action.ts:16`).
|
||||
pub const FIELD_POINT_O: &str = "o";
|
||||
/// Point field name for high price (`market-data-fetch.action.ts:17`).
|
||||
pub const FIELD_POINT_H: &str = "h";
|
||||
/// Point field name for low price (`market-data-fetch.action.ts:18`).
|
||||
pub const FIELD_POINT_L: &str = "l";
|
||||
/// Point field name for close price (`market-data-fetch.action.ts:19`).
|
||||
pub const FIELD_POINT_C: &str = "c";
|
||||
|
||||
/// Magnitude threshold distinguishing Unix milliseconds (`|t| >= 100_000_000_000`) from Unix
|
||||
/// seconds (`|t| < 100_000_000_000`).
|
||||
pub const TE_EPOCH_MILLIS_THRESHOLD: i64 = 100_000_000_000;
|
||||
/// Number of seconds in one UTC calendar day.
|
||||
pub const SECONDS_PER_DAY: i64 = 86_400;
|
||||
/// Number of milliseconds in one UTC calendar day.
|
||||
pub const MILLIS_PER_DAY: i64 = 86_400_000;
|
||||
|
||||
/// Converts an integer Unix epoch timestamp `t` (seconds or milliseconds per
|
||||
/// [`TE_EPOCH_MILLIS_THRESHOLD`]) into UTC `session_date` (days since `1970-01-01`).
|
||||
///
|
||||
/// Uses `unsigned_abs()` (avoiding `i64::MIN.abs()` overflow), `div_euclid` (flooring negative
|
||||
/// pre-1970 timestamps to the earlier UTC calendar day), and checked `i32::try_from`.
|
||||
#[inline]
|
||||
pub fn te_epoch_i64_to_session_date(t: i64) -> Option<i32> {
|
||||
let days = if t.unsigned_abs() >= TE_EPOCH_MILLIS_THRESHOLD as u64 {
|
||||
t.div_euclid(MILLIS_PER_DAY)
|
||||
} else {
|
||||
t.div_euclid(SECONDS_PER_DAY)
|
||||
};
|
||||
i32::try_from(days).ok()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn te_epoch_f64_to_session_date(point_index: usize, v: f64) -> Result<i32, BsonTeMarketDataError> {
|
||||
if !v.is_finite() {
|
||||
return Err(BsonTeMarketDataError::NonFiniteValue {
|
||||
point_index,
|
||||
field: FIELD_POINT_T,
|
||||
value: v,
|
||||
});
|
||||
}
|
||||
let is_millis = v.abs() >= TE_EPOCH_MILLIS_THRESHOLD as f64;
|
||||
let t_floor = v.floor();
|
||||
// Exact half-open range of `f64` values representable as `i64` (`[-2^63, 2^63)`).
|
||||
if !(-9_223_372_036_854_775_808.0..9_223_372_036_854_775_808.0).contains(&t_floor) {
|
||||
return Err(BsonTeMarketDataError::DateOutOfRange { point_index });
|
||||
}
|
||||
let t_i64 = t_floor as i64;
|
||||
let days = if is_millis {
|
||||
t_i64.div_euclid(MILLIS_PER_DAY)
|
||||
} else {
|
||||
t_i64.div_euclid(SECONDS_PER_DAY)
|
||||
};
|
||||
i32::try_from(days).map_err(|_| BsonTeMarketDataError::DateOutOfRange { point_index })
|
||||
}
|
||||
|
||||
/// Typed errors returned while decoding raw `teMarketData` BSON documents or length-prefixed
|
||||
/// buffers.
|
||||
///
|
||||
/// Every variant's `Display` output is a single line; no input path panics.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum BsonTeMarketDataError {
|
||||
/// Required top-level `teSymbol` field was absent.
|
||||
MissingSymbol,
|
||||
/// Top-level `teSymbol` string was empty or whitespace-only.
|
||||
EmptySymbol,
|
||||
/// Top-level `teSymbol` had an unexpected BSON element type.
|
||||
WrongSymbolType { actual: ElementType },
|
||||
/// Required `daily` field was absent on a matched `teSymbol` document.
|
||||
MissingDaily,
|
||||
/// `daily` field on a matched `teSymbol` document was not a BSON array.
|
||||
DailyNotArray { actual: ElementType },
|
||||
/// An element inside `daily` was not an embedded BSON document.
|
||||
PointNotDocument {
|
||||
point_index: usize,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A required field (`t`, `o`, `h`, `l`, or `c`) was absent from a `daily` point document.
|
||||
MissingPointField {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
},
|
||||
/// A required field in a `daily` point document had an unexpected BSON type.
|
||||
WrongPointFieldType {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
actual: ElementType,
|
||||
},
|
||||
/// A numeric field (`t`, `o`, `h`, `l`, or `c`) in a `daily` point was `NaN` or `±inf`.
|
||||
NonFiniteValue {
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
value: f64,
|
||||
},
|
||||
/// Point timestamp `t` mapped outside the `i32` UTC epoch-day range.
|
||||
DateOutOfRange { point_index: usize },
|
||||
/// Buffer ended before a complete 4-byte length prefix or declared document body.
|
||||
TruncatedDocument {
|
||||
offset: usize,
|
||||
remaining: usize,
|
||||
declared_len: Option<i32>,
|
||||
},
|
||||
/// Declared 4-byte little-endian BSON document length was `< 5` (or did not match a single
|
||||
/// document slice).
|
||||
CorruptDocumentLength { offset: usize, declared_len: i32 },
|
||||
/// Underlying top-level BSON framing or element bytes were malformed.
|
||||
CorruptBson { offset: usize, detail: String },
|
||||
/// Underlying BSON bytes inside a `daily` array or point document were malformed.
|
||||
CorruptPointBson {
|
||||
offset: usize,
|
||||
point_index: usize,
|
||||
detail: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl fmt::Display for BsonTeMarketDataError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::MissingSymbol => {
|
||||
write!(f, "teMarketData BSON missing required field '{FIELD_TE_SYMBOL}'")
|
||||
}
|
||||
Self::EmptySymbol => {
|
||||
write!(
|
||||
f,
|
||||
"teMarketData BSON field '{FIELD_TE_SYMBOL}' must not be empty or blank"
|
||||
)
|
||||
}
|
||||
Self::WrongSymbolType { actual } => write!(
|
||||
f,
|
||||
"teMarketData BSON field '{FIELD_TE_SYMBOL}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::MissingDaily => {
|
||||
write!(f, "teMarketData BSON missing required field '{FIELD_DAILY}'")
|
||||
}
|
||||
Self::DailyNotArray { actual } => write!(
|
||||
f,
|
||||
"teMarketData BSON field '{FIELD_DAILY}' has unexpected BSON type {actual:?} (expected Array)"
|
||||
),
|
||||
Self::PointNotDocument {
|
||||
point_index,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}]' has unexpected BSON type {actual:?} (expected EmbeddedDocument)"
|
||||
),
|
||||
Self::MissingPointField { point_index, field } => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}]' missing required field '{field}'"
|
||||
),
|
||||
Self::WrongPointFieldType {
|
||||
point_index,
|
||||
field,
|
||||
actual,
|
||||
} => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has unexpected BSON type {actual:?}"
|
||||
),
|
||||
Self::NonFiniteValue {
|
||||
point_index,
|
||||
field,
|
||||
value,
|
||||
} => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{field}' has non-finite value {value}"
|
||||
),
|
||||
Self::DateOutOfRange { point_index } => write!(
|
||||
f,
|
||||
"teMarketData BSON '{FIELD_DAILY}[{point_index}].{FIELD_POINT_T}' overflows i32 UTC session_date"
|
||||
),
|
||||
Self::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => match declared_len {
|
||||
Some(len) => write!(
|
||||
f,
|
||||
"truncated BSON document at byte offset {offset}: declared length {len} exceeds remaining {remaining} bytes"
|
||||
),
|
||||
None => write!(
|
||||
f,
|
||||
"truncated BSON document header at byte offset {offset}: only {remaining} bytes remaining"
|
||||
),
|
||||
},
|
||||
Self::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON document length {declared_len} at byte offset {offset}"
|
||||
),
|
||||
Self::CorruptBson { offset, detail } => {
|
||||
write!(f, "corrupt BSON bytes at byte offset {offset}: {detail}")
|
||||
}
|
||||
Self::CorruptPointBson {
|
||||
offset,
|
||||
point_index,
|
||||
detail,
|
||||
} => write!(
|
||||
f,
|
||||
"corrupt BSON bytes in '{FIELD_DAILY}[{point_index}]' at byte offset {offset}: {detail}"
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for BsonTeMarketDataError {}
|
||||
|
||||
#[inline]
|
||||
fn map_framing_error(err: BsonEodPriceError) -> BsonTeMarketDataError {
|
||||
match err {
|
||||
BsonEodPriceError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
} => BsonTeMarketDataError::TruncatedDocument {
|
||||
offset,
|
||||
remaining,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
} => BsonTeMarketDataError::CorruptDocumentLength {
|
||||
offset,
|
||||
declared_len,
|
||||
},
|
||||
BsonEodPriceError::CorruptBson { offset, detail } => {
|
||||
BsonTeMarketDataError::CorruptBson { offset, detail }
|
||||
}
|
||||
other => BsonTeMarketDataError::CorruptBson {
|
||||
offset: 0,
|
||||
detail: other.to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-batch document and point decode accounting for `teMarketData`.
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `docs_in == docs_matched + docs_other_symbol + docs_rejected_total()`
|
||||
/// - `points_in == points_decoded + rejected_total()`
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct BsonTeMarketDataDecodeStats {
|
||||
pub docs_in: usize,
|
||||
pub docs_matched: usize,
|
||||
pub docs_other_symbol: usize,
|
||||
pub rejected_missing_symbol: usize,
|
||||
pub rejected_empty_symbol: usize,
|
||||
pub rejected_wrong_symbol_type: usize,
|
||||
pub rejected_daily_missing: usize,
|
||||
pub rejected_daily_not_array: usize,
|
||||
pub rejected_corrupt_document: usize,
|
||||
pub points_in: usize,
|
||||
pub points_decoded: usize,
|
||||
pub rejected_point_not_document: usize,
|
||||
pub rejected_missing_field: usize,
|
||||
pub rejected_wrong_type: usize,
|
||||
pub rejected_non_finite: usize,
|
||||
pub rejected_date_out_of_range: usize,
|
||||
pub rejected_corrupt_point: usize,
|
||||
}
|
||||
|
||||
impl BsonTeMarketDataDecodeStats {
|
||||
/// Total number of document-level rejects across all document error categories.
|
||||
#[inline]
|
||||
pub fn docs_rejected_total(&self) -> usize {
|
||||
self.rejected_missing_symbol
|
||||
+ self.rejected_empty_symbol
|
||||
+ self.rejected_wrong_symbol_type
|
||||
+ self.rejected_daily_missing
|
||||
+ self.rejected_daily_not_array
|
||||
+ self.rejected_corrupt_document
|
||||
}
|
||||
|
||||
/// Total number of point-level rejects across all point error categories.
|
||||
#[inline]
|
||||
pub fn rejected_total(&self) -> usize {
|
||||
self.rejected_point_not_document
|
||||
+ self.rejected_missing_field
|
||||
+ self.rejected_wrong_type
|
||||
+ self.rejected_non_finite
|
||||
+ self.rejected_date_out_of_range
|
||||
+ self.rejected_corrupt_point
|
||||
}
|
||||
|
||||
/// Increments the point-level rejection counter corresponding to `err`.
|
||||
#[inline]
|
||||
fn record_point_error(&mut self, err: &BsonTeMarketDataError) {
|
||||
match err {
|
||||
BsonTeMarketDataError::PointNotDocument { .. } => {
|
||||
self.rejected_point_not_document += 1;
|
||||
}
|
||||
BsonTeMarketDataError::MissingPointField { .. } => {
|
||||
self.rejected_missing_field += 1;
|
||||
}
|
||||
BsonTeMarketDataError::WrongPointFieldType { .. } => {
|
||||
self.rejected_wrong_type += 1;
|
||||
}
|
||||
BsonTeMarketDataError::NonFiniteValue { .. } => {
|
||||
self.rejected_non_finite += 1;
|
||||
}
|
||||
BsonTeMarketDataError::DateOutOfRange { .. } => {
|
||||
self.rejected_date_out_of_range += 1;
|
||||
}
|
||||
BsonTeMarketDataError::CorruptPointBson { .. } => {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
_ => {
|
||||
self.rejected_corrupt_point += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Accumulates counters from another batch into `self`.
|
||||
#[inline]
|
||||
pub fn merge(&mut self, other: &Self) {
|
||||
self.docs_in += other.docs_in;
|
||||
self.docs_matched += other.docs_matched;
|
||||
self.docs_other_symbol += other.docs_other_symbol;
|
||||
self.rejected_missing_symbol += other.rejected_missing_symbol;
|
||||
self.rejected_empty_symbol += other.rejected_empty_symbol;
|
||||
self.rejected_wrong_symbol_type += other.rejected_wrong_symbol_type;
|
||||
self.rejected_daily_missing += other.rejected_daily_missing;
|
||||
self.rejected_daily_not_array += other.rejected_daily_not_array;
|
||||
self.rejected_corrupt_document += other.rejected_corrupt_document;
|
||||
self.points_in += other.points_in;
|
||||
self.points_decoded += other.points_decoded;
|
||||
self.rejected_point_not_document += other.rejected_point_not_document;
|
||||
self.rejected_missing_field += other.rejected_missing_field;
|
||||
self.rejected_wrong_type += other.rejected_wrong_type;
|
||||
self.rejected_non_finite += other.rejected_non_finite;
|
||||
self.rejected_date_out_of_range += other.rejected_date_out_of_range;
|
||||
self.rejected_corrupt_point += other.rejected_corrupt_point;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for BsonTeMarketDataDecodeStats {
|
||||
#[inline]
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.merge(&rhs);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_point_t(
|
||||
point_index: usize,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<i32, BsonTeMarketDataError> {
|
||||
match val {
|
||||
RawBsonRef::Int32(v) => te_epoch_i64_to_session_date(i64::from(v))
|
||||
.ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }),
|
||||
RawBsonRef::Int64(v) => te_epoch_i64_to_session_date(v)
|
||||
.ok_or(BsonTeMarketDataError::DateOutOfRange { point_index }),
|
||||
RawBsonRef::Double(v) => te_epoch_f64_to_session_date(point_index, v),
|
||||
other => Err(BsonTeMarketDataError::WrongPointFieldType {
|
||||
point_index,
|
||||
field: FIELD_POINT_T,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn decode_point_price(
|
||||
point_index: usize,
|
||||
field: &'static str,
|
||||
val: RawBsonRef<'_>,
|
||||
) -> Result<f64, BsonTeMarketDataError> {
|
||||
match val {
|
||||
RawBsonRef::Double(v) => {
|
||||
if !v.is_finite() {
|
||||
return Err(BsonTeMarketDataError::NonFiniteValue {
|
||||
point_index,
|
||||
field,
|
||||
value: v,
|
||||
});
|
||||
}
|
||||
Ok(v)
|
||||
}
|
||||
RawBsonRef::Int32(v) => Ok(f64::from(v)),
|
||||
RawBsonRef::Int64(v) => Ok(v as f64),
|
||||
other => Err(BsonTeMarketDataError::WrongPointFieldType {
|
||||
point_index,
|
||||
field,
|
||||
actual: other.element_type(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_point_doc(
|
||||
point_doc: &RawDocument,
|
||||
doc_offset: usize,
|
||||
point_index: usize,
|
||||
) -> Result<FxDailyBar, BsonTeMarketDataError> {
|
||||
let mut session_date: Option<i32> = None;
|
||||
let mut open: Option<f64> = None;
|
||||
let mut high: Option<f64> = None;
|
||||
let mut low: Option<f64> = None;
|
||||
let mut close: Option<f64> = None;
|
||||
let mut first_semantic_err: Option<BsonTeMarketDataError> = None;
|
||||
|
||||
for elem_res in point_doc.iter_elements() {
|
||||
let elem = elem_res.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: err.to_string(),
|
||||
})?;
|
||||
let key = elem.key().as_str();
|
||||
|
||||
if key == FIELD_POINT_T {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_T}': {err}"),
|
||||
})?;
|
||||
match decode_point_t(point_index, val) {
|
||||
Ok(v) => session_date = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_O {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_O}': {err}"),
|
||||
})?;
|
||||
match decode_point_price(point_index, FIELD_POINT_O, val) {
|
||||
Ok(v) => open = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_H {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_H}': {err}"),
|
||||
})?;
|
||||
match decode_point_price(point_index, FIELD_POINT_H, val) {
|
||||
Ok(v) => high = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_L {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_L}': {err}"),
|
||||
})?;
|
||||
match decode_point_price(point_index, FIELD_POINT_L, val) {
|
||||
Ok(v) => low = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_POINT_C {
|
||||
let val = elem
|
||||
.value()
|
||||
.map_err(|err| BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: format!("field '{FIELD_POINT_C}': {err}"),
|
||||
})?;
|
||||
match decode_point_price(point_index, FIELD_POINT_C, val) {
|
||||
Ok(v) => close = Some(v),
|
||||
Err(err) => {
|
||||
if first_semantic_err.is_none() {
|
||||
first_semantic_err = Some(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// `pc`, `ac`, and all unknown fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = first_semantic_err {
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
let Some(session_date) = session_date else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_T,
|
||||
});
|
||||
};
|
||||
let Some(open) = open else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_O,
|
||||
});
|
||||
};
|
||||
let Some(high) = high else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_H,
|
||||
});
|
||||
};
|
||||
let Some(low) = low else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_L,
|
||||
});
|
||||
};
|
||||
let Some(close) = close else {
|
||||
return Err(BsonTeMarketDataError::MissingPointField {
|
||||
point_index,
|
||||
field: FIELD_POINT_C,
|
||||
});
|
||||
};
|
||||
|
||||
Ok(FxDailyBar {
|
||||
session_date,
|
||||
open,
|
||||
high,
|
||||
low,
|
||||
close,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_te_market_data_doc_at<F, E>(
|
||||
doc: &RawDocument,
|
||||
doc_offset: usize,
|
||||
target_symbol: &str,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(BsonTeMarketDataError),
|
||||
{
|
||||
let mut stats = BsonTeMarketDataDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonTeMarketDataDecodeStats::default()
|
||||
};
|
||||
|
||||
let mut te_symbol: Option<&str> = None;
|
||||
let mut symbol_err: Option<BsonTeMarketDataError> = None;
|
||||
let mut daily_elem: Option<RawElement<'_>> = None;
|
||||
|
||||
for elem_res in doc.iter_elements() {
|
||||
let elem = match elem_res {
|
||||
Ok(elem) => elem,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeMarketDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: err.to_string(),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
let key = elem.key().as_str();
|
||||
if key == FIELD_TE_SYMBOL {
|
||||
let val = match elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeMarketDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_TE_SYMBOL}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
match val {
|
||||
RawBsonRef::String(s) => {
|
||||
if s.trim().is_empty() {
|
||||
if symbol_err.is_none() {
|
||||
symbol_err = Some(BsonTeMarketDataError::EmptySymbol);
|
||||
}
|
||||
} else {
|
||||
te_symbol = Some(s);
|
||||
}
|
||||
}
|
||||
other => {
|
||||
if symbol_err.is_none() {
|
||||
symbol_err = Some(BsonTeMarketDataError::WrongSymbolType {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if key == FIELD_DAILY {
|
||||
daily_elem = Some(elem);
|
||||
}
|
||||
// `FIELD_MONTHLY` and all other top-level fields are skipped without calling `elem.value()`.
|
||||
}
|
||||
|
||||
if let Some(err) = symbol_err {
|
||||
match &err {
|
||||
BsonTeMarketDataError::EmptySymbol => stats.rejected_empty_symbol += 1,
|
||||
BsonTeMarketDataError::WrongSymbolType { .. } => stats.rejected_wrong_symbol_type += 1,
|
||||
_ => stats.rejected_corrupt_document += 1,
|
||||
}
|
||||
on_error(err);
|
||||
return stats;
|
||||
}
|
||||
|
||||
let Some(symbol) = te_symbol else {
|
||||
stats.rejected_missing_symbol += 1;
|
||||
on_error(BsonTeMarketDataError::MissingSymbol);
|
||||
return stats;
|
||||
};
|
||||
|
||||
if !symbol.eq_ignore_ascii_case(target_symbol) {
|
||||
stats.docs_other_symbol += 1;
|
||||
return stats;
|
||||
}
|
||||
|
||||
let Some(daily_elem) = daily_elem else {
|
||||
stats.rejected_daily_missing += 1;
|
||||
on_error(BsonTeMarketDataError::MissingDaily);
|
||||
return stats;
|
||||
};
|
||||
|
||||
let daily_val = match daily_elem.value() {
|
||||
Ok(val) => val,
|
||||
Err(err) => {
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(BsonTeMarketDataError::CorruptBson {
|
||||
offset: doc_offset,
|
||||
detail: format!("field '{FIELD_DAILY}': {err}"),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
|
||||
let daily_arr = match daily_val {
|
||||
RawBsonRef::Array(arr) => arr,
|
||||
other => {
|
||||
stats.rejected_daily_not_array += 1;
|
||||
on_error(BsonTeMarketDataError::DailyNotArray {
|
||||
actual: other.element_type(),
|
||||
});
|
||||
return stats;
|
||||
}
|
||||
};
|
||||
|
||||
stats.docs_matched += 1;
|
||||
|
||||
for (point_index, item_res) in daily_arr.into_iter().enumerate() {
|
||||
stats.points_in += 1;
|
||||
let item = match item_res {
|
||||
Ok(item) => item,
|
||||
Err(err) => {
|
||||
let err = BsonTeMarketDataError::CorruptPointBson {
|
||||
offset: doc_offset,
|
||||
point_index,
|
||||
detail: err.to_string(),
|
||||
};
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
let point_doc = match item {
|
||||
RawBsonRef::Document(point_doc) => point_doc,
|
||||
other => {
|
||||
let err = BsonTeMarketDataError::PointNotDocument {
|
||||
point_index,
|
||||
actual: other.element_type(),
|
||||
};
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
match decode_point_doc(point_doc, doc_offset, point_index) {
|
||||
Ok(bar) => {
|
||||
stats.points_decoded += 1;
|
||||
on_bar(bar);
|
||||
}
|
||||
Err(err) => {
|
||||
stats.record_point_error(&err);
|
||||
on_error(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
/// Decodes a single `&RawDocument` representing a `teMarketData` MongoDB document in one forward
|
||||
/// pass without allocating a `bson::Document` or per-point heap memory.
|
||||
///
|
||||
/// Matches `teSymbol` against `target_symbol` using ASCII case-insensitive comparison. For matched
|
||||
/// documents, emits each valid `daily` point as an [`FxDailyBar`] via `on_bar` and reports
|
||||
/// document- or point-level errors to `on_error` without panicking.
|
||||
#[inline]
|
||||
pub fn decode_te_market_data_doc<F, E>(
|
||||
doc: &RawDocument,
|
||||
target_symbol: &str,
|
||||
on_bar: F,
|
||||
on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(BsonTeMarketDataError),
|
||||
{
|
||||
decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error)
|
||||
}
|
||||
|
||||
/// Decodes a single length-prefixed raw BSON document byte slice representing a `teMarketData`
|
||||
/// document.
|
||||
pub fn decode_te_market_data_bytes<F, E>(
|
||||
bytes: &[u8],
|
||||
target_symbol: &str,
|
||||
on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(BsonTeMarketDataError),
|
||||
{
|
||||
match parse_single_raw_doc(bytes) {
|
||||
Ok(doc) => decode_te_market_data_doc_at(doc, 0, target_symbol, on_bar, on_error),
|
||||
Err(err) => {
|
||||
let mut stats = BsonTeMarketDataDecodeStats {
|
||||
docs_in: 1,
|
||||
..BsonTeMarketDataDecodeStats::default()
|
||||
};
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(map_framing_error(err));
|
||||
stats
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Streams a concatenated length-prefixed BSON buffer through [`decode_te_market_data_doc`],
|
||||
/// emitting every valid [`FxDailyBar`] for `target_symbol` (ASCII case-insensitive) to `on_bar`
|
||||
/// and reporting document- or point-level errors to `on_error(byte_offset, err)` without aborting.
|
||||
///
|
||||
/// Always maintains:
|
||||
/// - `stats.docs_in == stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total()`
|
||||
/// - `stats.points_in == stats.points_decoded + stats.rejected_total()`
|
||||
pub fn decode_te_market_data_buffer<F, E>(
|
||||
buf: &[u8],
|
||||
target_symbol: &str,
|
||||
mut on_bar: F,
|
||||
mut on_error: E,
|
||||
) -> BsonTeMarketDataDecodeStats
|
||||
where
|
||||
F: FnMut(FxDailyBar),
|
||||
E: FnMut(usize, BsonTeMarketDataError),
|
||||
{
|
||||
let mut stats = BsonTeMarketDataDecodeStats::default();
|
||||
let mut iter = iter_raw_bson_docs(buf);
|
||||
|
||||
while let Some(item) = iter.next_with_offset() {
|
||||
match item {
|
||||
Ok((doc_offset, doc)) => {
|
||||
let doc_stats = decode_te_market_data_doc_at(
|
||||
doc,
|
||||
doc_offset,
|
||||
target_symbol,
|
||||
&mut on_bar,
|
||||
|err| on_error(doc_offset, err),
|
||||
);
|
||||
stats += doc_stats;
|
||||
}
|
||||
Err((doc_offset, err)) => {
|
||||
stats.docs_in += 1;
|
||||
stats.rejected_corrupt_document += 1;
|
||||
on_error(doc_offset, map_framing_error(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stats
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "bson_te_market_data_tests.rs"]
|
||||
mod tests;
|
||||
522
tools/curate-etl/src/bson_te_market_data_tests.rs
Normal file
522
tools/curate-etl/src/bson_te_market_data_tests.rs
Normal file
|
|
@ -0,0 +1,522 @@
|
|||
use bson::raw::{cstr, RawArrayBuf, RawDocumentBuf};
|
||||
use bson::spec::ElementType;
|
||||
|
||||
use super::*;
|
||||
use crate::bson_stream::{decode_te_market_data_stream, BsonStreamOptions};
|
||||
use crate::split::ymd_to_epoch_days;
|
||||
|
||||
fn day(y: i32, m: u32, d: u32) -> i32 {
|
||||
ymd_to_epoch_days(y, m, d).expect("valid date")
|
||||
}
|
||||
|
||||
fn assert_stats_conserved(stats: &BsonTeMarketDataDecodeStats) {
|
||||
assert_eq!(
|
||||
stats.docs_in,
|
||||
stats.docs_matched + stats.docs_other_symbol + stats.docs_rejected_total(),
|
||||
"doc conservation failed: {stats:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
stats.points_in,
|
||||
stats.points_decoded + stats.rejected_total(),
|
||||
"point conservation failed: {stats:?}"
|
||||
);
|
||||
}
|
||||
|
||||
fn make_te_doc(symbol: &str, daily: RawArrayBuf) -> RawDocumentBuf {
|
||||
let mut doc = RawDocumentBuf::new();
|
||||
doc.append(cstr!("teSymbol"), symbol);
|
||||
doc.append(cstr!("daily"), daily);
|
||||
doc
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_int32_int64_double_and_seconds_vs_millis_to_same_session_date() {
|
||||
let d_2025 = day(2025, 1, 2);
|
||||
let secs_2025 = i64::from(d_2025) * SECONDS_PER_DAY;
|
||||
let ms_2025 = i64::from(d_2025) * MILLIS_PER_DAY;
|
||||
|
||||
let mut daily = RawArrayBuf::new();
|
||||
|
||||
// Point 0: Int32 seconds + Int32 OHLC
|
||||
let mut p0 = RawDocumentBuf::new();
|
||||
p0.append(cstr!("t"), i32::try_from(secs_2025 + 43_200).unwrap());
|
||||
p0.append(cstr!("o"), 1_i32);
|
||||
p0.append(cstr!("h"), 2_i32);
|
||||
p0.append(cstr!("l"), 1_i32);
|
||||
p0.append(cstr!("c"), 2_i32);
|
||||
p0.append(cstr!("pc"), 0.5_f64);
|
||||
p0.append(cstr!("ac"), 0.01_f64);
|
||||
daily.push(p0);
|
||||
|
||||
// Point 1: Int64 milliseconds + Int64 OHLC
|
||||
let mut p1 = RawDocumentBuf::new();
|
||||
p1.append(cstr!("t"), ms_2025 + 86_399_999);
|
||||
p1.append(cstr!("o"), 1_i64);
|
||||
p1.append(cstr!("h"), 3_i64);
|
||||
p1.append(cstr!("l"), 1_i64);
|
||||
p1.append(cstr!("c"), 2_i64);
|
||||
daily.push(p1);
|
||||
|
||||
// Point 2: Double seconds + Double OHLC
|
||||
let mut p2 = RawDocumentBuf::new();
|
||||
p2.append(cstr!("t"), (secs_2025 as f64) + 123.75);
|
||||
p2.append(cstr!("o"), 1.430_f64);
|
||||
p2.append(cstr!("h"), 1.445_f64);
|
||||
p2.append(cstr!("l"), 1.425_f64);
|
||||
p2.append(cstr!("c"), 1.438_f64);
|
||||
daily.push(p2);
|
||||
|
||||
// Point 3: Double milliseconds + Double OHLC
|
||||
let mut p3 = RawDocumentBuf::new();
|
||||
p3.append(cstr!("t"), (ms_2025 as f64) + 500.5);
|
||||
p3.append(cstr!("o"), 1.431_f64);
|
||||
p3.append(cstr!("h"), 1.446_f64);
|
||||
p3.append(cstr!("l"), 1.426_f64);
|
||||
p3.append(cstr!("c"), 1.439_f64);
|
||||
daily.push(p3);
|
||||
|
||||
let doc = make_te_doc("USDCAD", daily);
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_doc(&doc, "USDCAD", |b| bars.push(b), |e| errors.push(e));
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errors.is_empty(), "unexpected errors: {errors:?}");
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.docs_matched, 1);
|
||||
assert_eq!(stats.points_in, 4);
|
||||
assert_eq!(stats.points_decoded, 4);
|
||||
assert_eq!(bars.len(), 4);
|
||||
for bar in &bars {
|
||||
assert_eq!(bar.session_date, d_2025);
|
||||
}
|
||||
assert_eq!(bars[0].open, 1.0);
|
||||
assert_eq!(bars[0].high, 2.0);
|
||||
assert_eq!(bars[1].high, 3.0);
|
||||
assert_eq!(bars[2].close.to_bits(), 1.438_f64.to_bits());
|
||||
assert_eq!(bars[3].close.to_bits(), 1.439_f64.to_bits());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn epoch_threshold_boundaries_and_negative_pre_1970_floor_correctly() {
|
||||
// Exact threshold boundaries
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(TE_EPOCH_MILLIS_THRESHOLD - 1),
|
||||
Some((TE_EPOCH_MILLIS_THRESHOLD - 1).div_euclid(SECONDS_PER_DAY) as i32)
|
||||
);
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(TE_EPOCH_MILLIS_THRESHOLD),
|
||||
Some(TE_EPOCH_MILLIS_THRESHOLD.div_euclid(MILLIS_PER_DAY) as i32)
|
||||
);
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(-(TE_EPOCH_MILLIS_THRESHOLD - 1)),
|
||||
Some((-(TE_EPOCH_MILLIS_THRESHOLD - 1)).div_euclid(SECONDS_PER_DAY) as i32)
|
||||
);
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(-TE_EPOCH_MILLIS_THRESHOLD),
|
||||
Some((-TE_EPOCH_MILLIS_THRESHOLD).div_euclid(MILLIS_PER_DAY) as i32)
|
||||
);
|
||||
|
||||
// Pre-1970 negative timestamps floor to earlier UTC day
|
||||
assert_eq!(te_epoch_i64_to_session_date(0), Some(0)); // 1970-01-01
|
||||
assert_eq!(te_epoch_i64_to_session_date(-1), Some(-1)); // 1969-12-31 23:59:59 UTC
|
||||
assert_eq!(te_epoch_i64_to_session_date(-SECONDS_PER_DAY), Some(-1)); // 1969-12-31 00:00:00 UTC
|
||||
assert_eq!(te_epoch_i64_to_session_date(-SECONDS_PER_DAY - 1), Some(-2)); // 1969-12-30
|
||||
|
||||
// Pre-1970 negative milliseconds (1966-10-31 is past -100_000_000_000 ms)
|
||||
let neg_ms = -100_000_000_001_i64;
|
||||
assert_eq!(
|
||||
te_epoch_i64_to_session_date(neg_ms),
|
||||
Some(neg_ms.div_euclid(MILLIS_PER_DAY) as i32)
|
||||
);
|
||||
|
||||
// Overflow boundaries: i64::MIN and i64::MAX must never panic, return None
|
||||
assert_eq!(te_epoch_i64_to_session_date(i64::MIN), None);
|
||||
assert_eq!(te_epoch_i64_to_session_date(i64::MAX), None);
|
||||
|
||||
// Fractional negative Double values in BSON
|
||||
let mut daily = RawArrayBuf::new();
|
||||
for t_val in [-1.5_f64, -86_400.5_f64, -100_000_000_000.5_f64] {
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), t_val);
|
||||
pt.append(cstr!("o"), 1.05_f64);
|
||||
pt.append(cstr!("h"), 1.06_f64);
|
||||
pt.append(cstr!("l"), 1.04_f64);
|
||||
pt.append(cstr!("c"), 1.05_f64);
|
||||
daily.push(pt);
|
||||
}
|
||||
let doc = make_te_doc("USDCAD", daily);
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_doc(&doc, "USDCAD", |b| bars.push(b), |e| errors.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errors.is_empty(), "{errors:?}");
|
||||
assert_eq!(bars[0].session_date, -1); // -1.5 -> floor -2s -> day -1
|
||||
assert_eq!(bars[1].session_date, -2); // -86400.5 -> floor -86401s -> day -2
|
||||
assert_eq!(
|
||||
bars[2].session_date,
|
||||
(-100_000_000_001_i64).div_euclid(MILLIS_PER_DAY) as i32
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn daily_before_symbol_case_insensitive_match_and_monthly_ignored() {
|
||||
let d1 = day(2025, 3, 10);
|
||||
|
||||
// 1. Matched doc (lowercase "usdcad") with `daily` BEFORE `teSymbol` and broken `monthly`
|
||||
let mut daily = RawArrayBuf::new();
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), i64::from(d1) * SECONDS_PER_DAY);
|
||||
pt.append(cstr!("o"), 1.44_f64);
|
||||
pt.append(cstr!("h"), 1.45_f64);
|
||||
pt.append(cstr!("l"), 1.43_f64);
|
||||
pt.append(cstr!("c"), 1.445_f64);
|
||||
pt.append(cstr!("pc"), bson::raw::RawBson::Null);
|
||||
pt.append(cstr!("ac"), bson::raw::RawBson::Null);
|
||||
pt.append(cstr!("extra"), "ignored");
|
||||
daily.push(pt);
|
||||
|
||||
let mut bad_monthly = RawArrayBuf::new();
|
||||
bad_monthly.push("not-a-doc");
|
||||
bad_monthly.push(f64::NAN);
|
||||
|
||||
let mut doc1 = RawDocumentBuf::new();
|
||||
doc1.append(cstr!("monthly"), bad_monthly);
|
||||
doc1.append(cstr!("daily"), daily);
|
||||
doc1.append(cstr!("teSymbol"), "usdcad");
|
||||
|
||||
// 2. Non-target symbol with invalid `daily` (not an array) placed BEFORE `teSymbol`:
|
||||
// must be counted as `docs_other_symbol` with zero errors!
|
||||
let mut doc2 = RawDocumentBuf::new();
|
||||
doc2.append(cstr!("daily"), "not-an-array");
|
||||
doc2.append(cstr!("teSymbol"), "EURUSD");
|
||||
|
||||
let mut buf = Vec::new();
|
||||
buf.extend_from_slice(doc1.as_bytes());
|
||||
buf.extend_from_slice(doc2.as_bytes());
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_buffer(
|
||||
&buf,
|
||||
"USDCAD",
|
||||
|b| bars.push(b),
|
||||
|off, e| errors.push((off, e)),
|
||||
);
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(errors.is_empty(), "unexpected errors: {errors:?}");
|
||||
assert_eq!(stats.docs_in, 2);
|
||||
assert_eq!(stats.docs_matched, 1);
|
||||
assert_eq!(stats.docs_other_symbol, 1);
|
||||
assert_eq!(stats.points_in, 1);
|
||||
assert_eq!(stats.points_decoded, 1);
|
||||
assert_eq!(bars.len(), 1);
|
||||
assert_eq!(bars[0].session_date, d1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn counts_every_doc_and_point_reject_reason_without_panicking() {
|
||||
let mut buf = Vec::new();
|
||||
|
||||
// Doc 0: MissingSymbol
|
||||
let mut d_missing_sym = RawDocumentBuf::new();
|
||||
d_missing_sym.append(cstr!("daily"), RawArrayBuf::new());
|
||||
buf.extend_from_slice(d_missing_sym.as_bytes());
|
||||
|
||||
// Doc 1: EmptySymbol
|
||||
let mut d_empty_sym = RawDocumentBuf::new();
|
||||
d_empty_sym.append(cstr!("teSymbol"), " ");
|
||||
d_empty_sym.append(cstr!("daily"), RawArrayBuf::new());
|
||||
buf.extend_from_slice(d_empty_sym.as_bytes());
|
||||
|
||||
// Doc 2: WrongSymbolType
|
||||
let mut d_wrong_sym = RawDocumentBuf::new();
|
||||
d_wrong_sym.append(cstr!("teSymbol"), 42_i32);
|
||||
buf.extend_from_slice(d_wrong_sym.as_bytes());
|
||||
|
||||
// Doc 3: MissingDaily
|
||||
let mut d_missing_daily = RawDocumentBuf::new();
|
||||
d_missing_daily.append(cstr!("teSymbol"), "USDCAD");
|
||||
buf.extend_from_slice(d_missing_daily.as_bytes());
|
||||
|
||||
// Doc 4: DailyNotArray
|
||||
let mut d_not_array = RawDocumentBuf::new();
|
||||
d_not_array.append(cstr!("teSymbol"), "USDCAD");
|
||||
d_not_array.append(cstr!("daily"), 123_i32);
|
||||
buf.extend_from_slice(d_not_array.as_bytes());
|
||||
|
||||
// Doc 5: Matched doc containing every point-level reject + 1 valid point
|
||||
let mut daily = RawArrayBuf::new();
|
||||
// [0] PointNotDocument
|
||||
daily.push("not-a-doc");
|
||||
// [1] MissingPointField (`t`)
|
||||
let mut p_no_t = RawDocumentBuf::new();
|
||||
p_no_t.append(cstr!("o"), 1.3_f64);
|
||||
p_no_t.append(cstr!("h"), 1.4_f64);
|
||||
p_no_t.append(cstr!("l"), 1.2_f64);
|
||||
p_no_t.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_no_t);
|
||||
// [2] MissingPointField (`o`)
|
||||
let mut p_no_o = RawDocumentBuf::new();
|
||||
p_no_o.append(cstr!("t"), 0_i32);
|
||||
p_no_o.append(cstr!("h"), 1.4_f64);
|
||||
p_no_o.append(cstr!("l"), 1.2_f64);
|
||||
p_no_o.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_no_o);
|
||||
// [3] WrongPointFieldType (`t` as String)
|
||||
let mut p_bad_t = RawDocumentBuf::new();
|
||||
p_bad_t.append(cstr!("t"), "2025-01-01");
|
||||
p_bad_t.append(cstr!("o"), 1.3_f64);
|
||||
p_bad_t.append(cstr!("h"), 1.4_f64);
|
||||
p_bad_t.append(cstr!("l"), 1.2_f64);
|
||||
p_bad_t.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_bad_t);
|
||||
// [4] WrongPointFieldType (`c` as Bool)
|
||||
let mut p_bad_c = RawDocumentBuf::new();
|
||||
p_bad_c.append(cstr!("t"), 0_i32);
|
||||
p_bad_c.append(cstr!("o"), 1.3_f64);
|
||||
p_bad_c.append(cstr!("h"), 1.4_f64);
|
||||
p_bad_c.append(cstr!("l"), 1.2_f64);
|
||||
p_bad_c.append(cstr!("c"), true);
|
||||
daily.push(p_bad_c);
|
||||
// [5] NonFiniteValue (`t` = NaN)
|
||||
let mut p_nan_t = RawDocumentBuf::new();
|
||||
p_nan_t.append(cstr!("t"), f64::NAN);
|
||||
p_nan_t.append(cstr!("o"), 1.3_f64);
|
||||
p_nan_t.append(cstr!("h"), 1.4_f64);
|
||||
p_nan_t.append(cstr!("l"), 1.2_f64);
|
||||
p_nan_t.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_nan_t);
|
||||
// [6] NonFiniteValue (`h` = +Inf)
|
||||
let mut p_inf_h = RawDocumentBuf::new();
|
||||
p_inf_h.append(cstr!("t"), 0_i32);
|
||||
p_inf_h.append(cstr!("o"), 1.3_f64);
|
||||
p_inf_h.append(cstr!("h"), f64::INFINITY);
|
||||
p_inf_h.append(cstr!("l"), 1.2_f64);
|
||||
p_inf_h.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_inf_h);
|
||||
// [7] NonFiniteValue (`l` = -Inf)
|
||||
let mut p_ninf_l = RawDocumentBuf::new();
|
||||
p_ninf_l.append(cstr!("t"), 0_i32);
|
||||
p_ninf_l.append(cstr!("o"), 1.3_f64);
|
||||
p_ninf_l.append(cstr!("h"), 1.4_f64);
|
||||
p_ninf_l.append(cstr!("l"), f64::NEG_INFINITY);
|
||||
p_ninf_l.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_ninf_l);
|
||||
// [8] DateOutOfRange (`i64::MIN`)
|
||||
let mut p_oor_min = RawDocumentBuf::new();
|
||||
p_oor_min.append(cstr!("t"), i64::MIN);
|
||||
p_oor_min.append(cstr!("o"), 1.3_f64);
|
||||
p_oor_min.append(cstr!("h"), 1.4_f64);
|
||||
p_oor_min.append(cstr!("l"), 1.2_f64);
|
||||
p_oor_min.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_oor_min);
|
||||
// [9] DateOutOfRange (`i64::MAX`)
|
||||
let mut p_oor_max = RawDocumentBuf::new();
|
||||
p_oor_max.append(cstr!("t"), i64::MAX);
|
||||
p_oor_max.append(cstr!("o"), 1.3_f64);
|
||||
p_oor_max.append(cstr!("h"), 1.4_f64);
|
||||
p_oor_max.append(cstr!("l"), 1.2_f64);
|
||||
p_oor_max.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_oor_max);
|
||||
// [10] DateOutOfRange (Double 1e20)
|
||||
let mut p_oor_f64 = RawDocumentBuf::new();
|
||||
p_oor_f64.append(cstr!("t"), 1e20_f64);
|
||||
p_oor_f64.append(cstr!("o"), 1.3_f64);
|
||||
p_oor_f64.append(cstr!("h"), 1.4_f64);
|
||||
p_oor_f64.append(cstr!("l"), 1.2_f64);
|
||||
p_oor_f64.append(cstr!("c"), 1.35_f64);
|
||||
daily.push(p_oor_f64);
|
||||
// [11] Valid point
|
||||
let d_ok = day(2026, 2, 14);
|
||||
let mut p_ok = RawDocumentBuf::new();
|
||||
p_ok.append(cstr!("t"), i64::from(d_ok) * MILLIS_PER_DAY);
|
||||
p_ok.append(cstr!("o"), 1.38_f64);
|
||||
p_ok.append(cstr!("h"), 1.39_f64);
|
||||
p_ok.append(cstr!("l"), 1.37_f64);
|
||||
p_ok.append(cstr!("c"), 1.385_f64);
|
||||
daily.push(p_ok);
|
||||
|
||||
let doc5 = make_te_doc("UsdCad", daily);
|
||||
buf.extend_from_slice(doc5.as_bytes());
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
let stats = decode_te_market_data_buffer(
|
||||
&buf,
|
||||
"USDCAD",
|
||||
|b| bars.push(b),
|
||||
|off, e| errors.push((off, e)),
|
||||
);
|
||||
|
||||
assert_stats_conserved(&stats);
|
||||
assert_eq!(stats.docs_in, 6);
|
||||
assert_eq!(stats.docs_matched, 1);
|
||||
assert_eq!(stats.docs_other_symbol, 0);
|
||||
assert_eq!(stats.rejected_missing_symbol, 1);
|
||||
assert_eq!(stats.rejected_empty_symbol, 1);
|
||||
assert_eq!(stats.rejected_wrong_symbol_type, 1);
|
||||
assert_eq!(stats.rejected_daily_missing, 1);
|
||||
assert_eq!(stats.rejected_daily_not_array, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 0);
|
||||
|
||||
assert_eq!(stats.points_in, 12);
|
||||
assert_eq!(stats.points_decoded, 1);
|
||||
assert_eq!(stats.rejected_point_not_document, 1);
|
||||
assert_eq!(stats.rejected_missing_field, 2);
|
||||
assert_eq!(stats.rejected_wrong_type, 2);
|
||||
assert_eq!(stats.rejected_non_finite, 3);
|
||||
assert_eq!(stats.rejected_date_out_of_range, 3);
|
||||
assert_eq!(stats.rejected_corrupt_point, 0);
|
||||
assert_eq!(bars.len(), 1);
|
||||
assert_eq!(bars[0].session_date, d_ok);
|
||||
|
||||
assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::MissingSymbol)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::EmptySymbol)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(
|
||||
e,
|
||||
BsonTeMarketDataError::WrongSymbolType {
|
||||
actual: ElementType::Int32
|
||||
}
|
||||
)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(e, BsonTeMarketDataError::MissingDaily)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(
|
||||
e,
|
||||
BsonTeMarketDataError::DailyNotArray {
|
||||
actual: ElementType::Int32
|
||||
}
|
||||
)));
|
||||
assert!(errors.iter().any(|(_, e)| matches!(
|
||||
e,
|
||||
BsonTeMarketDataError::PointNotDocument {
|
||||
point_index: 0,
|
||||
actual: ElementType::String
|
||||
}
|
||||
)));
|
||||
// Every error Display is single-line
|
||||
for (_, err) in &errors {
|
||||
let msg = err.to_string();
|
||||
assert!(!msg.contains('\n'), "multiline error display: {msg}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn corrupt_bson_bytes_and_streaming_rebase_offsets() {
|
||||
// 1. decode_te_market_data_bytes on truncated input
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_market_data_bytes(&[10, 0, 0, 0, 1], "USDCAD", |_| {}, |e| errs.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert_eq!(stats.docs_in, 1);
|
||||
assert_eq!(stats.rejected_corrupt_document, 1);
|
||||
assert!(matches!(
|
||||
errs.as_slice(),
|
||||
[BsonTeMarketDataError::TruncatedDocument { .. }]
|
||||
));
|
||||
|
||||
// 2. Streaming across tiny chunks rebases corrupt inner BSON offset accurately
|
||||
let mut good_daily = RawArrayBuf::new();
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), 0_i32);
|
||||
pt.append(cstr!("o"), 1.3_f64);
|
||||
pt.append(cstr!("h"), 1.4_f64);
|
||||
pt.append(cstr!("l"), 1.2_f64);
|
||||
pt.append(cstr!("c"), 1.35_f64);
|
||||
good_daily.push(pt);
|
||||
let doc1 = make_te_doc("USDCAD", good_daily);
|
||||
let doc1_len = doc1.as_bytes().len() as u64;
|
||||
|
||||
// Second doc: valid 4-byte length prefix (12 bytes) but invalid element type byte 0xFF
|
||||
let bad_doc: [u8; 12] = [12, 0, 0, 0, 0xFF, b'a', 0, 0, 0, 0, 0, 0];
|
||||
|
||||
let mut stream_bytes = Vec::new();
|
||||
stream_bytes.extend_from_slice(doc1.as_bytes());
|
||||
stream_bytes.extend_from_slice(&bad_doc);
|
||||
|
||||
let opts = BsonStreamOptions {
|
||||
chunk_capacity_bytes: 32,
|
||||
max_doc_bytes: 4096,
|
||||
};
|
||||
let mut bars = Vec::new();
|
||||
let mut stream_errs = Vec::new();
|
||||
let stream_stats = decode_te_market_data_stream(
|
||||
std::io::Cursor::new(&stream_bytes),
|
||||
opts,
|
||||
"USDCAD",
|
||||
|b| bars.push(b),
|
||||
|off, err| stream_errs.push((off, err)),
|
||||
)
|
||||
.expect("stream framing itself is valid");
|
||||
|
||||
assert_stats_conserved(&stream_stats);
|
||||
assert_eq!(bars.len(), 1);
|
||||
assert_eq!(stream_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(stream_errs.len(), 1);
|
||||
assert_eq!(stream_errs[0].0, doc1_len);
|
||||
match &stream_errs[0].1 {
|
||||
BsonTeMarketDataError::CorruptBson { offset, .. } => {
|
||||
assert_eq!(*offset as u64, doc1_len);
|
||||
}
|
||||
other => panic!("expected CorruptBson with rebased offset, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_corruption_after_semantic_reject_takes_precedence() {
|
||||
// 1. Point with non-finite `t` followed by corrupt element type byte on `c`.
|
||||
let mut pt = RawDocumentBuf::new();
|
||||
pt.append(cstr!("t"), f64::NAN);
|
||||
pt.append(cstr!("o"), 1.38_f64);
|
||||
pt.append(cstr!("h"), 1.39_f64);
|
||||
pt.append(cstr!("l"), 1.37_f64);
|
||||
pt.append(cstr!("c"), 1.385_f64);
|
||||
|
||||
let mut daily = RawArrayBuf::new();
|
||||
daily.push(pt);
|
||||
let doc = make_te_doc("USDCAD", daily);
|
||||
let mut bytes = doc.as_bytes().to_vec();
|
||||
let c_elem_pos = bytes
|
||||
.windows(3)
|
||||
.position(|w| w == b"\x01c\0")
|
||||
.expect("find double element 'c'");
|
||||
bytes[c_elem_pos] = 0xFF;
|
||||
|
||||
let mut bars = Vec::new();
|
||||
let mut errs = Vec::new();
|
||||
let stats = decode_te_market_data_bytes(&bytes, "USDCAD", |b| bars.push(b), |e| errs.push(e));
|
||||
assert_stats_conserved(&stats);
|
||||
assert!(bars.is_empty());
|
||||
assert_eq!(stats.points_in, 1);
|
||||
assert_eq!(stats.rejected_corrupt_point, 1);
|
||||
assert_eq!(stats.rejected_non_finite, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
errs.as_slice(),
|
||||
[BsonTeMarketDataError::CorruptPointBson { point_index: 0, .. }]
|
||||
),
|
||||
"expected CorruptPointBson to take precedence over NonFiniteValue, got {errs:?}"
|
||||
);
|
||||
|
||||
// 2. Top-level doc with empty `teSymbol` followed by corrupt element type byte on `daily`.
|
||||
let doc_empty_sym = make_te_doc("", RawArrayBuf::new());
|
||||
let mut doc_bytes = doc_empty_sym.as_bytes().to_vec();
|
||||
let daily_elem_pos = doc_bytes
|
||||
.windows(7)
|
||||
.position(|w| w == b"\x04daily\0")
|
||||
.expect("find array element 'daily'");
|
||||
doc_bytes[daily_elem_pos] = 0xFF;
|
||||
|
||||
let mut top_errs = Vec::new();
|
||||
let top_stats =
|
||||
decode_te_market_data_bytes(&doc_bytes, "USDCAD", |_| {}, |e| top_errs.push(e));
|
||||
assert_stats_conserved(&top_stats);
|
||||
assert_eq!(top_stats.rejected_corrupt_document, 1);
|
||||
assert_eq!(top_stats.rejected_empty_symbol, 0);
|
||||
assert!(
|
||||
matches!(
|
||||
top_errs.as_slice(),
|
||||
[BsonTeMarketDataError::CorruptBson { .. }]
|
||||
),
|
||||
"expected CorruptBson to take precedence over EmptySymbol, got {top_errs:?}"
|
||||
);
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
1944
tools/curate-etl/src/curate_adj.rs
Normal file
1944
tools/curate-etl/src/curate_adj.rs
Normal file
File diff suppressed because it is too large
Load diff
2312
tools/curate-etl/src/curate_adj_tests.rs
Normal file
2312
tools/curate-etl/src/curate_adj_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -386,7 +386,7 @@ where
|
|||
mapping_source,
|
||||
listing_currencies,
|
||||
)?;
|
||||
let write_stats = write_bars_1d_dataset(out_dir, &curated.rows, options)?;
|
||||
let write_stats = write_bars_1d_dataset(out_dir, curated.rows, options)?;
|
||||
Ok(CurateBars1dWriteReport {
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
|
|
|
|||
600
tools/curate-etl/src/curate_corporate_actions.rs
Normal file
600
tools/curate-etl/src/curate_corporate_actions.rs
Normal file
|
|
@ -0,0 +1,600 @@
|
|||
//! Pure, in-memory `corporate_actions` curation stage joining
|
||||
//! [`crate::corporate_actions::build_corporate_actions`],
|
||||
//! [`crate::provider_mapping::ProviderMappingTable`],
|
||||
//! [`crate::session_close::et_session_close_utc_micros`], and
|
||||
//! [`crate::parquet_corporate_actions::write_corporate_actions_dataset`] into contract
|
||||
//! [`CorporateActionsParquetRow`]s.
|
||||
//!
|
||||
//! # Contract & Point-in-Time Rules
|
||||
//! - Calls [`build_corporate_actions`] unchanged (drops `ratio == 1.0` split no-ops, `cash == 0.0`
|
||||
//! dividends, and delistings without an outcome; keeps same-key multi-dividends separate; clamps
|
||||
//! late declarations to `ex_date` with `KnownAtSource::ExDateFallback`).
|
||||
//! - Resolves each built row's `(mapping_source, key, ex_date) -> listing_id` via
|
||||
//! [`ProviderMappingTable::cursor_for`] / [`crate::provider_mapping::ProviderMappingCursor::resolve`]
|
||||
//! (one cursor per contiguous `key` run, since `build_corporate_actions` emits rows sorted by
|
||||
//! `key` then `ex_date`).
|
||||
//! - For [`CorporateActionKind::OtcDelistTransfer`] rows, Pass 6 anchors `ex_date` (and `known_at`)
|
||||
//! to `effectiveDate` (the successor's first OTC trading date), which normally falls after the
|
||||
//! outgoing listing's primary-venue `valid_to` (e.g. `SIVB.US` ends `2023-03-10`, `SIVBQ.US`
|
||||
//! starts `2023-03-28`) and may coincide with ticker reuse. `OtcDelistTransfer` therefore requires
|
||||
//! Pass 6's outgoing listing identity via [`CurateDelistingInput::from_listing_id`] (`Some(id)`):
|
||||
//! curation selects the `(mapping_source, key)` range with `valid_from <= ex_date` whose
|
||||
//! `listing_id == id` (so an unrelated occupant of `key` is never linked to the OTC successor),
|
||||
//! and any identity-less `OtcDelistTransfer` (`from_listing_id = None`) drops into
|
||||
//! `dropped_unmapped`. `successor_key` is always resolved strictly on `ex_date` to
|
||||
//! `successor_listing_id`. Unmapped outgoing keys (`dropped_unmapped`), unmapped successors
|
||||
//! (`dropped_unmapped_successor`), and successors that alias to the row's own `listing_id`
|
||||
//! (`dropped_self_successor`) are dropped—never emitted with `successor_listing_id = None` or a
|
||||
//! self-link.
|
||||
//! - Stamps `known_at_micros = et_session_close_utc_micros(known_at_date)` (`16:00:00 ET` of
|
||||
//! `known_at_date`, matching `bars_1d`'s conservative end-of-session convention because source
|
||||
//! corporate-action records carry no intraday announcement time). Dates outside
|
||||
//! `1976-01-01..=2030-12-31` drop into `dropped_known_at_out_of_range` without panicking.
|
||||
//! - Re-sorts mapped rows deterministically by all 11 columns (prefix `(listing_id, ex_date, kind)`)
|
||||
//! and resolves cross-`key` collisions:
|
||||
//! - `Split` groups on the same `(listing_id, ex_date)` with `> 1` distinct source key and `> 1`
|
||||
//! distinct `ratio` bit pattern drop the entire group (`listing_collision_dropped`).
|
||||
//! - Bitwise-identical rows from multiple source keys collapse to `max_per_key` copies
|
||||
//! (`listing_collision_collapsed`), preserving same-key multi-dividends (including equal-amount
|
||||
//! same-day regular + special dividends) while deduplicating cross-key aliases.
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::cmp::Ordering;
|
||||
use std::error::Error;
|
||||
use std::fmt;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionsStats,
|
||||
DelistingOutcomeEvent, DividendActionEvent, SplitActionEvent,
|
||||
};
|
||||
use crate::parquet_corporate_actions::{
|
||||
write_corporate_actions_dataset, CorporateActionsParquetRow, CorporateActionsWriteOptions,
|
||||
CorporateActionsWriteStats, ParquetCorporateActionsError,
|
||||
};
|
||||
use crate::provider_mapping::{MappingRange, ProviderMappingTable};
|
||||
use crate::session_close::et_session_close_utc_micros;
|
||||
|
||||
/// Accounting summary produced alongside [`CurateCorporateActionsOutput::rows`].
|
||||
///
|
||||
/// Conservation invariants:
|
||||
/// - `rows_in == builder.rows_out`
|
||||
/// - `rows_in == rows_out + dropped_unmapped + dropped_unmapped_successor + dropped_self_successor
|
||||
/// + dropped_known_at_out_of_range + listing_collision_collapsed + listing_collision_dropped`
|
||||
/// - `builder` independently satisfies all [`CorporateActionsStats`] conservation invariants.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct CurateCorporateActionsStats {
|
||||
pub builder: CorporateActionsStats,
|
||||
pub rows_in: usize,
|
||||
pub rows_out: usize,
|
||||
pub listings_out: usize,
|
||||
pub dropped_unmapped: usize,
|
||||
pub dropped_unmapped_successor: usize,
|
||||
pub dropped_self_successor: usize,
|
||||
pub dropped_known_at_out_of_range: usize,
|
||||
pub listing_collision_collapsed: usize,
|
||||
pub listing_collision_dropped: usize,
|
||||
}
|
||||
|
||||
/// Output of [`curate_corporate_actions`]: contract Parquet rows sorted deterministically with
|
||||
/// non-decreasing `(listing_id, ex_date, kind)` plus full stage and builder stats.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateCorporateActionsOutput {
|
||||
pub rows: Vec<CorporateActionsParquetRow>,
|
||||
pub stats: CurateCorporateActionsStats,
|
||||
}
|
||||
|
||||
/// Typed caller errors returned by [`curate_corporate_actions`].
|
||||
///
|
||||
/// Bad single rows (unmapped keys/successors, self-successors, out-of-range `known_at_date`, and
|
||||
/// cross-key collisions) are dropped and counted in [`CurateCorporateActionsStats`] rather than
|
||||
/// aborting the stage.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum CurateCorporateActionsError {
|
||||
/// Error propagated from [`build_corporate_actions`] (e.g. non-positive split ratio).
|
||||
CorporateAction(CorporateActionError),
|
||||
/// Caller-supplied `mapping_source` was empty or contained only whitespace.
|
||||
EmptyMappingSource,
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateCorporateActionsError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::CorporateAction(err) => write!(f, "{err}"),
|
||||
Self::EmptyMappingSource => {
|
||||
write!(f, "mapping_source must not be empty or blank")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateCorporateActionsError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::CorporateAction(err) => Some(err),
|
||||
Self::EmptyMappingSource => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CorporateActionError> for CurateCorporateActionsError {
|
||||
fn from(err: CorporateActionError) -> Self {
|
||||
Self::CorporateAction(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Combined stats returned by [`curate_and_write_corporate_actions`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct CurateCorporateActionsWriteReport {
|
||||
pub curate_stats: CurateCorporateActionsStats,
|
||||
pub write_stats: CorporateActionsWriteStats,
|
||||
}
|
||||
|
||||
/// Typed error returned by [`curate_and_write_corporate_actions`].
|
||||
#[derive(Debug)]
|
||||
pub enum CurateCorporateActionsWriteError {
|
||||
Curate(CurateCorporateActionsError),
|
||||
Parquet(ParquetCorporateActionsError),
|
||||
}
|
||||
|
||||
impl fmt::Display for CurateCorporateActionsWriteError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Curate(err) => write!(f, "corporate_actions curation failed: {err}"),
|
||||
Self::Parquet(err) => write!(f, "corporate_actions Parquet write failed: {err}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for CurateCorporateActionsWriteError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
Self::Curate(err) => Some(err),
|
||||
Self::Parquet(err) => Some(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CurateCorporateActionsError> for CurateCorporateActionsWriteError {
|
||||
fn from(err: CurateCorporateActionsError) -> Self {
|
||||
Self::Curate(err)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ParquetCorporateActionsError> for CurateCorporateActionsWriteError {
|
||||
fn from(err: ParquetCorporateActionsError) -> Self {
|
||||
Self::Parquet(err)
|
||||
}
|
||||
}
|
||||
|
||||
/// Input delisting item for [`curate_corporate_actions`], pairing a source key and
|
||||
/// [`DelistingOutcomeEvent`] with Pass 6's optional outgoing `listing_id` (`from_listing_id` in
|
||||
/// `corporate_action_continuity`).
|
||||
///
|
||||
/// Implements `From<(K, DelistingOutcomeEvent<K>)>` (with `from_listing_id = None`) for terminal
|
||||
/// delisting callers; `OtcDelistTransfer` rows require `from_listing_id = Some(id)` (via
|
||||
/// [`CurateDelistingInput::with_from_listing_id`]) so ended or reused outgoing tickers are never
|
||||
/// attached to an unrelated occupant—identity-less OTC transfers drop into `dropped_unmapped`.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct CurateDelistingInput<K = String> {
|
||||
pub key: K,
|
||||
pub event: DelistingOutcomeEvent<K>,
|
||||
pub from_listing_id: Option<i32>,
|
||||
}
|
||||
|
||||
impl<K> CurateDelistingInput<K> {
|
||||
/// Creates a delisting input without an explicit Pass 6 outgoing `listing_id`.
|
||||
#[inline]
|
||||
pub fn new(key: K, event: DelistingOutcomeEvent<K>) -> Self {
|
||||
Self {
|
||||
key,
|
||||
event,
|
||||
from_listing_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a delisting input carrying Pass 6's outgoing `from_listing_id`.
|
||||
#[inline]
|
||||
pub fn with_from_listing_id(
|
||||
key: K,
|
||||
from_listing_id: i32,
|
||||
event: DelistingOutcomeEvent<K>,
|
||||
) -> Self {
|
||||
Self {
|
||||
key,
|
||||
event,
|
||||
from_listing_id: Some(from_listing_id),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K> From<(K, DelistingOutcomeEvent<K>)> for CurateDelistingInput<K> {
|
||||
#[inline]
|
||||
fn from((key, event): (K, DelistingOutcomeEvent<K>)) -> Self {
|
||||
Self::new(key, event)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct DelistingIdentity<K> {
|
||||
key: K,
|
||||
ex_date: i32,
|
||||
kind: CorporateActionKind,
|
||||
successor_key: Option<K>,
|
||||
terminal_return_bits: Option<u64>,
|
||||
from_listing_id: Option<i32>,
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn cmp_delisting_identity<K: Ord>(a: &DelistingIdentity<K>, b: &DelistingIdentity<K>) -> Ordering {
|
||||
a.key
|
||||
.cmp(&b.key)
|
||||
.then_with(|| a.ex_date.cmp(&b.ex_date))
|
||||
.then_with(|| a.kind.cmp(&b.kind))
|
||||
.then_with(|| a.successor_key.cmp(&b.successor_key))
|
||||
.then_with(|| a.terminal_return_bits.cmp(&b.terminal_return_bits))
|
||||
.then_with(|| a.from_listing_id.cmp(&b.from_listing_id))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn resolve_for_listing_on_or_before(
|
||||
ranges: &[MappingRange],
|
||||
date: i32,
|
||||
expected_listing_id: i32,
|
||||
) -> Option<i32> {
|
||||
let end = ranges.partition_point(|r| r.valid_from <= date);
|
||||
ranges[..end]
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|r| r.listing_id == expected_listing_id)
|
||||
.map(|r| r.listing_id)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn opt_f64_bits(value: Option<f64>) -> Option<u64> {
|
||||
value.map(f64::to_bits)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn intern_currency(currency: Option<String>) -> Option<Cow<'static, str>> {
|
||||
currency.map(|c| match c.as_str() {
|
||||
"USD" => Cow::Borrowed("USD"),
|
||||
"CAD" => Cow::Borrowed("CAD"),
|
||||
_ => Cow::Owned(c),
|
||||
})
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn cmp_parquet_row(a: &CorporateActionsParquetRow, b: &CorporateActionsParquetRow) -> Ordering {
|
||||
a.listing_id
|
||||
.cmp(&b.listing_id)
|
||||
.then_with(|| a.ex_date.cmp(&b.ex_date))
|
||||
.then_with(|| a.kind.cmp(&b.kind))
|
||||
.then_with(|| a.declared_date.cmp(&b.declared_date))
|
||||
.then_with(|| opt_f64_bits(a.ratio).cmp(&opt_f64_bits(b.ratio)))
|
||||
.then_with(|| opt_f64_bits(a.cash_amount).cmp(&opt_f64_bits(b.cash_amount)))
|
||||
.then_with(|| a.currency.as_deref().cmp(&b.currency.as_deref()))
|
||||
.then_with(|| a.successor_listing_id.cmp(&b.successor_listing_id))
|
||||
.then_with(|| opt_f64_bits(a.terminal_return).cmp(&opt_f64_bits(b.terminal_return)))
|
||||
.then_with(|| a.known_at_micros.cmp(&b.known_at_micros))
|
||||
.then_with(|| a.known_at_source.cmp(&b.known_at_source))
|
||||
}
|
||||
|
||||
/// Pure `corporate_actions` curation stage: validates and builds source-keyed splits, dividends,
|
||||
/// and delisting outcomes via [`build_corporate_actions`], resolves `(mapping_source, key,
|
||||
/// ex_date) -> listing_id` (and OTC transfer `successor_key` on `ex_date`) through
|
||||
/// `provider_mapping`, stamps `known_at_micros = et_session_close_utc_micros(known_at_date)`,
|
||||
/// compacts cross-key collisions, and emits contract [`CorporateActionsParquetRow`]s sorted
|
||||
/// deterministically with non-decreasing `(listing_id, ex_date, kind)`.
|
||||
pub fn curate_corporate_actions<K, S, D, L, I>(
|
||||
splits: S,
|
||||
dividends: D,
|
||||
delistings: L,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
) -> Result<CurateCorporateActionsOutput, CurateCorporateActionsError>
|
||||
where
|
||||
K: Ord + Clone + AsRef<str>,
|
||||
S: IntoIterator<Item = (K, SplitActionEvent)>,
|
||||
D: IntoIterator<Item = (K, DividendActionEvent)>,
|
||||
L: IntoIterator<Item = I>,
|
||||
I: Into<CurateDelistingInput<K>>,
|
||||
{
|
||||
if mapping_source.trim().is_empty() {
|
||||
return Err(CurateCorporateActionsError::EmptyMappingSource);
|
||||
}
|
||||
|
||||
let delistings_iter = delistings.into_iter();
|
||||
let delistings_hint = delistings_iter.size_hint().0;
|
||||
let mut delistings_for_builder: Vec<(K, DelistingOutcomeEvent<K>)> =
|
||||
Vec::with_capacity(delistings_hint);
|
||||
let mut delisting_identities: Vec<DelistingIdentity<K>> = Vec::with_capacity(delistings_hint);
|
||||
|
||||
for raw in delistings_iter {
|
||||
let item = raw.into();
|
||||
match (&item.event.successor_key, item.event.terminal_return) {
|
||||
(Some(succ), None) => {
|
||||
delisting_identities.push(DelistingIdentity {
|
||||
key: item.key.clone(),
|
||||
ex_date: item.event.delist_date,
|
||||
kind: CorporateActionKind::OtcDelistTransfer,
|
||||
successor_key: Some(succ.clone()),
|
||||
terminal_return_bits: None,
|
||||
from_listing_id: item.from_listing_id,
|
||||
});
|
||||
}
|
||||
(None, Some(raw_return)) => {
|
||||
let norm = if raw_return == 0.0 { 0.0 } else { raw_return };
|
||||
delisting_identities.push(DelistingIdentity {
|
||||
key: item.key.clone(),
|
||||
ex_date: item.event.delist_date,
|
||||
kind: CorporateActionKind::Delisting,
|
||||
successor_key: None,
|
||||
terminal_return_bits: Some(norm.to_bits()),
|
||||
from_listing_id: item.from_listing_id,
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
delistings_for_builder.push((item.key, item.event));
|
||||
}
|
||||
|
||||
let built = build_corporate_actions(splits, dividends, delistings_for_builder)?;
|
||||
delisting_identities.sort_unstable_by(cmp_delisting_identity);
|
||||
let mut delisting_id_idx = 0usize;
|
||||
|
||||
let mut stats = CurateCorporateActionsStats {
|
||||
builder: built.stats,
|
||||
rows_in: built.rows.len(),
|
||||
..CurateCorporateActionsStats::default()
|
||||
};
|
||||
|
||||
let mut tagged: Vec<(CorporateActionsParquetRow, usize)> = Vec::with_capacity(built.rows.len());
|
||||
|
||||
let mut current_key: Option<K> = None;
|
||||
let mut key_run_id: usize = 0;
|
||||
let mut cursor = mapping.cursor_for(mapping_source, "");
|
||||
|
||||
for row in built.rows {
|
||||
let from_listing_id = match row.kind {
|
||||
CorporateActionKind::OtcDelistTransfer | CorporateActionKind::Delisting => {
|
||||
let ident = &delisting_identities[delisting_id_idx];
|
||||
debug_assert!(ident.key == row.key);
|
||||
debug_assert_eq!(ident.ex_date, row.ex_date);
|
||||
debug_assert_eq!(ident.kind, row.kind);
|
||||
debug_assert!(ident.successor_key == row.successor_key);
|
||||
debug_assert_eq!(ident.terminal_return_bits, opt_f64_bits(row.terminal_return));
|
||||
delisting_id_idx += 1;
|
||||
ident.from_listing_id
|
||||
}
|
||||
CorporateActionKind::Split | CorporateActionKind::Dividend => None,
|
||||
};
|
||||
|
||||
let key_changed = match ¤t_key {
|
||||
Some(prev) => *prev != row.key,
|
||||
None => true,
|
||||
};
|
||||
if key_changed {
|
||||
if current_key.is_some() {
|
||||
key_run_id += 1;
|
||||
}
|
||||
cursor = mapping.cursor_for(mapping_source, row.key.as_ref());
|
||||
current_key = Some(row.key);
|
||||
}
|
||||
|
||||
// Strict drop priority:
|
||||
// 1. Primary listing lookup -> dropped_unmapped.
|
||||
// For `OtcDelistTransfer`, Pass 6 anchors `ex_date` to the successor's first OTC
|
||||
// trading date (`effectiveDate`), after the outgoing listing's primary-venue mapping
|
||||
// has typically ended (e.g. SIVB.US ends 2023-03-10, SIVBQ.US starts 2023-03-28) and
|
||||
// possibly after ticker reuse. `OtcDelistTransfer` therefore requires Pass 6's
|
||||
// `from_listing_id = Some(id)` (selecting only a range with `valid_from <= ex_date`
|
||||
// matching `id`); identity-less OTC transfers (`None`) always drop into
|
||||
// `dropped_unmapped` so they can never attach to an unrelated replacement occupant.
|
||||
if cursor.ranges().is_empty() {
|
||||
stats.dropped_unmapped += 1;
|
||||
continue;
|
||||
}
|
||||
let primary_listing_id = match (row.kind, from_listing_id) {
|
||||
(CorporateActionKind::OtcDelistTransfer, Some(expected_id)) => {
|
||||
resolve_for_listing_on_or_before(cursor.ranges(), row.ex_date, expected_id)
|
||||
}
|
||||
(CorporateActionKind::OtcDelistTransfer, None) => None,
|
||||
(CorporateActionKind::Delisting, Some(expected_id)) => {
|
||||
cursor.resolve(row.ex_date).filter(|&id| id == expected_id)
|
||||
}
|
||||
_ => cursor.resolve(row.ex_date),
|
||||
};
|
||||
let Some(listing_id) = primary_listing_id else {
|
||||
stats.dropped_unmapped += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
// 2. For otc_delist_transfer, resolve successor_key on ex_date (Pass 6 effectiveDate)
|
||||
let successor_listing_id = if row.kind == CorporateActionKind::OtcDelistTransfer {
|
||||
let Some(ref succ_key) = row.successor_key else {
|
||||
stats.dropped_unmapped_successor += 1;
|
||||
continue;
|
||||
};
|
||||
let Some(succ_id) = mapping.resolve(mapping_source, succ_key.as_ref(), row.ex_date)
|
||||
else {
|
||||
stats.dropped_unmapped_successor += 1;
|
||||
continue;
|
||||
};
|
||||
if succ_id == listing_id {
|
||||
stats.dropped_self_successor += 1;
|
||||
continue;
|
||||
}
|
||||
Some(succ_id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
// 3. Convert known_at_date to 16:00:00 ET UTC microseconds
|
||||
let Ok(known_at_micros) = et_session_close_utc_micros(row.known_at_date) else {
|
||||
stats.dropped_known_at_out_of_range += 1;
|
||||
continue;
|
||||
};
|
||||
|
||||
tagged.push((
|
||||
CorporateActionsParquetRow {
|
||||
listing_id,
|
||||
ex_date: row.ex_date,
|
||||
declared_date: row.declared_date,
|
||||
kind: row.kind,
|
||||
ratio: row.ratio,
|
||||
cash_amount: row.cash_amount,
|
||||
currency: intern_currency(row.currency),
|
||||
successor_listing_id,
|
||||
terminal_return: row.terminal_return,
|
||||
known_at_micros,
|
||||
known_at_source: row.known_at_source,
|
||||
},
|
||||
key_run_id,
|
||||
));
|
||||
}
|
||||
|
||||
tagged.sort_unstable_by(|a, b| cmp_parquet_row(&a.0, &b.0).then_with(|| a.1.cmp(&b.1)));
|
||||
|
||||
let mut write_idx = 0usize;
|
||||
let mut read_idx = 0usize;
|
||||
let total_mapped = tagged.len();
|
||||
let mut last_listing_id: Option<i32> = None;
|
||||
|
||||
while read_idx < total_mapped {
|
||||
let listing_id = tagged[read_idx].0.listing_id;
|
||||
let ex_date = tagged[read_idx].0.ex_date;
|
||||
let kind = tagged[read_idx].0.kind;
|
||||
|
||||
let mut group_end = read_idx + 1;
|
||||
while group_end < total_mapped
|
||||
&& tagged[group_end].0.listing_id == listing_id
|
||||
&& tagged[group_end].0.ex_date == ex_date
|
||||
&& tagged[group_end].0.kind == kind
|
||||
{
|
||||
group_end += 1;
|
||||
}
|
||||
let group_len = group_end - read_idx;
|
||||
|
||||
// Cross-key conflicting split ratios on the same (listing_id, ex_date) drop the whole group.
|
||||
if kind == CorporateActionKind::Split && group_len > 1 {
|
||||
let first_key = tagged[read_idx].1;
|
||||
let first_ratio = opt_f64_bits(tagged[read_idx].0.ratio);
|
||||
let mut has_multi_key = false;
|
||||
let mut has_multi_ratio = false;
|
||||
for item in &tagged[read_idx + 1..group_end] {
|
||||
if item.1 != first_key {
|
||||
has_multi_key = true;
|
||||
}
|
||||
if opt_f64_bits(item.0.ratio) != first_ratio {
|
||||
has_multi_ratio = true;
|
||||
}
|
||||
if has_multi_key && has_multi_ratio {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if has_multi_key && has_multi_ratio {
|
||||
stats.listing_collision_dropped += group_len;
|
||||
read_idx = group_end;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Compact contiguous runs of bitwise-identical rows: keep `max_per_key` copies so
|
||||
// same-key multi-dividends (including equal-amount regular + special) stay separate while
|
||||
// cross-key alias duplicates collapse cleanly.
|
||||
let mut run_start = read_idx;
|
||||
while run_start < group_end {
|
||||
let mut run_end = run_start + 1;
|
||||
while run_end < group_end
|
||||
&& cmp_parquet_row(&tagged[run_start].0, &tagged[run_end].0) == Ordering::Equal
|
||||
{
|
||||
run_end += 1;
|
||||
}
|
||||
let run_len = run_end - run_start;
|
||||
|
||||
let keep_count = if run_len == 1 {
|
||||
1
|
||||
} else {
|
||||
let mut max_per_key = 0usize;
|
||||
let mut cur_key = tagged[run_start].1;
|
||||
let mut cur_count = 1usize;
|
||||
for item in &tagged[run_start + 1..run_end] {
|
||||
if item.1 == cur_key {
|
||||
cur_count += 1;
|
||||
} else {
|
||||
if cur_count > max_per_key {
|
||||
max_per_key = cur_count;
|
||||
}
|
||||
cur_key = item.1;
|
||||
cur_count = 1;
|
||||
}
|
||||
}
|
||||
if cur_count > max_per_key {
|
||||
max_per_key = cur_count;
|
||||
}
|
||||
max_per_key
|
||||
};
|
||||
|
||||
stats.listing_collision_collapsed += run_len - keep_count;
|
||||
|
||||
for offset in 0..keep_count {
|
||||
let src_idx = run_start + offset;
|
||||
if write_idx != src_idx {
|
||||
tagged.swap(write_idx, src_idx);
|
||||
}
|
||||
write_idx += 1;
|
||||
}
|
||||
|
||||
if last_listing_id != Some(listing_id) {
|
||||
stats.listings_out += 1;
|
||||
last_listing_id = Some(listing_id);
|
||||
}
|
||||
|
||||
run_start = run_end;
|
||||
}
|
||||
|
||||
read_idx = group_end;
|
||||
}
|
||||
|
||||
tagged.truncate(write_idx);
|
||||
let rows: Vec<CorporateActionsParquetRow> = tagged.into_iter().map(|(row, _)| row).collect();
|
||||
stats.rows_out = rows.len();
|
||||
|
||||
Ok(CurateCorporateActionsOutput { rows, stats })
|
||||
}
|
||||
|
||||
/// Thin end-to-end wrapper running [`curate_corporate_actions`] and publishing the resulting
|
||||
/// contract rows via [`write_corporate_actions_dataset`] to
|
||||
/// `<out_dir>/corporate_actions/part.parquet`.
|
||||
///
|
||||
/// Any [`CurateCorporateActionsError`] returns before [`write_corporate_actions_dataset`] is
|
||||
/// invoked, leaving `out_dir` untouched.
|
||||
pub fn curate_and_write_corporate_actions<P, K, S, D, L, I>(
|
||||
out_dir: P,
|
||||
splits: S,
|
||||
dividends: D,
|
||||
delistings: L,
|
||||
mapping_source: &str,
|
||||
mapping: &ProviderMappingTable,
|
||||
options: CorporateActionsWriteOptions,
|
||||
) -> Result<CurateCorporateActionsWriteReport, CurateCorporateActionsWriteError>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
K: Ord + Clone + AsRef<str>,
|
||||
S: IntoIterator<Item = (K, SplitActionEvent)>,
|
||||
D: IntoIterator<Item = (K, DividendActionEvent)>,
|
||||
L: IntoIterator<Item = I>,
|
||||
I: Into<CurateDelistingInput<K>>,
|
||||
{
|
||||
let curated = curate_corporate_actions(splits, dividends, delistings, mapping_source, mapping)?;
|
||||
let write_stats = write_corporate_actions_dataset(out_dir, &curated.rows, options)?;
|
||||
Ok(CurateCorporateActionsWriteReport {
|
||||
curate_stats: curated.stats,
|
||||
write_stats,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "curate_corporate_actions_tests.rs"]
|
||||
mod tests;
|
||||
1658
tools/curate-etl/src/curate_corporate_actions_tests.rs
Normal file
1658
tools/curate-etl/src/curate_corporate_actions_tests.rs
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -3,11 +3,19 @@
|
|||
pub mod adj;
|
||||
pub mod bars;
|
||||
pub mod bench;
|
||||
pub mod bson_ceo_shorts;
|
||||
pub mod bson_eod_prices;
|
||||
pub mod bson_qm_actions;
|
||||
pub mod bson_qm_events;
|
||||
pub mod bson_qm_prices;
|
||||
pub mod bson_stream;
|
||||
pub mod bson_te_market_data;
|
||||
pub mod cli;
|
||||
pub mod corporate_actions;
|
||||
pub mod events;
|
||||
pub mod fx;
|
||||
pub mod mongo_safety;
|
||||
pub mod mongo_stream;
|
||||
pub mod parquet_adj;
|
||||
pub mod parquet_bars;
|
||||
pub mod parquet_corporate_actions;
|
||||
|
|
@ -28,10 +36,50 @@ pub use bars::{
|
|||
build_bars_1d, Bar1dRow, Bars1dBuild, Bars1dStats, BarsError, EodDailyBar, QmRawVolume,
|
||||
VolumeMismatchSample, MAX_MISMATCH_SAMPLES,
|
||||
};
|
||||
pub use bson_ceo_shorts::{
|
||||
decode_ceo_shorts_buffer, decode_ceo_shorts_bytes, decode_ceo_shorts_doc,
|
||||
BsonCeoShortsDecodeStats, BsonCeoShortsError, CeoShortsFieldNames, DEFAULT_KEY_FIELD,
|
||||
DEFAULT_REPORT_DATE_FIELD,
|
||||
};
|
||||
pub use bson_eod_prices::{
|
||||
decode_eod_price_buffer, decode_eod_price_bytes, decode_eod_price_doc, iter_raw_bson_docs,
|
||||
BsonEodDecodeStats, BsonEodPriceError, RawBsonDocIter, RawEodDailyBar,
|
||||
};
|
||||
pub use bson_qm_actions::{
|
||||
decode_qm_dividend_buffer, decode_qm_dividend_bytes, decode_qm_dividend_doc,
|
||||
decode_qm_split_buffer, decode_qm_split_bytes, decode_qm_split_doc, BsonQmActionDecodeStats,
|
||||
BsonQmActionError, RawQmDividend, RawQmSplit, FIELD_DATE, FIELD_DECLARED, FIELD_DIVIDEND_CASH,
|
||||
FIELD_DIVIDEND_CURRENCY, FIELD_QM_SEARCH_CODE, FIELD_SPLIT_RATIO, FIELD_USD_FX_RATE,
|
||||
};
|
||||
pub use bson_qm_events::{
|
||||
decode_qm_earning_buffer, decode_qm_earning_bytes, decode_qm_earning_doc,
|
||||
decode_qm_filing_buffer, decode_qm_filing_bytes, decode_qm_filing_doc,
|
||||
BsonQmEarningsDecodeStats, BsonQmEventsError, BsonQmFilingsDecodeStats, QmEarningsFieldNames,
|
||||
QmFilingsFieldNames, RawQmEarning, RawQmFiling, DEFAULT_EARNINGS_ANNOUNCE_TIME_FIELD,
|
||||
DEFAULT_EARNINGS_KEY_FIELD, DEFAULT_EARNINGS_REPORT_DATE_FIELD, DEFAULT_FILINGS_KEY_FIELD,
|
||||
DEFAULT_FILINGS_TIMEFILED_FIELD,
|
||||
};
|
||||
pub use bson_qm_prices::{
|
||||
decode_qm_price_buffer, decode_qm_price_bytes, decode_qm_price_doc, BsonQmPriceDecodeStats,
|
||||
BsonQmPriceError, RawQmPrice, FIELD_SHARE_VOLUME,
|
||||
};
|
||||
pub use bson_stream::{
|
||||
decode_ceo_shorts_chunks, decode_ceo_shorts_stream, decode_eod_price_chunks,
|
||||
decode_eod_price_stream, decode_qm_dividend_chunks, decode_qm_dividend_stream,
|
||||
decode_qm_earnings_chunks, decode_qm_earnings_stream, decode_qm_filings_chunks,
|
||||
decode_qm_filings_stream, decode_qm_price_chunks, decode_qm_price_stream,
|
||||
decode_qm_split_chunks, decode_qm_split_stream, decode_te_market_data_chunks,
|
||||
decode_te_market_data_stream, BsonCeoShortsStreamError, BsonQmEventsStreamError,
|
||||
BsonStreamError, BsonStreamOptions, RawBsonChunk, RawBsonChunkReader,
|
||||
DEFAULT_CHUNK_CAPACITY_BYTES, DEFAULT_MAX_DOC_BYTES, MIN_BSON_DOC_BYTES,
|
||||
};
|
||||
pub use bson_te_market_data::{
|
||||
decode_te_market_data_buffer, decode_te_market_data_bytes, decode_te_market_data_doc,
|
||||
te_epoch_i64_to_session_date, BsonTeMarketDataDecodeStats, BsonTeMarketDataError, FIELD_DAILY,
|
||||
FIELD_MONTHLY, FIELD_POINT_C, FIELD_POINT_H, FIELD_POINT_L, FIELD_POINT_O, FIELD_POINT_T,
|
||||
FIELD_TE_SYMBOL, MILLIS_PER_DAY as TE_MILLIS_PER_DAY, SECONDS_PER_DAY as TE_SECONDS_PER_DAY,
|
||||
TE_EPOCH_MILLIS_THRESHOLD,
|
||||
};
|
||||
pub use corporate_actions::{
|
||||
build_corporate_actions, CorporateActionError, CorporateActionKind, CorporateActionRow,
|
||||
CorporateActionsBuild, CorporateActionsStats, DelistingOutcomeEvent, DividendActionEvent,
|
||||
|
|
@ -49,14 +97,27 @@ pub use fx::{
|
|||
build_fx_1d, fx_rate_on_or_before, Fx1dBuild, Fx1dRow, Fx1dStats, FxDailyBar, FxSource,
|
||||
FxSourceStats, FX_OVERLAP_REL_TOLERANCE, FX_PAIR_USDCAD,
|
||||
};
|
||||
pub use mongo_safety::{
|
||||
assert_read_only_mongo_uri, is_qa_mongo_target, parse_mongo_target, LocalHosts,
|
||||
MongoSafetyError, MongoScheme, MongoTarget, MongoTargetHost, ReadOnlyPolicy,
|
||||
ValidatedReadOnlyMongoUri, DEFAULT_ALLOWED_READ_USER, FORBIDDEN_ADMIN_USER, QA_MONGO_PORT,
|
||||
};
|
||||
pub use mongo_stream::{
|
||||
build_filter_document, open_read_only_mongo_from_env, open_read_only_mongo_uri,
|
||||
FilterDateValue, MongoCliOptions, MongoDateRange, MongoRawDocumentSource, MongoReadSpec,
|
||||
MongoStreamError, MongoUriSource, RawBsonCursorReader, RawDocumentSource, ReadOnlyMongoClient,
|
||||
SliceRawDocumentSource, SourceCollection, VecRawDocumentSource, DEFAULT_MONGO_BATCH_SIZE,
|
||||
DEFAULT_MONGO_URI_ENV, MAX_MONGO_BATCH_SIZE,
|
||||
};
|
||||
pub use parquet_adj::{
|
||||
adj_factors_parquet_schema, write_adj_factors_dataset, AdjFactorsParquetRow,
|
||||
AdjFactorsWriteOptions, AdjFactorsWriteStats, ParquetAdjError,
|
||||
};
|
||||
pub use parquet_bars::{
|
||||
bars_1d_parquet_schema, write_bars_1d_dataset, Bars1dParquetRow, Bars1dWriteOptions,
|
||||
Bars1dWriteStats, ParquetBarsError, RollbackFailure, DEFAULT_ROW_GROUP_ROWS,
|
||||
DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR, MIN_PARQUET_YEAR,
|
||||
bars_1d_parquet_schema, default_parallel_threads, write_bars_1d_dataset, Bars1dParquetRow,
|
||||
Bars1dWriteOptions, Bars1dWriteStats, ParquetBarsError, RollbackFailure,
|
||||
DEFAULT_ROW_GROUP_ROWS, DEFAULT_WRITE_THREADS, DEFAULT_ZSTD_LEVEL, MAX_PARQUET_YEAR,
|
||||
MIN_PARQUET_YEAR,
|
||||
};
|
||||
pub use parquet_corporate_actions::{
|
||||
corporate_actions_parquet_schema, write_corporate_actions_dataset, CorporateActionsParquetRow,
|
||||
|
|
@ -121,3 +182,71 @@ pub use curate_fx::{
|
|||
CurateFx1dStats, CurateFx1dWriteReport, CurateFxError, CurateFxWriteError,
|
||||
FX_1D_MICROS_PER_DAY, FX_1D_TS_OFFSET_MICROS_FROM_DAY_START,
|
||||
};
|
||||
|
||||
pub mod curate_adj;
|
||||
pub use curate_adj::{
|
||||
adj_factors_for_bar, curate_adj_factors, curate_adj_factors_as_of,
|
||||
curate_and_write_adj_factors, curate_and_write_adj_factors_as_of, read_adj_factors_dataset,
|
||||
read_adj_factors_dataset_as_of, AdjFactorsSnapshot, AdjPointInTimeFence, AdjSnapshotKind,
|
||||
CurateAdjError, CurateAdjFactorsOutput, CurateAdjFactorsStats, CurateAdjFactorsWriteReport,
|
||||
CurateAdjReadError, CurateAdjWriteError, ADJ_SNAPSHOT_FORMAT_VERSION,
|
||||
};
|
||||
|
||||
pub mod curate_corporate_actions;
|
||||
pub use curate_corporate_actions::{
|
||||
curate_and_write_corporate_actions, curate_corporate_actions, CurateCorporateActionsError,
|
||||
CurateCorporateActionsOutput, CurateCorporateActionsStats, CurateCorporateActionsWriteError,
|
||||
CurateCorporateActionsWriteReport, CurateDelistingInput,
|
||||
};
|
||||
|
||||
pub mod run_curate_bars;
|
||||
pub use run_curate_bars::{
|
||||
default_curate_bars_threads, format_curate_bars_report, load_listing_currencies_tsv,
|
||||
load_provider_mapping_tsv, run_curate_bars_1d, run_curate_bars_1d_with_readers,
|
||||
CurateBars1dArgs, CurateBars1dRunReport, QmVolumeRekeyStats, RunCurateBarsError,
|
||||
SplitRekeyStats, DEFAULT_CURATE_BARS_REL_TOLERANCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_adj;
|
||||
pub use run_curate_adj::{
|
||||
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
|
||||
run_curate_adj_factors_with_readers, CurateAdjFactorsArgs, CurateAdjFactorsRunReport,
|
||||
RunCurateAdjError,
|
||||
};
|
||||
|
||||
pub mod run_curate_corporate_actions;
|
||||
pub use run_curate_corporate_actions::{
|
||||
format_curate_corporate_actions_report, load_delistings_tsv, run_curate_corporate_actions,
|
||||
run_curate_corporate_actions_with_readers, CurateCorporateActionsArgs,
|
||||
CurateCorporateActionsRunReport, RunCurateCorporateActionsError,
|
||||
};
|
||||
|
||||
pub mod run_curate_fx;
|
||||
pub use run_curate_fx::{
|
||||
format_curate_fx_report, is_supported_te_symbol, run_curate_fx_1d,
|
||||
run_curate_fx_1d_with_readers, CurateFx1dArgs, CurateFx1dRunReport, RunCurateFxError,
|
||||
ALLOWED_TE_SYMBOLS, DEFAULT_TE_SYMBOL, EOD_CAD_FOREX_CODE,
|
||||
};
|
||||
|
||||
pub mod run_curate_shorts;
|
||||
pub use run_curate_shorts::{
|
||||
format_curate_shorts_report, run_curate_shorts, run_curate_shorts_with_reader,
|
||||
CurateShortsArgs, CurateShortsRunReport, RunCurateShortsError, DEFAULT_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
pub mod run_curate_events;
|
||||
pub use run_curate_events::{
|
||||
format_curate_events_report, run_curate_events, run_curate_events_with_readers,
|
||||
CurateEventsArgs, CurateEventsRunReport, RunCurateEventsError, DEFAULT_EVENTS_MAPPING_SOURCE,
|
||||
};
|
||||
|
||||
pub mod run_mongo;
|
||||
pub use run_mongo::{
|
||||
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
|
||||
run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo,
|
||||
CurateAdjFactorsMongoArgs, CurateBars1dMongoArgs, CurateCorporateActionsMongoArgs,
|
||||
CurateEventsMongoArgs, CurateFx1dMongoArgs, CurateShortsMongoArgs, RunMongoCurateError,
|
||||
};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tsv_fixture_tests;
|
||||
|
|
|
|||
|
|
@ -5,13 +5,33 @@ use std::process::ExitCode;
|
|||
|
||||
use curate_etl::bench::{
|
||||
run_adj_benchmark, run_bars_benchmark, run_bson_eod_prices_benchmark,
|
||||
run_corporate_actions_benchmark, run_curate_bars_benchmark, run_curate_events_benchmark,
|
||||
run_curate_fx_benchmark, run_curate_shorts_benchmark, run_events_benchmark, run_fx_benchmark,
|
||||
run_parquet_adj_benchmark, run_parquet_bars_benchmark, run_parquet_corporate_actions_benchmark,
|
||||
run_parquet_events_benchmark, run_parquet_fx_benchmark, run_parquet_shorts_benchmark,
|
||||
run_provider_mapping_benchmark, run_shorts_benchmark, run_split_benchmark,
|
||||
run_bson_qm_actions_benchmark, run_bson_stream_benchmark, run_corporate_actions_benchmark,
|
||||
run_curate_adj_benchmark, run_curate_adj_cmd_benchmark, run_curate_bars_benchmark,
|
||||
run_curate_bars_cmd_benchmark, run_curate_corporate_actions_benchmark,
|
||||
run_curate_corporate_actions_cmd_benchmark, run_curate_events_benchmark,
|
||||
run_curate_events_cmd_benchmark, run_curate_fx_benchmark, run_curate_fx_cmd_benchmark,
|
||||
run_curate_shorts_benchmark, run_curate_shorts_command_benchmark, run_events_benchmark,
|
||||
run_fx_benchmark, run_mongo_stream_benchmark, run_parquet_adj_benchmark,
|
||||
run_parquet_bars_benchmark,
|
||||
run_parquet_corporate_actions_benchmark, run_parquet_events_benchmark,
|
||||
run_parquet_fx_benchmark, run_parquet_shorts_benchmark, run_provider_mapping_benchmark,
|
||||
run_shorts_benchmark, run_split_benchmark,
|
||||
};
|
||||
use curate_etl::cli::{format_usage, format_usage_stderr, parse_args, CliAction};
|
||||
use curate_etl::run_curate_adj::{
|
||||
format_curate_adj_report, run_curate_adj_factors, run_curate_adj_factors_fenced,
|
||||
};
|
||||
use curate_etl::run_curate_bars::{format_curate_bars_report, run_curate_bars_1d};
|
||||
use curate_etl::run_curate_corporate_actions::{
|
||||
format_curate_corporate_actions_report, run_curate_corporate_actions,
|
||||
};
|
||||
use curate_etl::run_curate_events::{format_curate_events_report, run_curate_events};
|
||||
use curate_etl::run_curate_fx::{format_curate_fx_report, run_curate_fx_1d};
|
||||
use curate_etl::run_curate_shorts::{format_curate_shorts_report, run_curate_shorts};
|
||||
use curate_etl::run_mongo::{
|
||||
run_curate_adj_factors_mongo, run_curate_bars_1d_mongo, run_curate_corporate_actions_mongo,
|
||||
run_curate_events_mongo, run_curate_fx_1d_mongo, run_curate_shorts_mongo,
|
||||
};
|
||||
|
||||
const NAME: &str = env!("CARGO_PKG_NAME");
|
||||
const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
|
@ -28,6 +48,154 @@ fn main() -> ExitCode {
|
|||
println!("{NAME} {VERSION}");
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::CurateBars1d(curate_args)) => match run_curate_bars_1d(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_bars_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateBars1dMongo(curate_args)) => {
|
||||
match run_curate_bars_1d_mongo(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_bars_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateAdjFactors(curate_args)) => {
|
||||
match run_curate_adj_factors(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_adj_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateAdjFactorsFenced(curate_args, fence)) => {
|
||||
match run_curate_adj_factors_fenced(&curate_args, Some(fence)) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_adj_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateAdjFactorsMongo(curate_args)) => {
|
||||
match run_curate_adj_factors_mongo(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_adj_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateCorporateActions(curate_args)) => {
|
||||
match run_curate_corporate_actions(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_corporate_actions_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateCorporateActionsMongo(curate_args)) => {
|
||||
match run_curate_corporate_actions_mongo(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_corporate_actions_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateFx1d(curate_args)) => match run_curate_fx_1d(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_fx_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateFx1dMongo(curate_args)) => {
|
||||
match run_curate_fx_1d_mongo(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_fx_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateShorts(curate_args)) => match run_curate_shorts(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_shorts_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateShortsMongo(curate_args)) => {
|
||||
match run_curate_shorts_mongo(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_shorts_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::CurateEvents(curate_args)) => match run_curate_events(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_events_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
},
|
||||
Ok(CliAction::CurateEventsMongo(curate_args)) => {
|
||||
match run_curate_events_mongo(&curate_args) {
|
||||
Ok(report) => {
|
||||
println!("{}", format_curate_events_report(&report));
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(err) => {
|
||||
eprintln!("error: {err}");
|
||||
ExitCode::FAILURE
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(CliAction::BenchSplit(rows)) => {
|
||||
let report = match run_split_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -503,6 +671,118 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonQmActions(rows)) => {
|
||||
let report = run_bson_qm_actions_benchmark(rows);
|
||||
println!("curate-etl bench-bson-qm-actions");
|
||||
println!(
|
||||
" input: rows={} splits={} dividends={} bytes={}",
|
||||
report.rows, report.split_rows, report.dividend_rows, report.bytes
|
||||
);
|
||||
println!(
|
||||
" splits: decoded={} noop_ratio_one={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.split_stats.decoded,
|
||||
report.split_stats.split_noop_ratio_one,
|
||||
report.split_stats.rejected_total(),
|
||||
report.split_stats.rejected_missing_field,
|
||||
report.split_stats.rejected_empty_field,
|
||||
report.split_stats.rejected_wrong_type,
|
||||
report.split_stats.rejected_malformed_date,
|
||||
report.split_stats.rejected_invalid_number,
|
||||
report.split_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" dividends: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={})",
|
||||
report.dividend_stats.decoded,
|
||||
report.dividend_stats.rejected_total(),
|
||||
report.dividend_stats.rejected_missing_field,
|
||||
report.dividend_stats.rejected_empty_field,
|
||||
report.dividend_stats.rejected_wrong_type,
|
||||
report.dividend_stats.rejected_malformed_date,
|
||||
report.dividend_stats.rejected_invalid_number,
|
||||
report.dividend_stats.rejected_corrupt_document
|
||||
);
|
||||
println!(
|
||||
" perf: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s latency={:.2} ns/doc checksum=0x{:016x}",
|
||||
report.elapsed_ms,
|
||||
report.docs_per_sec,
|
||||
report.mb_per_sec,
|
||||
report.ns_per_doc,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchBsonStream(rows)) => {
|
||||
let report = match run_bson_stream_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: bson-stream benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-bson-stream");
|
||||
println!(" input: rows={} bytes={}", report.rows, report.bytes);
|
||||
println!(
|
||||
" decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}",
|
||||
report.stats.decoded,
|
||||
report.stats.rejected_total(),
|
||||
report.stats.rejected_missing_field,
|
||||
report.stats.rejected_empty_field,
|
||||
report.stats.rejected_wrong_type,
|
||||
report.stats.rejected_malformed_date,
|
||||
report.stats.rejected_invalid_number,
|
||||
report.stats.rejected_corrupt_document,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" buffer: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s",
|
||||
report.buffer_elapsed_ms, report.buffer_rows_per_sec, report.buffer_mib_per_sec
|
||||
);
|
||||
println!(
|
||||
" stream: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MiB/s ratio={:.3}x peak_buffer_capacity={} bytes",
|
||||
report.stream_elapsed_ms,
|
||||
report.stream_rows_per_sec,
|
||||
report.stream_mib_per_sec,
|
||||
report.stream_to_buffer_ratio,
|
||||
report.peak_buffer_capacity
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchMongoStream(rows)) => {
|
||||
let report = match run_mongo_stream_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: mongo-stream benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
println!("curate-etl bench-mongo-stream");
|
||||
println!(" input: rows={} bytes={}", report.rows, report.bytes);
|
||||
println!(
|
||||
" decode: decoded={} rejected={} (missing={} empty={} wrong_type={} malformed_date={} invalid_number={} corrupt={}) checksum=0x{:016x}",
|
||||
report.stats.decoded,
|
||||
report.stats.rejected_total(),
|
||||
report.stats.rejected_missing_field,
|
||||
report.stats.rejected_empty_field,
|
||||
report.stats.rejected_wrong_type,
|
||||
report.stats.rejected_malformed_date,
|
||||
report.stats.rejected_invalid_number,
|
||||
report.stats.rejected_corrupt_document,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" plain: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s",
|
||||
report.plain_elapsed_ms, report.plain_docs_per_sec, report.plain_mib_per_sec
|
||||
);
|
||||
println!(
|
||||
" cursor: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MiB/s ratio={:.3}x peak_pending_capacity={} bytes",
|
||||
report.cursor_elapsed_ms,
|
||||
report.cursor_docs_per_sec,
|
||||
report.cursor_mib_per_sec,
|
||||
report.cursor_to_plain_ratio,
|
||||
report.peak_pending_capacity
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBars(rows)) => {
|
||||
let report = match run_curate_bars_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -572,6 +852,104 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateBarsCmd(rows)) => {
|
||||
let report = match run_curate_bars_cmd_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-bars-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.rows > 0 {
|
||||
(report.rows_out as f64 / report.rows as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-bars-cmd");
|
||||
println!(
|
||||
" input: rows={} eod_bytes={} splits_docs={} splits_bytes={} qm_docs={} qm_bytes={} keys={}",
|
||||
report.rows,
|
||||
report.eod_bytes_read,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.qm_docs_framed,
|
||||
report.qm_bytes_read,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s unmapped_dropped={} buffered_bars={} buffered_bytes={} ({:.1} bytes/bar)",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_rows_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.bars_unmapped_source_dropped,
|
||||
report.buffered_bars,
|
||||
report.buffered_bar_bytes,
|
||||
report.bytes_per_buffered_bar
|
||||
);
|
||||
println!(
|
||||
" qm: elapsed={:.2} ms throughput={:.0} docs/s scan={:.2} MB/s attached={} unmapped={} no_eod_partner={} rejected={} checked={} within_tol={} mismatched={} (injected={}) unchecked={} samples={}",
|
||||
report.qm_decode_rekey_elapsed_ms,
|
||||
report.qm_decode_rekey_docs_per_sec,
|
||||
report.qm_input_mb_per_sec,
|
||||
report.qm_rekey.qm_attached,
|
||||
report.qm_rekey.qm_unmapped_qm,
|
||||
report.qm_rekey.qm_no_eod_partner,
|
||||
report.qm_prices_decode.rejected_total(),
|
||||
report.curate_stats.builder.volume_checked,
|
||||
report.curate_stats.builder.volume_within_tolerance,
|
||||
report.curate_stats.builder.volume_mismatched,
|
||||
report.injected_mismatches,
|
||||
report.curate_stats.builder.volume_unchecked,
|
||||
report.mismatch_samples_out
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} unmapped={} missing_curr={} ts_oor={} coll_collapsed={} coll_dropped={}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.curate_stats.dropped_unmapped,
|
||||
report.curate_stats.dropped_missing_currency,
|
||||
report.curate_stats.dropped_ts_out_of_range,
|
||||
report.curate_stats.listing_collision_collapsed,
|
||||
report.curate_stats.listing_collision_dropped
|
||||
);
|
||||
println!(
|
||||
" write_1: threads=1 elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_seq_elapsed_ms,
|
||||
report.write_seq_rows_per_sec,
|
||||
report.write_seq_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows_seq
|
||||
);
|
||||
println!(
|
||||
" write: threads={} elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s speedup={:.2}x files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.parallel_threads,
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.write_speedup,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s throughput_mb={:.2} MB/s splits_applied={} splits_coll_collapsed={} splits_unmapped_qm={} splits_no_eod_partner={} splits_noop={}",
|
||||
report.total_elapsed_ms,
|
||||
report.total_rows_per_sec,
|
||||
report.total_mb_per_sec,
|
||||
report.split_rekey.splits_applied,
|
||||
report.split_rekey.splits_collision_collapsed,
|
||||
report.split_rekey.splits_unmapped_qm,
|
||||
report.split_rekey.splits_no_eod_partner,
|
||||
report.split_rekey.splits_noop_dropped
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateShorts(rows)) => {
|
||||
let report = match run_curate_shorts_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -694,6 +1072,74 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateEventsCmd(rows)) => {
|
||||
let report = match run_curate_events_cmd_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-events-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.rows > 0 {
|
||||
(report.rows_out as f64 / report.rows as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-events-cmd");
|
||||
println!(
|
||||
" input: rows={} filings_docs={} filings_bytes={} earnings_docs={} earnings_bytes={} keys={} peak_chunk_bytes={}",
|
||||
report.rows,
|
||||
report.filings_docs_framed,
|
||||
report.filings_bytes_read,
|
||||
report.earnings_docs_framed,
|
||||
report.earnings_bytes_read,
|
||||
report.key_count,
|
||||
report.peak_chunk_bytes
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s filings_out={} filings_skipped={} earnings_out={} earnings_skipped={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_rows_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.filings_decode.rows_out,
|
||||
report.filings_decode.skipped_total(),
|
||||
report.earnings_decode.rows_out,
|
||||
report.earnings_decode.skipped_total()
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) filings_out={} earnings_out={} listings_out={} linked={} lagged_1605={} unmapped={} listing_dup={}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.filings_out,
|
||||
report.earnings_out,
|
||||
report.listings_out,
|
||||
report.curate_stats.builder.earnings_linked_to_filing,
|
||||
report.curate_stats.builder.earnings_lagged_1605,
|
||||
report.curate_stats.dropped_unmapped,
|
||||
report.curate_stats.listing_duplicate_collapsed
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s proj_30.96M={:.1}s ({:.2}m) checksum=0x{:016x}",
|
||||
report.total_elapsed_ms,
|
||||
report.total_rows_per_sec,
|
||||
report.total_extrap_full_secs,
|
||||
report.total_extrap_full_secs / 60.0,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateFx(rows)) => {
|
||||
let report = match run_curate_fx_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
|
|
@ -758,6 +1204,407 @@ fn main() -> ExitCode {
|
|||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateAdj(events)) => {
|
||||
let report = match run_curate_adj_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-adj benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-adj");
|
||||
println!(
|
||||
" input: events={} splits={} dividends={} keys={}",
|
||||
report.events, report.splits_in, report.dividends_in, report.key_count
|
||||
);
|
||||
println!(
|
||||
" builder: rows_out={} keys_out={} split_noops={} zero_div={} missing_prev_close={} currency_mismatch={} not_below_prev_close={}",
|
||||
report.stats.builder.rows_out,
|
||||
report.stats.builder.keys_out,
|
||||
report.stats.builder.split_noops_dropped,
|
||||
report.stats.builder.dividend_zero_cash_dropped,
|
||||
report.stats.builder.dividends_missing_prev_close,
|
||||
report.stats.builder.dividends_currency_mismatch,
|
||||
report.stats.builder.dividends_not_below_prev_close
|
||||
);
|
||||
println!(
|
||||
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.stage_elapsed_ms,
|
||||
report.stage_events_per_sec,
|
||||
report.stage_ns_per_event,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows,
|
||||
report.parquet_elapsed_ms,
|
||||
report.parquet_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s",
|
||||
report.total_elapsed_ms, report.total_events_per_sec
|
||||
);
|
||||
println!(
|
||||
" curate: splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} coll_collapsed={}",
|
||||
report.stats.splits_dropped_unmapped,
|
||||
report.stats.dividends_dropped_unmapped,
|
||||
report.stats.splits_collision_collapsed,
|
||||
report.stats.dividends_collision_collapsed,
|
||||
report.stats.listing_collision_collapsed
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateAdjCmd(events)) => {
|
||||
let report = match run_curate_adj_cmd_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-adj-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-adj-cmd");
|
||||
println!(
|
||||
" input: events={} splits_docs={} splits_bytes={} dividends_docs={} dividends_bytes={} bars_files={} bars_rows={} keys={}",
|
||||
report.events,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.dividends_docs_framed,
|
||||
report.dividends_bytes_read,
|
||||
report.bars_files_read,
|
||||
report.bars_rows_loaded,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" bars_load: elapsed={:.2} ms throughput={:.0} bars/s files={} rows={} listings={}",
|
||||
report.bars_load_elapsed_ms,
|
||||
report.bars_load_rows_per_sec,
|
||||
report.bars_files_read,
|
||||
report.bars_rows_loaded,
|
||||
report.bars_listings_indexed
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} events/s scan={:.2} MB/s splits_rejected={} divs_rejected={} with_prev_close={} without_prev_close={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_events_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.splits_decode.rejected_total(),
|
||||
report.dividends_decode.rejected_total(),
|
||||
report.dividends_with_prev_close,
|
||||
report.dividends_without_prev_close
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} events/s rows_out={} ({:.2}% retained) listings_out={} splits_unmapped={} divs_unmapped={} splits_coll_collapsed={} divs_coll_collapsed={} split_noops={} zero_div={} missing_prev_close={} curr_mismatch={} checksum=0x{:016x}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_events_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.curate_stats.splits_dropped_unmapped,
|
||||
report.curate_stats.dividends_dropped_unmapped,
|
||||
report.curate_stats.splits_collision_collapsed,
|
||||
report.curate_stats.dividends_collision_collapsed,
|
||||
report.curate_stats.builder.split_noops_dropped,
|
||||
report.curate_stats.builder.dividend_zero_cash_dropped,
|
||||
report.curate_stats.builder.dividends_missing_prev_close,
|
||||
report.curate_stats.builder.dividends_currency_mismatch,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s checksum=0x{:016x}",
|
||||
report.total_elapsed_ms, report.total_events_per_sec, report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateCorporateActions(events)) => {
|
||||
let report = match run_curate_corporate_actions_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-corporate-actions benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-corporate-actions");
|
||||
println!(
|
||||
" input: events={} splits={} dividends={} delistings={} keys={}",
|
||||
report.events,
|
||||
report.splits_in,
|
||||
report.dividends_in,
|
||||
report.delistings_in,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" builder: rows_out={} splits_out={} split_noops={} divs_out={} zero_div={} otc_out={} delist_out={} delist_no_outcome={}",
|
||||
report.stats.builder.rows_out,
|
||||
report.stats.builder.splits_out,
|
||||
report.stats.builder.split_noops_dropped,
|
||||
report.stats.builder.dividends_out,
|
||||
report.stats.builder.dividend_zero_cash_dropped,
|
||||
report.stats.builder.otc_delist_transfers_out,
|
||||
report.stats.builder.delistings_out,
|
||||
report.stats.builder.delist_without_outcome
|
||||
);
|
||||
println!(
|
||||
" stage: rows_out={} ({:.2}% retained) listings_out={} elapsed={:.2} ms throughput={:.0} events/s latency={:.2} ns/event checksum=0x{:016x}",
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.stage_elapsed_ms,
|
||||
report.stage_events_per_sec,
|
||||
report.stage_ns_per_event,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" parquet: files={} row_groups={} bytes={} read_back_rows={} elapsed={:.2} ms throughput={:.0} rows/s",
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows,
|
||||
report.parquet_elapsed_ms,
|
||||
report.parquet_rows_per_sec
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s",
|
||||
report.total_elapsed_ms, report.total_events_per_sec
|
||||
);
|
||||
println!(
|
||||
" curate: unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={}",
|
||||
report.stats.dropped_unmapped,
|
||||
report.stats.dropped_unmapped_successor,
|
||||
report.stats.dropped_self_successor,
|
||||
report.stats.dropped_known_at_out_of_range,
|
||||
report.stats.listing_collision_collapsed,
|
||||
report.stats.listing_collision_dropped
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateCorporateActionsCmd(events)) => {
|
||||
let report = match run_curate_corporate_actions_cmd_benchmark(events) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-corporate-actions-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.events > 0 {
|
||||
(report.rows_out as f64 / report.events as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-corporate-actions-cmd");
|
||||
println!(
|
||||
" input: events={} splits_docs={} splits_bytes={} dividends_docs={} dividends_bytes={} delistings_rows={} delistings_bytes={} keys={}",
|
||||
report.events,
|
||||
report.splits_docs_framed,
|
||||
report.splits_bytes_read,
|
||||
report.dividends_docs_framed,
|
||||
report.dividends_bytes_read,
|
||||
report.delistings_rows_loaded,
|
||||
report.delistings_bytes_read,
|
||||
report.key_count
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} events/s scan={:.2} MB/s splits_rejected={} divs_rejected={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_events_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.splits_decode.rejected_total(),
|
||||
report.dividends_decode.rejected_total()
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} events/s rows_out={} ({:.2}% retained) listings_out={} unmapped={} unmapped_succ={} self_succ={} known_at_oor={} coll_collapsed={} coll_dropped={} split_noops={} zero_div={} checksum=0x{:016x}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_events_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.curate_stats.dropped_unmapped,
|
||||
report.curate_stats.dropped_unmapped_successor,
|
||||
report.curate_stats.dropped_self_successor,
|
||||
report.curate_stats.dropped_known_at_out_of_range,
|
||||
report.curate_stats.listing_collision_collapsed,
|
||||
report.curate_stats.listing_collision_dropped,
|
||||
report.curate_stats.builder.split_noops_dropped,
|
||||
report.curate_stats.builder.dividend_zero_cash_dropped,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} events/s checksum=0x{:016x}",
|
||||
report.total_elapsed_ms, report.total_events_per_sec, report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateFxCmd(rows)) => {
|
||||
let report = match run_curate_fx_cmd_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-fx-cmd benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let b = &report.curate_stats.builder;
|
||||
println!("curate-etl bench-curate-fx-cmd");
|
||||
println!(
|
||||
" input: rows={} eod_docs={} eod_bytes={} te_docs={} te_points={} te_bytes={}",
|
||||
report.rows,
|
||||
report.eod_docs_framed,
|
||||
report.eod_bytes_read,
|
||||
report.te_docs_framed,
|
||||
report.te_decode.points_in,
|
||||
report.te_bytes_read
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s eod_kept={} eod_other={} eod_rejected={} te_matched={} te_other={} te_decoded={} te_rejected={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_rows_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.eod_cad_forex_kept,
|
||||
report.eod_other_symbol_skipped,
|
||||
report.eod_decode.rejected_total(),
|
||||
report.te_decode.docs_matched,
|
||||
report.te_decode.docs_other_symbol,
|
||||
report.te_decode.points_decoded,
|
||||
report.te_decode.rejected_total()
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} eod_out={} te_out={} te_superseded={} checksum=0x{:016x}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
b.eod_rows_out,
|
||||
b.te_rows_out,
|
||||
b.te_superseded_by_eod,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s checksum=0x{:016x}",
|
||||
report.total_elapsed_ms, report.total_rows_per_sec, report.checksum
|
||||
);
|
||||
println!(
|
||||
" overlap: checked={} within_tol={} mismatched={} max_rel={:.6}",
|
||||
b.overlap_checked,
|
||||
b.overlap_within_tolerance,
|
||||
b.overlap_mismatched,
|
||||
b.max_overlap_rel
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Ok(CliAction::BenchCurateShortsCommand(rows)) => {
|
||||
let report = match run_curate_shorts_command_benchmark(rows) {
|
||||
Ok(report) => report,
|
||||
Err(err) => {
|
||||
eprintln!("error: curate-shorts-command benchmark failed: {err}");
|
||||
return ExitCode::FAILURE;
|
||||
}
|
||||
};
|
||||
let retention_pct = if report.rows > 0 {
|
||||
(report.rows_out as f64 / report.rows as f64) * 100.0
|
||||
} else {
|
||||
0.0
|
||||
};
|
||||
println!("curate-etl bench-curate-shorts-command");
|
||||
println!(
|
||||
" input: rows={} docs_framed={} bytes_read={} keys={} peak_chunk_bytes={}",
|
||||
report.rows,
|
||||
report.docs_framed,
|
||||
report.bytes_read,
|
||||
report.key_count,
|
||||
report.peak_chunk_bytes
|
||||
);
|
||||
println!(
|
||||
" decode: elapsed={:.2} ms throughput={:.0} rows/s scan={:.2} MB/s rows_out={} skipped={} nulled_net_change={} nulled_pct_float={}",
|
||||
report.decode_elapsed_ms,
|
||||
report.decode_rows_per_sec,
|
||||
report.input_mb_per_sec,
|
||||
report.decode.rows_out,
|
||||
report.decode.skipped_total(),
|
||||
report.decode.nulled_wrong_type_net_change,
|
||||
report.decode.nulled_wrong_type_pct_float
|
||||
);
|
||||
println!(
|
||||
" curate: elapsed={:.2} ms throughput={:.0} rows/s rows_out={} ({:.2}% retained) listings_out={} dropped_unmapped={} dup_collapsed={} dup_conflict={} coll_collapsed={} coll_dropped={} invalid_shares={} checksum=0x{:016x}",
|
||||
report.curate_elapsed_ms,
|
||||
report.curate_rows_per_sec,
|
||||
report.rows_out,
|
||||
retention_pct,
|
||||
report.listings_out,
|
||||
report.curate_stats.dropped_unmapped,
|
||||
report.curate_stats.builder.duplicate_collapsed,
|
||||
report.curate_stats.builder.duplicate_conflict_dropped,
|
||||
report.curate_stats.listing_collision_collapsed,
|
||||
report.curate_stats.listing_collision_dropped,
|
||||
report.curate_stats.builder.dropped_invalid_shares_short,
|
||||
report.checksum
|
||||
);
|
||||
println!(
|
||||
" write: elapsed={:.2} ms throughput={:.0} rows/s write={:.2} MB/s files={} row_groups={} bytes={} read_back_rows={}",
|
||||
report.write_elapsed_ms,
|
||||
report.write_rows_per_sec,
|
||||
report.write_mb_per_sec,
|
||||
report.files_written,
|
||||
report.row_groups_written,
|
||||
report.bytes_written,
|
||||
report.read_back_rows
|
||||
);
|
||||
println!(
|
||||
" total: elapsed={:.2} ms throughput={:.0} rows/s peak_chunk_bytes={} checksum=0x{:016x}",
|
||||
report.total_elapsed_ms,
|
||||
report.total_rows_per_sec,
|
||||
report.peak_chunk_bytes,
|
||||
report.checksum
|
||||
);
|
||||
ExitCode::SUCCESS
|
||||
}
|
||||
Err(msg) => {
|
||||
eprintln!("error: {msg}");
|
||||
eprintln!("{}", format_usage_stderr(NAME));
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue