Python ## How to Calculate Sharpe Ratio with Pandas and NumPy

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

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

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 (**AAPL**, **MSFT**, **TWTR**, **IBM**). We read the data from start 2020 from the** Yahoo! Finance API** using **Pandas Datareader.**

Finally, we only keep the **Adjusted Close** price.

Let’s assume our portfolio is balanced as follows, 25%, 15%, 40%, and 20% to **AAPL**, **MSFT**, **TWTR**, **IBM**, 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**).

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.

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 **mean**value 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.

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.

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.

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

5 days ago

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

5 days ago

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

6 days ago

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

2 weeks ago

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

2 weeks ago

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

2 weeks ago

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