cleanup and fixed initial capital / commision / splippage
This commit is contained in:
parent
70da2c68e5
commit
d14380d740
19 changed files with 1344 additions and 33 deletions
134
apps/stock/orchestrator/test-performance-metrics.ts
Normal file
134
apps/stock/orchestrator/test-performance-metrics.ts
Normal file
|
|
@ -0,0 +1,134 @@
|
|||
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 testPerformanceMetrics() {
|
||||
console.log('Testing Performance Metrics Calculation...\n');
|
||||
|
||||
// Create minimal 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
|
||||
};
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode({
|
||||
mode: 'backtest',
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2023-03-31T00:00:00Z', // 3 months for more trades
|
||||
speed: 'max',
|
||||
symbols: ['AAPL'],
|
||||
initialCapital: 100000,
|
||||
dataFrequency: '1d',
|
||||
strategy: 'sma-crossover'
|
||||
});
|
||||
|
||||
// Create backtest engine
|
||||
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
|
||||
|
||||
// Run backtest
|
||||
const config = {
|
||||
mode: 'backtest',
|
||||
name: 'Performance Metrics Test',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL'],
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2023-03-31T00:00:00Z',
|
||||
initialCapital: 100000,
|
||||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d',
|
||||
speed: 'max'
|
||||
};
|
||||
|
||||
console.log('Running backtest...');
|
||||
const result = await backtestEngine.runBacktest(config);
|
||||
|
||||
// Analyze metrics
|
||||
console.log('\n=== PERFORMANCE METRICS ANALYSIS ===');
|
||||
console.log('\n📊 Returns:');
|
||||
console.log(` Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
|
||||
console.log(` Sharpe Ratio: ${result.metrics.sharpeRatio.toFixed(3)}`);
|
||||
console.log(` Max Drawdown: ${(result.metrics.maxDrawdown * 100).toFixed(2)}%`);
|
||||
|
||||
console.log('\n📈 Trading Statistics:');
|
||||
console.log(` Total Trades: ${result.metrics.totalTrades}`);
|
||||
console.log(` Win Rate: ${result.metrics.winRate.toFixed(2)}%`);
|
||||
console.log(` Profit Factor: ${result.metrics.profitFactor.toFixed(2)}`);
|
||||
console.log(` Average Win: $${result.metrics.avgWin.toFixed(2)}`);
|
||||
console.log(` Average Loss: $${result.metrics.avgLoss.toFixed(2)}`);
|
||||
|
||||
console.log('\n🎯 Trade Details:');
|
||||
console.log(` Closed Trades: ${result.trades.length}`);
|
||||
if (result.trades.length > 0) {
|
||||
const wins = result.trades.filter(t => t.pnl > 0);
|
||||
const losses = result.trades.filter(t => t.pnl < 0);
|
||||
console.log(` Winning Trades: ${wins.length}`);
|
||||
console.log(` Losing Trades: ${losses.length}`);
|
||||
console.log(` Calculated Win Rate: ${(wins.length / result.trades.length * 100).toFixed(2)}%`);
|
||||
|
||||
// Show first few trades
|
||||
console.log('\n First 3 trades:');
|
||||
result.trades.slice(0, 3).forEach((trade, i) => {
|
||||
console.log(` ${i + 1}. ${trade.side} ${trade.quantity} @ ${trade.exitPrice.toFixed(2)} | P&L: $${trade.pnl.toFixed(2)} (${trade.pnlPercent.toFixed(2)}%)`);
|
||||
});
|
||||
}
|
||||
|
||||
console.log('\n💰 Equity Curve:');
|
||||
console.log(` Starting Capital: $${config.initialCapital.toLocaleString()}`);
|
||||
console.log(` Final Value: $${result.equity[result.equity.length - 1].value.toFixed(2)}`);
|
||||
console.log(` Equity Points: ${result.equity.length}`);
|
||||
|
||||
// Show first and last few equity points
|
||||
console.log('\n First 3 equity points:');
|
||||
result.equity.slice(0, 3).forEach((point, i) => {
|
||||
console.log(` ${i + 1}. ${point.date} => $${point.value.toFixed(2)}`);
|
||||
});
|
||||
|
||||
console.log('\n Last 3 equity points:');
|
||||
result.equity.slice(-3).forEach((point, i) => {
|
||||
console.log(` ${i + 1}. ${point.date} => $${point.value.toFixed(2)}`);
|
||||
});
|
||||
|
||||
// Diagnostic checks
|
||||
console.log('\n🔍 Diagnostics:');
|
||||
const sharpeOK = result.metrics.sharpeRatio !== 0;
|
||||
const drawdownOK = result.metrics.maxDrawdown > 0 && result.metrics.maxDrawdown < 0.99;
|
||||
const winRateOK = result.metrics.winRate > 0 && result.metrics.winRate < 100;
|
||||
|
||||
console.log(` ✅ Sharpe Ratio calculated: ${sharpeOK ? 'YES' : 'NO'}`);
|
||||
console.log(` ✅ Max Drawdown reasonable: ${drawdownOK ? 'YES' : 'NO (suspicious value)'}`);
|
||||
console.log(` ✅ Win Rate reasonable: ${winRateOK ? 'YES' : 'NO (check trade P&L)'}`);
|
||||
|
||||
console.log('\n=== TEST COMPLETE ===');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
testPerformanceMetrics().catch(error => {
|
||||
console.error('Test failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue