Python

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 measure of the price fluctuations of an asset or portfolio (source).

Watch tutorial

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.

Want to learn more?

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

In the next lesson you will learn how to use Monte Carlo Simulation to Optimize a Portfolio using Pandas and NumPy.

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.

Rune

View Comments

  • 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'

    • 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.

Recent Posts

Build and Deploy an AI App

Build and Deploy an AI App with Python Flask, OpenAI API, and Google Cloud: In…

5 days ago

Building Python REST APIs with gcloud Serverless

Python REST APIs with gcloud Serverless In the fast-paced world of application development, building robust…

5 days ago

Accelerate Your Web App Development Journey with Python and Docker

App Development with Python using Docker Are you an aspiring app developer looking to level…

6 days ago

Data Science Course Made Easy: Unlocking the Path to Success

Why Value-driven Data Science is the Key to Your Success In the world of data…

2 weeks ago

15 Machine Learning Projects: From Beginner to Pro

Harnessing the Power of Project-Based Learning and Python for Machine Learning Mastery In today's data-driven…

2 weeks ago

Unlock the Power of Python: 17 Project-Based Lessons from Zero to Machine Learning

Is Python the right choice for Machine Learning? Should you learn Python for Machine Learning?…

2 weeks ago