T-82: M1.4a — Pure signal analyzer math in @stock-bot/calculations: per-date IC / rank-IC, Newey-West t-stat, quantile spreads, turnover and pre/post-2023 recency gate (no I/O)

This commit is contained in:
Studio 2026-11-28 01:47:48 -05:00
parent 659cd042f6
commit d9f0b45251
3 changed files with 344 additions and 59 deletions

View file

@ -15,8 +15,8 @@
* 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`).
* - Observed (Bun 1.2.16, 2 runs): `1,779.96 ms` (`8,494,557 observations/s`) and
* `1,809.95 ms` (`8,353,819 observations/s`).
*/
/** Default minimum finite cross-sectional pairs required to compute per-date IC. */
@ -36,6 +36,7 @@ export type SignalAnalysisErrorCode =
| 'LENGTH_MISMATCH'
| 'UNSORTED_DATES'
| 'DUPLICATE_DATE'
| 'DUPLICATE_ID'
| 'INVALID_DATE'
| 'INVALID_OPTION';
@ -215,6 +216,38 @@ export interface SignalPanelAnalysis {
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;
const RECENCY_ZERO_TOLERANCE_ULPS = 16;
const FAST_ID_EPOCH_LIMIT = 65536;
interface CompensatedSumResult {
readonly sum: number;
readonly absSum: number;
}
function compensatedSum(series: NumericSeries): CompensatedSumResult {
let sum = 0;
let compensation = 0;
let absSum = 0;
for (let i = 0; i < series.length; i++) {
const v = series[i] as number;
const t = sum + v;
if (Math.abs(sum) >= Math.abs(v)) {
compensation += sum - t + v;
} else {
compensation += v - t + sum;
}
sum = t;
absSum += Math.abs(v);
}
return { sum: sum + compensation, absSum };
}
function zeroToleranceForMean(absSum: number, count: number): number {
if (count <= 0 || absSum <= 0) {
return 0;
}
return RECENCY_ZERO_TOLERANCE_ULPS * Number.EPSILON * (absSum / count);
}
function isLeapYear(year: number): boolean {
return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
@ -532,6 +565,77 @@ function twoPassPearson(x: Float64Array, y: Float64Array, length: number): numbe
return rho < -1 ? -1 : rho > 1 ? 1 : rho;
}
function twoPassPearsonOrdered(
x: Float64Array,
y: Float64Array,
order: Int32Array,
length: number
): number | null {
if (length < 2) {
return null;
}
let sumX = 0;
let sumY = 0;
const firstIdx = order[0] as number;
const firstX = x[firstIdx] as number;
const firstY = y[firstIdx] as number;
let allEqualX = true;
let allEqualY = true;
for (let k = 0; k < length; k++) {
const idx = order[k] as number;
const vx = x[idx] as number;
const vy = y[idx] 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 k = 0; k < length; k++) {
const idx = order[k] as number;
const dx = (x[idx] as number) - meanX;
const dy = (y[idx] 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`.
@ -659,6 +763,7 @@ export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWes
const resolvedLag = lag ?? defaultNeweyWestLag(n);
let sum = 0;
let compensation = 0;
const first = series[0] as number;
let allEqual = true;
for (let t = 0; t < n; t++) {
@ -670,13 +775,19 @@ export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWes
lag: resolvedLag,
};
}
sum += v;
const next = sum + v;
if (Math.abs(sum) >= Math.abs(v)) {
compensation += sum - next + v;
} else {
compensation += v - next + sum;
}
sum = next;
if (v !== first) {
allEqual = false;
}
}
const avg = sum / n;
const avg = (sum + compensation) / n;
if (!Number.isFinite(avg) || allEqual) {
return {
status: 'insufficient_data',
@ -741,40 +852,40 @@ export function neweyWestMeanTest(series: NumericSeries, lag?: number): NeweyWes
};
}
/**
* 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');
}
interface IcSummaryWithAbsSum {
readonly summary: IcSummary;
readonly absSum: number;
}
function summarizeIcSeriesInternal(
series: NumericSeries,
lag: number | undefined
): IcSummaryWithAbsSum {
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,
summary: {
count: 0,
mean: null,
std: null,
icir: null,
hitRate: null,
neweyWest: {
status: 'insufficient_data',
reason: 'too_few_observations',
lag: null,
},
},
absSum: 0,
};
}
let sum = 0;
const { sum, absSum } = compensatedSum(series);
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++;
}
@ -787,16 +898,19 @@ export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOpti
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,
summary: {
count: n,
mean: Number.isFinite(avg) ? avg : null,
std: null,
icir: null,
hitRate,
neweyWest: {
status: 'insufficient_data',
reason: 'too_few_observations',
lag: null,
},
},
absSum,
};
}
@ -817,15 +931,31 @@ export function summarizeIcSeries(series: NumericSeries, options?: IcSummaryOpti
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),
summary: {
count: n,
mean: Number.isFinite(avg) ? avg : null,
std,
icir,
hitRate,
neweyWest: neweyWestMeanTest(series, lag),
},
absSum,
};
}
/**
* 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');
}
return summarizeIcSeriesInternal(series, lag).summary;
}
function buildRecencySplitResult(
dates: readonly string[],
rankIc: NumericSeries,
@ -847,19 +977,21 @@ function buildRecencySplitResult(
}
}
const pre = summarizeIcSeries(Float64Array.from(preValues), { lag });
const post = summarizeIcSeries(Float64Array.from(postValues), { lag });
const preStats = summarizeIcSeriesInternal(Float64Array.from(preValues), lag);
const postStats = summarizeIcSeriesInternal(Float64Array.from(postValues), lag);
const pre = preStats.summary;
const post = postStats.summary;
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) {
} else if (pre.mean <= zeroToleranceForMean(preStats.absSum, pre.count)) {
gate = { pass: false, reason: 'non_positive_pre_mean', ratio: null };
} else {
const ratio = post.mean / pre.mean;
if (post.mean <= 0) {
if (post.mean <= zeroToleranceForMean(postStats.absSum, post.count)) {
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 };
@ -959,11 +1091,7 @@ function meanFloat64(series: Float64Array): number | null {
if (n === 0) {
return null;
}
let sum = 0;
for (let i = 0; i < n; i++) {
sum += series[i] as number;
}
const avg = sum / n;
const avg = compensatedSum(series).sum / n;
return Number.isFinite(avg) ? avg : null;
}
@ -1063,6 +1191,9 @@ export function analyzeSignalPanel(
let currTop = new Set<EntityId>();
let prevBottom = new Set<EntityId>();
let currBottom = new Set<EntityId>();
const seenEpoch = new Int32Array(FAST_ID_EPOCH_LIMIT);
const seenIds = new Set<EntityId>();
let idEpoch = 0;
let totalObservations = 0;
let validObservations = 0;
@ -1091,6 +1222,15 @@ export function analyzeSignalPanel(
const n = signal.length;
totalObservations += n;
idEpoch++;
if (idEpoch === 0x7fffffff) {
seenEpoch.fill(0);
idEpoch = 1;
}
if (seenIds.size > 0) {
seenIds.clear();
}
let m = 0;
for (let i = 0; i < n; i++) {
const s = signal[i];
@ -1101,6 +1241,30 @@ export function analyzeSignalPanel(
Number.isFinite(s) &&
Number.isFinite(r)
) {
const id = ids[i] as EntityId;
if (
typeof id === 'number' &&
(id | 0) === id &&
id >= 0 &&
id < FAST_ID_EPOCH_LIMIT
) {
if (seenEpoch[id] === idEpoch) {
throw new SignalAnalysisError(
'DUPLICATE_ID',
`Duplicate entity id ${String(id)} on ${slice.date}`
);
}
seenEpoch[id] = idEpoch;
} else {
if (seenIds.has(id)) {
throw new SignalAnalysisError(
'DUPLICATE_ID',
`Duplicate entity id ${String(id)} on ${slice.date}`
);
}
seenIds.add(id);
}
validIdx[m] = i;
validSignal[m] = s;
validReturn[m] = r;
@ -1122,7 +1286,7 @@ export function analyzeSignalPanel(
if (!needsIc) {
icSkippedBelowMin++;
} else {
const pearson = twoPassPearson(validSignal, validReturn, m);
const pearson = twoPassPearsonOrdered(validSignal, validReturn, orderSignal, m);
if (pearson === null) {
icSkippedZeroVariance++;
} else {
@ -1133,7 +1297,7 @@ export function analyzeSignalPanel(
assignAverageRanks(orderSignal, validSignal, rankSignal, m);
assignAverageRanks(orderReturn, validReturn, rankReturn, m);
const rankIc = twoPassPearson(rankSignal, rankReturn, m);
const rankIc = twoPassPearsonOrdered(rankSignal, rankReturn, orderSignal, m);
if (rankIc === null) {
icSkippedZeroVariance++;
} else {