Share backtest request contracts and isolate stored result mapping
This commit is contained in:
parent
007e35c747
commit
420c47704e
21 changed files with 777 additions and 244 deletions
194
test/integration/backtest-request-contract.test.ts
Normal file
194
test/integration/backtest-request-contract.test.ts
Normal file
|
|
@ -0,0 +1,194 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
BACKTEST_DEFAULTS,
|
||||
BacktestConfigSchema,
|
||||
backtestRequestFromDefinition,
|
||||
isBacktestRequestError,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import { parseBacktestRequest as runnerParser } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { BacktestConfigSchema as orchestratorSchema } from '../../apps/stock/orchestrator/src/types';
|
||||
|
||||
const request = {
|
||||
mode: 'backtest',
|
||||
name: 'Contract fixture',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-03-01T00:00:00.000Z',
|
||||
initialCapital: 10000,
|
||||
dataFrequency: '1d',
|
||||
config: { fastPeriod: 3, slowPeriod: 7 },
|
||||
};
|
||||
const definition = {
|
||||
name: request.name,
|
||||
strategy: request.strategy,
|
||||
symbols: request.symbols,
|
||||
startDate: request.startDate,
|
||||
endDate: request.endDate,
|
||||
initialCapital: request.initialCapital,
|
||||
config: request.config,
|
||||
};
|
||||
|
||||
describe('shared backtest request contract', () => {
|
||||
test('runner and legacy schema exports delegate to the same pure contract', () => {
|
||||
expect(orchestratorSchema).toBe(BacktestConfigSchema);
|
||||
expect(runnerParser).toBe(parseBacktestRequest);
|
||||
});
|
||||
|
||||
test('definition snapshots and direct requests share defaults without mutating their inputs', () => {
|
||||
const input = structuredClone(request);
|
||||
const parsed = parseBacktestRequest(input);
|
||||
expect(JSON.parse(JSON.stringify(backtestRequestFromDefinition(definition)))).toEqual(parsed);
|
||||
expect(parsed).toMatchObject({
|
||||
commission: BACKTEST_DEFAULTS.commission,
|
||||
slippage: BACKTEST_DEFAULTS.slippage,
|
||||
dataFrequency: BACKTEST_DEFAULTS.dataFrequency,
|
||||
speed: 'max',
|
||||
});
|
||||
expect(input).toEqual(request);
|
||||
expect(parsed).not.toBe(input);
|
||||
expect(definition.config).toEqual({ fastPeriod: 3, slowPeriod: 7 });
|
||||
expect(
|
||||
backtestRequestFromDefinition({ ...definition, config: { commission: null, slippage: null } })
|
||||
).toMatchObject({
|
||||
commission: BACKTEST_DEFAULTS.commission,
|
||||
slippage: BACKTEST_DEFAULTS.slippage,
|
||||
});
|
||||
});
|
||||
|
||||
test('zero costs, explicit policies, replay identity and risk settings survive normalization', () => {
|
||||
const riskLimits = {
|
||||
maxPositionSize: 100,
|
||||
maxOrderSize: 100,
|
||||
maxDailyLoss: 100,
|
||||
maxGrossExposure: 1000,
|
||||
maxSymbolExposure: 500,
|
||||
};
|
||||
const policy = { adjustment: 'provider-adjusted', timestamp: 'utc-session-date' };
|
||||
const runId = '00000000-0000-4000-8000-000000000001';
|
||||
const backtestId = '00000000-0000-4000-8000-000000000002';
|
||||
const config = {
|
||||
...definition.config,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
dataPolicy: policy,
|
||||
datasetHash: 'f'.repeat(64),
|
||||
riskLimits,
|
||||
};
|
||||
const snapshot = backtestRequestFromDefinition(
|
||||
{ ...definition, config },
|
||||
{ runId, backtestId }
|
||||
);
|
||||
expect(snapshot).toMatchObject({
|
||||
runId,
|
||||
backtestId,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataPolicy: policy,
|
||||
datasetHash: config.datasetHash,
|
||||
riskLimits,
|
||||
config,
|
||||
});
|
||||
expect(parseBacktestRequest(JSON.parse(JSON.stringify(snapshot)))).toEqual(snapshot);
|
||||
});
|
||||
|
||||
test('API date labels and UTC-offset ranges canonicalize without guessing timezone or sessions', () => {
|
||||
expect(
|
||||
backtestRequestFromDefinition({
|
||||
...definition,
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-03-01',
|
||||
}).startDate
|
||||
).toBe(request.startDate);
|
||||
expect(
|
||||
backtestRequestFromDefinition({
|
||||
...definition,
|
||||
startDate: new Date(request.startDate),
|
||||
endDate: new Date(request.endDate),
|
||||
}).startDate
|
||||
).toBe(request.startDate);
|
||||
const intraday = backtestRequestFromDefinition({
|
||||
...definition,
|
||||
startDate: '2024-01-01T09:00:00-05:00',
|
||||
endDate: '2024-01-01T10:00:00-05:00',
|
||||
config: { dataFrequency: '1m' },
|
||||
});
|
||||
expect(intraday.startDate).toBe('2024-01-01T14:00:00.000Z');
|
||||
expect(() =>
|
||||
backtestRequestFromDefinition({ ...definition, startDate: '2024-01-01T00:00:00' })
|
||||
).toThrow('UTC offset');
|
||||
expect(() =>
|
||||
backtestRequestFromDefinition({ ...definition, startDate: '2024-01-01T01:00:00Z' })
|
||||
).toThrow('UTC midnight');
|
||||
});
|
||||
|
||||
test('API speed multipliers preserve existing buckets and reject invalid values', () => {
|
||||
for (const [speedMultiplier, speed] of [
|
||||
[null, 'max'],
|
||||
[0.5, 'realtime'],
|
||||
[1, 'realtime'],
|
||||
[2, '2x'],
|
||||
[4, '2x'],
|
||||
[5, '5x'],
|
||||
[9, '5x'],
|
||||
[10, '10x'],
|
||||
[100, '10x'],
|
||||
] as const) {
|
||||
expect(backtestRequestFromDefinition(definition, { speedMultiplier }).speed).toBe(speed);
|
||||
}
|
||||
for (const speedMultiplier of [0, -1, NaN, Infinity]) {
|
||||
expect(() => backtestRequestFromDefinition(definition, { speedMultiplier })).toThrow(
|
||||
'Speed multiplier'
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('direct and definition paths reject the same invalid execution settings', () => {
|
||||
for (const config of [
|
||||
{ commission: -0.1 },
|
||||
{ slippage: 0.11 },
|
||||
{ commission: '0.01' },
|
||||
{ slippage: Infinity },
|
||||
{ riskLimits: { maxDailyLoss: -1 } },
|
||||
{ datasetHash: 'invalid' },
|
||||
{ dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } },
|
||||
{ dataFrequency: '2h' },
|
||||
]) {
|
||||
expect(() => backtestRequestFromDefinition({ ...definition, config })).toThrow();
|
||||
expect(() => parseBacktestRequest({ ...request, ...config })).toThrow();
|
||||
}
|
||||
for (const fields of [
|
||||
{ symbols: ['A'] },
|
||||
{ symbols: ['A.US', 'A.US'] },
|
||||
{ initialCapital: Infinity },
|
||||
{ initialCapital: 0 },
|
||||
{ strategy: '' },
|
||||
{ endDate: request.startDate },
|
||||
]) {
|
||||
expect(() => backtestRequestFromDefinition({ ...definition, ...fields })).toThrow();
|
||||
expect(() => parseBacktestRequest({ ...request, ...fields })).toThrow();
|
||||
}
|
||||
});
|
||||
|
||||
test('strategy extension fields and direct multi-strategy requests remain intact', () => {
|
||||
const strategies = [{ name: 'custom', config: { feature: 'extension' } }];
|
||||
expect(parseBacktestRequest({ ...request, strategies }).strategies).toEqual([
|
||||
{ name: 'custom', enabled: true, config: { feature: 'extension' } },
|
||||
]);
|
||||
const config = { featureWindow: 27, customFeature: { version: 2 }, commission: 0 };
|
||||
expect(
|
||||
backtestRequestFromDefinition({ ...definition, strategy: 'custom', config }).config
|
||||
).toEqual(config);
|
||||
expect(isBacktestRequestError(new Error('database failure'))).toBe(false);
|
||||
for (const input of [{}, { ...request, symbols: ['A'] }]) {
|
||||
try {
|
||||
parseBacktestRequest(input);
|
||||
throw new Error('unexpected acceptance');
|
||||
} catch (error) {
|
||||
expect(isBacktestRequestError(error)).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
193
test/integration/backtest-result-mapping.test.ts
Normal file
193
test/integration/backtest-result-mapping.test.ts
Normal file
|
|
@ -0,0 +1,193 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
mapStoredBacktestResult,
|
||||
type StoredBacktestResult,
|
||||
} from '../../apps/stock/web-api/src/services/backtest-result';
|
||||
|
||||
function fixture(): StoredBacktestResult {
|
||||
return {
|
||||
run_id: 'run',
|
||||
backtest_id: 'definition',
|
||||
completed_at: new Date('2024-03-01T00:00:00Z'),
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['A.US'],
|
||||
start_date: new Date('2024-01-01T00:00:00Z'),
|
||||
end_date: new Date('2024-03-01T00:00:00Z'),
|
||||
initial_capital: '10000',
|
||||
metrics: {
|
||||
totalReturn: 25,
|
||||
winRate: 50,
|
||||
maxDrawdown: 0.1,
|
||||
sharpeRatio: null,
|
||||
profitFactor: null,
|
||||
totalTrades: 99,
|
||||
avgWin: 10,
|
||||
avgLoss: -5,
|
||||
annualReturn: 30,
|
||||
annualizedReturn: 30,
|
||||
cagr: 30,
|
||||
},
|
||||
analytics: {
|
||||
exposureTime: 25,
|
||||
dailyReturns: [1, -2],
|
||||
monthlyReturns: { '2024-01': 5 },
|
||||
drawdownSeries: [{ timestamp: 1, value: -10 }],
|
||||
riskMetrics: { var95: 0.02 },
|
||||
},
|
||||
trades: [
|
||||
{
|
||||
id: 'trade',
|
||||
symbol: 'A.US',
|
||||
side: 'buy',
|
||||
entryDate: '2024-01-01T00:00:00Z',
|
||||
entryPrice: 100,
|
||||
exitDate: null,
|
||||
quantity: 1,
|
||||
commission: 0,
|
||||
pnl: 5,
|
||||
},
|
||||
],
|
||||
equity_curve: [{ date: '2024-01-01', value: 10000 }],
|
||||
ohlc_data: {},
|
||||
positions: [],
|
||||
execution_time: 20,
|
||||
};
|
||||
}
|
||||
|
||||
describe('pure stored backtest result conversion', () => {
|
||||
test('legacy TypeScript percentage units and closed trade identities retain existing normalization', () => {
|
||||
const row = fixture();
|
||||
const before = structuredClone(row);
|
||||
const result = mapStoredBacktestResult(row);
|
||||
expect(result).toMatchObject({
|
||||
engine: 'legacy',
|
||||
legacy: true,
|
||||
status: 'completed',
|
||||
completedAt: '2024-03-01T00:00:00.000Z',
|
||||
config: {
|
||||
parameters: {},
|
||||
initialCapital: 10000,
|
||||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d',
|
||||
name: 'Backtest',
|
||||
},
|
||||
});
|
||||
expect(result.metrics).toMatchObject({
|
||||
totalReturn: 0.25,
|
||||
winRate: 0.5,
|
||||
maxDrawdown: 0.1,
|
||||
annualReturn: 0.3,
|
||||
annualizedReturn: 0.3,
|
||||
cagr: 30,
|
||||
totalTrades: 1,
|
||||
profitableTrades: 1,
|
||||
profitFactor: null,
|
||||
sharpeRatio: null,
|
||||
});
|
||||
expect(result.analytics).toMatchObject({
|
||||
exposureTime: 0.25,
|
||||
dailyReturns: [0.01, -0.02],
|
||||
monthlyReturns: { '2024-01': 0.05 },
|
||||
drawdownSeries: [{ timestamp: 1, value: -0.1 }],
|
||||
riskMetrics: { var95: 0.02 },
|
||||
});
|
||||
expect(result.trades[0]).toMatchObject({
|
||||
kind: 'closed',
|
||||
timestamp: row.trades[0]!.entryDate,
|
||||
price: 100,
|
||||
exitDate: null,
|
||||
});
|
||||
expect(row).toEqual(before);
|
||||
expect(mapStoredBacktestResult(row)).toEqual(result);
|
||||
});
|
||||
|
||||
test('legacy native daily fractions and fill counts are not scaled or recounted', () => {
|
||||
const row = fixture();
|
||||
row.metrics.finalValue = 12500;
|
||||
row.analytics!.dailyReturns = [0.01, -0.02];
|
||||
row.trades = [
|
||||
{
|
||||
id: 'fill',
|
||||
symbol: 'A.US',
|
||||
timestamp: '2024-01-01T00:00:00Z',
|
||||
price: 100,
|
||||
side: 'buy',
|
||||
quantity: 1,
|
||||
commission: 0,
|
||||
},
|
||||
];
|
||||
const result = mapStoredBacktestResult(row);
|
||||
expect(result.analytics.dailyReturns).toEqual([0.01, -0.02]);
|
||||
expect(result.metrics.totalTrades).toBe(99);
|
||||
expect(result.trades[0]?.kind).toBe('fill');
|
||||
expect(result.metrics.profitableTrades).toBeUndefined();
|
||||
});
|
||||
|
||||
test('current snapshots preserve null ratios, configuration provenance and units exactly', () => {
|
||||
const row = fixture();
|
||||
const config = {
|
||||
name: 'Frozen',
|
||||
strategy: 'custom',
|
||||
symbols: ['B.US'],
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2023-03-01T00:00:00Z',
|
||||
initialCapital: 100,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1m',
|
||||
parameters: { featureWindow: 3 },
|
||||
};
|
||||
row.configuration = config;
|
||||
row.engine = 'typescript';
|
||||
row.run_status = 'cancelled';
|
||||
row.metrics.totalReturn = -0.2;
|
||||
row.metrics.winRate = 0;
|
||||
const before = structuredClone(row);
|
||||
const result = mapStoredBacktestResult(row);
|
||||
expect(result.config).toEqual(config);
|
||||
expect(result.metrics).toEqual(before.metrics);
|
||||
expect(result.analytics).toEqual({
|
||||
...before.analytics,
|
||||
exposureTime: before.analytics?.exposureTime ?? 0,
|
||||
});
|
||||
expect(result.engine).toBe('typescript');
|
||||
expect(result.status).toBe('cancelled');
|
||||
expect(result).not.toHaveProperty('legacy');
|
||||
expect(row).toEqual(before);
|
||||
});
|
||||
|
||||
test('legacy explicit zero fees and absent optional analytics keep their existing defaults', () => {
|
||||
const row = fixture();
|
||||
row.backtest_config = {
|
||||
name: 'Legacy',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1h',
|
||||
feature: 9,
|
||||
};
|
||||
row.analytics = null;
|
||||
row.trades = [];
|
||||
expect(mapStoredBacktestResult(row)).toMatchObject({
|
||||
config: {
|
||||
name: 'Legacy',
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1h',
|
||||
parameters: row.backtest_config,
|
||||
},
|
||||
analytics: { exposureTime: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
test('malformed trade identities fail instead of fabricating an execution time or price', () => {
|
||||
const row = fixture();
|
||||
delete row.trades[0]!.entryDate;
|
||||
expect(() => mapStoredBacktestResult(row)).toThrow('Malformed stored backtest trade');
|
||||
row.trades[0]!.timestamp = '2024-01-01T00:00:00Z';
|
||||
delete row.trades[0]!.entryPrice;
|
||||
expect(() => mapStoredBacktestResult(row)).toThrow('Malformed stored backtest trade');
|
||||
row.trades[0]!.price = 0;
|
||||
expect(mapStoredBacktestResult(row).trades[0]?.price).toBe(0);
|
||||
});
|
||||
});
|
||||
|
|
@ -26,6 +26,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 { createBacktestRoutes as createV1Routes } from '../../apps/stock/web-api/src/routes/backtest.routes';
|
||||
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';
|
||||
|
|
@ -176,6 +177,11 @@ describe('one backtest execution workflow', () => {
|
|||
{ ...config, symbols: ['FIXTURE'] },
|
||||
{ ...config, config: { dataPolicy: { adjustment: 'raw', timestamp: 'utc-instant' } } },
|
||||
{ ...config, config: { datasetHash: 'invalid' } },
|
||||
{ ...config, config: { commission: -0.01 } },
|
||||
{ ...config, config: { slippage: 0.11 } },
|
||||
{ ...config, config: { commission: '0.001' } },
|
||||
{ ...config, initialCapital: 0 },
|
||||
{ ...config, strategy: '' },
|
||||
]) {
|
||||
const response = await api.request('/api/v2/backtests', {
|
||||
method: 'POST',
|
||||
|
|
@ -212,6 +218,18 @@ describe('one backtest execution workflow', () => {
|
|||
'not found'
|
||||
);
|
||||
});
|
||||
|
||||
test('V1 reports shared request-validation failures as bad input without creating definitions or runs', async () => {
|
||||
const f = await fixture();
|
||||
const response = await createV1Routes(f.services).request('/api/backtests', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ ...config, config: { commission: -0.01 } }),
|
||||
});
|
||||
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('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', {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue