stock-bot/apps/stock/orchestrator/test-portfolio-tracking.ts

109 lines
No EOL
3.8 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 testPortfolioTracking() {
console.log('Testing Portfolio Value Tracking...\n');
// Create minimal service container
const container: IServiceContainer = {
logger: {
info: (msg: string, ...args: any[]) => {
// Filter for portfolio value messages
if (msg.includes('portfolio') || msg.includes('Portfolio') || msg.includes('equity')) {
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[]) => {},
} 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-01-10T00:00:00Z', // Just 10 days
speed: 'max',
symbols: ['TEST'],
initialCapital: 100000,
dataFrequency: '1d',
strategy: 'sma-crossover'
});
// Create backtest engine
const backtestEngine = new BacktestEngine(container, storageService, strategyManager);
// Run backtest
const config = {
mode: 'backtest',
name: 'Portfolio Tracking Test',
strategy: 'sma-crossover',
symbols: ['TEST'],
startDate: '2023-01-01T00:00:00Z',
endDate: '2023-01-10T00: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 equity curve
console.log('\n=== EQUITY CURVE ANALYSIS ===');
console.log(`Initial Capital: $${config.initialCapital.toLocaleString()}`);
console.log(`Equity Points: ${result.equity.length}`);
// Show all equity points
console.log('\nAll equity points:');
result.equity.forEach((point, i) => {
console.log(` ${i + 1}. ${point.date} => $${point.value.toFixed(2)}`);
});
// Check for anomalies
const firstValue = result.equity[0].value;
const lastValue = result.equity[result.equity.length - 1].value;
const totalReturn = ((lastValue - firstValue) / firstValue) * 100;
console.log(`\nFirst Value: $${firstValue.toFixed(2)}`);
console.log(`Last Value: $${lastValue.toFixed(2)}`);
console.log(`Calculated Total Return: ${totalReturn.toFixed(2)}%`);
console.log(`Reported Total Return: ${result.metrics.totalReturn.toFixed(2)}%`);
// Check if values match
if (Math.abs(totalReturn - result.metrics.totalReturn) > 0.01) {
console.log('\n❌ WARNING: Calculated return does not match reported return!');
}
console.log('\n=== TEST COMPLETE ===');
process.exit(0);
}
testPortfolioTracking().catch(error => {
console.error('Test failed:', error);
process.exit(1);
});