0

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?

DataFrame

GuyS
  • 1
  • 1
  • Please include a sample dataframe and the desired output. – timgeb Dec 07 '21 at 15:32
  • 1
    @timgeb Thanks for your willingness to help. What is the best way for me to share a DataFrame here? – GuyS Dec 07 '21 at 15:49
  • see [here](https://stackoverflow.com/a/20159305/3620003) – timgeb Dec 07 '21 at 15:52
  • @timgeb I have tried to follow the directions of the post using pd.read_clipboard(sep='\s\s+') and even tried to understand from other sources, but I have not been able to format as a proper DataFrame. I am still new to python so I have a lot to learn. If you can help, I have attached the DataFrame as an image in the original post and here is the link https://i.stack.imgur.com/AUeyj.png – GuyS Dec 07 '21 at 22:35
  • In the output DataFrame you can see on 2020-01-23 there was the first position = -1 because 'close' was below 'open_sell_low'. But then position is equal to zero on 2020-01-28 because 'close' is not less than 'open_sell_low', but I need it to stay == -1 up until 2020-01-30 because that is the first occurrence where 'close' is greater than 'close_sell_high' – GuyS Dec 07 '21 at 22:42

0 Answers0