I have this python code of the supertrend implementation. i am using pandas dataframe. the code works fine but, the supertrend function runs slower and slower as the dataframe increases in length. i was wondering how i could convert the for loop in the supertrend function to a Pandas Vectorization or using the apply() method
def trueRange(df):
df['prevClose'] = df['close'].shift(1)
df['high-low'] = df['high'] - df['low']
df['high-pClose'] = abs(df['high'] - df['prevClose'])
df['low-pClose'] = abs(df['low'] - df['prevClose'])
tr = df[['high-low','high-pClose','low-pClose']].max(axis=1)
return tr
def averageTrueRange(df, peroid=12):
df['trueRange'] = trueRange(df)
the_atr = df['trueRange'].rolling(peroid).mean()
return the_atr
def superTrend(df, peroid=5, multipler=1.5):
df['averageTrueRange'] = averageTrueRange(df, peroid=peroid)
h2 = ((df['high'] + df['low']) / 2)
df['Upperband'] = h2 + (multipler * df['averageTrueRange'])
df['Lowerband'] = h2 - (multipler * df['averageTrueRange'])
df['inUptrend'] = None
for current in range(1,len(df.index)):
prev = current- 1
if df['close'][current] > df['Upperband'][prev]:
df['inUptrend'].iloc[current] = True
elif df['close'][current] < df['Lowerband'][prev]:
df['inUptrend'].iloc[current] = False
else:
df['inUptrend'].iloc[current] = df['inUptrend'][prev]
if df['inUptrend'][current] and df['Lowerband'][current] < df['Lowerband'][prev]:
df['Lowerband'].iloc[current] = df['Lowerband'][prev]
if not df['inUptrend'][current] and df['Upperband'][current] > df['Upperband'][prev]:
df['Upperband'].iloc[current] = df['Upperband'][prev]
Use .values[1:]
and .values[:-1]
for the vectorized comparison.
That is, .values[1:]
is current
, .values[:-1]
is prev
in your code.
Here is example to convert IF statements into vectorized comparison.
cond1 = df['close'].values[1:] > df['Upperband'].values[:-1]
cond1 = np.insert(cond1, 0, False)
df.loc[cond1, 'inUptrend'] = True
The reason using insert is the 0'th element has no element to be compared with.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.