Geek Logbook

Tech sea log book

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:

  • High Sharpe Ratio: Indicates that an asset is providing higher returns relative to the risk it involves.
  • Low or Negative Sharpe Ratio: Indicates that an asset’s returns do not sufficiently compensate for its risk or that the asset has negative returns relative to its risk.

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:

  • Average Excess Return is the average return of the asset above the risk-free rate.
  • Standard Deviation of Excess Return measures the volatility (or risk) of the asset.
  • sqrt(252) is an annualizing factor, assuming 252 trading days in a year.

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?

  • Higher Ratio: Indicates more return per unit of risk, suggesting the asset is compensating well for the risk taken.
  • Lower or Negative Ratio: Indicates poor compensation for risk or even losses relative to risk. For instance, a negative Sharpe Ratio, as seen in assets with prolonged negative returns, suggests that the investor might not be compensated for the risk and may even be losing money.

Understanding Sharpe Ratios for Each Asset

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

  • Apple (AAPL): 0.85 — Positive and approaching 1, suggesting relatively good performance relative to its risk.
  • Tesla (TSLA): -1.49 — Negative, meaning that the risk outweighs the returns.
  • Microsoft (MSFT): -0.75 — Also negative, though closer to zero, indicating that the risk isn’t fully justified by the returns.

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.

Tags: