I have the dataframe like this:
Price Signal
0 28.68 -1
1 33.36 1
2 44.7 -1
3 43.38 1 ---- smaller than Price[2] # False: Drop row[3,4]
4 41.67 -1
5 42.17 1 ---- smaller than Price[2] # False: Drop row[5,6]
6 44.21 -1
7 46.34 1 ---- greater than Price[2] # True: Keep
8 45.2 -1
9 43.4 1 ---- Still Keep because it is the last row
My logic is keep the row if the signal 1 has price greater than the one before. If not it will drop its row and the next row since the signal must interspersed between -1 and 1 and also must compare the next signal 1 with the last one above (I have explained in the snapshot of my dataframe above).
The last one Signal 1 still keep although it is not sastified the condition because rule is the last one item of Signal column must be 1
Until now my effort is here:
def filter_sell(df):
# For export the result
filtered_sell_df = pd.DataFrame()
for i in range(0, len(df) + 1):
if df.iloc[i]["Signal"] == 1:
if df.iloc[i]["Price"] > df.iloc[i - 1]["Price"]:
pass
else:
try:
df.drop([i, i + 1])
filter_sell(df)
# Try to handle the i + 1 above since len(df) is changed
except RecursionError:
break
else:
pass
I'm new with writing recursion, thanks for your help!