pythonpandasrolling-computation

Dataframe - Rolling product - timedelta window


I am trying to do a simple rolling multiplication of a dataframe (each new value should be the product of all the input values in the window). Realizing that rolling does not allow of products, I tried to look for alternate solutions but they seem not to work with variable lenghth windows :

start_date = '2024-05-01'
date_index = pd.date_range(end=start_date, periods=15, freq='B')
df = pd.DataFrame(list(range(1,16)), index = date_index, columns=['A'])
df.rolling('1W').agg({"A": "prod"})

This return the error : ValueError: <Week: weekday=6> is a non-fixed frequency

Is there any clean workarround for that type of rolling ?


Solution

  • Is this what you're looking for, a 7 day window? The documentation says you can provide a pd.Timedelta as parameter to pd.DataFrame.rolling

    >>> df.rolling(pd.Timedelta(days=7)).agg(lambda a: np.prod(a))
    ... # works also: df.rolling(pd.Timedelta('1W')).agg(lambda a: np.prod(a))
    ... # as well as: df.rolling(pd.Timedelta(weeks=1)).agg(lambda a: np.prod(a))
                       A
    2024-04-11       1.0
    2024-04-12       2.0
    2024-04-15       6.0
    2024-04-16      24.0
    2024-04-17     120.0
    2024-04-18     720.0
    2024-04-19    2520.0
    2024-04-22    6720.0
    2024-04-23   15120.0
    2024-04-24   30240.0
    2024-04-25   55440.0
    2024-04-26   95040.0
    2024-04-29  154440.0
    2024-04-30  240240.0
    2024-05-01  360360.0
    

    You have to use a lambda it seems; just the method throws an error. Or is your window type the data from the last Friday? If so, use a groupby with offsets (pd.offset.Weekday(weekday=THE_DAY)).