# Step-By-Step Implementation of the SuperTrend Indicator in Python

Updated: Jun 7

**Learn to build a powerful trading strategy with the SuperTrend indicator in python**

I’ve backtested a lot of trading strategies based on an extensive amount of technical indicators. Among those, some indicators’ results are off the charts and I term these as premium indicators. In today’s article, we are going to discuss a trend-following indicator that joins this exclusive list of premium indicators concerning its performance and efficiency. It’s none other than the SuperTrend indicator.

We will first explore what this indicator is all about and its complex calculation. Then, we will move on to building the indicator from scratch in Python and construct a simple trading strategy based on it. Finally, we will backtest it on the stock of Tesla and compare the strategy’s performance with the returns of SPY ETF (an ETF specifically designed to track the movements of the S&P 500 market index). Without further ado, let’s hop into the article.

**Average True Range**

Before moving on to discovering the SuperTrend indicator, it is essential to know what the Average True Range (ATR) is as it is involved in the calculation of the SuperTrend indicator.

The Average True Range is a technical indicator that measures how much an asset moves on an average. It is a lagging indicator meaning that it takes into account the historical data of an asset to measure the current value but it’s not capable of predicting the future data points. This is not considered as a drawback while using ATR as it’s one of the indicators to track the volatility of a market more accurately. Along with being a lagging indicator, ATR is also a non-directional indicator meaning that the movement of ATR is inversely proportional to the actual movement of the market. To calculate ATR, it is requisite to follow two steps:

**Calculate True Range (TR):**A True Range of an asset is calculated by taking the greatest values of three price differences which are: market high minus marker low, market high minus previous market close, previous market close minus market low. It can be represented as follows:

```
```**MAX**** **[ {**HIGH**** ****-**** ****LOW**}, {**HIGH**** ****-**** ****P****.****CLOSE**}, {**P****.****CLOSE**** ****-**** ****LOW**} ]
where,
MAX = Maximum values
HIGH = Market High
LOW = Market Low
P.CLOSE = Previous market close

**Calculate ATR:**The calculation for the Average True Range is simple. We just have to take a smoothed average of the previously calculated True Range values for a specified number of periods. The smoothed average is not just any SMA or EMA but an own type of smoothed average created by Wilder Wiles himself but there aren’t any restrictions in using other MAs too. In this article, we will be using the Exponential Moving Average (EMA) to calculate ATR rather than the custom moving average created by the founder of the indicator just to make things simple. The calculation of ATR with a traditional setting of 14 as the number of periods can be represented as follows:

```
```**ATR**** ****14** = **EMA**** ****14** [ **TR**** **]
where,
ATR 14 = 14 Period Average True Range
SMA 14 = 14 Period Simple Moving Average
TR = True Range

While using ATR as an indicator for trading purposes, traders must ensure that they are cautious than ever as the indicator is very lagging. Now that we have an understanding of what the Average True Range is all about. Let’s now dive into the main concept of this article, the SuperTrend Indicator.

**SuperTrend Indicator**

As the name suggests, the SuperTrend indicator tracks the direction of a trending market. This indicator is well-known for its precision in spotting efficient buy and sell signals for trades. I’ve got to be honest that the calculation of the SuperTrend is kinda a complex one but I’ll breakdown into pieces to make you understand better.

There are two main components involved in the calculation of this indicator which are the lookback period and the multiplier. The lookback period is nothing but the number of data points to take into account for the calculation and the multiplier is the value used to multiply the ATR. The traditional setting of the SuperTrend indicator is 10 as the lookback period and 3 as the multiplier. By taking these settings into consideration, let’s proceed to the steps involved in the calculation of the SuperTrend indicator.

The first step involved in the calculation is to determine the 10-day ATR using the formula we discussed before. The second step is to determine the basic upper and lower band. To calculate these two bands, we need to first find the High Low average (let’s now call it HLA) which is calculated by adding the high and low values of the stock and dividing it by 2. Using these HLA values, the upper band is calculated by first multiplying the 10-day ATR values with the multiplier (which is 3) and adding the product with the HLA values. The same procedure applies to the calculation of the basic lower band too but instead of adding, we need to subtract the product with the HLA values. The calculation of the two bands can be mathematically represented as follows:

```
```**BASIC**** ****UPPER**** ****BAND** = **HLA**** **+ [ **MULTIPLIER**** *** **10****-****DAY**** ****ATR** ]
**BASIC**** ****LOWER**** ****BAND** = **HLA**** **-** **[ **MULTIPLIER**** *** **10****-****DAY**** ****ATR**** **]
where,
HLA = High Low Average
MULTIPLIER = 3

Then comes the calculation of the final upper and lower bands which are the core components involved in the calculation of the SuperTrend indicator. There is no formula for the calculation of the final bands but instead, conditions are passed and the values will be appended to the bands concerning which condition gets satisfied. The condition for the current final upper band goes as follows:

If the current basic upper band is lesser than the previous final upper band or the previous closing price of the stock is greater than the previous final upper band, then, the current final upper band’s value is the current basic upper band.

If the condition fails to get satisfied, then the current final upper band’s value is the previous final upper band. The condition of the final upper band can be represented as follows:

```
IF
```**C****.****BUB** < **P****.****FUB** OR **P****.****CLOSE** > **P****.****FUB**: **C****.****FUB** = **C****.****BUB**
IF **THE**** ****CONDITION**** ****IS**** ****NOT**** ****SATISFIED****:**** ****C****.****FUB**** **= **P****.****FUB**
where,
C.BUB = Current Basic Upper Band
P.FUB = Previous Final Upper Band
P.CLOSE = Previous Closing Price of the Stock
C.FUB = Current Final Upper Band

The condition for the current lower band goes as follows:

If the current basic lower band is greater than the previous final lower band or the previous closing price of the stock is lesser than the previous final lower band, then, the current final lower band’s value is the current basic lower band.

If this condition of the current final lower band fails to get satisfied, then the current final lower band is the previous final lower band. The condition can be represented as follows:

```
IF
```**C****.****BLB** > **P****.****FLB** OR **P****.****CLOSE** < **P****.****FLB**: **C****.****FLB** = **C****.****BLB**
IF **THE**** ****CONDITION**** ****IS**** ****NOT**** ****SATISFIED****:**** ****C****.****FLB**** **= **P****.****FLB**
where,
C.BLB = Current Basic Lower Band
P.FLB = Previous Final Lower Band
P.CLOSE = Previous Closing Price of the Stock
C.FLB = Current Final Lower Band

Now we have all the essential components to determine the values of the SuperTrend indicator. Like how we used conditions to calculate the final bands’ values, the same applies to the calculation of the SuperTrend indicator too. While there is only one condition for determining the final bands’ values, there are four different conditions for the SuperTrend indicator. The conditions for the current SuperTrend value goes as follows:

If the previous SuperTrend indicator value is equal to the previous final upper band and the current closing price of the stock is lesser than the current final upper band, then, the current SuperTrend indicator value is the current final upper band.

If the previous SuperTrend indicator value is equal to the previous final upper band and the current closing price of the stock is greater than the current final upper band, then, the current SuperTrend indicator value is the current final lower band.

If the previous SuperTrend indicator value is equal to the previous final lower band and the current closing price of the stock is greater than the current final lower band, then, the current SuperTrend indicator value is the current final lower band.

If the previous SuperTrend indicator value is equal to the previous final lower band and the current closing price of the stock is lesser than the current final lower band, then, the current SuperTrend indicator value is the current final upper band.

When putting all these conditions together, the collective number of conditions can be represented as follows:

```
IF
```**P****.****ST** == **P****.****FUB** AND **C****.****CLOSE** < **C****.****FUB**: **C****.****ST** = **C****.****FUB**
IF **P****.****ST** == **P****.****FUB** AND **C****.****CLOSE** > **C****.****FUB**: **C****.****ST** = **C****.****FLB**
IF **P****.****ST** == **P****.****FLB** AND **C****.****CLOSE** > **C****.****FLB**: **C****.****ST** = **C****.****FLB**
IF **P****.****ST** == **P****.****FLB** AND **C****.****CLOSE** < **C****.****FLB**: **C****.****ST** = **C****.****FUB**
where,
P.ST = Previous SuperTrend indicator value
P.FUB = Previous Final Upper Band
P.FLB = Previous Final Lower Band
C.CLOSE = Current Closing Price of the Stock
C.ST = Current SuperTrend indicator value
C.FUB = Current Final Upper Band
C.FLB = Current Final Lower Band

That’s the whole process of calculating the SuperTrend indicator values. To build a stronger understanding of the indicator and how it works, let’s explore a chart where the closing price of a stock is plotted along with the SuperTrend indicator’s readings.

In the above chart, the blue line represents the closing price of the Tesla stock and the line with both red and green color represents the readings of the SuperTrend indicator. The line of the SuperTrend indicator turns green if the readings of the indicator are below the closing price and turns red if it’s above the closing price. As I said before, the SuperTrend indicator is a trend-following indicator and this can be observed in the chart that the indicator directly reveals the current trend of the market more accurately.

Traders use the color changes or trend changes observed in the SuperTrend indicator line to mark buy and sell signals for their trades. To be more elaborate, traders go long (buy the stock) if the indicator’s line crosses from above to below the closing price line, and similarly, they go short (sell the stock) if the indicator’s line crosses from below to above the closing price line. This SuperTrend strategy is called the crossover strategy. This strategy can be represented as follows:

```
IF
```**PREV****.****ST** > **PREV****.****CLOSE** AND **CUR****.****ST** < **CUR****.****CLOSE** ==> **BUY**** ****SIGNAL**
IF **PREV****.****ST** < **PREV****.****CLOSE** AND **CUR****.****ST** > **CUR****.****CLOSE** ==> **SELL**** ****SIGNAL**

This is the strategy we are going to implement in this article too. Many other strategies can also be implemented based on the SuperTrend indicator but just to make things simple to understand, we are going with the crossover strategy. This concludes our theory part on the SuperTrend indicator. Now, let’s move on to the coding part where we are first going to build the indicator from scratch, build the crossover strategy which we just discussed, then, compare our strategy’s performance with the SPY ETF’s returns in Python. Let’s do some coding! Before moving on, a note on disclaimer: This article’s sole purpose is to educate people and must be considered as an information piece but not as investment advice or so.

**Implementation in Python**

The coding part is classified into various steps as follows:

```
```**1.**** Importing Packages**
**2.**** Extracting Stock Data ****from**** Twelve Data**
**3.**** SuperTrend Calculation**
**4.**** Creating the Crossover Trading Strategy**
**5.**** Plotting the Trading Lists**
**6.**** Creating our Position**
**7.**** Backtesting**
**8.**** ****SPY**** ****ETF**** Comparison**

We will be following the order mentioned in the above list and buckle up your seat belts to follow every upcoming coding part.

**Step-1: Importing Packages**

Importing the required packages into the python environment is a non-skippable step. The primary packages are going to be Pandas to work with data, NumPy to work with arrays and for complex functions, Matplotlib for plotting purposes, and Requests to make API calls. The secondary packages are going to be Math for mathematical functions and Termcolor for font customization (optional).

**Python Implementation:**

```
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import requests
from math import floor
from termcolor import colored as cl
plt.style.use('fivethirtyeight')
plt.rcParams['figure.figsize'] = (20,10)
```

Now that we have imported all the required packages into our python. Let’s pull the historical data of Tesla with Twelve Data’s API endpoint.

**Step-2: Extracting data from Twelve Data**

In this step, we are going to pull the historical stock data of Tesla using an API endpoint provided by twelvedata.com. Before that, a note on twelvedata.com: Twelve Data is one of the leading market data providers having an enormous amount of API endpoints for all types of market data. It is very easy to interact with the APIs provided by Twelve Data and has one of the best documentation ever. Also, ensure that you have an account on twelvedata.com, only then, you will be able to access your API key (vital element to extract data with an API).

**Python Implementation:**

```
def get_historical_data(symbol, start_date):
api_key = 'YOUR API KEY'
api_url = f'https://api.twelvedata.com/time_series?symbol={symbol}&interval=1day&outputsize=5000&apikey={api_key}'
raw_df = requests.get(api_url).json()
df = pd.DataFrame(raw_df['values']).iloc[::-1].set_index('datetime').astype(float)
df = df[df.index >= start_date]
df.index = pd.to_datetime(df.index)
return df
tsla = get_historical_data('TSLA', '2020-01-01')
tsla
```

**Output:**

**Code Explanation:** The first thing we did is to define a function named ‘get_historical_data’ that takes the stock’s symbol (‘symbol’) and the starting date of the historical data (‘start_date’) as parameters. Inside the function, we are defining the API key and the URL and stored them into their respective variable. Next, we are extracting the historical data in JSON format using the ‘get’ function and stored it into the ‘raw_df’ variable. After doing some processes to clean and format the raw JSON data, we are returning it in the form of a clean Pandas dataframe. Finally, we are calling the created function to pull the historic data of Tesla from the starting of 2020 and stored it into the ‘tsla’ variable.

**Step-3: SuperTrend Calculation**

In this step, we are going to calculate the values of the SuperTrend indicator by following the methods we discussed before.

**Python Implementation:**

```
def get_supertrend(high, low, close, lookback, multiplier):
```** # ****ATR**
tr1 = pd.DataFrame(high - low)
tr2 = pd.DataFrame(abs(high - close.shift(1)))
tr3 = pd.DataFrame(abs(low - close.shift(1)))
frames = [tr1, tr2, tr3]
tr = pd.concat(frames, axis = 1, join = 'inner').max(axis = 1)
atr = tr.ewm(lookback).mean()
** # ****H****/****L**** ****AVG**** ****AND**** ****BASIC**** ****UPPER**** ****&**** ****LOWER**** ****BAND**
hl_avg = (high + low) / 2
upper_band = (hl_avg + multiplier * atr).dropna()
lower_band = (hl_avg - multiplier * atr).dropna()
**# ****FINAL**** ****UPPER**** ****BAND**
** **final_bands = pd.DataFrame(columns = ['upper', 'lower'])
final_bands.iloc[:,0] = [x for x in upper_band - upper_band]
final_bands.iloc[:,1] = final_bands.iloc[