230 lines
8.2 KiB
TypeScript
230 lines
8.2 KiB
TypeScript
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 analysis = defined(this.performanceAnalyzer).getAnalysis();
|
|
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,
|
|
profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100),
|
|
avgWin: performance.avgWin || 0,
|
|
avgLoss: performance.avgLoss || 0,
|
|
expectancy: performance.expectancy || 0,
|
|
calmarRatio: performance.calmarRatio,
|
|
sortinoRatio: performance.sortinoRatio,
|
|
annualizedReturn: performance.annualizedReturn,
|
|
cagr: performance.cagr,
|
|
},
|
|
|
|
// 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: analysis.equity.underwater.map(point => ({
|
|
...point,
|
|
value: point.value * 100,
|
|
})),
|
|
dailyReturns: analysis.equity.dailyReturns.map(value => value * 100),
|
|
monthlyReturns: Object.fromEntries(
|
|
Object.entries(analysis.equity.monthlyReturns).map(([month, value]) => [
|
|
month,
|
|
value * 100,
|
|
])
|
|
),
|
|
exposureTime: this.calculateExposureTime(closedTrades),
|
|
riskMetrics: {
|
|
volatility: analysis.risk.volatility,
|
|
downsideDeviation: analysis.risk.downsideDeviation,
|
|
var95: analysis.risk.var95,
|
|
var99: analysis.risk.var99,
|
|
cvar95: analysis.risk.cvar95,
|
|
maxConsecutiveLosses: analysis.trade.maxConsecutiveLosses,
|
|
},
|
|
},
|
|
};
|
|
|
|
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 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 getOHLCData(dataset: HistoricalDataset): Record<string, OHLCBar[]> {
|
|
const grouped: Record<string, OHLCBar[]> = 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;
|
|
}
|
|
}
|