ATR Trailing Stop loss Strategy Python

simonofficial
I'm trying to code ATR Trailing Stop loss. But the values are not matching with algo - back tested with streak / Trading view.

ATR Trailing stoploss (multiplier =1 and Period =5). I want to understand how it is calculated.

For example:
Close price crosses above ATR Trailing stoploss (What is the ATR Trailing stoploss here).

Is it previous close + (ATR*Multiplier) or Previous EMA 1 + (ATR*Multiplier)?

It will be helpful if anyone can help me with this part.

I do calculate ATR:
# Define a function to calculate ATR manually
def calculate_atr(df, window=5):
tr = pd.DataFrame()
tr['h-l'] = df['high'] - df['low']
tr['h-pc'] = np.abs(df['high'] - df['close'].shift())
tr['l-pc'] = np.abs(df['low'] - df['close'].shift())
atr = tr.max(axis=1).rolling(window=window).mean()
return atr

Am i doing it right or missing something? What to do with this ATR to get the condition close price crosses above ATR Trailing stop loss?
  • chinmay227
    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.
  • gsx_3013
    Le bhai tu bhi yaad rakhio apne dua mein ...

    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
Sign In or Register to comment.