3

I am trying to code the following algorithm for SuperTrend indicator in python using pandas.

BASIC UPPERBAND = (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

Here is the code that I wrote and tested:

# Compute basic upper and lower bands
df['basic_ub'] = (df['high'] + df['low']) / 2 + multiplier * df[atr]
df['basic_lb'] = (df['high'] + df['low']) / 2 - multiplier * df[atr]

# Compute final upper and lower bands
for i in range(0, len(df)):
    if i < period:
        df.set_value(i, 'basic_ub', 0.00)
        df.set_value(i, 'basic_lb', 0.00)
        df.set_value(i, 'final_ub', 0.00)
        df.set_value(i, 'final_lb', 0.00)
    else:
        df.set_value(i, 'final_ub', (df.get_value(i, 'basic_ub') 
                                     if df.get_value(i, 'basic_ub') < df.get_value(i-1, 'final_ub') or df.get_value(i-1, 'close') > df.get_value(i-1, 'final_ub') 
                                     else df.get_value(i-1, 'final_ub')))
        df.set_value(i, 'final_lb', (df.get_value(i, 'basic_lb') 
                                     if df.get_value(i, 'basic_lb') > df.get_value(i-1, 'final_lb') or df.get_value(i-1, 'close') < df.get_value(i-1, 'final_lb') 
                                     else df.get_value(i-1, 'final_lb')))

# Set the Supertrend value
for i in range(0, len(df)):
    if i < period:
        df.set_value(i, st, 0.00)
    else:
        df.set_value(i, 'st', (df.get_value(i, 'final_ub')
                             if ((df.get_value(i-1, 'st') == df.get_value(i-1, 'final_ub')) and (df.get_value(i, 'close') <= df.get_value(i, 'final_ub')))
                             else (df.get_value(i, 'final_lb')
                                   if ((df.get_value(i-1, 'st') == df.get_value(i-1, 'final_ub')) and (df.get_value(i, 'close') > df.get_value(i, 'final_ub')))
                                   else (df.get_value(i, 'final_lb')
                                         if ((df.get_value(i-1, 'st') == df.get_value(i-1, 'final_lb')) and (df.get_value(i, 'close') >= df.get_value(i, 'final_lb')))
                                         else (df.get_value(i, 'final_ub')
                                               if((df.get_value(i-1, 'st') == df.get_value(i-1, 'final_lb')) and (df.get_value(i, 'close') < df.get_value(i, 'final_lb')))
                                               else 0.00
                                              )
                                        )
                                  ) 
                            )
                    )


# Mark the trend direction up/down
df['stx'] = np.where((df['st'] > 0.00), np.where((df['close'] < df['st']), 'down',  'up'), np.NaN)

I works, but I am not happy with the for loop. Can anyone help optimise it?

You can find the released code on Github!

7
  • check out shift. it should put you on the right track.
    – acushner
    Aug 25, 2017 at 16:33
  • Thanks for your inputs @acushner. I have tried shift. I replaced above with df['final_ub'] = np.where(np.logical_or(df['basic_ub'] < df['final_ub'].shift(), df['close'].shift() > df['final_ub'].shift()), df['basic_ub'], df['final_ub'].shift()) and df['final_lb'] = np.where(np.logical_or(df['basic_lb'] > df['final_lb'].shift(), df['close'].shift() < df['final_lb'].shift()), df['basic_lb'], df['final_lb'].shift()). However I need to initialise df['final_ub'] = 0.00 and df['final_lb'] = 0.00, else I get KeyError exception.Yet the results are totally off. I am still debugging Any idea?
    – arkochhar
    Aug 25, 2017 at 20:19
  • You could checkout my code from my Git
    – arkochhar
    Aug 25, 2017 at 20:28
  • in this case, you're going to have to use apply for this. you can't vectorize the operation because upperband depends on its previous value.
    – acushner
    Aug 25, 2017 at 22:17
  • Thanks @acushner. Would apply not have same issue because we will need to refer to the previous value of the new column that is being added? Could you share a more an example that refers to a previous value on the web, if possible?
    – arkochhar
    Aug 26, 2017 at 12:47

2 Answers 2

5

SuperTrend Indicator is included in pandas_ta where you can simply:

import pandas_ta as ta

sti = ta.supertrend(df['High'], df['Low'], df['Close'], length=7, multiplier=3)

Given that df is a pandas DataFrame with OHLC prices, the result sti is a DataFrame with 4 columns:

  1. trend
  2. direction
  3. long
  4. short

where the trend is a concatenation of the long and short lines. Note that column captions are dynamic and contain the length and multiplier parameter values.

8
  • I have pass length 7 but I am getting data only till last 4 rows, all other rows are nan values, can you explain why?
    – Asif Khan
    Oct 16, 2021 at 13:08
  • 1
    How many rows do you have in your DF in total?
    – mac13k
    Oct 16, 2021 at 13:09
  • I have only 11 rows of each high low and close
    – Asif Khan
    Oct 16, 2021 at 16:06
  • also if you could tell me how many minimum rows value of each ,high low close should be passed to get accurate supertrend value?? because when I pass 11 rows I am getting different values than passing 60 rows..
    – Asif Khan
    Oct 16, 2021 at 16:10
  • 1
    11 - that's what I thought, because this indicator is based on ATR which uses rolling window statistics, so it as missing values at the beginning of the series.
    – mac13k
    Oct 16, 2021 at 19:27
1

Use this complete code

import numpy as np
import yfinance as yf
import pandas_datareader as pdr
import pandas as pd

data =yf.download("ACC.NS", period="1d",interval="5m")
data=data.reset_index(drop=True)

data['tr0'] = abs(data["High"] - data["Low"])
data['tr1'] = abs(data["High"] - data["Close"].shift(1))
data['tr2'] = abs(data["Low"]- data["Close"].shift(1))
data["TR"] = round(data[['tr0', 'tr1', 'tr2']].max(axis=1),2)
data["ATR"]=0.00
data['BUB']=0.00
data["BLB"]=0.00
data["FUB"]=0.00
data["FLB"]=0.00
data["ST"]=0.00

# Calculating ATR 
for i, row in data.iterrows():
    if i == 0:
        data.loc[i,'ATR'] = 0.00#data['ATR'].iat[0]
    else:
        data.loc[i,'ATR'] = ((data.loc[i-1,'ATR'] * 13)+data.loc[i,'TR'])/14

data['BUB'] = round(((data["High"] + data["Low"]) / 2) + (2 * data["ATR"]),2)
data['BLB'] = round(((data["High"] + data["Low"]) / 2) - (2 * data["ATR"]),2)


# FINAL UPPERBAND = IF( (Current BASICUPPERBAND < Previous FINAL UPPERBAND) or (Previous Close > Previous FINAL UPPERBAND))
#                     THEN (Current BASIC UPPERBAND) ELSE Previous FINALUPPERBAND)


for i, row in data.iterrows():
    if i==0:
        data.loc[i,"FUB"]=0.00
    else:
        if (data.loc[i,"BUB"]<data.loc[i-1,"FUB"])|(data.loc[i-1,"Close"]>data.loc[i-1,"FUB"]):
            data.loc[i,"FUB"]=data.loc[i,"BUB"]
        else:
            data.loc[i,"FUB"]=data.loc[i-1,"FUB"]

# FINAL LOWERBAND = IF( (Current BASIC LOWERBAND > Previous FINAL LOWERBAND) or (Previous Close < Previous FINAL LOWERBAND)) 
#                     THEN (Current BASIC LOWERBAND) ELSE Previous FINAL LOWERBAND)

for i, row in data.iterrows():
    if i==0:
        data.loc[i,"FLB"]=0.00
    else:
        if (data.loc[i,"BLB"]>data.loc[i-1,"FLB"])|(data.loc[i-1,"Close"]<data.loc[i-1,"FLB"]):
            data.loc[i,"FLB"]=data.loc[i,"BLB"]
        else:
            data.loc[i,"FLB"]=data.loc[i-1,"FLB"]



# 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


for i, row in data.iterrows():
    if i==0:
        data.loc[i,"ST"]=0.00
    elif (data.loc[i-1,"ST"]==data.loc[i-1,"FUB"]) & (data.loc[i,"Close"]<=data.loc[i,"FUB"]):
        data.loc[i,"ST"]=data.loc[i,"FUB"]
    elif (data.loc[i-1,"ST"]==data.loc[i-1,"FUB"])&(data.loc[i,"Close"]>data.loc[i,"FUB"]):
        data.loc[i,"ST"]=data.loc[i,"FLB"]
    elif (data.loc[i-1,"ST"]==data.loc[i-1,"FLB"])&(data.loc[i,"Close"]>=data.loc[i,"FLB"]):
        data.loc[i,"ST"]=data.loc[i,"FLB"]
    elif (data.loc[i-1,"ST"]==data.loc[i-1,"FLB"])&(data.loc[i,"Close"]<data.loc[i,"FLB"]):
        data.loc[i,"ST"]=data.loc[i,"FUB"]

# Buy Sell Indicator
for i, row in data.iterrows():
    if i==0:
        data["ST_BUY_SELL"]="NA"
    elif (data.loc[i,"ST"]<data.loc[i,"Close"]) :
        data.loc[i,"ST_BUY_SELL"]="BUY"
    else:
        data.loc[i,"ST_BUY_SELL"]="SELL"

2
  • You can also use for comprehensions or an applymap or apply (on the row). In your for loop you never use row, you can delete it. May 23, 2020 at 7:04
  • At least the ATR can be computed in a fully vectorized way with no difficulty. There is no reason to use an inefficient loop to compute the ATR.
    – Asclepius
    Oct 23, 2022 at 5:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.