123 lines
No EOL
4.9 KiB
TypeScript
123 lines
No EOL
4.9 KiB
TypeScript
import { BacktestEngine } from './src/backtest/BacktestEngine';
|
|
import { StrategyManager } from './src/strategies/StrategyManager';
|
|
import { StorageService } from './src/services/StorageService';
|
|
import { ModeManager } from './src/core/ModeManager';
|
|
import { MarketDataService } from './src/services/MarketDataService';
|
|
import { ExecutionService } from './src/services/ExecutionService';
|
|
import { IServiceContainer } from '@stock-bot/di';
|
|
|
|
async function testCommissionSlippage() {
|
|
console.log('Testing Commission and Slippage...\n');
|
|
|
|
// Create service container
|
|
const container: IServiceContainer = {
|
|
logger: {
|
|
info: (msg: string, ...args: any[]) => console.log('[INFO]', msg, ...args),
|
|
error: (msg: string, ...args: any[]) => console.error('[ERROR]', msg, ...args),
|
|
warn: (msg: string, ...args: any[]) => console.warn('[WARN]', msg, ...args),
|
|
debug: (msg: string, ...args: any[]) => console.log('[DEBUG]', msg, ...args),
|
|
} as any,
|
|
custom: {}
|
|
};
|
|
|
|
// Initialize services
|
|
const storageService = new StorageService();
|
|
const marketDataService = new MarketDataService(container);
|
|
const executionService = new ExecutionService(container);
|
|
const modeManager = new ModeManager(container, marketDataService, executionService, storageService);
|
|
const strategyManager = new StrategyManager(container);
|
|
|
|
// Set services in container
|
|
container.custom = {
|
|
MarketDataService: marketDataService,
|
|
ExecutionService: executionService,
|
|
ModeManager: modeManager,
|
|
StorageService: storageService
|
|
};
|
|
|
|
// Test with high commission and slippage
|
|
const config = {
|
|
mode: 'backtest',
|
|
name: 'Commission Test',
|
|
strategy: 'sma-crossover',
|
|
symbols: ['AAPL'],
|
|
startDate: '2023-01-01T00:00:00Z',
|
|
endDate: '2023-01-31T00:00:00Z',
|
|
initialCapital: 10000,
|
|
commission: 0.01, // 1% commission (very high for testing)
|
|
slippage: 0.005, // 0.5% slippage (very high for testing)
|
|
dataFrequency: '1d',
|
|
speed: 'max'
|
|
};
|
|
|
|
// Initialize backtest mode
|
|
await modeManager.initializeMode(config);
|
|
|
|
// Create backtest engine
|
|
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
|
|
|
|
console.log('Running backtest with:');
|
|
console.log(` Initial Capital: $${config.initialCapital}`);
|
|
console.log(` Commission: ${(config.commission * 100).toFixed(1)}%`);
|
|
console.log(` Slippage: ${(config.slippage * 100).toFixed(1)}%`);
|
|
|
|
try {
|
|
const result = await backtestEngine.runBacktest(config);
|
|
|
|
console.log('\n=== RESULTS ===');
|
|
console.log(`Initial Capital: $${config.initialCapital}`);
|
|
console.log(`Final Value: $${result.equity[result.equity.length - 1].value.toFixed(2)}`);
|
|
console.log(`Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
|
|
console.log(`Total Trades: ${result.metrics.totalTrades}`);
|
|
|
|
// Check trades for commission
|
|
if (result.trades.length > 0) {
|
|
console.log('\nFirst 3 trades with commission:');
|
|
result.trades.slice(0, 3).forEach((t, idx) => {
|
|
const tradeValue = t.quantity * t.entryPrice;
|
|
const expectedCommission = tradeValue * config.commission;
|
|
const totalCost = tradeValue + expectedCommission;
|
|
|
|
console.log(`\n${idx + 1}. ${t.symbol} ${t.side} ${t.quantity} shares`);
|
|
console.log(` Entry Price: $${t.entryPrice.toFixed(2)}`);
|
|
console.log(` Exit Price: $${t.exitPrice.toFixed(2)}`);
|
|
console.log(` Trade Value: $${tradeValue.toFixed(2)}`);
|
|
console.log(` Commission: $${t.commission.toFixed(2)} (expected: $${expectedCommission.toFixed(2)})`);
|
|
console.log(` P&L: $${t.pnl.toFixed(2)}`);
|
|
});
|
|
}
|
|
|
|
// Compare with zero commission/slippage
|
|
const zeroConfig = {
|
|
...config,
|
|
commission: 0,
|
|
slippage: 0
|
|
};
|
|
|
|
await modeManager.initializeMode(zeroConfig);
|
|
const zeroResult = await backtestEngine.runBacktest(zeroConfig);
|
|
|
|
console.log('\n=== COMPARISON ===');
|
|
console.log('With commission/slippage:');
|
|
console.log(` Final Value: $${result.equity[result.equity.length - 1].value.toFixed(2)}`);
|
|
console.log(` Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
|
|
|
|
console.log('\nWithout commission/slippage:');
|
|
console.log(` Final Value: $${zeroResult.equity[zeroResult.equity.length - 1].value.toFixed(2)}`);
|
|
console.log(` Total Return: ${zeroResult.metrics.totalReturn.toFixed(2)}%`);
|
|
|
|
const difference = zeroResult.equity[zeroResult.equity.length - 1].value - result.equity[result.equity.length - 1].value;
|
|
console.log(`\nCost of commission/slippage: $${difference.toFixed(2)}`);
|
|
|
|
} catch (error) {
|
|
console.error('Backtest failed:', error);
|
|
}
|
|
|
|
console.log('\n=== TEST COMPLETE ===');
|
|
process.exit(0);
|
|
}
|
|
|
|
testCommissionSlippage().catch(error => {
|
|
console.error('Test failed:', error);
|
|
process.exit(1);
|
|
}); |