
Image by Author
Mean and variance have been the standard tools for portfolio risk analysis since Harry Markowitz introduced Modern Portfolio Theory in 1952. They’re still widely used, but they have real limitations that can leave you with an incomplete picture of risk, especially when markets get volatile.
The problem: standard deviation treats all volatility the same, whether you’re making money or losing it. It also assumes returns follow a normal distribution, which breaks down during market downturns, when extreme losses are more common than the model suggests. When managing a portfolio, you care more about potential losses than volatility that goes both ways.
This tutorial covers two alternative risk metrics that focus on downside risk: Value at Risk (VaR) and Conditional Value at Risk (CVaR). You’ll calculate them using Python and real stock market data, and learn when they give you better insights than standard deviation.
Prerequisites and Setup
You’ll need a few Python packages for pulling data and running the analysis.
# Install required packages (run once) # pip install yfinance empyrical pandas numpy matplotlib import yfinance as yf import pandas as pd import numpy as np import empyrical as ep import matplotlib.pyplot as plt
The yfinance package downloads historical stock data, while empyrical provides pre-built functions for calculating advanced risk metrics. The pandas and numpy libraries handle data manipulation, and matplotlib creates visualizations.
Downloading Portfolio Data
We’ll analyze five stocks from different sectors to see how risk metrics vary across different types of assets.
# Define portfolio and date range
tickers = ['AAPL', 'MSFT', 'JPM', 'JNJ', 'XOM']
start_date = '2020-01-01'
end_date = '2024-01-01'
# Download adjusted close prices
raw = yf.download(
tickers,
start=start_date,
end=end_date,
auto_adjust=True,
group_by='column'
)
data = raw['Close']
data.head()
Output:
Ticker AAPL JNJ JPM MSFT XOM Date 2020-01-02 72.538521 124.072968 119.573349 152.791122 54.131065 2020-01-03 71.833282 122.636482 117.995438 150.888596 53.695881 2020-01-06 72.405678 122.483482 117.901619 151.278625 54.108177 2020-01-07 72.065147 123.231483 115.897224 149.899292 53.665337 2020-01-08 73.224426 123.214508 116.801331 152.286972 52.856056
This downloads four years of daily adjusted close prices for Apple, Microsoft, JPMorgan, Johnson & Johnson, and Exxon Mobil. The adjusted prices account for stock splits and dividends, giving you accurate historical performance data.
Calculating Daily Returns
Risk metrics measure how returns vary, not prices themselves.
# Calculate daily returns returns = data.pct_change().dropna() # Display first few returns print(returns.head())
Output:
Ticker AAPL JNJ JPM MSFT XOM Date 2020-01-03 -0.009722 -0.011577 -0.013197 -0.012452 -0.008040 2020-01-06 0.007968 -0.001248 -0.000795 0.002585 0.007678 2020-01-07 -0.004703 0.006107 -0.017001 -0.009118 -0.008184 2020-01-08 0.016086 -0.000138 0.007801 0.015928 -0.015080 2020-01-09 0.021241 0.002966 0.003651 0.012493 0.007656
The percentage change method calculates each day’s return as today’s price divided by yesterday’s price minus one. We drop the first row since there’s no previous price to compare it to.
Traditional Risk Metric: Mean Return
Mean return shows the average daily performance across the entire period.
# Calculate mean return for each stock
mean_returns = returns.mean()
print("Daily Mean Returns:")
print(mean_returns)
Output:
Daily Mean Returns: Ticker AAPL 0.001187 JNJ 0.000262 JPM 0.000541 MSFT 0.001095 XOM 0.000825 dtype: float64
Apple has the highest daily mean return at 0.12%, which translates to just over 30% annualized. But mean return alone tells you nothing about the risk you took to get those returns.
Traditional Risk Metric: Standard Deviation
Standard deviation measures how much returns bounce around from their average value.
# Calculate variance and standard deviation
variance = returns.var()
std_dev = returns.std()
print("Daily Variance:")
print(variance)
print(f"\nDaily Standard Deviation:")
print(std_dev)
Output:
Daily Variance: Ticker AAPL 0.000447 JNJ 0.000169 JPM 0.000470 MSFT 0.000422 XOM 0.000550 dtype: float64 Daily Standard Deviation: Ticker AAPL 0.021146 JNJ 0.013004 JPM 0.021685 MSFT 0.020546 XOM 0.023452 dtype: float64
Johnson & Johnson has the lowest daily standard deviation at 1.3%, making it the most stable stock here. Exxon Mobil shows the highest volatility at 2.3% daily.
Visualizing Return Distributions
The actual distribution of returns shows why standard deviation might not tell the whole story.
# Plot distribution for one stock (AAPL as example)
plt.figure(figsize=(10, 6))
plt.hist(returns['AAPL'], bins=50, edgecolor='black', alpha=0.7)
plt.axvline(mean_returns['AAPL'], color='red', linestyle='--',
label=f'Mean: {mean_returns["AAPL"]:.4f}')
plt.xlabel('Daily Returns')
plt.ylabel('Frequency')
plt.title('AAPL Return Distribution')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

This histogram shows Apple’s returns clustering around the mean, but with a noticeable left tail. Those are the days with significant losses. The distribution looks roughly symmetric but with some negative skewness, meaning extreme losses happen more often than extreme gains of the same size.
Alternative Risk Metric: Value at Risk (VaR)
Value at Risk answers a specific question: What’s the maximum expected loss over a given time period at a specific confidence level? A 95% VaR tells you the threshold where only 5% of returns fall below that level.
# Calculate 95% VaR for each stock (5% worst cases)
var_95 = {}
for ticker in tickers:
var_95[ticker] = ep.value_at_risk(returns[ticker], cutoff=0.05)
var_df = pd.DataFrame(var_95, index=['VaR (95%)']).T
print("Value at Risk (95% confidence):")
print(var_df)
Output:
Value at Risk (95% confidence):
VaR (95%)
AAPL -0.032406
MSFT -0.029482
JPM -0.029577
JNJ -0.018302
XOM -0.034851
Apple’s 95% VaR of -3.24% means that we are 95% confident that daily loss will not exceed 3.24% over the next trading day. Flip it around: only 5% of days see losses worse than 3.24%. Johnson & Johnson has the best VaR at -1.83%, while Exxon Mobil has the worst at -3.49%.
VaR gives you a clear, practical measure: “There’s a 95% chance daily losses won’t exceed this amount.” Unlike standard deviation, it focuses only on downside risk.
Visualizing Value at Risk
Seeing VaR in the context of the full return distribution makes this metric easier to understand.
# Visualize VaR for AAPL
plt.figure(figsize=(10, 6))
plt.hist(returns['AAPL'], bins=50, edgecolor='black', alpha=0.7)
plt.axvline(var_95['AAPL'], color='red', linestyle='--', linewidth=2,
label=f'VaR (95%): {var_95["AAPL"]:.4f}')
plt.xlabel('Daily Returns')
plt.ylabel('Frequency')
plt.title('AAPL: Value at Risk (95% Confidence)')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

The red line marks the VaR threshold. Everything to the left of that line represents the worst 5% of trading days. It’s just the bottom fifth percentile of the return distribution.
Alternative Risk Metric: Conditional Value at Risk (CVaR)
VaR tells you the threshold of the worst 5% of days, but not how bad those worst days actually get. Conditional Value at Risk (also called expected shortfall) fills that gap by calculating the expected loss given that the loss exceeds the VaR threshold.
# Calculate 95% CVaR for each stock
cvar_95 = {}
for ticker in tickers:
cvar_95[ticker] = ep.conditional_value_at_risk(returns[ticker], cutoff=0.05)
cvar_df = pd.DataFrame(cvar_95, index=['CVaR (95%)']).T
print("Conditional Value at Risk (95% confidence):")
print(cvar_df)
Output:
Conditional Value at Risk (95% confidence):
CVaR (95%)
AAPL -0.046855
MSFT -0.045188
JPM -0.047239
JNJ -0.029725
XOM -0.051412
Apple’s CVaR of -4.69% means that, when losses cross the VaR threshold, the average loss on those worst days is 4.69%. Notice that CVaR is always more negative than VaR. That’s because it averages only the worst outcomes.
Comparing VaR and CVaR
Both metrics together reveal important details about tail risk.
# Create comparison DataFrame
risk_comparison = pd.DataFrame({
'VaR (95%)': var_95,
'CVaR (95%)': cvar_95
})
print("VaR vs CVaR Comparison:")
print(risk_comparison)
Output:
VaR vs CVaR Comparison:
VaR (95%) CVaR (95%)
AAPL -0.032406 -0.046855
MSFT -0.029482 -0.045188
JPM -0.029577 -0.047239
JNJ -0.018302 -0.029725
XOM -0.034851 -0.051412
The gap between VaR and CVaR tells you about tail risk severity. JPMorgan has a VaR of -2.96% but a CVaR of -4.72% — a 1.76 percentage-point difference. This sizable gap suggests that when JPMorgan has bad days, they tend to be significantly worse than the VaR threshold alone indicates.
Visualizing VaR vs CVaR
Plotting both metrics on the return distribution shows how CVaR extends beyond the VaR threshold.
# Visualize both metrics for AAPL
plt.figure(figsize=(10, 6))
plt.hist(returns['AAPL'], bins=50, edgecolor='black', alpha=0.7)
plt.axvline(var_95['AAPL'], color='red', linestyle='--', linewidth=2,
label=f'VaR (95%): {var_95["AAPL"]:.4f}')
plt.axvline(cvar_95['AAPL'], color='darkred', linestyle='--', linewidth=2,
label=f'CVaR (95%): {cvar_95["AAPL"]:.4f}')
plt.xlabel('Daily Returns')
plt.ylabel('Frequency')
plt.title('AAPL: VaR vs CVaR Comparison')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()

The darker red CVaR line sits farther left than the VaR line, positioned at the average of all the returns in the left tail. This shows that CVaR captures information about loss severity that VaR alone misses.
Cross-Portfolio Comparison
Comparing all stocks at once reveals which assets have the most concerning downside risk profiles.
# Compare all stocks
risk_comparison.plot(kind='bar', figsize=(10, 6), color=['#ff7f0e', '#d62728'])
plt.title('VaR vs CVaR Across Portfolio')
plt.xlabel('Stock')
plt.ylabel('Risk Measure (Daily Returns)')
plt.xticks(rotation=45)
plt.legend(title='Risk Metric')
plt.grid(True, alpha=0.3, axis='y')
plt.tight_layout()
plt.show()

This chart makes relative risk immediately obvious. Johnson & Johnson shows the least downside risk on both metrics, while Exxon Mobil has the highest. The consistent gap between VaR and CVaR bars for each stock shows that tail risk exists across all assets but varies in severity.
Complete Risk Profile Summary
Traditional and alternative metrics together give you a full risk assessment.
# Create summary table with all metrics
summary = pd.DataFrame({
'Mean Return (Daily)': mean_returns,
'Std Dev (Daily)': std_dev,
'VaR (95%)': var_95,
'CVaR (95%)': cvar_95
})
print("Portfolio Risk Metrics Summary:")
print(summary.round(6))
Output:
Portfolio Risk Metrics Summary:
Mean Return (Daily) Std Dev (Daily) VaR (95%) CVaR (95%)
AAPL 0.001187 0.021146 -0.032406 -0.046855
JNJ 0.000262 0.013004 -0.018302 -0.029725
JPM 0.000541 0.021685 -0.029577 -0.047239
MSFT 0.001095 0.020546 -0.029482 -0.045188
XOM 0.000825 0.023452 -0.034851 -0.051412
This summary table shows the complete picture for each stock. Apple offers the highest mean return but comes with substantial downside risk as shown in its VaR and CVaR. Johnson & Johnson delivers lower returns but with significantly less downside risk. Standard deviation alone would make Apple and Microsoft look similar (2.11% vs. 2.05%), but their CVaR values show Apple has slightly more severe tail losses.
When To Use Alternative Risk Metrics
Standard deviation works well in many situations, especially when returns look fairly normal and when upside and downside volatility matter equally. But VaR and CVaR become valuable in several scenarios.
Use VaR when you need to explain risk in plain terms. Saying “there’s a 95% chance daily losses won’t exceed 3%” is often more intuitive than explaining standard deviation. Banking and insurance regulations frequently require VaR calculations for capital adequacy.
Use CVaR when understanding tail risk severity matters. Portfolio optimization with CVaR produces portfolios that hold up better during market stress compared to mean–variance optimization. CVaR also addresses VaR’s big limitation: VaR tells you the threshold but says nothing about what happens beyond it.
Consider using all three metrics together. Standard deviation captures overall volatility, VaR identifies the threshold of extreme losses, and CVaR quantifies how severe those extreme losses get. Each one answers a different question about risk.
Conclusion
Mean–variance analysis provides a solid foundation for portfolio risk assessment, but it treats all volatility the same and assumes returns follow a normal distribution. Value at Risk and Conditional Value at Risk focus specifically on downside risk, answering the questions investors care about: How much can I lose on a bad day, and how bad do those worst days get?
VaR gives you a clear threshold for maximum expected loss at a given confidence level, while CVaR extends this by averaging the losses beyond that threshold. Together, these metrics paint a more complete picture of portfolio risk than standard deviation alone, especially during market stress, when tail risk matters most.
Python’s empyrical library makes calculating these advanced metrics straightforward, so you can add them to your portfolio analysis workflow alongside traditional mean–variance measures.
