Skip to content

Instantly share code, notes, and snippets.

@ugik
Created July 2, 2021 17:13
def tr(data):
data['previous_close'] = data['close'].shift(1)
data['high-low'] = abs(data['high'] - data['low'])
data['high-pc'] = abs(data['high'] - data['previous_close'])
data['low-pc'] = abs(data['low'] - data['previous_close'])
tr = data[['high-low', 'high-pc', 'low-pc']].max(axis=1)
return tr
def atr(data, period):
data['tr'] = tr(data)
atr = data['tr'].rolling(period).mean()
return atr
def supertrend(df, period=20, atr_multiplier=6.7):
hl2 = (df['high'] + df['low']) / 2
df['atr'] = atr(df, period)
df['upperband'] = hl2 + (atr_multiplier * df['atr'])
df['lowerband'] = hl2 - (atr_multiplier * df['atr'])
df['in_uptrend'] = True
for current in range(1, len(df.index)):
previous = current - 1
if df['close'][current] > df['upperband'][previous]:
df['in_uptrend'][current] = True
elif df['close'][current] < df['lowerband'][previous]:
df['in_uptrend'][current] = False
else:
df['in_uptrend'][current] = df['in_uptrend'][previous]
if df['in_uptrend'][current] and df['lowerband'][current] < df['lowerband'][previous]:
df['lowerband'][current] = df['lowerband'][previous]
if not df['in_uptrend'][current] and df['upperband'][current] > df['upperband'][previous]:
df['upperband'][current] = df['upperband'][previous]
return df
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment