commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
144
test/integration/ingestion-backtest.test.ts
Normal file
144
test/integration/ingestion-backtest.test.ts
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import type { MongoDBClient } 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 { 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: { symbol: string; date: { $gte: string; $lt: string } }
|
||||
) {
|
||||
expect(collection).toBe('eodPrices');
|
||||
return documents
|
||||
.filter(
|
||||
row =>
|
||||
row.symbol === filter.symbol &&
|
||||
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('replays stored provider fixtures and produces identical trades and metrics', 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, mongodb, null, null);
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
name: 'Fixed replay',
|
||||
symbols: ['FIXTURE'],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
});
|
||||
const engine = new RustBacktestAdapter({ ...services, custom: { StorageService: storage } });
|
||||
const first = await engine.runBacktest(config);
|
||||
const second = await engine.runBacktest(config);
|
||||
expect(first.status).toBe('completed');
|
||||
expect(first.trades.length).toBeGreaterThan(0);
|
||||
expect(first.trades).toEqual(second.trades);
|
||||
expect(first.metrics).toEqual(second.metrics);
|
||||
expect(first.equity).toEqual(second.equity);
|
||||
expect(first.metrics.totalReturn).toBeFinite();
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
|
||||
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, null);
|
||||
await expect(storage.getHistoricalBars('FIXTURE', start, end, '1d')).rejects.toThrow(
|
||||
'explicit opt-in'
|
||||
);
|
||||
});
|
||||
|
||||
test('explicit synthetic fixtures use a stable seed', async () => {
|
||||
const storage = new StorageService({ logger }, null, null, null, {
|
||||
allowSyntheticData: true,
|
||||
syntheticSeed: 7,
|
||||
});
|
||||
expect(await storage.getHistoricalBars('FIXTURE', start, end, '1d')).toEqual(
|
||||
await storage.getHistoricalBars('FIXTURE', start, end, '1d')
|
||||
);
|
||||
});
|
||||
|
||||
test('empty storage and unknown strategies fail without leaving the engine running', async () => {
|
||||
const { mongodb } = memoryStore();
|
||||
const engine = new RustBacktestAdapter({ logger, mongodb });
|
||||
const config = BacktestConfigSchema.parse({
|
||||
mode: 'backtest',
|
||||
symbols: ['FIXTURE'],
|
||||
strategy: 'sma-crossover',
|
||||
startDate: start.toISOString(),
|
||||
endDate: end.toISOString(),
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
await expect(engine.runBacktest(config)).rejects.toThrow('No historical data');
|
||||
await expect(engine.runBacktest({ ...config, strategy: 'does-not-exist' })).rejects.toThrow(
|
||||
'Unknown native strategy'
|
||||
);
|
||||
expect(engine.getStatus().isRunning).toBe(false);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue