291 lines
9.2 KiB
TypeScript
291 lines
9.2 KiB
TypeScript
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 remain compatibility defaults, missing analytics are unknown', () => {
|
|
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: null },
|
|
});
|
|
});
|
|
|
|
test('legacy_missing_provenance: mutable definition fallback is explicitly not saved evidence', () => {
|
|
const row = fixture();
|
|
row.backtest_config = { name: 'Changed later', commission: 0.25 };
|
|
const result = mapStoredBacktestResult(row);
|
|
expect(result.config.name).toBe('Changed later'); // Old consumers keep their display fallback.
|
|
expect(result.provenance).toMatchObject({
|
|
configurationSource: 'legacy-definition-fallback',
|
|
datasetHash: null,
|
|
engineVersion: null,
|
|
economicsVersion: null,
|
|
strategyArtifactHash: null,
|
|
});
|
|
expect(result.provenance?.limitations.map(item => item.code)).toContain(
|
|
'missing-configuration'
|
|
);
|
|
expect(result.provenance?.limitations.map(item => item.code)).toContain(
|
|
'unversioned-execution'
|
|
);
|
|
});
|
|
|
|
test('frozen_config_not_mutable_definition: all stored inputs and dataset identity survive definition edits', () => {
|
|
const row = fixture();
|
|
row.engine = 'typescript';
|
|
row.configuration = {
|
|
name: 'Frozen strategy',
|
|
strategy: 'saved-strategy',
|
|
symbols: ['B.US'],
|
|
startDate: '2023-01-01',
|
|
endDate: '2023-02-01',
|
|
initialCapital: 1000,
|
|
commission: 0.0007,
|
|
slippage: 0.0002,
|
|
dataFrequency: '1m',
|
|
parameters: { lookback: 14 },
|
|
dataset: {
|
|
version: 1,
|
|
hash: 'a'.repeat(64),
|
|
instruments: [{ id: 'B.US', symbol: 'B', exchange: 'US' }],
|
|
startDate: '2023-01-01',
|
|
endDate: '2023-02-01',
|
|
interval: '1m',
|
|
policy: { adjustment: 'raw', timestamp: 'utc-instant' },
|
|
volumePolicy: 'reported',
|
|
qualityPolicy: 'reject-invalid-no-interpolation',
|
|
sources: [],
|
|
barCount: 10,
|
|
},
|
|
};
|
|
const first = mapStoredBacktestResult(row);
|
|
row.strategy = 'changed-strategy';
|
|
row.symbols = ['C.US'];
|
|
row.initial_capital = 999999;
|
|
row.backtest_config = { commission: 0.9, slippage: 0.9, dataFrequency: '1d' };
|
|
const reopened = mapStoredBacktestResult(row);
|
|
expect(reopened.config).toEqual(first.config);
|
|
expect(reopened.provenance).toEqual(first.provenance);
|
|
expect(reopened.provenance).toMatchObject({
|
|
configurationSource: 'stored-snapshot',
|
|
datasetHash: 'a'.repeat(64),
|
|
engineVersion: null,
|
|
economicsVersion: null,
|
|
strategyArtifactHash: null,
|
|
});
|
|
expect(reopened.provenance?.limitations.map(item => item.code)).not.toContain(
|
|
'missing-configuration'
|
|
);
|
|
});
|
|
|
|
test('null_metrics: known placeholders are unavailable without discarding computed statistics or mutating storage', () => {
|
|
const row = fixture();
|
|
row.engine = 'native';
|
|
row.metrics.sharpeRatio = 1.2;
|
|
row.metrics.sortinoRatio = 1.4;
|
|
row.analytics = {
|
|
exposureTime: 0,
|
|
riskMetrics: { value_at_risk_95: 0, volatility: 0.12, downside_deviation: 0.08 },
|
|
};
|
|
const before = structuredClone(row);
|
|
const result = mapStoredBacktestResult(row);
|
|
expect(result.analytics.exposureTime).toBeNull();
|
|
expect(result.analytics.riskMetrics).toEqual({
|
|
value_at_risk_95: null,
|
|
volatility: 0.12,
|
|
downside_deviation: 0.08,
|
|
});
|
|
expect(result.metrics.sharpeRatio).toBe(1.2);
|
|
expect(result.metrics.sortinoRatio).toBe(1.4);
|
|
expect(row).toEqual(before);
|
|
row.engine = 'typescript';
|
|
row.analytics = { exposureTime: 0, riskMetrics: { var95: 0 } };
|
|
expect(mapStoredBacktestResult(row).analytics).toEqual({
|
|
exposureTime: 0,
|
|
riskMetrics: { var95: 0 },
|
|
});
|
|
row.engine = 'legacy';
|
|
expect(mapStoredBacktestResult(row).analytics.exposureTime).toBeNull();
|
|
});
|
|
|
|
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);
|
|
});
|
|
});
|