Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- def get_supertrend(data, atr_period, atr_multiplier):
- # ATR
- atr = data.atr(period=atr_period)
- atr_df = atr.to_pandas()
- data_df = data.to_pandas()
- high, low, close = data_df['high'],data_df['low'],data_df['close']
- # HL2 is simply the average of high and low prices
- hl2 = (high + low) / 2
- # upperband and lowerband calculation
- # notice that final bands are set to be equal to the respective bands
- final_upperband = upperband = hl2 + (atr_multiplier * atr_df['atr'])
- final_lowerband = lowerband = hl2 - (atr_multiplier * atr_df['atr'])
- # print(final_upperband)
- # initialize Supertrend column to True
- supertrend = [1] * len(data_df)
- for i in range(1, len(data_df.index)):
- curr, prev = i, i-1
- # if current close price crosses above upperband
- if close[curr] > final_upperband[prev]:
- supertrend[curr] = 1
- # if current close price crosses below lowerband
- elif close[curr] < final_lowerband[prev]:
- supertrend[curr] = -1
- # else, the trend continues
- else:
- supertrend[curr] = supertrend[prev]
- # adjustment to the final bands
- if supertrend[curr] == 1 and final_lowerband[curr] < final_lowerband[prev]:
- final_lowerband[curr] = final_lowerband[prev]
- if supertrend[curr] == -1 and final_upperband[curr] > final_upperband[prev]:
- final_upperband[curr] = final_upperband[prev]
- # to remove bands according to the trend direction
- if supertrend[curr] == 1:
- final_upperband[curr] = np.nan
- else:
- final_lowerband[curr] = np.nan
- # print(supertrend)
- final_df = pd.DataFrame({
- 'Supertrend': supertrend,
- 'Final Lowerband': final_lowerband,
- 'Final Upperband': final_upperband
- }, index=data_df.index)
- # print(final_df.tail(1))
- active_band = final_lowerband[-1] if not np.isnan(final_lowerband[-1]) else final_upperband[-1]
- with PlotScope.root(data.symbol):
- plot_line(f"supertrend ({atr_period}/{atr_multiplier})", active_band)
- return supertrend, active_band
- # return pd.DataFrame({
- # 'Supertrend': supertrend,
- # 'Final Lowerband': final_lowerband,
- # 'Final Upperband': final_upperband
- # }, index=df.index)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement