Rolling Windows
Compute rolling means, sums, and standard deviations over a fixed number of rows with rolling(n).mean() and related methods.
What Are Rolling Windows?
A rolling window (also called a sliding window or moving window) computes a statistic over a fixed-size window of consecutive rows as it slides forward one row at a time. For example, a 7-day rolling mean replaces each day's value with the average of that day and the 6 preceding days. Rolling windows are the foundation of moving averages in finance, smoothing noisy sensor data, and computing trailing metrics in business dashboards.
import pandas as pd
import numpy as np
# Simple example: 3-day rolling mean
data = pd.Series([10, 12, 15, 11, 9, 13, 16, 14, 12, 18],
index=pd.date_range('2024-01-01', periods=10))
rolling_mean = data.rolling(window=3).mean()
print('Original:')
print(data.values)
print('\n3-day rolling mean:')
print(rolling_mean.values.round(2))The rolling() Method and window Parameter
Series.rolling(window=n) returns a Rolling object. The window parameter is the size of the sliding window in number of rows (for integer windows) or a time offset like '7D' (for time-indexed Series). After creating the rolling object, chain any aggregation method: .mean(), .sum(), .std(), .min(), .max(), or even .apply(func). The first window-1 rows will always be NaN because there are not enough preceding rows to fill the window.
import pandas as pd
import numpy as np
prices = pd.Series(
[100, 102, 98, 105, 110, 108, 115, 112, 120, 118],
index=pd.date_range('2024-01-01', periods=10),
name='price'
)
df = pd.DataFrame({'price': prices})
df['MA3'] = df['price'].rolling(3).mean()
df['MA7'] = df['price'].rolling(7).mean()
df['std3'] = df['price'].rolling(3).std()
print(df.round(2))