Unify analytics calculations and fail closed on unavailable data

This commit is contained in:
Boki 2026-10-21 19:28:21 -04:00
parent 783b619846
commit ccce401f72
31 changed files with 1978 additions and 1553 deletions

View file

@ -1,115 +1,144 @@
import type { BacktestResult } from '../types/backtest.types';
import { MetricsCard } from './MetricsCard';
interface BacktestMetricsProps {
result: BacktestResult | null;
isLoading: boolean;
}
// Full detailed metrics view - can be used as a separate page/view if needed
export function BacktestMetrics({ result, isLoading }: BacktestMetricsProps) {
if (isLoading) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{[...Array(6)].map((_, i) => (
<div key={i} className="bg-surface-secondary rounded-lg border border-border p-4 h-24 animate-pulse">
<div className="h-4 bg-surface rounded w-1/2 mb-2"></div>
<div className="h-6 bg-surface rounded w-3/4"></div>
</div>
))}
</div>
);
}
if (!result) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
<p className="text-text-secondary">Run a backtest to see performance metrics.</p>
</div>
);
}
const { metrics } = result;
return (
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<MetricsCard
title="Total Return"
value={`${((metrics.totalReturn ?? 0) * 100).toFixed(2)}%`}
trend={(metrics.totalReturn ?? 0) >= 0 ? 'up' : 'down'}
/>
<MetricsCard
title="Sharpe Ratio"
value={(metrics.sharpeRatio ?? 0).toFixed(2)}
trend={(metrics.sharpeRatio ?? 0) > 0 ? 'up' : 'down'}
/>
<MetricsCard
title="Max Drawdown"
value={`${((metrics.maxDrawdown ?? 0) * 100).toFixed(2)}%`}
trend='down'
/>
<MetricsCard
title="Win Rate"
value={`${((metrics.winRate ?? 0) * 100).toFixed(1)}%`}
trend={(metrics.winRate ?? 0) > 0.5 ? 'up' : 'down'}
/>
<MetricsCard
title="Total Trades"
value={(metrics.totalTrades ?? 0).toString()}
/>
<MetricsCard
title="Profit Factor"
value={(metrics.profitFactor ?? 0).toFixed(2)}
trend={(metrics.profitFactor ?? 0) > 1 ? 'up' : 'down'}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h4 className="text-sm font-medium text-text-secondary mb-3">Trade Statistics</h4>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Profitable Trades</span>
<span className="text-text-primary text-sm font-medium">{metrics.profitableTrades ?? 0}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Average Win</span>
<span className="text-success text-sm font-medium">${(metrics.avgWin ?? 0).toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Average Loss</span>
<span className="text-error text-sm font-medium">${Math.abs(metrics.avgLoss ?? 0).toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Expectancy</span>
<span className={`text-sm font-medium ${(metrics.expectancy ?? 0) >= 0 ? 'text-success' : 'text-error'}`}>
${(metrics.expectancy ?? 0).toFixed(2)}
</span>
</div>
</div>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h4 className="text-sm font-medium text-text-secondary mb-3">Risk Metrics</h4>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Calmar Ratio</span>
<span className="text-text-primary text-sm font-medium">{(metrics.calmarRatio ?? 0).toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Sortino Ratio</span>
<span className="text-text-primary text-sm font-medium">{(metrics.sortinoRatio ?? 0).toFixed(2)}</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Exposure Time</span>
<span className="text-text-primary text-sm font-medium">
{result.analytics?.exposureTime ? `${(result.analytics.exposureTime * 100).toFixed(1)}%` : 'N/A'}
</span>
</div>
</div>
</div>
</div>
</div>
);
}
import type { BacktestResult } from '../types/backtest.types';
import { MetricsCard } from './MetricsCard';
interface BacktestMetricsProps {
result: BacktestResult | null;
isLoading: boolean;
}
const ratioLabel = (value: number | null | undefined) =>
typeof value === 'number' && Number.isFinite(value) ? value.toFixed(2) : 'N/A';
// Full detailed metrics view - can be used as a separate page/view if needed
export function BacktestMetrics({ result, isLoading }: BacktestMetricsProps) {
if (isLoading) {
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
{[...Array(6)].map((_, i) => (
<div
key={i}
className="bg-surface-secondary rounded-lg border border-border p-4 h-24 animate-pulse"
>
<div className="h-4 bg-surface rounded w-1/2 mb-2"></div>
<div className="h-6 bg-surface rounded w-3/4"></div>
</div>
))}
</div>
);
}
if (!result) {
return (
<div className="bg-surface-secondary rounded-lg border border-border p-8 text-center">
<p className="text-text-secondary">Run a backtest to see performance metrics.</p>
</div>
);
}
const { metrics } = result;
return (
<div className="space-y-6">
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<MetricsCard
title="Total Return"
value={`${((metrics.totalReturn ?? 0) * 100).toFixed(2)}%`}
trend={(metrics.totalReturn ?? 0) >= 0 ? 'up' : 'down'}
/>
<MetricsCard
title="Sharpe Ratio"
value={ratioLabel(metrics.sharpeRatio)}
trend={
typeof metrics.sharpeRatio !== 'number'
? undefined
: metrics.sharpeRatio > 0
? 'up'
: 'down'
}
/>
<MetricsCard
title="Max Drawdown"
value={`${((metrics.maxDrawdown ?? 0) * 100).toFixed(2)}%`}
trend="down"
/>
<MetricsCard
title="Win Rate"
value={`${((metrics.winRate ?? 0) * 100).toFixed(1)}%`}
trend={(metrics.winRate ?? 0) > 0.5 ? 'up' : 'down'}
/>
<MetricsCard title="Total Trades" value={(metrics.totalTrades ?? 0).toString()} />
<MetricsCard
title="Profit Factor"
value={ratioLabel(metrics.profitFactor)}
trend={
typeof metrics.profitFactor !== 'number'
? undefined
: metrics.profitFactor > 1
? 'up'
: 'down'
}
/>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h4 className="text-sm font-medium text-text-secondary mb-3">Trade Statistics</h4>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Profitable Trades</span>
<span className="text-text-primary text-sm font-medium">
{metrics.profitableTrades ?? 0}
</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Average Win</span>
<span className="text-success text-sm font-medium">
${(metrics.avgWin ?? 0).toFixed(2)}
</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Average Loss</span>
<span className="text-error text-sm font-medium">
${Math.abs(metrics.avgLoss ?? 0).toFixed(2)}
</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Expectancy</span>
<span
className={`text-sm font-medium ${(metrics.expectancy ?? 0) >= 0 ? 'text-success' : 'text-error'}`}
>
${(metrics.expectancy ?? 0).toFixed(2)}
</span>
</div>
</div>
</div>
<div className="bg-surface-secondary rounded-lg border border-border p-4">
<h4 className="text-sm font-medium text-text-secondary mb-3">Risk Metrics</h4>
<div className="space-y-2">
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Calmar Ratio</span>
<span className="text-text-primary text-sm font-medium">
{ratioLabel(metrics.calmarRatio)}
</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Sortino Ratio</span>
<span className="text-text-primary text-sm font-medium">
{ratioLabel(metrics.sortinoRatio)}
</span>
</div>
<div className="flex justify-between">
<span className="text-text-secondary text-sm">Exposure Time</span>
<span className="text-text-primary text-sm font-medium">
{typeof result.analytics?.exposureTime === 'number'
? `${(result.analytics.exposureTime * 100).toFixed(1)}%`
: 'N/A'}
</span>
</div>
</div>
</div>
</div>
</div>
);
}

View file

@ -2,36 +2,36 @@ import type { RunResult } from '../services/backtestApiV2';
interface ExtendedMetrics {
// Core metrics
totalReturn?: number;
sharpeRatio?: number;
maxDrawdown?: number;
winRate?: number;
totalProfit?: number;
profitFactor?: number;
totalTrades?: number;
avgWin?: number;
avgLoss?: number;
expectancy?: number;
sortinoRatio?: number;
calmarRatio?: number;
profitableTrades?: number;
totalReturn?: number | null;
sharpeRatio?: number | null;
maxDrawdown?: number | null;
winRate?: number | null;
totalProfit?: number | null;
profitFactor?: number | null;
totalTrades?: number | null;
avgWin?: number | null;
avgLoss?: number | null;
expectancy?: number | null;
sortinoRatio?: number | null;
calmarRatio?: number | null;
profitableTrades?: number | null;
// Extended metrics from orchestrator
annualizedReturn?: number;
volatility?: number;
avgHoldingPeriod?: number;
maxConsecutiveLosses?: number;
maxConsecutiveWins?: number;
payoffRatio?: number;
largestWin?: number;
largestLoss?: number;
avgWinLoss?: number;
skewness?: number;
kurtosis?: number;
tailRatio?: number;
kellyFraction?: number;
informationRatio?: number;
avgTradesPerDay?: number;
annualizedReturn?: number | null;
volatility?: number | null;
avgHoldingPeriod?: number | null;
maxConsecutiveLosses?: number | null;
maxConsecutiveWins?: number | null;
payoffRatio?: number | null;
largestWin?: number | null;
largestLoss?: number | null;
avgWinLoss?: number | null;
skewness?: number | null;
kurtosis?: number | null;
tailRatio?: number | null;
kellyFraction?: number | null;
informationRatio?: number | null;
avgTradesPerDay?: number | null;
}
interface CompactPerformanceMetricsProps {
@ -58,12 +58,12 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma
// Calculate totalProfit if not provided
const totalProfit =
allMetrics.totalProfit ??
(allMetrics.totalReturn && result.config?.initialCapital
(typeof allMetrics.totalReturn === 'number' && typeof result.config?.initialCapital === 'number'
? allMetrics.totalReturn * result.config.initialCapital
: undefined);
const formatValue = (
value: number | undefined,
value: number | null | undefined,
format: 'percent' | 'number' | 'currency',
decimals = 2
) => {
@ -84,7 +84,7 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma
};
const getColorClass = (
value: number | undefined,
value: number | null | undefined,
thresholds: { good: number; warning?: number }
) => {
if (value === undefined || value === null) {
@ -324,7 +324,7 @@ export function CompactPerformanceMetrics({ result, isLoading }: CompactPerforma
<div className="text-center">
<span className="text-text-secondary">Exposure</span>
<div className="font-medium text-text-primary">
{result.analytics?.exposureTime
{typeof result.analytics?.exposureTime === 'number'
? formatValue(result.analytics.exposureTime, 'percent', 1)
: '-'}
</div>

View file

@ -22,18 +22,18 @@ export interface BacktestConfig {
export interface BacktestMetrics {
totalReturn: number;
sharpeRatio: number;
sharpeRatio: number | null;
maxDrawdown: number;
winRate: number;
totalTrades: number;
profitableTrades: number;
profitFactor?: number;
profitFactor?: number | null;
totalProfit?: number;
avgWin?: number;
avgLoss?: number;
expectancy?: number;
calmarRatio?: number;
sortinoRatio?: number;
calmarRatio?: number | null;
sortinoRatio?: number | null;
}
export interface Position {