I am apologizing in advance if I wrote my question in the wrong way. I am new here and I am really far from python, I just want to finish my master thesis in finance timely))
Basically I have the following dataframe. Here is only an example with two stocks. original Dataframe is much longer of course. Sorry I am not allowed to paste images((
Or here the code for an example df with one stock.
dates = pd.date_range(end='31/7/19', periods=12, freq='M')
cs = {'date': dates,
'code': [1,1,1,1,1,1,1,1,1,1,1,1],
'ret': [0.00,0.00,0.02,0.00,0.01,0.00,0.01,0.02,0.00,0.04,0.05,0.06]
}
csdf = pd.DataFrame(cs, columns= ['date','code', 'ret'])
csdf = csdf.sort_values(['code','date']).set_index('date')
J=3
umd = csdf.groupby(['code'])['ret'].rolling(J, min_periods=J).sum()
Basically I need to calculate cumulstive return on each date for each stock. For this purpose I am using this code and it works. (I already sorted original df on date and date is the index there)
J=3
umd = csdf.groupby(['code'])['ret'].rolling(J, min_periods=J).sum()
But now I need to implement a condition. Lets t be a date on which we calculate cumulative return. Basically now we just sum all returns over J months up to t. But I need to sum only if amount of zero returns of a stock in the previous J months is not exceeding 20% of all (zero and nonzero returns). And if the amount of zero returns in the next J months after t is also not exceeding 20 % of all. In other words if a stock have a lot zero returns prior ANDOR after month t, we do not need to calculate cumualtive return and we put NA.
How could I implement this condition? Thank you very much in advance!