In its simplest form, when the Supertrend is overlayed over a candlestick chart, if the Supertrend crosses to below the Price we take a Long Position and when the Supertrend crosses to above the Price, we take a Short position. Here is a snapshot of the Supertrend.
This article from Economic Times is probably a good place to start with to get a qucik overview of Supertrend.
So let us dive straight into and get the calculation of Supertrend. Check this Google Sheet for the Calculation of Supertrend.
Given below is the pseudo code for the calculation of Supertrend:
Basic UpperrBand = (High + Low) / 2 + Multiplier * ATR Basic LowerBand = (High + Low) / 2 - Multiplier * ATR Final UpperBand = IF((Current BasicUpperband < Previous Final UpperBand) OR (Previous Close > Previous Final UpperBand)) THEN (Current Basic UpperBand) ELSE (Previous FinalUpperBand) Final LowerBand = IF((Current Basic LowerBand > Previous Final LowerBand) OR (Previous Close < Previous Final LowerBand)) THEN (Current Basic LowerBand) ELSE (Previous Final LowerBand) SuperTrend = IF((Previous SuperTrend = Previous Final UpperBand) AND (Current Close <= Current Final UpperBand)) THEN Current Final UpperBand ELSE IF((Previous SuperTrend = Previous Final UpperBand) AND (Current Close > Current Final UpperBand)) THEN Current Final LowerBand ELSE IF((Previous SuperTrend = Previous Final LowerBand) AND (Current Close >= Current Final LowerBand)) THEN Current Final LowerBand ELSE IF((Previous SuperTrend = Previous Final LowerBand) AND (Current Close < Current Final LowerBand)) THEN Current Final UpperBand
Now lets see how this is calculated in Python. Lets first download the OHLCV data from the above google sheet into a CSV file. Name it as "test data". We can use this as our input file for the Python program.
Lets first take a look at the Imports and Global Declarations that we will use in this program:
#imports used in the program import numpy as np import pandas as pd #Global Declarations input_file = "test data.csv" multiplier = 2 # An integer to indicate the value to multiply the ATR. period = 14 atr = 'ATR' + '_' + str(period) st = 'SuperTrend' + '_' + str(period) + '_' + str(multiplier)