T-84: M1.3d — trial_ledger writer + cluster N̂-deflated Sharpe reader in @stock-bot/research (append one row per horizon, vault-fenced sample_end, PostgreSQL integration test + local benchmark)
This commit is contained in:
parent
6bbdb4049e
commit
bbc31b9cd7
6 changed files with 2467 additions and 1 deletions
380
test/postgres/trial-ledger-writer.test.ts
Normal file
380
test/postgres/trial-ledger-writer.test.ts
Normal file
|
|
@ -0,0 +1,380 @@
|
|||
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 { deflatedSharpeRatio, effectiveIndependentTrials } from '@stock-bot/calculations';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
import {
|
||||
TrialLedgerError,
|
||||
buildTrialRow,
|
||||
canonicalExpressionHash,
|
||||
clusterDeflatedSharpe,
|
||||
loadClusterTrials,
|
||||
recordTrials,
|
||||
type TrialRowInput,
|
||||
} from '@stock-bot/research';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('trial-ledger-writer-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();
|
||||
});
|
||||
|
||||
// Bootstrap pre-additive tables needed by the research migration track.
|
||||
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 };
|
||||
}
|
||||
|
||||
async function expectPgErrorCode(
|
||||
operation: Promise<unknown>,
|
||||
expectedCode: string,
|
||||
messagePattern?: RegExp
|
||||
): Promise<void> {
|
||||
try {
|
||||
await operation;
|
||||
} catch (error) {
|
||||
const pgError = error as { code?: string; message?: string } | null;
|
||||
expect(pgError?.code).toBe(expectedCode);
|
||||
if (messagePattern) {
|
||||
expect(pgError?.message ?? '').toMatch(messagePattern);
|
||||
}
|
||||
return;
|
||||
}
|
||||
throw new Error(`Expected PostgreSQL error code ${expectedCode}, but query succeeded`);
|
||||
}
|
||||
|
||||
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 createGaussianSampler(seed: number): () => number {
|
||||
const next = createSeededRng(seed);
|
||||
let spare: number | null = null;
|
||||
return () => {
|
||||
if (spare !== null) {
|
||||
const value = spare;
|
||||
spare = null;
|
||||
return value;
|
||||
}
|
||||
let u = 0;
|
||||
while (u <= 1e-12) {
|
||||
u = next();
|
||||
}
|
||||
const v = next();
|
||||
const mag = Math.sqrt(-2 * Math.log(u));
|
||||
const theta = 2 * Math.PI * v;
|
||||
spare = mag * Math.sin(theta);
|
||||
return mag * Math.cos(theta);
|
||||
};
|
||||
}
|
||||
|
||||
function makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] {
|
||||
const gauss = createGaussianSampler(seed);
|
||||
const out = new Array<number>(length);
|
||||
for (let i = 0; i < length; i += 1) {
|
||||
out[i] = mean + std * gauss();
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', () => {
|
||||
test('3-horizon recordTrials inserts 3 ascending rows, round-trips REAL series, rejects bad batch atomically, and preserves immutability triggers', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const horizons = [
|
||||
{ label: '1d', bucket: 'swing_1_10d' as const, seed: 1001 },
|
||||
{ label: '5d', bucket: 'swing_1_10d' as const, seed: 1002 },
|
||||
{ label: '20d', bucket: 'position_10d_plus' as const, seed: 1003 },
|
||||
];
|
||||
|
||||
const rows = horizons.map(h =>
|
||||
buildTrialRow({
|
||||
principalId: 'operator',
|
||||
stage: 'signal_ic',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: h.bucket,
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: 'rank(ret_20d) - zscore(vol_20d)',
|
||||
params: { lookback: 20 },
|
||||
universe: 'US_EQ',
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
horizon: h.label,
|
||||
}),
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(h.seed, 25),
|
||||
})
|
||||
);
|
||||
|
||||
const receipts = await recordTrials(f.pool, rows);
|
||||
expect(receipts).toHaveLength(3);
|
||||
expect(receipts[0]!.trialId).toBeLessThan(receipts[1]!.trialId);
|
||||
expect(receipts[1]!.trialId).toBeLessThan(receipts[2]!.trialId);
|
||||
|
||||
const swingRows = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
const positionRows = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'position_10d_plus',
|
||||
});
|
||||
expect(swingRows).toHaveLength(2);
|
||||
expect(positionRows).toHaveLength(1);
|
||||
|
||||
// Verify daily_series round-trips within IEEE-754 REAL precision.
|
||||
for (let i = 0; i < rows[0]!.dailySeries.length; i += 1) {
|
||||
expect(swingRows[0]!.dailySeries[i]).toBe(Math.fround(rows[0]!.dailySeries[i]!));
|
||||
}
|
||||
|
||||
// Batch with one invalid row throws TrialLedgerError and inserts 0 additional rows.
|
||||
const badBatch: TrialRowInput[] = [
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'event_study',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: 'b'.repeat(64),
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: '2024-12-31',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(2001, 10),
|
||||
},
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'event_study',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: 'c'.repeat(64),
|
||||
sampleStart: '2020-01-02',
|
||||
sampleEnd: VAULT_CUTOFF, // violates exclusive vault fence
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(2002, 10),
|
||||
},
|
||||
];
|
||||
|
||||
try {
|
||||
await recordTrials(f.pool, badBatch);
|
||||
throw new Error('Expected VAULT_FENCE_VIOLATION');
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(TrialLedgerError);
|
||||
expect((error as TrialLedgerError).code).toBe('VAULT_FENCE_VIOLATION');
|
||||
}
|
||||
|
||||
const caRows = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
expect(caRows).toHaveLength(0);
|
||||
|
||||
// Existing append-only triggers still block UPDATE, DELETE, and TRUNCATE.
|
||||
const expectedMsg = /Retained research evidence cannot be rewritten or deleted/;
|
||||
await expectPgErrorCode(
|
||||
f.pool.query('UPDATE trial_ledger SET n_obs = 999'),
|
||||
'23514',
|
||||
expectedMsg
|
||||
);
|
||||
await expectPgErrorCode(f.pool.query('DELETE FROM trial_ledger'), '23514', expectedMsg);
|
||||
await expectPgErrorCode(f.pool.query('TRUNCATE trial_ledger'), '23514', expectedMsg);
|
||||
|
||||
const totalCount = (await f.pool.query('SELECT count(*)::int AS c FROM trial_ledger')).rows[0]
|
||||
.c as number;
|
||||
expect(totalCount).toBe(3);
|
||||
});
|
||||
|
||||
test('computes N-hat and DSR end-to-end through PostgreSQL for near-duplicate vs independent clusters, cluster isolation, and asOf', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const nObs = 500;
|
||||
const clusterK = 12;
|
||||
|
||||
// 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97
|
||||
const factorGauss = createGaussianSampler(9001);
|
||||
const baseFactor = new Array<number>(nObs);
|
||||
for (let t = 0; t < nObs; t += 1) {
|
||||
baseFactor[t] = 0.0008 + 0.01 * factorGauss();
|
||||
}
|
||||
const noiseGauss = createGaussianSampler(9002);
|
||||
const nearDupRows = new Array<TrialRowInput>(clusterK);
|
||||
const loading = Math.sqrt(0.97);
|
||||
const noiseWeight = Math.sqrt(1 - 0.97);
|
||||
for (let k = 0; k < clusterK; k += 1) {
|
||||
const series = new Array<number>(nObs);
|
||||
for (let t = 0; t < nObs; t += 1) {
|
||||
series[t] = loading * (baseFactor[t] as number) + noiseWeight * 0.01 * noiseGauss();
|
||||
}
|
||||
nearDupRows[k] = {
|
||||
principalId: 'operator',
|
||||
stage: 'screen',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: `dup_signal_${k}`,
|
||||
params: { k },
|
||||
universe: 'US_EQ',
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
horizon: '5d',
|
||||
}),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: series,
|
||||
};
|
||||
}
|
||||
|
||||
const nearDupReceipts = await recordTrials(f.pool, nearDupRows);
|
||||
|
||||
// 2. Independent cluster in (CA_EQ, swing_1_10d) — also tests cluster isolation from US_EQ!
|
||||
const indepRows = new Array<TrialRowInput>(clusterK);
|
||||
for (let k = 0; k < clusterK; k += 1) {
|
||||
indepRows[k] = {
|
||||
principalId: 'operator',
|
||||
stage: 'screen',
|
||||
universeMarket: 'CA_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: canonicalExpressionHash({
|
||||
expression: `indep_signal_${k}`,
|
||||
params: { k },
|
||||
universe: 'CA_EQ',
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
horizon: '5d',
|
||||
}),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01),
|
||||
};
|
||||
}
|
||||
const indepReceipts = await recordTrials(f.pool, indepRows);
|
||||
|
||||
// 3. Another cluster in (US_EQ, position_10d_plus) to verify horizon_bucket isolation.
|
||||
await recordTrials(f.pool, [
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'engine_backtest',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'position_10d_plus',
|
||||
expressionHash: 'd'.repeat(64),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(7777, nObs),
|
||||
},
|
||||
]);
|
||||
|
||||
const nearDupDsr = await clusterDeflatedSharpe(f.pool, {
|
||||
trialId: nearDupReceipts[0]!.trialId,
|
||||
});
|
||||
expect(nearDupDsr.clusterSize).toBe(clusterK);
|
||||
expect(nearDupDsr.meanCorrelation).not.toBeNull();
|
||||
expect(nearDupDsr.meanCorrelation!).toBeGreaterThan(0.95);
|
||||
expect(nearDupDsr.effectiveTrials).toBeLessThan(clusterK * 0.25);
|
||||
|
||||
const indepDsr = await clusterDeflatedSharpe(f.pool, {
|
||||
trialId: indepReceipts[0]!.trialId,
|
||||
});
|
||||
expect(indepDsr.clusterSize).toBe(clusterK);
|
||||
expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85);
|
||||
expect(indepDsr.effectiveTrials).toBeLessThanOrEqual(clusterK);
|
||||
|
||||
// Direct deflatedSharpeRatio parity within 1e-9 on the persisted cluster rows.
|
||||
const persistedNearDup = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
const directEff = effectiveIndependentTrials(persistedNearDup.map(r => r.dailySeries));
|
||||
const directDsr = deflatedSharpeRatio({
|
||||
sharpeUnann: persistedNearDup[0]!.sharpeUnann,
|
||||
nObs: persistedNearDup[0]!.nObs,
|
||||
skewness: persistedNearDup[0]!.skewness,
|
||||
kurtosis: persistedNearDup[0]!.kurtosis,
|
||||
nHat: directEff.nHat,
|
||||
clusterSharpes: persistedNearDup.map(r => r.sharpeUnann),
|
||||
});
|
||||
expect(directDsr).not.toBeNull();
|
||||
expect(Math.abs((nearDupDsr.dsr ?? Number.NaN) - directDsr!.dsr)).toBeLessThan(1e-9);
|
||||
|
||||
// asOf filtering: record a newer row after a brief delay and verify asOf excludes it.
|
||||
const cutoffTs = nearDupReceipts[clusterK - 1]!.createdAt;
|
||||
await Bun.sleep(15);
|
||||
await recordTrials(f.pool, [
|
||||
{
|
||||
principalId: 'operator',
|
||||
stage: 'screen',
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
expressionHash: 'e'.repeat(64),
|
||||
sampleStart: '2022-01-03',
|
||||
sampleEnd: '2024-01-02',
|
||||
vaultCutoffDate: VAULT_CUTOFF,
|
||||
dailySeries: makeSeries(9999, nObs),
|
||||
},
|
||||
]);
|
||||
|
||||
const fullCluster = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
});
|
||||
const asOfCluster = await loadClusterTrials(f.pool, {
|
||||
universeMarket: 'US_EQ',
|
||||
horizonBucket: 'swing_1_10d',
|
||||
asOf: cutoffTs,
|
||||
});
|
||||
expect(fullCluster).toHaveLength(clusterK + 1);
|
||||
expect(asOfCluster).toHaveLength(clusterK);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue