Search code examples
pythonpandasdatetimerolling-average

Rolling cumulative product between dates


I have data (dataframe called returns) that looks like this

DATE         TICKER    RETURN_DATA
2010-01-01    xxx       0.05
2010-01-01    yyy       0.01
2010-01-02    xxx       0.02
2010-01-02    yyy       0.08
.....
2010-01-29    xxx       0.11
2010-01-29    yyy       0.01

what I try to do is to calculate 4(n)-weeks rolling returns.

I implemented this

def rolling_fct(returns, window_len):
    return returns.groupby('TICKER')['RETURN_DATA'].rolling(window=window_len).apply(lambda x: np.prod(1+x)-1)

where window_len = 28 days, this works but I just discovered I need to roll this over a time delta rather than having a window_len = integer. The problems is that I am dealing with public holidays etc, so my window length is not fixed.

I am looking for the same rolling logic just on a time delta rather than a length.


Solution

  • As mentioned by @Uvar, pandas dataframe supports an offset in window declaration. You need to create the dataframe and convert the index into datetime format. Then use the rolling function

    a
            DATE TICKER  RETURN_DATA
    0 2010-01-01    xxx         0.05
    1 2010-01-01    yyy         0.01
    2 2010-01-02    xxx         0.02
    3 2010-01-02    yyy         0.08
    5 2010-01-29    xxx         0.11
    6 2010-01-29    yyy         0.01
    
    a.DATE = pd.to_datetime(a.DATE)
    a.set_index('DATE', inplace=True)
    
    a.rolling('2D').mean() 
    
         TICKER  RETURN_DATA
    DATE                          
    2010-01-01    xxx     0.050000
    2010-01-01    yyy     0.030000
    2010-01-02    xxx     0.026667
    2010-01-02    yyy     0.040000
    2010-01-29    xxx     0.110000
    2010-01-29    yyy     0.060000