import { describe, expect, test } from 'bun:test'; import * as rootExports from '@stock-bot/calculations'; import * as analyticsExports from '@stock-bot/calculations/analytics'; import { DSR_VALIDATION_GATE, EULER_MASCHERONI, deflatedSharpeRatio, effectiveIndependentTrials, inverseNormalCdf, normalCdf, passesDsrGate, trialMoments, } 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 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); }; } describe('deflated-sharpe exports', () => { test('both root and analytics entrypoints export the complete DSR surface', () => { const names = [ 'DSR_VALIDATION_GATE', 'EULER_MASCHERONI', 'normalCdf', 'inverseNormalCdf', 'trialMoments', 'effectiveIndependentTrials', 'deflatedSharpeRatio', 'passesDsrGate', ] as const; for (const name of names) { expect(rootExports[name]).toBeDefined(); expect(analyticsExports[name]).toBe(rootExports[name]); } expect(DSR_VALIDATION_GATE).toBe(0.95); expect(EULER_MASCHERONI).toBeCloseTo(0.5772156649015329, 15); }); }); describe('normalCdf and inverseNormalCdf', () => { test('matches known reference values across center and tails', () => { expect(normalCdf(0)).toBe(0.5); expect(normalCdf(1.959963984540054)).toBeCloseTo(0.975, 12); expect(normalCdf(-1.959963984540054)).toBeCloseTo(0.025, 12); expect(normalCdf(1)).toBeCloseTo(0.8413447460685429, 12); expect(normalCdf(-1)).toBeCloseTo(0.15865525393145707, 12); // Extreme tails: Phi(-6) = 9.86587645037698e-10 expect(normalCdf(-6)).toBeCloseTo(9.86587645037698e-10, 15); expect(normalCdf(6)).toBeCloseTo(1 - 9.86587645037698e-10, 15); expect(inverseNormalCdf(0.5)).toBe(0); expect(inverseNormalCdf(0.975)).toBeCloseTo(1.959963984540054, 12); expect(inverseNormalCdf(0.025)).toBeCloseTo(-1.959963984540054, 12); expect(inverseNormalCdf(0.99)).toBeCloseTo(2.3263478740408408, 12); expect(inverseNormalCdf(1e-12)).toBeCloseTo(-7.034483825301132, 12); expect(inverseNormalCdf(1 - 1e-12)).toBeCloseTo(7.034486910047835, 9); }); test('satisfies symmetry and round-trip accuracy <= 1e-9 across [1e-12, 1 - 1e-12]', () => { for (const x of [0, 0.1, 0.45, 1, 2.5, 4, 5.5, 6.5]) { const pos = normalCdf(x); const neg = normalCdf(-x); expect(pos).not.toBeNull(); expect(neg).not.toBeNull(); expect((pos as number) + (neg as number)).toBeCloseTo(1, 14); } const probabilities = [ 1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 0.001, 0.025, 0.1, 0.25, 0.5, 0.75, 0.9, 0.975, 0.999, 1 - 1e-4, 1 - 1e-6, 1 - 1e-8, 1 - 1e-10, 1 - 1e-12, ]; for (const p of probabilities) { const z = inverseNormalCdf(p); expect(z).not.toBeNull(); const roundTrip = normalCdf(z as number); expect(roundTrip).not.toBeNull(); expect(Math.abs((roundTrip as number) - p)).toBeLessThanOrEqual(1e-9); if (p < 0.5) { // Use exact IEEE-754 complement pairs (pExact + pComp === 1) so // 1 - (1 - p) rounding at p = 1e-12 does not perturb the input. const pComp = 1 - p; const pExact = 1 - pComp; const zExact = inverseNormalCdf(pExact); const zSym = inverseNormalCdf(pComp); expect(zExact).not.toBeNull(); expect(zSym).not.toBeNull(); expect(Math.abs((zExact as number) + (zSym as number))).toBeLessThanOrEqual(1e-12); } } }); test('returns null without throwing on invalid inputs', () => { for (const badX of [Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]) { expect(normalCdf(badX)).toBeNull(); } for (const badP of [ -1, -1e-15, 0, 1, 1 + 1e-15, 2, Number.NaN, Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY, ]) { expect(inverseNormalCdf(badP)).toBeNull(); } }); }); describe('trialMoments', () => { test('computes unannualized daily Sharpe, plugin skewness, and Pearson kurtosis', () => { // Symmetric 4-point series: [-1, 0, 2, 3] // mean = 1.0 // deviations = [-2, -1, 1, 2] // sum2 = 10 -> sampleVar = 10/3, sampleStd = sqrt(10/3) // sharpeUnann = 1 / sqrt(10/3) (unannualized, no sqrt(252)) // m2 = 10/4 = 2.5, m3 = 0 -> skewness = 0 // sum4 = 16 + 1 + 1 + 16 = 34 -> m4 = 8.5 -> kurtosis = 8.5 / 6.25 = 1.36 const moments = trialMoments([-1, 0, 2, 3]); expect(moments).not.toBeNull(); expect(moments?.nObs).toBe(4); expect(moments?.sharpeUnann).toBeCloseTo(1 / Math.sqrt(10 / 3), 12); expect(moments?.skewness).toBeCloseTo(0, 12); expect(moments?.kurtosis).toBeCloseTo(1.36, 12); // Daily risk-free rate subtracts directly from mean before dividing by sampleStd const excess = trialMoments([-1, 0, 2, 3], 0.5); expect(excess?.sharpeUnann).toBeCloseTo(0.5 / Math.sqrt(10 / 3), 12); }); test('produces Pearson kurtosis near 3.0 on standard normal draws and supports nObs = 2 and 3', () => { const randn = createStandardNormal(42); const normalSample = Array.from({ length: 10000 }, () => randn()); const moments = trialMoments(normalSample); expect(moments).not.toBeNull(); expect(moments?.nObs).toBe(10000); expect(Math.abs(moments?.skewness as number)).toBeLessThan(0.1); expect(moments?.kurtosis as number).toBeGreaterThan(2.85); expect(moments?.kurtosis as number).toBeLessThan(3.15); // nObs = 2 (matching trial_ledger CHECK n_obs >= 2) const two = trialMoments([0.01, 0.03]); expect(two).not.toBeNull(); expect(two?.nObs).toBe(2); expect(two?.sharpeUnann).toBeCloseTo(0.02 / Math.sqrt(0.0002), 12); expect(two?.skewness).toBeCloseTo(0, 12); expect(two?.kurtosis).toBeCloseTo(1, 12); // nObs = 3 const three = trialMoments([0.01, 0.02, 0.06]); expect(three).not.toBeNull(); expect(three?.nObs).toBe(3); }); test('filters non-finite values and returns null on degenerate inputs without throwing', () => { const withGarbage = [Number.NaN, -1, Number.POSITIVE_INFINITY, 0, 2, Number.NEGATIVE_INFINITY, 3]; const filtered = trialMoments(withGarbage); const clean = trialMoments([-1, 0, 2, 3]); expect(filtered).toEqual(clean); // Sparse arrays const sparse = new Array(5); sparse[1] = 0.01; sparse[3] = 0.03; expect(trialMoments(sparse)).toEqual(trialMoments([0.01, 0.03])); // Degenerate inputs -> null expect(trialMoments([])).toBeNull(); expect(trialMoments([0.01])).toBeNull(); expect(trialMoments([0.01, Number.NaN, Number.POSITIVE_INFINITY])).toBeNull(); expect(trialMoments([0.1, 0.1, 0.1])).toBeNull(); expect(trialMoments([0, 0, 0, 0])).toBeNull(); expect(trialMoments(new Array(4))).toBeNull(); expect(trialMoments([0.01, 0.02], Number.NaN)).toBeNull(); expect(trialMoments([0.01, 0.02], Number.POSITIVE_INFINITY)).toBeNull(); }); }); describe('effectiveIndependentTrials', () => { test('matches doc example: two series with rho ~= 0.97 yield nHat ~= 1.03', () => { const randn = createStandardNormal(101); const n = 5000; const rhoTarget = 0.97; const noiseScale = Math.sqrt(1 - rhoTarget * rhoTarget); const s1: number[] = new Array(n); const s2: number[] = new Array(n); for (let t = 0; t < n; t++) { const z1 = randn(); const z2 = randn(); s1[t] = z1; s2[t] = rhoTarget * z1 + noiseScale * z2; } const result = effectiveIndependentTrials([s1, s2]); expect(result.k).toBe(2); expect(result.pairsUsed).toBe(1); expect(result.pairsSkipped).toBe(0); expect(result.meanCorrelation).not.toBeNull(); expect(result.meanCorrelation as number).toBeCloseTo(0.97, 2); expect(result.nHat).toBeCloseTo(1.03, 2); }); test('matches doc example: 100 near-orthogonal seeded series yield nHat ~= 100', () => { const randn = createStandardNormal(2026); const k = 100; const n = 2520; const seriesList: number[][] = Array.from({ length: k }, () => Array.from({ length: n }, () => randn()) ); const result = effectiveIndependentTrials(seriesList); expect(result.k).toBe(100); expect(result.pairsUsed).toBe((100 * 99) / 2); expect(result.pairsSkipped).toBe(0); expect(result.meanCorrelation).not.toBeNull(); expect(Math.abs(result.meanCorrelation as number)).toBeLessThan(0.01); // Tolerance: with K=100 independent draws of T=2520, std(rho_bar) ~ 0.0003, // so nHat sits within [99.0, 100.0]. expect(result.nHat).toBeGreaterThanOrEqual(99.0); expect(result.nHat).toBeLessThanOrEqual(100.0); }); test('handles identical series, negative correlation clamping, K <= 1, and large-offset stability', () => { const base = [1, 2, 4, 3, 5, 7, 6]; const identical = effectiveIndependentTrials([base, base, base]); expect(identical.pairsUsed).toBe(3); expect(identical.pairsSkipped).toBe(0); expect(identical.meanCorrelation).toBeCloseTo(1, 12); expect(identical.nHat).toBeCloseTo(1, 12); // Negatively correlated pair -> rho_bar = -1 -> clamped to nHat = K = 2 const opposite = base.map(v => -v); const neg = effectiveIndependentTrials([base, opposite]); expect(neg.meanCorrelation).toBeCloseTo(-1, 12); expect(neg.nHat).toBe(2); // K = 0 and K = 1 expect(effectiveIndependentTrials([])).toEqual({ k: 0, pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1, }); expect(effectiveIndependentTrials([base])).toEqual({ k: 1, pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1, }); // Shifted large-offset series verify centered correlation avoids catastrophic cancellation const offset = 1e9; const shiftedA = base.map(v => offset + v); const shiftedB = base.map(v => offset + 2 * v + 5); const shifted = effectiveIndependentTrials([shiftedA, shiftedB]); expect(shifted.meanCorrelation).toBeCloseTo(1, 12); expect(shifted.nHat).toBeCloseTo(1, 12); }); test('skips degenerate pairs without diluting meanCorrelation with synthetic zeros', () => { const a = [1, 2, 3, 4, 5]; const b = [2, 4, 6, 8, 10]; // rho(a, b) = 1 const constant = [0.1, 0.1, 0.1, 0.1, 0.1]; // constant -> skipped against both a and b const withConstant = effectiveIndependentTrials([a, b, constant]); expect(withConstant.k).toBe(3); expect(withConstant.pairsUsed).toBe(1); expect(withConstant.pairsSkipped).toBe(2); // If skipped pairs were treated as rho = 0, meanCorrelation would be 1/3 instead of 1. expect(withConstant.meanCorrelation).toBeCloseTo(1, 12); expect(withConstant.nHat).toBeCloseTo(1, 12); // Unequal lengths and NaN gaps: overlap on indices 1, 2, 4 -> (2,4), (3,6), (5,10) -> rho = 1 const gappedA = [Number.NaN, 2, 3, Number.POSITIVE_INFINITY, 5, 99, 100]; const gappedB = [1, 4, 6, 8, 10]; const gapped = effectiveIndependentTrials([gappedA, gappedB]); expect(gapped.pairsUsed).toBe(1); expect(gapped.pairsSkipped).toBe(0); expect(gapped.meanCorrelation).toBeCloseTo(1, 12); // Overlap < 2 finite points -> all pairs skipped -> conservative nHat = K const disjointA = [1, Number.NaN, Number.NaN]; const disjointB = [Number.NaN, 2, 3]; const allSkipped = effectiveIndependentTrials([disjointA, disjointB]); expect(allSkipped).toEqual({ k: 2, pairsUsed: 0, pairsSkipped: 1, meanCorrelation: null, nHat: 2, }); }); }); describe('deflatedSharpeRatio and passesDsrGate', () => { test('matches hand-computed golden DSR vector and penalizes negative skew and excess kurtosis', () => { // Hand-computed golden vector: // sharpeUnann = 0.15, nObs = 1000 (T - 1 = 999), nHat = 100 // clusterSharpes = [-0.02, 0.0, 0.02, 0.04, 0.06] // mean = 0.02, sum((x - mean)^2) = 0.004, sampleVar = 0.001 // sigmaSr = sqrt(0.001) = 0.03162277660168379 // z1 = Phi^-1(1 - 1/100) = Phi^-1(0.99) = 2.3263478740408408 // z2 = Phi^-1(1 - 1/(100 * e)) = Phi^-1(0.9963212055882856) = 2.680210444966887 // bracket = (1 - 0.5772156649015329) * 2.3263478740408408 // + 0.5772156649015329 * 2.680210444966887 // = 2.5306028932016846 // sr0 = 0.03162277660168379 * 2.5306028932016846 = 0.08002468995929155 // // Normal case (skewness = 0, kurtosis = 3): // radicand = (1 - 0 + ((3 - 1)/4) * 0.15^2) / 999 = 1.01125 / 999 // SE = sqrt(1.01125 / 999) = 0.031816069245937065 // z = (0.15 - 0.08002468995929155) / 0.031816069245937065 = 2.1993700575697134 // DSR = Phi(2.1993700575697134) = 0.9860741900352264 const clusterSharpes = [-0.02, 0.0, 0.02, 0.04, 0.06]; const normalCase = deflatedSharpeRatio({ sharpeUnann: 0.15, nObs: 1000, skewness: 0, kurtosis: 3, nHat: 100, clusterSharpes, }); expect(normalCase).not.toBeNull(); expect(normalCase?.sr0).toBeCloseTo(0.08002468995929155, 10); expect(normalCase?.standardError).toBeCloseTo(0.031816069245937065, 10); expect(normalCase?.dsr).toBeCloseTo(0.9860741900352264, 10); expect(passesDsrGate(normalCase?.dsr ?? null)).toBe(true); // Non-normal case (skewness = -1.5, kurtosis = 7): // radicand = (1 - (-1.5)*0.15 + ((7 - 1)/4) * 0.15^2) / 999 = 1.25875 / 999 // SE = sqrt(1.25875 / 999) = 0.035496619698360155 // z = (0.15 - 0.08002468995929155) / 0.035496619698360155 = 1.9713232028632037 // DSR = Phi(1.9713232028632037) = 0.9756565405046566 const nonNormalCase = deflatedSharpeRatio({ sharpeUnann: 0.15, nObs: 1000, skewness: -1.5, kurtosis: 7, nHat: 100, clusterSharpes, }); expect(nonNormalCase).not.toBeNull(); expect(nonNormalCase?.sr0).toBeCloseTo(normalCase?.sr0 as number, 12); expect(nonNormalCase?.standardError).toBeCloseTo(0.035496619698360155, 10); expect(nonNormalCase?.dsr).toBeCloseTo(0.9756565405046566, 10); expect(nonNormalCase?.standardError as number).toBeGreaterThan( normalCase?.standardError as number ); expect(nonNormalCase?.dsr as number).toBeLessThan(normalCase?.dsr as number); }); test('is monotonically non-increasing as nHat grows (including fractional 1 < nHat < 1.3)', () => { const clusterSharpes = [-0.02, 0.0, 0.02, 0.04, 0.06]; const nHatValues = [1, 1.03, 1.2, 2, 10, 100, 1000]; let prevSr0 = -1; let prevDsr = 2; for (const nHat of nHatValues) { const res = deflatedSharpeRatio({ sharpeUnann: 0.15, nObs: 1000, skewness: -0.5, kurtosis: 4, nHat, clusterSharpes, }); expect(res).not.toBeNull(); expect(res?.sr0 as number).toBeGreaterThanOrEqual(0); expect(res?.sr0 as number).toBeGreaterThanOrEqual(prevSr0); expect(res?.dsr as number).toBeLessThanOrEqual(prevDsr); prevSr0 = res?.sr0 as number; prevDsr = res?.dsr as number; } }); test('handles defined edge cases and returns null on invalid inputs without throwing', () => { const base = { sharpeUnann: 0.1, nObs: 252, skewness: 0, kurtosis: 3, nHat: 10, clusterSharpes: [0.02, 0.05, 0.1], }; // nHat = 1 -> sr0 = 0 expect(deflatedSharpeRatio({ ...base, nHat: 1 })?.sr0).toBe(0); // < 2 clusterSharpes -> sr0 = 0 expect(deflatedSharpeRatio({ ...base, clusterSharpes: [] })?.sr0).toBe(0); expect(deflatedSharpeRatio({ ...base, clusterSharpes: [0.1] })?.sr0).toBe(0); // Zero-variance clusterSharpes -> sr0 = 0 expect(deflatedSharpeRatio({ ...base, clusterSharpes: [0.1, 0.1, 0.1] })?.sr0).toBe(0); // Invalid inputs -> null expect(deflatedSharpeRatio({ ...base, nObs: 1 })).toBeNull(); expect(deflatedSharpeRatio({ ...base, nObs: 0 })).toBeNull(); expect(deflatedSharpeRatio({ ...base, nHat: 0.99 })).toBeNull(); expect(deflatedSharpeRatio({ ...base, sharpeUnann: Number.NaN })).toBeNull(); expect(deflatedSharpeRatio({ ...base, skewness: Number.POSITIVE_INFINITY })).toBeNull(); expect(deflatedSharpeRatio({ ...base, kurtosis: Number.NaN })).toBeNull(); expect(deflatedSharpeRatio({ ...base, clusterSharpes: [0.02, Number.NaN, 0.1] })).toBeNull(); expect(deflatedSharpeRatio({ ...base, clusterSharpes: new Array(3) })).toBeNull(); // Non-positive SE radicand -> null: // 1 - skewness * sr + ((kurtosis - 1)/4) * sr^2 = 1 - 10*0.5 + 0 = -4 <= 0 expect( deflatedSharpeRatio({ ...base, sharpeUnann: 0.5, skewness: 10, kurtosis: 1, }) ).toBeNull(); }); test('passesDsrGate enforces DSR >= 0.95 and rejects null or non-finite values', () => { expect(passesDsrGate(null)).toBe(false); expect(passesDsrGate(Number.NaN)).toBe(false); expect(passesDsrGate(Number.POSITIVE_INFINITY)).toBe(false); expect(passesDsrGate(0.9499)).toBe(false); expect(passesDsrGate(0.95)).toBe(true); expect(passesDsrGate(0.99)).toBe(true); expect(passesDsrGate(0.9, 0.9)).toBe(true); expect(passesDsrGate(0.95, Number.NaN)).toBe(false); }); });