From 70a371f3b0831c045823379569c3511a181ec97b Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 00:44:29 -0500 Subject: [PATCH] =?UTF-8?q?T-80:=20M1.3a=20(re-land)=20=E2=80=94=20Canonic?= =?UTF-8?q?al=20Deflated=20Sharpe=20Ratio=20+=20effective-trials=20(N?= =?UTF-8?q?=CC=82)=20math=20in=20`@stock-bot/calculations`=20(missing=20fr?= =?UTF-8?q?om=20`dev`)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/calculations/README.md | 15 + .../scripts/benchmark-deflated-sharpe.ts | 111 +++ .../src/analytics/deflated-sharpe.ts | 662 ++++++++++++++++++ libs/calculations/src/analytics/index.ts | 16 + libs/calculations/src/index.ts | 16 + .../calculations/test/deflated-sharpe.test.ts | 478 +++++++++++++ 6 files changed, 1298 insertions(+) create mode 100644 libs/calculations/scripts/benchmark-deflated-sharpe.ts create mode 100644 libs/calculations/src/analytics/deflated-sharpe.ts create mode 100644 libs/calculations/test/deflated-sharpe.test.ts diff --git a/libs/calculations/README.md b/libs/calculations/README.md index d4a28db7..b999c1d1 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -52,6 +52,21 @@ const risk = returnStatistics(returns); and downside deviation uses full-series RMS. Trade holding periods are minutes. Persisted strategy versions and execution/checkpoint behavior are unchanged. The legacy Kelly/leverage 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. + +## Benchmark + +Run the fixed-seed DSR + effective-trials benchmark (`K = 500` trials × `2,520` daily +observations, `124,750` pairs): + +```sh +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`. 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 diff --git a/libs/calculations/scripts/benchmark-deflated-sharpe.ts b/libs/calculations/scripts/benchmark-deflated-sharpe.ts new file mode 100644 index 00000000..20918fa9 --- /dev/null +++ b/libs/calculations/scripts/benchmark-deflated-sharpe.ts @@ -0,0 +1,111 @@ +import { + deflatedSharpeRatio, + effectiveIndependentTrials, + trialMoments, +} from '../src/analytics/deflated-sharpe'; + +const SEED = 20260401; +const K = 500; +const N_OBS = 2520; + +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); + }; +} + +// Generate K=500 synthetic daily return series of length T=2,520 with a mild common factor +// so pairwise correlations are realistic and non-degenerate. +const randn = createStandardNormal(SEED); +const marketFactor = new Float64Array(N_OBS); +for (let t = 0; t < N_OBS; t++) { + marketFactor[t] = 0.0003 + 0.01 * randn(); +} + +const seriesList: number[][] = new Array(K); +for (let i = 0; i < K; i++) { + const beta = 0.25 + (i % 10) * 0.02; + const alpha = ((i % 25) - 12) * 0.00004; + const series: number[] = new Array(N_OBS); + for (let t = 0; t < N_OBS; t++) { + series[t] = alpha + beta * (marketFactor[t] as number) + 0.012 * randn(); + } + seriesList[i] = series; +} + +const started = performance.now(); + +const momentsList = new Array(K); +const clusterSharpes: number[] = new Array(K); +for (let i = 0; i < K; i++) { + const m = trialMoments(seriesList[i] as number[]); + if (m === null) { + throw new Error(`Unexpected null trialMoments at trial ${i}`); + } + momentsList[i] = m; + clusterSharpes[i] = m.sharpeUnann; +} + +const eff = effectiveIndependentTrials(seriesList); + +let passedCount = 0; +for (let i = 0; i < K; i++) { + const m = momentsList[i]; + const res = deflatedSharpeRatio({ + sharpeUnann: m.sharpeUnann, + nObs: m.nObs, + skewness: m.skewness, + kurtosis: m.kurtosis, + nHat: eff.nHat, + clusterSharpes, + }); + if (res !== null && res.dsr >= 0.95) { + passedCount++; + } +} + +const elapsedMs = performance.now() - started; +const pairsPerSec = eff.pairsUsed / (elapsedMs / 1000); + +console.log( + JSON.stringify( + { + seed: SEED, + k: K, + nObs: N_OBS, + pairsUsed: eff.pairsUsed, + meanCorrelation: Number((eff.meanCorrelation ?? 0).toFixed(6)), + nHat: Number(eff.nHat.toFixed(4)), + passedDsrGate: passedCount, + elapsedMs: Number(elapsedMs.toFixed(2)), + pairsPerSec: Math.round(pairsPerSec), + }, + null, + 2 + ) +); diff --git a/libs/calculations/src/analytics/deflated-sharpe.ts b/libs/calculations/src/analytics/deflated-sharpe.ts new file mode 100644 index 00000000..4b488bc0 --- /dev/null +++ b/libs/calculations/src/analytics/deflated-sharpe.ts @@ -0,0 +1,662 @@ +import { mean, sampleDeviation } from './return-statistics'; + +/** + * Canonical Deflated Sharpe Ratio (DSR) and effective independent trials (N-hat) + * math per `design/VALIDATION-AND-RIGOR.md` §2.B and §2.C (Bailey & López de Prado). + * + * Pure stateless math: zero I/O, zero wall-clock or random calls, never throws on + * degenerate numeric input (returns `null` when a statistic is undefined). + * + * Local benchmark (fixed seed `20260401`, `K = 500` trials x `2,520` daily observations, + * `124,750` pairs, covering `trialMoments` + `effectiveIndependentTrials` + `deflatedSharpeRatio` + * for all 500 trials): + * - Command: `bun run libs/calculations/scripts/benchmark-deflated-sharpe.ts` + * - Observed (Bun 1.2.16, 2 runs): `150.18 ms` (`830,660 pairs/s`) and `159.79 ms` (`780,707 pairs/s`). + */ + +/** Euler-Mascheroni constant (gamma). */ +export const EULER_MASCHERONI = 0.5772156649015329; + +/** Canonical Candidate -> Validated DSR threshold (`DSR >= 0.95`). */ +export const DSR_VALIDATION_GATE = 0.95; + +/** + * Per-trial daily return or IC moments matching `trial_ledger` columns. + * + * - `nObs`: count of finite observations used (`>= 2`). + * - `sharpeUnann`: unannualized daily Sharpe `(mean - dailyRiskFree) / sampleStd` + * using sample standard deviation (`n - 1` degrees of freedom). + * - `skewness`: plugin third standardized central moment `m3 / m2^(3/2)`, where + * `m_k = (1/n) * sum((x_i - mean)^k)`. Defined for all `nObs >= 2`. + * - `kurtosis`: plugin Pearson fourth standardized central moment `m4 / m2^2` + * (normal distribution = `3.0`, not excess kurtosis). Defined for all `nObs >= 2` + * and always satisfies `kurtosis >= skewness^2 + 1 >= 1`. + */ +export interface TrialMoments { + readonly nObs: number; + readonly sharpeUnann: number; + readonly skewness: number; + readonly kurtosis: number; +} + +/** + * Effective independent trials (`nHat`) computed from pairwise overlapping + * Pearson correlations across `k` trial series in a relatedness cluster. + */ +export interface EffectiveTrialsResult { + readonly k: number; + readonly pairsUsed: number; + readonly pairsSkipped: number; + readonly meanCorrelation: number | null; + readonly nHat: number; +} + +/** Inputs for the non-normal Deflated Sharpe Ratio calculation. */ +export interface DeflatedSharpeInput { + readonly sharpeUnann: number; + readonly nObs: number; + readonly skewness: number; + readonly kurtosis: number; + readonly nHat: number; + readonly clusterSharpes: readonly number[]; +} + +/** Output of the non-normal Deflated Sharpe Ratio calculation. */ +export interface DeflatedSharpeResult { + readonly sr0: number; + readonly standardError: number; + readonly dsr: number; +} + +const INV_SQRT_PI = 0.5641895835477563; + +// Cody (1969) rational Chebyshev coefficients for erf/erfc (~1e-15 accuracy). +const ERF_A0 = 3.1611237438705655; +const ERF_A1 = 113.86415415105016; +const ERF_A2 = 377.485237685302; +const ERF_A3 = 3209.3775891384694; +const ERF_A4 = 0.18577770618460315; + +const ERF_B0 = 23.601290952344122; +const ERF_B1 = 244.02463793444417; +const ERF_B2 = 1282.6165260773723; +const ERF_B3 = 2844.236833439171; + +const ERFC_C0 = 0.5641884969886701; +const ERFC_C1 = 8.883149794388377; +const ERFC_C2 = 66.11919063714163; +const ERFC_C3 = 298.6351381974001; +const ERFC_C4 = 881.952221241769; +const ERFC_C5 = 1712.0476126340707; +const ERFC_C6 = 2051.0783778260716; +const ERFC_C7 = 1230.3393547979972; +const ERFC_C8 = 2.1531153547440383e-8; + +const ERFC_D0 = 15.744926110709835; +const ERFC_D1 = 117.6939508913125; +const ERFC_D2 = 537.1811018620099; +const ERFC_D3 = 1621.3895745666903; +const ERFC_D4 = 3290.7992357334597; +const ERFC_D5 = 4362.619090143247; +const ERFC_D6 = 3439.3676741437216; +const ERFC_D7 = 1230.3393548037495; + +const ERFC_P0 = 0.30532663496123236; +const ERFC_P1 = 0.36034489994980445; +const ERFC_P2 = 0.12578172611122926; +const ERFC_P3 = 0.016083785148742275; +const ERFC_P4 = 0.0006587491615298378; +const ERFC_P5 = 0.016315387137302097; + +const ERFC_Q0 = 2.568520192289822; +const ERFC_Q1 = 1.8729528499234604; +const ERFC_Q2 = 0.5279051029514285; +const ERFC_Q3 = 0.06051834131244132; +const ERFC_Q4 = 0.0023352049762686918; + +function erfSmall(y: number): number { + const ysq = y * y; + let xnum = ERF_A4 * ysq; + let xden = ysq; + xnum = (xnum + ERF_A0) * ysq; + xden = (xden + ERF_B0) * ysq; + xnum = (xnum + ERF_A1) * ysq; + xden = (xden + ERF_B1) * ysq; + xnum = (xnum + ERF_A2) * ysq; + xden = (xden + ERF_B2) * ysq; + return (y * (xnum + ERF_A3)) / (xden + ERF_B3); +} + +function erfcPositive(y: number): number { + if (y <= 0.46875) { + return 1 - erfSmall(y); + } + if (y <= 4.0) { + let xnum = ERFC_C8 * y; + let xden = y; + xnum = (xnum + ERFC_C0) * y; + xden = (xden + ERFC_D0) * y; + xnum = (xnum + ERFC_C1) * y; + xden = (xden + ERFC_D1) * y; + xnum = (xnum + ERFC_C2) * y; + xden = (xden + ERFC_D2) * y; + xnum = (xnum + ERFC_C3) * y; + xden = (xden + ERFC_D3) * y; + xnum = (xnum + ERFC_C4) * y; + xden = (xden + ERFC_D4) * y; + xnum = (xnum + ERFC_C5) * y; + xden = (xden + ERFC_D5) * y; + xnum = (xnum + ERFC_C6) * y; + xden = (xden + ERFC_D6) * y; + const ratio = (xnum + ERFC_C7) / (xden + ERFC_D7); + const ysq = Math.trunc(y * 16) / 16; + const del = (y - ysq) * (y + ysq); + return Math.exp(-ysq * ysq) * Math.exp(-del) * ratio; + } + if (y >= 26.543) { + return 0; + } + const ysq = 1 / (y * y); + let xnum = ERFC_P5 * ysq; + let xden = ysq; + xnum = (xnum + ERFC_P0) * ysq; + xden = (xden + ERFC_Q0) * ysq; + xnum = (xnum + ERFC_P1) * ysq; + xden = (xden + ERFC_Q1) * ysq; + xnum = (xnum + ERFC_P2) * ysq; + xden = (xden + ERFC_Q2) * ysq; + xnum = (xnum + ERFC_P3) * ysq; + xden = (xden + ERFC_Q3) * ysq; + const tail = (ysq * (xnum + ERFC_P4)) / (xden + ERFC_Q4); + const ratio = (INV_SQRT_PI - tail) / y; + const yTrunc = Math.trunc(y * 16) / 16; + const del = (y - yTrunc) * (y + yTrunc); + return Math.exp(-yTrunc * yTrunc) * Math.exp(-del) * ratio; +} + +/** + * Standard normal cumulative distribution function `Phi(x)`. + * Uses Cody's rational Chebyshev `erfc` approximation (~1e-15 accuracy). + * Returns `null` for non-finite inputs. + */ +export function normalCdf(x: number): number | null { + if (!Number.isFinite(x)) { + return null; + } + const y = Math.abs(x) * Math.SQRT1_2; + if (y <= 0.46875) { + const halfErf = 0.5 * erfSmall(y); + return x >= 0 ? 0.5 + halfErf : 0.5 - halfErf; + } + const tail = 0.5 * erfcPositive(y); + return x >= 0 ? 1 - tail : tail; +} + +// Wichura Algorithm AS 241 (ppnd16) rational coefficients (~1e-16 accuracy). +const PPND_A0 = 3.3871328727963665; +const PPND_A1 = 133.14166789178438; +const PPND_A2 = 1971.5909503065513; +const PPND_A3 = 13731.69376550946; +const PPND_A4 = 45921.95393154987; +const PPND_A5 = 67265.7709270087; +const PPND_A6 = 33430.57558358813; +const PPND_A7 = 2509.0809287301227; + +const PPND_B1 = 42.31333070160091; +const PPND_B2 = 687.1870074920579; +const PPND_B3 = 5394.196021424751; +const PPND_B4 = 21213.794301586597; +const PPND_B5 = 39307.89580009271; +const PPND_B6 = 28729.085735721943; +const PPND_B7 = 5226.495278852854; + +const PPND_C0 = 1.4234371107496835; +const PPND_C1 = 4.630337846156546; +const PPND_C2 = 5.769497221460691; +const PPND_C3 = 3.6478483247632045; +const PPND_C4 = 1.2704582524523684; +const PPND_C5 = 0.2417807251774506; +const PPND_C6 = 0.022723844989269184; +const PPND_C7 = 0.0007745450142783414; + +const PPND_D1 = 2.053191626637759; +const PPND_D2 = 1.6763848301838038; +const PPND_D3 = 0.6897673349851; +const PPND_D4 = 0.14810397642748008; +const PPND_D5 = 0.015198666563616457; +const PPND_D6 = 0.0005475938084995345; +const PPND_D7 = 1.0507500716444169e-9; + +const PPND_E0 = 6.657904643501103; +const PPND_E1 = 5.463784911164114; +const PPND_E2 = 1.7848265399172913; +const PPND_E3 = 0.29656057182850487; +const PPND_E4 = 0.026532189526576124; +const PPND_E5 = 0.0012426609473880784; +const PPND_E6 = 0.000027115555687434876; +const PPND_E7 = 2.0103343992922881e-7; + +const PPND_F1 = 0.599832206555888; +const PPND_F2 = 0.1369298809227358; +const PPND_F3 = 0.014875361290850615; +const PPND_F4 = 0.0007868691311456133; +const PPND_F5 = 0.000018463183175100548; +const PPND_F6 = 1.421511758316446e-7; +const PPND_F7 = 2.0442631033899397e-15; + +/** + * Inverse standard normal CDF `Phi^-1(p)` via Wichura's Algorithm AS 241 (`ppnd16`). + * Achieves <= 1e-15 absolute error across `p in [1e-12, 1 - 1e-12]` with exact + * antisymmetry `Phi^-1(1 - p) = -Phi^-1(p)`. + * Returns `null` when `p <= 0`, `p >= 1`, or `p` is non-finite. + */ +export function inverseNormalCdf(p: number): number | null { + if (!Number.isFinite(p) || p <= 0 || p >= 1) { + return null; + } + + const q = p - 0.5; + if (Math.abs(q) <= 0.425) { + const r = 0.180625 - q * q; + const num = + (((((((PPND_A7 * r + PPND_A6) * r + PPND_A5) * r + PPND_A4) * r + PPND_A3) * r + PPND_A2) * + r + + PPND_A1) * + r + + PPND_A0) * + q; + const den = + ((((((PPND_B7 * r + PPND_B6) * r + PPND_B5) * r + PPND_B4) * r + PPND_B3) * r + PPND_B2) * r + + PPND_B1) * + r + + 1; + return num / den; + } + + const tailP = q < 0 ? p : 1 - p; + const r = Math.sqrt(-Math.log(tailP)); + let val: number; + if (r <= 5.0) { + const s = r - 1.6; + const num = + ((((((PPND_C7 * s + PPND_C6) * s + PPND_C5) * s + PPND_C4) * s + PPND_C3) * s + PPND_C2) * s + + PPND_C1) * + s + + PPND_C0; + const den = + ((((((PPND_D7 * s + PPND_D6) * s + PPND_D5) * s + PPND_D4) * s + PPND_D3) * s + PPND_D2) * s + + PPND_D1) * + s + + 1; + val = num / den; + } else { + const s = r - 5.0; + const num = + ((((((PPND_E7 * s + PPND_E6) * s + PPND_E5) * s + PPND_E4) * s + PPND_E3) * s + PPND_E2) * s + + PPND_E1) * + s + + PPND_E0; + const den = + ((((((PPND_F7 * s + PPND_F6) * s + PPND_F5) * s + PPND_F4) * s + PPND_F3) * s + PPND_F2) * s + + PPND_F1) * + s + + 1; + val = num / den; + } + + return q < 0 ? -val : val; +} + +/** + * Computes per-trial moments `{ nObs, sharpeUnann, skewness, kurtosis }` for a + * daily return or IC series, matching `trial_ledger` columns. + * + * Estimators: + * - Non-finite and sparse entries are filtered out before computing moments. + * - `sharpeUnann = (mean - dailyRiskFree) / sampleStd`, where `sampleStd` uses + * `n - 1` degrees of freedom via `sampleDeviation`. + * - `skewness = m3 / m2^(3/2)` and Pearson `kurtosis = m4 / m2^2` (normal = 3.0), + * using plugin central moments `m_k = (1/n) * sum((x_i - mean)^k)`. + * + * Returns `null` if `dailyRiskFree` is non-finite, fewer than 2 finite + * observations exist, variance is zero, or any resulting moment is non-finite. + */ +export function trialMoments(series: readonly number[], dailyRiskFree = 0): TrialMoments | null { + if (!Number.isFinite(dailyRiskFree)) { + return null; + } + + const finiteValues: number[] = []; + for (let i = 0; i < series.length; i++) { + const value = series[i]; + if (typeof value === 'number' && Number.isFinite(value)) { + finiteValues.push(value); + } + } + + const n = finiteValues.length; + if (n < 2) { + return null; + } + + const average = mean(finiteValues); + const std = sampleDeviation(finiteValues); + if (average === null || std === null || std === 0) { + return null; + } + + const sharpeUnann = (average - dailyRiskFree) / std; + let sum2 = 0; + let sum3 = 0; + let sum4 = 0; + for (let i = 0; i < n; i++) { + const d = (finiteValues[i] as number) - average; + const d2 = d * d; + sum2 += d2; + sum3 += d2 * d; + sum4 += d2 * d2; + } + + const m2 = sum2 / n; + if (!Number.isFinite(m2) || m2 <= 0) { + return null; + } + + const skewness = sum3 / n / (m2 * Math.sqrt(m2)); + const kurtosis = sum4 / n / (m2 * m2); + if (!Number.isFinite(sharpeUnann) || !Number.isFinite(skewness) || !Number.isFinite(kurtosis)) { + return null; + } + + return { nObs: n, sharpeUnann, skewness, kurtosis }; +} + +interface PreparedSeries { + readonly raw: Float64Array; + readonly allFinite: boolean; + readonly unit: Float64Array | null; +} + +function prepareSeries(series: readonly number[]): PreparedSeries { + const len = series.length; + const raw = new Float64Array(len); + let allFinite = true; + let sum = 0; + let allEqual = true; + let first = 0; + + for (let t = 0; t < len; t++) { + const v = series[t]; + if (typeof v === 'number' && Number.isFinite(v)) { + raw[t] = v; + sum += v; + if (t === 0) { + first = v; + } else if (v !== first) { + allEqual = false; + } + } else { + raw[t] = Number.NaN; + allFinite = false; + } + } + + if (!allFinite || len < 2 || allEqual) { + return { raw, allFinite, unit: null }; + } + + const mu = sum / len; + if (!Number.isFinite(mu)) { + return { raw, allFinite, unit: null }; + } + + const unit = new Float64Array(len); + let normSq = 0; + for (let t = 0; t < len; t++) { + const d = (raw[t] as number) - mu; + unit[t] = d; + normSq += d * d; + } + + if (!Number.isFinite(normSq) || normSq <= 0) { + return { raw, allFinite, unit: null }; + } + + const invNorm = 1 / Math.sqrt(normSq); + if (!Number.isFinite(invNorm)) { + return { raw, allFinite, unit: null }; + } + + for (let t = 0; t < len; t++) { + unit[t] = (unit[t] as number) * invNorm; + } + + return { raw, allFinite, unit }; +} + +/** + * Computes mean pairwise Pearson correlation `rho_bar` across overlapping + * index-aligned finite observations and effective independent trials: + * `nHat = max(1, 1 + (K - 1) * (1 - max(0, rho_bar)))`. + * + * Pairs with fewer than 2 overlapping finite observations or zero variance on + * the overlap are skipped and counted in `pairsSkipped` rather than silently + * treated as `rho = 0`. + * + * - For `K <= 1`, returns `{ k, pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 }`. + * - For `K >= 2` with `pairsUsed === 0`, returns `meanCorrelation: null` and + * conservative `nHat = K` (no correlation discount without valid pairs). + */ +export function effectiveIndependentTrials( + seriesList: readonly (readonly number[])[] +): EffectiveTrialsResult { + const k = seriesList.length; + if (k <= 1) { + return { k, pairsUsed: 0, pairsSkipped: 0, meanCorrelation: null, nHat: 1 }; + } + + const prepared: PreparedSeries[] = new Array(k); + for (let i = 0; i < k; i++) { + prepared[i] = prepareSeries(seriesList[i] as readonly number[]); + } + + let rhoSum = 0; + let pairsUsed = 0; + let pairsSkipped = 0; + + for (let i = 0; i < k - 1; i++) { + const a = prepared[i] as PreparedSeries; + const aRaw = a.raw; + const aLen = aRaw.length; + const aUnit = a.unit; + const aAllFinite = a.allFinite; + + for (let j = i + 1; j < k; j++) { + const b = prepared[j] as PreparedSeries; + const bRaw = b.raw; + const bLen = bRaw.length; + + // Fast path: equal-length all-finite series use pre-normalized unit vectors. + if (aAllFinite && b.allFinite && aLen === bLen) { + const bUnit = b.unit; + if (aUnit === null || bUnit === null) { + pairsSkipped++; + continue; + } + let dot = 0; + for (let t = 0; t < aLen; t++) { + dot += (aUnit[t] as number) * (bUnit[t] as number); + } + if (!Number.isFinite(dot)) { + pairsSkipped++; + continue; + } + rhoSum += dot < -1 ? -1 : dot > 1 ? 1 : dot; + pairsUsed++; + continue; + } + + // General path: allocation-free two-pass centered Pearson over overlapping finite pairs. + const len = aLen < bLen ? aLen : bLen; + let overlap = 0; + let sumA = 0; + let sumB = 0; + let firstA = 0; + let firstB = 0; + let allEqualA = true; + let allEqualB = true; + + for (let t = 0; t < len; t++) { + const va = aRaw[t] as number; + const vb = bRaw[t] as number; + if (Number.isFinite(va) && Number.isFinite(vb)) { + if (overlap === 0) { + firstA = va; + firstB = vb; + } else { + if (va !== firstA) { + allEqualA = false; + } + if (vb !== firstB) { + allEqualB = false; + } + } + sumA += va; + sumB += vb; + overlap++; + } + } + + if (overlap < 2 || allEqualA || allEqualB) { + pairsSkipped++; + continue; + } + + const meanA = sumA / overlap; + const meanB = sumB / overlap; + let cov = 0; + let varA = 0; + let varB = 0; + + for (let t = 0; t < len; t++) { + const va = aRaw[t] as number; + const vb = bRaw[t] as number; + if (Number.isFinite(va) && Number.isFinite(vb)) { + const da = va - meanA; + const db = vb - meanB; + cov += da * db; + varA += da * da; + varB += db * db; + } + } + + if (!Number.isFinite(varA) || !Number.isFinite(varB) || varA <= 0 || varB <= 0) { + pairsSkipped++; + continue; + } + + const denom = Math.sqrt(varA * varB); + if (!Number.isFinite(denom) || denom <= 0) { + pairsSkipped++; + continue; + } + + const rawRho = cov / denom; + if (!Number.isFinite(rawRho)) { + pairsSkipped++; + continue; + } + + rhoSum += rawRho < -1 ? -1 : rawRho > 1 ? 1 : rawRho; + pairsUsed++; + } + } + + if (pairsUsed === 0) { + return { k, pairsUsed: 0, pairsSkipped, meanCorrelation: null, nHat: k }; + } + + const meanCorrelation = rhoSum / pairsUsed; + const nHat = Math.max(1, 1 + (k - 1) * (1 - Math.max(0, meanCorrelation))); + return { k, pairsUsed, pairsSkipped, meanCorrelation, nHat }; +} + +/** + * Computes the non-normal Deflated Sharpe Ratio (Bailey & López de Prado, 2014): + * + * - `SR0 = max(0, sigma_SR * [(1 - gamma) * Phi^-1(1 - 1/nHat) + gamma * Phi^-1(1 - 1/(nHat * e))])` + * where `sigma_SR` is the sample standard deviation of `clusterSharpes`. + * For `nHat === 1`, `clusterSharpes.length < 2`, or `sigma_SR === 0`, `SR0 = 0`. + * The `max(0, ...)` floor keeps `E[max Z] >= 0` for fractional `1 < nHat < ~1.298` + * (where the asymptotic EVT formula dips slightly negative) so DSR remains + * monotonically non-increasing in `nHat`. + * - `SE = sqrt((1 - skewness * sharpeUnann + ((kurtosis - 1) / 4) * sharpeUnann^2) / (nObs - 1))` + * - `DSR = Phi((sharpeUnann - SR0) / SE)` + * + * Returns `null` if any scalar or `clusterSharpes` entry is non-finite, + * `nObs < 2`, `nHat < 1`, or the SE radicand is non-positive. + */ +export function deflatedSharpeRatio(input: DeflatedSharpeInput): DeflatedSharpeResult | null { + const { sharpeUnann, nObs, skewness, kurtosis, nHat, clusterSharpes } = input; + + if ( + !Number.isFinite(sharpeUnann) || + !Number.isFinite(nObs) || + !Number.isFinite(skewness) || + !Number.isFinite(kurtosis) || + !Number.isFinite(nHat) || + nObs < 2 || + nHat < 1 + ) { + return null; + } + + for (let i = 0; i < clusterSharpes.length; i++) { + const value = clusterSharpes[i]; + if (typeof value !== 'number' || !Number.isFinite(value)) { + return null; + } + } + + let sr0 = 0; + if (nHat > 1 && clusterSharpes.length >= 2) { + const sigmaSr = sampleDeviation(clusterSharpes); + if (sigmaSr === null) { + return null; + } + if (sigmaSr > 0) { + const z1 = inverseNormalCdf(1 - 1 / nHat); + const z2 = inverseNormalCdf(1 - 1 / (nHat * Math.E)); + if (z1 === null || z2 === null) { + return null; + } + const rawSr0 = sigmaSr * ((1 - EULER_MASCHERONI) * z1 + EULER_MASCHERONI * z2); + if (!Number.isFinite(rawSr0)) { + return null; + } + sr0 = Math.max(0, rawSr0); + } + } + + const radicand = + (1 - skewness * sharpeUnann + ((kurtosis - 1) / 4) * sharpeUnann * sharpeUnann) / (nObs - 1); + if (!Number.isFinite(radicand) || radicand <= 0) { + return null; + } + + const standardError = Math.sqrt(radicand); + const dsr = normalCdf((sharpeUnann - sr0) / standardError); + if (dsr === null) { + return null; + } + + return { sr0, standardError, dsr }; +} + +/** + * Returns `true` when `dsr` is finite and meets or exceeds the validation gate + * (default `DSR_VALIDATION_GATE = 0.95`). Returns `false` for `null` or non-finite inputs. + */ +export function passesDsrGate(dsr: number | null, gate = DSR_VALIDATION_GATE): boolean { + return dsr !== null && Number.isFinite(dsr) && Number.isFinite(gate) && dsr >= gate; +} diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts index 06e16349..84025925 100644 --- a/libs/calculations/src/analytics/index.ts +++ b/libs/calculations/src/analytics/index.ts @@ -4,3 +4,19 @@ export { factorStatistics, mean, returnStatistics, sampleDeviation } from './ret export { tradeStatistics } from './trade-statistics'; export type { TradeObservation } from './trade-statistics'; export { formatStatistic, performanceAnalysis } from './performance'; +export { + DSR_VALIDATION_GATE, + EULER_MASCHERONI, + deflatedSharpeRatio, + effectiveIndependentTrials, + inverseNormalCdf, + normalCdf, + passesDsrGate, + trialMoments, +} from './deflated-sharpe'; +export type { + DeflatedSharpeInput, + DeflatedSharpeResult, + EffectiveTrialsResult, + TrialMoments, +} from './deflated-sharpe'; diff --git a/libs/calculations/src/index.ts b/libs/calculations/src/index.ts index 6f5a828f..001a8609 100644 --- a/libs/calculations/src/index.ts +++ b/libs/calculations/src/index.ts @@ -55,3 +55,19 @@ export { filterByTimeRange, groupBySymbol, } from './market-data'; +export { + DSR_VALIDATION_GATE, + EULER_MASCHERONI, + deflatedSharpeRatio, + effectiveIndependentTrials, + inverseNormalCdf, + normalCdf, + passesDsrGate, + trialMoments, +} from './analytics'; +export type { + DeflatedSharpeInput, + DeflatedSharpeResult, + EffectiveTrialsResult, + TrialMoments, +} from './analytics'; diff --git a/libs/calculations/test/deflated-sharpe.test.ts b/libs/calculations/test/deflated-sharpe.test.ts new file mode 100644 index 00000000..6e3fb3b2 --- /dev/null +++ b/libs/calculations/test/deflated-sharpe.test.ts @@ -0,0 +1,478 @@ +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); + }); +});