Calculating rolling mean wihout taking NA values into consideration

Viewed 59

I try to calculate a rolling mean with a look-back rolling window of two days. In the data, I have some NA values and I just want to ignore them. Because I try to get a mean return based on x last days, replacing NA values is not an option, because I further want to calculate a return distribution.

I have a simple example with four columns to show the issue:

returns:
           01K W    02K W   03K W   04K W
Dates               
2021-01-01  0.01    0.01    NaN     0.05
2021-01-02  NaN     0.02    0.04    -0.02
2021-01-03  0.03    NaN     0.01    NaN
2021-01-04  -0.03   0.01    0.02    NaN
2021-01-05  0.02    0.02    0.01    0.01
2021-01-06  0.01    NaN     0.03    0.02

With these daily returns, I want to create a DataFrame with the rolling mean return with a window of two. I would expect rolling_mean like that:

            01K W   02K W   03K W   04K W
Dates               
2021-01-01  NaN     NaN     NaN     NaN
2021-01-02  0.010   0.150   0.040   0.015
2021-01-03  0.030   0.020   0.025   -0.020
2021-01-04  0.000   0.010   0.015   NaN
2021-01-05  -0.010  0.015   0.015   0.010
2021-01-06  0.015   0.020   0.020   0.015

When I try to do it with the following command, then it gives me always an NA value if there is also an NA value in the rolling window.

rolling_mean = returns.rolling(window=2).mean(skipna=True)

Is there a way around that problem, to just ignore the NA values when calculating the mean of the look-back period?

Thank you very much!

0 Answers
Related