From 659cd042f66d72ef22db70dedc4a8a7c0c0753c8 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 01:34:00 -0500 Subject: [PATCH] =?UTF-8?q?T-82:=20M1.4a=20=E2=80=94=20Pure=20signal=20ana?= =?UTF-8?q?lyzer=20math=20in=20`@stock-bot/calculations`:=20per-date=20IC?= =?UTF-8?q?=20/=20rank-IC,=20Newey-West=20t-stat,=20quantile=20spreads,=20?= =?UTF-8?q?turnover=20and=20pre/post-2023=20recency=20gate=20(no=20I/O)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/calculations/README.md | 19 +- .../scripts/benchmark-signal-analysis.ts | 132 ++ libs/calculations/src/analytics/index.ts | 34 + .../src/analytics/signal-analysis.ts | 1275 +++++++++++++++++ libs/calculations/src/index.ts | 30 + .../calculations/test/signal-analysis.test.ts | 680 +++++++++ 6 files changed, 2169 insertions(+), 1 deletion(-) create mode 100644 libs/calculations/scripts/benchmark-signal-analysis.ts create mode 100644 libs/calculations/src/analytics/signal-analysis.ts create mode 100644 libs/calculations/test/signal-analysis.test.ts diff --git a/libs/calculations/README.md b/libs/calculations/README.md index b999c1d1..8de33c6f 100644 --- a/libs/calculations/README.md +++ b/libs/calculations/README.md @@ -54,7 +54,11 @@ const risk = returnStatistics(returns); fields in `performanceAnalysis` remain compatibility heuristics, not optimizers. Canonical Deflated Sharpe Ratio (`deflatedSharpeRatio`, `effectiveIndependentTrials`, `trialMoments`, `normalCdf`, `inverseNormalCdf`, `passesDsrGate`, `DSR_VALIDATION_GATE`) - is exported from both `./analytics` and the root entry. + and cross-sectional Signal Analysis (`analyzeSignalPanel`, `crossSectionIc`, + `neweyWestMeanTest`, `defaultNeweyWestLag`, `summarizeIcSeries`, `evaluateRecencyGate`, + `SignalAnalysisError`, `DEFAULT_MIN_CROSS_SECTION`, `DEFAULT_QUANTILE_COUNT`, + `RECENCY_SPLIT_DATE`, `RECENCY_MIN_RATIO`) are exported from both `./analytics` and + the root entry. ## Benchmark @@ -68,6 +72,19 @@ bun run libs/calculations/scripts/benchmark-deflated-sharpe.ts Observed locally on Bun 1.2.16 (2 runs, seed `20260401`): `150.18 ms` (`830,660 pairs/s`) and `159.79 ms` (`780,707 pairs/s`), `meanCorrelation = 0.071187`, `nHat = 464.4776`. +Run the fixed-seed Signal Analysis benchmark (`5,040` dates × `3,000` names, +`15,120,000` observations, covering full `analyzeSignalPanel` with IC, Newey-West HAC, +quintile spreads, turnover, and recency gate): + +```sh +bun run libs/calculations/scripts/benchmark-signal-analysis.ts +``` + +Observed locally on Bun 1.2.16 (2 runs, seed `20260402`): `1,664.54 ms` +(`3,028 dates/s`, `9,083,609 observations/s`) and `1,659.80 ms` (`3,037 dates/s`, +`9,109,520 observations/s`), `meanRankIc = 0.057294`, `rankIcTStat = 218.5078`, +`spreadMean = 0.003369`, `recencyGatePassed = true`. + The root entry exports the supported returns, indicators and market-data helpers. Use subpaths to avoid loading unrelated math. Shared domain types remain owned by `@stock-bot/types`; HTTP/date/proxy helpers remain in `@stock-bot/utils`. diff --git a/libs/calculations/scripts/benchmark-signal-analysis.ts b/libs/calculations/scripts/benchmark-signal-analysis.ts new file mode 100644 index 00000000..37524b31 --- /dev/null +++ b/libs/calculations/scripts/benchmark-signal-analysis.ts @@ -0,0 +1,132 @@ +import { analyzeSignalPanel, type SignalCrossSection } from '../src/analytics/signal-analysis'; + +const SEED = 20260402; +const DATES = 5040; +const NAMES_PER_DATE = 3000; + +function createMulberry32(seed: number): () => number { + let state = seed >>> 0; + return () => { + state = (state + 0x6d2b79f5) >>> 0; + let t = Math.imul(state ^ (state >>> 15), 1 | state); + t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; + return ((t ^ (t >>> 14)) >>> 0) / 4294967296; + }; +} + +function createStandardNormal(seed: number): () => number { + const nextUniform = createMulberry32(seed); + let spare: number | null = null; + return () => { + if (spare !== null) { + const value = spare; + spare = null; + return value; + } + let u1 = nextUniform(); + while (u1 <= 1e-12) { + u1 = nextUniform(); + } + const u2 = nextUniform(); + const radius = Math.sqrt(-2 * Math.log(u1)); + const theta = 2 * Math.PI * u2; + spare = radius * Math.sin(theta); + return radius * Math.cos(theta); + }; +} + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function generateBusinessDates(count: number, startYear: number): string[] { + const dates: string[] = new Array(count); + let year = startYear; + let month = 1; + let day = 1; + // 2006-01-01 was a Sunday (dow = 0) + let dow = 0; + let produced = 0; + + while (produced < count) { + if (dow !== 0 && dow !== 6) { + const yyyy = String(year).padStart(4, '0'); + const mm = String(month).padStart(2, '0'); + const dd = String(day).padStart(2, '0'); + dates[produced++] = `${yyyy}-${mm}-${dd}`; + } + + dow = (dow + 1) % 7; + day++; + const baseDays = DAYS_IN_MONTH[month] ?? 31; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day > maxDay) { + day = 1; + month++; + if (month > 12) { + month = 1; + year++; + } + } + } + + return dates; +} + +const randn = createStandardNormal(SEED); +const isoDates = generateBusinessDates(DATES, 2006); +const sharedIds = new Int32Array(NAMES_PER_DATE); +for (let i = 0; i < NAMES_PER_DATE; i++) { + sharedIds[i] = i + 1; +} + +const panel: SignalCrossSection[] = new Array(DATES); +for (let t = 0; t < DATES; t++) { + const signal = new Float64Array(NAMES_PER_DATE); + const forwardReturn = new Float64Array(NAMES_PER_DATE); + for (let i = 0; i < NAMES_PER_DATE; i++) { + const s = randn(); + signal[i] = s; + forwardReturn[i] = 0.0004 + 0.0012 * s + 0.02 * randn(); + } + panel[t] = { + date: isoDates[t] as string, + ids: sharedIds, + signal, + forwardReturn, + }; +} + +const started = performance.now(); +const result = analyzeSignalPanel(panel); +const elapsedMs = performance.now() - started; + +const totalObservations = DATES * NAMES_PER_DATE; +const elapsedSec = elapsedMs / 1000; +const datesPerSec = DATES / elapsedSec; +const observationsPerSec = totalObservations / elapsedSec; + +console.log( + JSON.stringify( + { + seed: SEED, + dates: DATES, + namesPerDate: NAMES_PER_DATE, + totalObservations, + elapsedMs: Number(elapsedMs.toFixed(2)), + datesPerSec: Math.round(datesPerSec), + observationsPerSec: Math.round(observationsPerSec), + meanRankIc: Number((result.rankIc.mean ?? 0).toFixed(6)), + rankIcTStat: + result.rankIc.neweyWest.status === 'ok' + ? Number(result.rankIc.neweyWest.tStat.toFixed(4)) + : null, + spreadMean: Number((result.quantiles.spreadSummary.mean ?? 0).toFixed(6)), + recencyGatePassed: result.recency.gate.pass, + }, + null, + 2 + ) +); diff --git a/libs/calculations/src/analytics/index.ts b/libs/calculations/src/analytics/index.ts index 84025925..e9695557 100644 --- a/libs/calculations/src/analytics/index.ts +++ b/libs/calculations/src/analytics/index.ts @@ -20,3 +20,37 @@ export type { EffectiveTrialsResult, TrialMoments, } from './deflated-sharpe'; +export { + DEFAULT_MIN_CROSS_SECTION, + DEFAULT_QUANTILE_COUNT, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + SignalAnalysisError, + analyzeSignalPanel, + crossSectionIc, + defaultNeweyWestLag, + evaluateRecencyGate, + neweyWestMeanTest, + summarizeIcSeries, +} from './signal-analysis'; +export type { + CrossSectionIcOptions, + CrossSectionIcResult, + EntityId, + EntityIdSeries, + IcSummary, + IcSummaryOptions, + NeweyWestResult, + NumericSeries, + QuantileSpreadResult, + RecencyGateOptions, + RecencyGateReason, + RecencyGateResult, + RecencySplitResult, + SignalAnalysisErrorCode, + SignalAnalysisOptions, + SignalCrossSection, + SignalPanelAnalysis, + SignalPanelDiagnostics, + TurnoverResult, +} from './signal-analysis'; diff --git a/libs/calculations/src/analytics/signal-analysis.ts b/libs/calculations/src/analytics/signal-analysis.ts new file mode 100644 index 00000000..7b0a00d7 --- /dev/null +++ b/libs/calculations/src/analytics/signal-analysis.ts @@ -0,0 +1,1275 @@ +/** + * Pure, zero-I/O cross-sectional signal analysis math per `design/PLATFORM-PLAN.md` + * and `design/VALIDATION-AND-RIGOR.md` §3. + * + * Covers: + * - Per-date Pearson IC and Spearman rank-IC (average ranks for ties) + * - Newey-West HAC t-statistic of the mean (Bartlett kernel, finite-sample scaling) + * - Deterministic-tie-break quantile bucket returns and top-minus-bottom spreads + * - Consecutive-date top/bottom quantile membership turnover + * - Pre/post-2023 recency split & gate with optional exclusive `vaultCutoffDate` fence + * + * Pure stateless math: zero I/O, zero wall-clock or random calls, reusable typed-array + * scratch buffers on the panel hot path. + * + * Local benchmark (fixed seed `20260402`, `5,040` dates x `3,000` names = `15,120,000` + * observations, covering full `analyzeSignalPanel`): + * - Command: `bun run libs/calculations/scripts/benchmark-signal-analysis.ts` + * - Observed (Bun 1.2.16, 2 runs): `1,664.54 ms` (`9,083,609 observations/s`) and + * `1,659.80 ms` (`9,109,520 observations/s`). + */ + +/** Default minimum finite cross-sectional pairs required to compute per-date IC. */ +export const DEFAULT_MIN_CROSS_SECTION = 5; + +/** Default number of signal quantile buckets (quintiles). */ +export const DEFAULT_QUANTILE_COUNT = 5; + +/** Canonical recency split boundary (`pre < 2023-01-01`, `post >= 2023-01-01`). */ +export const RECENCY_SPLIT_DATE = '2023-01-01'; + +/** Canonical minimum post/pre mean rank-IC ratio required to pass the recency gate. */ +export const RECENCY_MIN_RATIO = 0.5; + +/** Machine-readable error codes thrown by {@link SignalAnalysisError}. */ +export type SignalAnalysisErrorCode = + | 'LENGTH_MISMATCH' + | 'UNSORTED_DATES' + | 'DUPLICATE_DATE' + | 'INVALID_DATE' + | 'INVALID_OPTION'; + +/** Typed validation error thrown for malformed signal panels or invalid options. */ +export class SignalAnalysisError extends RangeError { + readonly code: SignalAnalysisErrorCode; + + constructor(code: SignalAnalysisErrorCode, message: string) { + super(message); + this.name = 'SignalAnalysisError'; + this.code = code; + } +} + +/** Numeric vector accepted by signal-analysis routines (prefers `Float64Array` on hot paths). */ +export type NumericSeries = Float64Array | readonly number[]; + +/** Cross-sectional entity identifier used for deterministic tie-breaking and turnover. */ +export type EntityId = number | string; + +/** Entity identifier vector aligned index-for-index with a cross-section's signal and return. */ +export type EntityIdSeries = readonly EntityId[] | Int32Array | Uint32Array; + +/** Single date cross-section in a date-ordered signal panel. */ +export interface SignalCrossSection { + readonly date: string; + readonly ids: EntityIdSeries; + readonly signal: NumericSeries; + readonly forwardReturn: NumericSeries; +} + +/** Options for {@link crossSectionIc}. */ +export interface CrossSectionIcOptions { + readonly minCrossSection?: number; +} + +/** Options for {@link summarizeIcSeries}. */ +export interface IcSummaryOptions { + readonly lag?: number; +} + +/** Options for {@link evaluateRecencyGate}. */ +export interface RecencyGateOptions { + readonly lag?: number; + readonly recencySplitDate?: string; + readonly recencyMinRatio?: number; + readonly vaultCutoffDate?: string; +} + +/** Options for {@link analyzeSignalPanel}. */ +export interface SignalAnalysisOptions { + readonly minCrossSection?: number; + readonly quantiles?: number; + readonly lag?: number; + readonly recencySplitDate?: string; + readonly recencyMinRatio?: number; + readonly vaultCutoffDate?: string; +} + +/** Output of {@link neweyWestMeanTest}. Never emits `NaN`. */ +export type NeweyWestResult = + | { + readonly status: 'ok'; + readonly lag: number; + readonly standardError: number; + readonly tStat: number; + readonly longRunVariance: number; + } + | { + readonly status: 'insufficient_data'; + readonly reason: 'too_few_observations' | 'non_positive_variance'; + readonly lag: number | null; + }; + +/** Time-series summary statistics for an IC or spread series. */ +export interface IcSummary { + readonly count: number; + readonly mean: number | null; + readonly std: number | null; + readonly icir: number | null; + readonly hitRate: number | null; + readonly neweyWest: NeweyWestResult; +} + +/** Output of {@link crossSectionIc} for a single date. */ +export type CrossSectionIcResult = + | { + readonly status: 'ok'; + readonly validCount: number; + readonly droppedPairs: number; + readonly pearsonIc: number; + readonly rankIc: number; + } + | { + readonly status: 'skipped'; + readonly reason: 'below_min_cross_section' | 'zero_variance'; + readonly validCount: number; + readonly droppedPairs: number; + }; + +/** Per-quantile equal-weight forward return series and top-minus-bottom spread summary. */ +export interface QuantileSpreadResult { + readonly quantiles: number; + readonly validDates: number; + readonly skippedDates: number; + readonly dates: readonly string[]; + readonly bucketMeanReturns: readonly (number | null)[]; + readonly perBucketSeries: readonly Float64Array[]; + readonly spreadSeries: Float64Array; + readonly spreadSummary: IcSummary; +} + +/** Consecutive-date membership turnover for the top and bottom signal quantiles. */ +export interface TurnoverResult { + readonly count: number; + readonly dates: readonly string[]; + readonly topSeries: Float64Array; + readonly bottomSeries: Float64Array; + readonly meanTopTurnover: number | null; + readonly meanBottomTurnover: number | null; +} + +/** Explicit reason describing why the recency gate passed or failed. */ +export type RecencyGateReason = + | 'passed' + | 'empty_pre_window' + | 'empty_post_window' + | 'non_positive_pre_mean' + | 'non_positive_post_mean' + | 'post_below_ratio_threshold'; + +/** Pass/fail outcome of the post-2023 recency gate. */ +export interface RecencyGateResult { + readonly pass: boolean; + readonly reason: RecencyGateReason; + readonly ratio: number | null; +} + +/** Pre/post recency split summaries, vault exclusion count, and gate decision. */ +export interface RecencySplitResult { + readonly splitDate: string; + readonly minRatio: number; + readonly vaultCutoffDate: string | null; + readonly vaultExcludedDates: number; + readonly pre: IcSummary; + readonly post: IcSummary; + readonly gate: RecencyGateResult; +} + +/** Observation and date-level accounting across the analyzed panel. */ +export interface SignalPanelDiagnostics { + readonly totalDates: number; + readonly eligibleDates: number; + readonly vaultExcludedDates: number; + readonly totalObservations: number; + readonly validObservations: number; + readonly droppedPairs: number; + readonly icValidDates: number; + readonly icSkippedBelowMin: number; + readonly icSkippedZeroVariance: number; + readonly quantileValidDates: number; + readonly quantileSkippedDates: number; +} + +/** Full cross-sectional signal analysis result returned by {@link analyzeSignalPanel}. */ +export interface SignalPanelAnalysis { + readonly dates: readonly string[]; + readonly pearsonIcSeries: Float64Array; + readonly rankIcSeries: Float64Array; + readonly pearsonIc: IcSummary; + readonly rankIc: IcSummary; + readonly quantiles: QuantileSpreadResult; + readonly turnover: TurnoverResult; + readonly recency: RecencySplitResult; + readonly diagnostics: SignalPanelDiagnostics; +} + +const ISO_DATE_RE = /^\d{4}-\d{2}-\d{2}$/; +const DAYS_IN_MONTH = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] as const; + +function isLeapYear(year: number): boolean { + return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0; +} + +function assertIsoDate(value: string, label: string): void { + if (typeof value !== 'string' || !ISO_DATE_RE.test(value)) { + throw new SignalAnalysisError('INVALID_DATE', `${label} must be a valid YYYY-MM-DD date`); + } + const year = Number(value.slice(0, 4)); + const month = Number(value.slice(5, 7)); + const day = Number(value.slice(8, 10)); + if (month < 1 || month > 12) { + throw new SignalAnalysisError('INVALID_DATE', `${label} has invalid month: ${value}`); + } + const baseDays = DAYS_IN_MONTH[month] ?? 0; + const maxDay = month === 2 && isLeapYear(year) ? 29 : baseDays; + if (day < 1 || day > maxDay) { + throw new SignalAnalysisError('INVALID_DATE', `${label} is not a valid calendar date: ${value}`); + } +} + +function assertIntegerOption(value: number, min: number, label: string): void { + if (typeof value !== 'number' || !Number.isInteger(value) || value < min) { + throw new SignalAnalysisError( + 'INVALID_OPTION', + `${label} must be an integer >= ${min}, received ${String(value)}` + ); + } +} + +function assertPositiveFiniteOption(value: number, label: string): void { + if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) { + throw new SignalAnalysisError( + 'INVALID_OPTION', + `${label} must be a finite number > 0, received ${String(value)}` + ); + } +} + +interface PanelScratch { + capacity: number; + validIdx: Int32Array; + validSignal: Float64Array; + validReturn: Float64Array; + orderSignal: Int32Array; + orderReturn: Int32Array; + sortScratch: Int32Array; + rankSignal: Float64Array; + rankReturn: Float64Array; +} + +function createPanelScratch(initialCapacity: number): PanelScratch { + const cap = initialCapacity > 0 ? initialCapacity : 1; + return { + capacity: cap, + validIdx: new Int32Array(cap), + validSignal: new Float64Array(cap), + validReturn: new Float64Array(cap), + orderSignal: new Int32Array(cap), + orderReturn: new Int32Array(cap), + sortScratch: new Int32Array(cap), + rankSignal: new Float64Array(cap), + rankReturn: new Float64Array(cap), + }; +} + +function compareIds(a: EntityId, b: EntityId): number { + const typeA = typeof a; + const typeB = typeof b; + if (typeA === typeB) { + return a < b ? -1 : a > b ? 1 : 0; + } + return typeA === 'number' ? -1 : 1; +} + +const INSERTION_RUN = 16; + +function sortOrderByFloat( + order: Int32Array, + values: Float64Array, + length: number, + scratch: Int32Array +): void { + if (length <= 1) { + return; + } + + for (let start = 0; start < length; start += INSERTION_RUN) { + const end = start + INSERTION_RUN < length ? start + INSERTION_RUN : length; + for (let i = start + 1; i < end; i++) { + const idx = order[i] as number; + const val = values[idx] as number; + let j = i - 1; + while (j >= start) { + const prevIdx = order[j] as number; + if ((values[prevIdx] as number) <= val) { + break; + } + order[j + 1] = prevIdx; + j--; + } + order[j + 1] = idx; + } + } + + let src = order; + let dst = scratch; + for (let width = INSERTION_RUN; width < length; width <<= 1) { + const step = width << 1; + for (let left = 0; left < length; left += step) { + const mid = left + width < length ? left + width : length; + const right = left + step < length ? left + step : length; + let i = left; + let j = mid; + let k = left; + while (i < mid && j < right) { + const li = src[i] as number; + const rj = src[j] as number; + if ((values[li] as number) <= (values[rj] as number)) { + dst[k++] = li; + i++; + } else { + dst[k++] = rj; + j++; + } + } + while (i < mid) { + dst[k++] = src[i++] as number; + } + while (j < right) { + dst[k++] = src[j++] as number; + } + } + const tmp = src; + src = dst; + dst = tmp; + } + + if (src !== order) { + for (let i = 0; i < length; i++) { + order[i] = src[i] as number; + } + } +} + +function sortOrderBySignalAndId( + order: Int32Array, + values: Float64Array, + validIdx: Int32Array, + ids: EntityIdSeries, + length: number, + scratch: Int32Array +): void { + if (length <= 1) { + return; + } + + for (let start = 0; start < length; start += INSERTION_RUN) { + const end = start + INSERTION_RUN < length ? start + INSERTION_RUN : length; + for (let i = start + 1; i < end; i++) { + const idx = order[i] as number; + const val = values[idx] as number; + let j = i - 1; + while (j >= start) { + const prevIdx = order[j] as number; + const prevVal = values[prevIdx] as number; + if ( + prevVal < val || + (prevVal === val && + compareIds( + ids[validIdx[prevIdx] as number] as EntityId, + ids[validIdx[idx] as number] as EntityId + ) <= 0) + ) { + break; + } + order[j + 1] = prevIdx; + j--; + } + order[j + 1] = idx; + } + } + + let src = order; + let dst = scratch; + for (let width = INSERTION_RUN; width < length; width <<= 1) { + const step = width << 1; + for (let left = 0; left < length; left += step) { + const mid = left + width < length ? left + width : length; + const right = left + step < length ? left + step : length; + let i = left; + let j = mid; + let k = left; + while (i < mid && j < right) { + const li = src[i] as number; + const rj = src[j] as number; + const va = values[li] as number; + const vb = values[rj] as number; + if ( + va < vb || + (va === vb && + compareIds( + ids[validIdx[li] as number] as EntityId, + ids[validIdx[rj] as number] as EntityId + ) <= 0) + ) { + dst[k++] = li; + i++; + } else { + dst[k++] = rj; + j++; + } + } + while (i < mid) { + dst[k++] = src[i++] as number; + } + while (j < right) { + dst[k++] = src[j++] as number; + } + } + const tmp = src; + src = dst; + dst = tmp; + } + + if (src !== order) { + for (let i = 0; i < length; i++) { + order[i] = src[i] as number; + } + } +} + +function assignAverageRanks( + order: Int32Array, + values: Float64Array, + ranksOut: Float64Array, + length: number +): void { + let i = 0; + while (i < length) { + const val = values[order[i] as number] as number; + let j = i + 1; + while (j < length && (values[order[j] as number] as number) === val) { + j++; + } + const midRank = (i + (j - 1)) * 0.5; + for (let k = i; k < j; k++) { + ranksOut[order[k] as number] = midRank; + } + i = j; + } +} + +function twoPassPearson(x: Float64Array, y: Float64Array, length: number): number | null { + if (length < 2) { + return null; + } + + let sumX = 0; + let sumY = 0; + const firstX = x[0] as number; + const firstY = y[0] as number; + let allEqualX = true; + let allEqualY = true; + + for (let i = 0; i < length; i++) { + const vx = x[i] as number; + const vy = y[i] as number; + sumX += vx; + sumY += vy; + if (vx !== firstX) { + allEqualX = false; + } + if (vy !== firstY) { + allEqualY = false; + } + } + + if (allEqualX || allEqualY) { + return null; + } + + const meanX = sumX / length; + const meanY = sumY / length; + if (!Number.isFinite(meanX) || !Number.isFinite(meanY)) { + return null; + } + + let cov = 0; + let varX = 0; + let varY = 0; + for (let i = 0; i < length; i++) { + const dx = (x[i] as number) - meanX; + const dy = (y[i] as number) - meanY; + cov += dx * dy; + varX += dx * dx; + varY += dy * dy; + } + + if (!Number.isFinite(varX) || !Number.isFinite(varY) || varX <= 0 || varY <= 0) { + return null; + } + + const denom = Math.sqrt(varX * varY); + if (!Number.isFinite(denom) || denom <= 0) { + return null; + } + + const rho = cov / denom; + if (!Number.isFinite(rho)) { + return null; + } + + return rho < -1 ? -1 : rho > 1 ? 1 : rho; +} + +/** + * Computes single-date Pearson IC and Spearman rank-IC (using average ranks for ties) + * between `signal` and `forwardReturn`. + * + * Pairs where either value is non-finite are dropped and counted in `droppedPairs`. + * Dates with fewer than `minCrossSection` (default 5) valid pairs or zero variance on + * either side return `{ status: 'skipped', ... }` rather than `NaN`. + */ +export function crossSectionIc( + signal: NumericSeries, + forwardReturn: NumericSeries, + options?: CrossSectionIcOptions +): CrossSectionIcResult { + const minCrossSection = options?.minCrossSection ?? DEFAULT_MIN_CROSS_SECTION; + assertIntegerOption(minCrossSection, 2, 'minCrossSection'); + + const n = signal.length; + if (n !== forwardReturn.length) { + throw new SignalAnalysisError( + 'LENGTH_MISMATCH', + `signal length (${n}) does not match forwardReturn length (${forwardReturn.length})` + ); + } + + const validSignal = new Float64Array(n); + const validReturn = new Float64Array(n); + let m = 0; + for (let i = 0; i < n; i++) { + const s = signal[i]; + const r = forwardReturn[i]; + if (typeof s === 'number' && typeof r === 'number' && Number.isFinite(s) && Number.isFinite(r)) { + validSignal[m] = s; + validReturn[m] = r; + m++; + } + } + + const droppedPairs = n - m; + if (m < minCrossSection) { + return { + status: 'skipped', + reason: 'below_min_cross_section', + validCount: m, + droppedPairs, + }; + } + + const pearsonIc = twoPassPearson(validSignal, validReturn, m); + if (pearsonIc === null) { + return { + status: 'skipped', + reason: 'zero_variance', + validCount: m, + droppedPairs, + }; + } + + const orderSignal = new Int32Array(m); + const orderReturn = new Int32Array(m); + const sortScratch = new Int32Array(m); + for (let i = 0; i < m; i++) { + orderSignal[i] = i; + orderReturn[i] = i; + } + + sortOrderByFloat(orderSignal, validSignal, m, sortScratch); + sortOrderByFloat(orderReturn, validReturn, m, sortScratch); + + const rankSignal = new Float64Array(m); + const rankReturn = new Float64Array(m); + assignAverageRanks(orderSignal, validSignal, rankSignal, m); + assignAverageRanks(orderReturn, validReturn, rankReturn, m); + + const rankIc = twoPassPearson(rankSignal, rankReturn, m); + if (rankIc === null) { + return { + status: 'skipped', + reason: 'zero_variance', + validCount: m, + droppedPairs, + }; + } + + return { + status: 'ok', + validCount: m, + droppedPairs, + pearsonIc, + rankIc, + }; +} + +/** + * Default Newey-West (1994) Bartlett bandwidth: `floor(4 * (T / 100)^(2/9))`. + * Returns `0` for `nObs < 2`. + */ +export function defaultNeweyWestLag(nObs: number): number { + if (!Number.isFinite(nObs) || nObs < 2) { + return 0; + } + return Math.floor(4 * Math.pow(nObs / 100, 2 / 9)); +} + +/** + * Newey-West HAC test of the mean using the Bartlett kernel and finite-sample + * `1 / (T - 1)` autocovariance scaling so `lag = 0` matches the plain Student t-stat + * `mean / (sampleStd / sqrt(T))` exactly. + * + * Returns a typed `insufficient_data` result rather than `NaN` when `T < 2` or + * the estimated long-run variance is non-positive / non-finite. + */ +export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWestResult { + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + + const n = series.length; + if (n < 2) { + return { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }; + } + + const resolvedLag = lag ?? defaultNeweyWestLag(n); + let sum = 0; + const first = series[0] as number; + let allEqual = true; + for (let t = 0; t < n; t++) { + const v = series[t] as number; + if (!Number.isFinite(v)) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + sum += v; + if (v !== first) { + allEqual = false; + } + } + + const avg = sum / n; + if (!Number.isFinite(avg) || allEqual) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + const residuals = new Float64Array(n); + let sumSq = 0; + for (let t = 0; t < n; t++) { + const e = (series[t] as number) - avg; + residuals[t] = e; + sumSq += e * e; + } + + const invDof = 1 / (n - 1); + let longRunVariance = sumSq * invDof; + const maxLag = resolvedLag < n - 1 ? resolvedLag : n - 1; + for (let l = 1; l <= maxLag; l++) { + let cov = 0; + for (let t = l; t < n; t++) { + cov += (residuals[t] as number) * (residuals[t - l] as number); + } + const gamma = cov * invDof; + const weight = 1 - l / (resolvedLag + 1); + longRunVariance += 2 * weight * gamma; + } + + if (!Number.isFinite(longRunVariance) || longRunVariance <= 0) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + const standardError = Math.sqrt(longRunVariance / n); + if (!Number.isFinite(standardError) || standardError <= 0) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + const tStat = avg / standardError; + if (!Number.isFinite(tStat)) { + return { + status: 'insufficient_data', + reason: 'non_positive_variance', + lag: resolvedLag, + }; + } + + return { + status: 'ok', + lag: resolvedLag, + standardError, + tStat, + longRunVariance, + }; +} + +/** + * Summarizes an IC or spread time series with count, mean, sample standard deviation + * (`n - 1` dof), ICIR (`mean / std`), hit rate (fraction strictly `> 0`), and + * Newey-West HAC t-statistic. + */ +export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOptions): IcSummary { + const lag = options?.lag; + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + + const n = series.length; + if (n === 0) { + return { + count: 0, + mean: null, + std: null, + icir: null, + hitRate: null, + neweyWest: { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }, + }; + } + + let sum = 0; + let hits = 0; + const first = series[0] as number; + let allEqual = true; + for (let i = 0; i < n; i++) { + const v = series[i] as number; + sum += v; + if (v > 0) { + hits++; + } + if (v !== first) { + allEqual = false; + } + } + + const avg = sum / n; + const hitRate = hits / n; + if (n < 2) { + return { + count: n, + mean: Number.isFinite(avg) ? avg : null, + std: null, + icir: null, + hitRate, + neweyWest: { + status: 'insufficient_data', + reason: 'too_few_observations', + lag: null, + }, + }; + } + + let std: number | null; + if (allEqual) { + std = 0; + } else { + let sumSq = 0; + for (let i = 0; i < n; i++) { + const d = (series[i] as number) - avg; + sumSq += d * d; + } + const variance = sumSq / (n - 1); + std = Number.isFinite(variance) && variance >= 0 ? Math.sqrt(variance) : null; + } + + const icir = + std !== null && std > 0 && Number.isFinite(avg / std) ? avg / std : null; + + return { + count: n, + mean: Number.isFinite(avg) ? avg : null, + std, + icir, + hitRate, + neweyWest: neweyWestMeanTest(series, lag), + }; +} + +function buildRecencySplitResult( + dates: readonly string[], + rankIc: NumericSeries, + splitDate: string, + minRatio: number, + vaultCutoffDate: string | null, + vaultExcludedDates: number, + lag: number | undefined +): RecencySplitResult { + const preValues: number[] = []; + const postValues: number[] = []; + for (let i = 0; i < dates.length; i++) { + const d = dates[i] as string; + const v = rankIc[i] as number; + if (d < splitDate) { + preValues.push(v); + } else { + postValues.push(v); + } + } + + const pre = summarizeIcSeries(Float64Array.from(preValues), { lag }); + const post = summarizeIcSeries(Float64Array.from(postValues), { lag }); + + let gate: RecencyGateResult; + if (pre.count === 0 || pre.mean === null) { + gate = { pass: false, reason: 'empty_pre_window', ratio: null }; + } else if (post.count === 0 || post.mean === null) { + gate = { pass: false, reason: 'empty_post_window', ratio: null }; + } else if (pre.mean <= 0) { + gate = { pass: false, reason: 'non_positive_pre_mean', ratio: null }; + } else { + const ratio = post.mean / pre.mean; + if (post.mean <= 0) { + gate = { pass: false, reason: 'non_positive_post_mean', ratio }; + } else if (post.mean < minRatio * pre.mean) { + gate = { pass: false, reason: 'post_below_ratio_threshold', ratio }; + } else { + gate = { pass: true, reason: 'passed', ratio }; + } + } + + return { + splitDate, + minRatio, + vaultCutoffDate, + vaultExcludedDates, + pre, + post, + gate, + }; +} + +/** + * Splits a date-ordered rank-IC series into `pre` (`date < recencySplitDate`) and + * `post` (`date >= recencySplitDate`, default `2023-01-01`), optionally excluding + * dates `>= vaultCutoffDate`, and evaluates the recency gate. + * + * Passing requires `pre.mean > 0`, `post.mean > 0`, and + * `post.mean >= recencyMinRatio * pre.mean` (default `0.5`). + */ +export function evaluateRecencyGate( + dates: readonly string[], + rankIc: NumericSeries, + options?: RecencyGateOptions +): RecencySplitResult { + const splitDate = options?.recencySplitDate ?? RECENCY_SPLIT_DATE; + const minRatio = options?.recencyMinRatio ?? RECENCY_MIN_RATIO; + const vaultCutoffDate = options?.vaultCutoffDate; + const lag = options?.lag; + + assertIsoDate(splitDate, 'recencySplitDate'); + assertPositiveFiniteOption(minRatio, 'recencyMinRatio'); + if (vaultCutoffDate !== undefined) { + assertIsoDate(vaultCutoffDate, 'vaultCutoffDate'); + } + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + + if (dates.length !== rankIc.length) { + throw new SignalAnalysisError( + 'LENGTH_MISMATCH', + `dates length (${dates.length}) does not match rankIc length (${rankIc.length})` + ); + } + + let eligibleCount = 0; + for (let i = 0; i < dates.length; i++) { + const d = dates[i] as string; + assertIsoDate(d, `dates[${i}]`); + if (i > 0) { + const prev = dates[i - 1] as string; + if (d === prev) { + throw new SignalAnalysisError('DUPLICATE_DATE', `Duplicate date at index ${i}: ${d}`); + } + if (d < prev) { + throw new SignalAnalysisError( + 'UNSORTED_DATES', + `Dates must be strictly ascending: ${prev} followed by ${d} at index ${i}` + ); + } + } + if (vaultCutoffDate === undefined || d < vaultCutoffDate) { + eligibleCount++; + } + } + + const vaultExcludedDates = dates.length - eligibleCount; + const eligibleDates = eligibleCount === dates.length ? dates : dates.slice(0, eligibleCount); + const eligibleRankIc = + eligibleCount === rankIc.length + ? rankIc + : rankIc instanceof Float64Array + ? rankIc.subarray(0, eligibleCount) + : rankIc.slice(0, eligibleCount); + + return buildRecencySplitResult( + eligibleDates, + eligibleRankIc, + splitDate, + minRatio, + vaultCutoffDate ?? null, + vaultExcludedDates, + lag + ); +} + +function meanFloat64(series: Float64Array): number | null { + const n = series.length; + if (n === 0) { + return null; + } + let sum = 0; + for (let i = 0; i < n; i++) { + sum += series[i] as number; + } + const avg = sum / n; + return Number.isFinite(avg) ? avg : null; +} + +function trimFloat64(buffer: Float64Array, length: number): Float64Array { + return length === buffer.length ? buffer : buffer.slice(0, length); +} + +/** + * Runs the full cross-sectional signal analysis over a date-ordered panel: + * per-date Pearson & Spearman rank-IC, IC summaries with Newey-West HAC t-stats, + * deterministic-tie-break quantile bucket returns & top-minus-bottom spreads, + * consecutive-date top/bottom quantile turnover, and the pre/post-2023 recency gate + * with optional exclusive `vaultCutoffDate` exclusion. + */ +export function analyzeSignalPanel( + panel: readonly SignalCrossSection[], + options?: SignalAnalysisOptions +): SignalPanelAnalysis { + const minCrossSection = options?.minCrossSection ?? DEFAULT_MIN_CROSS_SECTION; + const q = options?.quantiles ?? DEFAULT_QUANTILE_COUNT; + const lag = options?.lag; + const splitDate = options?.recencySplitDate ?? RECENCY_SPLIT_DATE; + const minRatio = options?.recencyMinRatio ?? RECENCY_MIN_RATIO; + const vaultCutoffDate = options?.vaultCutoffDate; + + assertIntegerOption(minCrossSection, 2, 'minCrossSection'); + assertIntegerOption(q, 2, 'quantiles'); + if (lag !== undefined) { + assertIntegerOption(lag, 0, 'lag'); + } + assertIsoDate(splitDate, 'recencySplitDate'); + assertPositiveFiniteOption(minRatio, 'recencyMinRatio'); + if (vaultCutoffDate !== undefined) { + assertIsoDate(vaultCutoffDate, 'vaultCutoffDate'); + } + + let eligibleDates = 0; + let maxCrossSectionLen = 0; + + for (let t = 0; t < panel.length; t++) { + const slice = panel[t] as SignalCrossSection; + assertIsoDate(slice.date, `panel[${t}].date`); + if (t > 0) { + const prevDate = (panel[t - 1] as SignalCrossSection).date; + if (slice.date === prevDate) { + throw new SignalAnalysisError( + 'DUPLICATE_DATE', + `Duplicate date at panel index ${t}: ${slice.date}` + ); + } + if (slice.date < prevDate) { + throw new SignalAnalysisError( + 'UNSORTED_DATES', + `Panel dates must be strictly ascending: ${prevDate} followed by ${slice.date} at index ${t}` + ); + } + } + + const nIds = slice.ids.length; + const nSig = slice.signal.length; + const nRet = slice.forwardReturn.length; + if (nIds !== nSig || nSig !== nRet) { + throw new SignalAnalysisError( + 'LENGTH_MISMATCH', + `Cross-section length mismatch on ${slice.date}: ids=${nIds}, signal=${nSig}, forwardReturn=${nRet}` + ); + } + + if (vaultCutoffDate === undefined || slice.date < vaultCutoffDate) { + eligibleDates++; + if (nSig > maxCrossSectionLen) { + maxCrossSectionLen = nSig; + } + } + } + + const vaultExcludedDates = panel.length - eligibleDates; + const scratch = createPanelScratch(maxCrossSectionLen); + + const icDates: string[] = []; + const pearsonIcBuf = new Float64Array(eligibleDates); + const rankIcBuf = new Float64Array(eligibleDates); + + const quantileDates: string[] = []; + const perBucketBufs: Float64Array[] = new Array(q); + for (let b = 0; b < q; b++) { + perBucketBufs[b] = new Float64Array(eligibleDates); + } + const spreadBuf = new Float64Array(eligibleDates); + + const turnoverCap = eligibleDates > 1 ? eligibleDates - 1 : 0; + const turnoverDates: string[] = []; + const topTurnoverBuf = new Float64Array(turnoverCap); + const bottomTurnoverBuf = new Float64Array(turnoverCap); + + let prevTop = new Set(); + let currTop = new Set(); + let prevBottom = new Set(); + let currBottom = new Set(); + + let totalObservations = 0; + let validObservations = 0; + let droppedPairs = 0; + let icCount = 0; + let icSkippedBelowMin = 0; + let icSkippedZeroVariance = 0; + let quantileCount = 0; + let quantileSkippedDates = 0; + let turnoverCount = 0; + + const { + validIdx, + validSignal, + validReturn, + orderSignal, + orderReturn, + sortScratch, + rankSignal, + rankReturn, + } = scratch; + + for (let t = 0; t < eligibleDates; t++) { + const slice = panel[t] as SignalCrossSection; + const { ids, signal, forwardReturn } = slice; + const n = signal.length; + totalObservations += n; + + let m = 0; + for (let i = 0; i < n; i++) { + const s = signal[i]; + const r = forwardReturn[i]; + if ( + typeof s === 'number' && + typeof r === 'number' && + Number.isFinite(s) && + Number.isFinite(r) + ) { + validIdx[m] = i; + validSignal[m] = s; + validReturn[m] = r; + orderSignal[m] = m; + m++; + } + } + + validObservations += m; + droppedPairs += n - m; + + const needsIc = m >= minCrossSection; + const needsQuantiles = m >= q; + + if (needsIc || needsQuantiles) { + sortOrderBySignalAndId(orderSignal, validSignal, validIdx, ids, m, sortScratch); + } + + if (!needsIc) { + icSkippedBelowMin++; + } else { + const pearson = twoPassPearson(validSignal, validReturn, m); + if (pearson === null) { + icSkippedZeroVariance++; + } else { + for (let i = 0; i < m; i++) { + orderReturn[i] = i; + } + sortOrderByFloat(orderReturn, validReturn, m, sortScratch); + assignAverageRanks(orderSignal, validSignal, rankSignal, m); + assignAverageRanks(orderReturn, validReturn, rankReturn, m); + + const rankIc = twoPassPearson(rankSignal, rankReturn, m); + if (rankIc === null) { + icSkippedZeroVariance++; + } else { + icDates.push(slice.date); + pearsonIcBuf[icCount] = pearson; + rankIcBuf[icCount] = rankIc; + icCount++; + } + } + } + + if (!needsQuantiles) { + quantileSkippedDates++; + } else { + for (let b = 0; b < q; b++) { + const start = Math.floor((b * m) / q); + const end = Math.floor(((b + 1) * m) / q); + let bucketSum = 0; + for (let k = start; k < end; k++) { + bucketSum += validReturn[orderSignal[k] as number] as number; + } + (perBucketBufs[b] as Float64Array)[quantileCount] = bucketSum / (end - start); + } + + const bottomRet = (perBucketBufs[0] as Float64Array)[quantileCount] as number; + const topRet = (perBucketBufs[q - 1] as Float64Array)[quantileCount] as number; + spreadBuf[quantileCount] = topRet - bottomRet; + quantileDates.push(slice.date); + + currBottom.clear(); + const bottomEnd = Math.floor(m / q); + for (let k = 0; k < bottomEnd; k++) { + currBottom.add(ids[validIdx[orderSignal[k] as number] as number] as EntityId); + } + + currTop.clear(); + const topStart = Math.floor(((q - 1) * m) / q); + for (let k = topStart; k < m; k++) { + currTop.add(ids[validIdx[orderSignal[k] as number] as number] as EntityId); + } + + if (quantileCount > 0) { + let topOverlap = 0; + for (const id of currTop) { + if (prevTop.has(id)) { + topOverlap++; + } + } + let bottomOverlap = 0; + for (const id of currBottom) { + if (prevBottom.has(id)) { + bottomOverlap++; + } + } + topTurnoverBuf[turnoverCount] = 1 - topOverlap / currTop.size; + bottomTurnoverBuf[turnoverCount] = 1 - bottomOverlap / currBottom.size; + turnoverDates.push(slice.date); + turnoverCount++; + } + + const tmpTop = prevTop; + prevTop = currTop; + currTop = tmpTop; + + const tmpBottom = prevBottom; + prevBottom = currBottom; + currBottom = tmpBottom; + + quantileCount++; + } + } + + const pearsonIcSeries = trimFloat64(pearsonIcBuf, icCount); + const rankIcSeries = trimFloat64(rankIcBuf, icCount); + const spreadSeries = trimFloat64(spreadBuf, quantileCount); + const perBucketSeries: Float64Array[] = new Array(q); + const bucketMeanReturns: (number | null)[] = new Array(q); + for (let b = 0; b < q; b++) { + const trimmed = trimFloat64(perBucketBufs[b] as Float64Array, quantileCount); + perBucketSeries[b] = trimmed; + bucketMeanReturns[b] = meanFloat64(trimmed); + } + + const topSeries = trimFloat64(topTurnoverBuf, turnoverCount); + const bottomSeries = trimFloat64(bottomTurnoverBuf, turnoverCount); + + const pearsonIc = summarizeIcSeries(pearsonIcSeries, { lag }); + const rankIc = summarizeIcSeries(rankIcSeries, { lag }); + const spreadSummary = summarizeIcSeries(spreadSeries, { lag }); + const recency = buildRecencySplitResult( + icDates, + rankIcSeries, + splitDate, + minRatio, + vaultCutoffDate ?? null, + vaultExcludedDates, + lag + ); + + return { + dates: icDates, + pearsonIcSeries, + rankIcSeries, + pearsonIc, + rankIc, + quantiles: { + quantiles: q, + validDates: quantileCount, + skippedDates: quantileSkippedDates, + dates: quantileDates, + bucketMeanReturns, + perBucketSeries, + spreadSeries, + spreadSummary, + }, + turnover: { + count: turnoverCount, + dates: turnoverDates, + topSeries, + bottomSeries, + meanTopTurnover: meanFloat64(topSeries), + meanBottomTurnover: meanFloat64(bottomSeries), + }, + recency, + diagnostics: { + totalDates: panel.length, + eligibleDates, + vaultExcludedDates, + totalObservations, + validObservations, + droppedPairs, + icValidDates: icCount, + icSkippedBelowMin, + icSkippedZeroVariance, + quantileValidDates: quantileCount, + quantileSkippedDates, + }, + }; +} diff --git a/libs/calculations/src/index.ts b/libs/calculations/src/index.ts index 001a8609..c82f07d6 100644 --- a/libs/calculations/src/index.ts +++ b/libs/calculations/src/index.ts @@ -56,18 +56,48 @@ export { groupBySymbol, } from './market-data'; export { + DEFAULT_MIN_CROSS_SECTION, + DEFAULT_QUANTILE_COUNT, DSR_VALIDATION_GATE, EULER_MASCHERONI, + RECENCY_MIN_RATIO, + RECENCY_SPLIT_DATE, + SignalAnalysisError, + analyzeSignalPanel, + crossSectionIc, + defaultNeweyWestLag, deflatedSharpeRatio, effectiveIndependentTrials, + evaluateRecencyGate, inverseNormalCdf, + neweyWestMeanTest, normalCdf, passesDsrGate, + summarizeIcSeries, trialMoments, } from './analytics'; export type { + CrossSectionIcOptions, + CrossSectionIcResult, DeflatedSharpeInput, DeflatedSharpeResult, EffectiveTrialsResult, + EntityId, + EntityIdSeries, + IcSummary, + IcSummaryOptions, + NeweyWestResult, + NumericSeries, + QuantileSpreadResult, + RecencyGateOptions, + RecencyGateReason, + RecencyGateResult, + RecencySplitResult, + SignalAnalysisErrorCode, + SignalAnalysisOptions, + SignalCrossSection, + SignalPanelAnalysis, + SignalPanelDiagnostics, TrialMoments, + TurnoverResult, } from './analytics'; diff --git a/libs/calculations/test/signal-analysis.test.ts b/libs/calculations/test/signal-analysis.test.ts new file mode 100644 index 00000000..e443cb6e --- /dev/null +++ b/libs/calculations/test/signal-analysis.test.ts @@ -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'); + }); +});