Freeze historical datasets and qualify backtest instrument identities

This commit is contained in:
Boki 2026-10-20 23:59:15 -04:00
parent 63c3856797
commit d6b09eb635
43 changed files with 2249 additions and 1230 deletions

View file

@ -25,6 +25,7 @@ import { BacktestHandler } from '../../apps/stock/orchestrator/src/handlers/back
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import type { OrchestratorServices } from '../../apps/stock/orchestrator/src/types';
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
import { createBacktestV2Routes } from '../../apps/stock/web-api/src/routes/backtests-v2.routes';
import { BacktestServiceV2 } from '../../apps/stock/web-api/src/services/backtest-v2.service';
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
import {
@ -45,7 +46,7 @@ const config = BacktestConfigSchema.parse({
mode: 'backtest',
name: 'Workflow fixture',
strategy: 'sma-crossover',
symbols: ['FIXTURE'],
symbols: ['FIXTURE.TEST'],
startDate: '2024-01-01T00:00:00.000Z',
endDate: '2024-03-15T00:00:00.000Z',
initialCapital: 100000,
@ -75,11 +76,12 @@ async function fixture(
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id), run_number integer,
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0,
request_snapshot jsonb, attempt_id uuid, attempt_number integer DEFAULT 0, dataset_hash text,
lease_expires_at timestamptz, cancel_requested boolean DEFAULT false,
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
CREATE TABLE backtest_dispatch (run_id uuid PRIMARY KEY REFERENCES runs(id),
next_publish_at timestamptz DEFAULT NOW(), last_published_at timestamptz, publish_count integer DEFAULT 0);
CREATE TABLE backtest_datasets (hash text PRIMARY KEY, payload jsonb, created_at timestamptz DEFAULT NOW());
CREATE TABLE backtest_results (run_id uuid PRIMARY KEY REFERENCES runs(id), completed_at timestamptz,
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb,
execution_time numeric, configuration jsonb, engine text);`);
@ -141,6 +143,49 @@ async function fixture(
}
describe('one backtest execution workflow', () => {
test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => {
const f = await fixture();
const api = createBacktestV2Routes(f.services);
for (const request of [
{ ...config, symbols: ['FIXTURE'] },
{ ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } },
{ ...config, config: { datasetHash: 'invalid' } },
]) {
const response = await api.request('/api/v2/backtests', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
expect(response.status).toBe(400);
}
expect((await f.postgres.query('SELECT * FROM backtests')).rows).toHaveLength(0);
expect((await f.postgres.query('SELECT * FROM runs')).rows).toHaveLength(0);
});
test('frozen inputs replay without reading mutable provider history and are recorded in results', async () => {
const f = await fixture();
const first = await f.runner.runBacktest(config);
expect(first.config.dataset?.barCount).toBe(70);
expect(first.config.dataset?.hash).toMatch(/^[a-f0-9]{64}$/);
const saved = await f.postgres.query('SELECT dataset_hash FROM runs WHERE id = $1', [
first.runId,
]);
expect(saved.rows[0]?.dataset_hash).toBe(first.config.dataset!.hash);
f.storage.getHistoricalBars = async () => {
throw new Error('Provider unavailable or revised');
};
const replay = await f.runner.runBacktest({
...config,
datasetHash: first.config.dataset!.hash,
});
expect(replay.config.dataset).toEqual(first.config.dataset);
expect(replay.trades).toEqual(first.trades);
expect(replay.metrics).toEqual(first.metrics);
expect(replay.equity).toEqual(first.equity);
expect((await f.postgres.query('SELECT * FROM backtest_datasets')).rows).toHaveLength(1);
await expect(f.runner.runBacktest({ ...config, datasetHash: 'f'.repeat(64) })).rejects.toThrow(
'not found'
);
});
test('REST and decorated jobs execute real data and commit the same canonical result', async () => {
const f = await fixture();
const response = await f.routes.request('/api/backtest/run', {
@ -208,10 +253,17 @@ describe('one backtest execution workflow', () => {
expect(result.engine).toBe('typescript');
expect(result.trades.length).toBeGreaterThan(0);
expect(result.status).toBe('completed');
const repeated = await services.custom!.BacktestRunner!.runBacktest(config);
services.custom!.StorageService!.getHistoricalBars = async () => {
throw new Error('Provider unavailable');
};
const repeated = await services.custom!.BacktestRunner!.runBacktest({
...config,
datasetHash: result.config.dataset!.hash,
});
expect(repeated.config.dataset).toEqual(result.config.dataset);
expect(repeated.trades).toEqual(result.trades);
expect(repeated.metrics).toEqual(result.metrics);
expect(result.ohlcData.FIXTURE).toHaveLength(70);
expect(result.ohlcData['FIXTURE.TEST']).toHaveLength(70);
expect(result.trades.every(trade => trade.kind === 'closed')).toBe(true);
expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('completed');
} finally {
@ -262,7 +314,7 @@ describe('one backtest execution workflow', () => {
const f = await fixture(true);
await expect(
new DataManager(f.storage).loadHistoricalData(
['FIXTURE'],
['FIXTURE.TEST'],
new Date(config.startDate),
new Date(config.endDate),
'1d'
@ -318,7 +370,10 @@ describe('one backtest execution workflow', () => {
if (sql.includes('INSERT INTO backtest_results')) {
throw new Error('Insert failed');
}
return { rows: [{ id: result.runId }], rowCount: 1 };
return {
rows: [{ id: result.runId, dataset_hash: result.config.dataset?.hash }],
rowCount: 1,
};
},
release() {
released = true;

View file

@ -1,11 +1,15 @@
import { describe, expect, test } from 'bun:test';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
import type { MongoDBClient } from '@stock-bot/services';
import type { MongoDBClient, QuestDBClient } from '@stock-bot/services';
import {
persistEodPrices,
type EodPrice,
} from '../../apps/stock/data-ingestion/src/handlers/eod/shared/price-storage';
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
import {
loadDataset,
validateDataset,
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
@ -48,13 +52,13 @@ function memoryStore() {
},
async find(
collection: string,
filter: { symbol: string; date: { $gte: string; $lt: string } }
filter: { eodSearchCode: string; date: { $gte: string; $lt: string } }
) {
expect(collection).toBe('eodPrices');
return documents
.filter(
row =>
row.symbol === filter.symbol &&
row.eodSearchCode === filter.eodSearchCode &&
row.date >= filter.date.$gte &&
row.date < filter.date.$lt
)
@ -65,6 +69,176 @@ function memoryStore() {
}
describe('deterministic ingestion → storage → native backtest', () => {
test('intraday queries bind qualified IDs and reject timezone-less instants or wrong listings', async () => {
let timestamp = '2024-01-01T10:00:00-05:00';
let symbol = identity.eodSearchCode;
const questdb = {
async query(_sql: string, parameters: unknown[]) {
expect(parameters[0]).toBe(identity.eodSearchCode);
return {
rows: [
{
symbol,
timestamp,
open: 100,
high: 101,
low: 99,
close: 100,
volume: 1000,
vwap: null,
},
],
};
},
} as unknown as QuestDBClient;
const storage = new StorageService({ logger }, null, null, questdb);
const bars = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m');
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T15:00:00.000Z');
timestamp = '2024-01-01T10:00:00';
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m')
).rejects.toThrow('explicit UTC offset');
timestamp = '2024-01-01T15:00:00Z';
symbol = 'FIXTURE.OTHER';
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1m')
).rejects.toThrow('identity mismatch');
});
test('provider routing namespaces remain distinct from venue metadata, including legacy rows', async () => {
const { documents, mongodb } = memoryStore();
const listing = { symbol: 'FIXTURE', exchange: 'NASDAQ', eodSearchCode: 'FIXTURE.US' };
await persistEodPrices(mongodb, listing, [fixture[0]!]);
expect(documents[0]?.exchange).toBe('NASDAQ');
expect((documents[0] as unknown as { providerExchange: string }).providerExchange).toBe('US');
const storage = new StorageService({ logger }, mongodb, null, null);
expect(
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.symbol
).toBe('FIXTURE.US');
delete (documents[0] as unknown as { providerExchange?: string }).providerExchange;
expect(
(await storage.getHistoricalBars(listing.eodSearchCode, start, end, '1d'))[0]?.close
).toBe(fixture[0]!.close);
});
test('same ticker on different exchanges never shares bars and bare tickers fail closed', async () => {
const { mongodb } = memoryStore();
const other = { symbol: 'FIXTURE', exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' };
await persistEodPrices(mongodb, identity, [fixture[0]!]);
await persistEodPrices(mongodb, other, [
{ ...fixture[0]!, open: 200, high: 201, low: 199, close: 200 },
]);
const storage = new StorageService({ logger }, mongodb, null, null);
expect(
(await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d'))[0]?.close
).toBe(fixture[0]!.close);
expect((await storage.getHistoricalBars(other.eodSearchCode, start, end, '1d'))[0]?.close).toBe(
200
);
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
'exchange-qualified'
);
expect(
BacktestConfigSchema.safeParse({ ...datasetConfig(), symbols: ['FIXTURE'] }).success
).toBe(false);
});
test('split and dividend adjusted-close factors apply to every OHLC price, never to reported volume', async () => {
const { mongodb } = memoryStore();
const prices = [
{
...fixture[0]!,
open: 100,
high: 110,
low: 90,
close: 100,
adjusted_close: 50,
volume: 1000,
},
{ ...fixture[1]!, open: 50, high: 55, low: 45, close: 50, adjusted_close: 49, volume: 2000 },
];
await persistEodPrices(mongodb, identity, prices);
const storage = new StorageService({ logger }, mongodb, null, null);
const raw = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d');
const adjusted = await storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
adjustment: 'provider-adjusted',
timestamp: 'utc-session-date',
});
expect(raw.map(b => b.close)).toEqual([100, 50]);
expect(adjusted.map(b => [b.open, b.high, b.low, b.close, b.volume])).toEqual([
[50, 55, 45, 50, 1000],
[49, 53.9, 44.1, 49, 2000],
]);
const a = await loadDataset(storage, datasetConfig());
const b = await loadDataset(storage, {
...datasetConfig(),
dataPolicy: { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' },
});
expect(a.manifest.hash).not.toBe(b.manifest.hash);
});
test('missing provider factors cannot silently turn adjusted requests into raw data', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, [fixture[0]!]);
const storage = new StorageService({ logger }, mongodb, null, null);
await expect(
storage.getHistoricalBars(identity.eodSearchCode, start, end, '1d', {
adjustment: 'provider-adjusted',
timestamp: 'utc-session-date',
})
).rejects.toThrow('unavailable');
await expect(
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, adjusted_close: 0 }])
).rejects.toThrow('Invalid OHLCV');
await expect(
persistEodPrices(mongodb, { ...identity, symbol: 'WRONG' }, [fixture[0]!])
).rejects.toThrow('identity mismatch');
});
test('daily timestamps are UTC session labels with aligned, exclusive ranges', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture.slice(0, 3));
const storage = new StorageService({ logger }, mongodb, null, null);
const bars = await storage.getHistoricalBars(
identity.eodSearchCode,
start,
new Date(start.getTime() + 86400000),
'1d'
);
expect(bars).toHaveLength(1);
expect(bars[0]?.timestamp.toISOString()).toBe('2024-01-01T00:00:00.000Z');
await expect(
storage.getHistoricalBars(
identity.eodSearchCode,
new Date(start.getTime() + 3600000),
end,
'1d'
)
).rejects.toThrow('UTC midnight');
await expect(
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, date: '2024-02-30' }])
).rejects.toThrow('Invalid OHLCV');
});
test('dataset hashes survive JSON key reordering and reject tampering or mismatched requests', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
const storage = new StorageService({ logger }, mongodb, null, null);
const first = await loadDataset(storage, datasetConfig());
const reordered = JSON.parse(JSON.stringify(first), (_key, value) =>
value && !Array.isArray(value) && typeof value === 'object'
? Object.fromEntries(Object.entries(value).reverse())
: value
);
expect(validateDataset(reordered, datasetConfig())).toEqual(first);
const changed = structuredClone(first);
changed.bars[0]!.volume++;
expect(() => validateDataset(changed)).toThrow('hash/content');
expect(() =>
validateDataset(first, { ...datasetConfig(), symbols: ['FIXTURE.OTHER'] })
).toThrow('does not match');
expect(() =>
validateDataset(first, { ...datasetConfig(), datasetHash: 'f'.repeat(64) })
).toThrow('does not match');
});
test('replays stored provider fixtures and produces identical trades and metrics', async () => {
const { documents, mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
@ -76,7 +250,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
const config = BacktestConfigSchema.parse({
mode: 'backtest',
name: 'Fixed replay',
symbols: ['FIXTURE'],
symbols: ['FIXTURE.TEST'],
strategy: 'sma-crossover',
startDate: start.toISOString(),
endDate: end.toISOString(),
@ -98,6 +272,28 @@ describe('deterministic ingestion → storage → native backtest', () => {
expect(engine.getStatus().isRunning).toBe(false);
});
test('all listings retain their first same-timestamp bar and deterministic tie ordering', async () => {
const { mongodb } = memoryStore();
const other = { ...identity, exchange: 'OTHER', eodSearchCode: 'FIXTURE.OTHER' };
await persistEodPrices(mongodb, identity, fixture);
await persistEodPrices(mongodb, other, fixture);
const config = {
...datasetConfig(),
symbols: [identity.eodSearchCode, other.eodSearchCode],
config: { fastPeriod: 3, slowPeriod: 7 },
};
const engine = new RustBacktestAdapter({ logger, mongodb });
const first = await engine.runBacktest(config);
const second = await engine.runBacktest(config);
for (const id of config.symbols) {
expect(first.ohlcData[id]).toHaveLength(fixture.length);
expect(first.ohlcData[id]?.[0]?.timestamp).toBe(start.getTime());
}
expect(first.trades).toEqual(second.trades);
expect(first.metrics).toEqual(second.metrics);
expect(first.equity).toEqual(second.equity);
});
test('rejects malformed provider records before writing anything', async () => {
const { documents, mongodb } = memoryStore();
await expect(
@ -108,7 +304,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
test('missing storage never silently produces synthetic prices', async () => {
const storage = new StorageService({ logger }, null, null, null);
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
await expect(storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).rejects.toThrow(
'explicit opt-in'
);
});
@ -118,8 +314,8 @@ describe('deterministic ingestion → storage → native backtest', () => {
allowSyntheticData: true,
syntheticSeed: 7,
});
expect(await storage.getHistoricalBars('FIXTURE', start, end, '1d')).toEqual(
await storage.getHistoricalBars('FIXTURE', start, end, '1d')
expect(await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).toEqual(
await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')
);
});
@ -128,7 +324,7 @@ describe('deterministic ingestion → storage → native backtest', () => {
const engine = new RustBacktestAdapter({ logger, mongodb });
const config = BacktestConfigSchema.parse({
mode: 'backtest',
symbols: ['FIXTURE'],
symbols: ['FIXTURE.TEST'],
strategy: 'sma-crossover',
startDate: start.toISOString(),
endDate: end.toISOString(),
@ -142,3 +338,15 @@ describe('deterministic ingestion → storage → native backtest', () => {
expect(engine.getStatus().isRunning).toBe(false);
});
});
function datasetConfig() {
return BacktestConfigSchema.parse({
mode: 'backtest',
symbols: [identity.eodSearchCode],
strategy: 'sma-crossover',
startDate: start.toISOString(),
endDate: end.toISOString(),
initialCapital: 100000,
dataFrequency: '1d',
});
}