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
130
apps/stock/orchestrator/test-full-backtest.ts
Normal file
130
apps/stock/orchestrator/test-full-backtest.ts
Normal file
|
|
@ -0,0 +1,130 @@
|
|||
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 testFullBacktest() {
|
||||
console.log('Testing Full Backtest with Real Data...\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 configuration matching what frontend might send
|
||||
const config = {
|
||||
mode: 'backtest',
|
||||
name: 'Full Test',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: ['AAPL', 'MSFT', 'GOOGL'], // Multiple symbols
|
||||
startDate: '2023-01-01T00:00:00Z',
|
||||
endDate: '2023-12-31T00:00:00Z', // Full year
|
||||
initialCapital: 100000,
|
||||
commission: 0.001,
|
||||
slippage: 0.0001,
|
||||
dataFrequency: '1d',
|
||||
speed: 'max'
|
||||
};
|
||||
|
||||
// Initialize backtest mode
|
||||
await modeManager.initializeMode(config);
|
||||
|
||||
// Create backtest engine
|
||||
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
|
||||
|
||||
console.log('Running full year backtest with multiple symbols...');
|
||||
const startTime = Date.now();
|
||||
|
||||
try {
|
||||
const result = await backtestEngine.runBacktest(config);
|
||||
|
||||
const duration = (Date.now() - startTime) / 1000;
|
||||
console.log(`\nBacktest completed in ${duration.toFixed(2)} seconds`);
|
||||
|
||||
// Check for data anomalies
|
||||
console.log('\n=== RESULT ANALYSIS ===');
|
||||
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(`Win Rate: ${result.metrics.winRate.toFixed(1)}%`);
|
||||
console.log(`Total Trades: ${result.metrics.totalTrades}`);
|
||||
console.log(`Trades Array Length: ${result.trades.length}`);
|
||||
|
||||
// Check equity curve
|
||||
console.log('\n=== EQUITY CURVE CHECK ===');
|
||||
console.log(`Equity Points: ${result.equity.length}`);
|
||||
if (result.equity.length > 0) {
|
||||
const first = result.equity[0];
|
||||
const last = result.equity[result.equity.length - 1];
|
||||
const max = Math.max(...result.equity.map(e => e.value));
|
||||
const min = Math.min(...result.equity.map(e => e.value));
|
||||
|
||||
console.log(`First: $${first.value.toFixed(2)}`);
|
||||
console.log(`Last: $${last.value.toFixed(2)}`);
|
||||
console.log(`Max: $${max.toFixed(2)}`);
|
||||
console.log(`Min: $${min.toFixed(2)}`);
|
||||
|
||||
// Check for exponential growth
|
||||
const growthRatio = last.value / first.value;
|
||||
if (growthRatio > 10) {
|
||||
console.log('\n⚠️ WARNING: Detected possible exponential growth!');
|
||||
console.log(`Growth ratio: ${growthRatio.toFixed(2)}x`);
|
||||
}
|
||||
}
|
||||
|
||||
// Sample some trades
|
||||
console.log('\n=== TRADE SAMPLES ===');
|
||||
if (result.trades.length > 0) {
|
||||
console.log('First 3 trades:');
|
||||
result.trades.slice(0, 3).forEach((t, i) => {
|
||||
console.log(` ${i+1}. ${t.symbol} ${t.side} ${t.quantity} @ ${t.exitPrice.toFixed(2)} | P&L: $${t.pnl.toFixed(2)} (${t.pnlPercent.toFixed(2)}%)`);
|
||||
});
|
||||
|
||||
if (result.trades.length > 3) {
|
||||
console.log('\nLast 3 trades:');
|
||||
result.trades.slice(-3).forEach((t, i) => {
|
||||
console.log(` ${i+1}. ${t.symbol} ${t.side} ${t.quantity} @ ${t.exitPrice.toFixed(2)} | P&L: $${t.pnl.toFixed(2)} (${t.pnlPercent.toFixed(2)}%)`);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Check raw metrics object
|
||||
console.log('\n=== RAW METRICS ===');
|
||||
console.log(JSON.stringify(result.metrics, null, 2));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Backtest failed:', error);
|
||||
}
|
||||
|
||||
console.log('\n=== TEST COMPLETE ===');
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
testFullBacktest().catch(error => {
|
||||
console.error('Test failed:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue