
Manage your portfolio's risk with value at risk
Manage your portfolio's risk with value at risk
In today's issue, I'm going to show you how to compute the value at risk (VaR) of a portfolio of stocks.
VaR is one way professional traders manage risk. It estimates how much your portfolio might lose over a set time period. Using VaR is a good way to avoid losing all your money if the market moves against you.
VaR lets you say something like this:
“With 95% confidence, my portfolio's loss will not exceed $750 in one day.
Unfortunately, most non-professional traders don't use VaR. They either don't know it exists or think it's too complicated to use.
I'm going to show you how to use Python to compute VaR using the variance-covariance method.
Let's go!
Step 1: Import the libraries
We'll use a new library today: scipy. Scipy is a library for scientific and technical computing. It has a lot of statistical functions.
I'm using Jupyter Notebook and want to plot my charts inline which is what %matplotlib inline does.
Step 2: Define the variables
We'll simulate a portfolio of stocks. To do this, we need to define the symbols, the weights, and the investment amount.
We also define the confidence level which we'll use later.
Now we can get the stock data for all the symbols in one line of code.
Step 3: Compute portfolio statistics
Computing portfolio returns is not as simple as just adding up the returns of the individual stocks. We need to take the covariance between the stocks in the portfolio into account.
Fortunately, this is easy in Python using pandas and NumPy.
First, we get the daily returns of the stocks in the portfolio. From there we get the mean return for all the data. We apply the weights to those returns and multiply them by the portfolio value to get the portfolio mean return.
Then we compute the covariance between the returns, take the square root of the covariance-adjusted weights of the stocks in the portfolio, and compute the portfolio standard deviation.
The portfolio mean and standard deviation are used in the next step.
Step 4: Compute VaR
To find the VaR of this portfolio, we start by finding the point on the density plot based on the confidence level, mean, and standard deviation.
This is where scipy comes in.
VaR is the portfolio value less this amount.
This is the most you can expect to lose in one day with 95% confidence.
Bonus: Scaling VaR to different time frames
What about over one week? Or one month?
Stock returns increase with the square root of time. Therefore to scale the value at risk, we multiply it by the square root of time. This sounds scary but it's simple in Python.
Multiply the one-day VaR by the square root of one (day) through the square root of 30 (days).
Then we plot it.

VaR is a simple measure that comes with various assumptions, caveats, and criticisms. It should be used as one of many risk management techniques. Despite its simplicity, it is a useful tool in the trader's tool belt.
Read more about VaR here.