I'm calculating a technical indicator in Python. The requirement has to calculate the price recursively. Say an indicator called HL, the logic is:
For each row(each bar),
if the close price > the ma1, then return 1,
else if the close price < the ma2, then return -1,
else return the previous result of HL.
Below is the snippet:
data=[{'close': 10, 'ma1':10, 'ma2': 9},{'close': 11, 'ma1':10.5, 'ma2': 10},{'close': 12, 'ma1':11, 'ma2': 11}]
df=pd.DataFrame(data)
def handle_HL(row):
if row['close'] > row['ma1']:
return 1
elif row['close'] < row['ma2']:
return -1
else:
# I don't know how to do here
return 0
df['HL'] = df.apply(lambda x: handle_HL(x), axis=1)
How can I do this recursive calculation in pandas?