Can you spot the mistakes in this machine-learning test of return forecasts?

Machine Learning
Backtesting
Tutorial
Python
When I was new to machine learning, I made several mistakes in a course assignment. Can you spot them before I list them?
Published

November 25, 2026

In my previous ridge regression post, I simulated monthly market returns, fitted ridge regression on the training data, chose its penalty on the validation data and evaluated its performance on the test data. But here, I show several mistakes I made in a course assignment when I was new to machine learning. Try to spot the mistakes in the method below before I tell you about them in Step 3.

The method

I test whether ordinary least squares (OLS) and ridge regression predict a stock’s monthly return better than the average return. I use the same simulated data as in my ridge post, with two changes that I describe in Step 1. Each row of the data is one stock in one month, with that month’s return and ten signals from the end of the previous month. The method that I use (wrongly) is the following:

  1. I split the rows randomly into training data (75%) and test data (25%) using scikit-learn’s train_test_split.
  2. I use five-fold cross-validation on the training data with GridSearchCV to pick the penalty parameter in ridge regression, which shrinks the coefficients toward zero to improve the mean squared error (MSE) on new data. The cross-validation divides the training data into five folds, with one fold at a time serving as the validation set while the regression is fitted on the other four.
  3. I fit OLS on the training data, and also ridge, with the penalty that had the lowest MSE according to the cross-validation.
  4. I compute each model’s out-of-sample R² on the test data with r2_score.
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.metrics import mean_squared_error, r2_score
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler

penalties = np.logspace(-1, 7, 33)


def my_method(data, signals, seed):
    X_train, X_test, y_train, y_test = train_test_split(data[signals], data["return"], test_size=0.25,
                                                        random_state=seed)
    ols = make_pipeline(StandardScaler(), LinearRegression()).fit(X_train, y_train)
    search = GridSearchCV(make_pipeline(StandardScaler(), Ridge()), {"ridge__alpha": penalties}, cv=5,
                          scoring="neg_mean_squared_error").fit(X_train, y_train)
    return {"penalty": search.best_params_["ridge__alpha"],
            "OLS R², %": 100 * r2_score(y_test, ols.predict(X_test)),
            "ridge R², %": 100 * r2_score(y_test, search.predict(X_test))}

Step 1. Simulating the data

In my ridge post, signals 1 and 2 predict returns, and the other eight signals do not. Here, I change two things. First, I simulate 500 stocks instead of one market, so the data have 120,000 rows from January 2000 to December 2019. Second, signals 1 and 2 stop predicting returns after 2009. This is an extreme case of what McLean and Pontiff (2016) find for 97 published signals, whose long-short portfolio returns are, on average, 58% lower after publication.

SEED = 0
N_STOCKS = 500
INTERCEPT = 0.5
TRUE_COEFFICIENTS = np.array([0.6, 0.6, 0, 0, 0, 0, 0, 0, 0, 0])
NOISE_SD = 4.5
LAST_YEAR_THE_SIGNALS_WORK = 2009


def simulate(seed, last_year_the_signals_work):
    rng = np.random.default_rng(seed)
    dates = pd.date_range("2000-01-31", "2019-12-31", freq="BME", name="date")
    stocks = [f"STOCK{k:03d}" for k in range(1, N_STOCKS + 1)]
    signals = [f"signal_{j}" for j in range(1, 11)]
    data = pd.DataFrame(index=pd.MultiIndex.from_product([dates, stocks], names=["date", "stock"]))
    data[signals] = rng.standard_normal((len(data), 10))
    works = data.index.get_level_values("date").year <= last_year_the_signals_work
    noise = rng.normal(0, NOISE_SD, len(data))
    data.insert(0, "return", INTERCEPT + works * (data[signals] @ TRUE_COEFFICIENTS) + noise)
    return data, signals


data, signals = simulate(SEED, LAST_YEAR_THE_SIGNALS_WORK)
print(data.iloc[:, :4].round(2).head().to_string())
print(f"rows: {len(data):,}")
                     return  signal_1  signal_2  signal_3
date       stock                                         
2000-01-31 STOCK001   -2.36      0.13     -0.13      0.64
           STOCK002    3.63     -0.62      0.04     -2.33
           STOCK003    5.35     -0.13      1.37     -0.67
           STOCK004    1.58     -1.01     -0.21     -0.16
           STOCK005    2.44     -1.26      1.51      1.35
rows: 120,000

The table shows the first five rows, with the return in percent and signals 1 to 3.

Step 2. Running the method

I compare OLS and ridge with a benchmark, which, in my opinion, is the simplest way to predict returns. The benchmark predicts every return with one average return, \(m\), and the out-of-sample R² compares each model with the benchmark:

\[ R^2 = 1 - \frac{\sum_{\text{test}} \left( r_{i,t} - \hat{r}_{i,t} \right)^2}{\sum_{\text{test}} \left( r_{i,t} - m \right)^2} \tag{1} \]

where \(r_{i,t}\) is stock \(i\)’s return in month \(t\), \(\hat{r}_{i,t}\) is the model’s predicted return, and both sums run over the same test rows. So a positive R² means that the model has a lower MSE than the benchmark, and a negative R² means a higher MSE. r2_score sets \(m\) to the average return of the test data.

print(pd.Series(my_method(data, signals, SEED)).round(2).to_string())
penalty        1000.00
OLS R², %         0.79
ridge R², %       0.79

The R² for both OLS and ridge is 0.79%. So, by my method, both models predict better than the benchmark. And the penalty is 1,000 according to the cross-validation.

Step 3. Spotting the three mistakes

Have you managed to spot the mistakes in this method? If you have, great. These are the three mistakes I made:

  1. train_test_split shuffles the rows at random. So each model is also fitted on rows from 2018 and 2019 and then used to predict returns in 2005. And remember that time series data, such as stock returns, are time-dependent, so we cannot shuffle the rows at random as I did.
  2. GridSearchCV with cv=5 divides the training data into five folds, and the rows are already shuffled, so every fold holds rows from all 20 years. And even if the five folds were in time order, the fifth fold, with the latest years, would help fit ridge whenever an earlier fold is the validation data. So, once again, I use future data to predict older data.
  3. r2_score uses the average return of the test data as \(m\) in (1). That average is impossible to know in practice when you evaluate the models month by month. You do not know the returns of the whole test period until that period has passed.

Step 4. Correcting the three mistakes

I correct the three mistakes as follows:

  1. In train_test_split, I set shuffle=False, so the rows stay in time order. The training data then runs from 2000 to 2014, and the test data from 2015 to 2019.
  2. In GridSearchCV, I use cv=TimeSeriesSplit(5) so that I choose the ridge penalty based on an expanding window. Each of the five folds is 30 months of validation data, and ridge is fitted on all the months before the fold.
  3. I replace \(m\) in (1) with the average return of the training data, so that the benchmark uses only training data.

The animation shows which rows the models are fitted on and tested on, and which rows ridge is validated on, first in my method and then after corrections 1 and 2.

Rows the models are fitted on and tested on, and rows ridge is validated on, in my method and after corrections 1 and 2 Signals 1 and 2 predict No signal predicts Split With my method, OLS's R² is +0.79% With the corrected method, OLS's R² is −1.60%

from sklearn.model_selection import TimeSeriesSplit


def corrected_method(data, signals):
    X_train, X_test, y_train, y_test = train_test_split(data[signals], data["return"], test_size=0.25,
                                                        shuffle=False)
    ols = make_pipeline(StandardScaler(), LinearRegression()).fit(X_train, y_train)
    search = GridSearchCV(make_pipeline(StandardScaler(), Ridge()), {"ridge__alpha": penalties},
                          cv=TimeSeriesSplit(5), scoring="neg_mean_squared_error").fit(X_train, y_train)
    benchmark_mse = mean_squared_error(y_test, np.full(len(y_test), y_train.mean()))
    return {"penalty": search.best_params_["ridge__alpha"],
            "OLS R², %": 100 * (1 - mean_squared_error(y_test, ols.predict(X_test)) / benchmark_mse),
            "ridge R², %": 100 * (1 - mean_squared_error(y_test, search.predict(X_test)) / benchmark_mse)}


X_train, X_test, y_train, y_test = train_test_split(data[signals], data["return"], test_size=0.25, shuffle=False)
train_dates, test_dates = X_train.index.get_level_values("date"), X_test.index.get_level_values("date")
for k, (fit_rows, validation_rows) in enumerate(TimeSeriesSplit(5).split(X_train), start=1):
    print(f"fold {k}: fitted on {train_dates[fit_rows[0]]:%b %Y} to {train_dates[fit_rows[-1]]:%b %Y}, "
          f"validated on {train_dates[validation_rows[0]]:%b %Y} to {train_dates[validation_rows[-1]]:%b %Y}")
print(f"test data: {test_dates[0]:%b %Y} to {test_dates[-1]:%b %Y}")
print(pd.Series(corrected_method(data, signals)).round(2).to_string())
fold 1: fitted on Jan 2000 to Jun 2002, validated on Jul 2002 to Dec 2004
fold 2: fitted on Jan 2000 to Dec 2004, validated on Jan 2005 to Jun 2007
fold 3: fitted on Jan 2000 to Jun 2007, validated on Jul 2007 to Dec 2009
fold 4: fitted on Jan 2000 to Dec 2009, validated on Jan 2010 to Jun 2012
fold 5: fitted on Jan 2000 to Jun 2012, validated on Jul 2012 to Dec 2014
test data: Jan 2015 to Dec 2019
penalty        10000.00
OLS R², %         -1.60
ridge R², %       -1.29

Now that the three mistakes are corrected, OLS’s R² is −1.60% and ridge’s is −1.29%. Although ridge predicts better than OLS, neither model predicts better than the benchmark: the simplest way to predict, using the average return of the training data. So, with the parameters I chose and in this dataset, neither model is good for predicting returns.

Signals 1 and 2 predict returns only until the end of 2009, but both models, fitted on 2000 to 2014, still use them in 2015 to 2019. There, the two signals only make the predictions differ from the average return of the training data, so each model has a higher MSE than the benchmark. The random split did not show that signals 1 and 2 stop predicting returns after 2009, because about half of its test rows come from 2000 to 2009.

Step 5. Repeating the experiment on 100 simulated data sets

One data set can mislead, so I repeat the experiment on 100 simulated data sets.

rows = []
for seed in range(100):
    sample, signals = simulate(seed, LAST_YEAR_THE_SIGNALS_WORK)
    rows.append({**{f"my method, {k}": v for k, v in my_method(sample, signals, seed).items()},
                 **{f"corrected method, {k}": v for k, v in corrected_method(sample, signals).items()}})
samples = pd.DataFrame(rows)
print(samples.drop(columns=["my method, penalty", "corrected method, penalty"]).mean().round(2).to_string())
print(f"my method, OLS R² above 0: {(samples['my method, OLS R², %'] > 0).sum()} of 100")
print(f"corrected method, OLS R² below 0: {(samples['corrected method, OLS R², %'] < 0).sum()} of 100")
print(f"corrected method, ridge R² above OLS's: "
      f"{(samples['corrected method, ridge R², %'] > samples['corrected method, OLS R², %']).sum()} of 100")
my method, OLS R², %             0.86
my method, ridge R², %           0.86
corrected method, OLS R², %     -1.58
corrected method, ridge R², %   -1.29
my method, OLS R² above 0: 100 of 100
corrected method, OLS R² below 0: 100 of 100
corrected method, ridge R² above OLS's: 100 of 100

With my method, OLS and ridge both have an average R² of 0.86%, and OLS’s R² is positive in all 100 data sets. With the corrected method, OLS’s R² averages −1.58% and is negative in all 100 data sets. Ridge’s R² averages −1.29% and is above OLS’s in every data set.

Conclusion

Mistakes like these can be costly, especially when the results are later used for decisions. And here, keeping track of the time order flips the conclusion about how well the models predict returns.

References

McLean, R. D., & Pontiff, J. (2016). Does academic research destroy stock return predictability? The Journal of Finance, 71(1), 5–32. https://doi.org/10.1111/jofi.12365