fix(engine): reconcile terminal equity after closing fees
This commit is contained in:
parent
1148673245
commit
74ba3b97f5
2 changed files with 307 additions and 0 deletions
50
test/integration/native-terminal-equity.test.ts
Normal file
50
test/integration/native-terminal-equity.test.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { BacktestEngine } from '@stock-bot/engine';
|
||||
import { nativeResultSchema } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
|
||||
test('native terminal liquidation reports both commissions in final equity', () => {
|
||||
const start = Date.parse('2024-01-01T00:00:00Z');
|
||||
const end = start + 3 * 86_400_000;
|
||||
const engine = new BacktestEngine({
|
||||
name: 'Terminal fee regression',
|
||||
symbols: ['A.US'],
|
||||
startDate: new Date(start).toISOString(),
|
||||
endDate: new Date(end).toISOString(),
|
||||
initialCapital: 10,
|
||||
commission: 0.01,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
engine.addNativeStrategy('sma_crossover', 'fixed-share SMA', 'terminal-fixture', {
|
||||
fastPeriod: 1,
|
||||
slowPeriod: 2,
|
||||
quantity: 1,
|
||||
});
|
||||
// The crossover buys exactly one share at 4 on day 3. Day 4 leaves it open
|
||||
// for terminal liquidation, also at 4; no production sizing is inferred.
|
||||
engine.loadMarketData(
|
||||
[4, 3, 4, 4].map((price, index) => ({
|
||||
symbol: 'A.US',
|
||||
timestamp: start + index * 86_400_000,
|
||||
type: 'bar',
|
||||
open: price,
|
||||
high: price,
|
||||
low: price,
|
||||
close: price,
|
||||
volume: 1_000,
|
||||
vwap: price,
|
||||
}))
|
||||
);
|
||||
|
||||
const result = nativeResultSchema.parse(JSON.parse(engine.run()));
|
||||
expect(result.trades).toHaveLength(2);
|
||||
expect(result.trades[0]).toMatchObject({ side: 'buy', quantity: 1, price: 4 });
|
||||
expect(result.trades[1]).toMatchObject({ side: 'sell', quantity: 1, price: 4 });
|
||||
expect(Date.parse(result.trades[1]!.timestamp)).toBe(end);
|
||||
expect(result.trades.reduce((sum, fill) => sum + fill.commission, 0)).toBeCloseTo(0.08, 10);
|
||||
expect(result.metrics.finalValue).toBeCloseTo(9.92, 10);
|
||||
expect(result.equity.at(-1)!.value).toBeCloseTo(9.92, 10);
|
||||
expect(result.positions.every(position => position.quantity === 0)).toBe(true);
|
||||
expect(result.equity.filter(point => Date.parse(point.date) === end)).toHaveLength(1);
|
||||
expect(new Set(result.equity.map(point => point.date)).size).toBe(result.equity.length);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue