diff --git a/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts new file mode 100644 index 00000000..9cff62f1 --- /dev/null +++ b/libs/data/duckdb/test/analyze-signal-fundamentals-real-duckdb.test.ts @@ -0,0 +1,522 @@ +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 type { MarketDataStore } from '@stock-bot/research/market-data-store'; +import type { FundamentalsAsOfQuery } from '@stock-bot/research/market-data-store-duckdb'; +import { createAnalyzeSignalTool, createMcpServer } from '@stock-bot/research/mcp'; +import { type SignalObservation, buildForwardReturnPanel, collectBars } from '@stock-bot/research/signal-panel'; +import { analyzeSignal } from '@stock-bot/research/signal-study'; +import type { TrialLedgerExecutor } from '@stock-bot/research/trial-ledger'; +import { createNodeDuckDbExecutor, openDuckDbMarketDataStore } from '../src/index'; + +// QA end-to-end evidence for T-149: MCP `analyze_signal` (source = fundamentals) +// driven against the REAL DuckDB `fundamentalsAsOf` over Hive Parquet files. +// - Dataset ID: `synthetic:qa-analyze-signal-fundamentals-real-duckdb:seed-20261206:v1` +// - Tool version: `mcp:analyze_signal:v1`; adjustment `raw`; horizon 3 sessions; modeled costs 0 +// - Pre-Vault window 2023-03-01..2023-05-12; Vault cutoff 2023-05-15T00:00:00.000Z +// - Bars: 6 listings (101..106), 20:00 UTC closes; 5 post-cutoff bars must be fenced out. +// - Fundamentals (ttm_revenue), all 13:00 UTC: +// 2023-03-10 verified (101..105), 2023-04-05 verified Q2 (all), +// 2023-04-18 same-month restatement (101..103, verified), +// 2023-04-18 estimated-lag update (104) -> omitted by DuckDB under default lag, +// 2023-04-20 verified row with NULL ttm_revenue (105) -> must not displace 2023-04-05. +// - Baseline: direct `buildForwardReturnPanel` + `analyzeSignal` over independently listed +// expected observations. + +const VAULT_CUTOFF_TS = Date.UTC(2023, 4, 15); +const VAULT_CUTOFF_DATE = '2023-05-15'; +const PRINCIPAL = 'agent:11111111-2222-4333-8444-555555555555'; +const LISTING_IDS = [101, 102, 103, 104, 105, 106] as const; +const HORIZON = 3; +// Listing with bars but no fundamentals rows at all (sparse coverage probe). +const UNCOVERED_LISTING_ID = 107; +const BAR_LISTING_IDS = [...LISTING_IDS, UNCOVERED_LISTING_ID] as const; + +const tempDirs: string[] = []; + +afterEach(async () => { + while (tempDirs.length > 0) { + const dir = tempDirs.pop(); + if (dir !== undefined) { + await rm(dir, { recursive: true, force: true }); + } + } +}); + +function createSeededRng(seed: number): () => number { + let s = seed >>> 0; + return () => { + s = (s + 0x6d2b79f5) >>> 0; + let t = s; + t = Math.imul(t ^ (t >>> 15), t | 1); + t ^= t + Math.imul(t ^ (t >>> 7), t | 61); + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function businessDates(start: string, count: number): string[] { + const out: string[] = []; + const d = new Date(`${start}T00:00:00Z`); + while (out.length < count) { + const dow = d.getUTCDay(); + if (dow !== 0 && dow !== 6) { + out.push(d.toISOString().slice(0, 10)); + } + d.setUTCDate(d.getUTCDate() + 1); + } + return out; +} + +function ms(date: string, hour: number): number { + return Date.parse(`${date}T${String(hour).padStart(2, '0')}:00:00.000Z`); +} + +interface PitRow { + readonly listingId: number; + readonly knownAt: string; // YYYY-MM-DD + readonly hour?: number; // UTC hour, default 13 + readonly ttm: number | null; + readonly estimated?: boolean; +} + +const BASE_PIT_ROWS: readonly PitRow[] = [ + ...[101, 102, 103, 104, 105].map((lid, l) => ({ + listingId: lid, + knownAt: '2023-03-10', + ttm: 200 + ((l * 3) % 5) * 25, + })), + ...LISTING_IDS.map((lid, l) => ({ listingId: lid, knownAt: '2023-04-05', ttm: 100 + l * 40 })), + ...[101, 102, 103].map((lid, l) => ({ listingId: lid, knownAt: '2023-04-18', ttm: 400 - l * 90 })), + { listingId: 104, knownAt: '2023-04-18', ttm: 999, estimated: true }, + { listingId: 105, knownAt: '2023-04-20', ttm: null }, +]; + +function pitRowSql(r: PitRow): string { + const est = r.estimated === true ? 'TRUE' : 'FALSE'; + const ttm = r.ttm === null ? 'NULL::DOUBLE' : `${r.ttm}::DOUBLE`; + const ttmMeta = + r.ttm === null ? 'NULL::DATE, NULL::VARCHAR' : `DATE '2023-03-31', 'USD'::VARCHAR`; + const ts = `${r.knownAt} ${String(r.hour ?? 13).padStart(2, '0')}:00:00+00`; + return `(${r.listingId}::INTEGER, TIMESTAMPTZ '${ts}', 'filing_date'::VARCHAR, ${est}::BOOLEAN, + DATE '2023-03-31', 'Q1'::VARCHAR, 'USD'::VARCHAR, TIMESTAMPTZ '${ts}', + 1.0::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, NULL::DOUBLE, + ${ttmMeta}, ${ttm}, NULL::DOUBLE, NULL::DOUBLE, ${est}::BOOLEAN)`; +} + +async function writeCurated( + curatedRoot: string, + pitPartitions: Readonly> +): Promise { + const rand = createSeededRng(20261206); + const dates = businessDates('2023-03-01', 58); // 53 pre-cutoff + 5 Vault sessions + const prices = BAR_LISTING_IDS.map(() => 40); + const barValues: string[] = []; + for (const date of dates) { + for (let l = 0; l < BAR_LISTING_IDS.length; l += 1) { + const ret = (l - 2.5) * 0.002 + (rand() * 2 - 1) * 0.009; + prices[l] = Math.max(1, prices[l]! * (1 + ret)); + const close = Number(prices[l]!.toFixed(6)); + const ts = `TIMESTAMPTZ '${date} 20:00:00+00'`; + barValues.push( + `(${BAR_LISTING_IDS[l]}::INTEGER, DATE '${date}', ${ts}, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, ${close}::DOUBLE, 50000.0::DOUBLE, NULL::DOUBLE, 'USD'::VARCHAR, ${ts})` + ); + } + } + + await mkdir(join(curatedRoot, 'bars_1d', 'year=2023'), { recursive: true }); + const writer = await createNodeDuckDbExecutor(); + try { + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${barValues.join(', ')}) + AS t(listing_id, session_date, ts, open, high, low, close, volume, vwap, currency, known_at) + ) TO '${join(curatedRoot, 'bars_1d', 'year=2023', 'part.parquet')}' (FORMAT PARQUET) + `); + for (const [year, rows] of Object.entries(pitPartitions)) { + const dir = join(curatedRoot, 'fundamentals_pit', `year=${year}`); + await mkdir(dir, { recursive: true }); + await writer.run(` + COPY ( + SELECT * FROM (VALUES ${rows.map(pitRowSql).join(', ')}) AS t( + listing_id, effective_known_at, known_at_source, has_estimated_lag, + period_end, fiscal_period, currency, period_known_at, + revenue, net_income, operating_cash_flow, total_assets, total_equity, shares_outstanding, + ttm_period_end, ttm_currency, ttm_revenue, ttm_net_income, ttm_operating_cash_flow, ttm_has_estimated_lag + ) + ) TO '${join(dir, 'part.parquet')}' (FORMAT PARQUET) + `); + } + } finally { + await writer.close(); + } +} + +interface LedgerRow { + 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: number[]; +} + +// Deterministic in-memory trial_ledger port (fixed created_at, sequential ids). +function createLedger(): { executor: TrialLedgerExecutor; rows: LedgerRow[] } { + const rows: LedgerRow[] = []; + let nextId = 1; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + const p = params ?? []; + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const id = nextId++; + const row: LedgerRow = { + trial_id: String(id), + created_at: new Date(Date.UTC(2024, 0, 1, 0, 0, id)), + 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: (p[13] as readonly number[]).map(v => Math.fround(v)), + }; + rows.push(row); + return { + rows: [{ trial_id: row.trial_id, created_at: row.created_at } 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 }; +} + +async function openStore( + pitPartitions: Readonly> +): Promise<{ + store: MarketDataStore; + calls: FundamentalsAsOfQuery[]; + close: () => Promise; +}> { + const root = await mkdtemp(join(tmpdir(), 'stockbot-qa-as-fnd-')); + tempDirs.push(root); + const curatedRoot = join(root, 'curated'); + const duckTempDir = join(root, 'duckdb-tmp'); + await mkdir(duckTempDir, { recursive: true }); + await writeCurated(curatedRoot, pitPartitions); + const opened = await openDuckDbMarketDataStore({ + curatedRoot, + vaultCutoffTs: VAULT_CUTOFF_TS, + env: { + STOCK_BOT_DUCKDB_MEMORY_LIMIT: '1GB', + STOCK_BOT_DUCKDB_THREADS: '2', + STOCK_BOT_DUCKDB_TEMP_DIR: duckTempDir, + }, + }); + const calls: FundamentalsAsOfQuery[] = []; + const inner = opened.store; + const store: MarketDataStore = { + ...inner, + bars: q => inner.bars(q), + shortsAsOf: q => inner.shortsAsOf(q), + universe: q => inner.universe(q), + fundamentalsAsOf: q => { + calls.push(q); + return inner.fundamentalsAsOf(q); + }, + }; + return { store, calls, close: () => opened.close() }; +} + +async function runTool( + store: MarketDataStore, + ledger: TrialLedgerExecutor, + allowEstimatedLag?: boolean, + listingIds: readonly number[] = LISTING_IDS +): Promise<{ isError: boolean; text: string }> { + const server = createMcpServer({ + name: 'stock-bot-research', + version: '0.1.0', + tools: [ + createAnalyzeSignalTool({ + store, + ledger, + vaultContext: { vaultCutoffTs: VAULT_CUTOFF_TS }, + principalId: PRINCIPAL, + }), + ], + }); + const raw = await server.handleMessage( + JSON.stringify({ + jsonrpc: '2.0', + id: 'qa-1', + method: 'tools/call', + params: { + name: 'analyze_signal', + arguments: { + listingIds: [...listingIds], + from: '2023-03-01', + to: '2023-05-19', // straddles the Vault cutoff; must be clamped + signal: { + source: 'fundamentals', + field: 'ttm_revenue', + ...(allowEstimatedLag === undefined ? {} : { allowEstimatedLag }), + }, + horizonSessions: HORIZON, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + }, + }, + }) + ); + const parsed = JSON.parse(raw as string) as { + result: { isError?: boolean; content: { text: string }[] }; + }; + return { isError: parsed.result.isError === true, text: parsed.result.content[0]?.text ?? '' }; +} + +function expectedObservations( + includeEstimated: boolean, + rows: readonly PitRow[] = BASE_PIT_ROWS +): SignalObservation[] { + const out: SignalObservation[] = []; + for (const r of rows) { + if (r.ttm === null || (r.estimated === true && !includeEstimated)) { + continue; + } + out.push({ listingId: r.listingId, knownAt: ms(r.knownAt, r.hour ?? 13), value: r.ttm }); + } + return out; +} + +async function directBaseline( + store: MarketDataStore, + signals: SignalObservation[], + listingIds: readonly number[] = LISTING_IDS +): Promise<{ rankIc: unknown; series: number[]; sampleStart: string; sampleEnd: string }> { + const bars = await collectBars(store.bars({ + listingIds: [...listingIds], + from: '2023-03-01', + to: '2023-05-12', + timeframe: '1d', + adjustment: 'raw', + })); + const built = buildForwardReturnPanel({ + bars, + signals, + horizonSessions: HORIZON, + vaultCutoffDate: VAULT_CUTOFF_DATE, + }); + const ledger = createLedger(); + const study = await analyzeSignal(ledger.executor, { + principalId: PRINCIPAL, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'qa_direct_baseline', + params: { field: 'ttm_revenue' }, + universe: [...listingIds], + horizon: `${HORIZON}d`, + }, + panel: built.panel, + vaultCutoffDate: VAULT_CUTOFF_DATE, + }); + if (study.status !== 'ok') { + throw new Error(`baseline study not ok: ${study.status}`); + } + return { + rankIc: study.analysis.rankIc, + series: ledger.rows[0]!.daily_series, + sampleStart: study.trial.sampleStart, + sampleEnd: study.trial.sampleEnd, + }; +} + +interface OkPayload { + status: 'ok'; + signal: unknown; + analysis: { rankIc: unknown }; + trial: { sampleStart: string; sampleEnd: string; expressionHash: string }; +} + +describe('analyze_signal fundamentals over real DuckDB fundamentalsAsOf (QA)', () => { + test('default lag: same-month restatement, estimated-lag omission and null-field rows replay exactly like the verified-only baseline', async () => { + const s = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor); + expect(res.isError).toBe(false); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + expect(payload.signal).toEqual({ + source: 'fundamentals', + field: 'ttm_revenue', + allowEstimatedLag: false, + }); + + const baseline = await directBaseline(s.store, expectedObservations(false)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows).toHaveLength(1); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + expect(payload.trial.sampleStart).toBe(baseline.sampleStart); + expect(payload.trial.sampleEnd).toBe(baseline.sampleEnd); + expect(payload.trial.sampleEnd < VAULT_CUTOFF_DATE).toBe(true); + + // Every real-store read is strictly pre-Vault and forwards the lag flag verbatim. + expect(s.calls.length).toBeGreaterThan(0); + for (const call of s.calls) { + expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); + expect(call.allowEstimatedLag).toBe(false); + expect(call.fields).toEqual(['ttm_revenue']); + } + // Fan-out bound: month-end snapshots (3) + at most one probe per eligible session (53). + expect(s.calls.length).toBeLessThanOrEqual(3 + 53); + } finally { + await s.close(); + } + }); + + test('allowEstimatedLag true includes the estimated update and matches its own baseline', async () => { + const s = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor, true); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + const baseline = await directBaseline(s.store, expectedObservations(true)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + expect(s.calls.every(c => c.allowEstimatedLag === true)).toBe(true); + + const defaultLedger = createLedger(); + const defaultRes = await runTool(s.store, defaultLedger.executor); + const defaultPayload = JSON.parse(defaultRes.text) as OkPayload; + expect(defaultPayload.trial.expressionHash).not.toBe(payload.trial.expressionHash); + expect(defaultLedger.rows[0]!.daily_series).not.toEqual(ledger.rows[0]!.daily_series); + } finally { + await s.close(); + } + }); + + test('appending Vault-window and post-cutoff revisions in another Parquet partition leaves payload and ledger rows byte-identical', async () => { + const clean = await openStore({ '2023': BASE_PIT_ROWS }); + const poisoned = await openStore({ + '2023': BASE_PIT_ROWS, + '2099': [ + // Exactly at the Vault cutoff, inside the Vault, and long after. + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-15', ttm: 5_000 + lid })), + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2023-05-17', ttm: 7_000 - lid })), + ...LISTING_IDS.map(lid => ({ listingId: lid, knownAt: '2024-01-02', ttm: 9_000 + lid })), + ], + }); + try { + const cleanLedger = createLedger(); + const poisonedLedger = createLedger(); + const cleanRes = await runTool(clean.store, cleanLedger.executor); + const poisonedRes = await runTool(poisoned.store, poisonedLedger.executor); + expect(cleanRes.isError).toBe(false); + expect(poisonedRes.text).toBe(cleanRes.text); + expect(poisonedLedger.rows).toEqual(cleanLedger.rows); + expect(poisoned.calls.map(c => c.asOf)).toEqual(clean.calls.map(c => c.asOf)); + } finally { + await clean.close(); + await poisoned.close(); + } + }); + + test('a release stamped exactly at a bar close and superseded next morning is replayed at that close', async () => { + // 106 files at 2023-04-12 20:00:00Z (== bar close ts) and restates at 2023-04-13 13:00Z. + // A month-end-only read would only see the 04-13 vintage; the 04-12 close must use 50. + const rows: readonly PitRow[] = [ + ...BASE_PIT_ROWS, + { listingId: 106, knownAt: '2023-04-12', hour: 20, ttm: 50 }, + { listingId: 106, knownAt: '2023-04-13', ttm: 900 }, + ]; + const s = await openStore({ '2023': rows }); + try { + const ledger = createLedger(); + const res = await runTool(s.store, ledger.executor); + const payload = JSON.parse(res.text) as OkPayload; + expect(payload.status).toBe('ok'); + const baseline = await directBaseline(s.store, expectedObservations(false, rows)); + expect(payload.analysis.rankIc).toEqual(baseline.rankIc); + expect(ledger.rows[0]!.daily_series).toEqual(baseline.series); + // Probe at the exact close timestamp is issued (store compares effective_known_at <= asOf). + expect(s.calls.some(c => Date.parse(c.asOf) === ms('2023-04-12', 20))).toBe(true); + } finally { + await s.close(); + } + }); + + test('sparse coverage: a listing with bars but no fundamentals stays bounded and does not change the study', async () => { + // Measurement for the reviewer's non-blocking fan-out note. The uncovered listing is + // probed at each eligible session, so calls grow with sessions, not with listings. + const covered = await openStore({ '2023': BASE_PIT_ROWS }); + const sparse = await openStore({ '2023': BASE_PIT_ROWS }); + try { + const coveredLedger = createLedger(); + const sparseLedger = createLedger(); + const coveredRes = await runTool(covered.store, coveredLedger.executor); + const sparseRes = await runTool(sparse.store, sparseLedger.executor, undefined, [ + ...LISTING_IDS, + UNCOVERED_LISTING_ID, + ]); + const coveredPayload = JSON.parse(coveredRes.text) as OkPayload; + const sparsePayload = JSON.parse(sparseRes.text) as OkPayload; + expect(coveredPayload.status).toBe('ok'); + expect(sparsePayload.status).toBe('ok'); + + // No signal for 107 -> same cross-sectional series as the covered-only study. + const baseline = await directBaseline(sparse.store, expectedObservations(false), [ + ...LISTING_IDS, + UNCOVERED_LISTING_ID, + ]); + expect(sparseLedger.rows[0]!.daily_series).toEqual(baseline.series); + + // 53 eligible sessions over 3 UTC months: <= 3 month-end snapshots + 53 probes. + expect(sparse.calls.length).toBeLessThanOrEqual(3 + 53); + expect(sparse.calls.length).toBeGreaterThan(covered.calls.length); + // Each session timestamp is probed at most once. + const asOfs = sparse.calls.map(c => c.asOf); + expect(new Set(asOfs).size).toBe(asOfs.length); + for (const call of sparse.calls) { + expect(Date.parse(call.asOf)).toBeLessThan(VAULT_CUTOFF_TS); + } + } finally { + await covered.close(); + await sparse.close(); + } + }); +});