stock-bot/libs/calculations/test/deflated-sharpe-qa.test.ts
2026-11-28 00:50:20 -05:00

252 lines
9.6 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import {
deflatedSharpeRatio,
effectiveIndependentTrials,
inverseNormalCdf,
normalCdf,
trialMoments,
} from '@stock-bot/calculations';
// Reference values below were produced independently with CPython 3 stdlib
// (`math.erfc`, `statistics.NormalDist`, `statistics.stdev`, `statistics.correlation`),
// not by the module under test.
describe('deflated-sharpe QA: independent reference values', () => {
test('normalCdf agrees with libm erfc to 1e-15 at Cody branch boundaries and deep tails', () => {
const cases: readonly (readonly [number, number])[] = [
// y = |x|/sqrt(2) = 0.46875 (erf/erfc branch switch)
[-0.46875 * Math.SQRT2, 0.253693263391031],
// y = 4.0 (rational/asymptotic branch switch)
[-4 * Math.SQRT2, 7.70862895014001e-9],
[-8, 6.220960574271819e-16],
[-10, 7.619853024160593e-24],
];
for (const [x, expected] of cases) {
const value = normalCdf(x);
expect(value).not.toBeNull();
expect(Math.abs((value as number) - expected)).toBeLessThanOrEqual(1e-15);
// Relative accuracy in the lower tail matters for tiny p-values.
expect(Math.abs((value as number) - expected) / expected).toBeLessThan(1e-12);
}
// Underflow is a valid probability, not null.
expect(normalCdf(-40)).toBe(0);
expect(normalCdf(40)).toBe(1);
});
test('normalCdf is monotone non-decreasing across all approximation branches', () => {
let previous = -1;
for (let x = -12; x <= 12; x += 0.001) {
const value = normalCdf(x) as number;
expect(value).toBeGreaterThanOrEqual(previous);
previous = value;
}
});
test('inverseNormalCdf matches statistics.NormalDist.inv_cdf on central and tail regions', () => {
const cases: readonly (readonly [number, number])[] = [
[0.075, -1.4395314709384557], // central region boundary |q| <= 0.425
[0.074, -1.4466320671589785], // just into tail region, r <= 5
[1e-11, -6.706023155495136], // r > 5 branch
[0.96, 1.7506860712521695],
];
for (const [p, expected] of cases) {
expect(inverseNormalCdf(p) as number).toBeCloseTo(expected, 12);
}
});
test('trialMoments matches stdlib sample Sharpe and plugin skewness / Pearson kurtosis', () => {
const series = [0.012, -0.004, 0.007, -0.021, 0.015, 0.003, -0.009, 0.031, -0.002, 0.006];
const moments = trialMoments(series);
expect(moments).not.toBeNull();
expect(moments?.nObs).toBe(10);
expect(moments?.sharpeUnann as number).toBeCloseTo(0.2671027396298783, 12);
expect(moments?.skewness as number).toBeCloseTo(0.16688842823043712, 12);
expect(moments?.kurtosis as number).toBeCloseTo(2.9464511067020083, 12);
// Plugin moments obey Pearson's inequality kurtosis >= skew^2 + 1.
const skew = moments?.skewness as number;
expect(moments?.kurtosis as number).toBeGreaterThanOrEqual(skew * skew + 1);
});
test('effectiveIndependentTrials mean correlation matches stdlib pairwise Pearson average', () => {
const a = [0.3, -1.2, 0.8, 2.1, -0.4, 0.0, 1.1, -0.7];
const b = [0.1, -0.9, 1.4, 1.0, -0.2, 0.5, 0.2, -1.3];
const c = [-0.5, 0.4, 0.2, -1.1, 0.9, 0.3, -0.6, 0.7];
// rho_ab = 0.7923790625364798, rho_ac = -0.840261348120643, rho_bc = -0.526175182297041
// rho_bar = -0.19135248929373472 (< 0, so clamped) -> nHat = K = 3
const result = effectiveIndependentTrials([a, b, c]);
expect(result.pairsUsed).toBe(3);
expect(result.pairsSkipped).toBe(0);
expect(result.meanCorrelation as number).toBeCloseTo(-0.19135248929373472, 12);
expect(result.nHat).toBe(3);
});
test('deflatedSharpeRatio matches an independently computed non-normal vector', () => {
// sigma_SR = stdev([0.01,0.03,0.05,0.02,0.07,0.04]) = 0.02160246899469287
// SR0 = sigma_SR * [(1-g)*inv(1-1/25) + g*inv(1-1/(25e))] = 0.043143368521767964
// SE = sqrt((1 + 0.8*0.08 + (5/4)*0.08^2) / 499) = 0.04634972052975479
// DSR = Phi((0.08 - SR0)/SE) = 0.7867472337253661
const result = deflatedSharpeRatio({
sharpeUnann: 0.08,
nObs: 500,
skewness: -0.8,
kurtosis: 6,
nHat: 25,
clusterSharpes: [0.01, 0.03, 0.05, 0.02, 0.07, 0.04],
});
expect(result).not.toBeNull();
expect(result?.sr0 as number).toBeCloseTo(0.043143368521767964, 12);
expect(result?.standardError as number).toBeCloseTo(0.04634972052975479, 12);
expect(result?.dsr as number).toBeCloseTo(0.7867472337253661, 12);
});
});
describe('deflated-sharpe QA: path consistency and degenerate inputs', () => {
test('fast (equal-length, all-finite) and general (unequal-length) paths give the same rho', () => {
const a = [0.3, -1.2, 0.8, 2.1, -0.4, 0.0, 1.1, -0.7];
const b = [0.1, -0.9, 1.4, 1.0, -0.2, 0.5, 0.2, -1.3];
const fast = effectiveIndependentTrials([a, b]);
// A trailing extra point on one side forces the general path over the same overlap.
const general = effectiveIndependentTrials([[...a, 42], b]);
// A NaN in one series forces the general path while keeping lengths equal.
const withNaN = effectiveIndependentTrials([
[...a, Number.NaN],
[...b, 1],
]);
expect(general.meanCorrelation as number).toBeCloseTo(fast.meanCorrelation as number, 12);
expect(withNaN.meanCorrelation as number).toBeCloseTo(fast.meanCorrelation as number, 12);
expect(fast.meanCorrelation as number).toBeCloseTo(0.7923790625364798, 12);
});
test('a series constant only on the overlap is skipped even if non-constant overall', () => {
const a = [1, 1, 1, 9];
const b = [3, 4, 5];
const result = effectiveIndependentTrials([a, b]);
expect(result).toEqual({ k: 2, pairsUsed: 0, pairsSkipped: 1, meanCorrelation: null, nHat: 2 });
});
test('empty member series are skipped, not counted as zero correlation', () => {
const a = [1, 2, 3, 4];
const b = [2, 3, 5, 9];
const result = effectiveIndependentTrials([a, b, []]);
expect(result.pairsUsed).toBe(1);
expect(result.pairsSkipped).toBe(2);
expect(result.meanCorrelation as number).toBeGreaterThan(0.9);
});
test('overflowing magnitudes return null / skip instead of throwing', () => {
const huge = [1.7e308, 1.7e308, -1];
expect(() => trialMoments(huge)).not.toThrow();
expect(trialMoments(huge)).toBeNull();
expect(() => effectiveIndependentTrials([huge, [1, 2, 3]])).not.toThrow();
expect(effectiveIndependentTrials([huge, [1, 2, 3]]).pairsUsed).toBe(0);
expect(
deflatedSharpeRatio({
sharpeUnann: 0.1,
nObs: 252,
skewness: 0,
kurtosis: 3,
nHat: 2,
clusterSharpes: [1e308, -1e308],
})
).toBeNull();
});
test('duplicate series feed DSR exactly like nHat = 1 despite rounding in rho', () => {
// Identical series can produce rho = 1 - ulp, so nHat lands a hair above 1;
// the SR0 floor must make the DSR identical to the nHat = 1 case.
const series = [1, 2, 4, 3, 5, 7, 6];
const { nHat } = effectiveIndependentTrials([series, series, series]);
expect(nHat).toBeGreaterThanOrEqual(1);
expect(nHat).toBeLessThan(1 + 1e-12);
const base = {
sharpeUnann: 0.1,
nObs: 252,
skewness: -0.3,
kurtosis: 4,
clusterSharpes: [0.02, 0.05, 0.1],
};
const fromDuplicates = deflatedSharpeRatio({ ...base, nHat });
const exact = deflatedSharpeRatio({ ...base, nHat: 1 });
expect(fromDuplicates).toEqual(exact);
expect(fromDuplicates?.sr0).toBe(0);
});
test('DSR rises with T and with SR, and falls as cluster Sharpe dispersion grows', () => {
const base = {
sharpeUnann: 0.08,
nObs: 500,
skewness: 0,
kurtosis: 3,
nHat: 20,
clusterSharpes: [0.01, 0.03, 0.05],
};
const dsr = (overrides: Partial<typeof base>) =>
deflatedSharpeRatio({ ...base, ...overrides })?.dsr as number;
expect(dsr({ nObs: 2000 })).toBeGreaterThan(dsr({ nObs: 500 }));
expect(dsr({ sharpeUnann: 0.12 })).toBeGreaterThan(dsr({}));
expect(dsr({ clusterSharpes: [0.0, 0.03, 0.06] })).toBeLessThan(dsr({}));
});
test('SR below SR0 yields DSR < 0.5; zero SR with zero SR0 yields exactly 0.5', () => {
const below = deflatedSharpeRatio({
sharpeUnann: 0.01,
nObs: 500,
skewness: 0,
kurtosis: 3,
nHat: 50,
clusterSharpes: [0.0, 0.05, 0.1],
});
expect(below?.dsr as number).toBeLessThan(0.5);
const atZero = deflatedSharpeRatio({
sharpeUnann: 0,
nObs: 500,
skewness: 0,
kurtosis: 3,
nHat: 1,
clusterSharpes: [],
});
expect(atZero?.dsr).toBe(0.5);
});
test('nHat so large that 1 - 1/nHat rounds to 1 returns null rather than a bogus SR0', () => {
expect(
deflatedSharpeRatio({
sharpeUnann: 0.1,
nObs: 252,
skewness: 0,
kurtosis: 3,
nHat: 1e17,
clusterSharpes: [0, 0.1],
})
).toBeNull();
expect(
deflatedSharpeRatio({
sharpeUnann: 0.1,
nObs: 252,
skewness: 0,
kurtosis: 3,
nHat: Number.POSITIVE_INFINITY,
clusterSharpes: [0, 0.1],
})
).toBeNull();
});
test('inputs are not mutated', () => {
const series = [0.01, Number.NaN, -0.02, 0.03];
const snapshot = [...series];
const cluster = [0.01, 0.02, 0.04];
const clusterSnapshot = [...cluster];
trialMoments(series);
effectiveIndependentTrials([series, [0.02, 0.01, 0.0, 0.05]]);
deflatedSharpeRatio({
sharpeUnann: 0.1,
nObs: 100,
skewness: 0,
kurtosis: 3,
nHat: 3,
clusterSharpes: cluster,
});
expect(series).toEqual(snapshot);
expect(cluster).toEqual(clusterSnapshot);
});
});