if data2.AboveUpper
is True
when the stock is above the upper rolling mean, then
pd.rolling_sum( data2.AboveUpper, window=X ) >= X
is True
wherever the stock has been above the upper rolling mean for at least X
consecutive days; so all you need is:
data2['buy'] = pd.rolling_sum( data2.AboveUpper, window=X ) >= X
as an example:
>>> ts = pd.Series( [True, True, False, False, True, True, True, False, True ] )
>>> pd.rolling_sum( ts, window=2 ) >= 2
0 False
1 True
2 False
3 False
4 False
5 True
6 True
7 False
8 False
dtype: bool