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.

12% Investment Solution

Would you like to get 12% in return of your investments?

D. A. Carter promises and shows how his simple investment strategy will deliver that in the book The 12% Solution. The book shows how to test this statement by using backtesting.

Did Carter find a strategy that will consistently beat the market?

Actually, it is not that hard to use Python to validate his calculations. But we can do better than that. If you want to work smarter than traditional investors then continue to read here.

Want to learn more?

This is part of a 2.5-hour full video course in 8 parts about Risk and Return.

If you are serious about learning Python for Finance check out this course.

  • Learn Python for Finance with pandas and NumPy.
  • 21 hours of video in over 180 lectures.
  • “Excellent course for anyone trying to learn to code and invest.” Lorenzo B.

Get Python for Finance HERE.

Python for Finance

Learn Python

Learn Python A BEGINNERS GUIDE TO PYTHON

  • 70 pages to get you started on your journey to master Python.
  • How to install your setup with Anaconda.
  • Written description and introduction to all concepts.
  • Jupyter Notebooks prepared for 17 projects.

Python 101: A CRASH COURSE

  1. How to get started with this 8 hours Python 101: A CRASH COURSE.
  2. Best practices for learning Python.
  3. How to download the material to follow along and create projects.
  4. A chapter for each lesson with a descriptioncode snippets for easy reference, and links to a lesson video.

Expert Data Science Blueprint

Expert Data Science Blueprint

  • Master the Data Science Workflow for actionable data insights.
  • How to download the material to follow along and create projects.
  • A chapter to each lesson with a Description, Learning Objective, and link to the lesson video.

Machine Learning

Machine Learning – The Simple Path to Mastery

  • How to get started with Machine Learning.
  • How to download the material to follow along and make the projects.
  • One chapter for each lesson with a Description, Learning Objectives, and link to the lesson video.

2 thoughts on “How to Calculate Sharpe Ratio with Pandas and NumPy”

  1. thanks for the video .
    am running into errors

    /usr/local/lib/python3.7/dist-packages/pandas_datareader/base.py:272: SymbolWarning: Failed to read symbol: ‘TATAMOTORS.NS’, replacing with NaN.
    warnings.warn(msg.format(sym), SymbolWarning)
    /usr/local/lib/python3.7/dist-packages/pandas_datareader/base.py:272: SymbolWarning: Failed to read symbol: ‘MSFT’, replacing with NaN.
    warnings.warn(msg.format(sym), SymbolWarning)
    /usr/local/lib/python3.7/dist-packages/pandas_datareader/base.py:272: SymbolWarning: Failed to read symbol: ‘TWTR’, replacing with NaN.
    warnings.warn(msg.format(sym), SymbolWarning)
    /usr/local/lib/python3.7/dist-packages/pandas_datareader/base.py:272: SymbolWarning: Failed to read symbol: ‘IBM’, replacing with NaN.
    warnings.warn(msg.format(sym), SymbolWarning)

    —————————————————————————

    RemoteDataError Traceback (most recent call last)

    in ()
    2 start = dt.datetime(2020, 1, 1)
    3
    —-> 4 data = pdr.get_data_yahoo(tickers, start)
    5
    6 data = data[‘Adj Close’]

    2 frames

    /usr/local/lib/python3.7/dist-packages/pandas_datareader/base.py in _dl_mult_symbols(self, symbols)
    275 if len(passed) == 0:
    276 msg = “No data fetched using {0!r}”
    –> 277 raise RemoteDataError(msg.format(self.__class__.__name__))
    278 try:
    279 if len(stocks) > 0 and len(failed) > 0 and len(passed) > 0:

    RemoteDataError: No data fetched using ‘YahooDailyReader’

    Reply
    • First check if you have the newest version of pandas datareader.

      print(pdr.__version__)

      It should print 0.10.0

      If older – update it first.

      Reply

Leave a Comment