Use numpy to calculate CVaR and see what VaR misses

By PyQuant News

Published: 2026-03-21

URL: https://pyquantnews.substack.com/p/measure-the-pain-past-the-threshold


Each week, I send out one Python tutorial to help you get started with algorithmic trading, market data analysis, and quant finance. Upgrade to a paid plan to access the code notebooks.

In today’s post, you’ll use Python to compute both the standard risk cutoff and the more informative average-loss measure for a portfolio of 90 stocks, then visualize exactly what extra information you gain.

Two ways to measure portfolio risk

Value at Risk (VaR) tells you the most you’d expect to lose over a set period with a given level of confidence.

For example, a 95% daily VaR of $5,000 means that on 95 out of 100 days, you’d expect to lose less than $5,000.

But it says nothing about what happens on those other 5 days.

Conditional Value at Risk (CVaR), also called expected shortfall, fixes that gap. Instead of just marking the cutoff, it averages all the losses beyond that cutoff. So if VaR says “you probably won’t lose more than $5,000,” CVaR answers the follow-up question: “but if you do, how much should you expect to lose on average?”

The idea of measuring tail risk (the chance and size of extreme losses) has been around since the 1990s.

Researchers like Philippe Artzner and his collaborators published influential work in 1999 arguing that VaR was a flawed risk measure because it ignored the severity of losses past the cutoff.

CVaR emerged as the preferred alternative because it accounts for the full shape of the worst outcomes, not just the boundary.

How professionals use CVaR

Today, risk teams at banks and hedge funds use CVaR as a standard part of their daily reporting.

They compute it across entire portfolios to understand how much capital they could lose during extreme market moves.

Some firms set hard limits on CVaR rather than VaR, because CVaR penalizes strategies that have rare but catastrophic losses.

Regulators have also moved in this direction.

The Basel Committee on Banking Supervision shifted from VaR to expected shortfall for setting bank capital requirements, precisely because CVaR captures the severity of bad days rather than just counting them.

Why this matters when you’re starting out

If you’re building your own portfolio and want to understand your risk, CVaR gives you a much more honest picture than VaR alone.

VaR can lull you into thinking your worst day will be manageable, because it ignores the ugly tail of the distribution.

CVaR forces you to confront the average loss during those worst days, which is the number that actually determines whether you can survive a bad stretch.

Learning to compute both measures in Python means you can stress-test any portfolio you build and make decisions based on realistic worst-case scenarios instead of optimistic ones.

Let’s see how this works with Python.

Library installation

Install the libraries needed to download market data, compute risk metrics, and plot the results.

Imports and setup

numpy handles array math and percentile calculations. pandas structures our return data as DataFrames. yfinance downloads historical stock prices from Yahoo Finance. matplotlib produces the histogram that visualizes VaR and CVaR.

Download and prepare portfolio returns

Define the 90 tickers from the S&P 100 index that make up our test portfolio, then count them so we can generate a matching set of weights later.

Download roughly two years of daily price data for all 90 stocks in a single call using yfinance.

Compute daily percentage returns from closing prices, then subtract each stock’s mean return to center the distribution around zero.

Demeaning the returns removes the average drift so our risk calculations focus purely on the volatility and tail behavior. This is a common preprocessing step in historical simulation because we want to measure how far returns deviate from normal, not whether the portfolio trends up or down on average.

Generate random portfolio weights and normalize them so their absolute values sum to one, giving us a fully invested long-only portfolio.

The result is a chart that looks like this.

Because the weights are random, every run produces a different portfolio. This lets you rerun the notebook and see how VaR and CVaR shift with different allocations, which builds intuition for how concentration in certain stocks changes tail risk.

Define VaR and CVaR functions

Compute Value at Risk by taking the 5th percentile of recent portfolio returns and scaling it to the dollar amount invested.

The dot product of daily returns and weights collapses 90 individual stock returns into a single portfolio return for each day. The percentile then finds the loss threshold that only 5% of historical days exceeded, which is exactly what 95% VaR means.

Compute Conditional Value at Risk by averaging all portfolio returns that fall below the VaR threshold, then scaling to dollars.

CVaR will always be a larger loss than VaR because it averages the worst outcomes beyond the cutoff. This is the number that tells you how painful a truly bad day is on average, which is why regulators and professional risk teams now prefer it over VaR alone.

Compute and visualize portfolio risk

Print both risk measures for a hypothetical $1,000,000 portfolio so we can see the dollar-loss estimates side by side.

Reconstruct the full series of portfolio returns over the lookback window, then convert VaR and CVaR from dollar amounts back to return percentages for plotting.

Plot a histogram of portfolio returns, coloring the tail losses separately, with vertical lines marking the VaR cutoff and the CVaR average.

The result is a chart that looks like this.

The solid red line is VaR, the boundary where losses become unlikely. The dashed red line is CVaR, sitting deeper in the left tail, showing the average loss when that boundary is breached. The gap between those two lines is exactly the blind spot the post describes: VaR tells you where the danger starts, but CVaR tells you how bad it actually gets on the worst days.

Your next steps

You now have the code to compute both VaR and CVaR for a real portfolio, which means you can size your risk based on what actually happens past the cutoff, not just where the cutoff sits. That’s the difference between a risk number you report and a risk number you survive.