436 lines
16 KiB
TypeScript
436 lines
16 KiB
TypeScript
import { describe, expect, spyOn, test } from 'bun:test';
|
|
import type { HistoricalDataset } from '@stock-bot/types';
|
|
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
|
|
import {
|
|
BacktestPlayback,
|
|
type PlaybackProgress,
|
|
} from '../../apps/stock/orchestrator/src/backtest/BacktestPlayback';
|
|
import { BacktestReport } from '../../apps/stock/orchestrator/src/backtest/BacktestReport';
|
|
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
|
import type { ClosedTrade } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
|
import { formatReport } from '../../apps/stock/orchestrator/src/backtest/report-format';
|
|
import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager';
|
|
import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types';
|
|
|
|
const day = 86400000;
|
|
const start = Date.parse('2024-01-01T00:00:00Z');
|
|
const config = BacktestConfigSchema.parse({
|
|
mode: 'backtest',
|
|
strategy: 'sma-crossover',
|
|
symbols: ['A.US', 'B.US'],
|
|
startDate: new Date(start).toISOString(),
|
|
endDate: '2024-03-01T00:00:00Z',
|
|
initialCapital: 1000,
|
|
dataFrequency: '1d',
|
|
});
|
|
const bars = [0, 1, 2].flatMap(index =>
|
|
config.symbols.map(symbol => ({
|
|
symbol,
|
|
timestamp: start + index * day,
|
|
open: 100,
|
|
high: 101,
|
|
low: 99,
|
|
close: 100,
|
|
volume: 1000,
|
|
vwap: 100,
|
|
}))
|
|
);
|
|
const dataset: HistoricalDataset = {
|
|
manifest: {
|
|
version: 1,
|
|
hash: '0'.repeat(64),
|
|
instruments: config.symbols.map(id => ({ id, symbol: id.split('.')[0]!, exchange: 'US' })),
|
|
startDate: config.startDate,
|
|
endDate: config.endDate,
|
|
interval: '1d',
|
|
policy: { adjustment: 'raw', timestamp: 'utc-session-date' },
|
|
volumePolicy: 'reported',
|
|
qualityPolicy: 'reject-invalid-no-interpolation',
|
|
sources: config.symbols.map(instrumentId => ({
|
|
instrumentId,
|
|
provider: 'synthetic',
|
|
revision: 'fixture',
|
|
})),
|
|
barCount: bars.length,
|
|
},
|
|
bars,
|
|
};
|
|
const trade: ClosedTrade = {
|
|
id: 'closed-1',
|
|
symbol: 'A.US',
|
|
side: 'Buy',
|
|
quantity: 1,
|
|
entry_price: 100,
|
|
exit_price: 90,
|
|
entry_time: new Date(start).toISOString(),
|
|
exit_time: new Date(start + day).toISOString(),
|
|
pnl: -10,
|
|
pnl_percent: -10,
|
|
commission: 0,
|
|
duration_ms: day,
|
|
};
|
|
|
|
function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (reason: unknown) => void;
|
|
const promise = new Promise<T>((done, fail) => {
|
|
resolve = done;
|
|
reject = fail;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
async function deadline<T>(work: Promise<T>): Promise<T> {
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
return await Promise.race([
|
|
work,
|
|
new Promise<never>((_resolve, reject) => {
|
|
timer = setTimeout(() => reject(new Error('Control did not settle promptly')), 500);
|
|
}),
|
|
]);
|
|
} finally {
|
|
clearTimeout(timer);
|
|
}
|
|
}
|
|
const turn = () => new Promise<void>(resolve => setTimeout(resolve, 0));
|
|
|
|
describe('backtest playback isolation and controls', () => {
|
|
test('a cursor consumes frozen inputs in order, preserves timestamp ties and yields to timers', async () => {
|
|
const playback = new BacktestPlayback(start, null);
|
|
const events = Object.freeze(
|
|
Array.from({ length: 1001 }, (_, id) => ({ id, timestamp: start + Math.floor(id / 2) }))
|
|
);
|
|
const seen: number[] = [];
|
|
const updates: PlaybackProgress[] = [];
|
|
let timerRan = false;
|
|
setTimeout(() => {
|
|
timerRan = true;
|
|
}, 0);
|
|
await playback.process(
|
|
events,
|
|
event => event.timestamp,
|
|
async event => {
|
|
seen.push(event.id);
|
|
},
|
|
update => updates.push(update)
|
|
);
|
|
playback.finish();
|
|
expect(seen).toEqual(events.map(event => event.id));
|
|
expect(timerRan).toBe(true);
|
|
expect(events).toHaveLength(1001);
|
|
expect(updates.filter(update => update.progress === 100)).toHaveLength(1);
|
|
expect(updates.at(-1)).toMatchObject({
|
|
processed: 1001,
|
|
total: 1001,
|
|
remaining: 0,
|
|
progress: 100,
|
|
});
|
|
expect(playback.getStatus()).toMatchObject({
|
|
isRunning: false,
|
|
isPaused: false,
|
|
progress: 100,
|
|
});
|
|
});
|
|
|
|
test('pause blocks delivery and resume wakes it without a polling interval', async () => {
|
|
const playback = new BacktestPlayback(start, null);
|
|
playback.pause();
|
|
let processed = 0;
|
|
const work = playback.process(
|
|
[start],
|
|
time => time,
|
|
async () => {
|
|
processed++;
|
|
},
|
|
() => {}
|
|
);
|
|
await turn();
|
|
expect(processed).toBe(0);
|
|
playback.resume();
|
|
await deadline(work);
|
|
expect(processed).toBe(1);
|
|
playback.finish();
|
|
playback.pause();
|
|
expect(playback.getStatus().isPaused).toBe(false);
|
|
});
|
|
|
|
test('stop wakes a paused run and never emits completed progress', async () => {
|
|
const playback = new BacktestPlayback(start, null);
|
|
playback.pause();
|
|
const updates: number[] = [];
|
|
const work = playback.process(
|
|
[start],
|
|
time => time,
|
|
async () => {
|
|
throw new Error('Must not execute');
|
|
},
|
|
update => updates.push(update.progress)
|
|
);
|
|
const outcome = work.catch(error => error);
|
|
await turn();
|
|
playback.stop();
|
|
expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError);
|
|
expect(updates).toEqual([]);
|
|
playback.finish();
|
|
});
|
|
|
|
test.each(['stop', 'setSpeed'] as const)('%s interrupts a long pacing timer', async control => {
|
|
const playback = new BacktestPlayback(start, 0.001);
|
|
let processed = 0;
|
|
const work = playback.process(
|
|
[start],
|
|
time => time,
|
|
async () => {
|
|
processed++;
|
|
},
|
|
() => {}
|
|
);
|
|
const outcome = work.catch(error => error);
|
|
await turn();
|
|
if (control === 'stop') playback.stop();
|
|
else playback.setSpeed(null);
|
|
const settled = await deadline(outcome);
|
|
if (control === 'stop') expect(settled).toBeInstanceOf(BacktestCancelledError);
|
|
expect(processed).toBe(control === 'stop' ? 0 : 1);
|
|
playback.finish();
|
|
});
|
|
|
|
test('cancellation detaches a slow read and a late rejection cannot resume execution', async () => {
|
|
const playback = new BacktestPlayback(start, null);
|
|
const load = deferred<number>();
|
|
const entered = deferred<void>();
|
|
const work = playback.read(() => {
|
|
entered.resolve();
|
|
return load.promise;
|
|
});
|
|
const outcome = work.catch(error => error);
|
|
await entered.promise;
|
|
playback.stop();
|
|
expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError);
|
|
load.reject(new Error('Late read failure'));
|
|
await turn();
|
|
let calls = 0;
|
|
await expect(
|
|
playback.read(async () => {
|
|
calls++;
|
|
return 1;
|
|
})
|
|
).rejects.toBeInstanceOf(BacktestCancelledError);
|
|
expect(calls).toBe(0);
|
|
playback.finish();
|
|
});
|
|
|
|
test('failed delivery cannot advance its cursor or claim completion', async () => {
|
|
const playback = new BacktestPlayback(start, null);
|
|
const updates: number[] = [];
|
|
await expect(
|
|
playback.process(
|
|
[1, 2],
|
|
time => time,
|
|
async time => {
|
|
if (time === 2) throw new Error('delivery failure');
|
|
},
|
|
update => updates.push(update.progress)
|
|
)
|
|
).rejects.toThrow('delivery failure');
|
|
expect(playback.getStatus().progress).toBe(50);
|
|
expect(updates).not.toContain(100);
|
|
playback.finish();
|
|
});
|
|
|
|
test('speed validation rejects non-finite, zero and negative values', () => {
|
|
for (const speed of [NaN, Infinity, 0, -1]) {
|
|
expect(() => new BacktestPlayback(start, speed)).toThrow('positive or null');
|
|
expect(() => new BacktestPlayback(start, null).setSpeed(speed)).toThrow('positive or null');
|
|
}
|
|
});
|
|
|
|
test('one playback cannot run two cursors or continue after finalization', async () => {
|
|
const playback = new BacktestPlayback(start, null);
|
|
await playback.process(
|
|
[start],
|
|
time => time,
|
|
async () => {},
|
|
() => {}
|
|
);
|
|
await expect(
|
|
playback.process(
|
|
[start],
|
|
time => time,
|
|
async () => {},
|
|
() => {}
|
|
)
|
|
).rejects.toThrow('already started');
|
|
playback.finish();
|
|
await expect(playback.read(async () => 1)).rejects.toBeInstanceOf(BacktestCancelledError);
|
|
});
|
|
});
|
|
|
|
describe('detached, repeatable backtest reporting', () => {
|
|
test('analysis runs once per completion and formatting never re-analyzes retained inputs', () => {
|
|
const analyze = spyOn(PerformanceAnalyzer.prototype, 'analyze');
|
|
try {
|
|
const report = new BacktestReport(config, 'cached');
|
|
report.record(start + day, 990);
|
|
report.complete(dataset, [trade], [], {});
|
|
report.export('html');
|
|
report.export('csv');
|
|
report.export('json');
|
|
expect(analyze).toHaveBeenCalledTimes(1);
|
|
} finally {
|
|
analyze.mockRestore();
|
|
}
|
|
});
|
|
test('exports retain completed equity and do not append the same trades repeatedly', () => {
|
|
const report = new BacktestReport(config, 'report');
|
|
report.record(start, 1000);
|
|
report.record(start + day, 990);
|
|
const trades = structuredClone([trade]);
|
|
const result = report.complete(dataset, trades, [], { totalIssues: 0 });
|
|
expect(result.metrics.totalTrades).toBe(1);
|
|
expect(result.config).toMatchObject({ commission: 0.001, slippage: 0.0001 });
|
|
const first = report.export();
|
|
const parsed = JSON.parse(first);
|
|
expect(parsed.summary.totalTrades).toBe(1);
|
|
expect(parsed.equityCurve.at(-1).value).toBe(990);
|
|
trades[0]!.pnl = 10000;
|
|
result.equity[0]!.value = 1;
|
|
report.export('csv');
|
|
report.export('html');
|
|
expect(report.export()).toBe(first);
|
|
expect(() => report.complete(dataset, [], [], {})).toThrow('already finalized');
|
|
expect(() => report.record(start + day * 2, 0)).toThrow('already finalized');
|
|
});
|
|
|
|
test('zero and negative equity remain losses, never a fabricated starting balance', () => {
|
|
const report = new BacktestReport(config, 'loss');
|
|
report.record(start + day, 0);
|
|
report.record(start + day * 2, -100);
|
|
const result = report.complete(dataset, [], [], {});
|
|
expect(result.equity.map(point => point.value)).toEqual([1000, 0, -100]);
|
|
expect(result.metrics.totalReturn).toBeCloseTo(-110);
|
|
expect(result.metrics.maxDrawdown).toBe(1.1);
|
|
expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110);
|
|
expect(
|
|
Object.values(result.analytics.riskMetrics).every(
|
|
value => value === null || Number.isFinite(value)
|
|
)
|
|
).toBe(true);
|
|
expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true);
|
|
});
|
|
|
|
test('a one-timestamp run has finite analytics, stable timestamp ties and grouped OHLC', () => {
|
|
const report = new BacktestReport(config, 'single');
|
|
report.record(start, 999);
|
|
report.record(start, 998);
|
|
const result = report.complete(dataset, [], [], {});
|
|
expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]);
|
|
expect(result.metrics.totalReturn).toBeCloseTo(-0.2);
|
|
expect(result.metrics.maxDrawdown).toBeCloseTo(0.002);
|
|
expect(result.analytics.dailyReturns).toHaveLength(1);
|
|
expect(result.analytics.dailyReturns[0]).toBeCloseTo(-0.2);
|
|
expect(result.metrics.sharpeRatio).toBeNull();
|
|
expect(result.metrics.annualizedReturn).toBeNull();
|
|
expect(
|
|
Object.values(result.analytics.riskMetrics).every(
|
|
value => value === null || Number.isFinite(value)
|
|
)
|
|
).toBe(true);
|
|
expect(Object.keys(result.ohlcData)).toEqual(config.symbols);
|
|
expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([
|
|
start,
|
|
start + day,
|
|
start + day * 2,
|
|
]);
|
|
expect(result.ohlcData['B.US']).toHaveLength(3);
|
|
});
|
|
|
|
test('ongoing drawdown duration uses the simulated horizon, not the wall clock', () => {
|
|
const report = new BacktestReport(config, 'drawdown');
|
|
report.record(start + day, 900);
|
|
report.record(start + day * 4, 800);
|
|
report.complete(dataset, [], [], {});
|
|
expect(JSON.parse(report.export()).summary.maxDrawdownDuration).toBe(3);
|
|
expect(report.export('html')).toContain('20.00%');
|
|
expect(JSON.parse(report.export()).performanceReport).toContain('Max Drawdown: 20.00%');
|
|
});
|
|
|
|
test('monthly grouping uses UTC, and invalid or unordered observations fail explicitly', () => {
|
|
const report = new BacktestReport(config, 'utc');
|
|
report.record(Date.parse('2024-01-31T23:30:00Z'), 1100);
|
|
report.record(Date.parse('2024-02-01T00:30:00Z'), 1200);
|
|
const result = report.complete(dataset, [], [], {});
|
|
expect(Object.keys(result.analytics.monthlyReturns)).toEqual(['2024-01', '2024-02']);
|
|
expect(result.analytics.monthlyReturns['2024-01']).toBeCloseTo(10);
|
|
expect(result.analytics.monthlyReturns['2024-02']).toBeCloseTo((100 / 1100) * 100);
|
|
const invalid = new BacktestReport(config, 'invalid');
|
|
expect(() => invalid.export()).toThrow('No completed');
|
|
expect(() => invalid.record(start - 1, 1000)).toThrow('Out-of-order');
|
|
expect(() => invalid.record(start, NaN)).toThrow('Invalid');
|
|
expect(() => invalid.record(Infinity, 1000)).toThrow('Invalid');
|
|
const insolvent = new BacktestReport(config, 'insolvent');
|
|
insolvent.record(start + day, 0);
|
|
insolvent.record(Date.parse('2024-02-01T00:30:00Z'), -10);
|
|
const losses = insolvent.complete(dataset, [], [], {});
|
|
expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 });
|
|
});
|
|
|
|
test('risk analytics and summary share fraction-based math without 100x percentage scaling', () => {
|
|
const report = new BacktestReport(config, 'risk');
|
|
let value = config.initialCapital;
|
|
for (let i = 1; i <= 30; i++) {
|
|
value *= 1 + (i % 2 ? -0.01 : 0.02);
|
|
report.record(start + i * day, value);
|
|
}
|
|
const result = report.complete(dataset, [], [], {});
|
|
const returns = result.analytics.dailyReturns.map(value => value / 100);
|
|
const average = returns.reduce((sum, value) => sum + value, 0) / returns.length;
|
|
const expected =
|
|
Math.sqrt(
|
|
returns.reduce((sum, value) => sum + (value - average) ** 2, 0) / (returns.length - 1)
|
|
) * Math.sqrt(252);
|
|
expect(result.analytics.riskMetrics.volatility).toBeCloseTo(expected, 10);
|
|
const summary = JSON.parse(report.export()).summary;
|
|
expect(summary.volatility / 100).toBeCloseTo(expected, 10);
|
|
expect(summary.var95 / 100).toBeCloseTo(result.analytics.riskMetrics.var95!, 10);
|
|
expect(summary.cvar95 / 100).toBeCloseTo(result.analytics.riskMetrics.cvar95!, 10);
|
|
});
|
|
|
|
test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => {
|
|
const input = structuredClone(dataset);
|
|
for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) {
|
|
bar.close = bar.symbol === 'A.US' ? 150 : 50;
|
|
bar.open = bar.close;
|
|
bar.high = bar.close + 1;
|
|
bar.low = bar.close - 1;
|
|
bar.vwap = bar.close;
|
|
}
|
|
const before = structuredClone(input);
|
|
const inspector = new DataManager({
|
|
async getHistoricalBars() {
|
|
return [];
|
|
},
|
|
});
|
|
inspector.inspectDataset(input);
|
|
const quality = inspector.getDataQualityReport();
|
|
expect(quality.totalIssues).toBe(4);
|
|
expect(quality.bySymbol).toEqual({ 'A.US': 2, 'B.US': 2 });
|
|
expect(quality.issues.map(issue => issue.symbol)).toEqual(['A.US', 'A.US', 'B.US', 'B.US']);
|
|
expect(input).toEqual(before);
|
|
inspector.inspectDataset(dataset);
|
|
expect(inspector.getDataQualityReport().totalIssues).toBe(0);
|
|
});
|
|
|
|
test('HTML escapes text and CSV quotes cells while preserving numeric losses', () => {
|
|
const report = new BacktestReport(config, 'escaping');
|
|
report.record(start + day, 990);
|
|
report.complete(dataset, [{ ...trade, symbol: '<script>"bad",\nvalue</script>' }], [], {});
|
|
expect(report.export('html')).not.toContain('<script>');
|
|
expect(report.export('html')).toContain('<script>');
|
|
expect(report.export('csv')).toContain('"<script>""bad"",\nvalue</script>"');
|
|
expect(report.export('csv')).toContain(',-10,-10');
|
|
const snapshot = JSON.parse(report.export());
|
|
snapshot.trades[0].symbol = '=HYPERLINK("hostile")';
|
|
expect(formatReport(snapshot, 'csv')).toContain('"\'=HYPERLINK(""hostile"")"');
|
|
});
|
|
});
|