0

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((

enter image description here

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!

German
  • 11
  • 2
  • 5
    Welcome to SO. Please see [How to make good reproducible pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples). It's far easier for us to understand the problem if you create some code that sets up an example dataframe and shows your expected output. There's a reason that you're discouraged from posting screenshots of code. – roganjosh Aug 09 '19 at 17:29
  • Sounds like you want to drop data, make a list of the data which matches your conditions, then drop matches. – ifly6 Aug 09 '19 at 17:37

0 Answers0