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

2
apps/stock/analytics/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
__pycache__/
*.py[cod]

View file

@ -1,163 +1,72 @@
from fastapi import APIRouter, HTTPException, Query, Depends
from datetime import datetime, date
from typing import List, Optional
import pandas as pd
import numpy as np
from ...analytics.performance import PerformanceAnalyzer
from ...analytics.regime import RegimeDetector
from ..app import get_performance_analyzer, get_regime_detector
router = APIRouter()
@router.get("/performance/{portfolio_id}")
async def get_performance_metrics(
portfolio_id: str,
start_date: datetime = Query(..., description="Start date for analysis"),
end_date: datetime = Query(..., description="End date for analysis"),
analyzer: PerformanceAnalyzer = Depends(get_performance_analyzer)
):
"""
Calculate comprehensive performance metrics for a portfolio
"""
try:
# In real implementation, would fetch data from database
# For now, using mock data
metrics = analyzer.calculate_metrics(
portfolio_id=portfolio_id,
start_date=start_date,
end_date=end_date
)
return metrics
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to calculate performance metrics: {str(e)}")
@router.get("/risk/{portfolio_id}")
async def get_risk_metrics(
portfolio_id: str,
window: int = Query(252, description="Rolling window for risk calculations"),
analyzer: PerformanceAnalyzer = Depends(get_performance_analyzer)
):
"""
Calculate risk metrics including VaR and CVaR
"""
try:
risk_metrics = analyzer.calculate_risk_metrics(
portfolio_id=portfolio_id,
window=window
)
return risk_metrics
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to calculate risk metrics: {str(e)}")
@router.get("/regime")
async def detect_market_regime(
lookback_days: int = Query(60, description="Days to look back for regime detection"),
detector: RegimeDetector = Depends(get_regime_detector)
):
"""
Detect current market regime using various indicators
"""
try:
regime = detector.detect_current_regime(lookback_days=lookback_days)
return {
"regime": regime['regime'],
"confidence": regime['confidence'],
"indicators": regime['indicators'],
"timestamp": datetime.utcnow().isoformat()
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to detect market regime: {str(e)}")
@router.post("/correlation")
async def calculate_correlation_matrix(
symbols: List[str],
start_date: Optional[date] = None,
end_date: Optional[date] = None,
method: str = Query("pearson", pattern="^(pearson|spearman|kendall)$")
):
"""
Calculate correlation matrix for given symbols
"""
try:
# In real implementation, would fetch price data
# For now, return mock correlation matrix
n = len(symbols)
# Generate realistic correlation matrix
np.random.seed(42)
A = np.random.randn(n, n)
correlation_matrix = np.dot(A, A.T)
# Normalize to correlation
D = np.sqrt(np.diag(np.diag(correlation_matrix)))
correlation_matrix = np.linalg.inv(D) @ correlation_matrix @ np.linalg.inv(D)
return {
"symbols": symbols,
"matrix": correlation_matrix.tolist(),
"method": method
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to calculate correlation: {str(e)}")
@router.get("/backtest/{backtest_id}")
async def analyze_backtest_results(
backtest_id: str,
analyzer: PerformanceAnalyzer = Depends(get_performance_analyzer)
):
"""
Analyze results from a completed backtest
"""
try:
analysis = analyzer.analyze_backtest(backtest_id)
return {
"backtest_id": backtest_id,
"metrics": analysis['metrics'],
"statistics": analysis['statistics'],
"risk_analysis": analysis['risk_analysis'],
"trade_analysis": analysis['trade_analysis']
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to analyze backtest: {str(e)}")
@router.post("/attribution")
async def performance_attribution(
portfolio_id: str,
benchmark: str,
start_date: date,
end_date: date,
method: str = Query("brinson", pattern="^(brinson|factor|risk)$")
):
"""
Perform performance attribution analysis
"""
try:
# Placeholder for attribution analysis
return {
"portfolio_id": portfolio_id,
"benchmark": benchmark,
"period": {
"start": start_date.isoformat(),
"end": end_date.isoformat()
},
"method": method,
"attribution": {
"allocation_effect": 0.0023,
"selection_effect": 0.0045,
"interaction_effect": 0.0001,
"total_effect": 0.0069
}
}
except Exception as e:
raise HTTPException(status_code=500, detail=f"Failed to perform attribution: {str(e)}")
"""Observed-data endpoints fail closed until an actual portfolio/history adapter exists.
Optimization and loaded-model prediction use their own caller/model inputs. These routes
must not turn random samples, placeholder attributions or constant reports into observations.
"""
from datetime import date, datetime
from typing import List, NoReturn, Optional
from fastapi import APIRouter, HTTPException, Query
router = APIRouter()
def unavailable() -> NoReturn:
raise HTTPException(
status_code=503,
detail={
"code": "analytics_data_unavailable",
"message": "Observed portfolio, benchmark and backtest data are not integrated",
},
)
@router.get("/performance/{portfolio_id}")
async def get_performance_metrics(
portfolio_id: str,
start_date: datetime = Query(...),
end_date: datetime = Query(...),
):
if end_date <= start_date:
raise HTTPException(status_code=400, detail="end_date must follow start_date")
unavailable()
@router.get("/risk/{portfolio_id}")
async def get_risk_metrics(portfolio_id: str, window: int = Query(252, ge=1)):
unavailable()
@router.get("/regime")
async def detect_market_regime(lookback_days: int = Query(60, ge=1)):
unavailable()
@router.post("/correlation")
async def calculate_correlation_matrix(
symbols: List[str],
start_date: Optional[date] = None,
end_date: Optional[date] = None,
method: str = Query("pearson", pattern="^(pearson|spearman|kendall)$"),
):
if len(symbols) < 2 or len(set(symbols)) != len(symbols):
raise HTTPException(status_code=400, detail="At least two distinct symbols are required")
unavailable()
@router.get("/backtest/{backtest_id}")
async def analyze_backtest_results(backtest_id: str):
unavailable()
@router.post("/attribution")
async def performance_attribution(
portfolio_id: str,
benchmark: str,
start_date: date,
end_date: date,
method: str = Query("brinson", pattern="^(brinson|factor|risk)$"),
):
if end_date <= start_date:
raise HTTPException(status_code=400, detail="end_date must follow start_date")
unavailable()

View file

@ -0,0 +1,55 @@
"""HTTP contract tests for the observed-data routes, without loading research/ML runtimes."""
import importlib.util
from pathlib import Path
import unittest
from fastapi import FastAPI
from fastapi.testclient import TestClient
class ObservedDataEndpoints(unittest.TestCase):
@classmethod
def setUpClass(cls):
source = Path(__file__).parents[1] / "src/api/endpoints/analytics.py"
spec = importlib.util.spec_from_file_location("observed_analytics_endpoints", source)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
app = FastAPI()
app.include_router(module.router, prefix="/analytics")
cls.client = TestClient(app)
@classmethod
def tearDownClass(cls):
cls.client.close()
def test_missing_observed_data_is_unavailable_not_generated_financial_results(self):
requests = [
("GET", "/performance/P?start_date=2024-01-01T00:00:00Z&end_date=2024-02-01T00:00:00Z", None),
("GET", "/risk/P", None),
("GET", "/regime", None),
("POST", "/correlation", ["A.US", "B.US"]),
("GET", "/backtest/run", None),
("POST", "/attribution?portfolio_id=P&benchmark=B&start_date=2024-01-01&end_date=2024-02-01", None),
]
for method, path, body in requests:
with self.subTest(path=path):
response = self.client.request(method, "/analytics" + path, json=body)
self.assertEqual(response.status_code, 503)
self.assertEqual(response.json()["detail"]["code"], "analytics_data_unavailable")
self.assertNotIn("metrics", response.json())
self.assertNotIn("matrix", response.json())
def test_invalid_ranges_and_duplicate_symbols_are_client_errors(self):
response = self.client.get("/analytics/performance/P?start_date=2024-02-01T00:00:00Z&end_date=2024-01-01T00:00:00Z")
self.assertEqual(response.status_code, 400)
response = self.client.post("/analytics/correlation", json=["A.US", "A.US"])
self.assertEqual(response.status_code, 400)
def test_framework_validates_dates_windows_and_request_shapes(self):
self.assertEqual(self.client.get("/analytics/risk/P?window=0").status_code, 422)
self.assertEqual(self.client.get("/analytics/performance/P").status_code, 422)
self.assertEqual(self.client.post("/analytics/correlation", json={"symbols": ["A.US", "B.US"]}).status_code, 422)
if __name__ == "__main__":
unittest.main()

View file

@ -1,8 +1,6 @@
import * as stats from 'simple-statistics';
import { at, defined } from '@stock-bot/invariants';
import { getLogger } from '@stock-bot/logger';
const logger = getLogger('PerformanceAnalyzer');
import { finite, type EquityPoint } from './equity';
import { formatStatistic, performanceAnalysis } from './performance';
import { factorStatistics } from './return-statistics';
export interface Trade {
entryTime: Date;
@ -15,689 +13,156 @@ export interface Trade {
commission: number;
pnl: number;
returnPct: number;
holdingPeriod: number; // in minutes
mae: number; // Maximum Adverse Excursion
mfe: number; // Maximum Favorable Excursion
holdingPeriod: number;
mae: number;
mfe: number;
}
export interface PerformanceMetrics {
// Return metrics
totalReturn: number;
annualizedReturn: number;
cagr: number; // Compound Annual Growth Rate
// Risk metrics
volatility: number;
downVolatility: number;
maxDrawdown: number;
maxDrawdownDuration: number; // days
var95: number; // Value at Risk 95%
cvar95: number; // Conditional VaR 95%
// Risk-adjusted returns
sharpeRatio: number;
sortinoRatio: number;
calmarRatio: number;
informationRatio: number;
// Trade statistics
totalTrades: number;
winRate: number;
avgWin: number;
avgLoss: number;
avgWinLoss: number;
profitFactor: number;
expectancy: number;
payoffRatio: number;
// Trade analysis
avgHoldingPeriod: number;
avgTradesPerDay: number;
maxConsecutiveWins: number;
maxConsecutiveLosses: number;
largestWin: number;
largestLoss: number;
// Statistical measures
skewness: number;
kurtosis: number;
tailRatio: number;
// Kelly criterion
kellyFraction: number;
optimalLeverage: number;
}
type Analysis = ReturnType<typeof performanceAnalysis>;
type CoreMetrics = Analysis['metrics'];
/** Legacy report facade: percentage fields remain percentage points; the pure core uses fractions. */
export type PerformanceMetrics = CoreMetrics;
export type FactorAttribution = ReturnType<typeof factorStatistics>;
export interface DrawdownAnalysis {
maxDrawdown: number;
maxDrawdownDuration: number;
currentDrawdown: number;
drawdownPeriods: Array<{
drawdownPeriods: {
start: Date;
end: Date;
depth: number;
duration: number;
recovery: number;
}>;
underwaterCurve: Array<{ date: Date; drawdown: number }>;
recovery: number | null;
}[];
underwaterCurve: { date: Date; drawdown: number }[];
}
export interface FactorAttribution {
alpha: number;
beta: number;
correlation: number;
treynorRatio: number;
trackingError: number;
upCapture: number;
downCapture: number;
}
const percentageFields = [
'totalReturn',
'annualizedReturn',
'cagr',
'volatility',
'downVolatility',
'var95',
'cvar95',
'winRate',
] as const;
/** Compatibility facade over pure, shared math; observations are detached and cache invalidation is explicit. */
export class PerformanceAnalyzer {
private equityCurve: Array<{ date: Date; value: number }> = [];
private equityCurve: EquityPoint[] = [];
private trades: Trade[] = [];
private dailyReturns: number[] = [];
private benchmarkReturns?: number[];
constructor(private initialCapital: number = 100000) {}
private analysis?: Analysis;
constructor(private readonly initialCapital = 100000) {
if (finite(initialCapital) <= 0) {
throw new Error('Initial capital must be positive');
}
}
addEquityPoint(date: Date, value: number): void {
this.equityCurve.push({ date, value });
// Don't calculate daily returns on every point - wait until analyze() is called
const timestamp = finite(date.getTime());
finite(value);
const last = this.equityCurve[this.equityCurve.length - 1];
if (last && timestamp < last.timestamp) {
throw new Error('Equity observations must be ordered');
}
if (last?.timestamp === timestamp) {
last.value = value;
} else {
this.equityCurve.push({ timestamp, value });
}
this.analysis = undefined;
}
addTrade(trade: Trade): void {
this.trades.push(trade);
finite(trade.pnl);
finite(trade.holdingPeriod);
if (trade.holdingPeriod < 0) {
throw new Error('Holding period must be nonnegative');
}
this.trades.push(structuredClone(trade));
this.analysis = undefined;
}
setBenchmark(returns: number[]): void {
this.benchmarkReturns = returns;
for (const value of returns) {
finite(value);
}
this.benchmarkReturns = [...returns];
this.analysis = undefined;
}
private evaluate(): Analysis {
this.analysis ??= performanceAnalysis(
this.equityCurve,
this.trades,
this.initialCapital,
this.benchmarkReturns
);
return this.analysis;
}
getAnalysis(): Analysis {
return structuredClone(this.evaluate());
}
analyze(): PerformanceMetrics {
if (this.equityCurve.length < 2) {
return this.getEmptyMetrics();
const metrics = { ...this.evaluate().metrics };
for (const field of percentageFields) {
const value = metrics[field];
if (value !== null) {
metrics[field] = finite(value * 100);
}
}
// Calculate daily returns before analysis
this.calculateDailyReturns();
// Calculate returns
const totalReturn = this.calculateTotalReturn();
const annualizedReturn = this.calculateAnnualizedReturn();
const cagr = this.calculateCAGR();
// Risk metrics
const volatility = this.calculateVolatility();
const downVolatility = this.calculateDownsideVolatility();
const drawdownAnalysis = this.analyzeDrawdowns();
const { var95, cvar95 } = this.calculateVaR();
// Risk-adjusted returns
const sharpeRatio = this.calculateSharpeRatio(annualizedReturn, volatility);
const sortinoRatio = this.calculateSortinoRatio(annualizedReturn, downVolatility);
const calmarRatio =
drawdownAnalysis.maxDrawdown > 0
? annualizedReturn / (drawdownAnalysis.maxDrawdown * 100)
: 0;
const informationRatio = this.calculateInformationRatio();
// Trade statistics
const tradeStats = this.analyzeTradeStatistics();
// Statistical measures
const { skewness, kurtosis } = this.calculateDistributionMetrics();
const tailRatio = this.calculateTailRatio();
// Kelly criterion
const { kellyFraction, optimalLeverage } = this.calculateKellyCriterion(tradeStats);
return {
totalReturn,
annualizedReturn,
cagr,
volatility: volatility * 100, // Convert to percentage for display
downVolatility: downVolatility * 100, // Convert to percentage for display
maxDrawdown: drawdownAnalysis.maxDrawdown,
maxDrawdownDuration: drawdownAnalysis.maxDrawdownDuration,
var95,
cvar95,
sharpeRatio,
sortinoRatio,
calmarRatio,
informationRatio,
totalTrades: tradeStats.totalTrades ?? 0,
winRate: tradeStats.winRate ?? 0,
avgWin: tradeStats.avgWin ?? 0,
avgLoss: tradeStats.avgLoss ?? 0,
avgWinLoss: tradeStats.avgWinLoss ?? 0,
profitFactor: tradeStats.profitFactor ?? 0,
expectancy: tradeStats.expectancy ?? 0,
payoffRatio: tradeStats.payoffRatio ?? 0,
avgHoldingPeriod: tradeStats.avgHoldingPeriod ?? 0,
avgTradesPerDay: tradeStats.avgTradesPerDay ?? 0,
maxConsecutiveWins: tradeStats.maxConsecutiveWins ?? 0,
maxConsecutiveLosses: tradeStats.maxConsecutiveLosses ?? 0,
largestWin: tradeStats.largestWin ?? 0,
largestLoss: tradeStats.largestLoss ?? 0,
skewness,
kurtosis,
tailRatio,
kellyFraction,
optimalLeverage,
};
return metrics;
}
analyzeDrawdowns(): DrawdownAnalysis {
const drawdowns: number[] = [];
const underwaterCurve: Array<{ date: Date; drawdown: number }> = [];
// Handle empty equity curve
if (this.equityCurve.length === 0) {
return {
maxDrawdown: 0,
maxDrawdownDuration: 0,
underwaterCurve: [],
drawdownPeriods: [],
currentDrawdown: 0,
};
}
let peak = at(this.equityCurve, 0).value;
let maxDrawdown = 0;
let currentDrawdownStart: Date | null = null;
const drawdownPeriods: DrawdownAnalysis['drawdownPeriods'] = [];
for (let i = 0; i < this.equityCurve.length; i++) {
const point = at(this.equityCurve, i);
if (point.value > peak) {
// New peak - end current drawdown if any
if (currentDrawdownStart) {
const period = {
start: currentDrawdownStart,
end: point.date,
depth: maxDrawdown,
duration: this.daysBetween(currentDrawdownStart, point.date),
recovery: i,
};
drawdownPeriods.push(period);
currentDrawdownStart = null;
}
peak = point.value;
}
const drawdown = (point.value - peak) / peak;
drawdowns.push(drawdown);
underwaterCurve.push({ date: point.date, drawdown });
if (drawdown < 0 && !currentDrawdownStart) {
currentDrawdownStart = point.date;
}
if (drawdown < maxDrawdown) {
maxDrawdown = drawdown;
}
}
// Handle ongoing drawdown
const currentDrawdown = at(drawdowns, drawdowns.length - 1);
// Calculate max drawdown duration
const maxDrawdownDuration = Math.max(
...drawdownPeriods.map(p => p.duration),
currentDrawdownStart
? this.daysBetween(
currentDrawdownStart,
at(this.equityCurve, this.equityCurve.length - 1).date
)
: 0
);
const equity = this.evaluate().equity;
return {
maxDrawdown: Math.abs(maxDrawdown),
maxDrawdownDuration,
currentDrawdown: Math.abs(currentDrawdown),
drawdownPeriods,
underwaterCurve,
maxDrawdown: equity.maxDrawdown,
maxDrawdownDuration: equity.maxDrawdownDuration,
currentDrawdown: equity.currentDrawdown,
drawdownPeriods: equity.periods.map(period => ({
...period,
start: new Date(period.start),
end: new Date(period.end),
})),
underwaterCurve: equity.underwater.map(point => ({
date: new Date(point.timestamp),
drawdown: point.value,
})),
};
}
calculateFactorAttribution(benchmarkReturns: number[]): FactorAttribution {
if (this.dailyReturns.length !== benchmarkReturns.length) {
throw new Error('Returns and benchmark must have same length');
}
// Calculate beta using linear regression
const regression = stats.linearRegression(
this.dailyReturns.map((r, i) => [at(benchmarkReturns, i), r])
);
const beta = regression.m;
const alpha = regression.b * 252; // Annualized
// Correlation
const correlation = stats.sampleCorrelation(this.dailyReturns, benchmarkReturns);
// Treynor ratio
const excessReturn = this.calculateAnnualizedReturn() - 0.02; // Assume 2% risk-free
const treynorRatio = beta !== 0 ? excessReturn / beta : 0;
// Tracking error
const returnDiffs = this.dailyReturns.map((r, i) => r - at(benchmarkReturns, i));
const trackingError = stats.standardDeviation(returnDiffs) * Math.sqrt(252);
// Up/down capture
const upDays = benchmarkReturns
.map((r, i) => (r > 0 ? { bench: r, port: this.dailyReturns[i] } : null))
.filter(d => d !== null) as Array<{ bench: number; port: number }>;
const downDays = benchmarkReturns
.map((r, i) => (r < 0 ? { bench: r, port: this.dailyReturns[i] } : null))
.filter(d => d !== null) as Array<{ bench: number; port: number }>;
const upCapture =
upDays.length > 0
? stats.mean(upDays.map(d => d.port)) / stats.mean(upDays.map(d => d.bench))
: 0;
const downCapture =
downDays.length > 0
? stats.mean(downDays.map(d => d.port)) / stats.mean(downDays.map(d => d.bench))
: 0;
return {
alpha,
beta,
correlation,
treynorRatio,
trackingError,
upCapture,
downCapture,
};
calculateFactorAttribution(benchmark: number[]): FactorAttribution {
return factorStatistics(this.evaluate().equity.dailyReturns, benchmark);
}
private calculateDailyReturns(): void {
this.dailyReturns = [];
// First, aggregate equity curve by day (taking last value of each day)
const dailyEquity = new Map<string, { date: Date; value: number }>();
for (const point of this.equityCurve) {
const dateKey = at(point.date.toISOString().split('T'), 0);
dailyEquity.set(dateKey, point); // This will keep the last value of each day
}
// Convert to sorted array
const dailyPoints = Array.from(dailyEquity.values()).sort(
(a, b) => a.date.getTime() - b.date.getTime()
);
// Calculate returns from daily points
for (let i = 1; i < dailyPoints.length; i++) {
const prevValue = at(dailyPoints, i - 1).value;
const currValue = at(dailyPoints, i).value;
if (prevValue > 0) {
this.dailyReturns.push((currValue - prevValue) / prevValue);
}
}
}
private calculateTotalReturn(): number {
const finalValue = at(this.equityCurve, this.equityCurve.length - 1).value;
return ((finalValue - this.initialCapital) / this.initialCapital) * 100;
}
private calculateAnnualizedReturn(): number {
const totalReturn = this.calculateTotalReturn() / 100;
const years = this.getYears();
return (Math.pow(1 + totalReturn, 1 / years) - 1) * 100;
}
private calculateCAGR(): number {
const finalValue = at(this.equityCurve, this.equityCurve.length - 1).value;
const years = this.getYears();
return (Math.pow(finalValue / this.initialCapital, 1 / years) - 1) * 100;
}
private calculateVolatility(): number {
if (this.dailyReturns.length === 0) {
return 0;
}
// Return volatility as a decimal percentage (not multiplied by 100)
return stats.standardDeviation(this.dailyReturns) * Math.sqrt(252);
}
private calculateDownsideVolatility(): number {
const negativeReturns = this.dailyReturns.filter(r => r < 0);
if (negativeReturns.length === 0) {
return 0;
}
// Return volatility as a decimal percentage (not multiplied by 100)
return stats.standardDeviation(negativeReturns) * Math.sqrt(252);
}
private calculateVaR(): { var95: number; cvar95: number } {
if (this.dailyReturns.length === 0) {
return { var95: 0, cvar95: 0 };
}
const sortedReturns = [...this.dailyReturns].sort((a, b) => a - b);
const index95 = Math.floor(sortedReturns.length * 0.05);
// Handle edge case where we don't have enough data points
if (index95 === 0 || sortedReturns.length < 20) {
return { var95: 0, cvar95: 0 };
}
const var95 = Math.abs(at(sortedReturns, index95)) * 100;
const tailReturns = sortedReturns.slice(0, index95);
const cvar95 = tailReturns.length > 0 ? Math.abs(stats.mean(tailReturns)) * 100 : 0;
return { var95, cvar95 };
}
private calculateSharpeRatio(
annualReturn: number,
volatility: number,
riskFree: number = 2
): number {
if (volatility === 0) {
return 0;
}
// Both annualReturn and volatility should be in percentage form
const volatilityPct = volatility * 100;
return (annualReturn - riskFree) / volatilityPct;
}
private calculateSortinoRatio(
annualReturn: number,
downVolatility: number,
riskFree: number = 2
): number {
if (downVolatility === 0) {
return 0;
}
// Both annualReturn and downVolatility should be in percentage form
const downVolatilityPct = downVolatility * 100;
return (annualReturn - riskFree) / downVolatilityPct;
}
private calculateInformationRatio(): number {
if (!this.benchmarkReturns || this.benchmarkReturns.length !== this.dailyReturns.length) {
return 0;
}
const excessReturns = this.dailyReturns.map(
(r, i) => r - at(defined(this.benchmarkReturns), i)
);
const trackingError = stats.standardDeviation(excessReturns);
if (trackingError === 0) {
return 0;
}
const avgExcessReturn = stats.mean(excessReturns);
return (avgExcessReturn * 252) / (trackingError * Math.sqrt(252));
}
private analyzeTradeStatistics(): Partial<PerformanceMetrics> {
if (this.trades.length === 0) {
return {
totalTrades: 0,
winRate: 0,
avgWin: 0,
avgLoss: 0,
avgWinLoss: 0,
profitFactor: 0,
expectancy: 0,
payoffRatio: 0,
avgHoldingPeriod: 0,
avgTradesPerDay: 0,
maxConsecutiveWins: 0,
maxConsecutiveLosses: 0,
largestWin: 0,
largestLoss: 0,
};
}
// Filter out trades with 0 or undefined P&L
const validTrades = this.trades.filter(t => t.pnl !== undefined && t.pnl !== null);
const wins = validTrades.filter(t => t.pnl > 0);
const losses = validTrades.filter(t => t.pnl < 0);
// Log trade analysis for debugging
logger.debug(
`Trade Analysis: Total=${this.trades.length}, Valid=${validTrades.length}, Wins=${wins.length}, Losses=${losses.length}`
);
const totalWins = wins.reduce((sum, t) => sum + t.pnl, 0);
const totalLosses = Math.abs(losses.reduce((sum, t) => sum + t.pnl, 0));
const avgWin = wins.length > 0 ? totalWins / wins.length : 0;
const avgLoss = losses.length > 0 ? totalLosses / losses.length : 0;
const winRate = validTrades.length > 0 ? (wins.length / validTrades.length) * 100 : 0;
const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0;
const expectancy = (winRate / 100) * avgWin - ((100 - winRate) / 100) * avgLoss;
const payoffRatio = avgLoss > 0 ? avgWin / avgLoss : 0;
// Holding period analysis
const holdingPeriods = this.trades.map(t => t.holdingPeriod);
const avgHoldingPeriod = stats.mean(holdingPeriods);
// Trades per day
const tradingDays = this.getTradingDays();
const avgTradesPerDay = tradingDays > 0 ? this.trades.length / tradingDays : 0;
// Consecutive wins/losses
const { maxConsecutiveWins, maxConsecutiveLosses } = this.calculateConsecutiveStats();
// Largest win/loss
const largestWin = Math.max(...this.trades.map(t => t.pnl), 0);
const largestLoss = Math.abs(Math.min(...this.trades.map(t => t.pnl), 0));
return {
totalTrades: this.trades.length,
winRate,
avgWin,
avgLoss,
avgWinLoss: avgWin - avgLoss,
profitFactor,
expectancy,
payoffRatio,
avgHoldingPeriod,
avgTradesPerDay,
maxConsecutiveWins,
maxConsecutiveLosses,
largestWin,
largestLoss,
};
}
private calculateDistributionMetrics(): { skewness: number; kurtosis: number } {
if (this.dailyReturns.length < 4) {
return { skewness: 0, kurtosis: 0 };
}
const mean = stats.mean(this.dailyReturns);
const std = stats.standardDeviation(this.dailyReturns);
if (std === 0) {
return { skewness: 0, kurtosis: 0 };
}
const n = this.dailyReturns.length;
// Skewness
const skewSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 3), 0);
const skewness = (n / ((n - 1) * (n - 2))) * skewSum;
// Kurtosis
const kurtSum = this.dailyReturns.reduce((sum, r) => sum + Math.pow((r - mean) / std, 4), 0);
const kurtosis =
((n * (n + 1)) / ((n - 1) * (n - 2) * (n - 3))) * kurtSum -
(3 * (n - 1) * (n - 1)) / ((n - 2) * (n - 3));
return { skewness, kurtosis };
}
private calculateTailRatio(): number {
if (this.dailyReturns.length < 20) {
return 0;
}
const sorted = [...this.dailyReturns].sort((a, b) => b - a);
const percentile95 = at(sorted, Math.floor(sorted.length * 0.05));
const percentile5 = at(sorted, Math.floor(sorted.length * 0.95));
return Math.abs(percentile5) > 0 ? percentile95 / Math.abs(percentile5) : 0;
}
private calculateKellyCriterion(tradeStats: Partial<PerformanceMetrics>): {
kellyFraction: number;
optimalLeverage: number;
} {
const winRate = (tradeStats.winRate || 0) / 100;
const payoffRatio = tradeStats.payoffRatio || 0;
if (payoffRatio === 0) {
return { kellyFraction: 0, optimalLeverage: 1 };
}
// Kelly formula: f = p - q/b
// where p = win probability, q = loss probability, b = payoff ratio
const kellyFraction = winRate - (1 - winRate) / payoffRatio;
// Conservative Kelly (25% of full Kelly)
const conservativeKelly = Math.max(0, Math.min(0.25, kellyFraction * 0.25));
// Optimal leverage based on Sharpe ratio
const sharpe = this.calculateSharpeRatio(
this.calculateAnnualizedReturn(),
this.calculateVolatility()
);
const optimalLeverage = Math.max(1, Math.min(3, sharpe / 2));
return {
kellyFraction: conservativeKelly,
optimalLeverage,
};
}
private calculateConsecutiveStats(): {
maxConsecutiveWins: number;
maxConsecutiveLosses: number;
} {
let maxWins = 0,
maxLosses = 0;
let currentWins = 0,
currentLosses = 0;
for (const trade of this.trades) {
if (trade.pnl > 0) {
currentWins++;
currentLosses = 0;
maxWins = Math.max(maxWins, currentWins);
} else if (trade.pnl < 0) {
currentLosses++;
currentWins = 0;
maxLosses = Math.max(maxLosses, currentLosses);
}
}
return { maxConsecutiveWins: maxWins, maxConsecutiveLosses: maxLosses };
}
private getYears(): number {
if (this.equityCurve.length < 2) {
return 1;
}
const start = at(this.equityCurve, 0).date;
const end = at(this.equityCurve, this.equityCurve.length - 1).date;
return this.daysBetween(start, end) / 365;
}
private getTradingDays(): number {
if (this.equityCurve.length < 2) {
return 0;
}
const start = at(this.equityCurve, 0).date;
const end = at(this.equityCurve, this.equityCurve.length - 1).date;
return this.daysBetween(start, end) * (252 / 365); // Approximate trading days
}
private daysBetween(start: Date, end: Date): number {
return (end.getTime() - start.getTime()) / (1000 * 60 * 60 * 24);
}
private getEmptyMetrics(): PerformanceMetrics {
return {
totalReturn: 0,
annualizedReturn: 0,
cagr: 0,
volatility: 0,
downVolatility: 0,
maxDrawdown: 0,
maxDrawdownDuration: 0,
var95: 0,
cvar95: 0,
sharpeRatio: 0,
sortinoRatio: 0,
calmarRatio: 0,
informationRatio: 0,
totalTrades: 0,
winRate: 0,
avgWin: 0,
avgLoss: 0,
avgWinLoss: 0,
profitFactor: 0,
expectancy: 0,
payoffRatio: 0,
avgHoldingPeriod: 0,
avgTradesPerDay: 0,
maxConsecutiveWins: 0,
maxConsecutiveLosses: 0,
largestWin: 0,
largestLoss: 0,
skewness: 0,
kurtosis: 0,
tailRatio: 0,
kellyFraction: 0,
optimalLeverage: 1,
};
}
exportReport(metrics: PerformanceMetrics = this.analyze()): string {
return `
# Performance Report
## Summary Statistics
- Total Return: ${metrics.totalReturn.toFixed(2)}%
- Annualized Return: ${metrics.annualizedReturn.toFixed(2)}%
- CAGR: ${metrics.cagr.toFixed(2)}%
- Volatility: ${metrics.volatility.toFixed(2)}%
- Max Drawdown: ${(metrics.maxDrawdown * 100).toFixed(2)}%
- Sharpe Ratio: ${metrics.sharpeRatio.toFixed(2)}
- Sortino Ratio: ${metrics.sortinoRatio.toFixed(2)}
## Trade Analysis
- Total Trades: ${metrics.totalTrades}
- Win Rate: ${metrics.winRate.toFixed(1)}%
- Profit Factor: ${metrics.profitFactor.toFixed(2)}
- Average Win: $${metrics.avgWin.toFixed(2)}
- Average Loss: $${metrics.avgLoss.toFixed(2)}
- Expectancy: $${metrics.expectancy.toFixed(2)}
## Risk Metrics
- VaR (95%): ${metrics.var95.toFixed(2)}%
- CVaR (95%): ${metrics.cvar95.toFixed(2)}%
- Downside Volatility: ${metrics.downVolatility.toFixed(2)}%
- Tail Ratio: ${metrics.tailRatio.toFixed(2)}
- Skewness: ${metrics.skewness.toFixed(2)}
- Kurtosis: ${metrics.kurtosis.toFixed(2)}
## Optimal Position Sizing
- Kelly Fraction: ${(metrics.kellyFraction * 100).toFixed(1)}%
- Optimal Leverage: ${metrics.optimalLeverage.toFixed(1)}x
`;
const number = (value: number | null, scale = 1) => formatStatistic(value, 2, scale);
return [
'# Performance Report',
'',
'## Summary Statistics',
'- Total Return: ' + number(metrics.totalReturn) + '%',
'- Annualized Return: ' +
number(metrics.annualizedReturn) +
(metrics.annualizedReturn === null ? '' : '%'),
'- CAGR: ' + number(metrics.cagr) + (metrics.cagr === null ? '' : '%'),
'- Volatility: ' + number(metrics.volatility) + (metrics.volatility === null ? '' : '%'),
'- Max Drawdown: ' + number(metrics.maxDrawdown, 100) + '%',
'- Sharpe Ratio: ' + number(metrics.sharpeRatio),
'- Sortino Ratio: ' + number(metrics.sortinoRatio),
'',
'## Trade Analysis',
'- Total Trades: ' + metrics.totalTrades,
'- Win Rate: ' + number(metrics.winRate) + '%',
'- Profit Factor: ' + number(metrics.profitFactor),
'- Average Win: $' + number(metrics.avgWin),
'- Average Loss: $' + number(metrics.avgLoss),
'- Expectancy: $' + number(metrics.expectancy),
'',
'## Risk Metrics',
'- VaR (95%): ' + number(metrics.var95) + (metrics.var95 === null ? '' : '%'),
'- CVaR (95%): ' + number(metrics.cvar95) + (metrics.cvar95 === null ? '' : '%'),
'- Downside Volatility: ' +
number(metrics.downVolatility) +
(metrics.downVolatility === null ? '' : '%'),
'- Tail Ratio: ' + number(metrics.tailRatio),
'- Skewness: ' + number(metrics.skewness),
'- Kurtosis: ' + number(metrics.kurtosis),
].join('\n');
}
}

View file

@ -0,0 +1,118 @@
/** Pure equity analysis. Returns/drawdowns are fractions; time is UTC milliseconds. */
export interface EquityPoint {
timestamp: number;
value: number;
}
export interface DrawdownPeriod {
start: number;
end: number;
depth: number;
duration: number;
recovery: number | null;
}
export const dayMs = 86400000;
export function finite(value: number): number {
if (!Number.isFinite(value)) {
throw new Error('Analytics values must be finite');
}
return value;
}
export function nullable(value: number): number | null {
return Number.isFinite(value) ? value : null;
}
export function ratio(numerator: number, denominator: number): number | null {
return denominator === 0 || !Number.isFinite(numerator) || !Number.isFinite(denominator)
? null
: nullable(numerator / denominator);
}
export function equityAnalysis(points: readonly EquityPoint[], initialCapital: number) {
if (finite(initialCapital) <= 0) {
throw new Error('Initial capital must be positive');
}
let previousTimestamp = -Infinity;
let peak = initialCapital;
let active: DrawdownPeriod | undefined;
let maxDrawdown = 0;
const periods: DrawdownPeriod[] = [];
const underwater: EquityPoint[] = [];
const daily = new Map<string, number>();
const monthly = new Map<string, number>();
for (const [index, point] of points.entries()) {
finite(point.timestamp);
finite(point.value);
if (point.timestamp < previousTimestamp) {
throw new Error('Equity observations must be ordered');
}
previousTimestamp = point.timestamp;
const iso = new Date(point.timestamp).toISOString();
daily.set(iso.slice(0, 10), point.value);
monthly.set(iso.slice(0, 7), point.value);
if (point.value >= peak) {
if (active) {
periods.push({
...active,
end: point.timestamp,
duration: (point.timestamp - active.start) / dayMs,
recovery: index,
});
active = undefined;
}
peak = point.value;
}
const drawdown = finite(Math.min(0, point.value / peak - 1));
underwater.push({ timestamp: point.timestamp, value: drawdown });
maxDrawdown = Math.max(maxDrawdown, -drawdown);
if (drawdown < 0) {
active ??= {
start: point.timestamp,
end: point.timestamp,
depth: 0,
duration: 0,
recovery: null,
};
active.depth = Math.max(active.depth, -drawdown);
active.end = point.timestamp;
active.duration = (point.timestamp - active.start) / dayMs;
}
}
if (active) {
periods.push(active);
}
const first = points[0];
const last = points[points.length - 1];
const elapsedDays = first && last ? (last.timestamp - first.timestamp) / dayMs : 0;
const finalValue = last?.value ?? initialCapital;
const totalReturn = finite(finalValue / initialCapital - 1);
const annualizedReturn =
elapsedDays > 0 && finalValue > 0
? nullable(Math.pow(finalValue / initialCapital, 365 / elapsedDays) - 1)
: null;
return {
totalReturn,
annualizedReturn,
elapsedDays,
maxDrawdown,
currentDrawdown: Math.abs(underwater[underwater.length - 1]?.value ?? 0),
maxDrawdownDuration: periods.reduce((max, period) => Math.max(max, period.duration), 0),
periods,
underwater,
// First observed period uses starting capital; no first-day loss/gain is discarded.
dailyReturns: [...periodReturns(daily, initialCapital).values()],
monthlyReturns: Object.fromEntries(periodReturns(monthly, initialCapital)),
};
}
function periodReturns(values: Map<string, number>, initialCapital: number): Map<string, number> {
let previous = initialCapital;
const returns = new Map<string, number>();
for (const [period, current] of values) {
// A nonpositive baseline has no defined percentage return; never invent a denominator.
if (previous > 0) {
returns.set(period, finite(current / previous - 1));
}
previous = current;
}
return returns;
}

View file

@ -0,0 +1,62 @@
import { equityAnalysis, nullable, ratio, type EquityPoint } from './equity';
import { factorStatistics, returnStatistics } from './return-statistics';
import { tradeStatistics, type TradeObservation } from './trade-statistics';
/** Canonical analysis core: fractions, account-currency P&L and explicit undefined statistics. */
export function performanceAnalysis(
points: readonly EquityPoint[],
trades: readonly TradeObservation[],
initialCapital: number,
benchmark?: readonly number[]
) {
const equity = equityAnalysis(points, initialCapital);
const risk = returnStatistics(equity.dailyReturns);
const trade = tradeStatistics(trades, equity.elapsedDays);
const factors = benchmark ? factorStatistics(equity.dailyReturns, benchmark) : undefined;
const kelly =
trade.payoffRatio === null || trade.payoffRatio === 0
? null
: nullable(
Math.max(
0,
Math.min(0.25, (trade.winRate - (1 - trade.winRate) / trade.payoffRatio) * 0.25)
)
);
return {
equity,
risk,
trade,
metrics: {
totalReturn: equity.totalReturn,
annualizedReturn: equity.annualizedReturn,
cagr: equity.annualizedReturn,
volatility: risk.volatility,
downVolatility: risk.downsideDeviation,
maxDrawdown: equity.maxDrawdown,
maxDrawdownDuration: equity.maxDrawdownDuration,
var95: risk.var95,
cvar95: risk.cvar95,
sharpeRatio: risk.sharpeRatio,
sortinoRatio: risk.sortinoRatio,
calmarRatio:
equity.annualizedReturn === null
? null
: ratio(equity.annualizedReturn, equity.maxDrawdown),
informationRatio: factors?.informationRatio ?? null,
...trade,
skewness: risk.skewness,
kurtosis: risk.kurtosis,
tailRatio: risk.tailRatio,
kellyFraction: kelly,
// Retained compatibility heuristic, not an optimizer or leverage recommendation.
optimalLeverage:
risk.sharpeRatio === null ? null : Math.max(1, Math.min(3, risk.sharpeRatio / 2)),
},
};
}
export function formatStatistic(value: number | null, digits = 2, scale = 1): string {
return value === null || !Number.isFinite(value * scale)
? 'N/A'
: (value * scale).toFixed(digits);
}

View file

@ -0,0 +1,170 @@
import { finite, nullable, ratio } from './equity';
export function mean(values: readonly number[]): number | null {
if (!values.length) {
return null;
}
let sum = 0;
for (const value of values) {
sum += finite(value);
}
return nullable(sum / values.length);
}
export function sampleDeviation(values: readonly number[]): number | null {
const average = mean(values);
if (values.length < 2 || average === null) {
return null;
}
return nullable(
Math.sqrt(values.reduce((sum, value) => sum + (value - average) ** 2, 0) / (values.length - 1))
);
}
/** Observed daily fractions; 252 periods/year, arithmetic excess returns, full-series downside RMS. */
export function returnStatistics(returns: readonly number[], annualRiskFree = 0.02) {
finite(annualRiskFree);
for (const value of returns) {
finite(value);
}
const average = mean(returns);
const deviation = sampleDeviation(returns);
const annualExcess = average === null ? null : nullable(average * 252 - annualRiskFree);
const volatility = deviation === null ? null : nullable(deviation * Math.sqrt(252));
const downsideDeviation =
returns.length < 2
? null
: nullable(
Math.sqrt(
returns.reduce(
(sum, value) => sum + Math.min(value - annualRiskFree / 252, 0) ** 2,
0
) / returns.length
) * Math.sqrt(252)
);
const sorted = [...returns].sort((a, b) => a - b);
const tail = (confidence: number) => {
const count = Math.max(1, Math.ceil(sorted.length * (1 - confidence) - 1e-12));
if (sorted.length < Math.round(1 / (1 - confidence))) {
return { value: null, conditional: null };
}
const boundary = sorted[count - 1];
const tailMean = mean(sorted.slice(0, count));
return {
value: boundary === undefined ? null : Math.max(0, -boundary),
conditional: tailMean === null ? null : Math.max(0, -tailMean),
};
};
const risk95 = tail(0.95);
const risk99 = tail(0.99);
const n = returns.length;
const moments =
average === null || !deviation || n < 4
? null
: returns.reduce(
(acc, value) => {
const z = (value - average) / deviation;
acc.third += z ** 3;
acc.fourth += z ** 4;
return acc;
},
{ third: 0, fourth: 0 }
);
return {
volatility,
downsideDeviation,
sharpeRatio:
annualExcess === null || volatility === null ? null : ratio(annualExcess, volatility),
sortinoRatio:
annualExcess === null || downsideDeviation === null
? null
: ratio(annualExcess, downsideDeviation),
var95: risk95.value,
cvar95: risk95.conditional,
var99: risk99.value,
skewness: moments ? nullable((n * moments.third) / ((n - 1) * (n - 2))) : null,
kurtosis: moments
? nullable(
(n * (n + 1) * moments.fourth) / ((n - 1) * (n - 2) * (n - 3)) -
(3 * (n - 1) ** 2) / ((n - 2) * (n - 3))
)
: null,
tailRatio:
sorted.length < 20
? null
: ratio(
sorted[Math.ceil(n * 0.95) - 1] ?? 0,
Math.abs(sorted[Math.ceil(n * 0.05) - 1] ?? 0)
),
};
}
/** Benchmark arrays must already be aligned to the same observed UTC daily periods. */
export function factorStatistics(
returns: readonly number[],
benchmark: readonly number[],
annualRiskFree = 0.02
) {
if (returns.length !== benchmark.length) {
throw new Error('Returns and benchmark must have same length');
}
for (const value of returns) {
finite(value);
}
for (const value of benchmark) {
finite(value);
}
finite(annualRiskFree);
const average = mean(returns);
const benchmarkAverage = mean(benchmark);
const n = returns.length;
let covariance = 0,
variance = 0;
if (average !== null && benchmarkAverage !== null) {
for (let i = 0; i < n; i++) {
covariance += ((returns[i] ?? 0) - average) * ((benchmark[i] ?? 0) - benchmarkAverage);
variance += ((benchmark[i] ?? 0) - benchmarkAverage) ** 2;
}
}
const beta = n < 2 ? null : ratio(covariance, variance);
const portfolioDeviation = sampleDeviation(returns);
const benchmarkDeviation = sampleDeviation(benchmark);
const excess = returns.map((value, index) => value - (benchmark[index] ?? 0));
const excessMean = mean(excess);
const excessDeviation = sampleDeviation(excess);
const trackingError =
excessDeviation === null ? null : nullable(excessDeviation * Math.sqrt(252));
const capture = (up: boolean) => {
let portfolio = 0,
market = 0,
count = 0;
benchmark.forEach((value, index) => {
if (up ? value > 0 : value < 0) {
portfolio += returns[index] ?? 0;
market += value;
count++;
}
});
return count ? ratio(portfolio, market) : null;
};
return {
beta,
alpha:
beta === null || average === null || benchmarkAverage === null
? null
: nullable(
(average - annualRiskFree / 252 - beta * (benchmarkAverage - annualRiskFree / 252)) *
252
),
correlation:
n < 2 || portfolioDeviation === null || benchmarkDeviation === null
? null
: ratio(covariance / (n - 1), portfolioDeviation * benchmarkDeviation),
treynorRatio:
average === null || beta === null ? null : ratio(average * 252 - annualRiskFree, beta),
trackingError,
informationRatio:
excessMean === null || trackingError === null ? null : ratio(excessMean * 252, trackingError),
upCapture: capture(true),
downCapture: capture(false),
};
}

View file

@ -0,0 +1,66 @@
import { finite, ratio } from './equity';
export interface TradeObservation {
pnl: number;
holdingPeriod: number;
}
/** Closed-trade statistics; P&L is account currency, holding periods are minutes. */
export function tradeStatistics(trades: readonly TradeObservation[], elapsedDays: number) {
let wins = 0,
losses = 0,
totalWins = 0,
totalLosses = 0,
duration = 0;
let largestWin = 0,
largestLoss = 0,
currentWins = 0,
currentLosses = 0;
let maxConsecutiveWins = 0,
maxConsecutiveLosses = 0;
for (const trade of trades) {
finite(trade.pnl);
finite(trade.holdingPeriod);
if (trade.holdingPeriod < 0) {
throw new Error('Holding period must be nonnegative');
}
duration += trade.holdingPeriod;
if (trade.pnl > 0) {
wins++;
totalWins += trade.pnl;
currentWins++;
currentLosses = 0;
maxConsecutiveWins = Math.max(maxConsecutiveWins, currentWins);
largestWin = Math.max(largestWin, trade.pnl);
} else if (trade.pnl < 0) {
losses++;
totalLosses -= trade.pnl;
currentLosses++;
currentWins = 0;
maxConsecutiveLosses = Math.max(maxConsecutiveLosses, currentLosses);
largestLoss = Math.max(largestLoss, -trade.pnl);
} else {
currentWins = 0;
currentLosses = 0;
}
}
const avgWin = wins ? finite(totalWins / wins) : 0;
const avgLoss = losses ? finite(totalLosses / losses) : 0;
return {
totalTrades: trades.length,
profitableTrades: wins,
winRate: trades.length ? wins / trades.length : 0,
avgWin,
avgLoss,
avgWinLoss: finite(avgWin - avgLoss),
profitFactor: ratio(totalWins, totalLosses),
payoffRatio: ratio(avgWin, avgLoss),
expectancy: trades.length ? finite((totalWins - totalLosses) / trades.length) : 0,
avgHoldingPeriod: trades.length ? finite(duration / trades.length) : 0,
avgTradesPerDay: elapsedDays > 0 ? ratio(trades.length, (elapsedDays * 252) / 365) : null,
maxConsecutiveWins,
maxConsecutiveLosses,
largestWin,
largestLoss,
};
}

View file

@ -1,215 +1,67 @@
import { Hono } from 'hono';
import { z } from 'zod';
import { AnalyticsService } from '../../services/AnalyticsService';
import type { OrchestratorServices as IServiceContainer } from '../../types';
import {
correlationRequestSchema,
dateRangeSchema,
optimizationRequestSchema,
predictionRequestSchema,
} from '../../contracts/analytics';
import { AnalyticsServiceError } from '../../services/analytics-error';
import type { OrchestratorServices } from '../../types';
const DateRangeSchema = z.object({
startDate: z.string().datetime(),
endDate: z.string().datetime(),
});
const OptimizationRequestSchema = z.object({
symbols: z.array(z.string()),
returns: z.array(z.array(z.number())),
constraints: z
.object({
minWeight: z.number().optional(),
maxWeight: z.number().optional(),
targetReturn: z.number().optional(),
maxRisk: z.number().optional(),
})
.optional(),
});
export function createAnalyticsRoutes(container: IServiceContainer): Hono {
export function createAnalyticsRoutes(container: OrchestratorServices): Hono {
const app = new Hono();
const analyticsService = container.custom?.AnalyticsService as AnalyticsService;
// Get performance metrics
const service = () => {
const analytics = container.custom?.AnalyticsService;
if (!analytics) {
throw new AnalyticsServiceError('unavailable');
}
return analytics;
};
app.onError((error, c) => {
if (error instanceof z.ZodError) {
return c.json({ error: 'Invalid analytics request', details: error.issues }, 400);
}
if (error instanceof SyntaxError) {
return c.json({ error: 'Invalid JSON body' }, 400);
}
if (error instanceof AnalyticsServiceError) {
return c.json({ error: error.message, code: error.code }, error.status);
}
container.logger.error('Analytics request failed', { name: error.name });
return c.json({ error: 'Analytics request failed' }, 500);
});
app.get('/performance/:portfolioId', async c => {
try {
const portfolioId = c.req.param('portfolioId');
const query = c.req.query();
const { startDate, endDate } = DateRangeSchema.parse({
startDate: query.start_date,
endDate: query.end_date,
});
const metrics = await analyticsService.getPerformanceMetrics(
portfolioId,
new Date(startDate),
new Date(endDate)
);
return c.json(metrics);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid date range',
details: error.errors,
},
400
);
}
container.logger.error('Error getting performance metrics:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get performance metrics',
},
500
);
}
const range = dateRangeSchema.parse({
startDate: c.req.query('start_date'),
endDate: c.req.query('end_date'),
});
return c.json(
await service().getPerformanceMetrics(
c.req.param('portfolioId'),
new Date(range.startDate),
new Date(range.endDate)
)
);
});
// Portfolio optimization
app.post('/optimize', async c => {
try {
const body = await c.req.json();
const request = OptimizationRequestSchema.parse(body);
const result = await analyticsService.optimizePortfolio({
returns: request.returns,
constraints: request.constraints,
});
return c.json(result);
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid optimization request',
details: error.errors,
},
400
);
}
container.logger.error('Error optimizing portfolio:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to optimize portfolio',
},
500
);
}
return c.json(
await service().optimizePortfolio(optimizationRequestSchema.parse(await c.req.json()))
);
});
// Get risk metrics
app.get('/risk/:portfolioId', async c => {
try {
const portfolioId = c.req.param('portfolioId');
const metrics = await analyticsService.getRiskMetrics(portfolioId);
return c.json(metrics);
} catch (error) {
container.logger.error('Error getting risk metrics:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to get risk metrics',
},
500
);
}
});
// Market regime detection
app.get('/regime', async c => {
try {
const regime = await analyticsService.detectMarketRegime();
return c.json({
regime,
timestamp: new Date().toISOString(),
});
} catch (error) {
container.logger.error('Error detecting market regime:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to detect market regime',
},
500
);
}
});
// Calculate correlation matrix
app.get('/risk/:portfolioId', async c =>
c.json(await service().getRiskMetrics(c.req.param('portfolioId')))
);
app.get('/regime', async c =>
c.json({ regime: await service().detectMarketRegime(), timestamp: new Date().toISOString() })
);
app.post('/correlation', async c => {
try {
const body = await c.req.json();
const { symbols } = z
.object({
symbols: z.array(z.string()).min(2),
})
.parse(body);
const matrix = await analyticsService.calculateCorrelationMatrix(symbols);
return c.json({
symbols,
matrix,
});
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid correlation request',
details: error.errors,
},
400
);
}
container.logger.error('Error calculating correlation:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to calculate correlation',
},
500
);
}
const { symbols } = correlationRequestSchema.parse(await c.req.json());
return c.json({ symbols, matrix: await service().calculateCorrelationMatrix(symbols) });
});
// ML model prediction
app.post('/predict', async c => {
try {
const body = await c.req.json();
const { modelId, features } = z
.object({
modelId: z.string(),
features: z.record(z.number()),
})
.parse(body);
const prediction = await analyticsService.predictWithModel(modelId, features);
if (prediction) {
return c.json(prediction);
} else {
return c.json({ error: 'Model not found or prediction failed' }, 404);
}
} catch (error) {
if (error instanceof z.ZodError) {
return c.json(
{
error: 'Invalid prediction request',
details: error.errors,
},
400
);
}
container.logger.error('Error making prediction:', error);
return c.json(
{
error: error instanceof Error ? error.message : 'Failed to make prediction',
},
500
);
}
const { modelId, features } = predictionRequestSchema.parse(await c.req.json());
return c.json(await service().predictWithModel(modelId, features));
});
return app;
}

View file

@ -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, []])

View file

@ -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>

View file

@ -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;
}

View file

@ -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>;
};
}

View file

@ -50,7 +50,7 @@ export async function registerOrchestratorServices(
// Create other services
const marketDataService = new MarketDataService(services);
const executionService = new ExecutionService(services, storageService);
const analyticsService = new AnalyticsService(services, storageService);
const analyticsService = new AnalyticsService(services);
const strategyManager = new StrategyManager(services, options.strategyRegistry);
Object.assign(custom, { StorageService: storageService });
const backtestEngine = options.useRustEngine

View file

@ -0,0 +1,149 @@
import { z } from 'zod';
const finite = z.number().finite();
const optionalRatio = finite.nullable();
const symbols = z
.array(z.string().trim().min(1).max(128))
.min(1)
.max(128)
.refine(values => new Set(values).size === values.length, 'Duplicate symbols');
export const PerformanceMetricsSchema = z.object({
totalReturn: finite,
sharpeRatio: optionalRatio,
sortinoRatio: optionalRatio,
maxDrawdown: finite.nonnegative(),
winRate: finite.min(0).max(1),
profitFactor: finite.nonnegative().nullable(),
avgWin: finite.nonnegative(),
avgLoss: finite.nonnegative(),
totalTrades: finite.int().nonnegative(),
});
export type PerformanceMetrics = z.infer<typeof PerformanceMetricsSchema>;
export const RiskMetricsSchema = z.object({
currentExposure: finite.nonnegative(),
dailyPnl: finite,
positionCount: finite.int().nonnegative(),
grossExposure: finite.nonnegative(),
var95: finite.nonnegative().nullable().optional(),
cvar95: finite.nonnegative().nullable().optional(),
});
export type RiskMetrics = z.infer<typeof RiskMetricsSchema>;
export const dateRangeSchema = z
.object({ startDate: z.string().datetime(), endDate: z.string().datetime() })
.refine(
value => Date.parse(value.endDate) > Date.parse(value.startDate),
'endDate must follow startDate'
);
export const optimizationRequestSchema = z
.object({
symbols,
returns: z.array(z.array(finite).min(1).max(128)).min(2).max(100000),
constraints: z
.object({
minWeight: finite.min(0).max(1).optional(),
maxWeight: finite.min(0).max(1).optional(),
targetReturn: finite.optional(),
maxRisk: finite.nonnegative().optional(),
})
.strict()
.optional(),
})
.strict()
.refine(
value => value.returns.every(row => row.length === value.symbols.length),
'Returns must have one column per symbol'
)
.refine(
value => (value.constraints?.minWeight ?? 0) <= (value.constraints?.maxWeight ?? 1),
'Invalid weight bounds'
)
.refine(
value =>
(value.constraints?.minWeight ?? 0) * value.symbols.length <= 1 &&
(value.constraints?.maxWeight ?? 1) * value.symbols.length >= 1,
'Infeasible weight bounds'
);
export type OptimizationParams = z.infer<typeof optimizationRequestSchema>;
export const portfolioWeightsSchema = z
.object({
symbols,
weights: z.array(finite.min(0).max(1)).min(1).max(128),
expected_return: finite,
expected_risk: finite.nonnegative(),
sharpe_ratio: optionalRatio,
})
.refine(
value =>
value.weights.length === value.symbols.length &&
Math.abs(value.weights.reduce((sum, weight) => sum + weight, 0) - 1) <= 1e-6,
'Invalid portfolio weights'
);
export const correlationRequestSchema = z.object({
symbols: symbols.refine(values => values.length >= 2, 'At least two symbols are required'),
});
export const correlationResponseSchema = z
.object({
symbols,
matrix: z.array(z.array(finite.min(-1).max(1)).max(128)).max(128),
})
.refine(value => {
const size = value.symbols.length;
if (value.matrix.length !== size || value.matrix.some(row => row.length !== size)) {
return false;
}
const lower = Array.from({ length: size }, () => Array<number>(size).fill(0));
for (let i = 0; i < size; i++) {
if (Math.abs((value.matrix[i]?.[i] ?? 0) - 1) > 1e-8) {
return false;
}
for (let j = 0; j <= i; j++) {
const input = value.matrix[i]?.[j] ?? 0;
if (Math.abs(input - (value.matrix[j]?.[i] ?? 0)) > 1e-8) {
return false;
}
let residual = input;
for (let k = 0; k < j; k++) {
residual -= (lower[i]?.[k] ?? 0) * (lower[j]?.[k] ?? 0);
}
const row = lower[i];
if (!row) {
return false;
}
if (i === j) {
if (residual < -1e-8) {
return false;
}
row[j] = Math.sqrt(Math.max(0, residual));
} else {
const diagonal = lower[j]?.[j] ?? 0;
if (diagonal > 1e-8) {
row[j] = residual / diagonal;
} else if (Math.abs(residual) > 1e-8) {
return false;
}
}
}
}
return true;
}, 'Invalid correlation matrix');
type Json = null | boolean | string | number | Json[] | { [key: string]: Json };
const json: z.ZodType<Json> = z.lazy(() =>
z.union([z.null(), z.boolean(), z.string(), finite, z.array(json), z.record(json)])
);
export const predictionRequestSchema = z
.object({ modelId: z.string().min(1).max(128), features: z.record(finite) })
.strict();
export const predictionResponseSchema = z.object({
model_id: z.string().min(1),
prediction: finite,
probability: z.record(finite.min(0).max(1)).nullable().optional(),
metadata: z.record(json).nullable().optional(),
});
export const backtestAnalysisSchema = z.object({
backtest_id: z.string().min(1),
metrics: z.record(optionalRatio),
statistics: z.record(optionalRatio),
risk_analysis: z.record(optionalRatio),
trade_analysis: z.record(optionalRatio),
});
export const regimeResponseSchema = z.object({ regime: z.string().trim().min(1).max(128) });

View file

@ -1,228 +1,197 @@
import axios from 'axios';
import { at } from '@stock-bot/utils';
import type { OrchestratorServices as IServiceContainer } from '../types';
import { type PerformanceMetrics, type RiskMetrics } from '../types';
import { StorageService } from './StorageService';
import axios, { type AxiosRequestConfig } from 'axios';
import { z } from 'zod';
import {
backtestAnalysisSchema,
correlationRequestSchema,
correlationResponseSchema,
dateRangeSchema,
optimizationRequestSchema,
PerformanceMetricsSchema,
portfolioWeightsSchema,
predictionRequestSchema,
predictionResponseSchema,
regimeResponseSchema,
RiskMetricsSchema,
type OptimizationParams,
} from '../contracts/analytics';
import type { OrchestratorServices } from '../types';
import { AnalyticsServiceError } from './analytics-error';
interface OptimizationParams {
returns: number[][];
constraints?: {
minWeight?: number;
maxWeight?: number;
targetReturn?: number;
maxRisk?: number;
};
}
interface PortfolioWeights {
symbols: string[];
weights: number[];
expectedReturn: number;
expectedRisk: number;
sharpeRatio: number;
export interface AnalyticsTransport {
request(config: AxiosRequestConfig): Promise<{ data: unknown }>;
}
/** Validated, bounded upstream access. Failure is never a fabricated financial observation. */
export class AnalyticsService {
private analyticsUrl: string;
private cache = new Map<string, { data: unknown; timestamp: number }>();
private readonly CACHE_TTL_MS = 60000; // 1 minute cache
private container: IServiceContainer;
private storageService: StorageService;
constructor(container: IServiceContainer, storageService: StorageService) {
this.container = container;
this.storageService = storageService;
this.analyticsUrl = process.env.ANALYTICS_SERVICE_URL || 'http://localhost:3003';
}
async getPerformanceMetrics(
portfolioId: string,
startDate: Date,
endDate: Date
): Promise<PerformanceMetrics> {
const cacheKey = `perf_${portfolioId}_${startDate.toISOString()}_${endDate.toISOString()}`;
const cached = this.getFromCache<PerformanceMetrics>(cacheKey);
if (cached) {
return cached;
}
try {
const response = await axios.get(
`${this.analyticsUrl}/analytics/performance/${portfolioId}`,
{
params: {
start_date: startDate.toISOString(),
end_date: endDate.toISOString(),
},
}
);
const metrics = response.data as PerformanceMetrics;
this.setCache(cacheKey, metrics);
return metrics;
} catch (error) {
this.container.logger.error('Error fetching performance metrics:', error);
// Return default metrics if analytics service is unavailable
return this.getDefaultPerformanceMetrics();
private readonly client: AnalyticsTransport;
private readonly now: () => number;
private readonly analyticsUrl: string;
private readonly timeoutMs: number;
private readonly cache = new Map<string, { data: unknown; expiresAt: number }>();
constructor(
private readonly container: Pick<OrchestratorServices, 'logger'>,
options: {
client?: AnalyticsTransport;
now?: () => number;
baseUrl?: string;
timeoutMs?: number;
} = {}
) {
this.client = options.client ?? axios;
this.now = options.now ?? Date.now;
this.analyticsUrl =
options.baseUrl ?? process.env.ANALYTICS_SERVICE_URL ?? 'http://localhost:3003';
this.timeoutMs = options.timeoutMs ?? 5000;
if (!Number.isInteger(this.timeoutMs) || this.timeoutMs < 1 || this.timeoutMs > 60000) {
throw new Error('Analytics timeout must be an integer between 1 and 60000 ms');
}
}
async optimizePortfolio(params: OptimizationParams): Promise<PortfolioWeights> {
try {
const response = await axios.post(`${this.analyticsUrl}/optimize/portfolio`, params);
return response.data as PortfolioWeights;
} catch (error) {
this.container.logger.error('Error optimizing portfolio:', error);
// Return equal weights as fallback
return this.getEqualWeights(at(params.returns, 0).length);
}
}
async getRiskMetrics(portfolioId: string): Promise<RiskMetrics> {
const cacheKey = `risk_${portfolioId}`;
const cached = this.getFromCache<RiskMetrics>(cacheKey);
if (cached) {
return cached;
}
try {
const response = await axios.get(`${this.analyticsUrl}/analytics/risk/${portfolioId}`);
const metrics = response.data as RiskMetrics;
this.setCache(cacheKey, metrics);
return metrics;
} catch (error) {
this.container.logger.error('Error fetching risk metrics:', error);
return this.getDefaultRiskMetrics();
}
}
async detectMarketRegime(): Promise<string> {
const cacheKey = 'market_regime';
const cached = this.getFromCache<string>(cacheKey);
if (cached) {
return cached;
}
try {
const response = await axios.get(`${this.analyticsUrl}/analytics/regime`);
const regime = response.data.regime as string;
this.setCache(cacheKey, regime, 300000); // Cache for 5 minutes
return regime;
} catch (error) {
this.container.logger.error('Error detecting market regime:', error);
return 'normal'; // Default regime
}
}
async calculateCorrelationMatrix(symbols: string[]): Promise<number[][]> {
try {
const response = await axios.post(`${this.analyticsUrl}/analytics/correlation`, { symbols });
return response.data.matrix as number[][];
} catch (error) {
this.container.logger.error('Error calculating correlation matrix:', error);
// Return identity matrix as fallback
return this.getIdentityMatrix(symbols.length);
}
}
async runBacktestAnalysis(backtestId: string) {
try {
const response = await axios.get(`${this.analyticsUrl}/analytics/backtest/${backtestId}`);
return response.data;
} catch (error) {
this.container.logger.error('Error running backtest analysis:', error);
return null;
}
}
async predictWithModel(modelId: string, features: Record<string, number>) {
try {
const response = await axios.post(`${this.analyticsUrl}/models/predict`, {
model_id: modelId,
features,
});
return response.data;
} catch (error) {
this.container.logger.error('Error getting model prediction:', error);
return null;
}
}
// Cache management
private getFromCache<T>(key: string): T | null {
const cached = this.cache.get(key);
if (!cached) {
return null;
}
const now = Date.now();
if (now - cached.timestamp > this.CACHE_TTL_MS) {
this.cache.delete(key);
return null;
}
return cached.data as T;
}
private setCache(key: string, data: unknown, ttl?: number): void {
this.cache.set(key, {
data,
timestamp: Date.now(),
async getPerformanceMetrics(portfolioId: string, startDate: Date, endDate: Date) {
const range = dateRangeSchema.parse({
startDate: startDate.toISOString(),
endDate: endDate.toISOString(),
});
// Auto-cleanup after TTL
setTimeout(() => {
this.cache.delete(key);
}, ttl || this.CACHE_TTL_MS);
}
// Fallback methods when analytics service is unavailable
private getDefaultPerformanceMetrics(): PerformanceMetrics {
return {
totalReturn: 0,
sharpeRatio: 0,
sortinoRatio: 0,
maxDrawdown: 0,
winRate: 0,
profitFactor: 0,
avgWin: 0,
avgLoss: 0,
totalTrades: 0,
};
}
private getDefaultRiskMetrics(): RiskMetrics {
return {
currentExposure: 0,
dailyPnl: 0,
positionCount: 0,
grossExposure: 0,
var95: 0,
cvar95: 0,
};
}
private getEqualWeights(n: number): PortfolioWeights {
const weight = 1 / n;
return {
symbols: Array(n)
.fill('')
.map((_, i) => `Asset${i + 1}`),
weights: Array(n).fill(weight),
expectedReturn: 0,
expectedRisk: 0,
sharpeRatio: 0,
};
}
private getIdentityMatrix(n: number): number[][] {
const matrix: number[][] = [];
for (let i = 0; i < n; i++) {
matrix[i] = [];
for (let j = 0; j < n; j++) {
at(matrix, i)[j] = i === j ? 1 : 0;
return this.fetch(
'/analytics/performance/' + encodeURIComponent(portfolioId),
PerformanceMetricsSchema,
{
params: { start_date: range.startDate, end_date: range.endDate },
cacheKey: JSON.stringify(['performance', portfolioId, range]),
ttl: 60000,
}
);
}
async getRiskMetrics(portfolioId: string) {
return this.fetch('/analytics/risk/' + encodeURIComponent(portfolioId), RiskMetricsSchema, {
cacheKey: JSON.stringify(['risk', portfolioId]),
ttl: 60000,
});
}
async optimizePortfolio(input: OptimizationParams) {
const request = optimizationRequestSchema.parse(input);
const constraints = request.constraints;
const raw = await this.fetch(
'/optimize/portfolio',
portfolioWeightsSchema.refine(
value => JSON.stringify(value.symbols) === JSON.stringify(request.symbols),
'Portfolio symbol identity mismatch'
),
{
data: {
symbols: request.symbols,
returns: request.returns,
constraints: constraints
? {
min_weight: constraints.minWeight ?? 0,
max_weight: constraints.maxWeight ?? 1,
target_return: constraints.targetReturn,
max_risk: constraints.maxRisk,
}
: undefined,
},
}
);
return {
symbols: raw.symbols,
weights: raw.weights,
expectedReturn: raw.expected_return,
expectedRisk: raw.expected_risk,
sharpeRatio: raw.sharpe_ratio,
};
}
async detectMarketRegime(): Promise<string> {
const result = await this.fetch('/analytics/regime', regimeResponseSchema, {
cacheKey: 'regime',
ttl: 300000,
});
return result.regime;
}
async calculateCorrelationMatrix(symbols: string[]): Promise<number[][]> {
const request = correlationRequestSchema.parse({ symbols });
const response = await this.fetch(
'/analytics/correlation',
correlationResponseSchema.refine(
value => JSON.stringify(value.symbols) === JSON.stringify(request.symbols),
'Correlation symbol identity mismatch'
),
{ data: request.symbols }
);
return response.matrix;
}
async runBacktestAnalysis(backtestId: string) {
return this.fetch(
'/analytics/backtest/' + encodeURIComponent(backtestId),
backtestAnalysisSchema.refine(
value => value.backtest_id === backtestId,
'Backtest identity mismatch'
)
);
}
async predictWithModel(modelId: string, features: Record<string, number>) {
const request = predictionRequestSchema.parse({ modelId, features });
return this.fetch(
'/models/predict',
predictionResponseSchema.refine(
value => value.model_id === request.modelId,
'Model identity mismatch'
),
{ data: { model_id: request.modelId, features: request.features } }
);
}
private async fetch<T>(
path: string,
schema: z.ZodType<T>,
options: {
data?: unknown;
params?: Record<string, string>;
cacheKey?: string;
ttl?: number;
} = {}
): Promise<T> {
const key = options.cacheKey;
const cached = key ? this.cache.get(key) : undefined;
if (cached && this.now() < cached.expiresAt) {
return schema.parse(structuredClone(cached.data));
}
return matrix;
if (key) {
this.cache.delete(key);
}
let response: { data: unknown };
try {
response = await this.client.request({
url: this.analyticsUrl + path,
method: options.data === undefined ? 'GET' : 'POST',
params: options.params,
data: options.data,
timeout: this.timeoutMs,
maxContentLength: 1048576,
});
} catch {
this.container.logger.error('Analytics upstream unavailable', { path });
throw new AnalyticsServiceError('unavailable');
}
const parsed = schema.safeParse(response.data);
if (!parsed.success) {
this.container.logger.error('Invalid analytics upstream response', { path });
throw new AnalyticsServiceError('invalid-response');
}
if (key) {
for (const [entry, value] of this.cache) {
if (this.now() >= value.expiresAt) {
this.cache.delete(entry);
}
}
if (this.cache.size >= 128) {
const oldest = this.cache.keys().next().value;
if (oldest !== undefined) {
this.cache.delete(oldest);
}
}
this.cache.set(key, {
data: structuredClone(parsed.data),
expiresAt: this.now() + (options.ttl ?? 60000),
});
}
return structuredClone(parsed.data);
}
}

View file

@ -0,0 +1,14 @@
export class AnalyticsServiceError extends Error {
readonly status: 502 | 503;
readonly code: 'analytics_unavailable' | 'analytics_invalid_response';
constructor(reason: 'unavailable' | 'invalid-response') {
super(
reason === 'unavailable'
? 'Analytics service is unavailable'
: 'Analytics service returned an invalid response'
);
this.name = 'AnalyticsServiceError';
this.status = reason === 'unavailable' ? 503 : 502;
this.code = reason === 'unavailable' ? 'analytics_unavailable' : 'analytics_invalid_response';
}
}

View file

@ -206,32 +206,8 @@ export const StrategyConfigSchema = z.object({
export type StrategyConfig = z.infer<typeof StrategyConfigSchema>;
// Analytics types
export const PerformanceMetricsSchema = z.object({
totalReturn: z.number(),
sharpeRatio: z.number(),
sortinoRatio: z.number(),
maxDrawdown: z.number(),
winRate: z.number(),
profitFactor: z.number(),
avgWin: z.number(),
avgLoss: z.number(),
totalTrades: z.number(),
});
export type PerformanceMetrics = z.infer<typeof PerformanceMetricsSchema>;
// Risk types
export const RiskMetricsSchema = z.object({
currentExposure: z.number(),
dailyPnl: z.number(),
positionCount: z.number(),
grossExposure: z.number(),
var95: z.number().optional(),
cvar95: z.number().optional(),
});
export type RiskMetrics = z.infer<typeof RiskMetricsSchema>;
export { PerformanceMetricsSchema, RiskMetricsSchema } from './contracts/analytics';
export type { PerformanceMetrics, RiskMetrics } from './contracts/analytics';
// Re-export specialized types
export type {

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 {