Instead of calculating the indicator value manually, you can try using a module. I use pandas_ta, which has many indicators built in as functions. You can find the documentation for the same online. Additionally, there is another library TA_lib, which is quite similar to pandas_ta.
def TrailStoploss(df, atr_period=14, hhv_period=10, multiplier=2.5, ATRinDF=False): """ This function calculates the trailing SL based on ATR and Multiplier set.
""" # Calculate ATR #data['ATR'] = data['High'].diff().abs().rolling(window=atr_period).mean() data = df.copy() if (ATRinDF==False): # if ATR col is not present, it will calculate the ATR otherwise it wont data["ATR"] = pta.atr(data.High, data.Low, data.Close, length=atr_period, mamode="rma") # end if
# Calculate highest high value data['HHV'] = data['High'].rolling(window=hhv_period).max()
#return data[['ATR', 'HHV', 'Prev', 'BarSinceCondition', 'TS']] """ if (ATRinDF==False): # if ATR col is not present, it will calculate the ATR otherwise it wont return round(data["ATR"],2), round(data['TS'],2) else: round(data['TS'],2) # end if """ return data.TS.round(2) # end fx
def TrailStoploss(df, atr_period=14, hhv_period=10, multiplier=2.5, ATRinDF=False):
"""
This function calculates the trailing SL based on ATR and Multiplier set.
"""
# Calculate ATR
#data['ATR'] = data['High'].diff().abs().rolling(window=atr_period).mean()
data = df.copy()
if (ATRinDF==False): # if ATR col is not present, it will calculate the ATR otherwise it wont
data["ATR"] = pta.atr(data.High, data.Low, data.Close, length=atr_period, mamode="rma")
# end if
# Calculate highest high value
data['HHV'] = data['High'].rolling(window=hhv_period).max()
# Calculate the trailing stop
data['Prev'] = data['HHV'] - multiplier * data['ATR']
condition = (data['Close'] > data['HHV']) & (data['Close'] > data['Close'].shift(1))
data['BarSinceCondition'] = np.where(condition, 0, np.nan)
data['BarSinceCondition'] = data['BarSinceCondition'].ffill().fillna(method='bfill', inplace=True)
data['TS'] = np.where(data.groupby(data['BarSinceCondition'].eq(0).cumsum())['Close'].cumcount() < 16, data['Close'], np.where(condition, data['HHV'], data['Prev']))
#return data[['ATR', 'HHV', 'Prev', 'BarSinceCondition', 'TS']]
"""
if (ATRinDF==False): # if ATR col is not present, it will calculate the ATR otherwise it wont
return round(data["ATR"],2), round(data['TS'],2)
else:
round(data['TS'],2)
# end if
"""
return data.TS.round(2)
# end fx