How to Calculate Sharpe Ratio with Pandas and NumPy

What will we cover?

In this tutorial we will see how to calculate the Sharpe Ratio using pandas DataFrames and NumPy with Python.

The Sharpe Ratio combines Risk and Return in one number.

The Sharpe Ratio is the average return earned in excess of the risk-free rate per unit of volatility or total risk. Volatility is a measure of the price fluctuations of an asset or portfolio (source).

Step 1: The formula for Sharpe Ratio and how to interpret the result

The Sharpe Ratio is the average return earned in excess of the risk-free rate per unit of volatility or total risk.

The idea with Sharpe Ratio, is to have one number to represent both return and risk. This makes it easy to compare different weights of portfolios. We will use that in the next lesson about Monte Carlo Simulations for Portfolio Optimization.

Now that is a lot of words. How does the Sharpe Ratio look like.

We need the return of the portfolio and the risk free return, as well as the standard deviation of the portfolio.

  • The return of the portfolio we covered in lesson 1, but we will calculate it with log returns here. 
  • It is custom for the risk free return to use the 10 Year Treasury Note, but as it has been low for long time, often 0 is used.
  • The standard deviation is a measure of the volatility, and is used here to represent the risk. This is similar to Average True Range.

Step 2: Get a portfolio of stock prices with Pandas Datareader

To get started, we need to read time series data of historic stock prices for a portfolio. This can be done as follows.

import numpy as np
import pandas_datareader as pdr
import datetime as dt
import pandas as pd
 
tickers = ['AAPL', 'MSFT', 'TWTR', 'IBM']
start = dt.datetime(2020, 1, 1)
 
data = pdr.get_data_yahoo(tickers, start)
data = data['Adj Close']

Where our portfolio will consist of the tickers for Apple, Microsoft, Twitter and IBM (AAPLMSFTTWTRIBM). We read the data from start 2020 from the Yahoo! Finance API using Pandas Datareader.

Finally, we only keep the Adjusted Close price.

Step 3: Calculate the log-return of the portfolio

Let’s assume our portfolio is balanced as follows, 25%, 15%, 40%, and 20% to AAPLMSFTTWTRIBM, respectively.

Then we can calculate the daily log return of the portfolio as follows.

portfolio = [.25, .15, .40, .20]
log_return = np.sum(np.log(data/data.shift())*portfolio, axis=1)

Where we use the np.log to take the logarithm of the daily change, we apply the portfolio. Finally, we sum (np.sum) along the rows (axis=1).

Step 4: Visualize the log-return of the portfolio

For the fun, we can visualize the daily log returns as follows.

import matplotlib.pyplot as plt
%matplotlib notebook
 
fig, ax = plt.subplots()
log_return.hist(bins=50, ax=ax)

Resulting in this.

This gives an impression of how volatile the portfolio is. The more data is centered around 0.0, the less volatile and risky.

Step 5: Calculate the Sharpe Ratio of the Portfolio

The Sharpe Ratio can be calculate directly as follows.

sharpe_ratio = log_return.mean()/log_return.std()

This gives a daily Sharpe Ratio, where we have the return to be the mean value. That is, the average return of the investment. And divided by the standard deviation. 

The greater is the standard deviation the greater the magnitude of the deviation from the meanvalue can be expected.

To get an annualized Sharpe Ratio.

asr = sharpe_ratio*252**.5

This is the measure we will use in the next lesson, where we will optimize the portfolio using Monte Carlo Simulation.

What next?

If you want to learn more? Then this is one part of a 8 lesson video course.

Leave a Reply