Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

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

    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.

    Python Circle

    Do you know what the 5 key success factors every programmer must have?

    How is it possible that some people become programmer so fast?

    While others struggle for years and still fail.

    Not only do they learn python 10 times faster they solve complex problems with ease.

    What separates them from the rest?

    I identified these 5 success factors that every programmer must have to succeed:

    1. Collaboration: sharing your work with others and receiving help with any questions or challenges you may have.
    2. Networking: the ability to connect with the right people and leverage their knowledge, experience, and resources.
    3. Support: receive feedback on your work and ask questions without feeling intimidated or judged.
    4. Accountability: stay motivated and accountable to your learning goals by surrounding yourself with others who are also committed to learning Python.
    5. Feedback from the instructor: receiving feedback and support from an instructor with years of experience in the field.

    I know how important these success factors are for growth and progress in mastering Python.

    That is why I want to make them available to anyone struggling to learn or who just wants to improve faster.

    With the Python Circle community, you can take advantage of 5 key success factors every programmer must have.

    Python Circle
    Python Circle

    Be part of something bigger and join the Python Circle community.

    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)
      —-> 4 data = pdr.get_data_yahoo(tickers, start)
      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.


        It should print 0.10.0

        If older – update it first.


    Leave a Comment