How do I measure out-of-sample R² for a forecast on a panel of stocks?

Split a long panel of stocks by date with TimeSeriesSplit and .isin(), fit OLS on the training dates, and score the test forecasts with an out-of-sample R² against the training mean, per fold and pooled.

After this lesson, you can score a forecast on a panel of stocks with an out-of-sample R² against a benchmark known at the time of the forecast.

How do I score forecasts against the training mean?

The out-of-sample R² compares the model’s squared forecast errors with those of the mean return of the training dates, a forecast that needs no model. It is positive when the model’s errors are smaller.

\[ R^2_{\text{OOS}} = 1 - \frac{\sum_i (y_i - \hat y_i)^2}{\sum_i (y_i - \bar y_{\text{train}})^2} \]

Here \(y_i\) is the realised return of test row \(i\), \(\hat y_i\) the model’s forecast and \(\bar y_{\text{train}}\) the mean return of the training rows of that fold.

The example is a long panel, as in the lesson on long and wide panels, of ten made-up stocks over 100 trading days. Each row holds a signal known at the close and the stock’s return on the next day, which equals 0.002 times the signal plus normal noise with a standard deviation of 1.5%.

The split runs over dates, so all ten stocks of a date fall on the same side, as in the lesson on TimeSeriesSplit. .isin() keeps the rows whose date is among the selected dates. fold_forecasts fits OLS on the training dates, as in the lesson on OLS, and adds the forecasts and the training mean to the test rows. oos_r2 computes the score of a set of rows, and pd.concat stacks the test rows of the five folds.

The following box builds the panel, runs the five folds and prints each fold’s score and the pooled score.

import numpy as np
import pandas as pd
import statsmodels.formula.api as smf
from sklearn.model_selection import TimeSeriesSplit

rng = np.random.default_rng(42)
dates = pd.bdate_range("2026-01-05", periods=100)
tickers = ["AAA", "BBB", "CCC", "DDD", "EEE", "FFF", "GGG", "HHH", "III", "JJJ"]

panel = pd.DataFrame({
    "date": np.tile(dates, 10),
    "ticker": np.repeat(tickers, 100),
    "signal": rng.normal(0, 1, 1000),
})
panel["next_return"] = 0.002 * panel["signal"] + rng.normal(0, 0.015, 1000)

def fold_forecasts(panel, train_dates, test_dates):
    train = panel[panel["date"].isin(train_dates)]
    test = panel[panel["date"].isin(test_dates)]
    model = smf.ols("next_return ~ signal", data=train).fit()
    return test.assign(forecast=model.predict(test), benchmark=train["next_return"].mean())

def oos_r2(rows):
    return 1 - ((rows["next_return"] - rows["forecast"]) ** 2).sum() / ((rows["next_return"] - rows["benchmark"]) ** 2).sum()

splitter = TimeSeriesSplit(n_splits=5, test_size=10)
forecasts = pd.concat([fold_forecasts(panel, dates[train], dates[test]).assign(fold=fold) for fold, (train, test) in enumerate(splitter.split(dates), start=1)])

print(forecasts.groupby("fold")[["next_return", "forecast", "benchmark"]].apply(oos_r2).round(4))
print(round(oos_r2(forecasts), 4))
fold
1    0.0148
2    0.0184
3    0.0337
4   -0.0035
5    0.0460
dtype: float64
0.0231

Four of the five folds score above zero, and the pooled score of 0.0231 says that the model’s squared errors are 2.3% smaller than those of the training mean. A true effect of 0.002 against noise of 1.5% allows an R² of only about 1.7% in the population, so a real signal on daily returns gives a small score.

Why not score against the test mean?

The test mean uses the outcomes being forecast, so it is not available when the forecasts are made, and it gives the smallest squared errors any constant can give on the test rows. The R² that .score() and r2_score report uses it, and here it lowers the pooled score from 0.0231 to 0.0222.

The following box scores the forecasts against the mean of all test returns.

print(round(oos_r2(forecasts.assign(benchmark=forecasts["next_return"].mean())), 4))
0.0222

Your turn

Score a forecast of zero for every test row against the training mean. You should see −0.006, so on these data a forecast of zero does worse than the training mean.

.assign(forecast=0.0) replaces the model’s forecasts with zeros.

print(round(oos_r2(forecasts.assign(forecast=0.0)), 4))
-0.006