stock-bot/libs/research/test/signal-panel-e2e.test.ts
2026-11-29 15:26:38 -05:00

403 lines
14 KiB
TypeScript

import { describe, expect, it } from 'bun:test';
import {
analyzeSignal,
buildForwardReturnPanel,
collectBars,
createDuckDbMarketDataStore,
shortsTableToSignalRows,
type DuckDbExecutor,
type DuckDbParam,
type TableRow,
type TrialLedgerExecutor,
} from '@stock-bot/research';
const CURATED_ROOT = '/mnt/data/stockbot/curated';
const SEED = 20261129;
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 makeUtcMs(date: string, hourUtc: number): number {
const [y, m, d] = date.split('-').map(Number);
return Date.UTC(y!, m! - 1, d!, hourUtc, 0, 0, 0);
}
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[];
}
function createInMemoryTrialExecutor(): {
executor: TrialLedgerExecutor;
rows: StoredTrialRow[];
} {
const rows: StoredTrialRow[] = [];
let nextTrialId = 1;
const executor: TrialLedgerExecutor = {
async query<Row = Record<string, unknown>>(text: string, params?: readonly unknown[]) {
const trimmed = text.trimStart();
if (trimmed.startsWith('INSERT INTO trial_ledger')) {
const p = params ?? [];
const trialId = nextTrialId++;
const createdAt = new Date(Date.UTC(2024, 5, 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 (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, rows };
}
interface CeoShortsFixture {
readonly listingIds: number[];
readonly allDates: string[];
readonly vaultCutoffDate: string;
readonly vaultCutoffTs: number;
readonly barRows: TableRow[];
readonly shortsRows: TableRow[];
}
function buildCeoShortsFixture(poisonPostCutoff: boolean): CeoShortsFixture {
const rand = createSeededRng(SEED);
const listingCount = 28;
const preCutoffSessions = 140; // spans late 2022 through early 2023 (pre-2023 & post-2023)
const postCutoffSessions = 10;
const allDates = makeBusinessDates('2022-09-01', preCutoffSessions + postCutoffSessions);
const vaultCutoffDate = allDates[preCutoffSessions]!;
const vaultCutoffTs = makeUtcMs(vaultCutoffDate, 0);
const listingIds = Array.from({ length: listingCount }, (_, i) => 50_001 + i);
const barRows: TableRow[] = [];
const shortsRows: TableRow[] = [];
// Semi-monthly ceoShorts reports (every 10 trading sessions). Publication follows the CIRO
// working assumption: 17:00 ET (22:00 UTC) four business days after `report_date`. A report
// only drives prices from the session AFTER its publication close, so no close ever reflects
// a report before its `known_at` (QA fix for the reviewer's look-ahead note).
// Plant a negative relationship: higher net_change predicts lower subsequent 5-session return.
const PUBLICATION_LAG_SESSIONS = 4;
const activeNetChange = new Float64Array(listingCount);
const pendingByPublishIdx = new Map<number, (number | null)[]>();
const prices = new Float64Array(listingCount);
for (let l = 0; l < listingCount; l += 1) {
prices[l] = 10 + l * 1.5;
}
for (let t = 0; t < allDates.length; t += 1) {
const date = allDates[t]!;
const closeTs = makeUtcMs(date, 21); // 16:00 ET close
// Reports published after the previous close become tradeable information today.
const released = pendingByPublishIdx.get(t - 1);
if (released !== undefined) {
for (let l = 0; l < listingCount; l += 1) {
const v = released[l];
if (v !== null && v !== undefined) {
activeNetChange[l] = v / 20_000; // normalized in [-1, 1]
}
}
}
const publishIdx = t + PUBLICATION_LAG_SESSIONS;
if (t % 10 === 0 && publishIdx < allDates.length) {
const reportKnownAt = makeUtcMs(allDates[publishIdx]!, 22); // 17:00 ET on T+4
const pending: (number | null)[] = [];
for (let l = 0; l < listingCount; l += 1) {
const isNullCell = t > 0 && (t + l) % 19 === 0;
const netChange = isNullCell ? null : Math.round((rand() * 2 - 1) * 20_000);
pending.push(netChange);
shortsRows.push({
listing_id: listingIds[l]!,
report_date: date,
known_at: reportKnownAt,
shares_short: 100_000 + l * 5_000 + Math.round(rand() * 10_000),
net_change: netChange,
pct_float: isNullCell ? null : Number((0.02 + rand() * 0.08).toFixed(4)),
source: 'ceoShorts',
});
}
pendingByPublishIdx.set(publishIdx, pending);
}
for (let l = 0; l < listingCount; l += 1) {
// Drift driven negatively by prior known short-interest change + idiosyncratic noise.
const dailyRet = -0.004 * activeNetChange[l]! + (rand() * 2 - 1) * 0.008;
prices[l] = Math.max(0.5, prices[l]! * (1 + dailyRet));
const isPostCutoff = date >= vaultCutoffDate;
const closeVal = poisonPostCutoff && isPostCutoff ? 999_999 : Number(prices[l]!.toFixed(6));
barRows.push({
listing_id: listingIds[l]!,
ts: closeTs,
open: closeVal,
high: closeVal,
low: closeVal,
close: closeVal,
volume: 50_000,
vwap: closeVal,
known_at: closeTs,
});
}
}
return {
listingIds,
allDates,
vaultCutoffDate,
vaultCutoffTs,
barRows,
shortsRows,
};
}
function createFakeDuckDbExecutor(fixture: CeoShortsFixture): {
executor: DuckDbExecutor;
runStatements: string[];
queryCount: () => number;
} {
const runStatements: string[] = [];
let queries = 0;
const executor: DuckDbExecutor = {
async run(sql: string) {
runStatements.push(sql);
},
async query(sql: string, params: readonly DuckDbParam[]): Promise<readonly TableRow[]> {
queries += 1;
if (sql.includes('bars_1d/year=*/part.parquet')) {
// Bound params: [...listingIds, fromIso, toIso, asOfIso]
const nIds = fixture.listingIds.length;
const idSet = new Set<number>(params.slice(0, nIds) as number[]);
const fromMs = Date.parse(params[nIds] as string);
const toMs = Date.parse(params[nIds + 1] as string);
const asOfMs = Date.parse(params[nIds + 2] as string);
return fixture.barRows.filter(row => {
const lid = row.listing_id as number;
const ts = row.ts as number;
const knownAt = row.known_at as number;
return idSet.has(lid) && ts >= fromMs && ts <= toMs && knownAt <= asOfMs;
});
}
if (sql.includes('shorts/part.parquet')) {
// Bound params: [...listingIds, fromDate, toDate, asOfIso]
const nIds = fixture.listingIds.length;
const idSet = new Set<number>(params.slice(0, nIds) as number[]);
const fromDate = params[nIds] as string;
const toDate = params[nIds + 1] as string;
const asOfMs = Date.parse(params[nIds + 2] as string);
return fixture.shortsRows.filter(row => {
const lid = row.listing_id as number;
const reportDate = row.report_date as string;
const knownAt = row.known_at as number;
return idSet.has(lid) && reportDate >= fromDate && reportDate <= toDate && knownAt <= asOfMs;
});
}
throw new Error(`Unexpected SQL in fake DuckDbExecutor: ${sql}`);
},
};
return {
executor,
runStatements,
queryCount: () => queries,
};
}
describe('ceoShorts end-to-end signal study (headless, no database)', () => {
async function runCeoShortsStudy(poisonPostCutoff: boolean) {
const fixture = buildCeoShortsFixture(poisonPostCutoff);
const duck = createFakeDuckDbExecutor(fixture);
const ledger = createInMemoryTrialExecutor();
const store = createDuckDbMarketDataStore({
executor: duck.executor,
curatedRoot: CURATED_ROOT,
vaultCutoffTs: fixture.vaultCutoffTs,
barBatchSize: 256,
});
const from = fixture.allDates[0]!;
const to = fixture.allDates[fixture.allDates.length - 1]!;
const bars = await collectBars(
store.bars({
listingIds: fixture.listingIds,
timeframe: '1d',
from,
to,
adjustment: 'raw',
})
);
const shortsTable = await store.shortsAsOf({
listingIds: fixture.listingIds,
from,
to,
});
const signals = shortsTableToSignalRows(shortsTable, 'net_change');
const built = buildForwardReturnPanel({
bars,
signals,
horizonSessions: 5,
vaultCutoffDate: fixture.vaultCutoffDate,
});
const studyResult = await analyzeSignal(ledger.executor, {
principalId: 'operator',
universeMarket: 'CA_EQ',
horizonBucket: 'swing_1_10d',
expression: {
expression: 'ceoshorts_net_change_5d',
params: { field: 'net_change', horizonSessions: 5 },
universe: 'CA_EQ_FIXTURE',
horizon: '5d',
},
panel: built.panel,
vaultCutoffDate: fixture.vaultCutoffDate,
});
return { fixture, duck, ledger, built, studyResult };
}
it('fixture publishes each ceoShorts report after the close four sessions past report_date', () => {
const fixture = buildCeoShortsFixture(false);
expect(fixture.shortsRows.length).toBeGreaterThan(0);
for (const row of fixture.shortsRows) {
const reportIdx = fixture.allDates.indexOf(row.report_date as string);
const publishDate = fixture.allDates[reportIdx + 4]!;
expect(row.known_at).toBe(makeUtcMs(publishDate, 22));
expect(row.known_at as number).toBeGreaterThan(makeUtcMs(publishDate, 21));
}
});
it('flows DuckDbMarketDataStore -> buildForwardReturnPanel -> analyzeSignal -> trial_ledger + DSR', async () => {
const clean = await runCeoShortsStudy(false);
// DuckDB connection budget SET statements ran exactly once.
expect(clean.duck.runStatements).toHaveLength(3);
expect(clean.duck.runStatements[0]).toContain('SET memory_limit');
expect(clean.duck.runStatements[1]).toContain('SET threads');
expect(clean.duck.runStatements[2]).toContain('SET temp_directory');
expect(clean.duck.queryCount()).toBe(2); // 1 bars query + 1 shortsAsOf query
// Panel Vault safety: no emitted date or forward session >= vaultCutoffDate.
expect(clean.built.panel.length).toBeGreaterThan(100);
for (const slice of clean.built.panel) {
expect(slice.date < clean.fixture.vaultCutoffDate).toBe(true);
const idx = clean.built.sessionDates.indexOf(slice.date);
expect(idx).toBeGreaterThanOrEqual(0);
expect(idx + 5).toBeLessThan(clean.built.sessionDates.length);
expect(clean.built.sessionDates[idx + 5]! < clean.fixture.vaultCutoffDate).toBe(true);
}
// Signal study succeeded and inserted exactly one `signal_ic` row for CA_EQ.
expect(clean.studyResult.status).toBe('ok');
if (clean.studyResult.status !== 'ok') {
return;
}
expect(clean.ledger.rows).toHaveLength(1);
const stored = clean.ledger.rows[0]!;
expect(stored.stage).toBe('signal_ic');
expect(stored.universe_market).toBe('CA_EQ');
expect(stored.horizon_bucket).toBe('swing_1_10d');
expect(clean.studyResult.trial.sampleEnd < clean.fixture.vaultCutoffDate).toBe(true);
expect(stored.sample_end < clean.fixture.vaultCutoffDate).toBe(true);
// Finite DSR with effectiveTrials >= 1.
expect(clean.studyResult.deflatedSharpe.dsr).not.toBeNull();
expect(Number.isFinite(clean.studyResult.deflatedSharpe.dsr!)).toBe(true);
expect(clean.studyResult.deflatedSharpe.effectiveTrials).toBeGreaterThanOrEqual(1);
// Planted negative short-interest change -> next-5-session return relationship yields negative mean rank-IC.
expect(clean.studyResult.analysis.rankIc.mean).not.toBeNull();
expect(clean.studyResult.analysis.rankIc.mean!).toBeLessThan(0);
// Poisoning post-cutoff fixture bars leaves study result and trial_ledger row byte-identical.
const poisoned = await runCeoShortsStudy(true);
expect(poisoned.studyResult).toEqual(clean.studyResult);
expect(poisoned.ledger.rows).toEqual(clean.ledger.rows);
expect(poisoned.built).toEqual(clean.built);
});
});