How to implement flipflop logic for buy / sell signals using NaN and fill in python pandas?

I have two series of buy and sell signals in my python dataframe. Logic is the trigger I am trying to implement - I can only sell after I buy, and I cannot buy before I have already sold. So basically, 1 and -1 should only happen after they've already happened.

buy      = [ 0,  0,  0,  1,  0,  0,  1,  1,  1,  0,  0,  0,  1,  0]
sell     = [ 0,  0,  0, -1, -1,  0,  0,  0,  0,  0,  0,  0, -1,  0]
expected = [ 0,  0,  0,  1, -1,  0,  1,  0,  0,  0,  0,  0, -1,  0]

      

How can I do this without a for loop? Perhaps with vectors + fillna + NaN values ​​or merge?

+3


source to share





All Articles