import pandas as pd orders = pd.DataFrame( { "date": pd.to_datetime( [ "2026-01-01", "2026-01-02", "2026-01-03", "2026-01-04", "2026-01-05", "2026-01-06", ] ), "orders": [18, 22, 17, 25, 29, 24], "sales_usd": [420.0, 510.0, 460.0, 590.0, 640.0, 610.0], } ) orders = orders.sort_values("date").set_index("date") result = orders.assign( sales_mean_3row=orders["sales_usd"] .rolling(window=3, min_periods=2) .mean() .round(2), sales_total_3row=orders["sales_usd"].rolling(window=3, min_periods=2).sum(), ) print("fixed-row rolling window") print(result.to_string()) print() check_date = pd.Timestamp("2026-01-05") window_values = orders.loc["2026-01-03":"2026-01-05", "sales_usd"] print("window values for 2026-01-05:", window_values.tolist()) print("verified average:", result.loc[check_date, "sales_mean_3row"]) print("verified total:", result.loc[check_date, "sales_total_3row"]) assert result.loc[check_date, "sales_mean_3row"] == round(window_values.mean(), 2) assert result.loc[check_date, "sales_total_3row"] == window_values.sum() irregular = pd.DataFrame( { "date": pd.to_datetime( ["2026-01-01", "2026-01-02", "2026-01-05", "2026-01-06"] ), "sales_usd": [420.0, 510.0, 640.0, 610.0], } ) time_window = irregular.assign( sales_total_3d=irregular.rolling( window="3D", on="date", min_periods=1 )["sales_usd"].sum() ) print() print("time-offset rolling window") print(time_window.to_string(index=False)) print() print("verification: rolling windows match source rows")