How do I count missing returns in a rolling window?

Count each stock’s missing returns over the last 250 rows, screen out stocks with too many gaps, see what a gap does to a rolling sum, and find the trading days a data vendor never sent.

After this lesson, you can decide whether a stock has enough daily returns for a 250-day calculation and find the trading days missing from a data table.

How do I count the gaps in each stock’s last 250 rows?

.isna() marks each missing return, and a rolling sum of the marks within each stock counts the gaps in the window, so groupby("ticker")["stock_return"].transform(count_gaps) gives every row the number of gaps in the 250 rows before it. On 29 January 2027, AAA has 3 gaps, BBB 12 and CCC none, so with at most 10 gaps allowed, BBB fails the screen.

The panel holds three made-up stocks’ daily returns in decimals on 280 weekdays from 5 January 2026, one row per stock and date, with three missing returns for AAA and twelve in a row for BBB.

Code: the made-up data
import numpy as np
import pandas as pd

rng = np.random.default_rng(42)
dates = pd.bdate_range("2026-01-05", periods=280)
panel = pd.DataFrame({
    "ticker": np.repeat(["AAA", "BBB", "CCC"], len(dates)),
    "date": np.tile(dates, 3),
    "stock_return": rng.normal(0.0005, 0.012, 3 * len(dates)),
})
panel.loc[(panel["ticker"] == "AAA") & panel["date"].isin(dates[[100, 180, 230]]), "stock_return"] = np.nan
panel.loc[(panel["ticker"] == "BBB") & panel["date"].isin(dates[100:112]), "stock_return"] = np.nan

count_gaps turns the marks into 1 and 0 with .astype(int), adds them over the window with .rolling(window).sum() and moves the count down one row with .shift(1), so a row’s count ends on the day before, when the decision is made. A row without 250 earlier rows gets NaN, and NaN <= 10 is False, so a short history also fails. .groupby("ticker").tail(1) takes each stock’s last row.

The following box counts the gaps and applies the screen.

def count_gaps(stock_return, window=250):
    return stock_return.isna().astype(int).rolling(window).sum().shift(1)

panel["missing_250"] = panel.groupby("ticker")["stock_return"].transform(count_gaps)
panel["eligible"] = panel["missing_250"] <= 10
print(panel.groupby("ticker").tail(1).round(4).to_string())
    ticker       date  stock_return  missing_250  eligible
279    AAA 2027-01-29        0.0037          3.0      True
559    BBB 2027-01-29       -0.0102         12.0     False
839    CCC 2027-01-29       -0.0035          0.0      True

What does a gap do to a rolling sum?

A rolling window that contains a gap gives NaN by default, because .rolling(3) needs three observed returns, and min_periods=2 lets two observed returns give a sum. At AAA’s position 102, whose window starts with the gap at position 100, the default sum is missing and the sum with min_periods=2 is 1.2316 percentage points.

A sum over two observed returns treats the missing day as a return of zero, while the day’s true return stays unknown. Multiplying by 100 shows the returns in percent.

The following box compares the two settings on AAA’s positions 98 to 103.

aaa_percent = 100 * panel.loc[panel["ticker"] == "AAA", "stock_return"].iloc[98:104]
print(pd.DataFrame({
    "return_percent": aaa_percent,
    "min_periods_3": aaa_percent.rolling(3).sum(),
    "min_periods_2": aaa_percent.rolling(3, min_periods=2).sum(),
}).round(4))
     return_percent  min_periods_3  min_periods_2
98           0.5297            NaN            NaN
99          -1.0366            NaN        -0.5068
100             NaN            NaN        -0.5068
101          1.6091            NaN         0.5725
102         -0.3775            NaN         1.2316
103          0.9350         2.1666         2.1666

What about a day with no row at all?

A day the vendor never sent has no row to mark, so .isna() cannot count it, and comparing the received ticker-date pairs with every expected pair finds it. When CCC’s rows for 16 and 17 March are absent, the comparison returns exactly those two pairs, and .reindex() puts them back as missing returns.

pd.MultiIndex.from_product builds all 840 expected pairs, .set_index(["ticker", "date"]) labels the received returns by their pairs, and .difference() keeps the expected pairs that are absent. Real data use each exchange’s trading days, as in the lesson on exchange calendars.

The following box removes CCC’s two rows, finds them and puts them back.

received = panel[~((panel["ticker"] == "CCC") & panel["date"].isin(dates[[50, 51]]))].set_index(["ticker", "date"])[["stock_return"]]
expected = pd.MultiIndex.from_product([["AAA", "BBB", "CCC"], dates], names=["ticker", "date"])
print(expected.difference(received.index).to_frame(index=False))
restored = received.reindex(expected).reset_index()
print(len(received), len(restored), restored["stock_return"].isna().sum())
  ticker       date
0    CCC 2026-03-16
1    CCC 2026-03-17
838 840 17

The 840 restored rows hold 17 missing returns, the 15 gaps of AAA and BBB and the two days of CCC.

Your turn

Count the gaps in the 120 rows before BBB’s final row. You should see 0.0, because BBB’s gaps lie at positions 100 to 111.

The window is an argument of count_gaps.

print(count_gaps(panel.loc[panel["ticker"] == "BBB", "stock_return"], window=120).iloc[-1])
0.0