T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O)

This commit is contained in:
Studio 2026-11-28 01:34:00 -05:00
parent 306d324b8d
commit 659cd042f6
6 changed files with 2169 additions and 1 deletions

View file

@ -54,7 +54,11 @@ const risk = returnStatistics(returns);
fields in `performanceAnalysis` remain compatibility heuristics, not optimizers.
Canonical Deflated Sharpe Ratio (`deflatedSharpeRatio`, `effectiveIndependentTrials`,
`trialMoments`, `normalCdf`, `inverseNormalCdf`, `passesDsrGate`, `DSR_VALIDATION_GATE`)
is exported from both `./analytics` and the root entry.
and cross-sectional Signal Analysis (`analyzeSignalPanel`, `crossSectionIc`,
`neweyWestMeanTest`, `defaultNeweyWestLag`, `summarizeIcSeries`, `evaluateRecencyGate`,
`SignalAnalysisError`, `DEFAULT_MIN_CROSS_SECTION`, `DEFAULT_QUANTILE_COUNT`,
`RECENCY_SPLIT_DATE`, `RECENCY_MIN_RATIO`) are exported from both `./analytics` and
the root entry.
## Benchmark
@ -68,6 +72,19 @@ bun run libs/calculations/scripts/benchmark-deflated-sharpe.ts
Observed locally on Bun 1.2.16 (2 runs, seed `20260401`): `150.18 ms` (`830,660 pairs/s`)
and `159.79 ms` (`780,707 pairs/s`), `meanCorrelation = 0.071187`, `nHat = 464.4776`.
Run the fixed-seed Signal Analysis benchmark (`5,040` dates × `3,000` names,
`15,120,000` observations, covering full `analyzeSignalPanel` with IC, Newey-West HAC,
quintile spreads, turnover, and recency gate):
```sh
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`,
`spreadMean = 0.003369`, `recencyGatePassed = true`.
The root entry exports the supported returns, indicators and market-data helpers.
Use subpaths to avoid loading unrelated math. Shared domain types remain owned by
`@stock-bot/types`; HTTP/date/proxy helpers remain in `@stock-bot/utils`.

View file

@ -0,0 +1,132 @@
import { analyzeSignalPanel, type SignalCrossSection } from '../src/analytics/signal-analysis';
const SEED = 20260402;
const DATES = 5040;
const NAMES_PER_DATE = 3000;
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;
};
}
function createStandardNormal(seed: number): () => number {
const nextUniform = createMulberry32(seed);
let spare: number | null = null;
return () => {
if (spare !== null) {
const value = spare;
spare = null;
return value;
}
let u1 = nextUniform();
while (u1 <= 1e-12) {
u1 = nextUniform();
}
const u2 = nextUniform();
const radius = Math.sqrt(-2 * Math.log(u1));
const theta = 2 * Math.PI * u2;
spare = radius * Math.sin(theta);
return radius * Math.cos(theta);
};
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
}
const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const;
function generateBusinessDates(count: number, startYear: number): string[] {
const dates: string[] = new Array(count);
let year = startYear;
let month = 1;
let day = 1;
// 2006-01-01 was a Sunday (dow = 0)
let dow = 0;
let produced = 0;
while (produced < count) {
if (dow !== 0 && dow !== 6) {
const yyyy = String(year).padStart(4, '0');
const mm = String(month).padStart(2, '0');
const dd = String(day).padStart(2, '0');
dates[produced++] = `${yyyy}-${mm}-${dd}`;
}
dow = (dow + 1) % 7;
day++;
const baseDays = DAYS_IN_MONTH[month] ?? 31;
const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays;
if (day > maxDay) {
day = 1;
month++;
if (month > 12) {
month = 1;
year++;
}
}
}
return dates;
}
const randn = createStandardNormal(SEED);
const isoDates = generateBusinessDates(DATES, 2006);
const sharedIds = new Int32Array(NAMES_PER_DATE);
for (let i = 0; i < NAMES_PER_DATE; i++) {
sharedIds[i] = i + 1;
}
const panel: SignalCrossSection[] = new Array(DATES);
for (let t = 0; t < DATES; t++) {
const signal = new Float64Array(NAMES_PER_DATE);
const forwardReturn = new Float64Array(NAMES_PER_DATE);
for (let i = 0; i < NAMES_PER_DATE; i++) {
const s = randn();
signal[i] = s;
forwardReturn[i] = 0.0004 + 0.0012 * s + 0.02 * randn();
}
panel[t] = {
date: isoDates[t] as string,
ids: sharedIds,
signal,
forwardReturn,
};
}
const started = performance.now();
const result = analyzeSignalPanel(panel);
const elapsedMs = performance.now() - started;
const totalObservations = DATES * NAMES_PER_DATE;
const elapsedSec = elapsedMs / 1000;
const datesPerSec = DATES / elapsedSec;
const observationsPerSec = totalObservations / elapsedSec;
console.log(
JSON.stringify(
{
seed: SEED,
dates: DATES,
namesPerDate: NAMES_PER_DATE,
totalObservations,
elapsedMs: Number(elapsedMs.toFixed(2)),
datesPerSec: Math.round(datesPerSec),
observationsPerSec: Math.round(observationsPerSec),
meanRankIc: Number((result.rankIc.mean ?? 0).toFixed(6)),
rankIcTStat:
result.rankIc.neweyWest.status === 'ok'
? Number(result.rankIc.neweyWest.tStat.toFixed(4))
: null,
spreadMean: Number((result.quantiles.spreadSummary.mean ?? 0).toFixed(6)),
recencyGatePassed: result.recency.gate.pass,
},
null,
2
)
);

View file

@ -20,3 +20,37 @@ export type {
EffectiveTrialsResult,
TrialMoments,
} from './deflated-sharpe';
export {
DEFAULT_MIN_CROSS_SECTION,
DEFAULT_QUANTILE_COUNT,
RECENCY_MIN_RATIO,
RECENCY_SPLIT_DATE,
SignalAnalysisError,
analyzeSignalPanel,
crossSectionIc,
defaultNeweyWestLag,
evaluateRecencyGate,
neweyWestMeanTest,
summarizeIcSeries,
} from './signal-analysis';
export type {
CrossSectionIcOptions,
CrossSectionIcResult,
EntityId,
EntityIdSeries,
IcSummary,
IcSummaryOptions,
NeweyWestResult,
NumericSeries,
QuantileSpreadResult,
RecencyGateOptions,
RecencyGateReason,
RecencyGateResult,
RecencySplitResult,
SignalAnalysisErrorCode,
SignalAnalysisOptions,
SignalCrossSection,
SignalPanelAnalysis,
SignalPanelDiagnostics,
TurnoverResult,
} from './signal-analysis';

File diff suppressed because it is too large Load diff

View file

@ -56,18 +56,48 @@ export {
groupBySymbol,
} from './market-data';
export {
DEFAULT_MIN_CROSS_SECTION,
DEFAULT_QUANTILE_COUNT,
DSR_VALIDATION_GATE,
EULER_MASCHERONI,
RECENCY_MIN_RATIO,
RECENCY_SPLIT_DATE,
SignalAnalysisError,
analyzeSignalPanel,
crossSectionIc,
defaultNeweyWestLag,
deflatedSharpeRatio,
effectiveIndependentTrials,
evaluateRecencyGate,
inverseNormalCdf,
neweyWestMeanTest,
normalCdf,
passesDsrGate,
summarizeIcSeries,
trialMoments,
} from './analytics';
export type {
CrossSectionIcOptions,
CrossSectionIcResult,
DeflatedSharpeInput,
DeflatedSharpeResult,
EffectiveTrialsResult,
EntityId,
EntityIdSeries,
IcSummary,
IcSummaryOptions,
NeweyWestResult,
NumericSeries,
QuantileSpreadResult,
RecencyGateOptions,
RecencyGateReason,
RecencyGateResult,
RecencySplitResult,
SignalAnalysisErrorCode,
SignalAnalysisOptions,
SignalCrossSection,
SignalPanelAnalysis,
SignalPanelDiagnostics,
TrialMoments,
TurnoverResult,
} from './analytics';

View file

@ -0,0 +1,680 @@
import { describe, expect, test } from 'bun:test';
import * as rootExports from '@stock-bot/calculations';
import * as analyticsExports from '@stock-bot/calculations/analytics';
import {
DEFAULT_MIN_CROSS_SECTION,
DEFAULT_QUANTILE_COUNT,
RECENCY_MIN_RATIO,
RECENCY_SPLIT_DATE,
SignalAnalysisError,
analyzeSignalPanel,
crossSectionIc,
defaultNeweyWestLag,
evaluateRecencyGate,
neweyWestMeanTest,
summarizeIcSeries,
type SignalCrossSection,
} from '@stock-bot/calculations';
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;
};
}
function assertAllFiniteFloat64(series: Float64Array): void {
for (let i = 0; i < series.length; i++) {
expect(Number.isFinite(series[i])).toBe(true);
}
}
function assertNoNaNDeep(value: unknown): void {
if (typeof value === 'number') {
expect(Number.isFinite(value)).toBe(true);
return;
}
if (value instanceof Float64Array) {
assertAllFiniteFloat64(value);
return;
}
if (Array.isArray(value)) {
for (const item of value) {
assertNoNaNDeep(item);
}
return;
}
if (value !== null && typeof value === 'object') {
for (const entry of Object.values(value)) {
assertNoNaNDeep(entry);
}
}
}
describe('signal-analysis exports', () => {
test('both root and analytics entrypoints export the complete signal-analysis surface', () => {
const names = [
'DEFAULT_MIN_CROSS_SECTION',
'DEFAULT_QUANTILE_COUNT',
'RECENCY_SPLIT_DATE',
'RECENCY_MIN_RATIO',
'SignalAnalysisError',
'crossSectionIc',
'defaultNeweyWestLag',
'neweyWestMeanTest',
'summarizeIcSeries',
'evaluateRecencyGate',
'analyzeSignalPanel',
] as const;
for (const name of names) {
expect(rootExports[name]).toBeDefined();
expect(analyticsExports[name]).toBe(rootExports[name]);
}
expect(DEFAULT_MIN_CROSS_SECTION).toBe(5);
expect(DEFAULT_QUANTILE_COUNT).toBe(5);
expect(RECENCY_SPLIT_DATE).toBe('2023-01-01');
expect(RECENCY_MIN_RATIO).toBe(0.5);
});
});
describe('crossSectionIc', () => {
test('matches hand-computed 5-name Pearson IC and Spearman rank-IC to 1e-12', () => {
// signal = [1, 2, 3, 4, 10], forwardReturn = [2, 1, 4, 3, 5]
// Pearson = 18 / sqrt(500) = 9 / (5 * sqrt(5)); Spearman = 0.8
const res = crossSectionIc([1, 2, 3, 4, 10], [2, 1, 4, 3, 5]);
expect(res.status).toBe('ok');
if (res.status === 'ok') {
expect(res.validCount).toBe(5);
expect(res.droppedPairs).toBe(0);
expect(Math.abs(res.pearsonIc - 9 / (5 * Math.sqrt(5)))).toBeLessThan(1e-12);
expect(Math.abs(res.rankIc - 0.8)).toBeLessThan(1e-12);
}
});
test('uses average ranks for tied signals and matches hand-computed fixture to 1e-12', () => {
// signal = [1, 2, 2, 4, 5], forwardReturn = [10, 20, 40, 30, 50]
// Pearson = 4 / (3 * sqrt(3)); Spearman = 8 / sqrt(95)
const res = crossSectionIc([1, 2, 2, 4, 5], [10, 20, 40, 30, 50]);
expect(res.status).toBe('ok');
if (res.status === 'ok') {
expect(res.validCount).toBe(5);
expect(res.droppedPairs).toBe(0);
expect(Math.abs(res.pearsonIc - 4 / (3 * Math.sqrt(3)))).toBeLessThan(1e-12);
expect(Math.abs(res.rankIc - 8 / Math.sqrt(95))).toBeLessThan(1e-12);
}
});
test('returns rank-IC = +1 for strictly increasing and -1 for reversed signals', () => {
const pos = crossSectionIc([1, 2, 3, 4, 5], [10, 12, 100, 101, 500]);
expect(pos.status).toBe('ok');
if (pos.status === 'ok') {
expect(Math.abs(pos.rankIc - 1)).toBeLessThan(1e-12);
}
const neg = crossSectionIc([5, 4, 3, 2, 1], [10, 12, 100, 101, 500]);
expect(neg.status).toBe('ok');
if (neg.status === 'ok') {
expect(Math.abs(neg.rankIc - -1)).toBeLessThan(1e-12);
}
});
test('drops non-finite pairs and skips below minCrossSection or zero variance without NaN', () => {
const withNaNs = crossSectionIc(
[1, Number.NaN, 2, 3, Number.POSITIVE_INFINITY, 4, 10],
[2, 5, 1, 4, 9, 3, 5]
);
expect(withNaNs.status).toBe('ok');
if (withNaNs.status === 'ok') {
expect(withNaNs.validCount).toBe(5);
expect(withNaNs.droppedPairs).toBe(2);
expect(Math.abs(withNaNs.rankIc - 0.8)).toBeLessThan(1e-12);
}
const tooSmall = crossSectionIc(
[1, 2, 3, 4, Number.NaN],
[2, 1, 4, 3, 5]
);
expect(tooSmall).toEqual({
status: 'skipped',
reason: 'below_min_cross_section',
validCount: 4,
droppedPairs: 1,
});
const zeroVar = crossSectionIc([0.1, 0.1, 0.1, 0.1, 0.1], [1, 2, 3, 4, 5]);
expect(zeroVar).toEqual({
status: 'skipped',
reason: 'zero_variance',
validCount: 5,
droppedPairs: 0,
});
});
});
describe('neweyWestMeanTest and summarizeIcSeries', () => {
test('defaultNeweyWestLag matches floor(4 * (T/100)^(2/9))', () => {
expect(defaultNeweyWestLag(0)).toBe(0);
expect(defaultNeweyWestLag(1)).toBe(0);
expect(defaultNeweyWestLag(100)).toBe(4);
expect(defaultNeweyWestLag(252)).toBe(Math.floor(4 * Math.pow(252 / 100, 2 / 9)));
expect(defaultNeweyWestLag(5040)).toBe(Math.floor(4 * Math.pow(5040 / 100, 2 / 9)));
});
test('lag = 0 equals plain mean / (sd / sqrt(T)) to 1e-12', () => {
const series = [0.05, 0.02, -0.01, 0.04, 0.03, 0.06, 0.01];
const summary = summarizeIcSeries(series, { lag: 0 });
expect(summary.count).toBe(7);
expect(summary.mean).not.toBeNull();
expect(summary.std).not.toBeNull();
expect(summary.neweyWest.status).toBe('ok');
if (summary.mean !== null && summary.std !== null && summary.neweyWest.status === 'ok') {
const plainSe = summary.std / Math.sqrt(series.length);
const plainT = summary.mean / plainSe;
expect(summary.neweyWest.lag).toBe(0);
expect(Math.abs(summary.neweyWest.standardError - plainSe)).toBeLessThan(1e-12);
expect(Math.abs(summary.neweyWest.tStat - plainT)).toBeLessThan(1e-12);
}
});
test('matches hand-computed Bartlett-weighted lag = 2 fixture to 1e-12', () => {
// series = [1, 2, 3, 6, 8], T = 5, mean = 4
// longRunVariance = 37/3, se = sqrt(37/15), t = 4 / sqrt(37/15)
const res = neweyWestMeanTest([1, 2, 3, 6, 8], 2);
expect(res.status).toBe('ok');
if (res.status === 'ok') {
const expectedLrv = 37 / 3;
const expectedSe = Math.sqrt(37 / 15);
const expectedT = 4 / expectedSe;
expect(res.lag).toBe(2);
expect(Math.abs(res.longRunVariance - expectedLrv)).toBeLessThan(1e-12);
expect(Math.abs(res.standardError - expectedSe)).toBeLessThan(1e-12);
expect(Math.abs(res.tStat - expectedT)).toBeLessThan(1e-12);
}
});
test('positively autocorrelated AR(1) series has smaller |t| with positive lag than lag = 0', () => {
const nextUniform = createMulberry32(42);
const n = 200;
const ar1 = new Float64Array(n);
let x = 0.05;
for (let t = 0; t < n; t++) {
const shock = (nextUniform() - 0.5) * 0.04;
x = 0.01 + 0.85 * x + shock;
ar1[t] = x;
}
const nw0 = neweyWestMeanTest(ar1, 0);
const nwDefault = neweyWestMeanTest(ar1);
expect(nw0.status).toBe('ok');
expect(nwDefault.status).toBe('ok');
if (nw0.status === 'ok' && nwDefault.status === 'ok') {
expect(nwDefault.lag).toBeGreaterThan(0);
expect(Math.abs(nwDefault.tStat)).toBeLessThan(Math.abs(nw0.tStat));
}
});
test('returns typed insufficient_data for T < 2 and constant or non-positive variance series', () => {
expect(neweyWestMeanTest([])).toEqual({
status: 'insufficient_data',
reason: 'too_few_observations',
lag: null,
});
expect(neweyWestMeanTest([0.05])).toEqual({
status: 'insufficient_data',
reason: 'too_few_observations',
lag: null,
});
expect(neweyWestMeanTest([0.1, 0.1, 0.1, 0.1], 2)).toEqual({
status: 'insufficient_data',
reason: 'non_positive_variance',
lag: 2,
});
const emptySummary = summarizeIcSeries([]);
expect(emptySummary.count).toBe(0);
expect(emptySummary.mean).toBeNull();
expect(emptySummary.std).toBeNull();
expect(emptySummary.icir).toBeNull();
expect(emptySummary.hitRate).toBeNull();
expect(emptySummary.neweyWest.status).toBe('insufficient_data');
assertNoNaNDeep(emptySummary);
});
});
describe('analyzeSignalPanel quantiles, tie-breaking, turnover, and invariants', () => {
test('computes exact 10-name q = 5 bucket means, spreads, and spread Newey-West summary', () => {
const panel: SignalCrossSection[] = [
{
date: '2022-06-01',
ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
signal: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
forwardReturn: [-0.05, -0.03, -0.01, 0.01, 0.0, 0.02, 0.03, 0.05, 0.06, 0.1],
},
{
date: '2022-06-02',
ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
signal: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100],
forwardReturn: [-0.03, -0.01, 0.0, 0.02, 0.01, 0.03, 0.04, 0.06, 0.12, 0.16],
},
];
const res = analyzeSignalPanel(panel, { quantiles: 5, lag: 0 });
expect(res.quantiles.validDates).toBe(2);
expect(res.quantiles.skippedDates).toBe(0);
// Date 1 buckets: [-0.04, 0.00, 0.01, 0.04, 0.08], spread = 0.12
// Date 2 buckets: [-0.02, 0.01, 0.02, 0.05, 0.14], spread = 0.16
const expectedMeans = [-0.03, 0.005, 0.015, 0.045, 0.11];
for (let b = 0; b < 5; b++) {
expect(
Math.abs((res.quantiles.bucketMeanReturns[b] as number) - (expectedMeans[b] as number))
).toBeLessThan(1e-12);
}
expect(Math.abs((res.quantiles.spreadSeries[0] as number) - 0.12)).toBeLessThan(1e-12);
expect(Math.abs((res.quantiles.spreadSeries[1] as number) - 0.16)).toBeLessThan(1e-12);
expect(Math.abs((res.quantiles.spreadSummary.mean as number) - 0.14)).toBeLessThan(1e-12);
// Spread = [0.12, 0.16] -> mean = 0.14, sd = sqrt(0.0008), se = 0.02, t = 7.0
expect(res.quantiles.spreadSummary.neweyWest.status).toBe('ok');
if (res.quantiles.spreadSummary.neweyWest.status === 'ok') {
expect(Math.abs(res.quantiles.spreadSummary.neweyWest.standardError - 0.02)).toBeLessThan(
1e-12
);
expect(Math.abs(res.quantiles.spreadSummary.neweyWest.tStat - 7)).toBeLessThan(1e-12);
}
assertNoNaNDeep(res);
});
test('tie-breaking is deterministic under input permutation within a date', () => {
const ids = ['AAPL', 'MSFT', 'NVDA', 'AMZN', 'META', 'GOOG', 'TSLA', 'JPM', 'BAC', 'XOM'];
const signal = [1, 1, 1, 2, 2, 2, 2, 3, 3, 3];
const forwardReturn = [0.01, -0.02, 0.05, 0.03, -0.01, 0.04, 0.02, 0.06, -0.03, 0.07];
const basePanel: SignalCrossSection[] = [
{ date: '2022-01-03', ids, signal, forwardReturn },
{ date: '2023-01-03', ids, signal: [3, 3, 1, 2, 2, 1, 1, 2, 3, 2], forwardReturn },
];
// Permute every cross-section deterministically
const perm = [7, 2, 9, 0, 5, 1, 8, 3, 6, 4];
const permutedPanel: SignalCrossSection[] = basePanel.map(slice => ({
date: slice.date,
ids: perm.map(i => slice.ids[i] as string),
signal: perm.map(i => slice.signal[i] as number),
forwardReturn: perm.map(i => slice.forwardReturn[i] as number),
}));
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);
});
test('strictly increasing nonlinear transform preserves rank-IC, quantiles, and turnover; negating flips signs', () => {
const panel: SignalCrossSection[] = [
{
date: '2022-05-02',
ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
signal: [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5],
forwardReturn: [-0.04, -0.02, -0.01, 0.0, 0.01, 0.02, 0.01, 0.03, 0.05, 0.06],
},
{
date: '2023-05-02',
ids: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
signal: [-3, -4, -1, -2, 1, 0, 3, 2, 5, 4],
forwardReturn: [-0.02, -0.03, 0.0, -0.01, 0.02, 0.01, 0.04, 0.03, 0.06, 0.05],
},
];
const transformed: SignalCrossSection[] = panel.map(slice => ({
...slice,
signal: Array.from(slice.signal, v => Math.exp(v * 0.3)),
}));
const negated: SignalCrossSection[] = panel.map(slice => ({
...slice,
signal: Array.from(slice.signal, v => -v),
}));
const baseRes = analyzeSignalPanel(panel, { quantiles: 5 });
const expRes = analyzeSignalPanel(transformed, { quantiles: 5 });
const negRes = analyzeSignalPanel(negated, { quantiles: 5 });
for (let i = 0; i < baseRes.rankIcSeries.length; i++) {
expect(Math.abs((baseRes.rankIcSeries[i] as number) - (expRes.rankIcSeries[i] as number))).toBeLessThan(1e-12);
expect(Math.abs((baseRes.rankIcSeries[i] as number) + (negRes.rankIcSeries[i] as number))).toBeLessThan(1e-12);
expect(Math.abs((baseRes.pearsonIcSeries[i] as number) + (negRes.pearsonIcSeries[i] as number))).toBeLessThan(
1e-12
);
}
expect(expRes.quantiles.spreadSeries).toEqual(baseRes.quantiles.spreadSeries);
expect(expRes.turnover.topSeries).toEqual(baseRes.turnover.topSeries);
expect(expRes.turnover.bottomSeries).toEqual(baseRes.turnover.bottomSeries);
for (let i = 0; i < baseRes.quantiles.spreadSeries.length; i++) {
expect(
Math.abs((baseRes.quantiles.spreadSeries[i] as number) + (negRes.quantiles.spreadSeries[i] as number))
).toBeLessThan(1e-12);
}
expect(negRes.turnover.topSeries).toEqual(baseRes.turnover.bottomSeries);
expect(negRes.turnover.bottomSeries).toEqual(baseRes.turnover.topSeries);
});
test('computes exact turnover for identical (0), disjoint (1), and half-replaced (0.5) membership', () => {
// q = 2 on 4 names -> bottom = 2 names, top = 2 names
// Date 1: bottom = {1, 2}, top = {3, 4}
// Date 2: bottom = {1, 2}, top = {3, 4} -> turnover = 0
// Date 3: bottom = {3, 4}, top = {1, 2} -> turnover = 1
// Date 4: bottom = {3, 1}, top = {4, 2} -> turnover = 0.5
const panel: SignalCrossSection[] = [
{
date: '2023-01-02',
ids: [1, 2, 3, 4],
signal: [1, 2, 3, 4],
forwardReturn: [0.01, 0.02, 0.03, 0.04],
},
{
date: '2023-01-03',
ids: [1, 2, 3, 4],
signal: [1, 2, 3, 4],
forwardReturn: [0.01, 0.02, 0.03, 0.04],
},
{
date: '2023-01-04',
ids: [1, 2, 3, 4],
signal: [3, 4, 1, 2],
forwardReturn: [0.01, 0.02, 0.03, 0.04],
},
{
date: '2023-01-05',
ids: [1, 2, 3, 4],
signal: [2, 4, 1, 3],
forwardReturn: [0.01, 0.02, 0.03, 0.04],
},
];
const res = analyzeSignalPanel(panel, { minCrossSection: 4, quantiles: 2 });
// First date contributes no turnover
expect(res.turnover.count).toBe(3);
expect(res.turnover.dates).toEqual(['2023-01-03', '2023-01-04', '2023-01-05']);
expect(Array.from(res.turnover.topSeries)).toEqual([0, 1, 0.5]);
expect(Array.from(res.turnover.bottomSeries)).toEqual([0, 1, 0.5]);
expect(res.turnover.meanTopTurnover).toBe(0.5);
expect(res.turnover.meanBottomTurnover).toBe(0.5);
});
test('skips and counts dates with fewer than q valid names or below minCrossSection / zero variance', () => {
const panel: SignalCrossSection[] = [
// 3 valid names (< minCrossSection 5 and < q 5)
{
date: '2022-01-03',
ids: [1, 2, 3, 4],
signal: [1, 2, 3, Number.NaN],
forwardReturn: [0.01, 0.02, 0.03, 0.04],
},
// 5 valid names, zero signal variance (valid for quantiles, skipped for IC)
{
date: '2022-01-04',
ids: [1, 2, 3, 4, 5],
signal: [1, 1, 1, 1, 1],
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05],
},
// 5 valid names, non-zero variance (valid for both)
{
date: '2023-01-04',
ids: [1, 2, 3, 4, 5],
signal: [1, 2, 3, 4, 5],
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05],
},
];
const res = analyzeSignalPanel(panel);
expect(res.diagnostics.droppedPairs).toBe(1);
expect(res.diagnostics.icValidDates).toBe(1);
expect(res.diagnostics.icSkippedBelowMin).toBe(1);
expect(res.diagnostics.icSkippedZeroVariance).toBe(1);
expect(res.diagnostics.quantileValidDates).toBe(2);
expect(res.diagnostics.quantileSkippedDates).toBe(1);
assertNoNaNDeep(res);
});
});
describe('evaluateRecencyGate and vaultCutoffDate fence', () => {
test('splits 2022-12-31 into pre and 2023-01-01 into post and passes when post >= 50% of pre', () => {
const res = evaluateRecencyGate(
['2022-12-30', '2022-12-31', '2023-01-01', '2023-01-02'],
[0.08, 0.12, 0.06, 0.08]
);
expect(res.pre.count).toBe(2);
expect(res.post.count).toBe(2);
expect(Math.abs((res.pre.mean as number) - 0.1)).toBeLessThan(1e-12);
expect(Math.abs((res.post.mean as number) - 0.07)).toBeLessThan(1e-12);
expect(res.gate.pass).toBe(true);
expect(res.gate.reason).toBe('passed');
expect(Math.abs((res.gate.ratio as number) - 0.7)).toBeLessThan(1e-12);
});
test('passes on exact 50% boundary and fails on < 50%, post <= 0, pre <= 0, or empty windows', () => {
const exactBoundary = evaluateRecencyGate(
['2022-12-31', '2023-01-01'],
[0.08, 0.04]
);
expect(exactBoundary.gate.pass).toBe(true);
expect(exactBoundary.gate.reason).toBe('passed');
expect(exactBoundary.gate.ratio).toBe(0.5);
const belowRatio = evaluateRecencyGate(
['2022-12-31', '2023-01-01'],
[0.08, 0.039]
);
expect(belowRatio.gate.pass).toBe(false);
expect(belowRatio.gate.reason).toBe('post_below_ratio_threshold');
const postZero = evaluateRecencyGate(
['2022-12-31', '2023-01-01'],
[0.08, 0]
);
expect(postZero.gate.pass).toBe(false);
expect(postZero.gate.reason).toBe('non_positive_post_mean');
const postNeg = evaluateRecencyGate(
['2022-12-31', '2023-01-01'],
[0.08, -0.02]
);
expect(postNeg.gate.pass).toBe(false);
expect(postNeg.gate.reason).toBe('non_positive_post_mean');
const preNeg = evaluateRecencyGate(
['2022-12-31', '2023-01-01'],
[-0.08, -0.06]
);
expect(preNeg.gate.pass).toBe(false);
expect(preNeg.gate.reason).toBe('non_positive_pre_mean');
expect(preNeg.gate.ratio).toBeNull();
const preZero = evaluateRecencyGate(
['2022-12-31', '2023-01-01'],
[0, 0.05]
);
expect(preZero.gate.pass).toBe(false);
expect(preZero.gate.reason).toBe('non_positive_pre_mean');
const emptyPre = evaluateRecencyGate(['2023-01-01', '2023-01-02'], [0.05, 0.06]);
expect(emptyPre.gate.pass).toBe(false);
expect(emptyPre.gate.reason).toBe('empty_pre_window');
const emptyPost = evaluateRecencyGate(['2022-12-30', '2022-12-31'], [0.05, 0.06]);
expect(emptyPost.gate.pass).toBe(false);
expect(emptyPost.gate.reason).toBe('empty_post_window');
});
test('vaultCutoffDate excludes dates >= cutoff, counts them, and isolates non-vault metrics', () => {
const basePanel: SignalCrossSection[] = [
{
date: '2022-12-30',
ids: [1, 2, 3, 4, 5],
signal: [1, 2, 3, 4, 5],
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05],
},
{
date: '2023-01-03',
ids: [1, 2, 3, 4, 5],
signal: [1, 2, 3, 4, 5],
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.06],
},
];
const withVault: SignalCrossSection[] = [
...basePanel,
// Extreme reversed data at and after vaultCutoffDate
{
date: '2025-06-01',
ids: [1, 2, 3, 4, 5],
signal: [1, 2, 3, 4, 5],
forwardReturn: [100, -100, -200, -300, -400],
},
{
date: '2025-06-02',
ids: [1, 2, 3, 4, 5],
signal: [1, 2, 3, 4, 5],
forwardReturn: [100, -100, -200, -300, -400],
},
];
const resBase = analyzeSignalPanel(basePanel, { vaultCutoffDate: '2025-06-01' });
const resVault = analyzeSignalPanel(withVault, { vaultCutoffDate: '2025-06-01' });
expect(resVault.diagnostics.totalDates).toBe(4);
expect(resVault.diagnostics.eligibleDates).toBe(2);
expect(resVault.diagnostics.vaultExcludedDates).toBe(2);
expect(resVault.recency.vaultExcludedDates).toBe(2);
expect(resVault.dates).toEqual(resBase.dates);
expect(resVault.rankIcSeries).toEqual(resBase.rankIcSeries);
expect(resVault.pearsonIcSeries).toEqual(resBase.pearsonIcSeries);
expect(resVault.quantiles.spreadSeries).toEqual(resBase.quantiles.spreadSeries);
expect(resVault.recency.gate).toEqual(resBase.recency.gate);
const directRecency = evaluateRecencyGate(
['2022-12-31', '2023-01-01', '2025-06-01', '2025-06-02'],
[0.08, 0.06, -0.9, -0.9],
{ vaultCutoffDate: '2025-06-01' }
);
expect(directRecency.vaultExcludedDates).toBe(2);
expect(directRecency.post.count).toBe(1);
expect(directRecency.gate.pass).toBe(true);
});
});
describe('input validation errors', () => {
const validSlice: SignalCrossSection = {
date: '2023-01-03',
ids: [1, 2, 3, 4, 5],
signal: [1, 2, 3, 4, 5],
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05],
};
function expectErrorCode(fn: () => unknown, code: SignalAnalysisError['code']): void {
try {
fn();
throw new Error(`Expected SignalAnalysisError(${code}) to be thrown`);
} catch (err) {
expect(err).toBeInstanceOf(SignalAnalysisError);
expect((err as SignalAnalysisError).code).toBe(code);
}
}
test('throws LENGTH_MISMATCH on mismatched array lengths', () => {
expectErrorCode(
() => crossSectionIc([1, 2, 3], [1, 2]),
'LENGTH_MISMATCH'
);
expectErrorCode(
() =>
analyzeSignalPanel([
{ ...validSlice, ids: [1, 2, 3, 4] },
]),
'LENGTH_MISMATCH'
);
expectErrorCode(
() =>
analyzeSignalPanel([
{ ...validSlice, forwardReturn: [0.01, 0.02] },
]),
'LENGTH_MISMATCH'
);
expectErrorCode(
() => evaluateRecencyGate(['2023-01-01'], [0.01, 0.02]),
'LENGTH_MISMATCH'
);
});
test('throws UNSORTED_DATES and DUPLICATE_DATE on bad date ordering', () => {
expectErrorCode(
() =>
analyzeSignalPanel([
{ ...validSlice, date: '2023-01-04' },
{ ...validSlice, date: '2023-01-03' },
]),
'UNSORTED_DATES'
);
expectErrorCode(
() =>
analyzeSignalPanel([
{ ...validSlice, date: '2023-01-03' },
{ ...validSlice, date: '2023-01-03' },
]),
'DUPLICATE_DATE'
);
expectErrorCode(
() => evaluateRecencyGate(['2023-01-04', '2023-01-03'], [0.01, 0.02]),
'UNSORTED_DATES'
);
expectErrorCode(
() => evaluateRecencyGate(['2023-01-03', '2023-01-03'], [0.01, 0.02]),
'DUPLICATE_DATE'
);
});
test('throws INVALID_DATE on malformed or impossible calendar dates', () => {
for (const badDate of ['2023-02-29', '2023-1-1', '2023-13-01', '2023-04-31', '2023-01-01T00:00:00Z']) {
expectErrorCode(
() => analyzeSignalPanel([{ ...validSlice, date: badDate }]),
'INVALID_DATE'
);
}
expectErrorCode(
() => analyzeSignalPanel([validSlice], { vaultCutoffDate: '2025-02-29' }),
'INVALID_DATE'
);
expectErrorCode(
() => analyzeSignalPanel([validSlice], { recencySplitDate: 'not-a-date' }),
'INVALID_DATE'
);
// Valid leap year date succeeds
const leap = analyzeSignalPanel([{ ...validSlice, date: '2024-02-29' }]);
expect(leap.dates).toEqual(['2024-02-29']);
});
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');
expectErrorCode(() => analyzeSignalPanel([validSlice], { lag: -1 }), 'INVALID_OPTION');
expectErrorCode(() => analyzeSignalPanel([validSlice], { lag: 1.5 }), 'INVALID_OPTION');
expectErrorCode(() => neweyWestMeanTest([1, 2, 3], -1), 'INVALID_OPTION');
expectErrorCode(() => neweyWestMeanTest([1, 2, 3], 0.5), 'INVALID_OPTION');
expectErrorCode(() => analyzeSignalPanel([validSlice], { minCrossSection: 1 }), 'INVALID_OPTION');
expectErrorCode(() => analyzeSignalPanel([validSlice], { minCrossSection: 3.2 }), 'INVALID_OPTION');
expectErrorCode(() => analyzeSignalPanel([validSlice], { recencyMinRatio: 0 }), 'INVALID_OPTION');
expectErrorCode(() => analyzeSignalPanel([validSlice], { recencyMinRatio: Number.NaN }), 'INVALID_OPTION');
});
});