is there a way to do this kind of computation where columns are interdependent with numpy.where without for loop
I have a small df with one column, z_score. I’ll then create 3 columns – sell, position, and short_exit.
The trading rule is that if z_score is greater than 2 AND there’s no an open position, sell. Which means sell value in that row will become 1. The position, with the default value of 0, also becomes 1 (this means I have an open position). It remains 1 until the position is closed. When z_score falls below 0, the position is closed, i.e., position becomes 0 again. In that case, short_exit gets the value of 1, and the position becomes 0 again because we don’t have an open position.
I believe it’s not that hard to do it. But I somehow failed.