feat(m1): complete curate-etl MongoDB driver, DuckDB MarketDataStore, Python SDK, and M1 evidence
This commit is contained in:
parent
88308e1f12
commit
d9191304fb
62 changed files with 9608 additions and 366 deletions
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();
|
||||
}
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue