diff --git a/libs/research/README.md b/libs/research/README.md index a685366d..8f0d6452 100644 --- a/libs/research/README.md +++ b/libs/research/README.md @@ -49,10 +49,11 @@ Exported from both `@stock-bot/research` and `@stock-bot/research/signal-study` | `analyzeSignal` (`ledgerSeries: 'quantile_spread'`) | `'signal_ic'` | `analysis.quantiles.spreadSeries` | `analysis.quantiles.dates` | | `runEventStudy` | `'event_study'` | `study.clustered.meanCars` | `study.clustered.dates` | -### Vault Holdout Behavior +### Vault Holdout & Cluster DSR Behavior - **`analyzeSignal`** delegates to `analyzeSignalPanel`'s exclusive `vaultCutoffDate` fence, excluding all cross-sections with `date >= vaultCutoffDate` (reported in `analysis.diagnostics.vaultExcludedDates`) so `sampleEnd < vaultCutoffDate`. Callers assembling pre-computed forward-return panels remain responsible for ensuring forward-return horizons do not consume post-cutoff prices. -- **`runEventStudy`** drops every event where `sessionDates[dayIndex] >= vaultCutoffDate` or `sessionDates[dayIndex + postDays] >= vaultCutoffDate` without mutating caller inputs, reporting the count in `vaultExcludedEvents`. +- **`runEventStudy`** validates return-array shapes against the original `sessionDates` calendar, drops every event where `sessionDates[dayIndex] >= vaultCutoffDate` or `sessionDates[dayIndex + postDays] >= vaultCutoffDate` (reported in `vaultExcludedEvents`), and passes only the pre-cutoff calendar and matching return prefixes to `eventStudy` without mutating caller inputs so held-out Vault-tail values (including non-finite returns) never leak into or fail pre-Vault studies. +- **Count-based DSR fallback:** Because `analyzeSignal` and `runEventStudy` supply `observationDatesByTrialId` only for the newly written trial and no shared session grid for historical trials in the cluster, `clusterDeflatedSharpe` skips unaligned historical correlation pairs (`pairsUsed === 0`, `pairsSkipped === clusterSize * (clusterSize - 1) / 2`) and falls back conservatively to count-based `effectiveTrials === clusterSize`. Callers needing correlation-aware `effectiveTrials` across historical trials should invoke `clusterDeflatedSharpe` directly with a trusted `sessionDates` calendar or per-trial `observationDatesByTrialId`. ### `SignalStudyError` Codes diff --git a/libs/research/src/signal-study.ts b/libs/research/src/signal-study.ts index 1ad26219..d59a5502 100644 --- a/libs/research/src/signal-study.ts +++ b/libs/research/src/signal-study.ts @@ -13,10 +13,12 @@ import { SignalAnalysisError, analyzeSignalPanel, eventStudy, + type EntityId, type EventStudyEvent, type EventStudyInput, type EventStudyOptions, type EventStudyResult, + type NumericSeries, type SignalAnalysisOptions, type SignalCrossSection, type SignalPanelAnalysis, @@ -156,6 +158,51 @@ const PROBE_SAMPLE_END = '2000-01-02'; const PROBE_VAULT_CUTOFF = '2000-01-03'; const PROBE_DAILY_SERIES: readonly number[] = [0, 1]; +type NumericTypedArray = + | Float64Array + | Float32Array + | Int32Array + | Uint32Array + | Int16Array + | Uint16Array + | Int8Array + | Uint8Array + | Uint8ClampedArray; + +function isNumericTypedArray(value: unknown): value is NumericTypedArray { + return ( + value instanceof Float64Array || + value instanceof Float32Array || + value instanceof Int32Array || + value instanceof Uint32Array || + value instanceof Int16Array || + value instanceof Uint16Array || + value instanceof Int8Array || + value instanceof Uint8Array || + value instanceof Uint8ClampedArray + ); +} + +function isSupportedVector(value: unknown): value is readonly unknown[] | NumericTypedArray { + return Array.isArray(value) || isNumericTypedArray(value); +} + +function sliceNumericSeries(series: NumericSeries, length: number): NumericSeries { + if (series.length === length) { + return series; + } + if (series instanceof Float64Array) { + return series.subarray(0, length); + } + if (Array.isArray(series)) { + return series.slice(0, length); + } + if (isNumericTypedArray(series)) { + return series.subarray(0, length) as unknown as NumericSeries; + } + return series; +} + interface BaseStudyRequest { readonly principalId: string; readonly campaignId?: string | null; @@ -318,6 +365,9 @@ async function persistTrialAndEvaluateDsr( } // Never retry the insert if the subsequent DSR read fails; surface trialId and cause. + // Only the newly written trial's observation dates are known here (no shared session grid + // for earlier cluster trials), so clusterDeflatedSharpe skips unaligned historical pairs + // (pairsUsed = 0) and falls back conservatively to count-based effectiveTrials = clusterSize. let deflatedSharpe: ClusterDeflatedSharpeResult; try { deflatedSharpe = await clusterDeflatedSharpe(executor, { @@ -358,7 +408,8 @@ export async function analyzeSignal( ): Promise { validateBaseRequest(executor, request, 'signal_ic'); - const ledgerSeries: SignalLedgerSeries = request.ledgerSeries ?? 'rank_ic'; + const ledgerSeries: SignalLedgerSeries = + request.ledgerSeries === undefined ? 'rank_ic' : request.ledgerSeries; if (ledgerSeries !== 'rank_ic' && ledgerSeries !== 'quantile_spread') { throw new SignalStudyError( 'invalid_option', @@ -380,6 +431,32 @@ export async function analyzeSignal( throw new SignalStudyError('empty_panel', 'request.panel must contain at least one cross-section.'); } + for (let i = 0; i < request.panel.length; i += 1) { + const slice: unknown = request.panel[i]; + if (typeof slice !== 'object' || slice === null) { + throw new SignalStudyError('invalid_panel', `panel[${i}] must be a non-null object.`); + } + const candidate = slice as Partial; + if (!isSupportedVector(candidate.ids)) { + throw new SignalStudyError( + 'invalid_panel', + `panel[${i}].ids must be an array or typed array of entity IDs.` + ); + } + if (!isSupportedVector(candidate.signal)) { + throw new SignalStudyError( + 'invalid_panel', + `panel[${i}].signal must be an array or numeric typed array.` + ); + } + if (!isSupportedVector(candidate.forwardReturn)) { + throw new SignalStudyError( + 'invalid_panel', + `panel[${i}].forwardReturn must be an array or numeric typed array.` + ); + } + } + let analysis: SignalPanelAnalysis; try { analysis = analyzeSignalPanel(request.panel, { @@ -497,7 +574,8 @@ export async function runEventStudy( throw new SignalStudyError('invalid_option', 'request.options must be a non-null object.'); } - const postDays = request.options?.postDays ?? DEFAULT_EVENT_POST_DAYS; + const postDays = + request.options?.postDays === undefined ? DEFAULT_EVENT_POST_DAYS : request.options.postDays; if (typeof postDays !== 'number' || !Number.isInteger(postDays) || postDays < 0) { throw new SignalStudyError( 'invalid_option', @@ -505,7 +583,7 @@ export async function runEventStudy( ); } - const { sessionDates, events } = request.input; + const { sessionDates, entityReturns, benchmarkReturns, events } = request.input; if (!Array.isArray(sessionDates)) { throw new SignalStudyError( 'invalid_panel', @@ -522,8 +600,10 @@ export async function runEventStudy( throw new SignalStudyError('invalid_panel', 'request.input.events must be an array.'); } - // Validate sessionDates ordering and calendar validity before vault fencing. + // Validate sessionDates ordering and calendar validity before vault fencing, and locate + // the exclusive pre-cutoff prefix boundary. let prevDate = ''; + let preCutoffLength = 0; for (let i = 0; i < sessionDates.length; i += 1) { const currentDate = assertStrictCalendarDate(sessionDates[i], `sessionDates[${i}]`); if (i > 0) { @@ -540,9 +620,86 @@ export async function runEventStudy( ); } } + if (currentDate < request.vaultCutoffDate) { + preCutoffLength += 1; + } prevDate = currentDate; } + const totalSessions = sessionDates.length; + + // Validate return series shapes against the full calendar before slicing to the pre-cutoff + // prefix so excluded Vault-tail values (e.g. non-finite returns) never leak into or break + // the pre-Vault study. + if ( + typeof entityReturns !== 'object' || + entityReturns === null || + typeof (entityReturns as { [Symbol.iterator]?: unknown })[Symbol.iterator] !== 'function' + ) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.entityReturns must be a ReadonlyMap of entityId to return series.' + ); + } + + const needsVaultTrim = preCutoffLength < totalSessions; + let fencedBenchmarkReturns: NumericSeries | undefined; + if (benchmarkReturns !== undefined) { + if (!isSupportedVector(benchmarkReturns)) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.benchmarkReturns must be an array or numeric typed array.' + ); + } + if (benchmarkReturns.length !== totalSessions) { + throw new SignalStudyError( + 'invalid_panel', + `benchmarkReturns length (${benchmarkReturns.length}) does not match sessionDates length (${totalSessions}).` + ); + } + fencedBenchmarkReturns = needsVaultTrim + ? sliceNumericSeries(benchmarkReturns, preCutoffLength) + : benchmarkReturns; + } + + const fencedEntityReturns = needsVaultTrim ? new Map() : null; + for (const entry of entityReturns) { + if (!Array.isArray(entry) || entry.length < 2) { + throw new SignalStudyError( + 'invalid_panel', + 'request.input.entityReturns entries must be [entityId, series] pairs.' + ); + } + const entityId: unknown = entry[0]; + const series: unknown = entry[1]; + const validEntityId = + typeof entityId === 'string' || (typeof entityId === 'number' && !Number.isNaN(entityId)); + if (!validEntityId) { + throw new SignalStudyError( + 'invalid_panel', + 'entityReturns key must be a string or non-NaN number.' + ); + } + if (!isSupportedVector(series)) { + throw new SignalStudyError( + 'invalid_panel', + `entityReturns[${String(entityId)}] must be an array or numeric typed array.` + ); + } + if (series.length !== totalSessions) { + throw new SignalStudyError( + 'invalid_panel', + `entityReturns[${String(entityId)}] length (${series.length}) does not match sessionDates length (${totalSessions}).` + ); + } + if (fencedEntityReturns !== null) { + fencedEntityReturns.set( + entityId, + sliceNumericSeries(series as NumericSeries, preCutoffLength) + ); + } + } + // Validate each event and fence out any event touching or extending into the Vault window. const fencedEvents: EventStudyEvent[] = []; let vaultExcludedEvents = 0; @@ -582,15 +739,17 @@ export async function runEventStudy( fencedEvents.push({ entityId, dayIndex }); } + const fencedSessionDates = needsVaultTrim ? sessionDates.slice(0, preCutoffLength) : sessionDates; + const fencedInput: EventStudyInput = { + sessionDates: fencedSessionDates, + entityReturns: fencedEntityReturns ?? entityReturns, + ...(fencedBenchmarkReturns !== undefined ? { benchmarkReturns: fencedBenchmarkReturns } : {}), + events: fencedEvents, + }; + let study: EventStudyResult; try { - study = eventStudy( - { - ...request.input, - events: fencedEvents, - }, - request.options - ); + study = eventStudy(fencedInput, request.options); } catch (error) { if (error instanceof EventStudyError) { throw mapEventStudyError(error); diff --git a/libs/research/test/signal-study.test.ts b/libs/research/test/signal-study.test.ts index 3daff53a..d0c2bbbb 100644 --- a/libs/research/test/signal-study.test.ts +++ b/libs/research/test/signal-study.test.ts @@ -470,6 +470,16 @@ describe('analyzeSignal', () => { ), 'invalid_option' ); + await expectStudyError( + () => + analyzeSignal( + executor, + makeSignalRequest({ + ledgerSeries: null as unknown as 'rank_ic', + }) + ), + 'invalid_option' + ); await expectStudyError( () => analyzeSignal(executor, makeSignalRequest({ dsrGate: Number.NaN })), 'invalid_option' @@ -495,9 +505,60 @@ describe('analyzeSignal', () => { 'invalid_panel' ); + // Missing or malformed cross-section vectors must throw SignalStudyError('invalid_panel'), + // never a raw TypeError, and issue zero SQL queries. + const missingForwardReturnPanel = [ + { date: '2025-03-05', ids: [1, 2, 3], signal: [1, 2, 3] }, + ] as unknown as SignalCrossSection[]; + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: missingForwardReturnPanel })), + 'invalid_panel' + ); + const nullSlicePanel = [null] as unknown as SignalCrossSection[]; + await expectStudyError( + () => analyzeSignal(executor, makeSignalRequest({ panel: nullSlicePanel })), + 'invalid_panel' + ); + expect(calls).toHaveLength(0); }); + it('supports typed-array panel vectors and falls back conservatively to count-based DSR across cluster trials', async () => { + const { executor, rows } = createInMemoryTrialExecutor(); + const dates = makeBusinessDates('2025-03-03', 12); + const typedPanel: SignalCrossSection[] = makeSignalPanel(dates, 12, 111).map(slice => ({ + date: slice.date, + ids: Int32Array.from(slice.ids as number[]), + signal: slice.signal, + forwardReturn: slice.forwardReturn, + })); + + const first = await analyzeSignal(executor, makeSignalRequest({ panel: typedPanel })); + const second = await analyzeSignal( + executor, + makeSignalRequest({ + panel: typedPanel, + expression: { + expression: 'rank(ret_10d)', + params: { lookback: 10 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + }) + ); + + expect(first.status).toBe('ok'); + expect(second.status).toBe('ok'); + if (first.status !== 'ok' || second.status !== 'ok') { + return; + } + expect(rows).toHaveLength(2); + expect(second.deflatedSharpe.clusterSize).toBe(2); + expect(second.deflatedSharpe.pairsUsed).toBe(0); + expect(second.deflatedSharpe.pairsSkipped).toBe(1); + expect(second.deflatedSharpe.effectiveTrials).toBe(2); + }); + it('does not mutate frozen caller inputs', async () => { const { executor } = createInMemoryTrialExecutor(); const dates = makeBusinessDates('2025-03-03', 10); @@ -624,6 +685,40 @@ describe('runEventStudy', () => { Array.from(res2.study.clustered.meanCars) ); expect(store1.rows[0]?.daily_series).toEqual(store2.rows[0]?.daily_series); + + // Non-finite returns (e.g. Infinity from zero prior price) in the excluded Vault tail + // must not fail the pre-Vault study or alter its outputs or ledger values. + const infiniteTailReturns = new Map(); + for (const [id, series] of baseInput.entityReturns.entries()) { + const copy = new Float64Array(series); + copy[cutoffIdx] = Number.POSITIVE_INFINITY; + copy[copy.length - 1] = Number.NEGATIVE_INFINITY; + infiniteTailReturns.set(id, copy); + } + const infiniteTailBenchmark = new Float64Array(baseInput.benchmarkReturns!); + infiniteTailBenchmark[cutoffIdx] = Number.POSITIVE_INFINITY; + const store3 = createInMemoryTrialExecutor(); + const res3 = await runEventStudy( + store3.executor, + makeEventStudyRequest({ + input: { + ...baseInput, + entityReturns: infiniteTailReturns, + benchmarkReturns: infiniteTailBenchmark, + }, + options: { preDays: 3, postDays, minEvents: 5 }, + }) + ); + expect(res3.status).toBe('ok'); + if (res3.status !== 'ok') { + return; + } + expect(res3.vaultExcludedEvents).toBe(3); + expect(res3.trial.expressionHash).toBe(res1.trial.expressionHash); + expect(Array.from(res3.study.clustered.meanCars)).toEqual( + Array.from(res1.study.clustered.meanCars) + ); + expect(store3.rows[0]?.daily_series).toEqual(store1.rows[0]?.daily_series); }); it('returns insufficient_data with zero queries for below_min_events, too_few_event_dates, and zero-variance clustered CARs', async () => { @@ -768,6 +863,16 @@ describe('runEventStudy', () => { ), 'invalid_option' ); + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + options: { postDays: null as unknown as number }, + }) + ), + 'invalid_option' + ); await expectStudyError( () => runEventStudy( @@ -782,6 +887,21 @@ describe('runEventStudy', () => { ), 'invalid_panel' ); + // Shape validation against the full calendar is preserved even when Vault dates exist. + await expectStudyError( + () => + runEventStudy( + executor, + makeEventStudyRequest({ + input: { + sessionDates: ['2025-04-29', '2025-04-30', '2025-05-01'], + entityReturns: new Map([[1, new Float64Array([0.01, 0.02])]]), + events: [], + }, + }) + ), + 'invalid_panel' + ); expect(calls).toHaveLength(0); // Frozen immutability test diff --git a/test/postgres/signal-study.test.ts b/test/postgres/signal-study.test.ts index 62b44092..96fd6474 100644 --- a/test/postgres/signal-study.test.ts +++ b/test/postgres/signal-study.test.ts @@ -179,6 +179,9 @@ describe.skipIf(!url)('signal-study runners PostgreSQL integration', () => { expect(sig2.trial.sampleEnd < VAULT_CUTOFF).toBe(true); expect(sig2.trial.expressionHash).not.toBe(sig1.trial.expressionHash); expect(sig2.deflatedSharpe.clusterSize).toBe(2); + expect(sig2.deflatedSharpe.pairsUsed).toBe(0); + expect(sig2.deflatedSharpe.pairsSkipped).toBe(1); + expect(sig2.deflatedSharpe.effectiveTrials).toBe(2); expect(Number.isFinite(sig2.deflatedSharpe.effectiveTrials)).toBe(true); const eventDates = makeBusinessDates('2025-02-03', 70); @@ -211,6 +214,9 @@ describe.skipIf(!url)('signal-study runners PostgreSQL integration', () => { expect(evtRes.vaultExcludedEvents).toBe(2); expect(evtRes.trial.sampleEnd < VAULT_CUTOFF).toBe(true); expect(evtRes.deflatedSharpe.clusterSize).toBe(3); + expect(evtRes.deflatedSharpe.pairsUsed).toBe(0); + expect(evtRes.deflatedSharpe.pairsSkipped).toBe(3); + expect(evtRes.deflatedSharpe.effectiveTrials).toBe(3); // Insufficient-data run must append 0 additional rows. const insufRes = await analyzeSignal(f.pool, {