Super Trend back testing with python(Part-2)

Complete Python Code for Super Trend:

def TrueRange(data):
data = data.copy()
data["TR"] = np.nan
for i in range(1,len(data)):
h = data.loc[i,"high"]
l = data.loc[i,"low"]
pc = data.loc[i-1,"close"]
x = h-l
y = abs(h-pc)
z = abs(l-pc)
TR = max(x,y,z)
data.loc[i,"TR"] = TR
return data

def average_true_range(data, period=10, drop_tr=True, smoothing="SMA"):
data = data.copy()
if smoothing == "RMA":
data['atr_' + str(period) + '_' + str(smoothing)] = data['TR'].ewm(com=period - 1,
min_periods=period).mean()
elif smoothing == "SMA":
data['atr_' + str(period) + '_' + str(smoothing)] = data['TR'].rolling(window=period).mean()
elif smoothing == "EMA":
data['atr_' + str(period) + '_' + str(smoothing)] = data['TR'].ewm(span=period, adjust=False).mean()
if drop_tr:
data.drop(['TR'], inplace=True, axis=1)
data = data.round(decimals=2)
return data
def SuperTrend(data):
### Time frame changing
import time
start = time.time()
TR1 = TrueRange(data)
ATR_df = average_true_range(data = TR1, period=10, drop_tr=True, smoothing="SMA")
f=2
n=11
df2 = ATR_df.copy()
#Calculation of SuperTrend
df2['Upper Basic']=(df2['high']+df2['low'])/2+(f*df2['atr_10_SMA'])
df2['Lower Basic']=(df2['high']+df2['low'])/2-(f*df2['atr_10_SMA'])
df2['Upper Band']=df2['Upper Basic']
df2['Lower Band']=df2['Lower Basic']
for i in range(n,len(df2)):
if df2['close'][i-1]<=df2['Upper Band'][i-1]:
df2['Upper Band'][i]=min(df2['Upper Basic'][i],df2['Upper Band'][i-1])
else:
df2['Upper Band'][i]=df2['Upper Basic'][i]
for i in range(n,len(df2)):
if df2['close'][i-1]>=df2['Lower Band'][i-1]:
df2['Lower Band'][i]=max(df2['Lower Basic'][i],df2['Lower Band'][i-1])
else:
df2['Lower Band'][i]=df2['Lower Basic'][i]
df2['SuperTrend']=np.nan
for i in df2['SuperTrend']:
if df2['close'][n-1]<=df2['Upper Band'][n-1]:
df2['SuperTrend'][n-1]=df2['Upper Band'][n-1]
elif df2['close'][n-1]>df2['Upper Band'][i]:
df2['SuperTrend'][n-1]=df2['Lower Band'][n-1]
for i in range(n,len(df2)):
if df2['SuperTrend'][i-1]==df2['Upper Band'][i-1] and df2['close'][i]<=df2['Upper Band'][i]:
df2['SuperTrend'][i]=df2['Upper Band'][i]
elif df2['SuperTrend'][i-1]==df2['Upper Band'][i-1] and df2['close'][i]>=df2['Upper Band'][i]:
df2['SuperTrend'][i]=df2['Lower Band'][i]
elif df2['SuperTrend'][i-1]==df2['Lower Band'][i-1] and df2['close'][i]>=df2['Lower Band'][i]:
df2['SuperTrend'][i]=df2['Lower Band'][i]
elif df2['SuperTrend'][i-1]==df2['Lower Band'][i-1] and df2['close'][i]<=df2['Lower Band'][i]:
df2['SuperTrend'][i]=df2['Upper Band'][i]
end = time.time()
print('Time taken for SuperTrend Calculation:',(end - start)/60,'minutes')
return df2

For more about code please follow my Git link -

If you like the post and for feature Updates follow me in link din -

I'm a Data Science enthusiast who loves to play with machine learning and deep learning.