diff --git a/README.md b/README.md index 02d5c446..a8739b12 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,34 @@ nothing. History is still retained in memory for the run; this is not a streamin solution. Run `bun run scripts/benchmark-execution.ts` for a local journal-read microbenchmark, not an end-to-end backtest performance estimate. +### TypeScript backtest composition + +`BacktestEngine` coordinates fresh components for each run: + +- `BacktestPlayback` owns the input cursor, pacing and interruptible pause/resume/stop. + Frozen bars are consumed in order without a second event array or queue shifting; + unlimited playback periodically yields so cancellation and lease heartbeats can run. +- `BacktestMarket` owns seeded market projection and per-symbol microstructure defaults. + It cannot submit orders; financial state still belongs to the execution ledger. +- `BacktestReport` records ledger equity and builds a detached completed snapshot. + `report-format.ts` formats that snapshot without re-reading the engine or adding trades. + +Overlapping runs fail before state changes. Cancellation raises `BacktestCancelledError`; +the runner records cancellation without persisting a partial successful result. Pending +historical reads cannot resume a cancelled run, and stop wakes paused/paced playback. +Arbitrary custom strategy callbacks are still cooperative, not forcibly isolated. + +Equity and final position valuations come from `ExecutionService`, not a best-effort native +P&L projection. Missing ledger state fails; zero/negative equity is never replaced with +starting capital. Drawdown duration uses simulated time. Month-end returns use UTC boundaries +and the preceding month-end balance (initial capital for the first month); percentage returns +with a nonpositive baseline are omitted. These corrections can change historical metrics. + +`exportResults()` is available after successful completion until the next run begins. +Repeated JSON/CSV/HTML exports retain the finished equity and trade count; exports cannot +mutate analysis. Charts and quality observations group frozen bars in one pass, but datasets +and detailed equity history still reside in memory; this is not a streaming backtest engine. + ## Backtest data integrity Historical storage no longer invents prices when a database is unavailable. Configure a diff --git a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts index cf83c418..6558e9b6 100644 --- a/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts +++ b/apps/stock/orchestrator/src/analytics/PerformanceAnalyzer.ts @@ -1,7 +1,6 @@ import * as stats from 'simple-statistics'; -import { defined } from '@stock-bot/invariants'; +import { at, defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; -import { at } from '@stock-bot/utils'; const logger = getLogger('PerformanceAnalyzer'); @@ -246,7 +245,12 @@ export class PerformanceAnalyzer { // Calculate max drawdown duration const maxDrawdownDuration = Math.max( ...drawdownPeriods.map(p => p.duration), - currentDrawdownStart ? this.daysBetween(currentDrawdownStart, new Date()) : 0 + currentDrawdownStart + ? this.daysBetween( + currentDrawdownStart, + at(this.equityCurve, this.equityCurve.length - 1).date + ) + : 0 ); return { @@ -662,10 +666,7 @@ export class PerformanceAnalyzer { }; } - exportReport(): string { - const metrics = this.analyze(); - const _drawdowns = this.analyzeDrawdowns(); - + exportReport(metrics: PerformanceMetrics = this.analyze()): string { return ` # Performance Report @@ -674,7 +675,7 @@ export class PerformanceAnalyzer { - Annualized Return: ${metrics.annualizedReturn.toFixed(2)}% - CAGR: ${metrics.cagr.toFixed(2)}% - Volatility: ${metrics.volatility.toFixed(2)}% -- Max Drawdown: ${metrics.maxDrawdown.toFixed(2)}% +- Max Drawdown: ${(metrics.maxDrawdown * 100).toFixed(2)}% - Sharpe Ratio: ${metrics.sharpeRatio.toFixed(2)} - Sortino Ratio: ${metrics.sortinoRatio.toFixed(2)} diff --git a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts index d0b2b0f3..82338da2 100644 --- a/apps/stock/orchestrator/src/backtest/BacktestEngine.ts +++ b/apps/stock/orchestrator/src/backtest/BacktestEngine.ts @@ -1,1003 +1,190 @@ -import { EventEmitter } from 'events'; +import { randomUUID } from 'node:crypto'; +import { EventEmitter } from 'node:events'; import { defined } from '@stock-bot/invariants'; -import { at } from '@stock-bot/utils'; -import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; import { DataManager } from '../data/DataManager'; import { resolveDataset, type DatasetResolver } from '../data/historical-dataset'; -import { StorageService } from '../services/StorageService'; -import type { Signal } from '../strategies/BaseStrategy'; -import { StrategyManager } from '../strategies/StrategyManager'; -import type { OrchestratorServices as IServiceContainer } from '../types'; -import { BacktestConfigSchema, type MarketData, type MarketMicrostructure } from '../types'; +import { amount, decimal } from '../execution/model'; +import type { StorageService } from '../services/StorageService'; +import type { StrategyManager } from '../strategies/StrategyManager'; +import { BacktestConfigSchema, type BacktestConfig, type OrchestratorServices } from '../types'; +import { BacktestMarket } from './BacktestMarket'; +import { BacktestPlayback, type PlaybackProgress } from './BacktestPlayback'; +import { BacktestReport } from './BacktestReport'; import type { BacktestExecutionEngine } from './execution-engine'; -import { MarketSimulator } from './MarketSimulator'; -import { closedTradesSchema, openPositionsSchema, type ClosedTrade } from './native-result'; -import type { BacktestResult, OHLCBar } from './typescript-result'; - -type BacktestEvent = { timestamp: number } & ( - | { type: 'market_data'; data: MarketData } - | { type: 'strategy_signal'; data: Signal } -); -interface ExportResult { - summary: PerformanceMetrics; - trades: ClosedTrade[]; - performanceReport: string; -} +import { closedTradesSchema } from './native-result'; +import type { BacktestResult } from './typescript-result'; export type { BacktestResult } from './typescript-result'; +const speeds = { max: null, realtime: 1, '2x': 2, '5x': 5, '10x': 10 } as const; +/** Composes one run's playback, market projection and report. The runner owns durable lifecycle. */ export class BacktestEngine extends EventEmitter implements BacktestExecutionEngine { - private eventQueue: BacktestEvent[] = []; - private currentTime: number = 0; - private equityCurve: { timestamp: number; value: number }[] = []; - private isRunning = false; - private isPaused = false; - private speedMultiplier: number | null = 1; // null means unlimited speed - private lastProcessTime = 0; - private dataManager: DataManager; - private marketSimulator: MarketSimulator; - private performanceAnalyzer!: PerformanceAnalyzer; - private microstructures: Map = new Map(); - private container: IServiceContainer; - private progressUpdateInterval = 100; // Update progress every 100 events - private totalEvents = 0; - private initialCapital: number = 100000; - private commission: number = 0.001; // Default 0.1% - private slippage: number = 0.0001; // Default 0.01% + private playback?: BacktestPlayback; + private active?: Promise; + private completedReport?: BacktestReport; + private closing = false; constructor( - container: IServiceContainer, - private storageService: StorageService, - private strategyManager: StrategyManager + private readonly container: OrchestratorServices, + private readonly storageService: StorageService, + private readonly strategyManager: StrategyManager ) { super(); - this.container = container; - this.dataManager = new DataManager(storageService); - this.marketSimulator = new MarketSimulator({ - useHistoricalSpreads: true, - modelHiddenLiquidity: true, - includeDarkPools: true, - latencyMs: 1, - }); - // Don't create performance analyzer here - wait for runBacktest - // this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); } - async runBacktest(config: unknown, resolver?: DatasetResolver): Promise { - // Validate config - const validatedConfig = BacktestConfigSchema.parse(config); - - this.container.logger.info( - `Starting backtest from ${validatedConfig.startDate} to ${validatedConfig.endDate}` - ); - - // Reset state - this.reset(); - this.isRunning = true; - this.initialCapital = validatedConfig.initialCapital; - this.commission = validatedConfig.commission ?? 0.001; - this.slippage = validatedConfig.slippage ?? 0.0001; - - // Recreate performance analyzer with correct initial capital - this.performanceAnalyzer = new PerformanceAnalyzer(this.initialCapital); - - // Initialize equity curve with starting capital - this.equityCurve.push({ - timestamp: new Date(validatedConfig.startDate).getTime(), - value: this.initialCapital, - }); - - // Initialize performance analyzer with starting capital - this.performanceAnalyzer.addEquityPoint( - new Date(validatedConfig.startDate), - this.initialCapital - ); - - this.container.logger.info( - `[BacktestEngine] Initial capital set to ${this.initialCapital}, equity curve initialized with ${this.equityCurve.length} points` - ); - - // Backend-local identifier; the application runner supplies the persisted identity. - const backtestId = `backtest_${Date.now()}`; - - // Set speed multiplier from config - if (validatedConfig.speed) { - switch (validatedConfig.speed) { - case 'max': - this.speedMultiplier = null; // Unlimited speed - break; - case 'realtime': - this.speedMultiplier = 1; - break; - case '2x': - this.speedMultiplier = 2; - break; - case '5x': - this.speedMultiplier = 5; - break; - case '10x': - this.speedMultiplier = 10; - break; - default: - this.speedMultiplier = null; // Default to max speed - } - this.container.logger.info( - `[BacktestEngine] Speed set to: ${validatedConfig.speed} (multiplier: ${this.speedMultiplier})` + async runBacktest(input: unknown, resolver?: DatasetResolver): Promise { + if (this.closing || this.active) { + throw new Error( + this.closing ? 'Backtest engine is shutting down' : 'Backtest already running' ); } - + const config = BacktestConfigSchema.parse(input); + const playback = new BacktestPlayback(Date.parse(config.startDate), speeds[config.speed]); + this.playback = playback; + this.completedReport = undefined; + const work = this.execute(config, playback, resolver); + this.active = work; try { - // Both engines execute exactly these frozen, already-normalized bars. - const dataset = await resolveDataset(this.storageService, validatedConfig, resolver); - this.dataManager.inspectDataset(dataset); - this.marketSimulator.resetWithSeed(Number.parseInt(dataset.manifest.hash.slice(0, 8), 16)); - - // Load market microstructure for each symbol - await this.loadMarketMicrostructure(validatedConfig.symbols); - - // Convert to flat array and sort by time - const marketData: MarketData[] = dataset.bars.map(bar => ({ - type: 'bar', - data: bar, - eventId: `${dataset.manifest.hash}:${bar.symbol}:${bar.timestamp}`, - })); - - this.container.logger.info(`Loaded ${marketData.length} market data points`); - - // Initialize strategies - const strategies = validatedConfig.strategies?.map((strategy, index) => ({ - id: `${strategy.name}-${index}`, - name: strategy.name, - enabled: strategy.enabled, - parameters: { ...strategy.config, initialCapital: validatedConfig.initialCapital }, - symbols: validatedConfig.symbols, - allocation: 1 / (validatedConfig.strategies?.length ?? 1), - })) || [ - { - id: `${validatedConfig.strategy}-0`, - name: validatedConfig.strategy, - enabled: true, - parameters: { - symbols: validatedConfig.symbols, - initialCapital: validatedConfig.initialCapital, - ...validatedConfig.config, - // Add any default strategy parameters here - }, - symbols: validatedConfig.symbols, - allocation: 1.0, // Use 100% of capital - }, - ]; - - await this.strategyManager.initializeStrategies(strategies); - this.container.logger.info(`Initialized ${strategies.length} strategies`); - - // Don't setup strategy order listeners - we already listen to StrategyManager - // this.setupStrategyOrderListeners(); - - // Convert market data to events - this.populateEventQueue(marketData); - - // Main backtest loop - await this.processEvents(); - - // Get trade history from Rust core - const tradingEngine = this.strategyManager.getTradingEngine(); - let closedTrades: ClosedTrade[] = []; - let tradeCount = 0; - if (tradingEngine) { - if (tradingEngine.getClosedTrades) { - try { - const tradesJson = tradingEngine.getClosedTrades(); - closedTrades = closedTradesSchema.parse(JSON.parse(tradesJson)); - this.container.logger.info( - `Retrieved ${closedTrades.length} closed trades from Rust core` - ); - } catch (error) { - this.container.logger.warn('Failed to get closed trades from Rust core:', { - value: error, - }); - } - } - if (tradingEngine.getTradeCount) { - try { - tradeCount = tradingEngine.getTradeCount(); - this.container.logger.info(`Total trades executed: ${tradeCount}`); - } catch (error) { - this.container.logger.warn('Failed to get trade count from Rust core:', { - value: error, - }); - } - } - } - - // Calculate final metrics - const performance = this.calculatePerformance(closedTrades); - - // Get final positions - const finalPositions = await this.getFinalPositions(); - - // Create comprehensive frontend-ready result - const result: BacktestResult = { - // Identification - backtestId, - status: 'completed' as const, - completedAt: new Date().toISOString(), - - // Configuration used - config: { - name: validatedConfig.name || 'Backtest', - strategy: validatedConfig.strategy, - symbols: validatedConfig.symbols, - startDate: validatedConfig.startDate, - endDate: validatedConfig.endDate, - initialCapital: validatedConfig.initialCapital, - commission: validatedConfig.commission || 0, - slippage: validatedConfig.slippage || 0, - dataFrequency: validatedConfig.dataFrequency || '1d', - }, - - // Performance metrics (frontend-ready) - metrics: { - totalReturn: performance.totalReturn, - sharpeRatio: performance.sharpeRatio, - maxDrawdown: performance.maxDrawdown, - winRate: performance.winRate, - totalTrades: tradeCount || performance.totalTrades, - profitFactor: performance.profitFactor || 0, - profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100), - avgWin: performance.avgWin || 0, - avgLoss: performance.avgLoss || 0, - expectancy: performance.expectancy || 0, - calmarRatio: performance.calmarRatio || 0, - sortinoRatio: performance.sortinoRatio || 0, - }, - - // Chart data (frontend-ready format) - equity: this.equityCurve - .sort((a, b) => a.timestamp - b.timestamp) - .map(point => ({ - date: new Date(point.timestamp).toISOString(), - value: point.value, - })), - - // OHLC data for charts - ohlcData: this.getOHLCData(marketData, validatedConfig.symbols), - - // Trade history (frontend-ready) - trades: closedTrades.map(trade => ({ - id: trade.id, - symbol: trade.symbol, - entryDate: trade.entry_time, - exitDate: trade.exit_time, - entryPrice: trade.entry_price, - exitPrice: trade.exit_price, - quantity: trade.quantity, - side: trade.side === 'Buy' ? 'buy' : 'sell', - pnl: trade.pnl, - pnlPercent: trade.pnl_percent, - commission: trade.commission, - duration: trade.duration_ms, - })), - - // Final positions - positions: finalPositions.map(pos => ({ - symbol: pos.symbol, - quantity: pos.quantity, - averagePrice: pos.averagePrice, - currentPrice: pos.currentPrice || pos.averagePrice, - unrealizedPnl: pos.unrealizedPnl || 0, - realizedPnl: pos.realizedPnl || 0, - })), - - // Additional analytics - analytics: { - drawdownSeries: this.calculateDrawdown(), - dailyReturns: this.calculateDailyReturns(), - monthlyReturns: this.calculateMonthlyReturns(), - exposureTime: this.calculateExposureTime(closedTrades), - riskMetrics: this.calculateRiskMetrics(closedTrades), - }, - }; - - this.container.logger.info( - `Backtest completed: ${performance.totalTrades} trades, ${performance.totalReturn}% return` - ); - - return result; - } catch (error) { - this.container.logger.error('Backtest failed:', error); - throw error; + return await work; } finally { - this.isRunning = false; - this.reset(); + playback.finish(); + this.active = undefined; } } - private populateEventQueue(marketData: MarketData[]): void { - // Convert market data to events - marketData.forEach(data => { - this.eventQueue.push({ - timestamp: data.data.timestamp, - type: 'market_data', - data, + private async execute( + config: BacktestConfig, + playback: BacktestPlayback, + resolver?: DatasetResolver + ): Promise { + this.container.logger.info('Starting TypeScript backtest', { symbols: config.symbols }); + const dataset = await playback.read(() => + resolveDataset(this.storageService, config, resolver) + ); + playback.assertRunning(); + const dataManager = new DataManager(this.storageService); + dataManager.inspectDataset(dataset); + const strategies = config.strategies?.map((strategy, index) => ({ + id: [strategy.name, index].join('-'), + name: strategy.name, + enabled: strategy.enabled, + parameters: { ...strategy.config, initialCapital: config.initialCapital }, + symbols: config.symbols, + allocation: 1 / (config.strategies?.length ?? 1), + })) ?? [ + { + id: config.strategy + '-0', + name: config.strategy, + enabled: true, + parameters: { + symbols: config.symbols, + initialCapital: config.initialCapital, + ...config.config, + }, + symbols: config.symbols, + allocation: 1, + }, + ]; + await this.strategyManager.initializeStrategies(strategies); + playback.assertRunning(); + const trading = defined( + this.strategyManager.getTradingEngine(), + 'Backtest trading engine is not initialized' + ); + const execution = defined( + this.container.custom?.ExecutionService, + 'Backtest execution ledger is not initialized' + ); + const market = new BacktestMarket(trading, config.symbols, dataset.manifest.hash); + const report = new BacktestReport(config, config.runId ?? randomUUID()); + await playback.process( + dataset.bars, + bar => bar.timestamp, + async bar => { + trading.advanceTime(bar.timestamp); + const data = { + type: 'bar' as const, + data: bar, + eventId: [dataset.manifest.hash, bar.symbol, bar.timestamp].join(':'), + }; + market.process(data); + await this.strategyManager.onMarketData(data); + report.record(bar.timestamp, (await execution.getAccount()).equity); + }, + progress => this.publishProgress(progress) + ); + playback.assertRunning(); + const closedTrades = closedTradesSchema.parse(JSON.parse(trading.getClosedTrades())); + const account = await execution.getAccount(); + playback.assertRunning(); + const positions = Object.values(account.positions) + .filter(position => position.quantity !== 0) + .map(position => { + const quote = account.quotes[position.symbol]; + const currentPrice = quote ? (quote.bid + quote.ask) / 2 : position.averagePrice; + return { + ...position, + currentPrice, + unrealizedPnl: amount( + decimal(currentPrice).minus(position.averagePrice).times(position.quantity) + ), + }; }); - }); - - // Sort by timestamp (should already be sorted) - this.eventQueue.sort((a, b) => a.timestamp - b.timestamp); + const result = report.complete( + dataset, + closedTrades, + positions, + dataManager.getDataQualityReport() + ); + this.completedReport = report; + this.container.logger.info('TypeScript backtest completed', { trades: result.trades.length }); + return result; } - private async processEvents(): Promise { - const tradingEngine = this.strategyManager.getTradingEngine(); - let lastEquityUpdate = 0; - const equityUpdateInterval = 60000; // Update equity every minute - - this.totalEvents = this.eventQueue.length; - this.container.logger.info( - `[BacktestEngine] Processing ${this.totalEvents} events with speed multiplier: ${this.speedMultiplier}` - ); - - let processedCount = 0; - - while (this.eventQueue.length > 0 && this.isRunning) { - // Check if paused - if (this.isPaused) { - await new Promise(resolve => setTimeout(resolve, 100)); - continue; - } - - const event = defined(this.eventQueue.shift()); - processedCount++; - - // Apply speed control if not unlimited - if (this.speedMultiplier !== null && this.speedMultiplier > 0) { - // Base delay in milliseconds for processing each event - // For 1x speed: 1000ms per event (1 event per second) - // For 2x speed: 500ms per event (2 events per second) - // For 10x speed: 100ms per event (10 events per second) - const baseDelay = 1000; // milliseconds - const actualDelay = baseDelay / this.speedMultiplier; - - // Add the delay - if (actualDelay > 1) { - if (processedCount % 50 === 0) { - // Log every 50 events to avoid spam - this.container.logger.debug( - `[BacktestEngine] Applying delay: ${actualDelay}ms (speed: ${this.speedMultiplier}x)` - ); - } - await new Promise(resolve => setTimeout(resolve, actualDelay)); - } - - // Also send progress updates more frequently at slower speeds - if (processedCount % Math.max(1, Math.floor(10 / this.speedMultiplier)) === 0) { - const progress = Math.round((processedCount / this.totalEvents) * 100); - this.sendProgressUpdate(progress, new Date(event.timestamp).toISOString()); - } - } - - this.lastProcessTime = Date.now(); - - // Advance time - this.currentTime = event.timestamp; - if (tradingEngine) { - await tradingEngine.advanceTime(this.currentTime); - } - - // Process event based on type - switch (event.type) { - case 'market_data': - await this.processMarketData(event.data); - break; - - case 'strategy_signal': - await this.processStrategySignal(event.data); - break; - } - - // Update equity curve periodically - if (this.currentTime - lastEquityUpdate > equityUpdateInterval) { - await this.updateEquityCurve(); - lastEquityUpdate = this.currentTime; - } - - // Send progress update via WebSocket (unless already sent in speed control) - if (this.speedMultiplier === null && processedCount % this.progressUpdateInterval === 0) { - const progress = Math.round((processedCount / this.totalEvents) * 100); - this.sendProgressUpdate(progress, new Date(this.currentTime).toISOString()); - - // Also emit local progress event - this.emit('progress', { - processed: processedCount, - total: this.totalEvents, - remaining: this.eventQueue.length, - currentTime: new Date(this.currentTime), - progress, - }); - } - } - - // Final equity update - await this.updateEquityCurve(); - - // Send 100% progress - this.sendProgressUpdate(100, new Date(this.currentTime).toISOString()); - } - - private async processMarketData(data: MarketData): Promise { - this.container.logger.info( - `[BacktestEngine] processMarketData called for ${data.data.symbol} (${data.type})` - ); - const tradingEngine = this.strategyManager.getTradingEngine(); - if (!tradingEngine) { - this.container.logger.warn(`[BacktestEngine] No trading engine available`); - return; - } - - // Process through market simulator for realistic orderbook - const orderbook = this.marketSimulator.processMarketData(data); - - if (orderbook) { - // Update trading engine with simulated orderbook - if (orderbook.bids.length > 0 && orderbook.asks.length > 0) { - tradingEngine.updateQuote( - orderbook.symbol, - at(orderbook.bids, 0).price, - at(orderbook.asks, 0).price, - at(orderbook.bids, 0).size, - at(orderbook.asks, 0).size - ); - } - - // Set microstructure in trading core for realistic fills - const microstructure = this.microstructures.get(orderbook.symbol); - if (microstructure && tradingEngine.setMicrostructure) { - tradingEngine.setMicrostructure(orderbook.symbol, microstructure); - } - } else { - // Fallback to simple processing - switch (data.type) { - case 'quote': - tradingEngine.updateQuote( - data.data.symbol, - data.data.bid, - data.data.ask, - data.data.bidSize, - data.data.askSize - ); - break; - - case 'trade': - tradingEngine.updateTrade( - data.data.symbol, - data.data.price, - data.data.size, - data.data.side - ); - break; - - case 'bar': { - const spread = data.data.high - data.data.low; - const spreadBps = (spread / data.data.close) * 10000; - const halfSpread = (data.data.close * Math.min(spreadBps, 10)) / 20000; - - tradingEngine.updateQuote( - data.data.symbol, - data.data.close - halfSpread, - data.data.close + halfSpread, - data.data.volume / 100, - data.data.volume / 100 - ); - break; - } - } - } - - // Let strategies process the data - this.container.logger.info( - `[BacktestEngine] Forwarding data to strategy manager for ${data.data.symbol}` - ); - await this.strategyManager.onMarketData(data); - - // Track performance - this.performanceAnalyzer.addEquityPoint( - new Date(this.currentTime), - await this.getPortfolioValue() - ); - } - - private async processStrategySignal(_signal: Signal): Promise { - // Strategy signals are handled by strategy manager - // This is here for future extensions - } - - private async updateEquityCurve(): Promise { - const totalEquity = await this.getPortfolioValue(); - - this.container.logger.debug( - `[updateEquityCurve] currentTime=${this.currentTime}, totalEquity=${totalEquity}, initialCapital=${this.initialCapital}` - ); - - // Don't add duplicate points at the same timestamp - const lastPoint = this.equityCurve[this.equityCurve.length - 1]; - if (lastPoint && lastPoint.timestamp === this.currentTime) { - // Update the value instead of adding a duplicate - this.container.logger.debug( - `[updateEquityCurve] Updating existing point at ${this.currentTime}: ${lastPoint.value} -> ${totalEquity}` - ); - lastPoint.value = totalEquity; - } else { - this.container.logger.debug( - `[updateEquityCurve] Adding new point at ${this.currentTime}: ${totalEquity}` - ); - this.equityCurve.push({ - timestamp: this.currentTime, - value: totalEquity, - }); - } - } - - private async getPortfolioValue(): Promise { - const tradingEngine = this.strategyManager.getTradingEngine(); - if (!tradingEngine) { - this.container.logger.debug( - `[getPortfolioValue] No trading engine, returning initialCapital: ${this.initialCapital}` - ); - return this.initialCapital; - } - + private publishProgress(progress: PlaybackProgress): void { try { - // Get current P&L - const [realized = 0, unrealized = 0] = tradingEngine.getTotalPnl(); - const totalValue = this.initialCapital + realized + unrealized; - - this.container.logger.debug( - `[getPortfolioValue] P&L: realized=${realized}, unrealized=${unrealized}, initialCapital=${this.initialCapital}, totalValue=${totalValue}` - ); - - // Ensure we never return 0 or negative values that would cause spikes - // This handles the case where getTotalPnl might not be initialized yet - if (totalValue <= 0 || isNaN(totalValue)) { - this.container.logger.debug( - `[getPortfolioValue] Invalid totalValue, returning initialCapital: ${this.initialCapital}` - ); - return this.initialCapital; - } - - return totalValue; + this.emit('progress', progress); } catch (error) { - // If getTotalPnl fails, return initial capital - this.container.logger.warn('Failed to get total P&L, using initial capital:', { - value: error, - }); - return this.initialCapital; + this.container.logger.error('Backtest progress observer failed', { error }); } } - private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics { - // Use sophisticated performance analyzer - // Add closed trades from Rust core - closedTrades.forEach(trade => { - this.performanceAnalyzer.addTrade({ - entryTime: new Date(trade.entry_time), - exitTime: new Date(trade.exit_time), - symbol: trade.symbol, - side: trade.side === 'Buy' ? 'long' : 'short', - entryPrice: trade.entry_price, - exitPrice: trade.exit_price, - quantity: trade.quantity, - commission: trade.commission || 0, - pnl: trade.pnl || 0, - returnPct: trade.pnl_percent || 0, - holdingPeriod: trade.duration_ms / 60000, // Convert to minutes - mae: 0, // Not tracked yet - mfe: 0, // Not tracked yet - }); - }); - - const metrics = this.performanceAnalyzer.analyze(); - - // Add drawdown analysis - const drawdownAnalysis = this.performanceAnalyzer.analyzeDrawdowns(); - - return { - ...metrics, - maxDrawdown: drawdownAnalysis.maxDrawdown, - maxDrawdownDuration: drawdownAnalysis.maxDrawdownDuration, - }; - } - - private sendProgressUpdate(progress: number, currentDate: string): void { - this.emit('progress', { progress, currentDate }); - } - - private calculateDrawdown(): { timestamp: number; value: number }[] { - const drawdowns: { timestamp: number; value: number }[] = []; - let peak = this.equityCurve[0]?.value || 0; - - for (const point of this.equityCurve) { - if (point.value > peak) { - peak = point.value; - } - const drawdown = ((point.value - peak) / peak) * 100; - drawdowns.push({ - timestamp: point.timestamp, - value: drawdown, - }); - } - - return drawdowns; - } - - private calculateMonthlyReturns(): Record { - const monthlyReturns: Record = {}; - const monthlyEquity = new Map(); - - for (const point of this.equityCurve) { - const date = new Date(point.timestamp); - const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`; - - if (!monthlyEquity.has(monthKey)) { - monthlyEquity.set(monthKey, { start: point.value, end: point.value }); - } else { - const month = defined(monthlyEquity.get(monthKey)); - month.end = point.value; - } - } - - for (const [month, values] of monthlyEquity) { - monthlyReturns[month] = ((values.end - values.start) / values.start) * 100; - } - - return monthlyReturns; - } - - private calculateExposureTime(closedTrades: ClosedTrade[] = []): number { - if (closedTrades.length === 0) { - return 0; - } - - let totalExposureTime = 0; - for (const trade of closedTrades) { - totalExposureTime += trade.duration_ms || 0; - } - - // Use equity curve to determine actual trading period - const startTime = this.equityCurve.length > 0 ? at(this.equityCurve, 0).timestamp : 0; - const endTime = - this.equityCurve.length > 0 ? at(this.equityCurve, this.equityCurve.length - 1).timestamp : 0; - const totalTime = endTime - startTime; - - return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0; - } - - private calculateRiskMetrics(closedTrades: ClosedTrade[] = []): Record { - const returns = this.calculateDailyReturns(); - - // Calculate various risk metrics - const avgReturn = returns.reduce((a, b) => a + b, 0) / Math.max(returns.length, 1); - const variance = - returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / returns.length; - const stdDev = Math.sqrt(variance); - - // Downside deviation (for Sortino) - const downsideReturns = returns.filter(r => r < 0); - const downsideVariance = - downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) / - Math.max(downsideReturns.length, 1); - const downsideDeviation = Math.sqrt(downsideVariance); - - return { - volatility: stdDev * Math.sqrt(252), // Annualized - downsideDeviation: downsideDeviation * Math.sqrt(252), - var95: this.calculateVaR(returns, 0.95), - var99: this.calculateVaR(returns, 0.99), - cvar95: this.calculateCVaR(returns, 0.95), - maxConsecutiveLosses: this.calculateMaxConsecutiveLosses(closedTrades), - }; - } - - private calculateVaR(returns: number[], confidence: number): number { - const sorted = [...returns].sort((a, b) => a - b); - const index = Math.floor((1 - confidence) * sorted.length); - return sorted[index] || 0; - } - - private calculateCVaR(returns: number[], confidence: number): number { - const sorted = [...returns].sort((a, b) => a - b); - const index = Math.floor((1 - confidence) * sorted.length); - const tail = sorted.slice(0, index + 1); - return tail.reduce((a, b) => a + b, 0) / Math.max(tail.length, 1); - } - - private calculateMaxConsecutiveLosses(closedTrades: ClosedTrade[] = []): number { - let maxLosses = 0; - let currentLosses = 0; - - for (const trade of closedTrades) { - if (trade.pnl && trade.pnl < 0) { - currentLosses++; - maxLosses = Math.max(maxLosses, currentLosses); - } else { - currentLosses = 0; - } - } - - return maxLosses; - } - - private calculateDailyReturns(): number[] { - const dailyReturns: number[] = []; - const dailyEquity = new Map(); - - // Group equity by day - for (const point of this.equityCurve) { - const date = new Date(point.timestamp).toISOString().slice(0, 10); - dailyEquity.set(date, point.value); - } - - // Calculate returns - const dates = Array.from(dailyEquity.keys()).sort(); - for (let i = 1; i < dates.length; i++) { - const prevValue = defined(dailyEquity.get(at(dates, i - 1))); - const currValue = defined(dailyEquity.get(at(dates, i))); - const dailyReturn = ((currValue - prevValue) / prevValue) * 100; - dailyReturns.push(dailyReturn); - } - - return dailyReturns; - } - - private async getFinalPositions(): Promise { - const tradingEngine = this.strategyManager.getTradingEngine(); - if (!tradingEngine) { - return []; - } - - const positions = openPositionsSchema.parse(JSON.parse(tradingEngine.getOpenPositions())); - return positions.map(position => ({ - symbol: position.symbol, - quantity: position.quantity, - averagePrice: position.average_price, - currentPrice: position.average_price, - unrealizedPnl: position.unrealized_pnl, - realizedPnl: position.realized_pnl, - })); - } - - private reset(): void { - this.eventQueue = []; - this.currentTime = 0; - this.equityCurve = []; - - this.isPaused = false; - this.speedMultiplier = 1; - this.lastProcessTime = 0; - this.marketSimulator.reset(); - } - - private async loadMarketMicrostructure(symbols: string[]): Promise { - // In real implementation, would load from database - // For now, create reasonable defaults based on symbol characteristics - for (const symbol of symbols) { - const microstructure: MarketMicrostructure = { - symbol, - avgSpreadBps: 3, - dailyVolume: 10_000_000, - avgTradeSize: 100, - volatility: 0.2, - tickSize: 0.01, - lotSize: 1, - intradayVolumeProfile: this.generateIntradayProfile(), - }; - - this.microstructures.set(symbol, microstructure); - this.marketSimulator.setMicrostructure(symbol, microstructure); - } - } - - private generateIntradayProfile(): number[] { - // U-shaped intraday volume pattern - const profile = new Array(24).fill(0); - const tradingHours = [9, 10, 11, 12, 13, 14, 15, 16]; // 9:30 AM to 4:00 PM - - tradingHours.forEach((hour, idx) => { - if (idx === 0 || idx === tradingHours.length - 1) { - // High volume at open and close - profile[hour] = 0.2; - } else if (idx === 1 || idx === tradingHours.length - 2) { - // Moderate volume - profile[hour] = 0.15; - } else { - // Lower midday volume - profile[hour] = 0.1; - } - }); - - // Normalize - const sum = profile.reduce((a, b) => a + b, 0); - return profile.map(v => v / sum); - } - async exportResults(format: 'json' | 'csv' | 'html' = 'json'): Promise { - // Get trades from Rust core - const tradingEngine = this.strategyManager.getTradingEngine(); - let closedTrades: ClosedTrade[] = []; - if (tradingEngine && tradingEngine.getClosedTrades) { - try { - const tradesJson = tradingEngine.getClosedTrades(); - closedTrades = closedTradesSchema.parse(JSON.parse(tradesJson)); - } catch (error) { - this.container.logger.warn('Failed to get closed trades for export:', { value: error }); - } + if (this.active) { + throw new Error('Cannot export an unfinished backtest'); } - - const result = { - summary: this.calculatePerformance(closedTrades), - trades: closedTrades, - equityCurve: this.equityCurve, - drawdowns: this.calculateDrawdown(), - dataQuality: this.dataManager.getDataQualityReport(), - performanceReport: this.performanceAnalyzer.exportReport(), - }; - - switch (format) { - case 'json': - return JSON.stringify(result, null, 2); - case 'csv': - // Convert to CSV format - return this.convertToCSV(result); - case 'html': - // Generate HTML report - return this.generateHTMLReport(result); - default: - return JSON.stringify(result); - } - } - - private convertToCSV(result: ExportResult): string { - // Simple CSV conversion for trades - const headers = ['Date', 'Symbol', 'Side', 'Entry', 'Exit', 'Quantity', 'PnL', 'Return%']; - const rows = result.trades.map(t => [ - new Date(String(t.entry_time)).toISOString(), - t.symbol, - t.side === 'Buy' ? 'buy' : 'sell', - t.entry_price, - t.exit_price, - t.quantity, - t.pnl, - t.pnl_percent, - ]); - - return [headers, ...rows].map(row => row.join(',')).join('\n'); - } - - private generateHTMLReport(result: ExportResult): string { - return ` - - - - Backtest Report - - - -

Backtest Performance Report

- -

Summary Statistics

-
Total Return: ${result.summary.totalReturn.toFixed(2)}%
-
Sharpe Ratio: ${result.summary.sharpeRatio.toFixed(2)}
-
Max Drawdown: ${result.summary.maxDrawdown.toFixed(2)}%
-
Win Rate: ${result.summary.winRate.toFixed(1)}%
-
Total Trades: ${result.summary.totalTrades}
- -

Detailed Performance Metrics

-
${result.performanceReport}
- -

Trade History

- - - - - - - - - - - - ${result.trades - .map( - t => ` - - - - - - - - - - - ` - ) - .join('')} -
DateSymbolSideEntry PriceExit PriceQuantityP&LReturn %
${new Date(t.entry_time).toLocaleDateString()}${t.symbol}${t.side}$${t.entry_price.toFixed(2)}$${t.exit_price.toFixed(2)}${t.quantity}$${t.pnl.toFixed(2)}${t.pnl_percent.toFixed(2)}%
- - - `; - } - - private getOHLCData(marketData: MarketData[], symbols: string[]): Record { - const ohlcData: Record = {}; - - symbols.forEach(symbol => { - const symbolData = marketData - .filter( - (d): d is Extract => - d.type === 'bar' && d.data.symbol === symbol - ) - .map(d => ({ - timestamp: d.data.timestamp, - open: d.data.open, - high: d.data.high, - low: d.data.low, - close: d.data.close, - volume: d.data.volume, - })) - .sort((a, b) => a.timestamp - b.timestamp); // Ensure data is sorted by time - - ohlcData[symbol] = symbolData; - }); - - return ohlcData; - } - - // Playback control methods - async pauseBacktest(): Promise { - this.isPaused = true; - this.container.logger.info('Backtest paused'); - } - - async resumeBacktest(): Promise { - this.isPaused = false; - this.container.logger.info('Backtest resumed'); - } - - async stopBacktest(): Promise { - this.isRunning = false; - this.isPaused = false; - } - - async shutdown(): Promise { - await this.stopBacktest(); - } - - setSpeedMultiplier(speed: number | null): void { - this.speedMultiplier = speed; - this.container.logger.info( - `Backtest speed multiplier set to: ${speed === null ? 'unlimited' : speed}` + return defined(this.completedReport, 'No completed backtest report is available').export( + format ); } - - getStatus(): { isRunning: boolean; isPaused: boolean; progress: number; currentTime: number } { - const progress = - this.totalEvents > 0 - ? Math.round(((this.totalEvents - this.eventQueue.length) / this.totalEvents) * 100) - : 0; - - return { - isRunning: this.isRunning, - isPaused: this.isPaused, - progress, - currentTime: this.currentTime, - }; + async pauseBacktest(): Promise { + this.playback?.pause(); + } + async resumeBacktest(): Promise { + this.playback?.resume(); + } + async stopBacktest(): Promise { + this.playback?.stop(); + } + async shutdown(): Promise { + this.closing = true; + await this.stopBacktest(); + await this.active?.catch(() => {}); + } + setSpeedMultiplier(speed: number | null): void { + if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) { + throw new Error('Backtest speed must be positive or null'); + } + this.playback?.setSpeed(speed); + } + getStatus() { + return ( + this.playback?.getStatus() ?? { + isRunning: false, + isPaused: false, + progress: 0, + currentTime: 0, + } + ); } } diff --git a/apps/stock/orchestrator/src/backtest/BacktestMarket.ts b/apps/stock/orchestrator/src/backtest/BacktestMarket.ts new file mode 100644 index 00000000..9de70280 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/BacktestMarket.ts @@ -0,0 +1,128 @@ +import type { TradingEngine } from '@stock-bot/engine'; +import { at } from '@stock-bot/invariants'; +import type { MarketData, MarketMicrostructure } from '../types'; +import { MarketSimulator } from './MarketSimulator'; + +export type BacktestMarketPort = Pick< + TradingEngine, + 'updateQuote' | 'updateTrade' | 'setMicrostructure' +>; + +/** Market projection only: orders and financial accounting still go through ExecutionService. */ +export class BacktestMarket { + private readonly simulator = new MarketSimulator(); + private readonly microstructures = new Map(); + + constructor( + private readonly engine: BacktestMarketPort, + symbols: string[], + datasetHash: string + ) { + this.simulator.resetWithSeed(Number.parseInt(datasetHash.slice(0, 8), 16)); + this.loadMarketMicrostructure(symbols); + } + + process(data: MarketData): void { + // Process through market simulator for realistic orderbook + const orderbook = this.simulator.processMarketData(data); + + if (orderbook) { + // Update trading engine with simulated orderbook + if (orderbook.bids.length > 0 && orderbook.asks.length > 0) { + this.engine.updateQuote( + orderbook.symbol, + at(orderbook.bids, 0).price, + at(orderbook.asks, 0).price, + at(orderbook.bids, 0).size, + at(orderbook.asks, 0).size + ); + } + + // Set microstructure in trading core for realistic fills + const microstructure = this.microstructures.get(orderbook.symbol); + if (microstructure && this.engine.setMicrostructure) { + this.engine.setMicrostructure(orderbook.symbol, microstructure); + } + } else { + // Fallback to simple processing + switch (data.type) { + case 'quote': + this.engine.updateQuote( + data.data.symbol, + data.data.bid, + data.data.ask, + data.data.bidSize, + data.data.askSize + ); + break; + + case 'trade': + this.engine.updateTrade( + data.data.symbol, + data.data.price, + data.data.size, + data.data.side + ); + break; + + case 'bar': { + const spread = data.data.high - data.data.low; + const spreadBps = (spread / data.data.close) * 10000; + const halfSpread = (data.data.close * Math.min(spreadBps, 10)) / 20000; + + this.engine.updateQuote( + data.data.symbol, + data.data.close - halfSpread, + data.data.close + halfSpread, + data.data.volume / 100, + data.data.volume / 100 + ); + break; + } + } + } + } + + private loadMarketMicrostructure(symbols: string[]): void { + // In real implementation, would load from database + // For now, create reasonable defaults based on symbol characteristics + for (const symbol of symbols) { + const microstructure: MarketMicrostructure = { + symbol, + avgSpreadBps: 3, + dailyVolume: 10_000_000, + avgTradeSize: 100, + volatility: 0.2, + tickSize: 0.01, + lotSize: 1, + intradayVolumeProfile: this.generateIntradayProfile(), + }; + + this.microstructures.set(symbol, microstructure); + this.simulator.setMicrostructure(symbol, microstructure); + } + } + + private generateIntradayProfile(): number[] { + // U-shaped intraday volume pattern + const profile = new Array(24).fill(0); + const tradingHours = [9, 10, 11, 12, 13, 14, 15, 16]; // 9:30 AM to 4:00 PM + + tradingHours.forEach((hour, idx) => { + if (idx === 0 || idx === tradingHours.length - 1) { + // High volume at open and close + profile[hour] = 0.2; + } else if (idx === 1 || idx === tradingHours.length - 2) { + // Moderate volume + profile[hour] = 0.15; + } else { + // Lower midday volume + profile[hour] = 0.1; + } + }); + + // Normalize + const sum = profile.reduce((a, b) => a + b, 0); + return profile.map(v => v / sum); + } +} diff --git a/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts b/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts new file mode 100644 index 00000000..db85f909 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/BacktestPlayback.ts @@ -0,0 +1,177 @@ +import { BacktestCancelledError } from './execution-engine'; + +export interface PlaybackProgress { + processed: number; + total: number; + remaining: number; + currentTime: Date; + currentDate: string; + progress: number; +} + +/** One run's cursor and interruptible controls; independent of trading, storage and reporting. */ +export class BacktestPlayback { + private readonly controller = new AbortController(); + private wake?: () => void; + private running = true; + private paused = false; + private processed = 0; + private total = 0; + private started = false; + + constructor( + private currentTime: number, + private speed: number | null + ) { + this.validateSpeed(speed); + } + + private validateSpeed(speed: number | null): void { + if (speed !== null && (!Number.isFinite(speed) || speed <= 0)) { + throw new Error('Backtest speed must be positive or null'); + } + } + + assertRunning(): void { + if (!this.running) { + throw new BacktestCancelledError(); + } + this.controller.signal.throwIfAborted(); + } + + /** Only race side-effect-free reads; late reads must never resume execution. */ + async read(load: () => Promise): Promise { + this.assertRunning(); + const { signal } = this.controller; + signal.throwIfAborted(); + let rejectAbort!: (reason: unknown) => void; + const aborted = new Promise((_resolve, reject) => { + rejectAbort = reject; + }); + const onAbort = () => rejectAbort(signal.reason); + signal.addEventListener('abort', onAbort, { once: true }); + try { + const work = Promise.resolve().then(() => { + this.assertRunning(); + return load(); + }); + return await Promise.race([work, aborted]); + } finally { + signal.removeEventListener('abort', onAbort); + } + } + + private async wait(ms?: number): Promise { + this.assertRunning(); + await new Promise(resolve => { + let timer: ReturnType | undefined; + const done = () => { + if (timer !== undefined) { + clearTimeout(timer); + } + this.wake = undefined; + resolve(); + }; + this.wake = done; + if (ms !== undefined) { + timer = setTimeout(done, ms); + } + }); + this.assertRunning(); + } + + private async ready(): Promise { + this.assertRunning(); + while (this.paused) { + await this.wait(); + } + } + + async process( + events: readonly T[], + timestamp: (event: T) => number, + consume: (event: T) => Promise, + progress: (value: PlaybackProgress) => void + ): Promise { + this.assertRunning(); + if (this.started) { + throw new Error('Backtest playback has already started'); + } + this.started = true; + this.total = events.length; + // Frozen inputs are already validated and ordered. A cursor avoids copying and shifting history. + for (const event of events) { + await this.ready(); + if (this.speed !== null) { + await this.wait(1000 / this.speed); + } + await this.ready(); + this.currentTime = timestamp(event); + await consume(event); + this.processed++; + this.assertRunning(); + const interval = this.speed === null ? 100 : Math.max(1, Math.floor(10 / this.speed)); + if (this.processed < this.total && this.processed % interval === 0) { + progress(this.progress()); + } + // Let cancellation, lease heartbeats and other accounts run even at unlimited speed. + if (this.speed === null && this.processed % 100 === 0) { + await this.wait(0); + } + } + this.assertRunning(); + progress(this.progress()); + this.assertRunning(); + } + + private progress(): PlaybackProgress { + return { + processed: this.processed, + total: this.total, + remaining: this.total - this.processed, + currentTime: new Date(this.currentTime), + currentDate: new Date(this.currentTime).toISOString(), + progress: + this.total > 0 + ? this.processed === this.total + ? 100 + : Math.min(99, Math.round((this.processed / this.total) * 100)) + : 0, + }; + } + + pause(): void { + if (!this.running) { + return; + } + this.paused = true; + this.wake?.(); + } + resume(): void { + this.paused = false; + this.wake?.(); + } + stop(): void { + this.controller.abort(new BacktestCancelledError()); + this.paused = false; + this.wake?.(); + } + finish(): void { + this.running = false; + this.paused = false; + this.wake?.(); + } + setSpeed(speed: number | null): void { + this.validateSpeed(speed); + this.speed = speed; + this.wake?.(); + } + getStatus() { + return { + isRunning: this.running, + isPaused: this.paused, + progress: this.progress().progress, + currentTime: this.currentTime, + }; + } +} diff --git a/apps/stock/orchestrator/src/backtest/BacktestReport.ts b/apps/stock/orchestrator/src/backtest/BacktestReport.ts new file mode 100644 index 00000000..9283ca41 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/BacktestReport.ts @@ -0,0 +1,324 @@ +import { at, defined } from '@stock-bot/invariants'; +import type { HistoricalDataset } from '@stock-bot/types'; +import { PerformanceAnalyzer, type PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; +import type { BacktestConfig } from '../types'; +import type { ClosedTrade } from './native-result'; +import { formatReport, type ReportExport } from './report-format'; +import type { BacktestResult, OHLCBar } from './typescript-result'; + +/** Run-local observations and a detached completed report; never reads services or financial state. */ +export class BacktestReport { + private readonly equityCurve: { timestamp: number; value: number }[]; + private performanceAnalyzer?: PerformanceAnalyzer; + private snapshot?: ReportExport; + private readonly config: BacktestConfig; + + constructor( + config: BacktestConfig, + private readonly backtestId: string + ) { + this.config = structuredClone(config); + const start = Date.parse(config.startDate); + this.equityCurve = [{ timestamp: start, value: config.initialCapital }]; + this.performanceAnalyzer = new PerformanceAnalyzer(config.initialCapital); + this.performanceAnalyzer.addEquityPoint(new Date(start), config.initialCapital); + } + + record(timestamp: number, equity: number): void { + if (this.snapshot) { + throw new Error('Backtest report is already finalized'); + } + if (!Number.isFinite(timestamp) || !Number.isFinite(equity)) { + throw new Error('Invalid backtest equity observation'); + } + const last = defined(this.equityCurve[this.equityCurve.length - 1]); + if (timestamp < last.timestamp) { + throw new Error('Out-of-order backtest equity observation'); + } + defined(this.performanceAnalyzer).addEquityPoint(new Date(timestamp), equity); + if (last.timestamp === timestamp) { + last.value = equity; + } else { + this.equityCurve.push({ timestamp, value: equity }); + } + } + + complete( + dataset: HistoricalDataset, + trades: ClosedTrade[], + finalPositions: BacktestResult['positions'], + dataQuality: unknown, + completedAt = new Date().toISOString() + ): BacktestResult { + if (this.snapshot) { + throw new Error('Backtest report is already finalized'); + } + const closedTrades = structuredClone(trades); + const performance = this.calculatePerformance(closedTrades); + const result: BacktestResult = { + // Identification + backtestId: this.backtestId, + status: 'completed' as const, + completedAt, + + // Configuration used + config: { + name: this.config.name || 'Backtest', + strategy: this.config.strategy, + symbols: this.config.symbols, + startDate: this.config.startDate, + endDate: this.config.endDate, + initialCapital: this.config.initialCapital, + commission: this.config.commission ?? 0.001, + slippage: this.config.slippage ?? 0.0001, + dataFrequency: this.config.dataFrequency || '1d', + }, + + // Performance metrics (frontend-ready) + metrics: { + totalReturn: performance.totalReturn, + sharpeRatio: performance.sharpeRatio, + maxDrawdown: performance.maxDrawdown, + winRate: performance.winRate, + totalTrades: performance.totalTrades, + profitFactor: performance.profitFactor || 0, + profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100), + avgWin: performance.avgWin || 0, + avgLoss: performance.avgLoss || 0, + expectancy: performance.expectancy || 0, + calmarRatio: performance.calmarRatio || 0, + sortinoRatio: performance.sortinoRatio || 0, + }, + + // Chart data (frontend-ready format) + equity: this.equityCurve.map(point => ({ + date: new Date(point.timestamp).toISOString(), + value: point.value, + })), + + // OHLC data for charts + ohlcData: this.getOHLCData(dataset), + + // Trade history (frontend-ready) + trades: closedTrades.map(trade => ({ + id: trade.id, + symbol: trade.symbol, + entryDate: trade.entry_time, + exitDate: trade.exit_time, + entryPrice: trade.entry_price, + exitPrice: trade.exit_price, + quantity: trade.quantity, + side: trade.side === 'Buy' ? 'buy' : 'sell', + pnl: trade.pnl, + pnlPercent: trade.pnl_percent, + commission: trade.commission, + duration: trade.duration_ms, + })), + + // Final positions + positions: finalPositions.map(pos => ({ + symbol: pos.symbol, + quantity: pos.quantity, + averagePrice: pos.averagePrice, + currentPrice: pos.currentPrice || pos.averagePrice, + unrealizedPnl: pos.unrealizedPnl || 0, + realizedPnl: pos.realizedPnl || 0, + })), + + // Additional analytics + analytics: { + drawdownSeries: this.calculateDrawdown(), + dailyReturns: this.calculateDailyReturns(), + monthlyReturns: this.calculateMonthlyReturns(), + exposureTime: this.calculateExposureTime(closedTrades), + riskMetrics: this.calculateRiskMetrics(closedTrades), + }, + }; + + this.snapshot = structuredClone({ + summary: performance, + trades: closedTrades, + equityCurve: this.equityCurve, + drawdowns: result.analytics.drawdownSeries, + dataQuality, + performanceReport: defined(this.performanceAnalyzer).exportReport(performance), + }); + // The completed snapshot is sufficient for export; do not retain the analysis input twice. + this.equityCurve.length = 0; + this.performanceAnalyzer = undefined; + return structuredClone(result); + } + + export(format: 'json' | 'csv' | 'html' = 'json'): string { + if (!this.snapshot) { + throw new Error('No completed backtest report is available'); + } + return formatReport(this.snapshot, format); + } + + private calculatePerformance(closedTrades: ClosedTrade[] = []): PerformanceMetrics { + const analyzer = defined(this.performanceAnalyzer); + // Import each closed trade once, when the completed snapshot is built. + closedTrades.forEach(trade => { + analyzer.addTrade({ + entryTime: new Date(trade.entry_time), + exitTime: new Date(trade.exit_time), + symbol: trade.symbol, + side: trade.side === 'Buy' ? 'long' : 'short', + entryPrice: trade.entry_price, + exitPrice: trade.exit_price, + quantity: trade.quantity, + commission: trade.commission || 0, + pnl: trade.pnl || 0, + returnPct: trade.pnl_percent || 0, + holdingPeriod: trade.duration_ms / 60000, // Convert to minutes + mae: 0, // Not tracked yet + mfe: 0, // Not tracked yet + }); + }); + + return analyzer.analyze(); + } + + private calculateDrawdown(): { timestamp: number; value: number }[] { + const drawdowns: { timestamp: number; value: number }[] = []; + let peak = this.config.initialCapital; + + for (const point of this.equityCurve) { + if (point.value > peak) { + peak = point.value; + } + const drawdown = ((point.value - peak) / peak) * 100; + drawdowns.push({ + timestamp: point.timestamp, + value: drawdown, + }); + } + + return drawdowns; + } + + private calculateMonthlyReturns(): Record { + const monthlyReturns: Record = {}; + const monthlyEquity = new Map(); + for (const point of this.equityCurve) { + monthlyEquity.set(new Date(point.timestamp).toISOString().slice(0, 7), point.value); + } + let previous = this.config.initialCapital; + for (const [month, value] of monthlyEquity) { + if (previous > 0) { + monthlyReturns[month] = ((value - previous) / previous) * 100; + } + previous = value; + } + return monthlyReturns; + } + + private calculateExposureTime(closedTrades: ClosedTrade[] = []): number { + if (closedTrades.length === 0) { + return 0; + } + + let totalExposureTime = 0; + for (const trade of closedTrades) { + totalExposureTime += trade.duration_ms || 0; + } + + // Use equity curve to determine actual trading period + const startTime = this.equityCurve.length > 0 ? at(this.equityCurve, 0).timestamp : 0; + const endTime = + this.equityCurve.length > 0 ? at(this.equityCurve, this.equityCurve.length - 1).timestamp : 0; + const totalTime = endTime - startTime; + + return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0; + } + + private calculateRiskMetrics(closedTrades: ClosedTrade[] = []): Record { + const returns = this.calculateDailyReturns(); + + // Calculate various risk metrics + const avgReturn = returns.reduce((a, b) => a + b, 0) / Math.max(returns.length, 1); + const variance = + returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / Math.max(returns.length, 1); + const stdDev = Math.sqrt(variance); + + // Downside deviation (for Sortino) + const downsideReturns = returns.filter(r => r < 0); + const downsideVariance = + downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) / + Math.max(downsideReturns.length, 1); + const downsideDeviation = Math.sqrt(downsideVariance); + + return { + volatility: stdDev * Math.sqrt(252), // Annualized + downsideDeviation: downsideDeviation * Math.sqrt(252), + var95: this.calculateVaR(returns, 0.95), + var99: this.calculateVaR(returns, 0.99), + cvar95: this.calculateCVaR(returns, 0.95), + maxConsecutiveLosses: this.calculateMaxConsecutiveLosses(closedTrades), + }; + } + + private calculateVaR(returns: number[], confidence: number): number { + const sorted = [...returns].sort((a, b) => a - b); + const index = Math.floor((1 - confidence) * sorted.length); + return sorted[index] || 0; + } + + private calculateCVaR(returns: number[], confidence: number): number { + const sorted = [...returns].sort((a, b) => a - b); + const index = Math.floor((1 - confidence) * sorted.length); + const tail = sorted.slice(0, index + 1); + return tail.reduce((a, b) => a + b, 0) / Math.max(tail.length, 1); + } + + private calculateMaxConsecutiveLosses(closedTrades: ClosedTrade[] = []): number { + let maxLosses = 0; + let currentLosses = 0; + + for (const trade of closedTrades) { + if (trade.pnl && trade.pnl < 0) { + currentLosses++; + maxLosses = Math.max(maxLosses, currentLosses); + } else { + currentLosses = 0; + } + } + + return maxLosses; + } + + private calculateDailyReturns(): number[] { + const dailyReturns: number[] = []; + const dailyEquity = new Map(); + + // Group equity by day + for (const point of this.equityCurve) { + const date = new Date(point.timestamp).toISOString().slice(0, 10); + dailyEquity.set(date, point.value); + } + + // Calculate returns + const dates = Array.from(dailyEquity.keys()).sort(); + for (let i = 1; i < dates.length; i++) { + const prevValue = defined(dailyEquity.get(at(dates, i - 1))); + const currValue = defined(dailyEquity.get(at(dates, i))); + if (prevValue > 0) { + dailyReturns.push(((currValue - prevValue) / prevValue) * 100); + } + } + + return dailyReturns; + } + + private getOHLCData(dataset: HistoricalDataset): Record { + const grouped: Record = Object.fromEntries( + this.config.symbols.map(symbol => [symbol, []]) + ); + for (const bar of dataset.bars) { + const { timestamp, open, high, low, close, volume } = bar; + defined(grouped[bar.symbol]).push({ timestamp, open, high, low, close, volume }); + } + return grouped; + } +} diff --git a/apps/stock/orchestrator/src/backtest/report-format.ts b/apps/stock/orchestrator/src/backtest/report-format.ts new file mode 100644 index 00000000..3af29760 --- /dev/null +++ b/apps/stock/orchestrator/src/backtest/report-format.ts @@ -0,0 +1,120 @@ +import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer'; +import type { ClosedTrade } from './native-result'; + +export interface ReportExport { + summary: PerformanceMetrics; + trades: ClosedTrade[]; + equityCurve: { timestamp: number; value: number }[]; + drawdowns: { timestamp: number; value: number }[]; + dataQuality: unknown; + performanceReport: string; +} + +export function formatReport(result: ReportExport, format: 'json' | 'csv' | 'html'): string { + switch (format) { + case 'json': + return JSON.stringify(result, null, 2); + case 'csv': + return convertToCSV(result); + case 'html': + return generateHTMLReport(result); + default: + throw new Error(`Unsupported backtest export format: ${format}`); + } +} + +function csvCell(value: string | number): string { + let text = String(value); + // Text is not a spreadsheet formula; numeric losses remain ordinary numbers. + if (typeof value === 'string' && /^[=+\-@\t\r]/.test(text)) { + text = "'" + text; + } + return /[",\r\n]/.test(text) ? '"' + text.replaceAll('"', '""') + '"' : text; +} + +function escapeHTML(value: string): string { + return value.replace( + /[&<>"']/g, + char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char] ?? char + ); +} + +export function convertToCSV(result: ReportExport): string { + // Simple CSV conversion for trades + const headers = ['Date', 'Symbol', 'Side', 'Entry', 'Exit', 'Quantity', 'PnL', 'Return%']; + const rows = result.trades.map(t => [ + new Date(String(t.entry_time)).toISOString(), + t.symbol, + t.side === 'Buy' ? 'buy' : 'sell', + t.entry_price, + t.exit_price, + t.quantity, + t.pnl, + t.pnl_percent, + ]); + + return [headers, ...rows].map(row => row.map(csvCell).join(',')).join('\n'); +} + +export function generateHTMLReport(result: ReportExport): string { + return ` + + + + Backtest Report + + + +

Backtest Performance Report

+ +

Summary Statistics

+
Total Return: ${result.summary.totalReturn.toFixed(2)}%
+
Sharpe Ratio: ${result.summary.sharpeRatio.toFixed(2)}
+
Max Drawdown: ${(result.summary.maxDrawdown * 100).toFixed(2)}%
+
Win Rate: ${result.summary.winRate.toFixed(1)}%
+
Total Trades: ${result.summary.totalTrades}
+ +

Detailed Performance Metrics

+
${escapeHTML(result.performanceReport)}
+ +

Trade History

+ + + + + + + + + + + + ${result.trades + .map( + t => ` + + + + + + + + + + + ` + ) + .join('')} +
DateSymbolSideEntry PriceExit PriceQuantityP&LReturn %
${new Date(t.entry_time).toISOString().slice(0, 10)}${escapeHTML(t.symbol)}${t.side}$${t.entry_price.toFixed(2)}$${t.exit_price.toFixed(2)}${t.quantity}$${t.pnl.toFixed(2)}${t.pnl_percent.toFixed(2)}%
+ + + `; +} diff --git a/apps/stock/orchestrator/src/data/DataManager.ts b/apps/stock/orchestrator/src/data/DataManager.ts index 5ec36982..b6f52203 100644 --- a/apps/stock/orchestrator/src/data/DataManager.ts +++ b/apps/stock/orchestrator/src/data/DataManager.ts @@ -1,9 +1,8 @@ import { EventEmitter } from 'events'; -import { defined } from '@stock-bot/invariants'; +import { at, defined } from '@stock-bot/invariants'; import { getLogger } from '@stock-bot/logger'; import type { HistoricalDataset } from '@stock-bot/types'; -import { at } from '@stock-bot/utils'; -import { StorageService, type HistoricalBar } from '../services/StorageService'; +import type { HistoricalBar, StorageService } from '../services/StorageService'; import { type Bar, type MarketData } from '../types'; const logger = getLogger('DataManager'); @@ -41,7 +40,7 @@ export class DataManager extends EventEmitter { private aggregatedCache: Map> = new Map(); private dataQualityIssues: DataQualityIssue[] = []; - constructor(private storageService: StorageService) { + constructor(private storageService: Pick) { super(); } @@ -90,17 +89,24 @@ export class DataManager extends EventEmitter { /** Observations only: never repair, interpolate, drop, or re-adjust execution inputs. */ inspectDataset(dataset: HistoricalDataset): void { this.clearCache(); + const grouped = new Map(); + for (const bar of dataset.bars) { + let bars = grouped.get(bar.symbol); + if (!bars) { + bars = []; + grouped.set(bar.symbol, bars); + } + bars.push(bar); + } for (const instrument of dataset.manifest.instruments) { - this.recordQualityWarnings( - instrument.id, - dataset.bars - .filter(bar => bar.symbol === instrument.id) - .map(bar => ({ ...bar, timestamp: new Date(bar.timestamp) })) - ); + this.recordQualityWarnings(instrument.id, grouped.get(instrument.id) ?? []); } } - private recordQualityWarnings(symbol: string, bars: HistoricalBar[]): void { + private recordQualityWarnings( + symbol: string, + bars: readonly { timestamp: Date | number; close: number }[] + ): void { bars.forEach((bar, index) => { const previous = bars[index - 1]; if (previous && Math.abs((bar.close - previous.close) / previous.close) > 0.2) { diff --git a/scripts/test/architecture.test.ts b/scripts/test/architecture.test.ts index abd83089..79ce0863 100644 --- a/scripts/test/architecture.test.ts +++ b/scripts/test/architecture.test.ts @@ -98,4 +98,21 @@ describe('orchestrator architecture boundaries', () => { expect(readFileSync(file, 'utf8')).not.toMatch(/switch\s*\(\s*config\.name/); expect(imports.get(join(root, 'strategies/StrategyRegistry.ts'))).toEqual([]); }); + + it('backtest playback cannot depend on trading, data, reporting or service adapters', () => { + const dependencies = [...reachable(join(root, 'backtest/BacktestPlayback.ts'))].map(file => relative(root, file)).sort(); + expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']); + }); + + it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => { + for (const entry of ['backtest/BacktestReport.ts', 'backtest/report-format.ts']) { + for (const file of reachable(join(root, entry))) { + expect(relative(root, file)).not.toMatch(/^(services|strategies|core|data|execution)\//); + expect(relative(root, file)).not.toMatch(/backtest\/(BacktestEngine|BacktestMarket|BacktestRunner|BacktestPlayback)/); + for (const specifier of imports.get(file) ?? []) { + expect(specifier.startsWith('.') || ['simple-statistics', 'zod', '@stock-bot/invariants', '@stock-bot/logger'].includes(specifier)).toBe(true); + } + } + } + }); }); diff --git a/test/integration/backtest-components.test.ts b/test/integration/backtest-components.test.ts new file mode 100644 index 00000000..cc38c1e4 --- /dev/null +++ b/test/integration/backtest-components.test.ts @@ -0,0 +1,404 @@ +import { describe, expect, spyOn, test } from 'bun:test'; +import type { HistoricalDataset } from '@stock-bot/types'; +import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer'; +import { + BacktestPlayback, + type PlaybackProgress, +} from '../../apps/stock/orchestrator/src/backtest/BacktestPlayback'; +import { BacktestReport } from '../../apps/stock/orchestrator/src/backtest/BacktestReport'; +import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; +import type { ClosedTrade } from '../../apps/stock/orchestrator/src/backtest/native-result'; +import { formatReport } from '../../apps/stock/orchestrator/src/backtest/report-format'; +import { DataManager } from '../../apps/stock/orchestrator/src/data/DataManager'; +import { BacktestConfigSchema } from '../../apps/stock/orchestrator/src/types'; + +const day = 86400000; +const start = Date.parse('2024-01-01T00:00:00Z'); +const config = BacktestConfigSchema.parse({ + mode: 'backtest', + strategy: 'sma-crossover', + symbols: ['A.US', 'B.US'], + startDate: new Date(start).toISOString(), + endDate: '2024-03-01T00:00:00Z', + initialCapital: 1000, + dataFrequency: '1d', +}); +const bars = [0, 1, 2].flatMap(index => + config.symbols.map(symbol => ({ + symbol, + timestamp: start + index * day, + open: 100, + high: 101, + low: 99, + close: 100, + volume: 1000, + vwap: 100, + })) +); +const dataset: HistoricalDataset = { + manifest: { + version: 1, + hash: '0'.repeat(64), + instruments: config.symbols.map(id => ({ id, symbol: id.split('.')[0]!, exchange: 'US' })), + startDate: config.startDate, + endDate: config.endDate, + interval: '1d', + policy: { adjustment: 'raw', timestamp: 'utc-session-date' }, + volumePolicy: 'reported', + qualityPolicy: 'reject-invalid-no-interpolation', + sources: config.symbols.map(instrumentId => ({ + instrumentId, + provider: 'synthetic', + revision: 'fixture', + })), + barCount: bars.length, + }, + bars, +}; +const trade: ClosedTrade = { + id: 'closed-1', + symbol: 'A.US', + side: 'Buy', + quantity: 1, + entry_price: 100, + exit_price: 90, + entry_time: new Date(start).toISOString(), + exit_time: new Date(start + day).toISOString(), + pnl: -10, + pnl_percent: -10, + commission: 0, + duration_ms: day, +}; + +function deferred() { + let resolve!: (value: T) => void; + let reject!: (reason: unknown) => void; + const promise = new Promise((done, fail) => { + resolve = done; + reject = fail; + }); + return { promise, resolve, reject }; +} +async function deadline(work: Promise): Promise { + let timer: ReturnType | undefined; + try { + return await Promise.race([ + work, + new Promise((_resolve, reject) => { + timer = setTimeout(() => reject(new Error('Control did not settle promptly')), 500); + }), + ]); + } finally { + clearTimeout(timer); + } +} +const turn = () => new Promise(resolve => setTimeout(resolve, 0)); + +describe('backtest playback isolation and controls', () => { + test('a cursor consumes frozen inputs in order, preserves timestamp ties and yields to timers', async () => { + const playback = new BacktestPlayback(start, null); + const events = Object.freeze( + Array.from({ length: 1001 }, (_, id) => ({ id, timestamp: start + Math.floor(id / 2) })) + ); + const seen: number[] = []; + const updates: PlaybackProgress[] = []; + let timerRan = false; + setTimeout(() => { + timerRan = true; + }, 0); + await playback.process( + events, + event => event.timestamp, + async event => { + seen.push(event.id); + }, + update => updates.push(update) + ); + playback.finish(); + expect(seen).toEqual(events.map(event => event.id)); + expect(timerRan).toBe(true); + expect(events).toHaveLength(1001); + expect(updates.filter(update => update.progress === 100)).toHaveLength(1); + expect(updates.at(-1)).toMatchObject({ + processed: 1001, + total: 1001, + remaining: 0, + progress: 100, + }); + expect(playback.getStatus()).toMatchObject({ + isRunning: false, + isPaused: false, + progress: 100, + }); + }); + + test('pause blocks delivery and resume wakes it without a polling interval', async () => { + const playback = new BacktestPlayback(start, null); + playback.pause(); + let processed = 0; + const work = playback.process( + [start], + time => time, + async () => { + processed++; + }, + () => {} + ); + await turn(); + expect(processed).toBe(0); + playback.resume(); + await deadline(work); + expect(processed).toBe(1); + playback.finish(); + playback.pause(); + expect(playback.getStatus().isPaused).toBe(false); + }); + + test('stop wakes a paused run and never emits completed progress', async () => { + const playback = new BacktestPlayback(start, null); + playback.pause(); + const updates: number[] = []; + const work = playback.process( + [start], + time => time, + async () => { + throw new Error('Must not execute'); + }, + update => updates.push(update.progress) + ); + const outcome = work.catch(error => error); + await turn(); + playback.stop(); + expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError); + expect(updates).toEqual([]); + playback.finish(); + }); + + test.each(['stop', 'setSpeed'] as const)('%s interrupts a long pacing timer', async control => { + const playback = new BacktestPlayback(start, 0.001); + let processed = 0; + const work = playback.process( + [start], + time => time, + async () => { + processed++; + }, + () => {} + ); + const outcome = work.catch(error => error); + await turn(); + if (control === 'stop') playback.stop(); + else playback.setSpeed(null); + const settled = await deadline(outcome); + if (control === 'stop') expect(settled).toBeInstanceOf(BacktestCancelledError); + expect(processed).toBe(control === 'stop' ? 0 : 1); + playback.finish(); + }); + + test('cancellation detaches a slow read and a late rejection cannot resume execution', async () => { + const playback = new BacktestPlayback(start, null); + const load = deferred(); + const entered = deferred(); + const work = playback.read(() => { + entered.resolve(); + return load.promise; + }); + const outcome = work.catch(error => error); + await entered.promise; + playback.stop(); + expect(await deadline(outcome)).toBeInstanceOf(BacktestCancelledError); + load.reject(new Error('Late read failure')); + await turn(); + let calls = 0; + await expect( + playback.read(async () => { + calls++; + return 1; + }) + ).rejects.toBeInstanceOf(BacktestCancelledError); + expect(calls).toBe(0); + playback.finish(); + }); + + test('failed delivery cannot advance its cursor or claim completion', async () => { + const playback = new BacktestPlayback(start, null); + const updates: number[] = []; + await expect( + playback.process( + [1, 2], + time => time, + async time => { + if (time === 2) throw new Error('delivery failure'); + }, + update => updates.push(update.progress) + ) + ).rejects.toThrow('delivery failure'); + expect(playback.getStatus().progress).toBe(50); + expect(updates).not.toContain(100); + playback.finish(); + }); + + test('speed validation rejects non-finite, zero and negative values', () => { + for (const speed of [NaN, Infinity, 0, -1]) { + expect(() => new BacktestPlayback(start, speed)).toThrow('positive or null'); + expect(() => new BacktestPlayback(start, null).setSpeed(speed)).toThrow('positive or null'); + } + }); + + test('one playback cannot run two cursors or continue after finalization', async () => { + const playback = new BacktestPlayback(start, null); + await playback.process( + [start], + time => time, + async () => {}, + () => {} + ); + await expect( + playback.process( + [start], + time => time, + async () => {}, + () => {} + ) + ).rejects.toThrow('already started'); + playback.finish(); + await expect(playback.read(async () => 1)).rejects.toBeInstanceOf(BacktestCancelledError); + }); +}); + +describe('detached, repeatable backtest reporting', () => { + test('analysis runs once per completion and formatting never re-analyzes retained inputs', () => { + const analyze = spyOn(PerformanceAnalyzer.prototype, 'analyze'); + try { + const report = new BacktestReport(config, 'cached'); + report.record(start + day, 990); + report.complete(dataset, [trade], [], {}); + report.export('html'); + report.export('csv'); + report.export('json'); + expect(analyze).toHaveBeenCalledTimes(1); + } finally { + analyze.mockRestore(); + } + }); + test('exports retain completed equity and do not append the same trades repeatedly', () => { + const report = new BacktestReport(config, 'report'); + report.record(start, 1000); + report.record(start + day, 990); + const trades = structuredClone([trade]); + const result = report.complete(dataset, trades, [], { totalIssues: 0 }); + expect(result.metrics.totalTrades).toBe(1); + expect(result.config).toMatchObject({ commission: 0.001, slippage: 0.0001 }); + const first = report.export(); + const parsed = JSON.parse(first); + expect(parsed.summary.totalTrades).toBe(1); + expect(parsed.equityCurve.at(-1).value).toBe(990); + trades[0]!.pnl = 10000; + result.equity[0]!.value = 1; + report.export('csv'); + report.export('html'); + expect(report.export()).toBe(first); + expect(() => report.complete(dataset, [], [], {})).toThrow('already finalized'); + expect(() => report.record(start + day * 2, 0)).toThrow('already finalized'); + }); + + test('zero and negative equity remain losses, never a fabricated starting balance', () => { + const report = new BacktestReport(config, 'loss'); + report.record(start + day, 0); + report.record(start + day * 2, -100); + const result = report.complete(dataset, [], [], {}); + expect(result.equity.map(point => point.value)).toEqual([1000, 0, -100]); + expect(result.metrics.totalReturn).toBeCloseTo(-110); + expect(result.metrics.maxDrawdown).toBe(1.1); + expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110); + expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true); + expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true); + }); + + test('a one-timestamp run has finite analytics, stable timestamp ties and grouped OHLC', () => { + const report = new BacktestReport(config, 'single'); + report.record(start, 999); + report.record(start, 998); + const result = report.complete(dataset, [], [], {}); + expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]); + expect(result.metrics.totalReturn).toBeCloseTo(-0.2); + expect(result.metrics.maxDrawdown).toBeCloseTo(0.002); + expect(result.analytics.dailyReturns).toEqual([]); + expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true); + expect(Object.keys(result.ohlcData)).toEqual(config.symbols); + expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([ + start, + start + day, + start + day * 2, + ]); + expect(result.ohlcData['B.US']).toHaveLength(3); + }); + + test('ongoing drawdown duration uses the simulated horizon, not the wall clock', () => { + const report = new BacktestReport(config, 'drawdown'); + report.record(start + day, 900); + report.record(start + day * 4, 800); + report.complete(dataset, [], [], {}); + expect(JSON.parse(report.export()).summary.maxDrawdownDuration).toBe(3); + expect(report.export('html')).toContain('20.00%'); + expect(JSON.parse(report.export()).performanceReport).toContain('Max Drawdown: 20.00%'); + }); + + test('monthly grouping uses UTC, and invalid or unordered observations fail explicitly', () => { + const report = new BacktestReport(config, 'utc'); + report.record(Date.parse('2024-01-31T23:30:00Z'), 1100); + report.record(Date.parse('2024-02-01T00:30:00Z'), 1200); + const result = report.complete(dataset, [], [], {}); + expect(Object.keys(result.analytics.monthlyReturns)).toEqual(['2024-01', '2024-02']); + expect(result.analytics.monthlyReturns['2024-01']).toBeCloseTo(10); + expect(result.analytics.monthlyReturns['2024-02']).toBeCloseTo((100 / 1100) * 100); + const invalid = new BacktestReport(config, 'invalid'); + expect(() => invalid.export()).toThrow('No completed'); + expect(() => invalid.record(start - 1, 1000)).toThrow('Out-of-order'); + expect(() => invalid.record(start, NaN)).toThrow('Invalid'); + expect(() => invalid.record(Infinity, 1000)).toThrow('Invalid'); + const insolvent = new BacktestReport(config, 'insolvent'); + insolvent.record(start + day, 0); + insolvent.record(Date.parse('2024-02-01T00:30:00Z'), -10); + const losses = insolvent.complete(dataset, [], [], {}); + expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 }); + }); + + test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => { + const input = structuredClone(dataset); + for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) { + bar.close = bar.symbol === 'A.US' ? 150 : 50; + bar.open = bar.close; + bar.high = bar.close + 1; + bar.low = bar.close - 1; + bar.vwap = bar.close; + } + const before = structuredClone(input); + const inspector = new DataManager({ + async getHistoricalBars() { + return []; + }, + }); + inspector.inspectDataset(input); + const quality = inspector.getDataQualityReport(); + expect(quality.totalIssues).toBe(4); + expect(quality.bySymbol).toEqual({ 'A.US': 2, 'B.US': 2 }); + expect(quality.issues.map(issue => issue.symbol)).toEqual(['A.US', 'A.US', 'B.US', 'B.US']); + expect(input).toEqual(before); + inspector.inspectDataset(dataset); + expect(inspector.getDataQualityReport().totalIssues).toBe(0); + }); + + test('HTML escapes text and CSV quotes cells while preserving numeric losses', () => { + const report = new BacktestReport(config, 'escaping'); + report.record(start + day, 990); + report.complete(dataset, [{ ...trade, symbol: '' }], [], {}); + expect(report.export('html')).not.toContain('"'); + expect(report.export('csv')).toContain(',-10,-10'); + const snapshot = JSON.parse(report.export()); + snapshot.trades[0].symbol = '=HYPERLINK("hostile")'; + expect(formatReport(snapshot, 'csv')).toContain('"\'=HYPERLINK(""hostile"")"'); + }); +}); diff --git a/test/integration/backtest-workflow.test.ts b/test/integration/backtest-workflow.test.ts index 999b6e40..ecfef1bd 100644 --- a/test/integration/backtest-workflow.test.ts +++ b/test/integration/backtest-workflow.test.ts @@ -142,6 +142,30 @@ async function fixture( return { postgres, mongodb, storage, engine, repository, runner, services, routes }; } +async function typescriptRuntime(f: Awaited>) { + const di = await new ServiceContainerBuilder() + .withOptions({ + enableCache: false, + enableQueue: false, + enableMongoDB: false, + enablePostgres: false, + enableQuestDB: false, + enableBrowser: false, + enableProxy: false, + }) + .build(); + const services: OrchestratorServices = { + logger, + postgres: f.postgres, + mongodb: f.mongodb, + custom: {}, + }; + di.register({ serviceContainer: asValue(services) }); + await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false }); + expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner); + return services; +} + describe('one backtest execution workflow', () => { test('V2 rejects ambiguous listing IDs and incompatible timestamp policies before accepting work', async () => { const f = await fixture(); @@ -228,26 +252,7 @@ describe('one backtest execution workflow', () => { test('the TypeScript backend uses the same runner, data policy, and persisted contract', async () => { const f = await fixture(); - const di = await new ServiceContainerBuilder() - .withOptions({ - enableCache: false, - enableQueue: false, - enableMongoDB: false, - enablePostgres: false, - enableQuestDB: false, - enableBrowser: false, - enableProxy: false, - }) - .build(); - const services: OrchestratorServices = { - logger, - postgres: f.postgres, - mongodb: f.mongodb, - custom: {}, - }; - di.register({ serviceContainer: asValue(services) }); - await registerOrchestratorServices(di, { initializeMode: false, useRustEngine: false }); - expect(di.resolve('BacktestRunner')).toBe(services.custom?.BacktestRunner); + const services = await typescriptRuntime(f); try { const result = await services.custom!.BacktestRunner!.runBacktest(config); expect(result.engine).toBe('typescript'); @@ -271,6 +276,55 @@ describe('one backtest execution workflow', () => { } }); + test('TypeScript cancellation is persisted without a partial success or completion event', async () => { + const f = await fixture(); + const services = await typescriptRuntime(f); + const runner = services.custom!.BacktestRunner!; + cleanup.unshift(async () => { + await runner.shutdown(); + await services.custom?.ModeManager?.shutdown(); + }); + let stopped: Promise | undefined; + let controlError: unknown; + let completed = 0; + runner.on('complete', () => { + completed++; + }); + const manager = services.custom!.StrategyManager!; + const deliver = manager.onMarketData.bind(manager); + manager.onMarketData = async data => { + await deliver(data); + stopped = runner.stopBacktest(runner.getStatus().runId).catch(error => { + controlError = error; + }); + }; + const outcome = await runner.runBacktest(config).catch(error => error); + expect(stopped).toBeDefined(); + await stopped; + expect(controlError).toBeUndefined(); + expect(outcome).toBeInstanceOf(BacktestCancelledError); + expect(completed).toBe(0); + expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('cancelled'); + expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); + expect(services.custom?.BacktestEngine?.getStatus().isRunning).toBe(false); + }); + + test('TypeScript ledger failures are persisted as failures, never fabricated equity or results', async () => { + const f = await fixture(); + const services = await typescriptRuntime(f); + const runner = services.custom!.BacktestRunner!; + cleanup.unshift(async () => { + await runner.shutdown(); + await services.custom?.ModeManager?.shutdown(); + }); + services.custom!.ExecutionService!.getAccount = async () => { + throw new Error('Ledger unavailable'); + }; + await expect(runner.runBacktest(config)).rejects.toThrow('Ledger unavailable'); + expect((await f.postgres.query('SELECT status FROM runs')).rows[0]?.status).toBe('failed'); + expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(0); + }); + test('V2 dispatch forwards strategy parameters and reads the runner-owned saved result', async () => { const f = await fixture(); const api = new BacktestServiceV2(f.services, async () => { diff --git a/test/integration/typescript-backtest.test.ts b/test/integration/typescript-backtest.test.ts new file mode 100644 index 00000000..520971f5 --- /dev/null +++ b/test/integration/typescript-backtest.test.ts @@ -0,0 +1,189 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { BacktestEngine } from '../../apps/stock/orchestrator/src/backtest/BacktestEngine'; +import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine'; +import { ModeManager } from '../../apps/stock/orchestrator/src/core/ModeManager'; +import { ExecutionService } from '../../apps/stock/orchestrator/src/services/ExecutionService'; +import { MarketDataService } from '../../apps/stock/orchestrator/src/services/MarketDataService'; +import { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService'; +import { StrategyManager } from '../../apps/stock/orchestrator/src/strategies/StrategyManager'; +import { + BacktestConfigSchema, + type OrchestratorServices, +} from '../../apps/stock/orchestrator/src/types'; +import { logger } from '../fixtures/execution'; + +const config = BacktestConfigSchema.parse({ + mode: 'backtest', + strategy: 'sma-crossover', + symbols: ['A.US', 'B.US'], + startDate: '2024-01-01T00:00:00Z', + endDate: '2024-03-15T00:00:00Z', + initialCapital: 10000, + dataFrequency: '1d', + speed: 'max', + commission: 0.001, + slippage: 0, +}); +const cleanup: (() => Promise)[] = []; +afterEach(async () => { + for (const close of cleanup.splice(0).reverse()) await close(); +}); +async function fixture() { + const services: OrchestratorServices = { logger, custom: {} }; + const storage = new StorageService(services, null, null, null, { + allowSyntheticData: true, + syntheticSeed: 42, + }); + const market = new MarketDataService(services); + const execution = new ExecutionService(services, storage); + const manager = new StrategyManager(services); + const mode = new ModeManager(services, market, execution, storage); + const backend = new BacktestEngine(services, storage, manager); + Object.assign(services.custom!, { + StorageService: storage, + ExecutionService: execution, + StrategyManager: manager, + ModeManager: mode, + MarketDataService: market, + }); + await mode.initializeMode(config); + cleanup.push(async () => { + await backend.shutdown(); + await mode.shutdown(); + }); + return { services, storage, execution, manager, mode, backend }; +} +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { + resolve = done; + }); + return { promise, resolve }; +} + +describe('composed TypeScript backtests', () => { + test('completed results and repeatable exports agree with the authoritative ledger', async () => { + const f = await fixture(); + const result = await f.backend.runBacktest(config); + const account = await f.execution.getAccount(); + expect(result.status).toBe('completed'); + expect(result.trades.length).toBeGreaterThan(0); + expect(result.equity.at(-1)?.value).toBe(account.equity); + expect(result.metrics.totalReturn).toBeCloseTo( + ((account.equity - config.initialCapital) / config.initialCapital) * 100 + ); + expect(result.positions.every(position => position.quantity !== 0)).toBe(true); + for (const position of result.positions) { + const quote = account.quotes[position.symbol]!; + expect(position.currentPrice).toBe((quote.bid + quote.ask) / 2); + } + const first = await f.backend.exportResults(); + expect(JSON.parse(first).summary.totalTrades).toBe(result.trades.length); + expect(JSON.parse(first).equityCurve.map((point: { value: number }) => point.value)).toEqual( + result.equity.map(point => point.value) + ); + result.equity[0]!.value = -1; + await f.backend.exportResults('csv'); + await f.backend.exportResults('html'); + expect(await f.backend.exportResults()).toBe(first); + expect(f.backend.getStatus()).toMatchObject({ + isRunning: false, + isPaused: false, + progress: 100, + }); + }); + + test('service reuse does not leak symbols, indicators, equity or exports across runs', async () => { + const f = await fixture(); + const first = await f.backend.runBacktest(config); + const secondConfig = { ...config, symbols: ['C.US'] }; + await f.mode.initializeMode(secondConfig); + const second = await f.backend.runBacktest(secondConfig); + expect(Object.keys(second.ohlcData)).toEqual(['C.US']); + expect(second.trades.every(trade => trade.symbol === 'C.US')).toBe(true); + await f.mode.initializeMode(config); + const repeated = await f.backend.runBacktest(config); + expect(repeated.trades).toEqual(first.trades); + expect(repeated.metrics).toEqual(first.metrics); + expect(repeated.equity).toEqual(first.equity); + }); + + test('overlapping runs fail before they can reset the active read or its controls', async () => { + const f = await fixture(); + const gate = deferred(); + let loads = 0; + const run = f.backend.runBacktest(config, async load => { + loads++; + await gate.promise; + return load(); + }); + const settled = run.catch(error => error); + await expect(f.backend.runBacktest(config)).rejects.toThrow('already running'); + await expect(f.backend.exportResults()).rejects.toThrow('unfinished'); + expect(loads).toBe(1); + await f.backend.stopBacktest(); + expect(await settled).toBeInstanceOf(BacktestCancelledError); + gate.resolve(); + await new Promise(resolve => setTimeout(resolve, 0)); + expect(f.manager.getAllStrategies()).toEqual([]); + await expect(f.backend.exportResults()).rejects.toThrow('No completed'); + expect(f.backend.getStatus()).toMatchObject({ isRunning: false, progress: 0 }); + }); + + test('cancellation at progress never returns a partial completed result or a reusable export', async () => { + const f = await fixture(); + const updates: number[] = []; + f.backend.on('progress', update => { + updates.push(update.progress); + void f.backend.stopBacktest(); + }); + const outcome = await f.backend.runBacktest(config).catch(error => error); + expect(outcome).toBeInstanceOf(BacktestCancelledError); + expect(updates).not.toContain(100); + expect(f.backend.getStatus()).toMatchObject({ isRunning: false, isPaused: false }); + await expect(f.backend.exportResults()).rejects.toThrow('No completed'); + }); + + test('pause gates the next input, and resume produces the same ledger result', async () => { + const f = await fixture(); + const paused = deferred(); + const original = f.manager.onMarketData.bind(f.manager); + let received = 0; + f.manager.onMarketData = async data => { + await original(data); + if (++received === 1) { + await f.backend.pauseBacktest(); + paused.resolve(); + } + }; + const run = f.backend.runBacktest(config); + await paused.promise; + await new Promise(resolve => setTimeout(resolve, 0)); + expect(received).toBe(1); + expect(f.backend.getStatus().isPaused).toBe(true); + await f.backend.resumeBacktest(); + const result = await run; + expect(result.status).toBe('completed'); + expect(result.equity.at(-1)?.value).toBe((await f.execution.getAccount()).equity); + }); + + test('unavailable financial state fails instead of fabricating initial-capital performance', async () => { + const f = await fixture(); + f.execution.getAccount = async () => { + throw new Error('Ledger unavailable'); + }; + await expect(f.backend.runBacktest(config)).rejects.toThrow('Ledger unavailable'); + expect(f.backend.getStatus().isRunning).toBe(false); + await expect(f.backend.exportResults()).rejects.toThrow('No completed'); + }); + + test('observer failures cannot change the result, and shutdown closes future admission', async () => { + const f = await fixture(); + f.backend.on('progress', () => { + throw new Error('observer failed'); + }); + expect((await f.backend.runBacktest(config)).status).toBe('completed'); + await f.backend.shutdown(); + await expect(f.backend.runBacktest(config)).rejects.toThrow('shutting down'); + }); +});