stock-bot/test/postgres/signal-study.test.ts

262 lines
8.9 KiB
TypeScript

import { randomUUID } from 'node:crypto';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { afterEach, describe, expect, test } from 'bun:test';
import { Pool } from 'pg';
import type { EventStudyInput, SignalCrossSection } from '@stock-bot/calculations';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
import { analyzeSignal, runEventStudy } from '@stock-bot/research';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('signal-study-postgres-test');
const url = process.env.PIPELINE_TEST_DATABASE_URL;
const initDir = fileURLToPath(new URL('../../database/postgres/init/', import.meta.url));
const VAULT_CUTOFF = '2025-05-01';
const cleanup: (() => Promise<void> | void)[] = [];
afterEach(async () => {
for (const close of cleanup.splice(0).reverse()) {
await close();
}
});
async function createIsolatedFixture() {
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
throw new Error('Dedicated stock_bot_safety database required');
}
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
const admin = new Pool({ connectionString: url });
await admin.query(`CREATE SCHEMA ${schema}`);
const pool = new Pool({
connectionString: url,
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
});
cleanup.push(async () => {
await pool.end();
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
await admin.end();
});
for (const filename of [
'06-create-backtest-tables.sql',
'07-fix-execution-time-type.sql',
'08-create-runs-table.sql',
]) {
await pool.query(readFileSync(`${initDir}${filename}`, 'utf8'));
}
const postgres = new PostgreSQLClient(
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
logger
);
Object.defineProperty(postgres, 'connectionPool', {
get: () => ({
connect: () => pool.connect(),
}),
});
await runPostgresMigrations(postgres, { track: 'research' });
return { pool, schema, postgres };
}
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 = new Array<string>(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: number, seed: number): 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.0004;
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 makeEventStudyInput(dates: readonly string[], eventDayIndices: readonly number[], seed: number): 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;
}
return {
sessionDates: dates,
entityReturns,
benchmarkReturns,
events: eventDayIndices.map((dayIndex, idx) => ({
entityId: (idx % 4) + 1,
dayIndex,
})),
};
}
describe.skipIf(!url)('signal-study runners PostgreSQL integration', () => {
test('appends 3 trials (2 signal_ic + 1 event_study), fences Vault dates, computes clusterSize=2 DSR, and writes 0 rows on insufficient_data', async () => {
const f = await createIsolatedFixture();
const preDates = makeBusinessDates('2025-03-03', 35);
const postDates = ['2025-05-01', '2025-05-02', '2025-05-05'];
const allPanelDates = [...preDates, ...postDates];
const sig1 = await analyzeSignal(f.pool, {
principalId: 'operator',
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(allPanelDates, 20, 1001),
vaultCutoffDate: VAULT_CUTOFF,
});
expect(sig1.status).toBe('ok');
if (sig1.status !== 'ok') {
return;
}
expect(sig1.analysis.diagnostics.vaultExcludedDates).toBe(3);
expect(sig1.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
expect(sig1.deflatedSharpe.clusterSize).toBe(1);
const sig2 = await analyzeSignal(f.pool, {
principalId: 'operator',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'rank(ret_10d) + zscore(turnover_20d)',
params: { lookback: 10 },
universe: 'US_EQ_TOP3000',
horizon: '5d',
},
panel: makeSignalPanel(allPanelDates, 20, 2002),
vaultCutoffDate: VAULT_CUTOFF,
});
expect(sig2.status).toBe('ok');
if (sig2.status !== 'ok') {
return;
}
expect(sig2.analysis.diagnostics.vaultExcludedDates).toBe(3);
expect(sig2.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
expect(sig2.trial.expressionHash).not.toBe(sig1.trial.expressionHash);
expect(sig2.deflatedSharpe.clusterSize).toBe(2);
expect(sig2.deflatedSharpe.pairsUsed).toBe(0);
expect(sig2.deflatedSharpe.pairsSkipped).toBe(1);
expect(sig2.deflatedSharpe.effectiveTrials).toBe(2);
expect(Number.isFinite(sig2.deflatedSharpe.effectiveTrials)).toBe(true);
const eventDates = makeBusinessDates('2025-02-03', 70);
const cutoffIdx = eventDates.findIndex(d => d >= VAULT_CUTOFF);
expect(cutoffIdx).toBeGreaterThan(35);
const evtRes = await runEventStudy(f.pool, {
principalId: 'operator',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'earnings_beat_car',
params: { minSurprisePct: 5 },
universe: 'US_EQ_TOP3000',
horizon: '5d',
},
input: makeEventStudyInput(
eventDates,
[8, 12, 16, 20, 24, 28, cutoffIdx - 3, cutoffIdx + 1],
3003
),
vaultCutoffDate: VAULT_CUTOFF,
options: { preDays: 3, postDays: 5, minEvents: 5 },
});
expect(evtRes.status).toBe('ok');
if (evtRes.status !== 'ok') {
return;
}
expect(evtRes.vaultExcludedEvents).toBe(2);
expect(evtRes.trial.sampleEnd < VAULT_CUTOFF).toBe(true);
expect(evtRes.deflatedSharpe.clusterSize).toBe(3);
expect(evtRes.deflatedSharpe.pairsUsed).toBe(0);
expect(evtRes.deflatedSharpe.pairsSkipped).toBe(3);
expect(evtRes.deflatedSharpe.effectiveTrials).toBe(3);
// Insufficient-data run must append 0 additional rows.
const insufRes = await analyzeSignal(f.pool, {
principalId: 'operator',
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'too_short_signal',
params: {},
universe: 'US_EQ_TOP3000',
horizon: '5d',
},
panel: makeSignalPanel(['2025-04-30', '2025-05-01'], 10, 4004),
vaultCutoffDate: VAULT_CUTOFF,
});
expect(insufRes.status).toBe('insufficient_data');
const dbResult = await f.pool.query<{
trial_id: string;
stage: string;
n_obs: number;
expression_hash: string;
sample_end: string;
}>(
`SELECT trial_id, stage, n_obs, expression_hash, sample_end::text AS sample_end
FROM trial_ledger
ORDER BY trial_id ASC`
);
expect(dbResult.rows).toHaveLength(3);
expect(dbResult.rows.map(r => r.stage)).toEqual(['signal_ic', 'signal_ic', 'event_study']);
expect(dbResult.rows[0]!.n_obs).toBe(sig1.trial.nObs);
expect(dbResult.rows[1]!.n_obs).toBe(sig2.trial.nObs);
expect(dbResult.rows[2]!.n_obs).toBe(evtRes.trial.nObs);
const hashes = new Set(dbResult.rows.map(r => r.expression_hash));
expect(hashes.size).toBe(3);
for (const row of dbResult.rows) {
expect(row.sample_end < VAULT_CUTOFF).toBe(true);
}
});
});