6.1 KiB
This code downloads historical price data for SPY and AAPL from Yahoo Finance, calculates daily returns, and computes the Sharpe ratio for these returns. It includes a function to determine the Sharpe ratio, adjusting for a daily benchmark return. The code then plots the rolling 30-day Sharpe ratio for AAPL and visualizes the histogram of these Sharpe ratios. Additionally, it compares the rolling 30-day Sharpe ratio of AAPL against SPY and plots the histogram of the differences.
import yfinance as yf import numpy as np
Download historical price data for SPY and AAPL from Yahoo Finance
data = yf.download(["SPY", "AAPL"], start="2020-01-01", end="2022-07-31")
Extract adjusted closing prices for SPY and AAPL
closes = data['Adj Close'] spy_returns = closes.SPY.pct_change().dropna() aapl_returns = closes.AAPL.pct_change().dropna()
Define a function to calculate the Sharpe ratio of a strategy
def sharpe_ratio(returns, adjustment_factor=0.0): """ Determines the Sharpe ratio of a strategy. Parameters ---------- returns : pd.Series or np.ndarray Daily returns of the strategy, noncumulative. adjustment_factor : int, float Constant daily benchmark return throughout the period. Returns ------- sharpe_ratio : float Note ----- See https://en.wikipedia.org/wiki/Sharpe_ratio for more details. """ # Adjust returns by subtracting the benchmark return returns_risk_adj = returns - adjustment_factor # Print the annualized standard deviation of the risk-adjusted returns print(returns_risk_adj.std() * np.sqrt(252)) # Return the annualized Sharpe ratio return ( returns_risk_adj.mean() / returns_risk_adj.std() ) * np.sqrt(252)
Calculate the Sharpe ratio for SPY daily returns
sharpe_ratio(spy_returns)
Calculate the Sharpe ratio for AAPL daily returns
sharpe_ratio(aapl_returns)
Plot the rolling 30-day Sharpe ratio for AAPL
aapl_returns.rolling(30).apply(sharpe_ratio).plot()
Plot the histogram of the rolling 30-day Sharpe ratios for AAPL
aapl_returns.rolling(30).apply(sharpe_ratio).hist(bins=50)
Compare the rolling 30-day Sharpe ratio of AAPL against SPY and plot the histogram of the differences
( aapl_returns.rolling(30).apply(sharpe_ratio) - spy_returns.rolling(30).apply(sharpe_ratio) ).hist(bins=50)
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.
