DEV Community

Cover image for pandas Rolling Time Window vs Fixed Window: 6 Tests on a Daily Stock Mentions Series With a Holiday Gap
dustin liang
dustin liang

Posted on

pandas Rolling Time Window vs Fixed Window: 6 Tests on a Daily Stock Mentions Series With a Holiday Gap

For a pandas rolling time window, pass an offset string such as s.rolling("7D") on a DatetimeIndex (or df.rolling("7D", on="date")); pass an integer such as rolling(5) when you want the last five rows no matter how far apart they are. The two match only when every period has exactly one row. On trading-day data they split after weekends, holidays and missed feed days: the time window shrinks, the row window reaches further back. Offset windows need a sorted (monotonic) datetime index, and they change the defaults. The pandas DataFrame.rolling reference states that "for a window that is specified by an offset, min_periods will default to 1", while for an integer window it defaults to the window size, and that closed defaults to 'right'. Every number below comes from code run on pandas 3.0.6.

Facts

  • What: six side-by-side tests of rolling(5) and offset windows ("5D", "7D", "10D", "1h") on daily and intraday mention counts.
  • Environment: Python 3.13.5, pandas 3.0.6, NumPy 2.5.5, matplotlib 3.11.2.
  • Data: one placeholder ticker, 37 trading days from 2026-09-01 to 2026-10-30, with a simulated 7-day closure (10-01 to 10-07) and two missing feed days; plus 60 intraday events and a 1,000,000-row series for timing.
  • Source & as-of: simulated with NumPy default_rng(20261122), prepared 2026-11-22 (Asia/Shanghai).

All data here is synthetic. The counts are fake news mentions, not prices, and nothing in this post says anything about a real stock.

What I compared, and how

Five questions decide which window is right for a mentions series:

  1. What rows end up inside the window after a gap?
  2. When does the first value appear (min_periods)?
  3. How many rows does each window hold on a normal week?
  4. How do missing feed days count?
  5. What breaks on intraday timestamps (order, duplicates, per-ticker windows)?

Plus one practical check: speed on a million rows.

The test series

Trading days only, a closure in early October, two days the feed missed, and a burst right after the market reopens:

import numpy as np
import pandas as pd

rng = np.random.default_rng(20261122)
days = pd.bdate_range("2026-09-01", "2026-10-30")
closure = pd.date_range("2026-10-01", "2026-10-07")          # simulated 7-day closure
days = days[~days.isin(closure)]
gaps = pd.to_datetime(["2026-09-16", "2026-10-21"])           # feed missed these days
days = days[~days.isin(gaps)]
s = pd.Series(rng.poisson(20, len(days)).astype("float64"), index=days, name="mentions")
s.loc["2026-10-08":"2026-10-09"] += [40, 25]                  # post-closure burst
print(len(s), s.index[0].date(), s.index[-1].date())
#> 37 2026-09-01 2026-10-30
Enter fullscreen mode Exit fullscreen mode

The missing days are absent rows, not NaN rows. That is how most scraped logs look, and it matters in test 4.

Test 1: what each window sees after the closure

cmp = pd.DataFrame({
    "mentions": s,
    "rows_5":  s.rolling(5).count(),
    "rows_7D": s.rolling("7D").count(),
    "mean_5":  s.rolling(5).mean(),
    "mean_7D": s.rolling("7D").mean(),
})
print(cmp.loc["2026-09-28":"2026-10-14"].round(1))
Enter fullscreen mode Exit fullscreen mode
            mentions  rows_5  rows_7D  mean_5  mean_7D
2026-09-28      15.0     5.0      5.0    18.2     18.2
2026-09-29      14.0     5.0      5.0    18.8     18.8
2026-09-30      13.0     5.0      5.0    16.8     16.8
2026-10-08      61.0     5.0      1.0    24.8     61.0
2026-10-09      44.0     5.0      2.0    29.4     52.5
2026-10-12      18.0     5.0      3.0    30.0     41.0
2026-10-13      21.0     5.0      4.0    31.4     36.0
2026-10-14      18.0     5.0      5.0    32.4     32.4
Enter fullscreen mode Exit fullscreen mode

Before the closure the two means are identical, because five trading days fit inside seven calendar days. On the first day back, rolling("7D") contains one row, so its "mean" is just that day's 61. rolling(5) still averages five rows, four of them from late September, and reports 24.8. Neither is wrong. They answer different questions: "average over the last week of calendar time" versus "average over the last five observations".

For a spike alert the difference is large. Comparing today with the trailing mean, the time window gives a ratio of 1.0 on 10-08 (today against itself) and the row window gives 2.5. If the alert also compares today with a baseline that excludes today, the time window has no baseline at all on 10-08.

Line chart over simulated trading days from 2026-09-21 to 2026-10-23. Grey bars show daily mention counts. A blue line for rolling(5).mean() and an orange line for rolling('7D').mean() overlap until the simulated closure from 10-01 to 10-07. On 10-08 the orange line jumps to 61, equal to that day's count, while the blue line rises to about 25. The lines meet again at 32.4 on 10-14.

Test 2: min_periods changes when you switch to an offset

head = pd.DataFrame({
    "int_5":      s.rolling(5).mean(),
    "off_7D":     s.rolling("7D").mean(),
    "off_7D_mp4": s.rolling("7D", min_periods=4).mean(),
}).head(6).round(1)
print(head)
Enter fullscreen mode Exit fullscreen mode
            int_5  off_7D  off_7D_mp4
2026-09-01    NaN    13.0         NaN
2026-09-02    NaN    18.0         NaN
2026-09-03    NaN    17.3         NaN
2026-09-04    NaN    17.0        17.0
2026-09-07   19.4    19.4        19.4
2026-09-08   18.4    18.4        18.4
Enter fullscreen mode Exit fullscreen mode

The integer window waits for five rows. The offset window returns a value from the first row, because its min_periods defaults to 1. If you swap rolling(5) for rolling("7D") in an existing pipeline, the warm-up NaNs disappear silently, and so does the protection they gave you.

Setting min_periods explicitly fixes the start, and it also hides the thin days after the closure:

mp4 = s.rolling("7D", min_periods=4).mean()
print(mp4.loc["2026-10-08":"2026-10-09"].isna().tolist())
#> [True, True]
Enter fullscreen mode Exit fullscreen mode

That is usually what I want for a monitoring chart: no value is better than a one-row "average".

Test 3: how many rows each window holds

for w in [5, "5D", "7D", "10D"]:
    c = s.rolling(w).count()
    print(f"{str(w):>4}: min={int(c.min())} max={int(c.max())} "
          f"days with 5 rows={(c == 5).mean():.0%}")
Enter fullscreen mode Exit fullscreen mode
   5: min=5 max=5 days with 5 rows=89%
  5D: min=1 max=5 days with 5 rows=11%
  7D: min=1 max=5 days with 5 rows=57%
 10D: min=1 max=8 days with 5 rows=11%
Enter fullscreen mode Exit fullscreen mode

"5D" means five calendar days, not five trading days. On a Monday it covers Thursday to Monday, which is three trading rows, so it holds five rows on only 11% of days. "7D" is the closest calendar match to a trading week and still drops below five rows on 43% of days, because of the closure, the two missing feed days and the start of the series. rolling(5) is always five rows once warmed up (the remaining 11% are the first four days, which are NaN).

Step chart of how many rows each rolling window holds on each simulated trading day from 2026-09-01 to 2026-10-30. The dashed blue rolling(5) line stays at 5. The green rolling('5D') line is mostly at 3. The orange rolling('7D') line is usually 5, dips to 4 around the two missing feed days and falls to 1 on 10-08 after the closure. The purple rolling('10D') line moves between 3 and 8 after the first few days.

If you need "the last five trading days", neither "5D" nor "7D" gives it to you. That is test 4.

Test 4: count trading days from a calendar, not from the rows you have

The row window has the opposite problem with feed gaps: 2026-09-16 is missing, so rolling(5) on 09-17 silently reaches back six trading days. Reindex onto a trading calendar first, so a missing day becomes a NaN row that the window can see:

cal = pd.bdate_range("2026-09-01", "2026-10-30")
cal = cal[~cal.isin(closure)]              # your exchange calendar goes here
full = s.reindex(cal)                      # missing feed days -> NaN rows

print(pd.DataFrame({
    "rows_int5_on_s":  s.rolling(5).count(),
    "rows_td5_on_cal": full.rolling(5).count(),
}).loc["2026-09-17":"2026-09-23"])
Enter fullscreen mode Exit fullscreen mode
            rows_int5_on_s  rows_td5_on_cal
2026-09-17             5.0              4.0
2026-09-18             5.0              4.0
2026-09-21             5.0              4.0
2026-09-22             5.0              4.0
2026-09-23             5.0              5.0
Enter fullscreen mode Exit fullscreen mode

On the calendar version, the window spans exactly five trading days and counts four real observations while the gap is inside it. Add min_periods to decide how many gaps you tolerate:

td5 = full.rolling(5, min_periods=4).mean()   # "last 5 trading days, at least 4 observed"
Enter fullscreen mode Exit fullscreen mode

This is the version I use for daily charts such as an AI-sector board heat chart, where a week should mean a trading week and a missing feed day should not quietly pull in older data. In a real pipeline, build cal from an exchange calendar instead of bdate_range.

Test 5: intraday timestamps (order, duplicates, per-ticker windows)

Time windows are most useful on event-level data, where rows arrive at irregular times. Three things to know.

The column must be sorted.

ts = pd.Timestamp("2026-10-08 09:30") + pd.to_timedelta(
    np.sort(rng.integers(0, 330, 60)), unit="min")
ev = pd.DataFrame({"ts": ts, "stock": rng.choice(["S01", "S02"], 60), "n": 1})

ev.sample(frac=1, random_state=1).rolling("1h", on="ts")["n"].sum()
#> ValueError: ts values must be monotonic
Enter fullscreen mode Exit fullscreen mode

An integer window would have run on the shuffled frame without complaint. The error is the useful outcome here.

Duplicate timestamps give position-dependent results.

tie = pd.Series(1.0, index=pd.to_datetime(["2026-10-08 10:00"] * 3 + ["2026-10-08 10:30"]))
print(tie.rolling("1h").sum().tolist())
#> [1.0, 2.0, 3.0, 4.0]
print(tie.groupby(level=0).sum().rolling("1h").sum().tolist())
#> [3.0, 4.0]
Enter fullscreen mode Exit fullscreen mode

Three mentions at 10:00 get three different "last hour" counts, depending on row order. My 60 simulated events had 8 duplicated timestamps. If you need one number per moment, aggregate per timestamp first.

Per-ticker windows: groupby().rolling(..., on=) returns an index you can't assign directly.

per_stock = ev.sort_values(["stock", "ts"]).groupby("stock").rolling("1h", on="ts")["n"].sum()
print(per_stock.index.names)
#> ['stock', 'ts']
ev["n_1h_stock"] = per_stock.reset_index(level=0, drop=True)
#> ValueError: cannot reindex on an axis with duplicate labels
Enter fullscreen mode Exit fullscreen mode

On pandas 3.0.6 the second level is the timestamp, not the original row label, so it can't be aligned back. Sort first, then assign by position:

ev2 = ev.sort_values(["stock", "ts"]).reset_index(drop=True)
ev2["n_1h_stock"] = ev2.groupby("stock").rolling("1h", on="ts")["n"].sum().to_numpy()
print(ev2.groupby("stock")["n_1h_stock"].max().to_dict())
#> {'S01': 10.0, 'S02': 8.0}
Enter fullscreen mode Exit fullscreen mode

This relies on groupby returning groups in sorted key order and keeping row order inside each group, which is why the frame is sorted by ["stock", "ts"] first. The script checks the S01 result against a single-ticker rolling("1h") and they match.

Also worth knowing: center=True is accepted with an offset window (it ran without error), and it uses future rows. Keep it out of anything that feeds an alert.

Test 6: speed on 1,000,000 rows

A one-million-row series with irregular timestamps over 300 days, best of three runs on one machine:

secs = np.sort(rng.integers(0, 300 * 86400, 1_000_000))
big = pd.Series(rng.poisson(3, secs.size).astype("float64"),
                index=pd.Timestamp("2026-01-01") + pd.to_timedelta(secs, unit="s"))

big.rolling(500).sum()        # integer window
big.rolling("1h").sum()       # offset window
big.rolling("1D").sum()
big.rolling(3333).median()    # about one day of rows
big.rolling("1D").median()
Enter fullscreen mode Exit fullscreen mode
rolling(500).sum()          11.7 ms
rolling('1h').sum()         34.7 ms
rolling('1D').sum()         32.4 ms
rolling(3333).median()     418.2 ms
rolling('1D').median()     505.0 ms
Enter fullscreen mode Exit fullscreen mode

The offset window was about 3× slower for sum, but the window length barely mattered ("1h" and "1D" took the same time). For median both were slow and the gap was about 20%. Neither is a reason to choose one window over the other; pick by meaning. Timings depend on the machine, so rerun snippets.py before quoting them.

Results side by side

Question rolling(5) rolling("7D") calendar + rolling(5)
Unit of the window rows calendar time trading days
Default min_periods 5 1 5 (set your own)
After a 7-day closure reaches back into older data 1 row on day one reaches back, NaN rows visible
Missing feed day silently reaches further back window just has fewer rows NaN inside the window
Needs sorted index no yes (raises) yes in practice
Speed (sum, 1M rows) fastest about 3× slower same as rolling(5)

Which to use:

  • Event-level data (one row per mention): an offset window like "1h" or "1D". Integer windows mean nothing when the gap between rows varies. Aggregate duplicate timestamps first.
  • Daily data where you want "last N trading days": reindex onto a trading calendar and use an integer window with an explicit min_periods.
  • Daily data where calendar time is the point (for example "mentions in the last 7 days" shown to a reader): "7D", with min_periods set so the first days after a closure don't show a one-row average.
  • Never: "5D" as a stand-in for five trading days.

The same choice comes up in any stock heat monitoring workflow that mixes daily summaries with intraday mention logs: decide per chart whether "a week" means rows, calendar days or trading days, and write it next to the chart.

FAQ

Does rolling("7D") include the current row?
Yes. The default closed for offset windows is 'right', so the window is (t − 7 days, t]. Use closed="left" for a baseline that excludes today.

Can I use a time window without a DatetimeIndex?
Yes, with on="date" on a DataFrame, as long as that column is datetime and sorted.

Why does my groupby rolling time window return a MultiIndex?
The group key is added as the first level. Sort by key and time, then assign with .to_numpy() as in test 5, or reset the index and merge on key and time when timestamps are unique.

Does rolling("5B") work for business days?
No. It raises ValueError: <5 * BusinessDays> is a non-fixed frequency; offset windows must be fixed-length ("D", "h", "min" and so on). Use the calendar reindex from test 4.

The full script (snippets.py) and its output reproduce every number above; make_figures.py draws both charts from the same data.


Lava (熔岩, lava.ai-dolphin.com) — A-share stock heat & sentiment monitoring by AI-Dolphin. All examples in this post use simulated data.

中文简介: pandas 按时间窗口滚动(rolling("7D"))和按行数滚动(rolling(5))只有在每天恰好一行时才等价。本文用模拟的 A 股交易日新闻提及序列(含 7 天休市和两天缺数)实测了 6 项差异:休市后时间窗口只剩 1 行、偏移窗口的 min_periods 默认是 1、"5D" 不等于 5 个交易日、缺数日让行窗口悄悄往前多取,以及盘中时间戳要排序、重复时间戳和分组滚动回填的写法(pandas 3.0.6 实跑)。

Top comments (0)