refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,454 +0,0 @@
|
|||
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
|
||||
/**
|
||||
* Basic Financial Calculations
|
||||
* Core mathematical functions for financial analysis
|
||||
*/
|
||||
|
||||
/**
|
||||
* Calculate percentage change between two values
|
||||
*/
|
||||
export function percentageChange(oldValue: number, newValue: number): number {
|
||||
if (oldValue === 0) {
|
||||
return 0;
|
||||
}
|
||||
return ((newValue - oldValue) / oldValue) * 100;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate simple return
|
||||
*/
|
||||
export function simpleReturn(initialPrice: number, finalPrice: number): number {
|
||||
if (initialPrice === 0) {
|
||||
return 0;
|
||||
}
|
||||
return (finalPrice - initialPrice) / initialPrice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate logarithmic return
|
||||
*/
|
||||
export function logReturn(initialPrice: number, finalPrice: number): number {
|
||||
if (initialPrice <= 0 || finalPrice <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.log(finalPrice / initialPrice);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate compound annual growth rate (CAGR)
|
||||
*/
|
||||
export function cagr(startValue: number, endValue: number, years: number): number {
|
||||
if (years <= 0 || startValue <= 0 || endValue <= 0) {
|
||||
return 0;
|
||||
}
|
||||
return Math.pow(endValue / startValue, 1 / years) - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate annualized return from periodic returns
|
||||
*/
|
||||
export function annualizeReturn(periodicReturn: number, periodsPerYear: number): number {
|
||||
return Math.pow(1 + periodicReturn, periodsPerYear) - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate annualized volatility from periodic returns
|
||||
*/
|
||||
export function annualizeVolatility(periodicVolatility: number, periodsPerYear: number): number {
|
||||
return periodicVolatility * Math.sqrt(periodsPerYear);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate present value
|
||||
*/
|
||||
export function presentValue(futureValue: number, rate: number, periods: number): number {
|
||||
return futureValue / Math.pow(1 + rate, periods);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate future value
|
||||
*/
|
||||
export function futureValue(presentValue: number, rate: number, periods: number): number {
|
||||
return presentValue * Math.pow(1 + rate, periods);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate net present value of cash flows
|
||||
*/
|
||||
export function netPresentValue(cashFlows: number[], discountRate: number): number {
|
||||
return cashFlows.reduce((npv, cashFlow, index) => {
|
||||
return npv + cashFlow / Math.pow(1 + discountRate, index);
|
||||
}, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate internal rate of return (IRR) using Newton-Raphson method
|
||||
*/
|
||||
export function internalRateOfReturn(
|
||||
cashFlows: number[],
|
||||
guess: number = 0.1,
|
||||
maxIterations: number = 100
|
||||
): number {
|
||||
let rate = guess;
|
||||
|
||||
for (let i = 0; i < maxIterations; i++) {
|
||||
let npv = 0;
|
||||
let dnpv = 0;
|
||||
|
||||
for (let j = 0; j < cashFlows.length; j++) {
|
||||
const cashFlow = cashFlows[j];
|
||||
if (cashFlow !== undefined) {
|
||||
npv += cashFlow / Math.pow(1 + rate, j);
|
||||
dnpv += (-j * cashFlow) / Math.pow(1 + rate, j + 1);
|
||||
}
|
||||
}
|
||||
|
||||
if (Math.abs(npv) < 1e-10) {
|
||||
break;
|
||||
}
|
||||
if (Math.abs(dnpv) < 1e-10) {
|
||||
break;
|
||||
}
|
||||
|
||||
rate = rate - npv / dnpv;
|
||||
}
|
||||
|
||||
return rate;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate payback period
|
||||
*/
|
||||
export function paybackPeriod(initialInvestment: number, cashFlows: number[]): number {
|
||||
let cumulativeCashFlow = 0;
|
||||
|
||||
for (let i = 0; i < cashFlows.length; i++) {
|
||||
const cashFlow = cashFlows[i];
|
||||
if (cashFlow !== undefined) {
|
||||
cumulativeCashFlow += cashFlow;
|
||||
if (cumulativeCashFlow >= initialInvestment) {
|
||||
return i + 1 - (cumulativeCashFlow - initialInvestment) / cashFlow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return -1; // Never pays back
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate compound interest
|
||||
*/
|
||||
export function compoundInterest(
|
||||
principal: number,
|
||||
rate: number,
|
||||
periods: number,
|
||||
compoundingFrequency: number = 1
|
||||
): number {
|
||||
return principal * Math.pow(1 + rate / compoundingFrequency, compoundingFrequency * periods);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate effective annual rate
|
||||
*/
|
||||
export function effectiveAnnualRate(nominalRate: number, compoundingFrequency: number): number {
|
||||
return Math.pow(1 + nominalRate / compoundingFrequency, compoundingFrequency) - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate bond price given yield
|
||||
*/
|
||||
export function bondPrice(
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
yieldToMaturity: number,
|
||||
periodsToMaturity: number,
|
||||
paymentsPerYear: number = 2
|
||||
): number {
|
||||
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
|
||||
const discountRate = yieldToMaturity / paymentsPerYear;
|
||||
|
||||
let price = 0;
|
||||
|
||||
// Present value of coupon payments
|
||||
for (let i = 1; i <= periodsToMaturity; i++) {
|
||||
price += couponPayment / Math.pow(1 + discountRate, i);
|
||||
}
|
||||
|
||||
// Present value of face value
|
||||
price += faceValue / Math.pow(1 + discountRate, periodsToMaturity);
|
||||
|
||||
return price;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate bond yield given price (Newton-Raphson approximation)
|
||||
*/
|
||||
export function bondYield(
|
||||
price: number,
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
periodsToMaturity: number,
|
||||
paymentsPerYear: number = 2,
|
||||
guess: number = 0.05
|
||||
): number {
|
||||
let yield_ = guess;
|
||||
const maxIterations = 100;
|
||||
const tolerance = 1e-8;
|
||||
|
||||
for (let i = 0; i < maxIterations; i++) {
|
||||
const calculatedPrice = bondPrice(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yield_,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
const diff = calculatedPrice - price;
|
||||
|
||||
if (Math.abs(diff) < tolerance) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Numerical derivative
|
||||
const delta = 0.0001;
|
||||
const priceUp = bondPrice(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yield_ + delta,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
const derivative = (priceUp - calculatedPrice) / delta;
|
||||
|
||||
if (Math.abs(derivative) < tolerance) {
|
||||
break;
|
||||
}
|
||||
|
||||
yield_ = yield_ - diff / derivative;
|
||||
}
|
||||
|
||||
return yield_;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate duration (Macaulay duration)
|
||||
*/
|
||||
export function macaulayDuration(
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
yieldToMaturity: number,
|
||||
periodsToMaturity: number,
|
||||
paymentsPerYear: number = 2
|
||||
): number {
|
||||
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
|
||||
const discountRate = yieldToMaturity / paymentsPerYear;
|
||||
const bondPriceValue = bondPrice(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yieldToMaturity,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
|
||||
let weightedTime = 0;
|
||||
|
||||
// Weighted time of coupon payments
|
||||
for (let i = 1; i <= periodsToMaturity; i++) {
|
||||
const presentValue = couponPayment / Math.pow(1 + discountRate, i);
|
||||
weightedTime += (i * presentValue) / bondPriceValue;
|
||||
}
|
||||
|
||||
// Weighted time of face value
|
||||
const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity);
|
||||
weightedTime += (periodsToMaturity * faceValuePV) / bondPriceValue;
|
||||
|
||||
return weightedTime / paymentsPerYear; // Convert to years
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate modified duration
|
||||
*/
|
||||
export function modifiedDuration(
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
yieldToMaturity: number,
|
||||
periodsToMaturity: number,
|
||||
paymentsPerYear: number = 2
|
||||
): number {
|
||||
const macDuration = macaulayDuration(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yieldToMaturity,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
return macDuration / (1 + yieldToMaturity / paymentsPerYear);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate bond convexity
|
||||
*/
|
||||
export function bondConvexity(
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
yieldToMaturity: number,
|
||||
periodsToMaturity: number,
|
||||
paymentsPerYear: number = 2
|
||||
): number {
|
||||
const couponPayment = (faceValue * couponRate) / paymentsPerYear;
|
||||
const discountRate = yieldToMaturity / paymentsPerYear;
|
||||
|
||||
let convexity = 0;
|
||||
const bondPriceValue = bondPrice(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yieldToMaturity,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
|
||||
for (let i = 1; i <= periodsToMaturity; i++) {
|
||||
const presentValue = couponPayment / Math.pow(1 + discountRate, i);
|
||||
convexity += (i * (i + 1) * presentValue) / Math.pow(1 + discountRate, 2);
|
||||
}
|
||||
|
||||
const faceValuePV = faceValue / Math.pow(1 + discountRate, periodsToMaturity);
|
||||
convexity +=
|
||||
(periodsToMaturity * (periodsToMaturity + 1) * faceValuePV) / Math.pow(1 + discountRate, 2);
|
||||
|
||||
return convexity / (bondPriceValue * paymentsPerYear * paymentsPerYear);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate dollar duration
|
||||
*/
|
||||
export function dollarDuration(
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
yieldToMaturity: number,
|
||||
periodsToMaturity: number,
|
||||
paymentsPerYear: number = 2,
|
||||
basisPointChange: number = 0.01 // 1 basis point = 0.01%
|
||||
): number {
|
||||
const modifiedDur = modifiedDuration(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yieldToMaturity,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
const bondPriceValue = bondPrice(
|
||||
faceValue,
|
||||
couponRate,
|
||||
yieldToMaturity,
|
||||
periodsToMaturity,
|
||||
paymentsPerYear
|
||||
);
|
||||
return modifiedDur * bondPriceValue * basisPointChange;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate accrued interest
|
||||
*/
|
||||
export function accruedInterest(
|
||||
faceValue: number,
|
||||
couponRate: number,
|
||||
daysSinceLastCoupon: number,
|
||||
daysInCouponPeriod: number
|
||||
): number {
|
||||
return faceValue * couponRate * (daysSinceLastCoupon / daysInCouponPeriod);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate clean price
|
||||
*/
|
||||
export function cleanPrice(dirtyPrice: number, accruedInterestValue: number): number {
|
||||
return dirtyPrice - accruedInterestValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate dirty price
|
||||
*/
|
||||
export function dirtyPrice(cleanPriceValue: number, accruedInterestValue: number): number {
|
||||
return cleanPriceValue + accruedInterestValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate dividend discount model (DDM)
|
||||
*/
|
||||
export function dividendDiscountModel(
|
||||
currentDividend: number,
|
||||
growthRate: number,
|
||||
discountRate: number
|
||||
): number {
|
||||
if (discountRate <= growthRate) {
|
||||
return NaN;
|
||||
} // Indeterminate
|
||||
return (currentDividend * (1 + growthRate)) / (discountRate - growthRate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate weighted average cost of capital (WACC)
|
||||
*/
|
||||
export function weightedAverageCostOfCapital(
|
||||
costOfEquity: number,
|
||||
costOfDebt: number,
|
||||
equityWeight: number,
|
||||
debtWeight: number,
|
||||
taxRate: number
|
||||
): number {
|
||||
return equityWeight * costOfEquity + debtWeight * costOfDebt * (1 - taxRate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate capital asset pricing model (CAPM)
|
||||
*/
|
||||
export function capitalAssetPricingModel(
|
||||
riskFreeRate: number,
|
||||
beta: number,
|
||||
marketRiskPremium: number
|
||||
): number {
|
||||
return riskFreeRate + beta * marketRiskPremium;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate hurdle rate
|
||||
*/
|
||||
export function hurdleRate(costOfCapital: number, riskPremium: number): number {
|
||||
return costOfCapital + riskPremium;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate degree of operating leverage (DOL)
|
||||
*/
|
||||
export function degreeOfOperatingLeverage(
|
||||
contributionMargin: number,
|
||||
operatingIncome: number
|
||||
): number {
|
||||
return contributionMargin / operatingIncome;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate degree of financial leverage (DFL)
|
||||
*/
|
||||
export function degreeOfFinancialLeverage(ebit: number, earningsBeforeTax: number): number {
|
||||
return ebit / earningsBeforeTax;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate degree of total leverage (DTL)
|
||||
*/
|
||||
export function degreeOfTotalLeverage(dol: number, dfl: number): number {
|
||||
return dol * dfl;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate economic value added (EVA)
|
||||
*/
|
||||
export function economicValueAdded(
|
||||
netOperatingProfitAfterTax: number,
|
||||
capitalInvested: number,
|
||||
wacc: number
|
||||
): number {
|
||||
return netOperatingProfitAfterTax - capitalInvested * wacc;
|
||||
}
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
/** Opt-in historical APIs, not aliases for the reviewed core. See the package migration notes. */
|
||||
export * as basic from './basic-calculations';
|
||||
export * as indicators from './technical-indicators';
|
||||
export * as risk from './risk-metrics';
|
||||
export * as performance from './performance-metrics';
|
||||
|
|
@ -1,941 +0,0 @@
|
|||
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
|
||||
import { ulcerIndex } from './risk-metrics';
|
||||
|
||||
/**
|
||||
* Performance Metrics and Analysis
|
||||
* Comprehensive performance measurement tools for trading strategies and portfolios
|
||||
*/
|
||||
|
||||
// import type { PortfolioMetrics } from '@stock-bot/types';
|
||||
|
||||
// Define PortfolioMetrics locally until it's added to types library
|
||||
export interface PortfolioMetrics {
|
||||
totalValue: number;
|
||||
totalReturn: number;
|
||||
totalReturnPercent: number;
|
||||
dailyReturn: number;
|
||||
dailyReturnPercent: number;
|
||||
maxDrawdown: number;
|
||||
sharpeRatio: number;
|
||||
beta: number;
|
||||
alpha: number;
|
||||
volatility: number;
|
||||
}
|
||||
|
||||
export interface TradePerformance {
|
||||
totalTrades: number;
|
||||
winningTrades: number;
|
||||
losingTrades: number;
|
||||
winRate: number;
|
||||
averageWin: number;
|
||||
averageLoss: number;
|
||||
largestWin: number;
|
||||
largestLoss: number;
|
||||
profitFactor: number;
|
||||
expectancy: number;
|
||||
averageTradeReturn: number;
|
||||
consecutiveWins: number;
|
||||
consecutiveLosses: number;
|
||||
}
|
||||
|
||||
export interface DrawdownAnalysis {
|
||||
maxDrawdown: number;
|
||||
maxDrawdownDuration: number;
|
||||
averageDrawdown: number;
|
||||
drawdownPeriods: Array<{
|
||||
start: Date;
|
||||
end: Date;
|
||||
duration: number;
|
||||
magnitude: number;
|
||||
}>;
|
||||
}
|
||||
|
||||
export interface ReturnAnalysis {
|
||||
totalReturn: number;
|
||||
annualizedReturn: number;
|
||||
compoundAnnualGrowthRate: number;
|
||||
volatility: number;
|
||||
annualizedVolatility: number;
|
||||
skewness: number;
|
||||
kurtosis: number;
|
||||
bestMonth: number;
|
||||
worstMonth: number;
|
||||
positiveMonths: number;
|
||||
negativeMonths: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate comprehensive trade performance metrics
|
||||
*/
|
||||
export function analyzeTradePerformance(
|
||||
trades: Array<{ pnl: number; date: Date }>
|
||||
): TradePerformance {
|
||||
if (trades.length === 0) {
|
||||
return {
|
||||
totalTrades: 0,
|
||||
winningTrades: 0,
|
||||
losingTrades: 0,
|
||||
winRate: 0,
|
||||
averageWin: 0,
|
||||
averageLoss: 0,
|
||||
largestWin: 0,
|
||||
largestLoss: 0,
|
||||
profitFactor: 0,
|
||||
expectancy: 0,
|
||||
averageTradeReturn: 0,
|
||||
consecutiveWins: 0,
|
||||
consecutiveLosses: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const winningTrades = trades.filter(trade => trade.pnl > 0);
|
||||
const losingTrades = trades.filter(trade => trade.pnl < 0);
|
||||
|
||||
const totalWins = winningTrades.reduce((sum, trade) => sum + trade.pnl, 0);
|
||||
const totalLosses = Math.abs(losingTrades.reduce((sum, trade) => sum + trade.pnl, 0));
|
||||
|
||||
const averageWin = winningTrades.length > 0 ? totalWins / winningTrades.length : 0;
|
||||
const averageLoss = losingTrades.length > 0 ? totalLosses / losingTrades.length : 0;
|
||||
|
||||
const largestWin = winningTrades.length > 0 ? Math.max(...winningTrades.map(t => t.pnl)) : 0;
|
||||
const largestLoss = losingTrades.length > 0 ? Math.min(...losingTrades.map(t => t.pnl)) : 0;
|
||||
|
||||
const profitFactor = totalLosses > 0 ? totalWins / totalLosses : totalWins > 0 ? Infinity : 0;
|
||||
const winRate = winningTrades.length / trades.length;
|
||||
const expectancy = winRate * averageWin - (1 - winRate) * averageLoss;
|
||||
|
||||
const totalPnL = trades.reduce((sum, trade) => sum + trade.pnl, 0);
|
||||
const averageTradeReturn = totalPnL / trades.length;
|
||||
|
||||
// Calculate consecutive wins/losses
|
||||
let consecutiveWins = 0;
|
||||
let consecutiveLosses = 0;
|
||||
let currentWinStreak = 0;
|
||||
let currentLossStreak = 0;
|
||||
|
||||
for (const trade of trades) {
|
||||
if (trade.pnl > 0) {
|
||||
currentWinStreak++;
|
||||
currentLossStreak = 0;
|
||||
consecutiveWins = Math.max(consecutiveWins, currentWinStreak);
|
||||
} else if (trade.pnl < 0) {
|
||||
currentLossStreak++;
|
||||
currentWinStreak = 0;
|
||||
consecutiveLosses = Math.max(consecutiveLosses, currentLossStreak);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
totalTrades: trades.length,
|
||||
winningTrades: winningTrades.length,
|
||||
losingTrades: losingTrades.length,
|
||||
winRate,
|
||||
averageWin,
|
||||
averageLoss,
|
||||
largestWin,
|
||||
largestLoss,
|
||||
profitFactor,
|
||||
expectancy,
|
||||
averageTradeReturn,
|
||||
consecutiveWins,
|
||||
consecutiveLosses,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze drawdown characteristics
|
||||
*/
|
||||
export function analyzeDrawdowns(
|
||||
equityCurve: Array<{ value: number; date: Date }>
|
||||
): DrawdownAnalysis {
|
||||
if (equityCurve.length < 2) {
|
||||
return {
|
||||
maxDrawdown: 0,
|
||||
maxDrawdownDuration: 0,
|
||||
averageDrawdown: 0,
|
||||
drawdownPeriods: [],
|
||||
};
|
||||
}
|
||||
|
||||
const first = equityCurve[0];
|
||||
if (!first) {
|
||||
return { maxDrawdown: 0, maxDrawdownDuration: 0, averageDrawdown: 0, drawdownPeriods: [] };
|
||||
}
|
||||
|
||||
let peak = first.value;
|
||||
let peakDate = first.date;
|
||||
let maxDrawdown = 0;
|
||||
let maxDrawdownDuration = 0;
|
||||
|
||||
const drawdownPeriods: Array<{
|
||||
start: Date;
|
||||
end: Date;
|
||||
duration: number;
|
||||
magnitude: number;
|
||||
}> = [];
|
||||
|
||||
let currentDrawdownStart: Date | null = null;
|
||||
const drawdowns: number[] = [];
|
||||
|
||||
for (let i = 1; i < equityCurve.length; i++) {
|
||||
const current = equityCurve[i];
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current.value > peak) {
|
||||
// New peak - end any current drawdown
|
||||
if (currentDrawdownStart) {
|
||||
const prev = equityCurve[i - 1];
|
||||
if (!prev) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const drawdownMagnitude = (peak - prev.value) / peak;
|
||||
const duration = Math.floor(
|
||||
(prev.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24)
|
||||
);
|
||||
|
||||
drawdownPeriods.push({
|
||||
start: currentDrawdownStart,
|
||||
end: prev.date,
|
||||
duration,
|
||||
magnitude: drawdownMagnitude,
|
||||
});
|
||||
|
||||
drawdowns.push(drawdownMagnitude);
|
||||
maxDrawdownDuration = Math.max(maxDrawdownDuration, duration);
|
||||
currentDrawdownStart = null;
|
||||
}
|
||||
|
||||
peak = current.value;
|
||||
peakDate = current.date;
|
||||
} else {
|
||||
// In drawdown
|
||||
if (!currentDrawdownStart) {
|
||||
currentDrawdownStart = peakDate;
|
||||
}
|
||||
|
||||
const drawdown = (peak - current.value) / peak;
|
||||
maxDrawdown = Math.max(maxDrawdown, drawdown);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle ongoing drawdown
|
||||
if (currentDrawdownStart) {
|
||||
const lastPoint = equityCurve[equityCurve.length - 1];
|
||||
if (!lastPoint) {
|
||||
return { maxDrawdown, maxDrawdownDuration, averageDrawdown: 0, drawdownPeriods };
|
||||
}
|
||||
|
||||
const drawdownMagnitude = (peak - lastPoint.value) / peak;
|
||||
const duration = Math.floor(
|
||||
(lastPoint.date.getTime() - currentDrawdownStart.getTime()) / (1000 * 60 * 60 * 24)
|
||||
);
|
||||
|
||||
drawdownPeriods.push({
|
||||
start: currentDrawdownStart,
|
||||
end: lastPoint.date,
|
||||
duration,
|
||||
magnitude: drawdownMagnitude,
|
||||
});
|
||||
|
||||
drawdowns.push(drawdownMagnitude);
|
||||
maxDrawdownDuration = Math.max(maxDrawdownDuration, duration);
|
||||
}
|
||||
|
||||
const averageDrawdown =
|
||||
drawdowns.length > 0 ? drawdowns.reduce((sum, dd) => sum + dd, 0) / drawdowns.length : 0;
|
||||
|
||||
return {
|
||||
maxDrawdown,
|
||||
maxDrawdownDuration,
|
||||
averageDrawdown,
|
||||
drawdownPeriods,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Analyze return characteristics
|
||||
*/
|
||||
export function analyzeReturns(
|
||||
returns: Array<{ return: number; date: Date }>,
|
||||
periodsPerYear: number = 252
|
||||
): ReturnAnalysis {
|
||||
if (returns.length === 0) {
|
||||
return {
|
||||
totalReturn: 0,
|
||||
annualizedReturn: 0,
|
||||
compoundAnnualGrowthRate: 0,
|
||||
volatility: 0,
|
||||
annualizedVolatility: 0,
|
||||
skewness: 0,
|
||||
kurtosis: 0,
|
||||
bestMonth: 0,
|
||||
worstMonth: 0,
|
||||
positiveMonths: 0,
|
||||
negativeMonths: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const returnValues = returns.map(r => r.return);
|
||||
|
||||
// Calculate basic statistics
|
||||
const totalReturn = returnValues.reduce((product, ret) => product * (1 + ret), 1) - 1;
|
||||
const averageReturn = returnValues.reduce((sum, ret) => sum + ret, 0) / returnValues.length;
|
||||
const annualizedReturn = Math.pow(1 + averageReturn, periodsPerYear) - 1;
|
||||
|
||||
// Calculate CAGR
|
||||
const years = returns.length / periodsPerYear;
|
||||
const cagr = years > 0 ? Math.pow(1 + totalReturn, 1 / years) - 1 : 0;
|
||||
|
||||
// Calculate volatility
|
||||
const variance =
|
||||
returnValues.reduce((sum, ret) => sum + Math.pow(ret - averageReturn, 2), 0) /
|
||||
(returnValues.length - 1);
|
||||
const volatility = Math.sqrt(variance);
|
||||
const annualizedVolatility = volatility * Math.sqrt(periodsPerYear);
|
||||
|
||||
// Calculate skewness and kurtosis
|
||||
const skewness = calculateSkewness(returnValues);
|
||||
const kurtosis = calculateKurtosis(returnValues);
|
||||
|
||||
// Monthly analysis
|
||||
const monthlyReturns = aggregateMonthlyReturns(returns);
|
||||
const bestMonth = monthlyReturns.length > 0 ? Math.max(...monthlyReturns) : 0;
|
||||
const worstMonth = monthlyReturns.length > 0 ? Math.min(...monthlyReturns) : 0;
|
||||
const positiveMonths = monthlyReturns.filter(ret => ret > 0).length;
|
||||
const negativeMonths = monthlyReturns.filter(ret => ret < 0).length;
|
||||
|
||||
return {
|
||||
totalReturn,
|
||||
annualizedReturn,
|
||||
compoundAnnualGrowthRate: cagr,
|
||||
volatility,
|
||||
annualizedVolatility,
|
||||
skewness,
|
||||
kurtosis,
|
||||
bestMonth,
|
||||
worstMonth,
|
||||
positiveMonths,
|
||||
negativeMonths,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate rolling performance metrics
|
||||
*/
|
||||
export function calculateRollingMetrics(
|
||||
returns: number[],
|
||||
windowSize: number,
|
||||
metricType: 'sharpe' | 'volatility' | 'return' = 'sharpe'
|
||||
): number[] {
|
||||
if (returns.length < windowSize) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rollingMetrics: number[] = [];
|
||||
|
||||
for (let i = windowSize - 1; i < returns.length; i++) {
|
||||
const window = returns.slice(i - windowSize + 1, i + 1);
|
||||
|
||||
switch (metricType) {
|
||||
case 'sharpe':
|
||||
rollingMetrics.push(calculateSharpeRatio(window));
|
||||
break;
|
||||
case 'volatility':
|
||||
rollingMetrics.push(calculateVolatility(window));
|
||||
break;
|
||||
case 'return': {
|
||||
const avgReturn = window.reduce((sum, ret) => sum + ret, 0) / window.length;
|
||||
rollingMetrics.push(avgReturn);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return rollingMetrics;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate performance attribution
|
||||
*/
|
||||
export function strategyPerformanceAttribution(
|
||||
portfolioReturns: number[],
|
||||
benchmarkReturns: number[],
|
||||
sectorWeights: number[],
|
||||
sectorReturns: number[]
|
||||
): {
|
||||
allocationEffect: number;
|
||||
selectionEffect: number;
|
||||
interactionEffect: number;
|
||||
totalActiveReturn: number;
|
||||
} {
|
||||
if (portfolioReturns.length !== benchmarkReturns.length) {
|
||||
throw new Error('Portfolio and benchmark returns must have same length');
|
||||
}
|
||||
|
||||
const portfolioReturn =
|
||||
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
|
||||
const benchmarkReturn =
|
||||
benchmarkReturns.reduce((sum, ret) => sum + ret, 0) / benchmarkReturns.length;
|
||||
|
||||
let allocationEffect = 0;
|
||||
let selectionEffect = 0;
|
||||
let interactionEffect = 0;
|
||||
|
||||
for (let i = 0; i < sectorWeights.length; i++) {
|
||||
const portfolioWeight = sectorWeights[i];
|
||||
const sectorReturn = sectorReturns[i];
|
||||
if (portfolioWeight === undefined || sectorReturn === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const benchmarkWeight = 1 / sectorWeights.length; // Assuming equal benchmark weights
|
||||
|
||||
// Allocation effect: (portfolio weight - benchmark weight) * (benchmark sector return - benchmark return)
|
||||
allocationEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - benchmarkReturn);
|
||||
|
||||
// Selection effect: benchmark weight * (portfolio sector return - benchmark sector return)
|
||||
selectionEffect += benchmarkWeight * (sectorReturn - sectorReturn); // Simplified
|
||||
|
||||
// Interaction effect: (portfolio weight - benchmark weight) * (portfolio sector return - benchmark sector return)
|
||||
interactionEffect += (portfolioWeight - benchmarkWeight) * (sectorReturn - sectorReturn); // Simplified
|
||||
}
|
||||
|
||||
const totalActiveReturn = portfolioReturn - benchmarkReturn;
|
||||
|
||||
return {
|
||||
allocationEffect,
|
||||
selectionEffect,
|
||||
interactionEffect,
|
||||
totalActiveReturn,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Omega ratio
|
||||
*/
|
||||
export function omegaRatio(returns: number[], threshold: number = 0): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const gains = returns
|
||||
.filter(ret => ret > threshold)
|
||||
.reduce((sum, ret) => sum + (ret - threshold), 0);
|
||||
const losses = returns
|
||||
.filter(ret => ret < threshold)
|
||||
.reduce((sum, ret) => sum + Math.abs(ret - threshold), 0);
|
||||
|
||||
return losses === 0 ? Infinity : gains / losses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate gain-to-pain ratio
|
||||
*/
|
||||
export function gainToPainRatio(returns: number[]): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const totalGain = returns.reduce((sum, ret) => sum + ret, 0);
|
||||
const totalPain = returns.filter(ret => ret < 0).reduce((sum, ret) => sum + Math.abs(ret), 0);
|
||||
|
||||
return totalPain === 0 ? (totalGain > 0 ? Infinity : 0) : totalGain / totalPain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Martin ratio (modified Sharpe with downside deviation)
|
||||
*/
|
||||
export function martinRatio(returns: number[], riskFreeRate: number = 0): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const averageReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const downsideReturns = returns.filter(ret => ret < riskFreeRate);
|
||||
|
||||
if (downsideReturns.length === 0) {
|
||||
return Infinity;
|
||||
}
|
||||
|
||||
const downsideDeviation = Math.sqrt(
|
||||
downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length
|
||||
);
|
||||
|
||||
return downsideDeviation === 0 ? Infinity : (averageReturn - riskFreeRate) / downsideDeviation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate comprehensive portfolio metrics
|
||||
*/
|
||||
export function calculateStrategyMetrics(
|
||||
equityCurve: Array<{ value: number; date: Date }>,
|
||||
benchmarkReturns?: number[],
|
||||
riskFreeRate: number = 0.02
|
||||
): PortfolioMetrics {
|
||||
if (equityCurve.length < 2) {
|
||||
return {
|
||||
totalValue: 0,
|
||||
totalReturn: 0,
|
||||
totalReturnPercent: 0,
|
||||
dailyReturn: 0,
|
||||
dailyReturnPercent: 0,
|
||||
maxDrawdown: 0,
|
||||
sharpeRatio: 0,
|
||||
beta: 0,
|
||||
alpha: 0,
|
||||
volatility: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const returns = [];
|
||||
for (let i = 1; i < equityCurve.length; i++) {
|
||||
const current = equityCurve[i];
|
||||
const previous = equityCurve[i - 1];
|
||||
if (!current || !previous) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const ret = (current.value - previous.value) / previous.value;
|
||||
returns.push(ret);
|
||||
}
|
||||
|
||||
const lastPoint = equityCurve[equityCurve.length - 1];
|
||||
const firstPoint = equityCurve[0];
|
||||
if (!lastPoint || !firstPoint) {
|
||||
return {
|
||||
totalValue: 0,
|
||||
totalReturn: 0,
|
||||
totalReturnPercent: 0,
|
||||
dailyReturn: 0,
|
||||
dailyReturnPercent: 0,
|
||||
maxDrawdown: 0,
|
||||
sharpeRatio: 0,
|
||||
beta: 0,
|
||||
alpha: 0,
|
||||
volatility: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const totalValue = lastPoint.value;
|
||||
const totalReturn = totalValue - firstPoint.value;
|
||||
const totalReturnPercent = (totalReturn / firstPoint.value) * 100;
|
||||
|
||||
const dailyReturn = returns[returns.length - 1] || 0;
|
||||
const dailyReturnPercent = dailyReturn * 100;
|
||||
|
||||
const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown;
|
||||
const sharpeRatio = calculateSharpeRatio(returns, riskFreeRate);
|
||||
const volatility = calculateVolatility(returns);
|
||||
|
||||
let beta = 0;
|
||||
let alpha = 0;
|
||||
|
||||
if (benchmarkReturns && benchmarkReturns.length === returns.length) {
|
||||
beta = calculateBeta(returns, benchmarkReturns);
|
||||
alpha = calculateAlpha(returns, benchmarkReturns, riskFreeRate);
|
||||
}
|
||||
|
||||
return {
|
||||
totalValue,
|
||||
totalReturn,
|
||||
totalReturnPercent,
|
||||
dailyReturn,
|
||||
dailyReturnPercent,
|
||||
maxDrawdown,
|
||||
sharpeRatio,
|
||||
beta,
|
||||
alpha,
|
||||
volatility,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Calmar Ratio
|
||||
*/
|
||||
export function calmarRatio(
|
||||
returns: number[],
|
||||
equityCurve: Array<{ value: number; date: Date }>,
|
||||
riskFreeRate: number = 0
|
||||
): number {
|
||||
const maxDrawdown = analyzeDrawdowns(equityCurve).maxDrawdown;
|
||||
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
|
||||
return maxDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / maxDrawdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Sterling Ratio
|
||||
*/
|
||||
export function sterlingRatio(
|
||||
returns: number[],
|
||||
equityCurve: Array<{ value: number; date: Date }>,
|
||||
riskFreeRate: number = 0
|
||||
): number {
|
||||
const averageDrawdown = analyzeDrawdowns(equityCurve).averageDrawdown;
|
||||
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
|
||||
return averageDrawdown === 0 ? 0 : (avgReturn - riskFreeRate) / averageDrawdown;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Information Ratio
|
||||
*/
|
||||
export function informationRatio(portfolioReturns: number[], benchmarkReturns: number[]): number {
|
||||
if (portfolioReturns.length !== benchmarkReturns.length) {
|
||||
throw new Error('Portfolio and benchmark returns must have the same length.');
|
||||
}
|
||||
|
||||
const excessReturns = portfolioReturns.map((portfolioReturn, index) => {
|
||||
const benchmark = benchmarkReturns[index];
|
||||
return benchmark !== undefined ? portfolioReturn - benchmark : 0;
|
||||
});
|
||||
const trackingError = calculateVolatility(excessReturns);
|
||||
const avgExcessReturn = excessReturns.reduce((sum, ret) => sum + ret, 0) / excessReturns.length;
|
||||
|
||||
return trackingError === 0 ? 0 : avgExcessReturn / trackingError;
|
||||
}
|
||||
|
||||
// Treynor Ratio is already exported from risk-metrics
|
||||
|
||||
/**
|
||||
* Calculate Jensen's Alpha (same as Alpha, but included for clarity)
|
||||
*/
|
||||
export function jensensAlpha(
|
||||
portfolioReturns: number[],
|
||||
marketReturns: number[],
|
||||
riskFreeRate: number
|
||||
): number {
|
||||
return calculateAlpha(portfolioReturns, marketReturns, riskFreeRate);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Capture Ratio (Up Capture and Down Capture)
|
||||
*/
|
||||
export function captureRatio(
|
||||
portfolioReturns: number[],
|
||||
benchmarkReturns: number[]
|
||||
): { upCaptureRatio: number; downCaptureRatio: number } {
|
||||
let upCapture = 0;
|
||||
let downCapture = 0;
|
||||
let upMarketPeriods = 0;
|
||||
let downMarketPeriods = 0;
|
||||
|
||||
for (let i = 0; i < portfolioReturns.length; i++) {
|
||||
const benchmarkReturn = benchmarkReturns[i];
|
||||
const portfolioReturn = portfolioReturns[i];
|
||||
if (benchmarkReturn === undefined || portfolioReturn === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (benchmarkReturn > 0) {
|
||||
upCapture += portfolioReturn;
|
||||
upMarketPeriods++;
|
||||
} else if (benchmarkReturn < 0) {
|
||||
downCapture += portfolioReturn;
|
||||
downMarketPeriods++;
|
||||
}
|
||||
}
|
||||
|
||||
const upCaptureRatio =
|
||||
upMarketPeriods > 0
|
||||
? upCapture /
|
||||
upMarketPeriods /
|
||||
(benchmarkReturns.filter(r => r > 0).reduce((sum, r) => sum + r, 0) / upMarketPeriods)
|
||||
: 0;
|
||||
const downCaptureRatio =
|
||||
downMarketPeriods > 0
|
||||
? downCapture /
|
||||
downMarketPeriods /
|
||||
(benchmarkReturns.filter(r => r < 0).reduce((sum, r) => sum + r, 0) / downMarketPeriods)
|
||||
: 0;
|
||||
|
||||
return { upCaptureRatio, downCaptureRatio };
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Sortino Ratio
|
||||
*/
|
||||
export function sortinoRatio(returns: number[], riskFreeRate: number = 0): number {
|
||||
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const downsideReturns = returns.filter(ret => ret < riskFreeRate);
|
||||
const downsideDeviation = Math.sqrt(
|
||||
downsideReturns.reduce((sum, ret) => sum + Math.pow(ret - riskFreeRate, 2), 0) / returns.length
|
||||
);
|
||||
|
||||
return downsideDeviation === 0 ? 0 : (avgReturn - riskFreeRate) / downsideDeviation;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Tail Ratio
|
||||
*/
|
||||
export function tailRatio(returns: number[], tailPercent: number = 0.1): number {
|
||||
const numReturns = returns.length;
|
||||
const tailSize = Math.floor(numReturns * tailPercent);
|
||||
|
||||
if (tailSize === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sortedReturns = [...returns].sort((a, b) => a - b);
|
||||
const worstTail = sortedReturns.slice(0, tailSize);
|
||||
const bestTail = sortedReturns.slice(numReturns - tailSize);
|
||||
|
||||
const avgWorst = worstTail.reduce((sum, ret) => sum + ret, 0) / tailSize;
|
||||
const avgBest = bestTail.reduce((sum, ret) => sum + ret, 0) / tailSize;
|
||||
|
||||
return avgWorst === 0 ? 0 : avgBest / Math.abs(avgWorst);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Rolling Beta
|
||||
*/
|
||||
export function calculateRollingBeta(
|
||||
portfolioReturns: number[],
|
||||
marketReturns: number[],
|
||||
windowSize: number
|
||||
): number[] {
|
||||
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rollingBetas: number[] = [];
|
||||
|
||||
for (let i = windowSize; i <= portfolioReturns.length; i++) {
|
||||
const portfolioWindow = portfolioReturns.slice(i - windowSize, i);
|
||||
const marketWindow = marketReturns.slice(i - windowSize, i);
|
||||
rollingBetas.push(calculateBeta(portfolioWindow, marketWindow));
|
||||
}
|
||||
|
||||
return rollingBetas;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Ulcer Performance Index (UPI)
|
||||
*/
|
||||
export function ulcerPerformanceIndex(
|
||||
returns: number[],
|
||||
equityCurve: Array<{ value: number; date: Date }>,
|
||||
riskFreeRate: number = 0
|
||||
): number {
|
||||
const ui = ulcerIndex(equityCurve);
|
||||
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
|
||||
return ui === 0 ? 0 : (avgReturn - riskFreeRate) / ui;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Rolling Alpha
|
||||
*/
|
||||
export function calculateRollingAlpha(
|
||||
portfolioReturns: number[],
|
||||
marketReturns: number[],
|
||||
riskFreeRate: number,
|
||||
windowSize: number
|
||||
): number[] {
|
||||
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < windowSize) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const rollingAlphas: number[] = [];
|
||||
|
||||
for (let i = windowSize; i <= portfolioReturns.length; i++) {
|
||||
const portfolioWindow = portfolioReturns.slice(i - windowSize, i);
|
||||
const marketWindow = marketReturns.slice(i - windowSize, i);
|
||||
rollingAlphas.push(calculateAlpha(portfolioWindow, marketWindow, riskFreeRate));
|
||||
}
|
||||
|
||||
return rollingAlphas;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Time Weighted Rate of Return (TWRR)
|
||||
*/
|
||||
export function timeWeightedRateOfReturn(
|
||||
cashFlows: Array<{ amount: number; date: Date; value: number }>
|
||||
): number {
|
||||
if (cashFlows.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const first = cashFlows[0];
|
||||
if (!first) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let totalReturn = 1;
|
||||
let previousValue = first.value;
|
||||
|
||||
for (let i = 1; i < cashFlows.length; i++) {
|
||||
const current = cashFlows[i];
|
||||
if (!current) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const periodReturn =
|
||||
(current.value - previousValue - current.amount) / (previousValue + current.amount);
|
||||
totalReturn *= 1 + periodReturn;
|
||||
previousValue = current.value;
|
||||
}
|
||||
|
||||
return totalReturn - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Money Weighted Rate of Return (MWRR) - Approximation using IRR
|
||||
*/
|
||||
export function moneyWeightedRateOfReturn(
|
||||
cashFlows: Array<{ amount: number; date: Date; value: number }>
|
||||
): number {
|
||||
if (cashFlows.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const first = cashFlows[0];
|
||||
if (!first) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Approximate MWRR using Internal Rate of Return (IRR)
|
||||
// This requires a numerical method or library for accurate IRR calculation
|
||||
// This is a simplified example and may not be accurate for all cases
|
||||
|
||||
let totalCashFlow = 0;
|
||||
let totalWeightedCashFlow = 0;
|
||||
const startDate = first.date.getTime();
|
||||
|
||||
for (const cf of cashFlows) {
|
||||
const timeDiff = (cf.date.getTime() - startDate) / (1000 * 60 * 60 * 24 * 365); // Years
|
||||
totalCashFlow += cf.amount;
|
||||
totalWeightedCashFlow += cf.amount * timeDiff;
|
||||
}
|
||||
|
||||
// Simplified approximation: MWRR ≈ totalCashFlow / totalWeightedCashFlow - 1
|
||||
return totalWeightedCashFlow === 0 ? 0 : totalCashFlow / totalWeightedCashFlow - 1;
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
function calculateSharpeRatio(returns: number[], riskFreeRate: number = 0): number {
|
||||
if (returns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const avgReturn = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance =
|
||||
returns.reduce((sum, ret) => sum + Math.pow(ret - avgReturn, 2), 0) / (returns.length - 1);
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
return stdDev === 0 ? 0 : (avgReturn - riskFreeRate) / stdDev;
|
||||
}
|
||||
|
||||
function calculateVolatility(returns: number[]): number {
|
||||
if (returns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance =
|
||||
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
|
||||
|
||||
return Math.sqrt(variance);
|
||||
}
|
||||
|
||||
function calculateBeta(portfolioReturns: number[], marketReturns: number[]): number {
|
||||
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const portfolioMean =
|
||||
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
|
||||
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
|
||||
|
||||
let covariance = 0;
|
||||
let marketVariance = 0;
|
||||
|
||||
for (let i = 0; i < portfolioReturns.length; i++) {
|
||||
const portfolioReturn = portfolioReturns[i];
|
||||
const marketReturn = marketReturns[i];
|
||||
if (portfolioReturn === undefined || marketReturn === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const portfolioDiff = portfolioReturn - portfolioMean;
|
||||
const marketDiff = marketReturn - marketMean;
|
||||
|
||||
covariance += portfolioDiff * marketDiff;
|
||||
marketVariance += marketDiff * marketDiff;
|
||||
}
|
||||
|
||||
covariance /= portfolioReturns.length - 1;
|
||||
marketVariance /= marketReturns.length - 1;
|
||||
|
||||
return marketVariance === 0 ? 0 : covariance / marketVariance;
|
||||
}
|
||||
|
||||
function calculateAlpha(
|
||||
portfolioReturns: number[],
|
||||
marketReturns: number[],
|
||||
riskFreeRate: number
|
||||
): number {
|
||||
const portfolioMean =
|
||||
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
|
||||
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
|
||||
const beta = calculateBeta(portfolioReturns, marketReturns);
|
||||
|
||||
return portfolioMean - (riskFreeRate + beta * (marketMean - riskFreeRate));
|
||||
}
|
||||
|
||||
function calculateSkewness(returns: number[]): number {
|
||||
if (returns.length < 3) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
if (stdDev === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const skew =
|
||||
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length;
|
||||
|
||||
return skew;
|
||||
}
|
||||
|
||||
function calculateKurtosis(returns: number[]): number {
|
||||
if (returns.length < 4) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
if (stdDev === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const kurt =
|
||||
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length;
|
||||
|
||||
return kurt - 3; // Excess kurtosis
|
||||
}
|
||||
|
||||
function aggregateMonthlyReturns(returns: Array<{ return: number; date: Date }>): number[] {
|
||||
const monthlyReturns: { [key: string]: number } = {};
|
||||
|
||||
for (const ret of returns) {
|
||||
const monthKey = `${ret.date.getFullYear()}-${ret.date.getMonth()}`;
|
||||
if (!monthlyReturns[monthKey]) {
|
||||
monthlyReturns[monthKey] = 1;
|
||||
}
|
||||
monthlyReturns[monthKey] *= 1 + ret.return;
|
||||
}
|
||||
|
||||
return Object.values(monthlyReturns).map(cumReturn => cumReturn - 1);
|
||||
}
|
||||
|
|
@ -1,482 +0,0 @@
|
|||
/** Legacy calculation API retained for migration/research; see ../../README.md before use. */
|
||||
/**
|
||||
* Risk Metrics and Analysis
|
||||
* Comprehensive risk measurement tools for portfolio and trading analysis
|
||||
*/
|
||||
|
||||
import type { RiskMetrics } from '@stock-bot/types';
|
||||
|
||||
/**
|
||||
* Calculate Value at Risk (VaR) using historical simulation
|
||||
*/
|
||||
export function valueAtRisk(returns: number[], confidenceLevel: number = 0.95): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sortedReturns = [...returns].sort((a, b) => a - b);
|
||||
const index = Math.floor((1 - confidenceLevel) * sortedReturns.length);
|
||||
|
||||
return sortedReturns[index] || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Conditional Value at Risk (CVaR/Expected Shortfall)
|
||||
*/
|
||||
export function conditionalValueAtRisk(returns: number[], confidenceLevel: number = 0.95): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sortedReturns = [...returns].sort((a, b) => a - b);
|
||||
const cutoffIndex = Math.floor((1 - confidenceLevel) * sortedReturns.length);
|
||||
|
||||
if (cutoffIndex === 0) {
|
||||
return sortedReturns[0] || 0;
|
||||
}
|
||||
|
||||
const tailReturns = sortedReturns.slice(0, cutoffIndex);
|
||||
return tailReturns.reduce((sum, ret) => sum + ret, 0) / tailReturns.length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate parametric VaR using normal distribution
|
||||
*/
|
||||
export function parametricVaR(
|
||||
returns: number[],
|
||||
confidenceLevel: number = 0.95,
|
||||
portfolioValue: number = 1
|
||||
): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance =
|
||||
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
// Z-score for confidence level (normal distribution)
|
||||
const zScore = getZScore(confidenceLevel);
|
||||
|
||||
return portfolioValue * (mean - zScore * stdDev);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate maximum drawdown
|
||||
*/
|
||||
export function maxDrawdown(equityCurve: number[]): number {
|
||||
if (equityCurve.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let maxDD = 0;
|
||||
const first = equityCurve[0];
|
||||
if (first === undefined) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let peak = first;
|
||||
|
||||
for (let i = 1; i < equityCurve.length; i++) {
|
||||
const current = equityCurve[i];
|
||||
if (current === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (current > peak) {
|
||||
peak = current;
|
||||
} else {
|
||||
const drawdown = (peak - current) / peak;
|
||||
maxDD = Math.max(maxDD, drawdown);
|
||||
}
|
||||
}
|
||||
|
||||
return maxDD;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate downside deviation
|
||||
*/
|
||||
export function downsideDeviation(returns: number[], targetReturn: number = 0): number {
|
||||
if (returns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const downsideReturns = returns.filter(ret => ret < targetReturn);
|
||||
|
||||
if (downsideReturns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const sumSquaredDownside = downsideReturns.reduce(
|
||||
(sum, ret) => sum + Math.pow(ret - targetReturn, 2),
|
||||
0
|
||||
);
|
||||
|
||||
return Math.sqrt(sumSquaredDownside / returns.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Sharpe ratio
|
||||
*/
|
||||
export function sharpeRatio(returns: number[], riskFreeRate: number = 0): number {
|
||||
if (returns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance =
|
||||
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
if (stdDev === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return (mean - riskFreeRate) / stdDev;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate beta coefficient
|
||||
*/
|
||||
export function beta(portfolioReturns: number[], marketReturns: number[]): number {
|
||||
if (portfolioReturns.length !== marketReturns.length || portfolioReturns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const n = portfolioReturns.length;
|
||||
const portfolioMean = portfolioReturns.reduce((sum, ret) => sum + ret, 0) / n;
|
||||
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / n;
|
||||
|
||||
let covariance = 0;
|
||||
let marketVariance = 0;
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
const portfolioReturn = portfolioReturns[i];
|
||||
const marketReturn = marketReturns[i];
|
||||
if (portfolioReturn === undefined || marketReturn === undefined) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const portfolioDiff = portfolioReturn - portfolioMean;
|
||||
const marketDiff = marketReturn - marketMean;
|
||||
|
||||
covariance += portfolioDiff * marketDiff;
|
||||
marketVariance += marketDiff * marketDiff;
|
||||
}
|
||||
|
||||
return marketVariance === 0 ? 0 : covariance / marketVariance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate alpha
|
||||
*/
|
||||
export function alpha(
|
||||
portfolioReturns: number[],
|
||||
marketReturns: number[],
|
||||
riskFreeRate: number = 0
|
||||
): number {
|
||||
const portfolioMean =
|
||||
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
|
||||
const marketMean = marketReturns.reduce((sum, ret) => sum + ret, 0) / marketReturns.length;
|
||||
const portfolioBeta = beta(portfolioReturns, marketReturns);
|
||||
|
||||
return portfolioMean - (riskFreeRate + portfolioBeta * (marketMean - riskFreeRate));
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Treynor ratio
|
||||
*/
|
||||
export function treynorRatio(
|
||||
portfolioReturns: number[],
|
||||
marketReturns: number[],
|
||||
riskFreeRate: number = 0
|
||||
): number {
|
||||
const portfolioBeta = beta(portfolioReturns, marketReturns);
|
||||
|
||||
if (portfolioBeta === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const portfolioMean =
|
||||
portfolioReturns.reduce((sum, ret) => sum + ret, 0) / portfolioReturns.length;
|
||||
return (portfolioMean - riskFreeRate) / portfolioBeta;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate tracking error
|
||||
*/
|
||||
export function trackingError(portfolioReturns: number[], benchmarkReturns: number[]): number {
|
||||
if (portfolioReturns.length !== benchmarkReturns.length || portfolioReturns.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const activeReturns = portfolioReturns.map((ret, i) => {
|
||||
const benchmark = benchmarkReturns[i];
|
||||
return benchmark !== undefined ? ret - benchmark : 0;
|
||||
});
|
||||
const mean = activeReturns.reduce((sum, ret) => sum + ret, 0) / activeReturns.length;
|
||||
|
||||
const variance =
|
||||
activeReturns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) /
|
||||
(activeReturns.length - 1);
|
||||
|
||||
return Math.sqrt(variance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate volatility (standard deviation of returns)
|
||||
*/
|
||||
export function volatility(returns: number[]): number {
|
||||
if (returns.length < 2) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance =
|
||||
returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / (returns.length - 1);
|
||||
|
||||
return Math.sqrt(variance);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate annualized volatility
|
||||
*/
|
||||
export function annualizedVolatility(returns: number[], periodsPerYear: number = 252): number {
|
||||
return volatility(returns) * Math.sqrt(periodsPerYear);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate skewness (measure of asymmetry)
|
||||
*/
|
||||
export function skewness(returns: number[]): number {
|
||||
if (returns.length < 3) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
if (stdDev === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const skew =
|
||||
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 3), 0) / returns.length;
|
||||
|
||||
return skew;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate kurtosis (measure of tail heaviness)
|
||||
*/
|
||||
export function kurtosis(returns: number[]): number {
|
||||
if (returns.length < 4) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const mean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
const variance = returns.reduce((sum, ret) => sum + Math.pow(ret - mean, 2), 0) / returns.length;
|
||||
const stdDev = Math.sqrt(variance);
|
||||
|
||||
if (stdDev === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const kurt =
|
||||
returns.reduce((sum, ret) => sum + Math.pow((ret - mean) / stdDev, 4), 0) / returns.length;
|
||||
|
||||
return kurt - 3; // Excess kurtosis (subtract 3 for normal distribution baseline)
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate comprehensive risk metrics
|
||||
*/
|
||||
export function calculateRiskMetrics(
|
||||
returns: number[],
|
||||
equityCurve: number[],
|
||||
marketReturns?: number[],
|
||||
riskFreeRate: number = 0
|
||||
): RiskMetrics {
|
||||
if (returns.length === 0) {
|
||||
return {
|
||||
var95: 0,
|
||||
var99: 0,
|
||||
cvar95: 0,
|
||||
maxDrawdown: 0,
|
||||
volatility: 0,
|
||||
downside_deviation: 0,
|
||||
calmar_ratio: 0,
|
||||
sortino_ratio: 0,
|
||||
beta: 0,
|
||||
alpha: 0,
|
||||
sharpeRatio: 0,
|
||||
treynorRatio: 0,
|
||||
trackingError: 0,
|
||||
informationRatio: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const portfolioVolatility = volatility(returns);
|
||||
const portfolioMean = returns.reduce((sum, ret) => sum + ret, 0) / returns.length;
|
||||
// Calculate VaR
|
||||
const var95Value = valueAtRisk(returns, 0.95);
|
||||
const var99Value = valueAtRisk(returns, 0.99);
|
||||
const cvar95Value = conditionalValueAtRisk(returns, 0.95);
|
||||
|
||||
// Calculate max drawdown
|
||||
const maxDD = maxDrawdown(equityCurve);
|
||||
|
||||
// Calculate downside deviation
|
||||
const downsideDeviationValue = downsideDeviation(returns);
|
||||
// Calculate ratios
|
||||
const calmarRatio = maxDD > 0 ? portfolioMean / maxDD : 0;
|
||||
const sortinoRatio =
|
||||
downsideDeviationValue > 0 ? (portfolioMean - riskFreeRate) / downsideDeviationValue : 0;
|
||||
const sharpeRatio =
|
||||
portfolioVolatility > 0 ? (portfolioMean - riskFreeRate) / portfolioVolatility : 0;
|
||||
|
||||
let portfolioBeta = 0;
|
||||
let portfolioAlpha = 0;
|
||||
let portfolioTreynorRatio = 0;
|
||||
let portfolioTrackingError = 0;
|
||||
let informationRatio = 0;
|
||||
|
||||
if (marketReturns && marketReturns.length === returns.length) {
|
||||
portfolioBeta = beta(returns, marketReturns);
|
||||
portfolioAlpha = alpha(returns, marketReturns, riskFreeRate);
|
||||
portfolioTreynorRatio = treynorRatio(returns, marketReturns, riskFreeRate);
|
||||
portfolioTrackingError = trackingError(returns, marketReturns);
|
||||
informationRatio = portfolioTrackingError > 0 ? portfolioAlpha / portfolioTrackingError : 0;
|
||||
}
|
||||
return {
|
||||
var95: var95Value,
|
||||
var99: var99Value,
|
||||
cvar95: cvar95Value,
|
||||
maxDrawdown: maxDD,
|
||||
volatility: portfolioVolatility,
|
||||
downside_deviation: downsideDeviationValue,
|
||||
calmar_ratio: calmarRatio,
|
||||
sortino_ratio: sortinoRatio,
|
||||
beta: portfolioBeta,
|
||||
alpha: portfolioAlpha,
|
||||
sharpeRatio,
|
||||
treynorRatio: portfolioTreynorRatio,
|
||||
trackingError: portfolioTrackingError,
|
||||
informationRatio,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to get Z-score for confidence level
|
||||
* This implementation handles arbitrary confidence levels
|
||||
*/
|
||||
function getZScore(confidenceLevel: number): number {
|
||||
// First check our lookup table for common values (more precise)
|
||||
const zScores: { [key: string]: number } = {
|
||||
'0.90': 1.282,
|
||||
'0.95': 1.645,
|
||||
'0.975': 1.96,
|
||||
'0.99': 2.326,
|
||||
'0.995': 2.576,
|
||||
};
|
||||
|
||||
const key = confidenceLevel.toString();
|
||||
if (zScores[key]) {
|
||||
return zScores[key];
|
||||
}
|
||||
|
||||
// For arbitrary confidence levels, use approximation
|
||||
if (confidenceLevel < 0.5) {
|
||||
return -getZScore(1 - confidenceLevel);
|
||||
}
|
||||
|
||||
if (confidenceLevel >= 0.999) {
|
||||
return 3.09;
|
||||
} // Cap at 99.9% for numerical stability
|
||||
|
||||
// Approximation of inverse normal CDF
|
||||
const y = Math.sqrt(-2.0 * Math.log(1.0 - confidenceLevel));
|
||||
return (
|
||||
y -
|
||||
(2.515517 + 0.802853 * y + 0.010328 * y * y) /
|
||||
(1.0 + 1.432788 * y + 0.189269 * y * y + 0.001308 * y * y * y)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate portfolio risk contribution
|
||||
*/
|
||||
export function riskContribution(
|
||||
weights: number[],
|
||||
covarianceMatrix: number[][],
|
||||
portfolioVolatility: number
|
||||
): number[] {
|
||||
const n = weights.length;
|
||||
const contributions: number[] = [];
|
||||
|
||||
for (let i = 0; i < n; i++) {
|
||||
let marginalContribution = 0;
|
||||
const row = covarianceMatrix[i];
|
||||
if (!row) {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (let j = 0; j < n; j++) {
|
||||
const weight = weights[j];
|
||||
const covariance = row[j];
|
||||
if (weight !== undefined && covariance !== undefined) {
|
||||
marginalContribution += weight * covariance;
|
||||
}
|
||||
}
|
||||
|
||||
const weight = weights[i];
|
||||
if (weight !== undefined && portfolioVolatility !== 0) {
|
||||
const contribution = (weight * marginalContribution) / Math.pow(portfolioVolatility, 2);
|
||||
contributions.push(contribution);
|
||||
}
|
||||
}
|
||||
|
||||
return contributions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate Ulcer Index
|
||||
*/
|
||||
export function ulcerIndex(equityCurve: Array<{ value: number; date: Date }>): number {
|
||||
if (equityCurve.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let sumSquaredDrawdown = 0;
|
||||
const first = equityCurve[0];
|
||||
if (!first) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
let peak = first.value;
|
||||
|
||||
for (const point of equityCurve) {
|
||||
peak = Math.max(peak, point.value);
|
||||
const drawdownPercent = ((peak - point.value) / peak) * 100;
|
||||
sumSquaredDrawdown += drawdownPercent * drawdownPercent;
|
||||
}
|
||||
|
||||
return Math.sqrt(sumSquaredDrawdown / equityCurve.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate risk-adjusted return (RAR)
|
||||
*/
|
||||
export function riskAdjustedReturn(
|
||||
portfolioReturn: number,
|
||||
portfolioRisk: number,
|
||||
riskFreeRate: number = 0
|
||||
): number {
|
||||
if (portfolioRisk === 0) {
|
||||
return 0;
|
||||
}
|
||||
return (portfolioReturn - riskFreeRate) / portfolioRisk;
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue