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>(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; readonly caListingIds: ReadonlySet; 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(); 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 { 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; 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(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(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(params.slice(0, nKinds) as string[]); const idSet = new Set(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); }); });