Python

How to Calculate Volatility as Average True Range (ATR) with Python DataFrames and NumPy

What will we cover?

In this tutorial we will learn about the volatility of a stock price measured with Average True Range. The Volatility of a stock is one measure of investment risk.

The Average True Range was originally designed to calculate the volatility of commodities, but the technical indicator can also be used for stock prices, as we will do in this tutorial.

We will get some stock price time series data and make the calculation using pandas DataFrames and NumPy.

Step 1: Get historic stock price data

To get started, we need some historic stock prices. This can be done as follows and is covered in Lesson 1.

import numpy as np
import pandas_datareader as pdr
import datetime as dt
import pandas as pd

start = dt.datetime(2020, 1, 1)
data = pdr.get_data_yahoo("NFLX", start)

This reads the time series data of the historic stock prices of Netflix (ticker NFLX).

Step 2: The formula of Average True Range (ATR)

To calculate the Average True Range (ATR) we need a formula, which is given on investoperia.org.

The Average True Range (ATR) is a moving average of the True Range (TR). And the TR is given by the maximum of the current high (H) minus current low (L), the absolute value of current high (H) minus previous close (Cp), and the absolute value of current low (L) and previous close (Cp).

Sted 3: The calculations of Average True Range with DataFrames and NumPy

The above formula can look intimidating at first, but don’t worry, this is where the power of Pandas DataFrames and Series come into the picture.

It is always a good idea to make your calculations simple.

high_low = data['High'] - data['Low']
high_cp = np.abs(data['High'] - data['Close'].shift())
low_cp = np.abs(data['Low'] - data['Close'].shift())

Here we make a Series for each of the values needed. Notice, that we get the previous close by using shift() (data[‘Close’].shift()).

Then a great way to get the maximum value of these is to create a DataFrame with all the values.

df = pd.concat([high_low, high_cp, low_cp], axis=1)
true_range = np.max(df, axis=1)

Now that is nice.

Then we get the ATR as the moving average of 14 days (14 days is the default).

average_true_range = true_range.rolling(14).mean()

Step 4: Visualize the result with Matplotlib

Finally, let’s try to visualize it. Often visualization helps us understand it better.

import matplotlib.pyplot as plt
%matplotlib notebook

fig, ax = plt.subplots()
average_true_range.plot(ax=ax)
ax2 = data['Close'].plot(ax=ax, secondary_y=True, alpha=.3)
ax.set_ylabel("ATR")
ax2.set_ylabel("Price")

Resulting in the following chart.

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
Rune

Recent Posts

Python Project: Fibonacci

Project Description The Fibonacci sequence is as follows. 0 1 1 2 3 5 8…

2 weeks ago

Python Project: ELIZA

How ELIZA works? It looks for simple patterns and substitutes to give the illusion of…

2 weeks ago

Python Project: ToDo List

Project Description The program you write can do 4 things. It can show the content…

3 weeks ago

Python Project: Store

Project Description You will start to sell items from your awesome store. You count items…

1 month ago

Python Project: Temperature Converter

Project Description Create a converter from Fahrenheit to celsius using the formula °𝐶=(°𝐹−32)×5/9 Project Prompt…

2 months ago

Python Project: Leet speak

Project Description Leet (or "1337"), also known as eleet or leetspeak, is a system of…

2 months ago