1275 lines
36 KiB
TypeScript
1275 lines
36 KiB
TypeScript
/**
|
|
* 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<EntityId>();
|
|
let currTop = new Set<EntityId>();
|
|
let prevBottom = new Set<EntityId>();
|
|
let currBottom = new Set<EntityId>();
|
|
|
|
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,
|
|
},
|
|
};
|
|
}
|