Unify analytics calculations and fail closed on unavailable data
This commit is contained in:
parent
783b619846
commit
ccce401f72
31 changed files with 1978 additions and 1553 deletions
61
README.md
61
README.md
|
|
@ -161,6 +161,67 @@ Repeated JSON/CSV/HTML exports retain the finished equity and trade count; expor
|
|||
mutate analysis. Charts and quality observations group frozen bars in one pass, but datasets
|
||||
and detailed equity history still reside in memory; this is not a streaming backtest engine.
|
||||
|
||||
## Analytics correctness and availability
|
||||
|
||||
`orchestrator/src/analytics/{equity,return-statistics,trade-statistics,performance}.ts`
|
||||
contains pure shared math. `PerformanceAnalyzer` is a detached, cached compatibility facade;
|
||||
`BacktestReport` consumes that same analysis instead of recalculating daily returns, drawdowns
|
||||
and risk statistics. Core returns and risk magnitudes are fractions. The legacy direct-backend
|
||||
and report-summary percentage-point fields are converted only at the facade; the runner's
|
||||
persisted/public `BacktestRunResult` still uses fractions. Risk statistics no longer apply
|
||||
volatility/VaR calculations directly to percentage-point returns (the former 100× scaling bug).
|
||||
|
||||
Conventions are explicit and covered by golden fixtures:
|
||||
|
||||
- UTC daily/month-end observations use the final value in each period. The first period uses
|
||||
initial capital, so its gain/loss is not discarded. Nonpositive subsequent denominators are
|
||||
omitted rather than replaced; same-timestamp observations use the last value.
|
||||
- CAGR uses observed elapsed calendar time (365 days/year), and is `null` for zero elapsed
|
||||
time, nonpositive ending equity or an unrepresentable result. Total losses and drawdowns
|
||||
beyond 100% remain valid observations; no opening balance is invented.
|
||||
- Volatility uses sample standard deviation and 252 observed daily periods/year. Sharpe uses
|
||||
arithmetic daily excess returns against a 2% annual reference rate divided by 252, not CAGR
|
||||
divided by volatility. See [Sharpe's definition](https://web.stanford.edu/~wfsharpe/art/sr/sr.htm).
|
||||
- Sortino uses full-series downside RMS relative to that daily reference target, not the
|
||||
standard deviation of only negative returns. The denominator includes every observed return;
|
||||
see [PerformanceAnalytics' downside-deviation conventions](https://search.r-project.org/CRAN/refmans/PerformanceAnalytics/html/DownsideDeviation.html).
|
||||
- Historical VaR/CVaR are nonnegative loss magnitudes from the worst empirical tail. The 95%
|
||||
tail requires at least 20 returns; the 99% tail requires 100. These are historical statistics,
|
||||
not forecasts. Sparse observed dates are not an exchange-calendar completeness guarantee.
|
||||
- Drawdown periods have independent peak-to-trough depth, recover on equality with the peak,
|
||||
and measure calendar days from the first below-peak observation to recovery or the observed
|
||||
end. Ongoing periods are explicit; neither duration nor depth comes from another period.
|
||||
- Undefined ratios and insufficient-sample statistics are `null`, not zero or infinity.
|
||||
Profit factor is `null` with no losses; breakeven trades reset win/loss streaks. Empty trade
|
||||
series retain zero trade count/win rate as a convention. UI/text ratios display unavailable
|
||||
values as “N/A” or “-”; JSON preserves `null`. The old leverage field remains a compatibility
|
||||
heuristic, not an optimizer or trading recommendation.
|
||||
|
||||
Corrected analytics can change new-run results. Existing saved rows are not recalculated and
|
||||
no database migration/reset is performed. Native trading algorithms and engine-specific
|
||||
supplemental statistics are not silently redefined by this TypeScript math refactor.
|
||||
|
||||
The external analytics client validates finite responses, ordered instrument/model identity,
|
||||
portfolio weights and correlation matrices (including positive semidefiniteness). Requests
|
||||
have a five-second timeout and one-MiB response limit. Its success cache is capped at 128
|
||||
entries with per-entry TTL; failed/expired requests never become fresh fake observations.
|
||||
HTTP 503 means unavailable upstream/data; 502 means an invalid upstream response; invalid
|
||||
client input remains 400. No outage produces zero risk metrics, equal portfolio weights,
|
||||
an identity correlation matrix or a “normal” market regime.
|
||||
|
||||
The Python portfolio-performance/risk, regime, correlation, saved-backtest-analysis and
|
||||
attribution endpoints currently have no observed-data adapter. They now return explicit 503
|
||||
instead of random samples or constant reports. They remain unavailable until real data is
|
||||
integrated; research helpers are not production data sources. Optimization still consumes
|
||||
caller-provided returns/symbols, and prediction requires an actual loaded model. TypeScript
|
||||
maps their snake-case Python wire fields explicitly rather than guessing weights/identities.
|
||||
|
||||
Run `bun run check` for TypeScript/native checks and analytics regression fixtures.
|
||||
Separately run `bun run test:analytics-api` for real FastAPI router HTTP tests. That optional
|
||||
command needs Python 3.12 and `uv`; it obtains the FastAPI/HTTPX/Pydantic versions already
|
||||
pinned by the Python service, without installing the research/ML runtime. It tests the router,
|
||||
not full Python-service startup or a live upstream deployment.
|
||||
|
||||
## Backtest data integrity
|
||||
|
||||
Historical storage no longer invents prices when a database is unavailable. Configure a
|
||||
|
|
|
|||
2
apps/stock/analytics/.gitignore
vendored
Normal file
2
apps/stock/analytics/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
__pycache__/
|
||||
*.py[cod]
|
||||
|
|
@ -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()
|
||||
|
|
|
|||
55
apps/stock/analytics/test/test_unavailable_endpoints.py
Normal file
55
apps/stock/analytics/test/test_unavailable_endpoints.py
Normal 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()
|
||||
|
|
@ -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');
|
||||
}
|
||||
}
|
||||
|
|
|
|||
118
apps/stock/orchestrator/src/analytics/equity.ts
Normal file
118
apps/stock/orchestrator/src/analytics/equity.ts
Normal 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;
|
||||
}
|
||||
62
apps/stock/orchestrator/src/analytics/performance.ts
Normal file
62
apps/stock/orchestrator/src/analytics/performance.ts
Normal 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);
|
||||
}
|
||||
170
apps/stock/orchestrator/src/analytics/return-statistics.ts
Normal file
170
apps/stock/orchestrator/src/analytics/return-statistics.ts
Normal 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),
|
||||
};
|
||||
}
|
||||
66
apps/stock/orchestrator/src/analytics/trade-statistics.ts
Normal file
66
apps/stock/orchestrator/src/analytics/trade-statistics.ts
Normal 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,
|
||||
};
|
||||
}
|
||||
|
|
@ -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;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,6 +55,7 @@ export class BacktestReport {
|
|||
}
|
||||
const closedTrades = structuredClone(trades);
|
||||
const performance = this.calculatePerformance(closedTrades);
|
||||
const analysis = defined(this.performanceAnalyzer).getAnalysis();
|
||||
const result: BacktestResult = {
|
||||
// Identification
|
||||
backtestId: this.backtestId,
|
||||
|
|
@ -81,13 +82,15 @@ export class BacktestReport {
|
|||
maxDrawdown: performance.maxDrawdown,
|
||||
winRate: performance.winRate,
|
||||
totalTrades: performance.totalTrades,
|
||||
profitFactor: performance.profitFactor || 0,
|
||||
profitFactor: performance.profitFactor,
|
||||
profitableTrades: Math.round((performance.totalTrades * performance.winRate) / 100),
|
||||
avgWin: performance.avgWin || 0,
|
||||
avgLoss: performance.avgLoss || 0,
|
||||
expectancy: performance.expectancy || 0,
|
||||
calmarRatio: performance.calmarRatio || 0,
|
||||
sortinoRatio: performance.sortinoRatio || 0,
|
||||
calmarRatio: performance.calmarRatio,
|
||||
sortinoRatio: performance.sortinoRatio,
|
||||
annualizedReturn: performance.annualizedReturn,
|
||||
cagr: performance.cagr,
|
||||
},
|
||||
|
||||
// Chart data (frontend-ready format)
|
||||
|
|
@ -127,11 +130,26 @@ export class BacktestReport {
|
|||
|
||||
// Additional analytics
|
||||
analytics: {
|
||||
drawdownSeries: this.calculateDrawdown(),
|
||||
dailyReturns: this.calculateDailyReturns(),
|
||||
monthlyReturns: this.calculateMonthlyReturns(),
|
||||
drawdownSeries: analysis.equity.underwater.map(point => ({
|
||||
...point,
|
||||
value: point.value * 100,
|
||||
})),
|
||||
dailyReturns: analysis.equity.dailyReturns.map(value => value * 100),
|
||||
monthlyReturns: Object.fromEntries(
|
||||
Object.entries(analysis.equity.monthlyReturns).map(([month, value]) => [
|
||||
month,
|
||||
value * 100,
|
||||
])
|
||||
),
|
||||
exposureTime: this.calculateExposureTime(closedTrades),
|
||||
riskMetrics: this.calculateRiskMetrics(closedTrades),
|
||||
riskMetrics: {
|
||||
volatility: analysis.risk.volatility,
|
||||
downsideDeviation: analysis.risk.downsideDeviation,
|
||||
var95: analysis.risk.var95,
|
||||
var99: analysis.risk.var99,
|
||||
cvar95: analysis.risk.cvar95,
|
||||
maxConsecutiveLosses: analysis.trade.maxConsecutiveLosses,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
|
|
@ -180,40 +198,6 @@ export class BacktestReport {
|
|||
return analyzer.analyze();
|
||||
}
|
||||
|
||||
private calculateDrawdown(): { timestamp: number; value: number }[] {
|
||||
const drawdowns: { timestamp: number; value: number }[] = [];
|
||||
let peak = this.config.initialCapital;
|
||||
|
||||
for (const point of this.equityCurve) {
|
||||
if (point.value > peak) {
|
||||
peak = point.value;
|
||||
}
|
||||
const drawdown = ((point.value - peak) / peak) * 100;
|
||||
drawdowns.push({
|
||||
timestamp: point.timestamp,
|
||||
value: drawdown,
|
||||
});
|
||||
}
|
||||
|
||||
return drawdowns;
|
||||
}
|
||||
|
||||
private calculateMonthlyReturns(): Record<string, number> {
|
||||
const monthlyReturns: Record<string, number> = {};
|
||||
const monthlyEquity = new Map<string, number>();
|
||||
for (const point of this.equityCurve) {
|
||||
monthlyEquity.set(new Date(point.timestamp).toISOString().slice(0, 7), point.value);
|
||||
}
|
||||
let previous = this.config.initialCapital;
|
||||
for (const [month, value] of monthlyEquity) {
|
||||
if (previous > 0) {
|
||||
monthlyReturns[month] = ((value - previous) / previous) * 100;
|
||||
}
|
||||
previous = value;
|
||||
}
|
||||
return monthlyReturns;
|
||||
}
|
||||
|
||||
private calculateExposureTime(closedTrades: ClosedTrade[] = []): number {
|
||||
if (closedTrades.length === 0) {
|
||||
return 0;
|
||||
|
|
@ -233,84 +217,6 @@ export class BacktestReport {
|
|||
return totalTime > 0 ? (totalExposureTime / totalTime) * 100 : 0;
|
||||
}
|
||||
|
||||
private calculateRiskMetrics(closedTrades: ClosedTrade[] = []): Record<string, number> {
|
||||
const returns = this.calculateDailyReturns();
|
||||
|
||||
// Calculate various risk metrics
|
||||
const avgReturn = returns.reduce((a, b) => a + b, 0) / Math.max(returns.length, 1);
|
||||
const variance =
|
||||
returns.reduce((sum, r) => sum + Math.pow(r - avgReturn, 2), 0) / Math.max(returns.length, 1);
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
// Downside deviation (for Sortino)
|
||||
const downsideReturns = returns.filter(r => r < 0);
|
||||
const downsideVariance =
|
||||
downsideReturns.reduce((sum, r) => sum + Math.pow(r, 2), 0) /
|
||||
Math.max(downsideReturns.length, 1);
|
||||
const downsideDeviation = Math.sqrt(downsideVariance);
|
||||
|
||||
return {
|
||||
volatility: stdDev * Math.sqrt(252), // Annualized
|
||||
downsideDeviation: downsideDeviation * Math.sqrt(252),
|
||||
var95: this.calculateVaR(returns, 0.95),
|
||||
var99: this.calculateVaR(returns, 0.99),
|
||||
cvar95: this.calculateCVaR(returns, 0.95),
|
||||
maxConsecutiveLosses: this.calculateMaxConsecutiveLosses(closedTrades),
|
||||
};
|
||||
}
|
||||
|
||||
private calculateVaR(returns: number[], confidence: number): number {
|
||||
const sorted = [...returns].sort((a, b) => a - b);
|
||||
const index = Math.floor((1 - confidence) * sorted.length);
|
||||
return sorted[index] || 0;
|
||||
}
|
||||
|
||||
private calculateCVaR(returns: number[], confidence: number): number {
|
||||
const sorted = [...returns].sort((a, b) => a - b);
|
||||
const index = Math.floor((1 - confidence) * sorted.length);
|
||||
const tail = sorted.slice(0, index + 1);
|
||||
return tail.reduce((a, b) => a + b, 0) / Math.max(tail.length, 1);
|
||||
}
|
||||
|
||||
private calculateMaxConsecutiveLosses(closedTrades: ClosedTrade[] = []): number {
|
||||
let maxLosses = 0;
|
||||
let currentLosses = 0;
|
||||
|
||||
for (const trade of closedTrades) {
|
||||
if (trade.pnl && trade.pnl < 0) {
|
||||
currentLosses++;
|
||||
maxLosses = Math.max(maxLosses, currentLosses);
|
||||
} else {
|
||||
currentLosses = 0;
|
||||
}
|
||||
}
|
||||
|
||||
return maxLosses;
|
||||
}
|
||||
|
||||
private calculateDailyReturns(): number[] {
|
||||
const dailyReturns: number[] = [];
|
||||
const dailyEquity = new Map<string, number>();
|
||||
|
||||
// Group equity by day
|
||||
for (const point of this.equityCurve) {
|
||||
const date = new Date(point.timestamp).toISOString().slice(0, 10);
|
||||
dailyEquity.set(date, point.value);
|
||||
}
|
||||
|
||||
// Calculate returns
|
||||
const dates = Array.from(dailyEquity.keys()).sort();
|
||||
for (let i = 1; i < dates.length; i++) {
|
||||
const prevValue = defined(dailyEquity.get(at(dates, i - 1)));
|
||||
const currValue = defined(dailyEquity.get(at(dates, i)));
|
||||
if (prevValue > 0) {
|
||||
dailyReturns.push(((currValue - prevValue) / prevValue) * 100);
|
||||
}
|
||||
}
|
||||
|
||||
return dailyReturns;
|
||||
}
|
||||
|
||||
private getOHLCData(dataset: HistoricalDataset): Record<string, OHLCBar[]> {
|
||||
const grouped: Record<string, OHLCBar[]> = Object.fromEntries(
|
||||
this.config.symbols.map(symbol => [symbol, []])
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { formatStatistic } from '../analytics/performance';
|
||||
import type { PerformanceMetrics } from '../analytics/PerformanceAnalyzer';
|
||||
import type { ClosedTrade } from './native-result';
|
||||
|
||||
|
|
@ -77,7 +78,7 @@ export function generateHTMLReport(result: ReportExport): string {
|
|||
|
||||
<h2>Summary Statistics</h2>
|
||||
<div class="metric">Total Return: <span class="${result.summary.totalReturn >= 0 ? 'positive' : 'negative'}">${result.summary.totalReturn.toFixed(2)}%</span></div>
|
||||
<div class="metric">Sharpe Ratio: ${result.summary.sharpeRatio.toFixed(2)}</div>
|
||||
<div class="metric">Sharpe Ratio: ${formatStatistic(result.summary.sharpeRatio)}</div>
|
||||
<div class="metric">Max Drawdown: <span class="negative">${(result.summary.maxDrawdown * 100).toFixed(2)}%</span></div>
|
||||
<div class="metric">Win Rate: ${result.summary.winRate.toFixed(1)}%</div>
|
||||
<div class="metric">Total Trades: ${result.summary.totalTrades}</div>
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ const analyticsSchema = z.object({
|
|||
drawdownSeries: z.array(z.object({ timestamp: finite, value: finite })).optional(),
|
||||
dailyReturns: z.array(finite).optional(),
|
||||
monthlyReturns: z.record(finite).optional(),
|
||||
riskMetrics: z.record(finite).optional(),
|
||||
riskMetrics: z.record(finite.nullable()).optional(),
|
||||
});
|
||||
/** Validate once before persistence and before publishing a terminal result. */
|
||||
export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
||||
|
|
@ -55,7 +55,7 @@ export const backtestRunResultSchema: z.ZodType<BacktestRunResult> = z.object({
|
|||
metrics: z
|
||||
.object({
|
||||
totalReturn: finite,
|
||||
sharpeRatio: finite,
|
||||
sharpeRatio: finite.nullable(),
|
||||
maxDrawdown: finite,
|
||||
winRate: finite,
|
||||
totalTrades: finite,
|
||||
|
|
@ -152,7 +152,7 @@ export function normalizeBacktestResult(
|
|||
metrics.totalTrades = raw.trades.length; // Completed round trips, not individual fills.
|
||||
metrics.profitableTrades = raw.trades.filter(trade => (trade.pnl ?? 0) > 0).length;
|
||||
}
|
||||
for (const key of ['annualReturn', 'annualizedReturn']) {
|
||||
for (const key of ['annualReturn', 'annualizedReturn', 'cagr']) {
|
||||
if (typeof metrics[key] === 'number') {
|
||||
metrics[key] /= 100;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,17 +30,19 @@ export interface BacktestResult {
|
|||
// Performance metrics
|
||||
metrics: {
|
||||
totalReturn: number;
|
||||
sharpeRatio: number;
|
||||
sharpeRatio: number | null;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
totalTrades: number;
|
||||
profitFactor: number;
|
||||
profitFactor: number | null;
|
||||
profitableTrades: number;
|
||||
avgWin: number;
|
||||
avgLoss: number;
|
||||
expectancy: number;
|
||||
calmarRatio: number;
|
||||
sortinoRatio: number;
|
||||
calmarRatio: number | null;
|
||||
sortinoRatio: number | null;
|
||||
annualizedReturn: number | null;
|
||||
cagr: number | null;
|
||||
};
|
||||
|
||||
// Chart data
|
||||
|
|
@ -79,6 +81,6 @@ export interface BacktestResult {
|
|||
dailyReturns: number[];
|
||||
monthlyReturns: Record<string, number>;
|
||||
exposureTime: number;
|
||||
riskMetrics: Record<string, number>;
|
||||
riskMetrics: Record<string, number | null>;
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
149
apps/stock/orchestrator/src/contracts/analytics.ts
Normal file
149
apps/stock/orchestrator/src/contracts/analytics.ts
Normal 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) });
|
||||
|
|
@ -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);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
14
apps/stock/orchestrator/src/services/analytics-error.ts
Normal file
14
apps/stock/orchestrator/src/services/analytics-error.ts
Normal 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';
|
||||
}
|
||||
}
|
||||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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>
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -27,7 +27,7 @@ export interface BacktestRunConfiguration {
|
|||
/** Return, drawdown, and win-rate metrics are fractions (0.10 = 10%). */
|
||||
export interface BacktestRunMetrics {
|
||||
totalReturn: number;
|
||||
sharpeRatio: number;
|
||||
sharpeRatio: number | null;
|
||||
maxDrawdown: number;
|
||||
winRate: number;
|
||||
/** Completed round trips; trades[] can contain fills or closed trades, identified by kind. */
|
||||
|
|
@ -87,7 +87,7 @@ export interface BacktestRunResult {
|
|||
drawdownSeries?: { timestamp: number; value: number }[];
|
||||
dailyReturns?: number[];
|
||||
monthlyReturns?: Record<string, number>;
|
||||
riskMetrics?: Record<string, number>;
|
||||
riskMetrics?: Record<string, number | null>;
|
||||
};
|
||||
executionTime: number;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@
|
|||
"test:integration": "bun test test/integration/",
|
||||
"test:native": "cargo test -p engine --lib --offline",
|
||||
"test:postgres": "bun run scripts/test-postgres.ts",
|
||||
"test:analytics-api": "uv run --no-project --with fastapi==0.104.1 --with httpx==0.25.2 --with pydantic==2.5.0 python -m unittest discover -s apps/stock/analytics/test",
|
||||
"audit:secrets": "bun run scripts/audit-secrets.ts",
|
||||
"test:e2e": "bun test test/e2e",
|
||||
"test:libs": "turbo run test --filter='./libs/**'",
|
||||
|
|
|
|||
|
|
@ -256,6 +256,16 @@ describe('orchestrator architecture boundaries', () => {
|
|||
expect(dependencies).toEqual(['backtest/BacktestPlayback.ts', 'backtest/execution-engine.ts']);
|
||||
});
|
||||
|
||||
it('shared analytics math is pure and cannot load report facades or application adapters', () => {
|
||||
for (const entry of ['equity', 'performance', 'return-statistics', 'trade-statistics']) {
|
||||
for (const file of reachable(join(root, 'analytics/' + entry + '.ts'))) {
|
||||
expect(relative(root, file)).toMatch(/^analytics\//);
|
||||
expect(relative(root, file)).not.toBe('analytics/PerformanceAnalyzer.ts');
|
||||
expect((imports.get(file) ?? []).every(specifier => specifier.startsWith('.'))).toBe(true);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('backtest reports are independent of run control, native engines, data loading and financial mutation', () => {
|
||||
for (const entry of ['backtest/BacktestReport.ts', 'backtest/report-format.ts']) {
|
||||
for (const file of reachable(join(root, entry))) {
|
||||
|
|
|
|||
16
test/fixtures/analytics-golden.json
vendored
Normal file
16
test/fixtures/analytics-golden.json
vendored
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
{
|
||||
"drawdowns": { "equity": [100, 80, 110, 99, 120], "depths": [0.2, 0.1], "durations": [1, 1] },
|
||||
"daily": {
|
||||
"returns": [-0.01, 0.02, -0.03, 0.04],
|
||||
"annualVariance": 0.2436,
|
||||
"annualDownsideVariance": 0.063,
|
||||
"annualExcess": 1.26
|
||||
},
|
||||
"trades": {
|
||||
"pnl": [10, -4, 0, 20, -2, -3, 0, -1],
|
||||
"profitFactor": 3,
|
||||
"winRate": 0.25,
|
||||
"expectancy": 2.5,
|
||||
"maxConsecutiveLosses": 2
|
||||
}
|
||||
}
|
||||
154
test/integration/analytics-math.test.ts
Normal file
154
test/integration/analytics-math.test.ts
Normal file
|
|
@ -0,0 +1,154 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { dayMs, equityAnalysis } from '../../apps/stock/orchestrator/src/analytics/equity';
|
||||
import { performanceAnalysis } from '../../apps/stock/orchestrator/src/analytics/performance';
|
||||
import { PerformanceAnalyzer } from '../../apps/stock/orchestrator/src/analytics/PerformanceAnalyzer';
|
||||
import {
|
||||
factorStatistics,
|
||||
returnStatistics,
|
||||
} from '../../apps/stock/orchestrator/src/analytics/return-statistics';
|
||||
import { tradeStatistics } from '../../apps/stock/orchestrator/src/analytics/trade-statistics';
|
||||
import golden from '../fixtures/analytics-golden.json';
|
||||
|
||||
const start = Date.parse('2024-01-01T00:00:00Z');
|
||||
const points = (values: number[]) =>
|
||||
values.map((value, i) => ({ timestamp: start + i * dayMs, value }));
|
||||
|
||||
describe('pure, fraction-based analytics golden fixtures', () => {
|
||||
test('drawdown depths belong to each period, equal peaks recover, and ongoing periods use observed time', () => {
|
||||
const result = equityAnalysis(points(golden.drawdowns.equity), 100);
|
||||
result.periods.forEach((period, i) => {
|
||||
expect(period.depth).toBeCloseTo(golden.drawdowns.depths[i]!);
|
||||
expect(period.duration).toBe(golden.drawdowns.durations[i]!);
|
||||
});
|
||||
expect(result.maxDrawdown).toBeCloseTo(0.2);
|
||||
expect(result.currentDrawdown).toBe(0);
|
||||
const recovered = equityAnalysis(points([100, 90, 100, 80]), 100);
|
||||
expect(recovered.periods[0]?.recovery).toBe(2);
|
||||
expect(recovered.periods[1]?.recovery).toBeNull();
|
||||
expect(recovered.periods[1]?.depth).toBeCloseTo(0.2);
|
||||
expect(recovered.maxDrawdownDuration).toBe(1);
|
||||
const facade = new PerformanceAnalyzer(100);
|
||||
points(golden.drawdowns.equity).forEach(point =>
|
||||
facade.addEquityPoint(new Date(point.timestamp), point.value)
|
||||
);
|
||||
expect(facade.analyzeDrawdowns().drawdownPeriods.map(period => period.depth)).toEqual(
|
||||
result.periods.map(period => period.depth)
|
||||
);
|
||||
});
|
||||
test('CAGR requires positive capital, positive ending equity and positive elapsed time', () => {
|
||||
expect(equityAnalysis([], 100).annualizedReturn).toBeNull();
|
||||
const growth = equityAnalysis(
|
||||
[
|
||||
{ timestamp: start, value: 100 },
|
||||
{ timestamp: start + 730 * dayMs, value: 121 },
|
||||
],
|
||||
100
|
||||
);
|
||||
expect(growth.totalReturn).toBeCloseTo(0.21);
|
||||
expect(growth.annualizedReturn).toBeCloseTo(0.1);
|
||||
for (const end of [0, -10])
|
||||
expect(equityAnalysis(points([100, end]), 100).annualizedReturn).toBeNull();
|
||||
expect(() => equityAnalysis(points([100]), 0)).toThrow();
|
||||
expect(() => equityAnalysis(points([100, NaN]), 100)).toThrow('finite');
|
||||
expect(() => equityAnalysis(points([100, 110]).reverse(), 100)).toThrow('ordered');
|
||||
const sameTime = new PerformanceAnalyzer(100);
|
||||
sameTime.addEquityPoint(new Date(start), 100);
|
||||
sameTime.addEquityPoint(new Date(start), 101);
|
||||
expect(sameTime.analyze().cagr).toBeNull();
|
||||
expect(sameTime.analyze().annualizedReturn).toBeNull();
|
||||
expect(sameTime.exportReport()).toContain('CAGR: N/A');
|
||||
expect(sameTime.exportReport()).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
test('UTC grouping keeps first-period returns and never associates a skipped denominator with another month', () => {
|
||||
const result = equityAnalysis(
|
||||
[
|
||||
{ timestamp: Date.parse('2024-01-31T23:30:00Z'), value: 110 },
|
||||
{ timestamp: Date.parse('2024-02-01T00:30:00Z'), value: 0 },
|
||||
{ timestamp: Date.parse('2024-03-01T00:30:00Z'), value: 50 },
|
||||
{ timestamp: Date.parse('2024-04-01T00:30:00Z'), value: 75 },
|
||||
],
|
||||
100
|
||||
);
|
||||
expect(result.dailyReturns[0]).toBeCloseTo(0.1);
|
||||
expect(result.monthlyReturns['2024-01']).toBeCloseTo(0.1);
|
||||
expect(result.monthlyReturns['2024-02']).toBe(-1);
|
||||
expect(result.monthlyReturns['2024-03']).toBeUndefined();
|
||||
expect(result.monthlyReturns['2024-04']).toBe(0.5);
|
||||
});
|
||||
test('sample volatility and full-series downside RMS use daily fractions, not percentage points', () => {
|
||||
const result = returnStatistics(golden.daily.returns, 0);
|
||||
expect(result.volatility! ** 2).toBeCloseTo(golden.daily.annualVariance, 10);
|
||||
expect(result.downsideDeviation! ** 2).toBeCloseTo(golden.daily.annualDownsideVariance, 10);
|
||||
expect(result.sharpeRatio).toBeCloseTo(
|
||||
golden.daily.annualExcess / Math.sqrt(golden.daily.annualVariance)
|
||||
);
|
||||
expect(result.sortinoRatio).toBeCloseTo(
|
||||
golden.daily.annualExcess / Math.sqrt(golden.daily.annualDownsideVariance)
|
||||
);
|
||||
expect(returnStatistics([], 0).volatility).toBeNull();
|
||||
expect(returnStatistics([0.1], 0).sharpeRatio).toBeNull();
|
||||
expect(returnStatistics([0, 0, 0], 0).sharpeRatio).toBeNull();
|
||||
expect(returnStatistics([0, 0, 0], 0).volatility).toBe(0);
|
||||
expect(returnStatistics([0.1, 0.2], 0).sortinoRatio).toBeNull();
|
||||
expect(() => returnStatistics([Infinity])).toThrow('finite');
|
||||
expect(() => returnStatistics(Array<number>(3))).toThrow('finite');
|
||||
});
|
||||
test('historical loss tails require enough samples and have one shared positive-loss sign convention', () => {
|
||||
expect(returnStatistics(Array(19).fill(-0.01)).var95).toBeNull();
|
||||
const risk = returnStatistics(Array.from({ length: 100 }, (_, i) => i / 1000 - 0.05));
|
||||
expect(risk.var95).toBeCloseTo(0.046);
|
||||
expect(risk.cvar95).toBeCloseTo(0.048);
|
||||
expect(risk.var99).toBeCloseTo(0.05);
|
||||
expect(returnStatistics(Array(100).fill(0.01)).var95).toBe(0);
|
||||
});
|
||||
test('trade statistics count completed trades, break streaks on breakeven and preserve undefined ratios', () => {
|
||||
const result = tradeStatistics(
|
||||
golden.trades.pnl.map(pnl => ({ pnl, holdingPeriod: 60 })),
|
||||
365
|
||||
);
|
||||
const { pnl: _pnl, ...expected } = golden.trades;
|
||||
expect(result).toMatchObject(expected);
|
||||
expect(result.avgWin).toBe(15);
|
||||
expect(result.avgLoss).toBe(2.5);
|
||||
expect(result.avgHoldingPeriod).toBe(60);
|
||||
expect(result.avgTradesPerDay).toBeCloseTo(8 / 252);
|
||||
expect(tradeStatistics([], 0).profitFactor).toBeNull();
|
||||
expect(tradeStatistics([{ pnl: 10, holdingPeriod: 0 }], 1).profitFactor).toBeNull();
|
||||
expect(tradeStatistics([{ pnl: -10, holdingPeriod: 0 }], 1).profitFactor).toBe(0);
|
||||
expect(() => tradeStatistics([{ pnl: NaN, holdingPeriod: 0 }], 1)).toThrow();
|
||||
});
|
||||
test('benchmark math validates alignment and uses the same fraction-based excess-return convention', () => {
|
||||
const benchmark = [-0.01, 0.02, -0.02, 0.03];
|
||||
const result = factorStatistics(
|
||||
benchmark.map(value => 2 * value),
|
||||
benchmark,
|
||||
0
|
||||
);
|
||||
expect(result.beta).toBeCloseTo(2);
|
||||
expect(result.alpha).toBeCloseTo(0);
|
||||
expect(result.correlation).toBeCloseTo(1);
|
||||
expect(factorStatistics([0, 0], [0, 0]).beta).toBeNull();
|
||||
expect(() => factorStatistics([0], [0, 0])).toThrow('same length');
|
||||
expect(() => factorStatistics([0, NaN], [0, 0])).toThrow('finite');
|
||||
});
|
||||
test('facade input/output detachment, cache invalidation and legacy report percentages are explicit', () => {
|
||||
const analyzer = new PerformanceAnalyzer(100);
|
||||
const date = new Date(start);
|
||||
analyzer.addEquityPoint(date, 100);
|
||||
date.setUTCFullYear(2030);
|
||||
analyzer.addEquityPoint(new Date(start + 365 * dayMs), 110);
|
||||
expect(analyzer.analyze().totalReturn).toBeCloseTo(10);
|
||||
expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1);
|
||||
const view = analyzer.getAnalysis();
|
||||
view.metrics.totalReturn = 999;
|
||||
expect(analyzer.getAnalysis().metrics.totalReturn).toBeCloseTo(0.1);
|
||||
analyzer.addEquityPoint(new Date(start + 366 * dayMs), 120);
|
||||
expect(analyzer.analyze().totalReturn).toBeCloseTo(20);
|
||||
const bankrupt = performanceAnalysis(points([100, 0, -10]), [], 100);
|
||||
expect(bankrupt.metrics.totalReturn).toBeCloseTo(-1.1);
|
||||
expect(bankrupt.metrics.cagr).toBeNull();
|
||||
expect(
|
||||
Object.values(bankrupt.metrics).every(value => value === null || Number.isFinite(value))
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
295
test/integration/analytics-service.test.ts
Normal file
295
test/integration/analytics-service.test.ts
Normal file
|
|
@ -0,0 +1,295 @@
|
|||
import type { AxiosRequestConfig } from 'axios';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { createAnalyticsRoutes } from '../../apps/stock/orchestrator/src/api/rest/analytics';
|
||||
import { AnalyticsServiceError } from '../../apps/stock/orchestrator/src/services/analytics-error';
|
||||
import { AnalyticsService } from '../../apps/stock/orchestrator/src/services/AnalyticsService';
|
||||
import { logger } from '../fixtures/execution';
|
||||
|
||||
const performance = {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
sortinoRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
totalTrades: 0,
|
||||
};
|
||||
const risk = { currentExposure: 0, dailyPnl: 0, positionCount: 0, grossExposure: 0, var95: null };
|
||||
const optimize = {
|
||||
symbols: ['A.US', 'B.US'],
|
||||
returns: [
|
||||
[0.01, -0.01],
|
||||
[-0.01, 0.02],
|
||||
],
|
||||
constraints: { minWeight: 0.1, maxWeight: 0.9 },
|
||||
};
|
||||
function fixture(initial: unknown = performance) {
|
||||
let data = initial;
|
||||
let failure = false;
|
||||
let now = 0;
|
||||
const requests: AxiosRequestConfig[] = [];
|
||||
const service = new AnalyticsService(
|
||||
{ logger },
|
||||
{
|
||||
baseUrl: 'http://analytics.fixture',
|
||||
now: () => now,
|
||||
client: {
|
||||
async request(request) {
|
||||
requests.push(structuredClone(request));
|
||||
if (failure) throw new Error('Private upstream diagnostic must never reach the client');
|
||||
return { data };
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
return {
|
||||
service,
|
||||
requests,
|
||||
routes: createAnalyticsRoutes({ logger, custom: { AnalyticsService: service } }),
|
||||
setData(value: unknown) {
|
||||
data = value;
|
||||
},
|
||||
fail(value = true) {
|
||||
failure = value;
|
||||
},
|
||||
advance(ms: number) {
|
||||
now += ms;
|
||||
},
|
||||
};
|
||||
}
|
||||
const post = (body: unknown) => ({
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const from = new Date('2024-01-01T00:00:00Z');
|
||||
const to = new Date('2024-02-01T00:00:00Z');
|
||||
|
||||
describe('analytics upstream contract and HTTP failure semantics', () => {
|
||||
test('outages never become zero metrics, equal weights, normal regimes, identity matrices or false model misses', async () => {
|
||||
const f = fixture();
|
||||
f.fail();
|
||||
for (const [path, options] of [
|
||||
[
|
||||
'/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString(),
|
||||
undefined,
|
||||
],
|
||||
['/risk/P', undefined],
|
||||
['/regime', undefined],
|
||||
['/optimize', post(optimize)],
|
||||
['/correlation', post({ symbols: ['A.US', 'B.US'] })],
|
||||
['/predict', post({ modelId: 'model', features: { x: 1 } })],
|
||||
] as const) {
|
||||
const response = await f.routes.request(path, options);
|
||||
expect(response.status).toBe(503);
|
||||
expect(await response.json()).toEqual({
|
||||
error: 'Analytics service is unavailable',
|
||||
code: 'analytics_unavailable',
|
||||
});
|
||||
}
|
||||
await expect(f.service.runBacktestAnalysis('run')).rejects.toBeInstanceOf(
|
||||
AnalyticsServiceError
|
||||
);
|
||||
expect(
|
||||
f.requests.every(request => request.timeout === 5000 && request.maxContentLength === 1048576)
|
||||
).toBe(true);
|
||||
const missing = await createAnalyticsRoutes({ logger }).request('/risk/P');
|
||||
expect(missing.status).toBe(503);
|
||||
});
|
||||
test('invalid upstream values are 502, not client 400, and never enter the success cache', async () => {
|
||||
const f = fixture({ ...performance, totalReturn: '0' });
|
||||
const path =
|
||||
'/performance/P?start_date=' + from.toISOString() + '&end_date=' + to.toISOString();
|
||||
const response = await f.routes.request(path);
|
||||
expect(response.status).toBe(502);
|
||||
expect((await response.json()).code).toBe('analytics_invalid_response');
|
||||
f.setData(performance);
|
||||
expect(await f.service.getPerformanceMetrics('P', from, to)).toEqual(performance);
|
||||
expect(f.requests).toHaveLength(2);
|
||||
const view = await f.service.getPerformanceMetrics('P', from, to);
|
||||
view.totalReturn = 100;
|
||||
expect((await f.service.getPerformanceMetrics('P', from, to)).totalReturn).toBe(0);
|
||||
f.setData({ ...performance, totalReturn: Infinity });
|
||||
f.advance(60000);
|
||||
await expect(f.service.getPerformanceMetrics('P', from, to)).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
test('cache expiration honors each entry TTL and expired failures never masquerade as fresh observations', async () => {
|
||||
const f = fixture({ regime: 'observed-bull' });
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bull');
|
||||
f.setData({ regime: 'observed-bear' });
|
||||
f.advance(60001);
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bull');
|
||||
expect(f.requests).toHaveLength(1);
|
||||
f.advance(240000);
|
||||
expect(await f.service.detectMarketRegime()).toBe('observed-bear');
|
||||
f.setData(risk);
|
||||
expect(await f.service.getRiskMetrics('P')).toEqual(risk);
|
||||
f.advance(60000);
|
||||
f.fail();
|
||||
await expect(f.service.getRiskMetrics('P')).rejects.toMatchObject({ status: 503 });
|
||||
f.fail(false);
|
||||
f.setData({ ...risk, dailyPnl: -10 });
|
||||
expect((await f.service.getRiskMetrics('P')).dailyPnl).toBe(-10);
|
||||
});
|
||||
test('success cache is bounded and identifiers are encoded rather than interpreted as paths', async () => {
|
||||
const f = fixture(risk);
|
||||
for (let i = 0; i < 129; i++) await f.service.getRiskMetrics(String(i));
|
||||
await f.service.getRiskMetrics('0');
|
||||
expect(f.requests).toHaveLength(130);
|
||||
await f.service.getRiskMetrics('A/B?secret');
|
||||
expect(f.requests.at(-1)?.url).toBe('http://analytics.fixture/analytics/risk/A%2FB%3Fsecret');
|
||||
});
|
||||
test('optimization forwards real symbol identities and maps the Python wire contract without fabricating weights', async () => {
|
||||
const f = fixture({
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: null,
|
||||
});
|
||||
const result = await f.service.optimizePortfolio(optimize);
|
||||
expect(result).toEqual({
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expectedReturn: 0.1,
|
||||
expectedRisk: 0.2,
|
||||
sharpeRatio: null,
|
||||
});
|
||||
expect(f.requests[0]?.data).toMatchObject({
|
||||
symbols: optimize.symbols,
|
||||
returns: optimize.returns,
|
||||
constraints: { min_weight: 0.1, max_weight: 0.9 },
|
||||
});
|
||||
for (const data of [
|
||||
{
|
||||
symbols: ['B.US', 'A.US'],
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
{
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.4],
|
||||
expected_return: 0.1,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
{
|
||||
symbols: optimize.symbols,
|
||||
weights: [0.4, 0.6],
|
||||
expected_return: NaN,
|
||||
expected_risk: 0.2,
|
||||
sharpe_ratio: 1,
|
||||
},
|
||||
]) {
|
||||
f.setData(data);
|
||||
await expect(f.service.optimizePortfolio(optimize)).rejects.toMatchObject({ status: 502 });
|
||||
}
|
||||
});
|
||||
test('correlations validate dimensions, ordered identities, symmetry, range and positive semidefiniteness', async () => {
|
||||
const f = fixture({
|
||||
symbols: ['A.US', 'B.US'],
|
||||
matrix: [
|
||||
[1, 0.5],
|
||||
[0.5, 1],
|
||||
],
|
||||
});
|
||||
expect(await f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).toEqual([
|
||||
[1, 0.5],
|
||||
[0.5, 1],
|
||||
]);
|
||||
expect(f.requests[0]?.data).toEqual(['A.US', 'B.US']);
|
||||
for (const matrix of [
|
||||
[[1]],
|
||||
[
|
||||
[1, 2],
|
||||
[2, 1],
|
||||
],
|
||||
[
|
||||
[1, 0.5],
|
||||
[0.2, 1],
|
||||
],
|
||||
[
|
||||
[0.9, 0],
|
||||
[0, 1],
|
||||
],
|
||||
[
|
||||
[1, NaN],
|
||||
[NaN, 1],
|
||||
],
|
||||
]) {
|
||||
f.setData({ symbols: ['A.US', 'B.US'], matrix });
|
||||
await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
}
|
||||
f.setData({
|
||||
symbols: ['A.US', 'B.US', 'C.US'],
|
||||
matrix: [
|
||||
[1, 0.9, 0.9],
|
||||
[0.9, 1, -0.9],
|
||||
[0.9, -0.9, 1],
|
||||
],
|
||||
});
|
||||
await expect(
|
||||
f.service.calculateCorrelationMatrix(['A.US', 'B.US', 'C.US'])
|
||||
).rejects.toMatchObject({ status: 502 });
|
||||
f.setData({
|
||||
symbols: ['B.US', 'A.US'],
|
||||
matrix: [
|
||||
[1, 0],
|
||||
[0, 1],
|
||||
],
|
||||
});
|
||||
await expect(f.service.calculateCorrelationMatrix(['A.US', 'B.US'])).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
});
|
||||
test('model and backtest responses validate identity, finite JSON and wire field names', async () => {
|
||||
const f = fixture({
|
||||
model_id: 'model',
|
||||
prediction: 0,
|
||||
probability: null,
|
||||
metadata: { version: 'v1' },
|
||||
});
|
||||
expect((await f.service.predictWithModel('model', { x: 1 })).prediction).toBe(0);
|
||||
expect(f.requests[0]?.data).toEqual({ model_id: 'model', features: { x: 1 } });
|
||||
f.setData({ model_id: 'wrong-model', prediction: 1 });
|
||||
await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
f.setData({ model_id: 'model', prediction: 1, metadata: { nested: { value: Infinity } } });
|
||||
await expect(f.service.predictWithModel('model', { x: 1 })).rejects.toMatchObject({
|
||||
status: 502,
|
||||
});
|
||||
f.setData({
|
||||
backtest_id: 'other',
|
||||
metrics: {},
|
||||
statistics: {},
|
||||
risk_analysis: {},
|
||||
trade_analysis: {},
|
||||
});
|
||||
await expect(f.service.runBacktestAnalysis('run')).rejects.toMatchObject({ status: 502 });
|
||||
});
|
||||
test('invalid client requests return 400 before upstream access', async () => {
|
||||
const f = fixture();
|
||||
for (const [path, options] of [
|
||||
[
|
||||
'/performance/P?start_date=' + to.toISOString() + '&end_date=' + from.toISOString(),
|
||||
undefined,
|
||||
],
|
||||
['/optimize', post({ ...optimize, returns: [[1], [2]] })],
|
||||
['/optimize', post({ ...optimize, constraints: { minWeight: 0.8 } })],
|
||||
['/correlation', post({ symbols: ['A.US', 'A.US'] })],
|
||||
['/predict', post({ modelId: '', features: { x: 1 } })],
|
||||
['/predict', { method: 'POST', body: '{broken' }],
|
||||
] as const)
|
||||
expect((await f.routes.request(path, options)).status).toBe(400);
|
||||
expect(f.requests).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
90
test/integration/analytics-ui.test.tsx
Normal file
90
test/integration/analytics-ui.test.tsx
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { createElement } from 'react';
|
||||
import { renderToStaticMarkup } from 'react-dom/server';
|
||||
import type { BacktestRunResult } from '@stock-bot/types';
|
||||
import { BacktestMetrics } from '../../apps/stock/web-app/src/features/backtest/components/BacktestMetrics';
|
||||
import { CompactPerformanceMetrics } from '../../apps/stock/web-app/src/features/backtest/components/CompactPerformanceMetrics';
|
||||
|
||||
const metrics = {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: null,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitableTrades: 0,
|
||||
profitFactor: null,
|
||||
calmarRatio: null,
|
||||
sortinoRatio: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
};
|
||||
const text = (html: string) => html.replace(/<[^>]*>/g, '');
|
||||
test('detailed metrics distinguish undefined ratios from legitimate zero return and exposure', () => {
|
||||
const html = renderToStaticMarkup(
|
||||
createElement(BacktestMetrics, {
|
||||
isLoading: false,
|
||||
result: {
|
||||
id: 'fixture',
|
||||
config: {
|
||||
name: 'fixture',
|
||||
startDate: new Date('2024-01-01'),
|
||||
endDate: new Date('2024-02-01'),
|
||||
initialCapital: 1000,
|
||||
symbols: ['A.US'],
|
||||
strategy: 'sma',
|
||||
speedMultiplier: 0,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
},
|
||||
metrics,
|
||||
positions: [],
|
||||
trades: [],
|
||||
performanceData: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
},
|
||||
})
|
||||
);
|
||||
const rendered = text(html);
|
||||
expect(rendered).toContain('Sharpe RatioN/A');
|
||||
expect(rendered).toContain('Profit FactorN/A');
|
||||
expect(rendered).toContain('Calmar RatioN/A');
|
||||
expect(rendered).toContain('Sortino RatioN/A');
|
||||
expect(rendered).toContain('Total Return0.00%');
|
||||
expect(rendered).toContain('Exposure Time0.0%');
|
||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
test('compact metrics preserve null ratios and render a genuine zero profit', () => {
|
||||
const result: BacktestRunResult = {
|
||||
runId: 'fixture',
|
||||
backtestId: 'fixture',
|
||||
engine: 'typescript',
|
||||
status: 'completed',
|
||||
completedAt: '2024-02-01T00:00:00Z',
|
||||
config: {
|
||||
name: 'fixture',
|
||||
strategy: 'sma',
|
||||
symbols: ['A.US'],
|
||||
startDate: '2024-01-01T00:00:00Z',
|
||||
endDate: '2024-02-01T00:00:00Z',
|
||||
initialCapital: 1000,
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
parameters: {},
|
||||
},
|
||||
metrics,
|
||||
equity: [],
|
||||
ohlcData: {},
|
||||
positions: [],
|
||||
trades: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
executionTime: 0,
|
||||
};
|
||||
const rendered = text(
|
||||
renderToStaticMarkup(createElement(CompactPerformanceMetrics, { result, isLoading: false }))
|
||||
);
|
||||
expect(rendered).toContain('Sharpe Ratio-');
|
||||
expect(rendered).toContain('Profit Factor-');
|
||||
expect(rendered).toContain('$0.00');
|
||||
expect(rendered).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
|
|
@ -311,7 +311,11 @@ describe('detached, repeatable backtest reporting', () => {
|
|||
expect(result.metrics.totalReturn).toBeCloseTo(-110);
|
||||
expect(result.metrics.maxDrawdown).toBe(1.1);
|
||||
expect(result.analytics.drawdownSeries.at(-1)?.value).toBeCloseTo(-110);
|
||||
expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true);
|
||||
expect(
|
||||
Object.values(result.analytics.riskMetrics).every(
|
||||
value => value === null || Number.isFinite(value)
|
||||
)
|
||||
).toBe(true);
|
||||
expect(result.analytics.dailyReturns.every(Number.isFinite)).toBe(true);
|
||||
});
|
||||
|
||||
|
|
@ -323,8 +327,15 @@ describe('detached, repeatable backtest reporting', () => {
|
|||
expect(result.equity).toEqual([{ date: new Date(start).toISOString(), value: 998 }]);
|
||||
expect(result.metrics.totalReturn).toBeCloseTo(-0.2);
|
||||
expect(result.metrics.maxDrawdown).toBeCloseTo(0.002);
|
||||
expect(result.analytics.dailyReturns).toEqual([]);
|
||||
expect(Object.values(result.analytics.riskMetrics).every(Number.isFinite)).toBe(true);
|
||||
expect(result.analytics.dailyReturns).toHaveLength(1);
|
||||
expect(result.analytics.dailyReturns[0]).toBeCloseTo(-0.2);
|
||||
expect(result.metrics.sharpeRatio).toBeNull();
|
||||
expect(result.metrics.annualizedReturn).toBeNull();
|
||||
expect(
|
||||
Object.values(result.analytics.riskMetrics).every(
|
||||
value => value === null || Number.isFinite(value)
|
||||
)
|
||||
).toBe(true);
|
||||
expect(Object.keys(result.ohlcData)).toEqual(config.symbols);
|
||||
expect(result.ohlcData['A.US']?.map(bar => bar.timestamp)).toEqual([
|
||||
start,
|
||||
|
|
@ -364,6 +375,27 @@ describe('detached, repeatable backtest reporting', () => {
|
|||
expect(losses.analytics.monthlyReturns).toEqual({ '2024-01': -100 });
|
||||
});
|
||||
|
||||
test('risk analytics and summary share fraction-based math without 100x percentage scaling', () => {
|
||||
const report = new BacktestReport(config, 'risk');
|
||||
let value = config.initialCapital;
|
||||
for (let i = 1; i <= 30; i++) {
|
||||
value *= 1 + (i % 2 ? -0.01 : 0.02);
|
||||
report.record(start + i * day, value);
|
||||
}
|
||||
const result = report.complete(dataset, [], [], {});
|
||||
const returns = result.analytics.dailyReturns.map(value => value / 100);
|
||||
const average = returns.reduce((sum, value) => sum + value, 0) / returns.length;
|
||||
const expected =
|
||||
Math.sqrt(
|
||||
returns.reduce((sum, value) => sum + (value - average) ** 2, 0) / (returns.length - 1)
|
||||
) * Math.sqrt(252);
|
||||
expect(result.analytics.riskMetrics.volatility).toBeCloseTo(expected, 10);
|
||||
const summary = JSON.parse(report.export()).summary;
|
||||
expect(summary.volatility / 100).toBeCloseTo(expected, 10);
|
||||
expect(summary.var95 / 100).toBeCloseTo(result.analytics.riskMetrics.var95!, 10);
|
||||
expect(summary.cvar95 / 100).toBeCloseTo(result.analytics.riskMetrics.cvar95!, 10);
|
||||
});
|
||||
|
||||
test('quality inspection groups symbols once without changing frozen inputs or retaining old warnings', () => {
|
||||
const input = structuredClone(dataset);
|
||||
for (const bar of input.bars.filter(bar => bar.timestamp === start + day)) {
|
||||
|
|
|
|||
|
|
@ -59,7 +59,8 @@ const config = BacktestConfigSchema.parse({
|
|||
|
||||
async function fixture(
|
||||
empty = false,
|
||||
engineOptions: ConstructorParameters<typeof RustBacktestAdapter>[1] = {}
|
||||
engineOptions: ConstructorParameters<typeof RustBacktestAdapter>[1] = {},
|
||||
barCount = 70
|
||||
) {
|
||||
// PostgreSQL protocol is replaced with an in-process database; SQL and transaction manager are real.
|
||||
const db = newDb();
|
||||
|
|
@ -108,7 +109,7 @@ async function fixture(
|
|||
await persistEodPrices(
|
||||
mongodb,
|
||||
{ symbol: 'FIXTURE', exchange: 'TEST', eodSearchCode: 'FIXTURE.TEST' },
|
||||
Array.from({ length: 70 }, (_, index) => {
|
||||
Array.from({ length: barCount }, (_, index) => {
|
||||
const close = 100 + Math.sin((index * Math.PI) / 6) * 8 + index * 0.02;
|
||||
return {
|
||||
date: new Date(Date.parse(config.startDate) + index * 86400000)
|
||||
|
|
@ -307,6 +308,26 @@ describe('one backtest execution workflow', () => {
|
|||
expect((await f.postgres.query('SELECT * FROM backtest_results')).rows).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('undefined one-timestamp statistics survive normalization, persistence and the public result reader as null', async () => {
|
||||
const f = await fixture(false, {}, 1);
|
||||
const services = await typescriptRuntime(f);
|
||||
const runner = services.custom!.BacktestRunner!;
|
||||
cleanup.unshift(async () => {
|
||||
await runner.shutdown();
|
||||
await services.custom?.ModeManager?.shutdown();
|
||||
});
|
||||
const result = await runner.runBacktest(config);
|
||||
expect(result.metrics.sharpeRatio).toBeNull();
|
||||
expect(result.metrics.profitFactor).toBeNull();
|
||||
expect(result.metrics.cagr).toBeNull();
|
||||
expect(result.metrics.annualizedReturn).toBeNull();
|
||||
expect(result.analytics.riskMetrics?.volatility).toBeNull();
|
||||
const saved = await new BacktestServiceV2(services).getRunResults(result.runId);
|
||||
expect(saved?.metrics).toEqual(result.metrics);
|
||||
expect(saved?.analytics).toEqual(result.analytics);
|
||||
expect(JSON.stringify(saved)).not.toMatch(/Infinity|NaN/);
|
||||
});
|
||||
|
||||
test('TypeScript cancellation is persisted without a partial success or completion event', async () => {
|
||||
const f = await fixture();
|
||||
const services = await typescriptRuntime(f);
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue