Unify analytics calculations and fail closed on unavailable data
This commit is contained in:
parent
783b619846
commit
ccce401f72
31 changed files with 1978 additions and 1553 deletions
|
|
@ -55,6 +55,7 @@ export class BacktestReport {
|
|||
}
|
||||
const closedTrades = structuredClone(trades);
|
||||
const performance = this.calculatePerformance(closedTrades);
|
||||
const analysis = defined(this.performanceAnalyzer).getAnalysis();
|
||||
const result: BacktestResult = {
|
||||
// Identification
|
||||
backtestId: this.backtestId,
|
||||
|
|
@ -81,13 +82,15 @@ export class BacktestReport {
|
|||
maxDrawdown: performance.maxDrawdown,
|
||||
winRate: performance.winRate,
|
||||
totalTrades: performance.totalTrades,
|
||||
profitFactor: performance.profitFactor || 0,
|
||||
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 || 0,
|
||||
sortinoRatio: performance.sortinoRatio || 0,
|
||||
calmarRatio: performance.calmarRatio,
|
||||
sortinoRatio: performance.sortinoRatio,
|
||||
annualizedReturn: performance.annualizedReturn,
|
||||
cagr: performance.cagr,
|
||||
},
|
||||
|
||||
// Chart data (frontend-ready format)
|
||||
|
|
@ -127,11 +130,26 @@ export class BacktestReport {
|
|||
|
||||
// Additional analytics
|
||||
analytics: {
|
||||
drawdownSeries: this.calculateDrawdown(),
|
||||
dailyReturns: this.calculateDailyReturns(),
|
||||
monthlyReturns: this.calculateMonthlyReturns(),
|
||||
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: this.calculateRiskMetrics(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,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -180,40 +198,6 @@ export class BacktestReport {
|
|||
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<string, number> {
|
||||
const monthlyReturns: Record<string, number> = {};
|
||||
const monthlyEquity = new Map<string, number>();
|
||||
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;
|
||||
|
|
@ -233,84 +217,6 @@ export class BacktestReport {
|
|||
return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0;
|
||||
}
|
||||
|
||||
private calculateRiskMetrics(closedTrades: ClosedTrade[] = []): Record<string, number> {
|
||||
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<string, number>();
|
||||
|
||||
// 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<string, OHLCBar[]> {
|
||||
const grouped: Record<string, OHLCBar[]> = Object.fromEntries(
|
||||
this.config.symbols.map(symbol => [symbol, []])
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { formatStatistic } from '../analytics/performance';
|
||||
import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
|
||||
import type { ClosedTrade } from './native-result';
|
||||
|
||||
|
|
@ -77,7 +78,7 @@ export function generateHTMLReport(result: ReportExport): string {
|
|||
|
||||
<h2>Summary Statistics</h2>
|
||||
<div class="metric">Total Return: <span class="${result.summary.totalReturn >= 0 ? 'positive' : 'negative'}">${result.summary.totalReturn.toFixed(2)}%</span></div>
|
||||
<div class="metric">Sharpe Ratio: ${result.summary.sharpeRatio.toFixed(2)}</div>
|
||||
<div class="metric">Sharpe Ratio: ${formatStatistic(result.summary.sharpeRatio)}</div>
|
||||
<div class="metric">Max Drawdown: <span class="negative">${(result.summary.maxDrawdown * 100).toFixed(2)}%</span></div>
|
||||
<div class="metric">Win Rate: ${result.summary.winRate.toFixed(1)}%</div>
|
||||
<div class="metric">Total Trades: ${result.summary.totalTrades}</div>
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ const analyticsSchema = z.object({
|
|||
drawdownSeries: z.array(z.object({ timestamp: finite, value: finite })).optional(),
|
||||
dailyReturns: z.array(finite).optional(),
|
||||
monthlyReturns: z.record(finite).optional(),
|
||||
riskMetrics: z.record(finite).optional(),
|
||||
riskMetrics: z.record(finite.nullable()).optional(),
|
||||
});
|
||||
/** Validate once before persistence and before publishing a terminal result. */
|
||||
export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
||||
|
|
@ -55,7 +55,7 @@ export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
|||
metrics: z
|
||||
.object({
|
||||
totalReturn: finite,
|
||||
sharpeRatio: finite,
|
||||
sharpeRatio: finite.nullable(),
|
||||
maxDrawdown: finite,
|
||||
winRate: finite,
|
||||
totalTrades: finite,
|
||||
|
|
@ -152,7 +152,7 @@ export function normalizeBacktestResult(
|
|||
metrics.totalTrades = raw.trades.length; // Completed round trips, not individual fills.
|
||||
metrics.profitableTrades = raw.trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||
for (const key of ['annualReturn', 'annualizedReturn', 'cagr']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,17 +30,19 @@ export interface BacktestResult {
|
|||
// Performance metrics
|
||||
metrics: {
|
||||
totalReturn: number;
|
||||
sharpeRatio: number;
|
||||
sharpeRatio: number | null;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
totalTrades: number;
|
||||
profitFactor: number;
|
||||
profitFactor: number | null;
|
||||
profitableTrades: number;
|
||||
avgWin: number;
|
||||
avgLoss: number;
|
||||
expectancy: number;
|
||||
calmarRatio: number;
|
||||
sortinoRatio: number;
|
||||
calmarRatio: number | null;
|
||||
sortinoRatio: number | null;
|
||||
annualizedReturn: number | null;
|
||||
cagr: number | null;
|
||||
};
|
||||
|
||||
// Chart data
|
||||
|
|
@ -79,6 +81,6 @@ export interface BacktestResult {
|
|||
dailyReturns: number[];
|
||||
monthlyReturns: Record<string, number>;
|
||||
exposureTime: number;
|
||||
riskMetrics: Record<string, number>;
|
||||
riskMetrics: Record<string, number | null>;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue