5.1 KiB
This code calculates the downside deviation of stock returns for Apple Inc. (AAPL). It imports necessary libraries and loads historical adjusted closing prices. The downside deviation is computed to measure risk by focusing on negative returns. This metric is useful for investors aiming to quantify the volatility of negative returns. The downside deviation is annualized for practical financial analysis.
import numpy as np
from openbb_terminal.sdk import openbb
Load historical adjusted closing prices for Apple Inc. (AAPL)
data = openbb.stocks.load("AAPL")
Calculate daily percentage change in adjusted closing prices to obtain returns
returns = data["Adj Close"].pct_change()
Calculate the downside deviation of the returns
def downside_deviation(returns): """Calculate downside deviation of returns Parameters ---------- returns : np.ndarray Array of daily percentage returns Returns ------- downside_deviation : float Annualized downside deviation of returns Notes ----- This function calculates the downside deviation, which measures the volatility of negative returns. It annualizes the deviation for practical financial analysis. """ # Initialize an empty array to store downside deviation values out = np.empty(returns.shape[1:]) # Clip returns at zero to focus on negative returns downside_diff = np.clip(returns, np.NINF, 0) # Square the clipped values to calculate the squared deviations np.square(downside_diff, out=downside_diff) # Calculate the mean of squared deviations ignoring NaNs np.nanmean(downside_diff, axis=0, out=out) # Take the square root of the mean squared deviations np.sqrt(out, out=out) # Annualize the downside deviation by multiplying by the square root of 252 np.multiply(out, np.sqrt(252), out=out) # Return the annualized downside deviation as a single value return out.item()
Calculate and output the downside deviation of the returns
downside_deviation(returns)
Calculate the annualized standard deviation of returns for comparison
np.sqrt(np.square(returns).mean()) * np.sqrt(252)
PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.
