How to compute the Sharpe Ratio using Python

4 min

The Sharpe ratio is a metric used by investors to evaluate the return of an investment compared to its risk.

The higher the Sharpe the better the return is compared to its risk.

The Sharpe ratio formula is given by:

Where

So there are a few steps before we are able to compute the Sharpe Ratio.

  1. Compute the portfolio returns
  2. Get the risk-free rate
  3. Compute the standard deviation of the excess returns

How to compute the portfolio returns

Usually, the portfolio returns are computed from an initial portfolio value and the portfolio value at date.

Here is the formula

The return formula

Let me illustrate it using an example

If you invested 1,000 USD a year ago, but today this invested amount is worth 10,000 USD you would have had a return of ~900% since inception.

The return of this portfolio

How to get the risk free rate

The risk-free rate is the return rate that you would normally get if you were to invest in the least risky asset on the market. What is most often used as a reference is the T-bonds rate. But as today's rates are extremely low we usually take 0% (you could put 1% but IMO it is still a bit too optimistic).

How to compute the standard deviation of the excess returns

The excess returns are the portfolio returns minus the risk-free rate.

Since we are taking 0% as risk-free rate, our standard deviation will be the standard deviation of our portfolio's returns.

Here is the formula of the standard deviation

As you can see the standard deviation is the squared root of the variance.

Furthermore, our X_i here will be the portfolio's return at date i.

In finance the standard deviation is a proxy for volatility, so to say how much our portfolio varies over time. Remember, in investing you often aim for a portfolio with minimal variance and maximum returns.

This is because investors usually don't like when their portfolio drops 40% during the night.

So how do we code this standard deviation?

We will need the evolution of the portfolio returns over time to get its standard deviation.

Let me show you using an example

The code

For this example, we will compute the Sharpe ratio of one Apple stock bought on the 2nd of January 2020.

We use yfinance to fetch Apple stocks data from Yahoo.

We simulate the performance of the stock as if it was held onto until today.

import yfinance as yf
import matplotlib.pyplot as plt

# We download Apple stock prices since 2020 01 02
df = yf.download(["AAPL"], start='2020-01-02')

# We compute the portfolio's returns
portfolio_returns = (df["Close"] - df["Close"][0]) / df["Close"][0]

# We compute the standard deviation of the excess return here as risk free rate
# is 0 the excess return equal the portfolio's returns
portfolio_std = returns.std()

# We compute the sharpe ratio
portfolio_sharpe = portfolio_returns / portfolio_std

# We plot the canvas
fig, axes = plt.subplots(2,1, figsize=(8,6), sharex=True)

# We plot the close prices
axes[0].plot(df["Close"])
axes[0].set_title("AAPL close price")
axes[0].set_ylabel("USD price")
axes[0].grid()

# We plot the portfolio sharpe ratio evolution
axes[1].plot(portfolio_sharpe, c='tab:orange')
axes[1].set_title("AAPL sharpe ratio evolution")
axes[1].set_ylabel("Sharpe ratio")
axes[1].grid()

# We clean and tidy our plot
fig.tight_layout()

# We plot it
plt.plot()
How to compute the Sharpe Ratio using Python

Here you are! You now know how to compute the Sharpe Ratio using Python!

More on financial analysis

If you want to know more about Financial Analysis in Python and avoid the headaches... check out the other articles I wrote by clicking just here:

Financial Analysis - The Python You Need
We gathered the only Python essentials that you will probably ever need.