How to power trading portfolio risk analysis with downside deviation

July 29, 2023
Facebook logo.
Twitter logo.
LinkedIn logo.
Get this code in Google Colab

How to power trading portfolio risk analysis with downside deviation

In today's newsletter, we're taking a close look at portfolio risk, a key concept for any trader.

You'll learn how to build a simple metric called downside deviation to measure risk.

Let's dive in!

How to power trading portfolio risk analysis with downside deviation

Portfolio risk is the potential for financial loss and uncertainty about its extent. Downside deviation is a common measure of financial risk that measures the volatility of negative returns.

This measure gives a more accurate picture of the type of risk traders care about:

The risk of losing money.

Since volatility to the upside is not usually a concern, downside risk is used by traders to gauge the risks that lead to portfolio drawdown—a key worry.

Let's get started!

Imports and set up

First import NumPy for the math and the OpenBB SDK for the data.

1import numpy as np
2
3from openbb_terminal.sdk import openbb
4From there, download stock prices and compute the daily simple returns.
5
6data = openbb.stocks.load("AAPL")
7returns = data["Adj Close"].pct_change()

Compute downside deviation

The calculation for downside deviation is straightforward.

Instead of using pandas methods (returns is a pandas Series), you’ll see how to use NumPy to concisely make the calculation.

1def downside_deviation(returns):
2    
3    out = np.empty(returns.shape[1:])
4    
5    downside_diff = np.clip(returns, np.NINF, 0)
6    np.square(downside_diff, out=downside_diff)
7    np.nanmean(downside_diff, axis=0, out=out)
8    np.sqrt(out, out=out)
9    np.multiply(out, np.sqrt(252), out=out)
10    
11    return out.item()

The function first creates an empty array the same size as the returns input (less one to remove the NaNs).

Then we use the clip method to grab all the returns between negative infinity and 0.

From there, we square the returns, take the mean value, apply the square root, then annualize by multiplying by the square root of 252.

When comparing the downside deviation to the standard deviation of returns, it will be different. In the case of this example (at the time of writing) it’s 33% lower!

That’s because AAPL has been rallying over the time period. If you repeat the analysis for a trading portfolio or asset that has not been on a steady incline, your results will be different.

Next steps

There’s one action step for today.

Repeat this analysis for other stocks you’re interested in or a portfolio of stocks. If you’re running a trading strategy, you can repeat the analysis for the strategy returns.

Man with glasses and a wristwatch, wearing a white shirt, looking thoughtfully at a laptop with a data screen in the background.