Home > OS >  How to recursively apply in function?
How to recursively apply in function?

Time:03-27

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?

CodePudding user response:

You can try with np.select and ffill (front fill) to fill NaN by previous value of HL:

import numpy as np

condlist = [df['close'] > df['ma1'],
            df['close'] < df['ma2']]

df['HL'] = np.select(condlist=condlist, choicelist=[1, -1], default=np.NaN)
df['HL'] = df['HL'].ffill()
print(df)

# Output
   close   ma1  ma2   HL
0     10  10.0    9  NaN
1     11  10.5   10  1.0
2     12  11.0   11  1.0

A better example:

# Input
>>> df
   close  ma1  ma2
0     10    9    9
1     11   12   13
2     12   12   12

# Output
0     10    9    9  1.0  # 1
1     11   12   13 -1.0  # 0
2     12   12   12 -1.0  # front filled
  • Related