5.5 KiB
This code downloads historical stock data for SPY from Yahoo Finance, calculates daily returns, and analyzes drawdowns. It defines functions to compute drawdowns and maximum drawdowns, which are essential for risk management. The drawdown function calculates the percentage decline from a peak in the cumulative return series. The max_drawdown function identifies the largest drawdown over the period. These metrics are visualized to evaluate the stock's risk.
import yfinance as yf import numpy as np
Download historical stock data for SPY from Yahoo Finance
data = yf.download("SPY", start="2020-01-01", end="2022-07-31")
Calculate daily returns from the adjusted closing prices
returns = data["Adj Close"].pct_change()
Define a function to determine the drawdown from daily returns
def drawdown(returns): """Determines the drawdown Parameters ---------- returns : pd.Series Daily returns of an asset, noncumulative Returns ------- drawdown : pd.Series Notes ----- This function calculates the percentage decline from the peak value of cumulative returns. """ # Replace the first NaN value with 0.0 for accurate calculations returns.fillna(0.0, inplace=True) # Create a series of cumulative returns over time cumulative = (returns + 1).cumprod() # Calculate the running maximum value of cumulative returns running_max = np.maximum.accumulate(cumulative) # Compute the drawdown as the percentage decline from the running maximum return (cumulative - running_max) / running_max
Plot the drawdown over time as an area chart
drawdown(returns).plot(kind="area", color="salmon", alpha=0.5)
Define a function to determine the maximum drawdown from daily returns
def max_drawdown(returns): """Determines the maximum drawdown Parameters ---------- returns : pd.Series Daily returns of an asset, noncumulative Returns ------- max_drawdown : float Notes ----- This function identifies the largest drawdown over the specified period. """ # Calculate the drawdown and return the minimum value as the max drawdown return np.min(drawdown(returns))
Calculate the rolling maximum drawdown over a 30-day window and plot it
returns.rolling(30).apply(max_drawdown).plot(kind="area", color="salmon", alpha=0.5)
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.
