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.
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.
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.
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.