Advertisement
akanoce

Trality_Supertrend

Mar 1st, 2022
980
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.39 KB | None | 0 0
  1. def get_supertrend(data, atr_period, atr_multiplier):
  2.    
  3.     # ATR
  4.     atr = data.atr(period=atr_period)
  5.     atr_df = atr.to_pandas()
  6.    
  7.     data_df = data.to_pandas()
  8.  
  9.     high, low, close = data_df['high'],data_df['low'],data_df['close']
  10.      # HL2 is simply the average of high and low prices
  11.     hl2 = (high + low) / 2
  12.     # upperband and lowerband calculation
  13.     # notice that final bands are set to be equal to the respective bands
  14.     final_upperband = upperband = hl2 + (atr_multiplier * atr_df['atr'])
  15.     final_lowerband = lowerband = hl2 - (atr_multiplier * atr_df['atr'])
  16.  
  17.     # print(final_upperband)
  18.    
  19.    
  20.     # initialize Supertrend column to True
  21.     supertrend = [1] * len(data_df)
  22.     for i in range(1, len(data_df.index)):
  23.         curr, prev = i, i-1
  24.        
  25.         # if current close price crosses above upperband
  26.         if close[curr] > final_upperband[prev]:
  27.             supertrend[curr] = 1
  28.         # if current close price crosses below lowerband
  29.         elif close[curr] < final_lowerband[prev]:
  30.             supertrend[curr] = -1
  31.         # else, the trend continues
  32.         else:
  33.             supertrend[curr] = supertrend[prev]
  34.            
  35.             # adjustment to the final bands
  36.             if supertrend[curr] == 1 and final_lowerband[curr] < final_lowerband[prev]:
  37.                 final_lowerband[curr] = final_lowerband[prev]
  38.             if supertrend[curr] == -1 and final_upperband[curr] > final_upperband[prev]:
  39.                 final_upperband[curr] = final_upperband[prev]
  40.  
  41.         # to remove bands according to the trend direction
  42.         if supertrend[curr] == 1:
  43.             final_upperband[curr] = np.nan
  44.         else:
  45.             final_lowerband[curr] = np.nan
  46.  
  47.     # print(supertrend)
  48.     final_df = pd.DataFrame({
  49.         'Supertrend': supertrend,
  50.         'Final Lowerband': final_lowerband,
  51.         'Final Upperband': final_upperband
  52.     }, index=data_df.index)
  53.     # print(final_df.tail(1))
  54.  
  55.     active_band = final_lowerband[-1] if not np.isnan(final_lowerband[-1]) else final_upperband[-1]
  56.     with PlotScope.root(data.symbol):
  57.         plot_line(f"supertrend ({atr_period}/{atr_multiplier})", active_band)
  58.     return supertrend, active_band
  59.     # return pd.DataFrame({
  60.     #     'Supertrend': supertrend,
  61.     #     'Final Lowerband': final_lowerband,
  62.     #     'Final Upperband': final_upperband
  63.     # }, index=df.index)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement