he Sharpe ratio is a financial metric that measures the performance of an investment compared to a risk-free asset, after adjusting for its risk1. It was developed by William F. Sharpe in 1966 and is widely used to evaluate the risk-adjusted return of investments17.
The Sharpe ratio is calculated using the following formula:
S=Rp−Rf / σp
Where:
Rp is the return of the portfolio or investment
Rf is the risk-free rate of return
- σp is the standard deviation of the portfolio’s excess return.
- A higher Sharpe ratio indicates better risk-adjusted performance. Generally, a Sharpe ratio of 1.0 or higher is considered good, 2.0 or higher is very good, and 3.0 or higher is excellent4.
To calculate the Sharpe ratio in Python, you can use the following code:
import numpy as np
import pandas as pd
import yfinance as yf
# Download stock data
ticker = “AAPL”
start_date = “2020-01-01”
end_date = “2025-03-02″
data = yf.download(ticker, start=start_date, end=end_date)
# Calculate daily returns
data[‘Returns’] = data[‘Adj Close’].pct_change()
# Set risk-free rate (e.g., 3% annual rate)
risk_free_rate = 0.03 / 252 # Daily risk-free rate
# Calculate excess returns
data[‘Excess_Returns’] = data[‘Returns’] – risk_free_rate
# Calculate annualized Sharpe ratio:
sharpe_ratio = np.sqrt(252) * data[‘Excess_Returns’].mean() / data[‘Excess_Returns’].std()
print(The annualized Sharpe ratio for {ticker} is: {sharpe_ratio:.4f}”)
This code does the following:
1.) Imports necessary libraries
2.) Downloads stock data using yfinance
3.) Calculates daily returns
4.) Sets a risk-free rate (adjust as needed)
5.) Calculates excess returns
Computes the annualized Sharpe ratio
The Sharpe ratio is a powerful tool for comparing investment opportunities, but it has limitations. It assumes that returns are normally distributed and may understate tail risk. Additionally, the results can be influenced by the chosen time period and return measurement intervals.