diff --git a/libs/research/test/signal-study-qa.test.ts b/libs/research/test/signal-study-qa.test.ts new file mode 100644 index 00000000..990a694e --- /dev/null +++ b/libs/research/test/signal-study-qa.test.ts @@ -0,0 +1,519 @@ +import { describe, expect, it } from 'bun:test'; +import { + analyzeSignalPanel, + eventStudy, + type EventStudyInput, + type SignalCrossSection, +} from '@stock-bot/calculations'; +import { + analyzeSignal, + canonicalExpressionHash, + runEventStudy, + SignalStudyError, + type AnalyzeSignalRequest, + type RunEventStudyRequest, + type SignalStudyErrorCode, + type TrialLedgerExecutor, +} from '@stock-bot/research'; + +// QA edge cases for T-85 study runners: window-boundary fencing, parity with the pure math, +// logged-row contents, error-code mapping and append-only accounting. + +const VAULT_CUTOFF = '2025-05-01'; +const CAMPAIGN_ID = '11111111-2222-4333-8444-555555555555'; + +interface Call { + readonly text: string; + readonly params: readonly unknown[] | undefined; +} + +interface Stored { + 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 createExecutor(opts: { readonly dsrThrows?: unknown } = {}) { + const calls: Call[] = []; + const rows: Stored[] = []; + let nextId = 500; + const executor: TrialLedgerExecutor = { + async query>(text: string, params?: readonly unknown[]) { + calls.push({ text, params }); + const trimmed = text.trimStart(); + if (trimmed.startsWith('INSERT INTO trial_ledger')) { + const p = params ?? []; + const id = ++nextId; + const row: Stored = { + trial_id: String(id), + created_at: new Date(Date.UTC(2025, 3, 2, 0, 0, id % 60)), + 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 (opts.dsrThrows !== undefined) { + throw opts.dsrThrows; + } + if (text.includes('WHERE trial_id = $1::bigint')) { + const m = rows.filter(r => r.trial_id === String(params?.[0])); + return { rows: m as unknown as Row[], rowCount: m.length }; + } + if (text.includes('WHERE universe_market = $1')) { + const m = rows.filter( + r => r.universe_market === params?.[0] && r.horizon_bucket === params?.[1] + ); + return { rows: m as unknown as Row[], rowCount: m.length }; + } + } + return { rows: [], rowCount: 0 }; + }, + }; + return { executor, calls, rows }; +} + +function rng(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 businessDates(start: string, count: number): string[] { + const out: string[] = []; + const d = new Date(`${start}T00:00:00.000Z`); + 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 signalPanel(dates: readonly string[], seed = 7, n = 15): SignalCrossSection[] { + const r = rng(seed); + const ids = Array.from({ length: n }, (_, i) => i + 1); + return dates.map((date, t) => { + const signal = new Float64Array(n); + const forwardReturn = new Float64Array(n); + const slope = 0.002 + ((t % 5) - 2) * 0.0005; + for (let i = 0; i < n; i += 1) { + const s = r() * 2 - 1; + signal[i] = s; + forwardReturn[i] = 0.0005 + slope * s + 0.015 * (r() * 2 - 1); + } + return { date, ids, signal, forwardReturn }; + }); +} + +function signalRequest(overrides: Partial = {}): AnalyzeSignalRequest { + return { + principalId: 'operator', + campaignId: CAMPAIGN_ID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'rank(ret_20d)', + params: { lookback: 20 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + panel: signalPanel(businessDates('2025-03-03', 20)), + vaultCutoffDate: VAULT_CUTOFF, + ...overrides, + }; +} + +function eventInput( + dates: readonly string[], + dayIndices: readonly number[], + seed = 13 +): EventStudyInput { + const r = rng(seed); + const entityReturns = new Map(); + for (let id = 1; id <= 4; id += 1) { + const s = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + s[t] = (r() - 0.5) * 0.02; + } + entityReturns.set(id, s); + } + const benchmarkReturns = new Float64Array(dates.length); + for (let t = 0; t < dates.length; t += 1) { + benchmarkReturns[t] = (r() - 0.5) * 0.01; + } + return { + sessionDates: dates, + entityReturns, + benchmarkReturns, + events: dayIndices.map((dayIndex, i) => ({ entityId: (i % 4) + 1, dayIndex })), + }; +} + +function eventRequest(overrides: Partial = {}): RunEventStudyRequest { + return { + principalId: 'operator', + campaignId: CAMPAIGN_ID, + universeMarket: 'US_EQ', + horizonBucket: 'swing_1_10d', + expression: { + expression: 'earnings_car', + params: { minSurprisePct: 5 }, + universe: 'US_EQ_TOP3000', + horizon: '5d', + }, + input: eventInput(businessDates('2025-01-02', 60), [12, 16, 20, 24, 28, 32]), + vaultCutoffDate: VAULT_CUTOFF, + options: { preDays: 3, postDays: 5, minEvents: 5 }, + ...overrides, + }; +} + +async function expectCode(fn: () => Promise, code: SignalStudyErrorCode) { + let caught: unknown; + try { + await fn(); + } catch (error) { + caught = error; + } + expect(caught).toBeInstanceOf(SignalStudyError); + expect((caught as SignalStudyError).code).toBe(code); + return caught as SignalStudyError; +} + +describe('runEventStudy vault window boundary', () => { + const dates = businessDates('2025-03-03', 55); + const cutoffIdx = dates.findIndex(d => d >= VAULT_CUTOFF); + + it('keeps an event whose window ends on the last pre-cutoff session and drops one ending on the cutoff', async () => { + const postDays = 5; + const lastSafe = cutoffIdx - 1 - postDays; + const firstUnsafe = cutoffIdx - postDays; + const { executor } = createExecutor(); + + const res = await runEventStudy( + executor, + eventRequest({ + input: eventInput(dates, [6, 10, 14, 18, lastSafe, firstUnsafe]), + options: { preDays: 3, postDays, minEvents: 5 }, + }) + ); + + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + expect(res.vaultExcludedEvents).toBe(1); + expect(res.study.diagnostics.eventsUsed).toBe(5); + expect(res.study.diagnostics.droppedWindowOutOfRange).toBe(0); + expect(res.trial.sampleEnd < VAULT_CUTOFF).toBe(true); + }); + + it('with postDays = 0 fences on the event date alone', async () => { + const { executor } = createExecutor(); + const res = await runEventStudy( + executor, + eventRequest({ + input: eventInput(dates, [6, 10, 14, 18, cutoffIdx - 1, cutoffIdx]), + options: { preDays: 3, postDays: 0, minEvents: 5 }, + }) + ); + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + expect(res.vaultExcludedEvents).toBe(1); + expect(res.study.diagnostics.eventsUsed).toBe(5); + }); + + it('returns insufficient_data with zero queries when the cutoff precedes every session', async () => { + const { executor, calls } = createExecutor(); + const res = await runEventStudy( + executor, + eventRequest({ + input: eventInput(dates, [6, 10, 14, 18, 22]), + vaultCutoffDate: '2025-01-01', + }) + ); + expect(res.status).toBe('insufficient_data'); + expect(res.vaultExcludedEvents).toBe(5); + expect(calls).toHaveLength(0); + }); + + it('matches eventStudy run directly on the manually truncated pre-cutoff input', async () => { + const options = { preDays: 3, postDays: 5, minEvents: 5 }; + const input = eventInput(dates, [6, 10, 14, 18, 22, cutoffIdx - 2, cutoffIdx + 3]); + const { executor, rows } = createExecutor(); + + const res = await runEventStudy(executor, eventRequest({ input, options })); + + const manualReturns = new Map(); + for (const [id, s] of input.entityReturns) { + manualReturns.set(id as number, Float64Array.from(s).subarray(0, cutoffIdx)); + } + const expected = eventStudy( + { + sessionDates: dates.slice(0, cutoffIdx), + entityReturns: manualReturns, + benchmarkReturns: Float64Array.from(input.benchmarkReturns ?? []).subarray(0, cutoffIdx), + events: input.events.slice(0, 5), + }, + options + ); + expect(res.status).toBe('ok'); + expect(expected.status).toBe('ok'); + if (res.status !== 'ok' || expected.status !== 'ok') { + return; + } + expect(res.vaultExcludedEvents).toBe(2); + expect(res.study).toEqual(expected); + expect(rows[0]?.daily_series).toEqual( + Array.from(expected.clustered.meanCars, v => Math.fround(v)) + ); + }); + + it('leaves caller Map, arrays and events untouched when the calendar is trimmed', async () => { + const input = eventInput(dates, [6, 10, 14, 18, 22, cutoffIdx + 1]); + const snapshot = { + sessionDates: [...input.sessionDates], + events: input.events.map(e => ({ ...e })), + benchmark: Array.from(input.benchmarkReturns ?? []), + entities: Array.from(input.entityReturns, ([k, v]) => [k, Array.from(v)] as const), + }; + const { executor } = createExecutor(); + + const res = await runEventStudy(executor, eventRequest({ input })); + + expect(res.status).toBe('ok'); + expect([...input.sessionDates]).toEqual(snapshot.sessionDates); + expect(input.events.map(e => ({ ...e }))).toEqual(snapshot.events); + expect(Array.from(input.benchmarkReturns ?? [])).toEqual(snapshot.benchmark); + expect(Array.from(input.entityReturns, ([k, v]) => [k, Array.from(v)] as const)).toEqual( + snapshot.entities + ); + }); +}); + +describe('runEventStudy error mapping (zero queries)', () => { + it('maps eventStudy option and return errors to typed codes', async () => { + const { executor, calls } = createExecutor(); + await expectCode( + () => runEventStudy(executor, eventRequest({ options: { preDays: -1, postDays: 5 } })), + 'invalid_option' + ); + await expectCode( + () => runEventStudy(executor, eventRequest({ options: { postDays: 2.5 } })), + 'invalid_option' + ); + + const base = eventRequest(); + const badReturns = new Map(base.input.entityReturns); + const poisoned = Float64Array.from(badReturns.get(1) ?? []); + poisoned[3] = Number.POSITIVE_INFINITY; // pre-cutoff value: must be rejected + badReturns.set(1, poisoned); + await expectCode( + () => + runEventStudy(executor, { ...base, input: { ...base.input, entityReturns: badReturns } }), + 'invalid_panel' + ); + await expectCode( + () => + runEventStudy(executor, { + ...base, + input: { ...base.input, sessionDates: ['2025-01-02', '2025-13-01'] }, + }), + 'invalid_date' + ); + await expectCode( + () => + runEventStudy(executor, { + ...base, + input: { ...base.input, events: [{ entityId: Number.NaN, dayIndex: 3 }] }, + }), + 'invalid_panel' + ); + await expectCode( + () => runEventStudy(executor, { ...base, input: null as unknown as EventStudyInput }), + 'invalid_request' + ); + expect(calls).toHaveLength(0); + }); +}); + +describe('analyzeSignal contract details', () => { + it('returns the same analysis as analyzeSignalPanel with the cutoff applied', async () => { + const dates = [...businessDates('2025-04-01', 12), '2025-05-01', '2025-05-02']; + const panel = signalPanel(dates, 21); + const options = { minCrossSection: 5, quantiles: 5 }; + const { executor } = createExecutor(); + + const res = await analyzeSignal(executor, signalRequest({ panel, options })); + + expect(res.status).toBe('ok'); + expect(res.analysis).toEqual( + analyzeSignalPanel(panel, { ...options, vaultCutoffDate: VAULT_CUTOFF }) + ); + expect(res.analysis.diagnostics.vaultExcludedDates).toBe(2); + }); + + it('writes the INSERT with request metadata, logged rank-IC series and a hash bound to the sample window', async () => { + const { executor, rows } = createExecutor(); + const req = signalRequest({ campaignId: undefined, hypothesisId: undefined }); + + const res = await analyzeSignal(executor, req); + + expect(res.status).toBe('ok'); + if (res.status !== 'ok') { + return; + } + const row = rows[0]; + expect(row).toBeDefined(); + if (row === undefined) { + return; + } + expect(row.principal_id).toBe('operator'); + expect(row.campaign_id).toBeNull(); + expect(row.hypothesis_id).toBeNull(); + expect(row.stage).toBe('signal_ic'); + expect(row.universe_market).toBe('US_EQ'); + expect(row.horizon_bucket).toBe('swing_1_10d'); + expect(row.sample_start).toBe(res.trial.sampleStart); + expect(row.sample_end).toBe(res.trial.sampleEnd); + expect(row.n_obs).toBe(res.analysis.rankIcSeries.length); + expect(row.daily_series).toEqual(Array.from(res.analysis.rankIcSeries, v => Math.fround(v))); + expect(res.trial.expressionHash).toBe( + canonicalExpressionHash({ + ...req.expression, + sampleStart: res.trial.sampleStart, + sampleEnd: res.trial.sampleEnd, + }) + ); + expect(res.trial.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + }); + + it('changes expressionHash when the sample window changes but the expression does not', async () => { + const a = await analyzeSignal(createExecutor().executor, signalRequest()); + const b = await analyzeSignal( + createExecutor().executor, + signalRequest({ panel: signalPanel(businessDates('2025-02-03', 20)) }) + ); + expect(a.status).toBe('ok'); + expect(b.status).toBe('ok'); + if (a.status !== 'ok' || b.status !== 'ok') { + return; + } + expect(a.trial.sampleStart).not.toBe(b.trial.sampleStart); + expect(a.trial.expressionHash).not.toBe(b.trial.expressionHash); + }); + + it('appends one row per call even for identical repeated requests (no dedupe)', async () => { + const { executor, rows } = createExecutor(); + const req = signalRequest(); + const first = await analyzeSignal(executor, req); + const second = await analyzeSignal(executor, req); + expect(rows).toHaveLength(2); + expect(first.status === 'ok' && second.status === 'ok').toBe(true); + if (first.status !== 'ok' || second.status !== 'ok') { + return; + } + expect(second.trial.trialId).not.toBe(first.trial.trialId); + expect(second.deflatedSharpe.clusterSize).toBe(2); + }); + + it('forwards dsrGate so passesGate follows the requested threshold', async () => { + const low = await analyzeSignal(createExecutor().executor, signalRequest({ dsrGate: -1 })); + const high = await analyzeSignal(createExecutor().executor, signalRequest({ dsrGate: 2 })); + expect(low.status).toBe('ok'); + expect(high.status).toBe('ok'); + if (low.status !== 'ok' || high.status !== 'ok') { + return; + } + expect(low.deflatedSharpe.dsr).toBe(high.deflatedSharpe.dsr); + expect(low.deflatedSharpe.passesGate).toBe(true); + expect(high.deflatedSharpe.passesGate).toBe(false); + }); + + it('wraps a non-Error DSR read rejection as dsr_read_failed carrying trialId and raw cause', async () => { + const { executor, calls } = createExecutor({ dsrThrows: 'connection reset' }); + const err = await expectCode(() => analyzeSignal(executor, signalRequest()), 'dsr_read_failed'); + expect(err.trialId).toBe(501); + expect(err.cause).toBe('connection reset'); + expect(calls.filter(c => c.text.trimStart().startsWith('INSERT'))).toHaveLength(1); + }); + + it('returns insufficient_data with zero queries when the cutoff precedes the whole panel', async () => { + const { executor, calls } = createExecutor(); + const res = await analyzeSignal(executor, signalRequest({ vaultCutoffDate: '2025-01-01' })); + expect(res.status).toBe('insufficient_data'); + expect(res.analysis.diagnostics.vaultExcludedDates).toBe(20); + expect(calls).toHaveLength(0); + }); + + it('rejects malformed ledger metadata before any query', async () => { + const { executor, calls } = createExecutor(); + await expectCode( + () => analyzeSignal(executor, signalRequest({ campaignId: 'not-a-uuid' })), + 'invalid_request' + ); + await expectCode( + () => analyzeSignal(executor, signalRequest({ universeMarket: 'XX' as unknown as 'US_EQ' })), + 'invalid_request' + ); + await expectCode( + () => + analyzeSignal( + executor, + signalRequest({ horizonBucket: 'forever' as unknown as 'swing_1_10d' }) + ), + 'invalid_request' + ); + await expectCode( + () => analyzeSignal(executor, signalRequest({ vaultCutoffDate: '2025-5-1' })), + 'invalid_date' + ); + await expectCode( + () => analyzeSignal(executor, signalRequest({ options: { quantiles: 0 } })), + 'invalid_option' + ); + await expectCode( + () => analyzeSignal(executor, null as unknown as AnalyzeSignalRequest), + 'invalid_request' + ); + expect(calls).toHaveLength(0); + }); +});