stock-bot/test/integration/ingestion-backtest.test.ts

374 lines
15 KiB
TypeScript

import { describe, expect, test } from 'bun:test';
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
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';
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
const logger = getLogger('replay-test');
const identity = { symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' };
const start = new Date('2024-01-01T00:00:00.000Z');
const end = new Date('2024-03-15T00:00:00.000Z');
const fixture: EodPrice[] = Array.from({ length: 70 }, (_, i) => {
const close = 100 + Math.sin((i * Math.PI) / 6) * 8 + i * 0.02;
return {
date: new Date(start.getTime() + i * 86400000).toISOString().slice(0, 10),
open: close - 0.1,
high: close + 1,
low: close - 1,
close,
volume: 1_000_000,
};
});
/** Only the database transport is replaced; normalization, storage reads, and engine are real. */
function memoryStore() {
const documents: Array<EodPrice & typeof identity & { source: string }> = [];
const transport = {
async batchUpsert(collection: string, rows: typeof documents) {
expect(collection).toBe('eodPrices');
for (const row of rows) {
const index = documents.findIndex(
old => old.date === row.date && old.eodSearchCode === row.eodSearchCode
);
if (index >= 0) {
documents[index] = row;
} else {
documents.push(row);
}
}
return {
insertedCount: rows.length,
modifiedCount: 0,
matchedCount: 0,
upsertedCount: rows.length,
};
},
async find(
collection: string,
filter: { eodSearchCode: string; date: { $gte: string; $lt: string } }
) {
expect(collection).toBe('eodPrices');
return documents
.filter(
row =>
row.eodSearchCode === filter.eodSearchCode &&
row.date >= filter.date.$gte &&
row.date < filter.date.$lt
)
.sort((a, b) => a.date.localeCompare(b.date));
},
};
return { documents, mongodb: transport as unknown as MongoDBClient };
}
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, 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);
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);
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);
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('explicit source requests reach storage and cannot silently reuse another provider', async () => {
const { mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
const storage = new StorageService(logger, mongodb, null);
const providers: unknown[] = [];
const selected = await loadDataset(
{
getHistoricalBars: (...args: Parameters<StorageService['getHistoricalBars']>) => {
providers.push(args[6]);
return storage.getHistoricalBars(...args);
},
},
{ ...datasetConfig(), dataSource: 'eod' }
);
expect(providers).toEqual(['eod']);
expect(selected.manifest.sources.map(source => source.provider)).toEqual(['eod']);
expect(() => validateDataset(selected, { ...datasetConfig(), dataSource: 'questdb' })).toThrow(
'does not match'
);
await expect(
loadDataset(storage, { ...datasetConfig(), dataSource: 'questdb' })
).rejects.toThrow();
});
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);
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);
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);
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('stored provider fixtures normalize into identical frozen inputs before admission', async () => {
const { documents, mongodb } = memoryStore();
await persistEodPrices(mongodb, identity, fixture);
await persistEodPrices(mongodb, identity, fixture);
expect(documents).toHaveLength(fixture.length);
expect(documents.every(row => row.source === 'eod')).toBe(true);
const services = { logger, mongodb };
const storage = new StorageService(services.logger, mongodb, null);
const config = BacktestConfigSchema.parse({
mode: 'backtest',
name: 'Fixed replay',
symbols: ['FIXTURE.TEST'],
strategy: 'sma-crossover',
startDate: start.toISOString(),
endDate: end.toISOString(),
initialCapital: 100000,
dataFrequency: '1d',
commission: 0,
slippage: 0,
config: { fastPeriod: 3, slowPeriod: 7 },
});
const first = await loadDataset(storage, config);
const second = await loadDataset(storage, config);
expect(first).toEqual(second);
expect(first.bars).toHaveLength(fixture.length);
expect(first.manifest.hash).toBe(second.manifest.hash);
});
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 storage = new StorageService(logger, mongodb, null);
const first = await loadDataset(storage, config);
const second = await loadDataset(storage, config);
for (const id of config.symbols) {
const bars = first.bars.filter(bar => bar.symbol === id);
expect(bars).toHaveLength(fixture.length);
expect(bars[0]?.timestamp).toBe(start.getTime());
}
expect(first).toEqual(second);
});
test('rejects malformed provider records before writing anything', async () => {
const { documents, mongodb } = memoryStore();
await expect(
persistEodPrices(mongodb, identity, [{ ...fixture[0]!, low: -1 }])
).rejects.toThrow('Invalid OHLCV');
expect(documents).toHaveLength(0);
});
test('missing storage never silently produces synthetic prices', async () => {
const storage = new StorageService(logger, null, null);
await expect(storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).rejects.toThrow(
'explicit opt-in'
);
});
test('explicit synthetic fixtures use a stable seed', async () => {
const storage = new StorageService(logger, null, null, {
allowSyntheticData: true,
syntheticSeed: 7,
});
expect(await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')).toEqual(
await storage.getHistoricalBars('FIXTURE.TEST', start, end, '1d')
);
});
test('retired provider-at-execution entry refuses before storage or native strategy resolution', async () => {
const engine = new RustBacktestAdapter({ logger });
const config = BacktestConfigSchema.parse({
mode: 'backtest',
symbols: ['FIXTURE.TEST'],
strategy: 'sma-crossover',
startDate: start.toISOString(),
endDate: end.toISOString(),
initialCapital: 100000,
dataFrequency: '1d',
});
await expect(engine.runBacktest(config)).rejects.toThrow(
'Legacy backtest execution is retired'
);
await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow(
'Legacy backtest execution is retired'
);
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',
});
}