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:
Studio 2026-11-28 03:03:17 -05:00
parent 9b57ea9677
commit dd05e20325
4 changed files with 919 additions and 178 deletions

View file

@ -119,6 +119,21 @@ function createGaussianSampler(seed: number): () => number {
};
}
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 makeSeries(seed: number, length: number, mean = 0.0005, std = 0.01): number[] {
const gauss = createGaussianSampler(seed);
const out = new Array<number>(length);
@ -239,6 +254,9 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
const f = await createIsolatedFixture();
const nObs = 500;
const clusterK = 12;
const sessionDates = makeBusinessDates('2022-01-03', nObs);
const sampleStart = sessionDates[0]!;
const sampleEnd = sessionDates[nObs - 1]!;
// 1. Near-duplicate cluster in (US_EQ, swing_1_10d): target pairwise rho ~ 0.97
const factorGauss = createGaussianSampler(9001);
@ -264,12 +282,12 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
expression: `dup_signal_${k}`,
params: { k },
universe: 'US_EQ',
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
horizon: '5d',
}),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: series,
};
@ -289,12 +307,12 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
expression: `indep_signal_${k}`,
params: { k },
universe: 'CA_EQ',
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
horizon: '5d',
}),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(5000 + k, nObs, 0.0005, 0.01),
};
@ -309,8 +327,8 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
universeMarket: 'US_EQ',
horizonBucket: 'position_10d_plus',
expressionHash: 'd'.repeat(64),
sampleStart: '2022-01-03',
sampleEnd: '2024-01-02',
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(7777, nObs),
},
@ -318,6 +336,7 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
const nearDupDsr = await clusterDeflatedSharpe(f.pool, {
trialId: nearDupReceipts[0]!.trialId,
sessionDates,
});
expect(nearDupDsr.clusterSize).toBe(clusterK);
expect(nearDupDsr.meanCorrelation).not.toBeNull();
@ -326,6 +345,7 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
const indepDsr = await clusterDeflatedSharpe(f.pool, {
trialId: indepReceipts[0]!.trialId,
sessionDates,
});
expect(indepDsr.clusterSize).toBe(clusterK);
expect(indepDsr.effectiveTrials).toBeGreaterThan(clusterK * 0.85);
@ -348,33 +368,111 @@ describe.skipIf(!url)('trial_ledger PostgreSQL writer and cluster DSR reader', (
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),
},
]);
// Writer receipt timestamp round-trip: exact receipt timestamp with Z and +00:00 select the same rows.
const receiptTs = nearDupReceipts[clusterK - 1]!.createdAt;
const atReceiptZ = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: receiptTs,
});
const atReceiptOffset = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: receiptTs.replace(/Z$/, '+00:00'),
});
expect(atReceiptZ).toHaveLength(clusterK);
expect(atReceiptOffset.map(r => r.trialId)).toEqual(atReceiptZ.map(r => r.trialId));
const fullCluster = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
// Deterministic asOf ordering fixture: explicit distinct microsecond created_at values (no wall-clock sleep).
const olderRow = buildTrialRow({
principalId: 'operator',
stage: 'screen',
universeMarket: 'FX',
horizonBucket: 'intraday',
expressionHash: 'e'.repeat(64),
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(9998, 10),
});
const asOfCluster = await loadClusterTrials(f.pool, {
universeMarket: 'US_EQ',
horizonBucket: 'swing_1_10d',
asOf: cutoffTs,
const newerRow = buildTrialRow({
principalId: 'operator',
stage: 'screen',
universeMarket: 'FX',
horizonBucket: 'intraday',
expressionHash: 'f'.repeat(64),
sampleStart,
sampleEnd,
vaultCutoffDate: VAULT_CUTOFF,
dailySeries: makeSeries(9999, 10),
});
expect(fullCluster).toHaveLength(clusterK + 1);
expect(asOfCluster).toHaveLength(clusterK);
await f.pool.query(
`INSERT INTO trial_ledger (
created_at, principal_id, campaign_id, stage, universe_market, horizon_bucket,
hypothesis_id, expression_hash, sample_start, sample_end, n_obs,
sharpe_unann, skewness, kurtosis, daily_series
) VALUES
($1::timestamptz, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12::double precision, $13::double precision, $14::double precision, $15::real[]),
($16::timestamptz, $17, $18, $19, $20, $21, $22, $23, $24, $25, $26, $27::double precision, $28::double precision, $29::double precision, $30::real[])`,
[
'2025-04-01T10:00:00.123456Z',
olderRow.principalId,
olderRow.campaignId,
olderRow.stage,
olderRow.universeMarket,
olderRow.horizonBucket,
olderRow.hypothesisId,
olderRow.expressionHash,
olderRow.sampleStart,
olderRow.sampleEnd,
olderRow.nObs,
olderRow.sharpeUnann,
olderRow.skewness,
olderRow.kurtosis,
olderRow.dailySeries,
'2025-04-01T10:00:00.123457Z',
newerRow.principalId,
newerRow.campaignId,
newerRow.stage,
newerRow.universeMarket,
newerRow.horizonBucket,
newerRow.hypothesisId,
newerRow.expressionHash,
newerRow.sampleStart,
newerRow.sampleEnd,
newerRow.nObs,
newerRow.sharpeUnann,
newerRow.skewness,
newerRow.kurtosis,
newerRow.dailySeries,
]
);
const fxAll = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
});
const fxAtZ = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
asOf: '2025-04-01T10:00:00.123456Z',
});
const fxAtPlusZero = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
asOf: '2025-04-01T10:00:00.123456+00:00',
});
const fxAtPlusTwo = await loadClusterTrials(f.pool, {
universeMarket: 'FX',
horizonBucket: 'intraday',
asOf: '2025-04-01T12:00:00.123456+02:00',
});
expect(fxAll).toHaveLength(2);
expect(fxAtZ).toHaveLength(1);
expect(fxAtPlusZero).toHaveLength(1);
expect(fxAtPlusTwo).toHaveLength(1);
expect(fxAtPlusZero[0]!.trialId).toBe(fxAtZ[0]!.trialId);
expect(fxAtPlusTwo[0]!.trialId).toBe(fxAtZ[0]!.trialId);
});
});