I am working with a financial instrument DataFrame. Firstly I used the following code to check all the occurrences where the closing price was higher than the previous high of n periods, and when the closing price was below the previous low of n periods. Then assigned the relevant values to the new column "position".
entry = [self.data['close'] > self.data['open_buy_high'], self.data['close'] < self.data['open_sell_low']]
self.data['position'] = np.select(entry, [1, -1], 0)
This worked well and returned values. The next step is I need the "position" column to stay equal to 1 or -1 until the closing price exceeds the high or low of a shorter period. So I tried the following code:
exit = [(self.data['position'] == 1) & (self.data['close'] > self.data['close_buy_low']),
(self.data['position'] == -1) & (self.data['close'] <
self.data['close_sell_high'])]
self.data['position'] = np.select(exit, [1, -1], 0)
After running this I got exactly the same DataFrame back, and I realized the conditions I used means that where the position was equal to zero, it will stay equal to zero. Because the second block of code will only return true when position is 1 or -1. So obviously I would get the same result as if I just ran the first block.
My issue now is I have no idea how to update the 0 values of the position column to stay equal to 1 (instead of 0) until the closing price falls below the 'close_buy_low', or -1 (instead of 0) until the closing price goes above 'close_sell_high'.
Any suggestions on what I can do/ use to achieve this?