Algorithmic Trading & Indicators
Intermediate
Calculate Sortino Ratio, Omega Ratio & 99% CVaR (Expected Shortfall) in Python
Go beyond Sharpe Ratio in Python by computing Downside-Deviation Sortino Ratio, Omega Ratio, and 99% Conditional Value at Risk (CVaR).
#pandas#numpy
Problem Statement
The standard Sharpe Ratio penalizes upside volatility (huge winning trades) just as harshly as downside losses. Sortino and Omega Ratios isolate harmful downside tail risk.
Formula / Core Logic
Sortino = (Annual_Ret - Rf) / Downside_Deviation
Omega = Sum(Gains above threshold) / Sum(Losses below threshold)
CVaR_95 = Mean of returns worse than the 5th percentile.
Installation
pip install pandas numpy
calculate-sortino-ratio-omega-ratio-tail-risk-python.py
import numpy as np
import pandas as pd
def advanced_tail_risk_metrics(returns: pd.Series, rf=0.05):
daily_rf = rf / 252
excess = returns - daily_rf
downside = excess[excess < 0]
downside_std = np.sqrt(np.mean(downside ** 2)) * np.sqrt(252)
sortino = (excess.mean() * 252) / downside_std if downside_std != 0 else np.nan
gains = excess[excess > 0].sum()
losses = abs(excess[excess < 0].sum())
omega = gains / losses if losses != 0 else np.nan
var_95 = np.percentile(returns, 5)
cvar_95 = returns[returns <= var_95].mean()
return {'Sortino_Ratio': round(sortino, 2), 'Omega_Ratio': round(omega, 2), 'Daily_CVaR_95_Pct': round(cvar_95 * 100, 2)}
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: Why is CVaR (Expected Shortfall) superior to standard VaR?
Standard VaR only tells you the threshold of the worst 5% of days; CVaR calculates the average crash magnitude when that 5% tail event actually happens.