Background
I have a dataframe of stock prices and am trying to build a trading entry signal. The logic is to enter position one day after whenever there is a Trigger with a stop loss signal “Exit”
Because once there has been an Entry I will hold the position until stopped out, a new Entry (except the first) can only occur once there has been an Exit after the previous Entry. (e.g. 2 Entries cannot happen without an Exit in between)
Problem
I am having trouble how to create Entry signals in column “signal 3” to uniquely capture only real Entry (Trigger day after if there has been an Exit after the previous Entry).
Below dataframe is what I am working with:
Date Price Trigger signal 3 Stop Loss
2024-03-06 9540.0 NaN NaN NaN
2024-03-07 10270.0 NaN NaN NaN
2024-03-08 8120.0 Trigger NaN NaN
2024-03-11 6620.0 NaN Entry NaN
2024-03-12 5620.0 NaN NaN NaN
2024-03-13 6620.0 NaN NaN Exit
2024-03-14 5930.0 NaN NaN NaN
...
2024-03-22 7120.0 Trigger NaN NaN
2024-03-28 6090.0 NaN Entry NaN
2024-03-29 5680.0 Trigger NaN NaN
2024-04-01 5340.0 NaN NaN NaN
2024-04-02 4885.0 NaN NaN NaN
As per example above the last Trigger should not result in an entry since the Trigger before that lead to an Entry but no Exit was defined.
Right now I am only using a for loop to iterate through every single row with a variable called position that increments to 1 whenever entry is made and resets to 0 when exit is made but given this is a dataframe there must be a vectorized faster solution.