In the pairs trading code, the positions will exit as soon as they re-enter the lower or upper band rather than when they reach the middle band
# Long Entry
df['long_position'] = np.where(df.spread < df.lower_band, 1, 0)
# Long Exit
df['long_position'] = np.where(
df.spread >= df.middle_band, 0, df.long_position)
I should elaborate further. Shouldn't we get the return inside the band too if it hasn't hit the middle band yet?
As soon as the spread exits the band it is long, then when it enters the band but doesn't touch the middle line it will get allocated a 0 signal which would mean we get 0 return for that period even though it it still technically long. When it re-exits the band it goes long again and will take the return.
Hello John,
As you rightly mentioned, when spreads exit the band, i.e. when the spread is below the lower band, 'long_position' is set to 1 and remains as 1 until the spread goes above the middle band (long_position = 0 when the spread is above /equal to the middle band)
So, the value of long_position will be '1' when the price is between the lower band and the middle band (after setting long_position to 1). In the case you mentioned, where long_position = 1 and the spread goes below the lower band and reenters again above the lower band, the long_position remains unchanged and would be equal to 1.
Hope this explanation made the concept clear. In case you have any more doubts about this, please feel free to leave a comment.
Thank you