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
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);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue