Skip to content
>GLB_
Go back

Comparing Risk-Adjusted Returns Using the Sharpe Ratio in Python

Investors frequently face the challenge of assessing whether an asset’s return justifies its risk. This is where the Sharpe Ratio becomes invaluable, providing a measure that accounts for both returns and risk in a single metric. In this post, we’ll go over how to calculate and interpret the Sharpe Ratio in Python, using real stock data from three popular companies—Apple (AAPL), Tesla (TSLA), and Microsoft (MSFT).

Understanding the Sharpe Ratio

The Sharpe Ratio helps investors measure the risk-adjusted return of an asset. In simple terms, it tells us how much return we earn per unit of risk taken. For instance:

The Sharpe Ratio is often annualized to standardize comparisons and account for daily fluctuations. The formula to calculate the annualized Sharpe Ratio is:

Sharpe Ratio = (Average Excess Return / Standard Deviation of Excess Return) * sqrt(252)

Where:

A Sharpe Ratio greater than 1 is often seen as favorable, while a ratio below 1 suggests the risk might outweigh the returns.

Step-by-Step Python Code for Sharpe Ratio Calculation

Now, let’s implement this in Python and apply it to real stock data using the yfinance library.

# Import necessary libraries
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt

# Step 1: Define assets and download historical data
assets = ["AAPL", "TSLA", "MSFT"]
data = yf.download(assets, start="2022-01-01", end="2023-01-01")['Adj Close']

# Step 2: Calculate daily returns for each asset
daily_returns = data.pct_change().dropna()

# Step 3: Function to calculate Sharpe Ratio
def calculate_sharpe_ratio(returns, risk_free_rate=0):
    excess_returns = returns - risk_free_rate
    return np.mean(excess_returns) / np.std(excess_returns) * np.sqrt(252)

# Calculate Sharpe Ratios for each asset
sharpe_ratios = {asset: calculate_sharpe_ratio(daily_returns[asset]) for asset in assets}

# Display Sharpe Ratios
print("Sharpe Ratios of Selected Assets:")
for asset, ratio in sharpe_ratios.items():
    print(f"{asset}: {ratio:.2f}")

# Step 4: Visualize the Sharpe Ratios
plt.figure(figsize=(10, 6))
plt.bar(sharpe_ratios.keys(), sharpe_ratios.values(), color=['blue', 'orange', 'green'])
plt.title('Sharpe Ratios of Selected Assets')
plt.xlabel('Assets')
plt.ylabel('Sharpe Ratio')
plt.show()

# Additional: Calculate annualized volatility for a risk comparison
volatility = daily_returns.std() * np.sqrt(252)
print("\nAnnualized Volatility of Selected Assets:")
for asset, vol in volatility.items():
    print(f"{asset}: {vol:.2f}")
Sharpe Ratios of Selected Assets:
AAPL: -0.76
TSLA: -1.49
MSFT: -0.75

How to Interpret the Sharpe Ratio

What Does the Sharpe Ratio Tell Us?

Understanding Sharpe Ratios for Each Asset

Let’s say our calculated Sharpe Ratios show the following:

Tesla, despite its growth potential, may exhibit substantial volatility, contributing to a negative Sharpe Ratio. This doesn’t necessarily mean Tesla is a “bad” investment, but it implies that the returns do not consistently justify the level of risk, especially if the investor is risk-averse.

Conclusion

In this post, we used Python to calculate and analyze the Sharpe Ratio for different assets, learning how it serves as a useful metric to gauge risk-adjusted performance. By comparing the Sharpe Ratios and understanding the volatility of assets like Apple, Tesla, and Microsoft, investors can gain insight into which assets provide the best returns for the level of risk.


Share this post:

Previous Post
Comparative Investment Analysis of Invesco and Blackstone Using Python
Next Post
Handling the "ERR_HTTP_HEADERS_SENT" Error in Node.js Express