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:
parent
306d324b8d
commit
659cd042f6
6 changed files with 2169 additions and 1 deletions
680
libs/calculations/test/signal-analysis.test.ts
Normal file
680
libs/calculations/test/signal-analysis.test.ts
Normal 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');
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue