import { describe, expect, test } from 'bun:test'; import { analyzeSignalPanel, crossSectionIc, evaluateRecencyGate, neweyWestMeanTest, SignalAnalysisError, summarizeIcSeries, type EntityId, type SignalAnalysisOptions, type SignalCrossSection, type SignalPanelAnalysis, } from '@stock-bot/calculations'; // QA reference: a deliberately naive, allocation-heavy implementation written from the // T-82 spec (not from the module under test). The optimized panel path must match it // date by date so a failure names the first diverging date and stage. function createMulberry32(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) / 4294967296; }; } interface Row { readonly id: EntityId; readonly s: number; readonly r: number; } function refCompareIds(a: EntityId, b: EntityId): number { if (typeof a === 'number' && typeof b === 'number') { return a - b; } if (typeof a === 'string' && typeof b === 'string') { return a < b ? -1 : a > b ? 1 : 0; } return typeof a === 'number' ? -1 : 1; } function refPearson(x: readonly number[], y: readonly number[]): number | null { const n = x.length; const mx = x.reduce((a, v) => a + v, 0) / n; const my = y.reduce((a, v) => a + v, 0) / n; let sxy = 0; let sxx = 0; let syy = 0; for (let i = 0; i < n; i++) { const dx = (x[i] as number) - mx; const dy = (y[i] as number) - my; sxy += dx * dy; sxx += dx * dx; syy += dy * dy; } if (sxx === 0 || syy === 0) { return null; } return sxy / Math.sqrt(sxx * syy); } function refAverageRanks(values: readonly number[]): number[] { const idx = values.map((_, i) => i).sort((a, b) => (values[a] as number) - (values[b] as number)); const ranks = new Array(values.length).fill(0); let i = 0; while (i < idx.length) { let j = i; while (j + 1 < idx.length && values[idx[j + 1] as number] === values[idx[i] as number]) { j++; } for (let k = i; k <= j; k++) { ranks[idx[k] as number] = (i + j) / 2 + 1; } i = j + 1; } return ranks; } interface RefDate { readonly date: string; readonly ic: { pearson: number; rank: number } | null; readonly buckets: number[] | null; readonly top: Set | null; readonly bottom: Set | null; } function refAnalyze( panel: readonly SignalCrossSection[], minCross: number, q: number, cutoff?: string ): RefDate[] { const out: RefDate[] = []; for (const slice of panel) { if (cutoff !== undefined && slice.date >= cutoff) { continue; } const rows: Row[] = []; for (let i = 0; i < slice.signal.length; i++) { const s = slice.signal[i] as number; const r = slice.forwardReturn[i] as number; if (Number.isFinite(s) && Number.isFinite(r)) { rows.push({ id: slice.ids[i] as EntityId, s, r }); } } rows.sort((a, b) => (a.s !== b.s ? a.s - b.s : refCompareIds(a.id, b.id))); const m = rows.length; let ic: RefDate['ic'] = null; if (m >= minCross) { const xs = rows.map(row => row.s); const ys = rows.map(row => row.r); const p = refPearson(xs, ys); const rk = p === null ? null : refPearson(refAverageRanks(xs), refAverageRanks(ys)); ic = p === null || rk === null ? null : { pearson: p, rank: rk }; } let buckets: number[] | null = null; let top: Set | null = null; let bottom: Set | null = null; if (m >= q) { buckets = []; for (let b = 0; b < q; b++) { const members = rows.slice(Math.floor((b * m) / q), Math.floor(((b + 1) * m) / q)); buckets.push(members.reduce((a, row) => a + row.r, 0) / members.length); if (b === 0) { bottom = new Set(members.map(row => row.id)); } if (b === q - 1) { top = new Set(members.map(row => row.id)); } } } out.push({ date: slice.date, ic, buckets, top, bottom }); } return out; } function turnoverOf(curr: Set, prev: Set): number { let overlap = 0; for (const id of curr) { if (prev.has(id)) { overlap++; } } return 1 - overlap / curr.size; } function compareToReference( panel: readonly SignalCrossSection[], options: SignalAnalysisOptions, res: SignalPanelAnalysis ): void { const ref = refAnalyze( panel, options.minCrossSection ?? 5, options.quantiles ?? 5, options.vaultCutoffDate ); const refIc = ref.filter(d => d.ic !== null); expect(res.dates).toEqual(refIc.map(d => d.date)); refIc.forEach((d, i) => { const ic = d.ic as { pearson: number; rank: number }; const label = `${d.date} IC`; expect([label, Math.abs((res.pearsonIcSeries[i] as number) - ic.pearson) < 1e-12]).toEqual([ label, true, ]); expect([label, Math.abs((res.rankIcSeries[i] as number) - ic.rank) < 1e-12]).toEqual([ label, true, ]); }); const refQ = ref.filter(d => d.buckets !== null); expect(res.quantiles.dates).toEqual(refQ.map(d => d.date)); refQ.forEach((d, i) => { const buckets = d.buckets as number[]; buckets.forEach((value, b) => { const label = `${d.date} bucket ${b}`; const actual = (res.quantiles.perBucketSeries[b] as Float64Array)[i] as number; expect([label, Math.abs(actual - value) < 1e-12]).toEqual([label, true]); }); const spread = (buckets[buckets.length - 1] as number) - (buckets[0] as number); expect(Math.abs((res.quantiles.spreadSeries[i] as number) - spread)).toBeLessThan(1e-12); }); const refTurnDates: string[] = []; for (let i = 1; i < refQ.length; i++) { const curr = refQ[i] as RefDate; const prev = refQ[i - 1] as RefDate; refTurnDates.push(curr.date); const k = i - 1; const top = turnoverOf(curr.top as Set, prev.top as Set); const bottom = turnoverOf(curr.bottom as Set, prev.bottom as Set); expect([curr.date, res.turnover.topSeries[k]]).toEqual([curr.date, top]); expect([curr.date, res.turnover.bottomSeries[k]]).toEqual([curr.date, bottom]); } expect(res.turnover.dates).toEqual(refTurnDates); } function buildRandomPanel(seed: number, nDates: number, stringIds: boolean): SignalCrossSection[] { const rnd = createMulberry32(seed); const panel: SignalCrossSection[] = []; const universe = 40; for (let t = 0; t < nDates; t++) { // Mix of tiny (skipped), uneven (m % q != 0) and normal cross-sections. const n = 2 + Math.floor(rnd() * 30); const pool = Array.from({ length: universe }, (_, i) => i); for (let i = pool.length - 1; i > 0; i--) { const j = Math.floor(rnd() * (i + 1)); [pool[i], pool[j]] = [pool[j] as number, pool[i] as number]; } const ids: EntityId[] = []; const signal: number[] = []; const forwardReturn: number[] = []; for (let i = 0; i < n; i++) { const raw = pool[i] as number; ids.push(stringIds ? `T${String(raw).padStart(3, '0')}` : raw * 1000 + 70000); // Coarse grid -> heavy ties in both signal and returns. const s = Math.round(rnd() * 6) / 2; let r = Math.round((s * 0.01 + (rnd() - 0.5) * 0.04) * 200) / 200; const u = rnd(); if (u < 0.04) { r = Number.NaN; } else if (u < 0.06) { r = Number.NEGATIVE_INFINITY; } signal.push(rnd() < 0.03 ? Number.NaN : s); forwardReturn.push(r); } // 48 sorted dates per year starting 2021 (day 1/8/15/22 of each month). const year = 2021 + Math.floor(t / 48); const month = Math.floor((t % 48) / 4) + 1; const dayOfMonth = (t % 4) * 7 + 1; const day = `${year}-${String(month).padStart(2, '0')}-${String(dayOfMonth).padStart(2, '0')}`; panel.push({ date: day, ids, signal, forwardReturn }); } return panel; } describe('signal-analysis QA: optimized panel matches a naive reference loop', () => { for (const [seed, stringIds] of [ [101, false], [202, true], [303, false], ] as const) { test(`seed ${seed} (${stringIds ? 'string' : 'numeric >= 65536'} ids, ties, NaN/Inf, uneven buckets)`, () => { const panel = buildRandomPanel(seed, 160, stringIds); const options: SignalAnalysisOptions = { minCrossSection: 6, quantiles: 4, vaultCutoffDate: '2023-09-01', }; const res = analyzeSignalPanel(panel, options); expect(res.diagnostics.vaultExcludedDates).toBeGreaterThan(0); expect(res.diagnostics.quantileSkippedDates).toBeGreaterThan(0); expect(res.rankIcSeries.length).toBeGreaterThan(30); expect(res.turnover.count).toBeGreaterThan(30); compareToReference(panel, options, res); // Per-date Pearson/rank-IC agree with the standalone crossSectionIc entry point. let k = 0; for (const slice of panel) { if (slice.date >= '2023-09-01') { break; } const single = crossSectionIc(slice.signal, slice.forwardReturn, { minCrossSection: 6 }); if (single.status === 'ok') { expect(Math.abs(single.pearsonIc - (res.pearsonIcSeries[k] as number))).toBeLessThan( 1e-12 ); expect(Math.abs(single.rankIc - (res.rankIcSeries[k] as number))).toBeLessThan(1e-12); k++; } } expect(k).toBe(res.rankIcSeries.length); // Diagnostics accounting closes. const d = res.diagnostics; expect(d.validObservations + d.droppedPairs).toBe(d.totalObservations); expect(d.icValidDates + d.icSkippedBelowMin + d.icSkippedZeroVariance).toBe(d.eligibleDates); expect(d.quantileValidDates + d.quantileSkippedDates).toBe(d.eligibleDates); expect(d.eligibleDates + d.vaultExcludedDates).toBe(d.totalDates); expect(res.recency.pre.count + res.recency.post.count).toBe(res.rankIcSeries.length); }); } test('uneven bucket sizes (7 names, q = 5) use floor(b*m/q) boundaries and |A_t| as turnover denominator', () => { const panel: SignalCrossSection[] = [ { date: '2022-03-01', ids: [1, 2, 3, 4, 5, 6, 7], signal: [1, 2, 3, 4, 5, 6, 7], forwardReturn: [1, 2, 3, 4, 5, 6, 7], }, // Top bucket (2 names) keeps id 7 only -> 0.5; bottom (1 name) id 2 replaces id 1 -> 1. { date: '2022-03-02', ids: [1, 2, 3, 4, 5, 6, 7], signal: [3, 1, 2, 4, 7, 5, 6], forwardReturn: [1, 2, 3, 4, 5, 6, 7], }, ]; const res = analyzeSignalPanel(panel, { quantiles: 5 }); // Buckets: [0,1) [1,2) [2,4) [4,5) [5,7) expect(Array.from(res.quantiles.perBucketSeries, s => s[0])).toEqual([1, 2, 3.5, 5, 6.5]); expect(res.quantiles.spreadSeries[0]).toBe(5.5); expect(Array.from(res.turnover.topSeries)).toEqual([0.5]); expect(Array.from(res.turnover.bottomSeries)).toEqual([1]); }); test('turnover links to the previous valid quantile date across a skipped date', () => { const ids = [1, 2, 3, 4]; const panel: SignalCrossSection[] = [ { date: '2022-03-01', ids, signal: [1, 2, 3, 4], forwardReturn: [0, 0, 0, 1] }, { date: '2022-03-02', ids, signal: [1, Number.NaN, Number.NaN, Number.NaN], forwardReturn: [0, 0, 0, 0], }, { date: '2022-03-03', ids, signal: [1, 2, 3, 4], forwardReturn: [0, 0, 0, 1] }, ]; const res = analyzeSignalPanel(panel, { quantiles: 2, minCrossSection: 2 }); expect(res.quantiles.skippedDates).toBe(1); expect(res.turnover.dates).toEqual(['2022-03-03']); expect(Array.from(res.turnover.topSeries)).toEqual([0]); }); }); describe('signal-analysis QA: ids, determinism and isolation', () => { test('typed-array inputs give bit-identical results to plain arrays and inputs are not mutated', () => { const panel = buildRandomPanel(404, 40, false); const typed: SignalCrossSection[] = panel.map(slice => ({ date: slice.date, ids: Uint32Array.from(slice.ids as number[]), signal: Float64Array.from(slice.signal), forwardReturn: Float64Array.from(slice.forwardReturn), })); const snapshot = JSON.stringify( panel.map(s => [s.ids, Array.from(s.signal, String), Array.from(s.forwardReturn, String)]) ); const a = analyzeSignalPanel(panel); const b = analyzeSignalPanel(typed); const c = analyzeSignalPanel(panel); expect(b).toEqual(a); expect(c).toEqual(a); expect( JSON.stringify( panel.map(s => [s.ids, Array.from(s.signal, String), Array.from(s.forwardReturn, String)]) ) ).toBe(snapshot); }); test('duplicate ids are rejected on both the small-int fast path and the Set path, only among valid rows', () => { const base = { date: '2022-01-03', signal: [1, 2, 3, 4, 5], forwardReturn: [1, 2, 3, 4, 5] }; const cases: readonly (readonly EntityId[])[] = [ [1, 2, 3, 4, 1], [70000, 2, 3, 70000, 5], [-1, 2, 3, 4, -1], [1.5, 2, 3, 4, 1.5], ['A', 'B', 'C', 'D', 'A'], ]; for (const ids of cases) { expect(() => analyzeSignalPanel([{ ...base, ids }])).toThrow(SignalAnalysisError); try { analyzeSignalPanel([{ ...base, ids }]); } catch (err) { expect((err as SignalAnalysisError).code).toBe('DUPLICATE_ID'); } } // Same id on an invalid (dropped) row is allowed; same ids across dates are allowed. const ok = analyzeSignalPanel([ { date: '2022-01-03', ids: [1, 2, 3, 4, 5, 1], signal: [1, 2, 3, 4, 5, Number.NaN], forwardReturn: [1, 2, 3, 4, 5, 9], }, { date: '2022-01-04', ids: [1, 2, 3, 4, 5], signal: [1, 2, 3, 4, 5], forwardReturn: [1, 2, 3, 4, 5], }, ]); expect(ok.diagnostics.droppedPairs).toBe(1); // Number 1 and string '1' are distinct entities. expect(() => analyzeSignalPanel([{ ...base, ids: [1, '1', 2, 3, 4] }])).not.toThrow(); }); test('mixed numeric/string ids tie-break numbers before strings deterministically', () => { const ids: EntityId[] = ['b', 3, 'a', 1, 2, 'c']; const signal = [0, 0, 0, 0, 0, 0]; const forwardReturn = [10, 20, 30, 40, 50, 60]; // Order: 1, 2, 3, 'a', 'b', 'c' -> returns 40, 50, 20, 30, 10, 60 const res = analyzeSignalPanel([{ date: '2022-01-03', ids, signal, forwardReturn }], { quantiles: 3, }); expect(Array.from(res.quantiles.perBucketSeries, s => s[0])).toEqual([45, 25, 35]); expect(res.diagnostics.icSkippedZeroVariance).toBe(1); }); test('empty panel returns typed empty results with no NaN', () => { const res = analyzeSignalPanel([]); expect(res.rankIcSeries.length).toBe(0); expect(res.rankIc.mean).toBeNull(); expect(res.quantiles.bucketMeanReturns).toEqual([null, null, null, null, null]); expect(res.turnover.meanTopTurnover).toBeNull(); expect(res.recency.gate).toEqual({ pass: false, reason: 'empty_pre_window', ratio: null }); expect(JSON.stringify(res)).not.toContain('NaN'); }); }); describe('signal-analysis QA: Newey-West and summaries', () => { function refNeweyWest(x: readonly number[], lag: number): number { const n = x.length; const mu = x.reduce((a, v) => a + v, 0) / n; let lrv = 0; for (let l = -Math.min(lag, n - 1); l <= Math.min(lag, n - 1); l++) { let g = 0; for (let t = Math.abs(l); t < n; t++) { g += ((x[t] as number) - mu) * ((x[t - Math.abs(l)] as number) - mu); } lrv += (1 - Math.abs(l) / (lag + 1)) * (g / (n - 1)); } return mu / Math.sqrt(lrv / n); } test('matches a symmetric-sum Bartlett reference for every lag including lag >= T', () => { const rnd = createMulberry32(7); const x = Array.from({ length: 23 }, () => rnd() - 0.4); for (const lag of [0, 1, 2, 5, 22, 23, 100]) { const res = neweyWestMeanTest(x, lag); expect(res.status).toBe('ok'); if (res.status === 'ok') { expect(res.lag).toBe(lag); expect(Math.abs(res.tStat - refNeweyWest(x, lag))).toBeLessThan(1e-10); } } }); test('summary ICIR, hit rate and std follow their definitions; zero counts as a miss', () => { const s = summarizeIcSeries([0.1, 0, -0.05, 0.2], { lag: 0 }); const mean = 0.0625; const sd = Math.sqrt([0.1, 0, -0.05, 0.2].reduce((a, v) => a + (v - mean) ** 2, 0) / 3); expect(Math.abs((s.mean as number) - mean)).toBeLessThan(1e-15); expect(Math.abs((s.std as number) - sd)).toBeLessThan(1e-15); expect(Math.abs((s.icir as number) - mean / sd)).toBeLessThan(1e-12); expect(s.hitRate).toBe(0.5); const constant = summarizeIcSeries([0.03, 0.03, 0.03]); expect(constant.std).toBe(0); expect(constant.icir).toBeNull(); expect(constant.neweyWest.status).toBe('insufficient_data'); }); }); describe('signal-analysis QA: recency gate and validation edges', () => { test('custom recencySplitDate and recencyMinRatio are honoured', () => { const dates = ['2019-06-01', '2020-06-01', '2021-06-01']; const res = evaluateRecencyGate(dates, [0.1, 0.09, 0.09], { recencySplitDate: '2020-06-01', recencyMinRatio: 0.95, }); expect(res.splitDate).toBe('2020-06-01'); expect(res.pre.count).toBe(1); expect(res.post.count).toBe(2); expect(res.gate.reason).toBe('post_below_ratio_threshold'); expect( evaluateRecencyGate(dates, [0.1, 0.09, 0.09], { recencySplitDate: '2020-06-01' }).gate.pass ).toBe(true); }); test('vault cutoff equal to the split date leaves an empty post window (typed non-pass)', () => { const res = evaluateRecencyGate(['2022-12-30', '2023-01-02'], [0.1, 0.1], { vaultCutoffDate: '2023-01-01', }); expect(res.vaultExcludedDates).toBe(1); expect(res.gate).toEqual({ pass: false, reason: 'empty_post_window', ratio: null }); }); test('analyzeSignalPanel recency matches evaluateRecencyGate on its own rank-IC output', () => { const panel = buildRandomPanel(505, 200, true); const res = analyzeSignalPanel(panel, { lag: 3 }); const direct = evaluateRecencyGate(res.dates, res.rankIcSeries, { lag: 3 }); expect(res.recency).toEqual(direct); }); test('leap-year and calendar validation of dates and options', () => { const slice = { ids: [1, 2, 3, 4, 5], signal: [1, 2, 3, 4, 5], forwardReturn: [1, 2, 3, 4, 5] }; for (const date of ['2000-02-29', '2024-02-29']) { expect(() => analyzeSignalPanel([{ ...slice, date }])).not.toThrow(); } for (const date of [ '1900-02-29', '2023-13-01', '2023-00-10', '2023-04-31', '2023-01-00', ' 2023-01-01', '2023/01/01', ]) { try { analyzeSignalPanel([{ ...slice, date }]); throw new Error(`expected INVALID_DATE for ${date}`); } catch (err) { expect([date, (err as SignalAnalysisError).code]).toEqual([date, 'INVALID_DATE']); } } const badOptions: readonly SignalAnalysisOptions[] = [ { minCrossSection: 1 }, { minCrossSection: 5.5 }, { quantiles: 1 }, { quantiles: Number.NaN }, { lag: 1.5 }, { lag: -1 }, { recencyMinRatio: 0 }, { recencyMinRatio: Number.POSITIVE_INFINITY }, { recencySplitDate: '2023-1-1' }, { vaultCutoffDate: '2025-02-30' }, ]; for (const options of badOptions) { expect(() => analyzeSignalPanel([{ ...slice, date: '2022-01-03' }], options)).toThrow( SignalAnalysisError ); } expect(() => neweyWestMeanTest([1, 2, 3], -1)).toThrow(SignalAnalysisError); expect(() => summarizeIcSeries([1, 2, 3], { lag: 0.5 })).toThrow(SignalAnalysisError); expect(() => crossSectionIc([1, 2], [1, 2], { minCrossSection: 1 })).toThrow( SignalAnalysisError ); expect(() => evaluateRecencyGate(['2023-01-02', '2023-01-01'], [0, 0])).toThrow( SignalAnalysisError ); expect(() => evaluateRecencyGate(['2023-02-29'], [0])).toThrow(SignalAnalysisError); }); });