diff --git a/libs/calculations/README.md b/libs/calculations/README.md index 8de33c6f..a26ced06 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -80,9 +80,9 @@ quintile spreads, turnover, and recency gate): bun run libs/calculations/scripts/benchmark-signal-analysis.ts ``` -Observed locally on Bun 1.2.16 (2 runs, seed `20260402`): `1,664.54 ms` -(`3,028 dates/s`, `9,083,609 observations/s`) and `1,659.80 ms` (`3,037 dates/s`, -`9,109,520 observations/s`), `meanRankIc = 0.057294`, `rankIcTStat = 218.5078`, +Observed locally on Bun 1.2.16 (2 runs, seed `20260402`): `1,779.96 ms` +(`2,832 dates/s`, `8,494,557 observations/s`) and `1,809.95 ms` (`2,785 dates/s`, +`8,353,819 observations/s`), `meanRankIc = 0.057294`, `rankIcTStat = 218.5078`, `spreadMean = 0.003369`, `recencyGatePassed = true`. The root entry exports the supported returns, indicators and market-data helpers. diff --git a/libs/calculations/src/analytics/signal-analysis.ts b/libs/calculations/src/analytics/signal-analysis.ts index 7b0a00d7..dae0c60c 100644 --- a/libs/calculations/src/analytics/signal-analysis.ts +++ b/libs/calculations/src/analytics/signal-analysis.ts @@ -15,8 +15,8 @@ * Local benchmark (fixed seed `20260402`, `5,040` dates x `3,000` names = `15,120,000` * observations, covering full `analyzeSignalPanel`): * - Command: `bun run libs/calculations/scripts/benchmark-signal-analysis.ts` - * - Observed (Bun 1.2.16, 2 runs): `1,664.54 ms` (`9,083,609 observations/s`) and - * `1,659.80 ms` (`9,109,520 observations/s`). + * - Observed (Bun 1.2.16, 2 runs): `1,779.96 ms` (`8,494,557 observations/s`) and + * `1,809.95 ms` (`8,353,819 observations/s`). */ /** Default minimum finite cross-sectional pairs required to compute per-date IC. */ @@ -36,6 +36,7 @@ export type SignalAnalysisErrorCode = | 'LENGTH_MISMATCH' | 'UNSORTED_DATES' | 'DUPLICATE_DATE' + | 'DUPLICATE_ID' | 'INVALID_DATE' | 'INVALID_OPTION'; @@ -215,6 +216,38 @@ export interface SignalPanelAnalysis { const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; +const RECENCY_ZERO_TOLERANCE_ULPS = 16; +const FAST_ID_EPOCH_LIMIT = 65536; + +interface CompensatedSumResult { + readonly sum: number; + readonly absSum: number; +} + +function compensatedSum(series: NumericSeries): CompensatedSumResult { + let sum = 0; + let compensation = 0; + let absSum = 0; + for (let i = 0; i < series.length; i++) { + const v = series[i] as number; + const t = sum + v; + if (Math.abs(sum) >= Math.abs(v)) { + compensation += sum - t + v; + } else { + compensation += v - t + sum; + } + sum = t; + absSum += Math.abs(v); + } + return { sum: sum + compensation, absSum }; +} + +function zeroToleranceForMean(absSum: number, count: number): number { + if (count <= 0 || absSum <= 0) { + return 0; + } + return RECENCY_ZERO_TOLERANCE_ULPS * Number.EPSILON * (absSum / count); +} function isLeapYear(year: number): boolean { return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; @@ -532,6 +565,77 @@ function twoPassPearson(x: Float64Array, y: Float64Array, length: number): numbe return rho < -1 ? -1 : rho > 1 ? 1 : rho; } +function twoPassPearsonOrdered( + x: Float64Array, + y: Float64Array, + order: Int32Array, + length: number +): number | null { + if (length < 2) { + return null; + } + + let sumX = 0; + let sumY = 0; + const firstIdx = order[0] as number; + const firstX = x[firstIdx] as number; + const firstY = y[firstIdx] as number; + let allEqualX = true; + let allEqualY = true; + + for (let k = 0; k < length; k++) { + const idx = order[k] as number; + const vx = x[idx] as number; + const vy = y[idx] as number; + sumX += vx; + sumY += vy; + if (vx !== firstX) { + allEqualX = false; + } + if (vy !== firstY) { + allEqualY = false; + } + } + + if (allEqualX || allEqualY) { + return null; + } + + const meanX = sumX / length; + const meanY = sumY / length; + if (!Number.isFinite(meanX) || !Number.isFinite(meanY)) { + return null; + } + + let cov = 0; + let varX = 0; + let varY = 0; + for (let k = 0; k < length; k++) { + const idx = order[k] as number; + const dx = (x[idx] as number) - meanX; + const dy = (y[idx] as number) - meanY; + cov += dx * dy; + varX += dx * dx; + varY += dy * dy; + } + + if (!Number.isFinite(varX) || !Number.isFinite(varY) || varX <= 0 || varY <= 0) { + return null; + } + + const denom = Math.sqrt(varX * varY); + if (!Number.isFinite(denom) || denom <= 0) { + return null; + } + + const rho = cov / denom; + if (!Number.isFinite(rho)) { + return null; + } + + return rho < -1 ? -1 : rho > 1 ? 1 : rho; +} + /** * Computes single-date Pearson IC and Spearman rank-IC (using average ranks for ties) * between `signal` and `forwardReturn`. @@ -659,6 +763,7 @@ export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWes const resolvedLag = lag ?? defaultNeweyWestLag(n); let sum = 0; + let compensation = 0; const first = series[0] as number; let allEqual = true; for (let t = 0; t < n; t++) { @@ -670,13 +775,19 @@ export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWes lag: resolvedLag, }; } - sum += v; + const next = sum + v; + if (Math.abs(sum) >= Math.abs(v)) { + compensation += sum - next + v; + } else { + compensation += v - next + sum; + } + sum = next; if (v !== first) { allEqual = false; } } - const avg = sum / n; + const avg = (sum + compensation) / n; if (!Number.isFinite(avg) || allEqual) { return { status: 'insufficient_data', @@ -741,40 +852,40 @@ export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWes }; } -/** - * Summarizes an IC or spread time series with count, mean, sample standard deviation - * (`n - 1` dof), ICIR (`mean / std`), hit rate (fraction strictly `> 0`), and - * Newey-West HAC t-statistic. - */ -export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOptions): IcSummary { - const lag = options?.lag; - if (lag !== undefined) { - assertIntegerOption(lag, 0, 'lag'); - } +interface IcSummaryWithAbsSum { + readonly summary: IcSummary; + readonly absSum: number; +} +function summarizeIcSeriesInternal( + series: NumericSeries, + lag: number | undefined +): IcSummaryWithAbsSum { const n = series.length; if (n === 0) { return { - count: 0, - mean: null, - std: null, - icir: null, - hitRate: null, - neweyWest: { - status: 'insufficient_data', - reason: 'too_few_observations', - lag: null, + summary: { + count: 0, + mean: null, + std: null, + icir: null, + hitRate: null, + neweyWest: { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }, }, + absSum: 0, }; } - let sum = 0; + const { sum, absSum } = compensatedSum(series); let hits = 0; const first = series[0] as number; let allEqual = true; for (let i = 0; i < n; i++) { const v = series[i] as number; - sum += v; if (v > 0) { hits++; } @@ -787,16 +898,19 @@ export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOpti const hitRate = hits / n; if (n < 2) { return { - count: n, - mean: Number.isFinite(avg) ? avg : null, - std: null, - icir: null, - hitRate, - neweyWest: { - status: 'insufficient_data', - reason: 'too_few_observations', - lag: null, + summary: { + count: n, + mean: Number.isFinite(avg) ? avg : null, + std: null, + icir: null, + hitRate, + neweyWest: { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }, }, + absSum, }; } @@ -817,15 +931,31 @@ export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOpti std !== null && std > 0 && Number.isFinite(avg / std) ? avg / std : null; return { - count: n, - mean: Number.isFinite(avg) ? avg : null, - std, - icir, - hitRate, - neweyWest: neweyWestMeanTest(series, lag), + summary: { + count: n, + mean: Number.isFinite(avg) ? avg : null, + std, + icir, + hitRate, + neweyWest: neweyWestMeanTest(series, lag), + }, + absSum, }; } +/** + * Summarizes an IC or spread time series with count, mean, sample standard deviation + * (`n - 1` dof), ICIR (`mean / std`), hit rate (fraction strictly `> 0`), and + * Newey-West HAC t-statistic. + */ +export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOptions): IcSummary { + const lag = options?.lag; + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + return summarizeIcSeriesInternal(series, lag).summary; +} + function buildRecencySplitResult( dates: readonly string[], rankIc: NumericSeries, @@ -847,19 +977,21 @@ function buildRecencySplitResult( } } - const pre = summarizeIcSeries(Float64Array.from(preValues), { lag }); - const post = summarizeIcSeries(Float64Array.from(postValues), { lag }); + const preStats = summarizeIcSeriesInternal(Float64Array.from(preValues), lag); + const postStats = summarizeIcSeriesInternal(Float64Array.from(postValues), lag); + const pre = preStats.summary; + const post = postStats.summary; let gate: RecencyGateResult; if (pre.count === 0 || pre.mean === null) { gate = { pass: false, reason: 'empty_pre_window', ratio: null }; } else if (post.count === 0 || post.mean === null) { gate = { pass: false, reason: 'empty_post_window', ratio: null }; - } else if (pre.mean <= 0) { + } else if (pre.mean <= zeroToleranceForMean(preStats.absSum, pre.count)) { gate = { pass: false, reason: 'non_positive_pre_mean', ratio: null }; } else { const ratio = post.mean / pre.mean; - if (post.mean <= 0) { + if (post.mean <= zeroToleranceForMean(postStats.absSum, post.count)) { gate = { pass: false, reason: 'non_positive_post_mean', ratio }; } else if (post.mean < minRatio * pre.mean) { gate = { pass: false, reason: 'post_below_ratio_threshold', ratio }; @@ -959,11 +1091,7 @@ function meanFloat64(series: Float64Array): number | null { if (n === 0) { return null; } - let sum = 0; - for (let i = 0; i < n; i++) { - sum += series[i] as number; - } - const avg = sum / n; + const avg = compensatedSum(series).sum / n; return Number.isFinite(avg) ? avg : null; } @@ -1063,6 +1191,9 @@ export function analyzeSignalPanel( let currTop = new Set(); let prevBottom = new Set(); let currBottom = new Set(); + const seenEpoch = new Int32Array(FAST_ID_EPOCH_LIMIT); + const seenIds = new Set(); + let idEpoch = 0; let totalObservations = 0; let validObservations = 0; @@ -1091,6 +1222,15 @@ export function analyzeSignalPanel( const n = signal.length; totalObservations += n; + idEpoch++; + if (idEpoch === 0x7fffffff) { + seenEpoch.fill(0); + idEpoch = 1; + } + if (seenIds.size > 0) { + seenIds.clear(); + } + let m = 0; for (let i = 0; i < n; i++) { const s = signal[i]; @@ -1101,6 +1241,30 @@ export function analyzeSignalPanel( Number.isFinite(s) && Number.isFinite(r) ) { + const id = ids[i] as EntityId; + if ( + typeof id === 'number' && + (id | 0) === id && + id >= 0 && + id < FAST_ID_EPOCH_LIMIT + ) { + if (seenEpoch[id] === idEpoch) { + throw new SignalAnalysisError( + 'DUPLICATE_ID', + `Duplicate entity id ${String(id)} on ${slice.date}` + ); + } + seenEpoch[id] = idEpoch; + } else { + if (seenIds.has(id)) { + throw new SignalAnalysisError( + 'DUPLICATE_ID', + `Duplicate entity id ${String(id)} on ${slice.date}` + ); + } + seenIds.add(id); + } + validIdx[m] = i; validSignal[m] = s; validReturn[m] = r; @@ -1122,7 +1286,7 @@ export function analyzeSignalPanel( if (!needsIc) { icSkippedBelowMin++; } else { - const pearson = twoPassPearson(validSignal, validReturn, m); + const pearson = twoPassPearsonOrdered(validSignal, validReturn, orderSignal, m); if (pearson === null) { icSkippedZeroVariance++; } else { @@ -1133,7 +1297,7 @@ export function analyzeSignalPanel( assignAverageRanks(orderSignal, validSignal, rankSignal, m); assignAverageRanks(orderReturn, validReturn, rankReturn, m); - const rankIc = twoPassPearson(rankSignal, rankReturn, m); + const rankIc = twoPassPearsonOrdered(rankSignal, rankReturn, orderSignal, m); if (rankIc === null) { icSkippedZeroVariance++; } else { diff --git a/libs/calculations/test/signal-analysis.test.ts b/libs/calculations/test/signal-analysis.test.ts index e443cb6e..0ca83b1b 100644 --- a/libs/calculations/test/signal-analysis.test.ts +++ b/libs/calculations/test/signal-analysis.test.ts @@ -312,11 +312,40 @@ describe('analyzeSignalPanel quantiles, tie-breaking, turnover, and invariants', const a = analyzeSignalPanel(basePanel, { quantiles: 5 }); const b = analyzeSignalPanel(permutedPanel, { quantiles: 5 }); - expect(a.rankIcSeries).toEqual(b.rankIcSeries); - expect(a.quantiles.spreadSeries).toEqual(b.quantiles.spreadSeries); - expect(a.quantiles.bucketMeanReturns).toEqual(b.quantiles.bucketMeanReturns); - expect(a.turnover.topSeries).toEqual(b.turnover.topSeries); - expect(a.turnover.bottomSeries).toEqual(b.turnover.bottomSeries); + expect(a).toEqual(b); + for (let i = 0; i < a.pearsonIcSeries.length; i++) { + expect(Object.is(a.pearsonIcSeries[i], b.pearsonIcSeries[i])).toBe(true); + expect(Object.is(a.rankIcSeries[i], b.rankIcSeries[i])).toBe(true); + } + }); + + test('Pearson IC and full panel analysis are bit-for-bit invariant under row swaps with sensitive float sums', () => { + const A = 0.015625; + const B = 0.0019531250000000004; + const C = -0.03515625; + const base: SignalCrossSection[] = [ + { + date: '2022-06-01', + ids: ['id-1', 'id-2', 'id-3', 'id-4', 'id-5'], + signal: [-1, -1, 1, 1, 0], + forwardReturn: [A, B, A, B, C], + }, + ]; + const swapped: SignalCrossSection[] = [ + { + date: '2022-06-01', + ids: ['id-1', 'id-3', 'id-2', 'id-4', 'id-5'], + signal: [-1, 1, -1, 1, 0], + forwardReturn: [A, A, B, B, C], + }, + ]; + + const resBase = analyzeSignalPanel(base, { quantiles: 5 }); + const resSwapped = analyzeSignalPanel(swapped, { quantiles: 5 }); + + expect(resBase).toEqual(resSwapped); + expect(Object.is(resBase.pearsonIcSeries[0], resSwapped.pearsonIcSeries[0])).toBe(true); + expect(Object.is(resBase.pearsonIc.mean, resSwapped.pearsonIc.mean)).toBe(true); }); test('strictly increasing nonlinear transform preserves rank-IC, quantiles, and turnover; negating flips signs', () => { @@ -518,6 +547,39 @@ describe('evaluateRecencyGate and vaultCutoffDate fence', () => { expect(emptyPost.gate.reason).toBe('empty_post_window'); }); + test('rejects pre-2023 or post-2023 rank-IC means that cancel to zero within floating-point rounding', () => { + // 5-name cross-sections with exact Spearman rank-ICs: + // [2, 5, 1, 4, 3] -> 0.1, [1, 4, 5, 2, 3] -> 0.2, [5, 1, 3, 4, 2] -> -0.3 + // Exact mean = (0.1 + 0.2 - 0.3) / 3 = 0, but uncompensated float sum leaves ~1.85e-17. + const ids = [1, 2, 3, 4, 5]; + const signal = [1, 2, 3, 4, 5]; + const panelZeroPre: SignalCrossSection[] = [ + { date: '2022-12-28', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2022-12-29', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2022-12-30', ids, signal, forwardReturn: [5, 1, 3, 4, 2] }, + { date: '2023-01-03', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + ]; + + const resZeroPre = analyzeSignalPanel(panelZeroPre); + expect(Math.abs((resZeroPre.rankIcSeries[0] as number) - 0.1)).toBeLessThan(1e-12); + expect(Math.abs((resZeroPre.rankIcSeries[1] as number) - 0.2)).toBeLessThan(1e-12); + expect(Math.abs((resZeroPre.rankIcSeries[2] as number) - -0.3)).toBeLessThan(1e-12); + expect(Math.abs((resZeroPre.rankIcSeries[3] as number) - 0.1)).toBeLessThan(1e-12); + expect(resZeroPre.recency.gate.pass).toBe(false); + expect(resZeroPre.recency.gate.reason).toBe('non_positive_pre_mean'); + expect(resZeroPre.recency.gate.ratio).toBeNull(); + + const panelZeroPost: SignalCrossSection[] = [ + { date: '2022-12-30', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2023-01-03', ids, signal, forwardReturn: [2, 5, 1, 4, 3] }, + { date: '2023-01-04', ids, signal, forwardReturn: [1, 4, 5, 2, 3] }, + { date: '2023-01-05', ids, signal, forwardReturn: [5, 1, 3, 4, 2] }, + ]; + const resZeroPost = analyzeSignalPanel(panelZeroPost); + expect(resZeroPost.recency.gate.pass).toBe(false); + expect(resZeroPost.recency.gate.reason).toBe('non_positive_post_mean'); + }); + test('vaultCutoffDate excludes dates >= cutoff, counts them, and isolates non-vault metrics', () => { const basePanel: SignalCrossSection[] = [ { @@ -665,6 +727,65 @@ describe('input validation errors', () => { expect(leap.dates).toEqual(['2024-02-29']); }); + test('throws DUPLICATE_ID when valid rows in a cross-section share an entity ID (including at a bucket boundary)', () => { + // Two rows for the same security with the lowest signal and different forward returns at q=5 boundary + expectErrorCode( + () => + analyzeSignalPanel( + [ + { + date: '2023-01-03', + ids: ['SEC1', 'SEC1', 'SEC2', 'SEC3', 'SEC4'], + signal: [1, 1, 2, 3, 4], + forwardReturn: [-0.05, 0.15, 0.01, 0.02, 0.03], + }, + ], + { quantiles: 5 } + ), + 'DUPLICATE_ID' + ); + + // Small integer ID fast path + expectErrorCode( + () => + analyzeSignalPanel([ + { + date: '2023-01-03', + ids: [10, 10, 20, 30, 40], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + ]), + 'DUPLICATE_ID' + ); + + // Large/negative numeric ID fallback path + expectErrorCode( + () => + analyzeSignalPanel([ + { + date: '2023-01-03', + ids: [100_000, 100_000, -5, 1, 2], + signal: [1, 2, 3, 4, 5], + forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05], + }, + ]), + 'DUPLICATE_ID' + ); + + // A duplicate ID whose extra row is dropped as non-finite leaves unique valid IDs and succeeds + const resWithDroppedDup = analyzeSignalPanel([ + { + date: '2023-01-03', + ids: ['SEC1', 'SEC1', 'SEC2', 'SEC3', 'SEC4', 'SEC5'], + signal: [1, Number.NaN, 2, 3, 4, 5], + forwardReturn: [0.01, 0.99, 0.02, 0.03, 0.04, 0.05], + }, + ]); + expect(resWithDroppedDup.diagnostics.validObservations).toBe(5); + expect(resWithDroppedDup.diagnostics.droppedPairs).toBe(1); + }); + test('throws INVALID_OPTION on invalid quantiles, lag, minCrossSection, or recencyMinRatio', () => { expectErrorCode(() => analyzeSignalPanel([validSlice], { quantiles: 1 }), 'INVALID_OPTION'); expectErrorCode(() => analyzeSignalPanel([validSlice], { quantiles: 2.5 }), 'INVALID_OPTION');