Files
strategy-lab/to_explore/pyquantnews/10_SharpeRatio.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

6.1 KiB

No description has been provided for this image

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.

In [ ]:
import yfinance as yf
import numpy as np

Download historical price data for SPY and AAPL from Yahoo Finance

In [ ]:
data = yf.download(["SPY", "AAPL"], start="2020-01-01", end="2022-07-31")

Extract adjusted closing prices for SPY and AAPL

In [ ]:
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

In [ ]:
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

In [ ]:
sharpe_ratio(spy_returns)

Calculate the Sharpe ratio for AAPL daily returns

In [ ]:
sharpe_ratio(aapl_returns)

Plot the rolling 30-day Sharpe ratio for AAPL

In [ ]:
aapl_returns.rolling(30).apply(sharpe_ratio).plot()

Plot the histogram of the rolling 30-day Sharpe ratios for AAPL

In [ ]:
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

In [ ]:
(
    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.