How do I estimate a rolling beta?

Estimate a rolling beta for every stock in a long pandas panel, with rolling cov and var or with RollingOLS, and see what min_periods and where do with a missing return.

After this lesson, you can compute a rolling beta for each stock in a panel and handle a missing return.

How do I compute a rolling beta with .cov() and .var()?

The beta of a stock is the covariance between the stock’s return and the market’s return, divided by the variance of the market’s return.

\[ \beta = \frac{\operatorname{Cov}(r, r_m)}{\operatorname{Var}(r_m)} \]

Here \(r\) is the stock’s return and \(r_m\) is the market’s return.

.cov() and .var() compute the two parts, and .rolling(window, min_periods=min_observations) makes them use the last window days, here three, as long as min_observations of those days have both returns. both is True on the days where both returns are present, and .where(both) keeps the returns only on those days, so the covariance and the variance always use the same days. Real data need a longer window, such as 60 days.

The example is a long panel, as in the lesson on long and wide panels, of two made-up stocks over six trading days. AAA always moves twice as much as the market and BBB half as much, so their betas are 2.0 and 0.5. pd.bdate_range gives the trading days, np.tile repeats the dates and market returns for each stock, and np.repeat repeats each ticker and multiplier six times.

groupby("ticker") runs rolling_beta on each stock separately, so a window never mixes AAA and BBB, and group_keys=False keeps the row labels, so the betas fit back into the panel.

The following box builds the panel and computes the betas.

import numpy as np
import pandas as pd

dates = pd.bdate_range("2026-03-02", periods=6)
market_returns = [0.01, -0.02, 0.03, 0.00, 0.02, -0.01]

panel = pd.DataFrame({
    "date": np.tile(dates, 2),
    "ticker": np.repeat(["AAA", "BBB"], 6),
    "market_return": np.tile(market_returns, 2),
})
panel["stock_return"] = np.repeat([2.0, 0.5], 6) * panel["market_return"]

def rolling_beta(stock, window=3, min_observations=3):
    both = stock["stock_return"].notna() & stock["market_return"].notna()
    stock_return = stock["stock_return"].where(both)
    market_return = stock["market_return"].where(both)
    covariance = stock_return.rolling(window, min_periods=min_observations).cov(market_return)
    variance = market_return.rolling(window, min_periods=min_observations).var()
    return covariance / variance

panel["beta"] = panel.groupby("ticker", group_keys=False)[["stock_return", "market_return"]].apply(rolling_beta)
print(panel)
         date ticker  market_return  stock_return  beta
0  2026-03-02    AAA           0.01         0.020   NaN
1  2026-03-03    AAA          -0.02        -0.040   NaN
2  2026-03-04    AAA           0.03         0.060   2.0
3  2026-03-05    AAA           0.00         0.000   2.0
4  2026-03-06    AAA           0.02         0.040   2.0
5  2026-03-09    AAA          -0.01        -0.020   2.0
6  2026-03-02    BBB           0.01         0.005   NaN
7  2026-03-03    BBB          -0.02        -0.010   NaN
8  2026-03-04    BBB           0.03         0.015   0.5
9  2026-03-05    BBB           0.00         0.000   0.5
10 2026-03-06    BBB           0.02         0.010   0.5
11 2026-03-09    BBB          -0.01        -0.005   0.5

The beta on 4 March uses 2, 3 and 4 March. The first two days have no beta, because their windows hold fewer than three days.

How do I compute a rolling beta with RollingOLS?

RollingOLS regresses the stock’s return on the market’s return in each window, so one command gives the same beta.

RollingOLS.from_formula("stock_return ~ market_return", data=stock, window=window) sets up one regression per window, .fit(params_only=True) estimates them without standard errors, and .params["market_return"] keeps the slope, which is the beta.

The following box prints the RollingOLS betas beside the first ones.

from statsmodels.regression.rolling import RollingOLS

def ols_beta(stock, window=3):
    model = RollingOLS.from_formula("stock_return ~ market_return", data=stock, window=window)
    return model.fit(params_only=True).params["market_return"]

panel["beta_ols"] = panel.groupby("ticker", group_keys=False)[["stock_return", "market_return"]].apply(ols_beta)
print(panel[["date", "ticker", "beta", "beta_ols"]])
         date ticker  beta  beta_ols
0  2026-03-02    AAA   NaN       NaN
1  2026-03-03    AAA   NaN       NaN
2  2026-03-04    AAA   2.0       2.0
3  2026-03-05    AAA   2.0       2.0
4  2026-03-06    AAA   2.0       2.0
5  2026-03-09    AAA   2.0       2.0
6  2026-03-02    BBB   NaN       NaN
7  2026-03-03    BBB   NaN       NaN
8  2026-03-04    BBB   0.5       0.5
9  2026-03-05    BBB   0.5       0.5
10 2026-03-06    BBB   0.5       0.5
11 2026-03-09    BBB   0.5       0.5

When does rolling return NaN?

By default, rolling needs a full window, so every window with a missing return gives NaN. min_periods lowers the number of days a window needs, and both keeps the covariance and the variance on the same days.

In the example, AAA’s return on 4 March is missing, and BBB’s returns are complete.

  • With min_observations=3, a window needs all three days, so AAA has no beta on 4 to 6 March.
  • With min_observations=2, those windows use their two complete days, and the beta is 2.0.

panel_gap.loc[2, "stock_return"] = np.nan removes AAA’s return on 4 March, and by_stock holds the panel grouped by stock, so each setting is one .apply(). .to_string() prints every column of the table.

The following box computes the betas with three and with two required days.

panel_gap = panel.copy()
panel_gap.loc[2, "stock_return"] = np.nan
by_stock = panel_gap.groupby("ticker", group_keys=False)[["stock_return", "market_return"]]

panel_gap["min_observations_3"] = by_stock.apply(rolling_beta)
panel_gap["min_observations_2"] = by_stock.apply(rolling_beta, min_observations=2)

columns = ["date", "ticker", "stock_return", "market_return", "min_observations_3", "min_observations_2"]
print(panel_gap[columns].round(3).to_string())
         date ticker  stock_return  market_return  min_observations_3  min_observations_2
0  2026-03-02    AAA         0.020           0.01                 NaN                 NaN
1  2026-03-03    AAA        -0.040          -0.02                 NaN                 2.0
2  2026-03-04    AAA           NaN           0.03                 NaN                 2.0
3  2026-03-05    AAA         0.000           0.00                 NaN                 2.0
4  2026-03-06    AAA         0.040           0.02                 NaN                 2.0
5  2026-03-09    AAA        -0.020          -0.01                 2.0                 2.0
6  2026-03-02    BBB         0.005           0.01                 NaN                 NaN
7  2026-03-03    BBB        -0.010          -0.02                 NaN                 0.5
8  2026-03-04    BBB         0.015           0.03                 0.5                 0.5
9  2026-03-05    BBB         0.000           0.00                 0.5                 0.5
10 2026-03-06    BBB         0.010           0.02                 0.5                 0.5
11 2026-03-09    BBB        -0.005          -0.01                 0.5                 0.5

RollingOLS gives the same betas as min_observations=2 with min_nobs=2, expanding=True and missing="drop", which helps for a rolling regression on several factors. min_nobs is the smallest number of days a window needs, expanding=True lets the first windows start before they hold three days, and missing="drop" uses only the days with both returns.

How do I view the betas as a wide table?

.pivot() turns the long panel into a wide table, with one row per date and one column per stock. index="date" gives the rows, columns="ticker" the columns and values="beta" the cells.

The following box pivots the betas.

wide = panel.pivot(index="date", columns="ticker", values="beta")
print(wide)
ticker      AAA  BBB
date                
2026-03-02  NaN  NaN
2026-03-03  NaN  NaN
2026-03-04  2.0  0.5
2026-03-05  2.0  0.5
2026-03-06  2.0  0.5
2026-03-09  2.0  0.5

Your turn

Compute the betas in panel_gap with a 4-day window and min_observations=3, and print them as a wide table. You should see BBB’s first beta on 4 March and AAA’s on 5 March, one day later because of AAA’s missing return.

.apply() passes window=4 and min_observations=3 on to rolling_beta.

panel_gap["beta_4"] = by_stock.apply(rolling_beta, window=4, min_observations=3)
print(panel_gap.pivot(index="date", columns="ticker", values="beta_4"))
ticker      AAA  BBB
date                
2026-03-02  NaN  NaN
2026-03-03  NaN  NaN
2026-03-04  NaN  0.5
2026-03-05  2.0  0.5
2026-03-06  2.0  0.5
2026-03-09  2.0  0.5