929 lines
32 KiB
TypeScript
929 lines
32 KiB
TypeScript
import { describe, expect, it } from 'bun:test';
|
|
import type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations';
|
|
import {
|
|
SignalStudyError,
|
|
analyzeSignal,
|
|
runEventStudy,
|
|
type AnalyzeSignalRequest,
|
|
type RunEventStudyRequest,
|
|
type SignalStudyErrorCode,
|
|
type TrialLedgerExecutor,
|
|
} from '@stock-bot/research';
|
|
import {
|
|
SignalStudyError as SubpathSignalStudyError,
|
|
analyzeSignal as subpathAnalyzeSignal,
|
|
runEventStudy as subpathRunEventStudy,
|
|
} from '@stock-bot/research/signal-study';
|
|
|
|
const VAULT_CUTOFF = '2025-05-01';
|
|
const VALID_CAMPAIGN_ID = '11111111-2222-4333-8444-555555555555';
|
|
const VALID_HYPOTHESIS_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee';
|
|
|
|
interface RecordedSqlCall {
|
|
readonly text: string;
|
|
readonly params: readonly unknown[] | undefined;
|
|
}
|
|
|
|
interface StoredTrialRow {
|
|
readonly trial_id: string;
|
|
readonly created_at: Date;
|
|
readonly principal_id: string;
|
|
readonly campaign_id: string | null;
|
|
readonly stage: string;
|
|
readonly universe_market: string;
|
|
readonly horizon_bucket: string;
|
|
readonly hypothesis_id: string | null;
|
|
readonly expression_hash: string;
|
|
readonly sample_start: string;
|
|
readonly sample_end: string;
|
|
readonly n_obs: number;
|
|
readonly sharpe_unann: number;
|
|
readonly skewness: number;
|
|
readonly kurtosis: number;
|
|
readonly daily_series: readonly number[];
|
|
}
|
|
|
|
interface InMemoryExecutorOptions {
|
|
readonly failOnInsert?: Error;
|
|
readonly failOnDsrRead?: Error;
|
|
}
|
|
|
|
function createInMemoryTrialExecutor(options: InMemoryExecutorOptions = {}): {
|
|
executor: TrialLedgerExecutor;
|
|
calls: RecordedSqlCall[];
|
|
rows: StoredTrialRow[];
|
|
} {
|
|
const calls: RecordedSqlCall[] = [];
|
|
const rows: StoredTrialRow[] = [];
|
|
let nextTrialId = 100;
|
|
|
|
const executor: TrialLedgerExecutor = {
|
|
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
|
|
calls.push({ text, params });
|
|
const trimmed = text.trimStart();
|
|
|
|
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
|
|
if (options.failOnInsert !== undefined) {
|
|
throw options.failOnInsert;
|
|
}
|
|
const p = params ?? [];
|
|
const trialId = ++nextTrialId;
|
|
const createdAt = new Date(Date.UTC(2025, 3, 1, 12, 0, trialId));
|
|
const dailySeries = (p[13] as readonly number[]).map(v => Math.fround(v));
|
|
const stored: StoredTrialRow = {
|
|
trial_id: String(trialId),
|
|
created_at: createdAt,
|
|
principal_id: p[0] as string,
|
|
campaign_id: (p[1] as string | null) ?? null,
|
|
stage: p[2] as string,
|
|
universe_market: p[3] as string,
|
|
horizon_bucket: p[4] as string,
|
|
hypothesis_id: (p[5] as string | null) ?? null,
|
|
expression_hash: p[6] as string,
|
|
sample_start: p[7] as string,
|
|
sample_end: p[8] as string,
|
|
n_obs: p[9] as number,
|
|
sharpe_unann: p[10] as number,
|
|
skewness: p[11] as number,
|
|
kurtosis: p[12] as number,
|
|
daily_series: dailySeries,
|
|
};
|
|
rows.push(stored);
|
|
return {
|
|
rows: [{ trial_id: stored.trial_id, created_at: stored.created_at } as unknown as Row],
|
|
rowCount: 1,
|
|
};
|
|
}
|
|
|
|
if (trimmed.startsWith('SELECT')) {
|
|
if (options.failOnDsrRead !== undefined) {
|
|
throw options.failOnDsrRead;
|
|
}
|
|
if (text.includes('WHERE trial_id = $1::bigint')) {
|
|
const targetId = String(params?.[0]);
|
|
const matched = rows.filter(r => r.trial_id === targetId);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
if (text.includes('WHERE universe_market = $1')) {
|
|
const market = params?.[0] as string;
|
|
const bucket = params?.[1] as string;
|
|
const matched = rows.filter(
|
|
r => r.universe_market === market && r.horizon_bucket === bucket
|
|
);
|
|
return { rows: matched as unknown as Row[], rowCount: matched.length };
|
|
}
|
|
}
|
|
|
|
return { rows: [], rowCount: 0 };
|
|
},
|
|
};
|
|
|
|
return { executor, calls, rows };
|
|
}
|
|
|
|
function createSeededRng(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) / 4_294_967_296;
|
|
};
|
|
}
|
|
|
|
function makeBusinessDates(startDate: string, count: number): string[] {
|
|
const out: string[] = new Array(count);
|
|
const current = new Date(`${startDate}T00:00:00.000Z`);
|
|
let written = 0;
|
|
while (written < count) {
|
|
const day = current.getUTCDay();
|
|
if (day !== 0 && day !== 6) {
|
|
out[written] = current.toISOString().slice(0, 10);
|
|
written += 1;
|
|
}
|
|
current.setUTCDate(current.getUTCDate() + 1);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
function makeSignalPanel(dates: readonly string[], nNames = 15, seed = 42): SignalCrossSection[] {
|
|
const rand = createSeededRng(seed);
|
|
const ids = Array.from({ length: nNames }, (_, i) => i + 1);
|
|
return dates.map((date, t) => {
|
|
const signal = new Float64Array(nNames);
|
|
const forwardReturn = new Float64Array(nNames);
|
|
const slope = 0.002 + ((t % 5) - 2) * 0.0005;
|
|
for (let i = 0; i < nNames; i += 1) {
|
|
const s = rand() * 2 - 1;
|
|
signal[i] = s;
|
|
forwardReturn[i] = 0.0005 + slope * s + 0.015 * (rand() * 2 - 1);
|
|
}
|
|
return { date, ids, signal, forwardReturn };
|
|
});
|
|
}
|
|
|
|
function makeSignalRequest(overrides: Partial<AnalyzeSignalRequest> = {}): AnalyzeSignalRequest {
|
|
const dates = makeBusinessDates('2025-03-03', 20);
|
|
return {
|
|
principalId: 'operator',
|
|
campaignId: VALID_CAMPAIGN_ID,
|
|
hypothesisId: VALID_HYPOTHESIS_ID,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
|
params: { lookback: 20 },
|
|
universe: 'US_EQ_TOP3000',
|
|
horizon: '5d',
|
|
},
|
|
panel: makeSignalPanel(dates),
|
|
vaultCutoffDate: VAULT_CUTOFF,
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
function makeEventStudyInput(
|
|
dates: readonly string[],
|
|
eventDayIndices: readonly number[],
|
|
seed = 99
|
|
): EventStudyInput {
|
|
const rand = createSeededRng(seed);
|
|
const entityReturns = new Map<number, Float64Array>();
|
|
for (let entityId = 1; entityId <= 4; entityId += 1) {
|
|
const series = new Float64Array(dates.length);
|
|
for (let t = 0; t < dates.length; t += 1) {
|
|
series[t] = (rand() - 0.5) * 0.02;
|
|
}
|
|
entityReturns.set(entityId, series);
|
|
}
|
|
const benchmarkReturns = new Float64Array(dates.length);
|
|
for (let t = 0; t < dates.length; t += 1) {
|
|
benchmarkReturns[t] = (rand() - 0.5) * 0.01;
|
|
}
|
|
const events = eventDayIndices.map((dayIndex, idx) => ({
|
|
entityId: (idx % 4) + 1,
|
|
dayIndex,
|
|
}));
|
|
return {
|
|
sessionDates: dates,
|
|
entityReturns,
|
|
benchmarkReturns,
|
|
events,
|
|
};
|
|
}
|
|
|
|
function makeEventStudyRequest(
|
|
overrides: Partial<RunEventStudyRequest> = {}
|
|
): RunEventStudyRequest {
|
|
const dates = makeBusinessDates('2025-01-02', 60);
|
|
return {
|
|
principalId: 'operator',
|
|
campaignId: VALID_CAMPAIGN_ID,
|
|
hypothesisId: VALID_HYPOTHESIS_ID,
|
|
universeMarket: 'US_EQ',
|
|
horizonBucket: 'swing_1_10d',
|
|
expression: {
|
|
expression: 'earnings_surprise_car',
|
|
params: { minSurprisePct: 5 },
|
|
universe: 'US_EQ_TOP3000',
|
|
horizon: '5d',
|
|
},
|
|
input: makeEventStudyInput(dates, [12, 16, 20, 24, 28, 32]),
|
|
vaultCutoffDate: VAULT_CUTOFF,
|
|
options: { preDays: 5, postDays: 5, minEvents: 5 },
|
|
...overrides,
|
|
};
|
|
}
|
|
|
|
async function expectStudyError(
|
|
fn: () => Promise<unknown>,
|
|
expectedCode: SignalStudyErrorCode
|
|
): Promise<SignalStudyError> {
|
|
try {
|
|
await fn();
|
|
} catch (error) {
|
|
expect(error).toBeInstanceOf(SignalStudyError);
|
|
const typed = error as SignalStudyError;
|
|
expect(typed.code).toBe(expectedCode);
|
|
return typed;
|
|
}
|
|
throw new Error(`Expected SignalStudyError(${expectedCode}), but call succeeded`);
|
|
}
|
|
|
|
describe('signal-study exports', () => {
|
|
it('exposes identical runtime exports from package root and subpath', () => {
|
|
expect(analyzeSignal).toBe(subpathAnalyzeSignal);
|
|
expect(runEventStudy).toBe(subpathRunEventStudy);
|
|
expect(SignalStudyError).toBe(SubpathSignalStudyError);
|
|
});
|
|
});
|
|
|
|
describe('analyzeSignal', () => {
|
|
it('runs happy path with default rank_ic series, issuing 1 INSERT then 2 SELECTs', async () => {
|
|
const { executor, calls, rows } = createInMemoryTrialExecutor();
|
|
const request = makeSignalRequest();
|
|
|
|
const result = await analyzeSignal(executor, request);
|
|
|
|
expect(result.status).toBe('ok');
|
|
if (result.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
expect(calls).toHaveLength(3);
|
|
expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true);
|
|
expect(calls[0]?.params?.[2]).toBe('signal_ic');
|
|
expect(calls[1]?.text).toContain('WHERE trial_id = $1::bigint');
|
|
expect(calls[2]?.text).toContain('WHERE universe_market = $1');
|
|
|
|
expect(rows).toHaveLength(1);
|
|
expect(result.trial.trialId).toBe(101);
|
|
expect(result.trial.nObs).toBe(result.analysis.rankIcSeries.length);
|
|
expect(result.trial.sampleStart).toBe(result.analysis.dates[0]!);
|
|
expect(result.trial.sampleEnd).toBe(result.analysis.dates[result.analysis.dates.length - 1]!);
|
|
expect(result.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
|
expect(result.trial.expressionHash).toMatch(/^[0-9a-f]{64}$/);
|
|
expect(result.deflatedSharpe.trialId).toBe(101);
|
|
expect(result.deflatedSharpe.clusterSize).toBe(1);
|
|
expect(Number.isFinite(result.deflatedSharpe.effectiveTrials)).toBe(true);
|
|
});
|
|
|
|
it('logs quantile spread series when ledgerSeries is quantile_spread', async () => {
|
|
const { executor, calls, rows } = createInMemoryTrialExecutor();
|
|
const request = makeSignalRequest({ ledgerSeries: 'quantile_spread' });
|
|
|
|
const result = await analyzeSignal(executor, request);
|
|
|
|
expect(result.status).toBe('ok');
|
|
if (result.status !== 'ok') {
|
|
return;
|
|
}
|
|
expect(calls).toHaveLength(3);
|
|
expect(rows).toHaveLength(1);
|
|
expect(result.trial.nObs).toBe(result.analysis.quantiles.spreadSeries.length);
|
|
expect(result.trial.sampleStart).toBe(result.analysis.quantiles.dates[0]!);
|
|
expect(result.trial.sampleEnd).toBe(
|
|
result.analysis.quantiles.dates[result.analysis.quantiles.dates.length - 1]!
|
|
);
|
|
const logged = rows[0]!.daily_series;
|
|
expect(logged).toHaveLength(result.analysis.quantiles.spreadSeries.length);
|
|
for (let i = 0; i < logged.length; i += 1) {
|
|
expect(logged[i]).toBe(Math.fround(result.analysis.quantiles.spreadSeries[i]!));
|
|
}
|
|
});
|
|
|
|
it('returns insufficient_data with zero queries when fewer than 2 valid dates remain', async () => {
|
|
const { executor, calls } = createInMemoryTrialExecutor();
|
|
const dates = ['2025-04-30', '2025-05-01', '2025-05-02'];
|
|
const request = makeSignalRequest({
|
|
panel: makeSignalPanel(dates),
|
|
vaultCutoffDate: VAULT_CUTOFF,
|
|
});
|
|
|
|
const result = await analyzeSignal(executor, request);
|
|
|
|
expect(result.status).toBe('insufficient_data');
|
|
if (result.status === 'insufficient_data') {
|
|
expect(result.reason).toBe('too_few_observations');
|
|
}
|
|
expect(calls).toHaveLength(0);
|
|
});
|
|
|
|
it('returns insufficient_data with zero queries when rankIcSeries has zero variance', async () => {
|
|
const { executor, calls } = createInMemoryTrialExecutor();
|
|
const dates = makeBusinessDates('2025-03-03', 6);
|
|
const ids = [1, 2, 3, 4, 5, 6];
|
|
const panel: SignalCrossSection[] = dates.map(date => ({
|
|
date,
|
|
ids,
|
|
signal: [1, 2, 3, 4, 5, 6],
|
|
forwardReturn: [0.01, 0.02, 0.03, 0.04, 0.05, 0.06],
|
|
}));
|
|
|
|
const result = await analyzeSignal(executor, makeSignalRequest({ panel }));
|
|
|
|
expect(result.status).toBe('insufficient_data');
|
|
if (result.status === 'insufficient_data') {
|
|
expect(result.reason).toBe('zero_variance_series');
|
|
}
|
|
expect(calls).toHaveLength(0);
|
|
});
|
|
|
|
it('excludes dates >= vaultCutoffDate and is bit-invariant to post-cutoff mutations', async () => {
|
|
const preDates = makeBusinessDates('2025-04-01', 12);
|
|
const postDates = ['2025-05-01', '2025-05-02', '2025-05-05'];
|
|
const allDates = [...preDates, ...postDates];
|
|
const basePanel = makeSignalPanel(allDates, 15, 77);
|
|
|
|
const mutatedPanel: SignalCrossSection[] = basePanel.map(slice => {
|
|
if (slice.date >= VAULT_CUTOFF) {
|
|
return {
|
|
...slice,
|
|
signal: Array.from({ length: slice.ids.length }, (_, i) => (i + 1) * 999),
|
|
forwardReturn: Array.from({ length: slice.ids.length }, () => -0.75),
|
|
};
|
|
}
|
|
return slice;
|
|
});
|
|
|
|
const run1Store = createInMemoryTrialExecutor();
|
|
const run2Store = createInMemoryTrialExecutor();
|
|
const res1 = await analyzeSignal(run1Store.executor, makeSignalRequest({ panel: basePanel }));
|
|
const res2 = await analyzeSignal(
|
|
run2Store.executor,
|
|
makeSignalRequest({ panel: mutatedPanel })
|
|
);
|
|
|
|
expect(res1.status).toBe('ok');
|
|
expect(res2.status).toBe('ok');
|
|
if (res1.status !== 'ok' || res2.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
expect(res1.analysis.diagnostics.vaultExcludedDates).toBe(3);
|
|
expect(res1.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
|
expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash);
|
|
expect(res1.trial.sampleStart).toBe(res2.trial.sampleStart);
|
|
expect(res1.trial.sampleEnd).toBe(res2.trial.sampleEnd);
|
|
expect(Array.from(res1.analysis.rankIcSeries)).toEqual(Array.from(res2.analysis.rankIcSeries));
|
|
expect(run1Store.rows[0]?.daily_series).toEqual(run2Store.rows[0]?.daily_series);
|
|
});
|
|
|
|
it('produces identical expressionHash for identical requests and different hashes on param change', async () => {
|
|
const store1 = createInMemoryTrialExecutor();
|
|
const store2 = createInMemoryTrialExecutor();
|
|
const store3 = createInMemoryTrialExecutor();
|
|
|
|
const baseReq = makeSignalRequest();
|
|
const res1 = await analyzeSignal(store1.executor, baseReq);
|
|
const res2 = await analyzeSignal(store2.executor, baseReq);
|
|
const res3 = await analyzeSignal(
|
|
store3.executor,
|
|
makeSignalRequest({
|
|
panel: baseReq.panel,
|
|
expression: {
|
|
...baseReq.expression,
|
|
params: { lookback: 40 },
|
|
},
|
|
})
|
|
);
|
|
|
|
expect(res1.status).toBe('ok');
|
|
expect(res2.status).toBe('ok');
|
|
expect(res3.status).toBe('ok');
|
|
if (res1.status === 'ok' && res2.status === 'ok' && res3.status === 'ok') {
|
|
expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash);
|
|
expect(res1.trial.expressionHash).not.toBe(res3.trial.expressionHash);
|
|
}
|
|
});
|
|
|
|
it('propagates INSERT failure with no result and 1 total query', async () => {
|
|
const insertError = new Error('simulated pg insert failure');
|
|
const { executor, calls } = createInMemoryTrialExecutor({ failOnInsert: insertError });
|
|
|
|
await expect(analyzeSignal(executor, makeSignalRequest())).rejects.toBe(insertError);
|
|
expect(calls).toHaveLength(1);
|
|
expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true);
|
|
});
|
|
|
|
it('throws SignalStudyError(dsr_read_failed) carrying trialId and cause without retrying INSERT', async () => {
|
|
const readError = new Error('simulated pg select failure');
|
|
const { executor, calls, rows } = createInMemoryTrialExecutor({ failOnDsrRead: readError });
|
|
|
|
const err = await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest()),
|
|
'dsr_read_failed'
|
|
);
|
|
expect(err.trialId).toBe(101);
|
|
expect(err.cause).toBe(readError);
|
|
expect(rows).toHaveLength(1);
|
|
const insertCount = calls.filter(c => c.text.trimStart().startsWith('INSERT')).length;
|
|
expect(insertCount).toBe(1);
|
|
});
|
|
|
|
it('rejects invalid inputs with typed SignalStudyError codes and zero SQL queries', async () => {
|
|
const { executor, calls } = createInMemoryTrialExecutor();
|
|
|
|
await expectStudyError(
|
|
() => analyzeSignal(null as unknown as TrialLedgerExecutor, makeSignalRequest()),
|
|
'invalid_request'
|
|
);
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ panel: [] })),
|
|
'empty_panel'
|
|
);
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ vaultCutoffDate: '2025-02-30' })),
|
|
'invalid_date'
|
|
);
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ principalId: 'bad-principal' })),
|
|
'invalid_request'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
analyzeSignal(
|
|
executor,
|
|
makeSignalRequest({
|
|
ledgerSeries: 'bad_series' as unknown as 'rank_ic',
|
|
})
|
|
),
|
|
'invalid_option'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
analyzeSignal(
|
|
executor,
|
|
makeSignalRequest({
|
|
ledgerSeries: null as unknown as 'rank_ic',
|
|
})
|
|
),
|
|
'invalid_option'
|
|
);
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ dsrGate: Number.NaN })),
|
|
'invalid_option'
|
|
);
|
|
|
|
const unsortedPanel = makeSignalPanel(['2025-03-05', '2025-03-04']);
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ panel: unsortedPanel })),
|
|
'unsorted_dates'
|
|
);
|
|
|
|
const duplicatePanel = makeSignalPanel(['2025-03-05', '2025-03-05']);
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ panel: duplicatePanel })),
|
|
'duplicate_date'
|
|
);
|
|
|
|
const mismatchedPanel: SignalCrossSection[] = [
|
|
{ date: '2025-03-05', ids: [1, 2, 3], signal: [1, 2], forwardReturn: [0.1, 0.2, 0.3] },
|
|
];
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ panel: mismatchedPanel })),
|
|
'invalid_panel'
|
|
);
|
|
|
|
// Missing or malformed cross-section vectors must throw SignalStudyError('invalid_panel'),
|
|
// never a raw TypeError, and issue zero SQL queries.
|
|
const missingForwardReturnPanel = [
|
|
{ date: '2025-03-05', ids: [1, 2, 3], signal: [1, 2, 3] },
|
|
] as unknown as SignalCrossSection[];
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ panel: missingForwardReturnPanel })),
|
|
'invalid_panel'
|
|
);
|
|
const nullSlicePanel = [null] as unknown as SignalCrossSection[];
|
|
await expectStudyError(
|
|
() => analyzeSignal(executor, makeSignalRequest({ panel: nullSlicePanel })),
|
|
'invalid_panel'
|
|
);
|
|
|
|
expect(calls).toHaveLength(0);
|
|
});
|
|
|
|
it('supports typed-array panel vectors and falls back conservatively to count-based DSR across cluster trials', async () => {
|
|
const { executor, rows } = createInMemoryTrialExecutor();
|
|
const dates = makeBusinessDates('2025-03-03', 12);
|
|
const typedPanel: SignalCrossSection[] = makeSignalPanel(dates, 12, 111).map(slice => ({
|
|
date: slice.date,
|
|
ids: Int32Array.from(slice.ids as number[]),
|
|
signal: slice.signal,
|
|
forwardReturn: slice.forwardReturn,
|
|
}));
|
|
|
|
const first = await analyzeSignal(executor, makeSignalRequest({ panel: typedPanel }));
|
|
const second = await analyzeSignal(
|
|
executor,
|
|
makeSignalRequest({
|
|
panel: typedPanel,
|
|
expression: {
|
|
expression: 'rank(ret_10d)',
|
|
params: { lookback: 10 },
|
|
universe: 'US_EQ_TOP3000',
|
|
horizon: '5d',
|
|
},
|
|
})
|
|
);
|
|
|
|
expect(first.status).toBe('ok');
|
|
expect(second.status).toBe('ok');
|
|
if (first.status !== 'ok' || second.status !== 'ok') {
|
|
return;
|
|
}
|
|
expect(rows).toHaveLength(2);
|
|
expect(second.deflatedSharpe.clusterSize).toBe(2);
|
|
expect(second.deflatedSharpe.pairsUsed).toBe(0);
|
|
expect(second.deflatedSharpe.pairsSkipped).toBe(1);
|
|
expect(second.deflatedSharpe.effectiveTrials).toBe(2);
|
|
});
|
|
|
|
it('does not mutate frozen caller inputs', async () => {
|
|
const { executor } = createInMemoryTrialExecutor();
|
|
const dates = makeBusinessDates('2025-03-03', 10);
|
|
const panel = Object.freeze(
|
|
makeSignalPanel(dates).map(slice =>
|
|
Object.freeze({
|
|
date: slice.date,
|
|
ids: Object.freeze([...slice.ids]),
|
|
signal: Object.freeze([...slice.signal]),
|
|
forwardReturn: Object.freeze([...slice.forwardReturn]),
|
|
})
|
|
)
|
|
);
|
|
const expression = Object.freeze({
|
|
expression: 'rank(ret_5d)',
|
|
params: Object.freeze({ lookback: 5 }),
|
|
universe: 'US_EQ',
|
|
horizon: '5d',
|
|
});
|
|
const options = Object.freeze({ minCrossSection: 5, quantiles: 5 });
|
|
const request = Object.freeze(makeSignalRequest({ panel, expression, options }));
|
|
|
|
const result = await analyzeSignal(executor, request);
|
|
expect(result.status).toBe('ok');
|
|
});
|
|
});
|
|
|
|
describe('runEventStudy', () => {
|
|
it('runs happy path issuing 1 INSERT (stage=event_study) then 2 SELECTs', async () => {
|
|
const { executor, calls, rows } = createInMemoryTrialExecutor();
|
|
const request = makeEventStudyRequest();
|
|
|
|
const result = await runEventStudy(executor, request);
|
|
|
|
expect(result.status).toBe('ok');
|
|
if (result.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
expect(calls).toHaveLength(3);
|
|
expect(calls[0]?.text.trimStart().startsWith('INSERT INTO trial_ledger')).toBe(true);
|
|
expect(calls[0]?.params?.[2]).toBe('event_study');
|
|
expect(calls[1]?.text).toContain('WHERE trial_id = $1::bigint');
|
|
expect(calls[2]?.text).toContain('WHERE universe_market = $1');
|
|
|
|
expect(rows).toHaveLength(1);
|
|
expect(result.vaultExcludedEvents).toBe(0);
|
|
expect(result.trial.trialId).toBe(101);
|
|
expect(result.trial.nObs).toBe(result.study.clustered.meanCars.length);
|
|
expect(result.trial.sampleStart).toBe(result.study.clustered.dates[0]!);
|
|
expect(result.trial.sampleEnd).toBe(
|
|
result.study.clustered.dates[result.study.clustered.dates.length - 1]!
|
|
);
|
|
expect(result.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
|
expect(result.deflatedSharpe.clusterSize).toBe(1);
|
|
});
|
|
|
|
it('fences events whose event date OR post-event window end >= vaultCutoffDate and is bit-invariant to post-cutoff return mutations', async () => {
|
|
const dates = makeBusinessDates('2025-03-03', 55);
|
|
const cutoffIdx = dates.findIndex(d => d >= VAULT_CUTOFF);
|
|
expect(cutoffIdx).toBeGreaterThan(25);
|
|
|
|
const postDays = 5;
|
|
// 5 safe events strictly ending before cutoff;
|
|
// 1 event before cutoff whose dayIndex + postDays lands ON cutoff;
|
|
// 1 event ON cutoff;
|
|
// 1 event AFTER cutoff.
|
|
const eventDayIndices = [
|
|
6,
|
|
10,
|
|
14,
|
|
18,
|
|
22,
|
|
cutoffIdx - postDays,
|
|
cutoffIdx,
|
|
cutoffIdx + 2,
|
|
];
|
|
const baseInput = makeEventStudyInput(dates, eventDayIndices, 303);
|
|
|
|
const mutatedReturns = new Map<number, Float64Array>();
|
|
for (const [id, series] of baseInput.entityReturns.entries()) {
|
|
const copy = new Float64Array(series);
|
|
for (let t = cutoffIdx; t < copy.length; t += 1) {
|
|
copy[t] = 0.95;
|
|
}
|
|
mutatedReturns.set(id, copy);
|
|
}
|
|
const mutatedBenchmark = new Float64Array(baseInput.benchmarkReturns!);
|
|
for (let t = cutoffIdx; t < mutatedBenchmark.length; t += 1) {
|
|
mutatedBenchmark[t] = -0.5;
|
|
}
|
|
const mutatedInput: EventStudyInput = {
|
|
...baseInput,
|
|
entityReturns: mutatedReturns,
|
|
benchmarkReturns: mutatedBenchmark,
|
|
};
|
|
|
|
const store1 = createInMemoryTrialExecutor();
|
|
const store2 = createInMemoryTrialExecutor();
|
|
const res1 = await runEventStudy(
|
|
store1.executor,
|
|
makeEventStudyRequest({ input: baseInput, options: { preDays: 3, postDays, minEvents: 5 } })
|
|
);
|
|
const res2 = await runEventStudy(
|
|
store2.executor,
|
|
makeEventStudyRequest({
|
|
input: mutatedInput,
|
|
options: { preDays: 3, postDays, minEvents: 5 },
|
|
})
|
|
);
|
|
|
|
expect(res1.status).toBe('ok');
|
|
expect(res2.status).toBe('ok');
|
|
if (res1.status !== 'ok' || res2.status !== 'ok') {
|
|
return;
|
|
}
|
|
|
|
expect(res1.vaultExcludedEvents).toBe(3);
|
|
expect(res2.vaultExcludedEvents).toBe(3);
|
|
expect(res1.study.diagnostics.eventsUsed).toBe(5);
|
|
expect(res1.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
|
|
expect(res1.trial.expressionHash).toBe(res2.trial.expressionHash);
|
|
expect(Array.from(res1.study.clustered.meanCars)).toEqual(
|
|
Array.from(res2.study.clustered.meanCars)
|
|
);
|
|
expect(store1.rows[0]?.daily_series).toEqual(store2.rows[0]?.daily_series);
|
|
|
|
// Non-finite returns (e.g. Infinity from zero prior price) in the excluded Vault tail
|
|
// must not fail the pre-Vault study or alter its outputs or ledger values.
|
|
const infiniteTailReturns = new Map<number, Float64Array>();
|
|
for (const [id, series] of baseInput.entityReturns.entries()) {
|
|
const copy = new Float64Array(series);
|
|
copy[cutoffIdx] = Number.POSITIVE_INFINITY;
|
|
copy[copy.length - 1] = Number.NEGATIVE_INFINITY;
|
|
infiniteTailReturns.set(id, copy);
|
|
}
|
|
const infiniteTailBenchmark = new Float64Array(baseInput.benchmarkReturns!);
|
|
infiniteTailBenchmark[cutoffIdx] = Number.POSITIVE_INFINITY;
|
|
const store3 = createInMemoryTrialExecutor();
|
|
const res3 = await runEventStudy(
|
|
store3.executor,
|
|
makeEventStudyRequest({
|
|
input: {
|
|
...baseInput,
|
|
entityReturns: infiniteTailReturns,
|
|
benchmarkReturns: infiniteTailBenchmark,
|
|
},
|
|
options: { preDays: 3, postDays, minEvents: 5 },
|
|
})
|
|
);
|
|
expect(res3.status).toBe('ok');
|
|
if (res3.status !== 'ok') {
|
|
return;
|
|
}
|
|
expect(res3.vaultExcludedEvents).toBe(3);
|
|
expect(res3.trial.expressionHash).toBe(res1.trial.expressionHash);
|
|
expect(Array.from(res3.study.clustered.meanCars)).toEqual(
|
|
Array.from(res1.study.clustered.meanCars)
|
|
);
|
|
expect(store3.rows[0]?.daily_series).toEqual(store1.rows[0]?.daily_series);
|
|
});
|
|
|
|
it('returns insufficient_data with zero queries for below_min_events, too_few_event_dates, and zero-variance clustered CARs', async () => {
|
|
const { executor, calls } = createInMemoryTrialExecutor();
|
|
const dates = makeBusinessDates('2025-01-02', 40);
|
|
|
|
// below_min_events
|
|
const resBelowMin = await runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: makeEventStudyInput(dates, [10, 15]),
|
|
options: { preDays: 3, postDays: 3, minEvents: 5 },
|
|
})
|
|
);
|
|
expect(resBelowMin.status).toBe('insufficient_data');
|
|
if (resBelowMin.status === 'insufficient_data') {
|
|
expect(resBelowMin.reason).toBe('below_min_events');
|
|
}
|
|
|
|
// too_few_event_dates (all 5 events on the exact same dayIndex)
|
|
const sameDayInput = makeEventStudyInput(dates, [15, 15, 15, 15]);
|
|
const sameDayWithFive = {
|
|
...sameDayInput,
|
|
entityReturns: new Map([
|
|
...sameDayInput.entityReturns.entries(),
|
|
[5, new Float64Array(dates.length).fill(0.005)],
|
|
]),
|
|
events: [1, 2, 3, 4, 5].map(entityId => ({ entityId, dayIndex: 15 })),
|
|
};
|
|
const resTooFewDates = await runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: sameDayWithFive,
|
|
options: { preDays: 3, postDays: 3, minEvents: 5 },
|
|
})
|
|
);
|
|
expect(resTooFewDates.status).toBe('insufficient_data');
|
|
if (resTooFewDates.status === 'insufficient_data') {
|
|
expect(resTooFewDates.reason).toBe('too_few_event_dates');
|
|
}
|
|
|
|
// zero_variance_series (identical constant returns on every date -> identical clustered meanCars)
|
|
const constantReturns = new Map<number, Float64Array>([
|
|
[1, new Float64Array(dates.length).fill(0.01)],
|
|
[2, new Float64Array(dates.length).fill(0.01)],
|
|
]);
|
|
const constantInput: EventStudyInput = {
|
|
sessionDates: dates,
|
|
entityReturns: constantReturns,
|
|
events: [
|
|
{ entityId: 1, dayIndex: 6 },
|
|
{ entityId: 2, dayIndex: 10 },
|
|
{ entityId: 1, dayIndex: 14 },
|
|
{ entityId: 2, dayIndex: 18 },
|
|
{ entityId: 1, dayIndex: 22 },
|
|
],
|
|
};
|
|
const resZeroVar = await runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: constantInput,
|
|
options: { preDays: 2, postDays: 2, minEvents: 5 },
|
|
})
|
|
);
|
|
expect(resZeroVar.status).toBe('insufficient_data');
|
|
if (resZeroVar.status === 'insufficient_data') {
|
|
expect(resZeroVar.reason).toBe('zero_variance_series');
|
|
}
|
|
|
|
expect(calls).toHaveLength(0);
|
|
});
|
|
|
|
it('propagates INSERT failure and wraps DSR-read failure with trialId and cause without retry', async () => {
|
|
const insertError = new Error('event insert failed');
|
|
const failInsertStore = createInMemoryTrialExecutor({ failOnInsert: insertError });
|
|
await expect(runEventStudy(failInsertStore.executor, makeEventStudyRequest())).rejects.toBe(
|
|
insertError
|
|
);
|
|
expect(failInsertStore.calls).toHaveLength(1);
|
|
|
|
const readError = new Error('event dsr read failed');
|
|
const failReadStore = createInMemoryTrialExecutor({ failOnDsrRead: readError });
|
|
const err = await expectStudyError(
|
|
() => runEventStudy(failReadStore.executor, makeEventStudyRequest()),
|
|
'dsr_read_failed'
|
|
);
|
|
expect(err.trialId).toBe(101);
|
|
expect(err.cause).toBe(readError);
|
|
expect(failReadStore.calls.filter(c => c.text.trimStart().startsWith('INSERT'))).toHaveLength(
|
|
1
|
|
);
|
|
});
|
|
|
|
it('validates inputs with zero queries and does not mutate frozen caller inputs', async () => {
|
|
const { executor, calls } = createInMemoryTrialExecutor();
|
|
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: { sessionDates: [], entityReturns: new Map(), events: [] },
|
|
})
|
|
),
|
|
'empty_panel'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: {
|
|
sessionDates: ['2025-01-05', '2025-01-04'],
|
|
entityReturns: new Map(),
|
|
events: [],
|
|
},
|
|
})
|
|
),
|
|
'unsorted_dates'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: {
|
|
sessionDates: ['2025-01-05', '2025-01-05'],
|
|
entityReturns: new Map(),
|
|
events: [],
|
|
},
|
|
})
|
|
),
|
|
'duplicate_date'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
options: { postDays: -1 },
|
|
})
|
|
),
|
|
'invalid_option'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
options: { postDays: null as unknown as number },
|
|
})
|
|
),
|
|
'invalid_option'
|
|
);
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: {
|
|
sessionDates: ['2025-01-05', '2025-01-06'],
|
|
entityReturns: new Map(),
|
|
events: [{ entityId: 1, dayIndex: -2 }],
|
|
},
|
|
})
|
|
),
|
|
'invalid_panel'
|
|
);
|
|
// Shape validation against the full calendar is preserved even when Vault dates exist.
|
|
await expectStudyError(
|
|
() =>
|
|
runEventStudy(
|
|
executor,
|
|
makeEventStudyRequest({
|
|
input: {
|
|
sessionDates: ['2025-04-29', '2025-04-30', '2025-05-01'],
|
|
entityReturns: new Map([[1, new Float64Array([0.01, 0.02])]]),
|
|
events: [],
|
|
},
|
|
})
|
|
),
|
|
'invalid_panel'
|
|
);
|
|
expect(calls).toHaveLength(0);
|
|
|
|
// Frozen immutability test
|
|
const baseReq = makeEventStudyRequest();
|
|
const frozenInput: EventStudyInput = Object.freeze({
|
|
sessionDates: Object.freeze([...baseReq.input.sessionDates]),
|
|
entityReturns: baseReq.input.entityReturns,
|
|
benchmarkReturns: Object.freeze([...(baseReq.input.benchmarkReturns ?? [])]),
|
|
events: Object.freeze(baseReq.input.events.map(e => Object.freeze({ ...e }))),
|
|
});
|
|
const frozenReq = Object.freeze({
|
|
...baseReq,
|
|
input: frozenInput,
|
|
options: Object.freeze({ ...baseReq.options }),
|
|
expression: Object.freeze({
|
|
...baseReq.expression,
|
|
params: Object.freeze({ minSurprisePct: 5 }),
|
|
}),
|
|
});
|
|
|
|
const okStore = createInMemoryTrialExecutor();
|
|
const result = await runEventStudy(okStore.executor, frozenReq);
|
|
expect(result.status).toBe('ok');
|
|
});
|
|
});
|