from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
# Small networks train faster on a few threads than on all cores
torch.set_num_threads(4)Predicting Returns with a Neural Network
In Reading Handwritten Digits and Pricing Options with Neural Networks, the networks learned relations that are strong and stable: how each digit is written, and how option prices vary across strikes and maturities. This notebook turns to a problem with much more noise: predicting the stock market’s return from the variables Welch and Goyal (2008) study. A linear regression and a neural network are re-estimated every year from 2000 to 2025 and compared with the simplest forecast, the historical average. Both lose, the network by much more, and seeing why is the point of the exercise.
Packages
PyTorch is the library we use to build and train networks.
The data
Amit Goyal keeps the data of Welch and Goyal (2008) up to date on his website, and Goyal et al. (2024) repeat their study through 2021 with 29 newer predictors. The monthly file has the S&P 500, its dividends and earnings, interest rates, and other variables proposed as predictors of the market’s return. We download it once and save it.
DATA = Path("../_data") if Path("../_data").exists() else Path("data")
file = DATA / "goyal_welch_monthly_2025.parquet"
if not file.exists():
url = ("https://docs.google.com/spreadsheets/d/"
"1qwpl2R_DNujpU5YUkk8lacP1tTeMb9iJ/export?format=csv")
DATA.mkdir(exist_ok=True)
pd.read_csv(url, thousands=",").to_parquet(file)
raw = pd.read_parquet(file)
raw.index = pd.PeriodIndex(raw.pop("yyyymm").astype(str), freq="M")
raw.tail(3)| Index | D12 | E12 | b/m | tbl | AAA | BAA | lty | ntis | Rfree | infl | ltr | corpr | svar | csp | CRSP_SPvw | CRSP_SPvwx | |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| yyyymm | |||||||||||||||||
| 2025-10 | 6840.20 | 78.6242 | 238.1967 | 0.172936 | 0.0382 | 0.0513 | 0.0574 | 0.0406 | -0.008996 | 0.0037 | -0.001044 | 0.0062 | 0.0038 | 0.001646 | NaN | 0.023013 | 0.022302 |
| 2025-11 | 6849.09 | 78.7722 | 242.3333 | 0.172380 | 0.0378 | 0.0526 | 0.0586 | 0.0409 | -0.008713 | 0.0030 | -0.001045 | 0.0062 | 0.0065 | 0.001700 | NaN | 0.002286 | 0.001166 |
| 2025-12 | 6845.50 | 78.9202 | 246.4700 | 0.171136 | 0.0359 | 0.0531 | 0.0590 | 0.0414 | -0.029750 | 0.0034 | -0.000210 | -0.0033 | -0.0020 | 0.000649 | NaN | 0.000834 | -0.000293 |
We build nine predictors as Welch and Goyal (2008) do: the dividend-price and earnings-price ratios of the S&P 500 (in logs), the book-to-market ratio of the Dow Jones, the Treasury bill rate, the term spread, the default spread, net equity issuance, stock variance, and inflation. Inflation is published with a delay, so we lag it one more month. The outcome is the next month’s equity premium: the return on the value-weighted CRSP index of S&P 500 stocks minus the Treasury bill rate.
X = pd.DataFrame({
"dp": np.log(raw["D12"]) - np.log(raw["Index"]),
"ep": np.log(raw["E12"]) - np.log(raw["Index"]),
"bm": raw["b/m"],
"tbl": raw["tbl"],
"tms": raw["lty"] - raw["tbl"],
"dfy": raw["BAA"] - raw["AAA"],
"ntis": raw["ntis"],
"svar": raw["svar"],
"infl": raw["infl"].shift(1),
})
premium = (raw["CRSP_SPvw"] - raw["Rfree"]).shift(-1).rename("premium")
data = pd.concat([X, premium], axis=1).dropna()
predictors = list(X.columns)
print(data.index.min(), "to", data.index.max(), f"({len(data)} months)")1926-12 to 2025-11 (1188 months)
Re-estimating every year
A forecaster in 2000 would not fit a model once and use it for 25 years. Each year, they would refit it on all the data available so far. We do the same, as Welch and Goyal (2008) do: at the end of each year from 1999 to 2024, we estimate the models on all months up to then and forecast the premium in each month of the following year. The premium in row t is earned during month t + 1, so at the end of December the last premium we know is the one in the November row.
years = range(2000, data.index.max().year + 1)
y = data["premium"].to_numpy()
test = data.index >= pd.Period("2000-01", "M")
def estimation_sample(year):
"""Months whose premium is known at the end of the year before `year`."""
return data.index < pd.Period(f"{year - 1}-12", "M")The benchmark is the simplest forecast: the average premium over all months known at the time of the forecast. A model is worth something only if it beats that. We measure this with the out-of-sample R^2, which compares a model’s squared forecast errors with the benchmark’s and is negative when the model does worse.
benchmark = data["premium"].expanding().mean().shift(1).to_numpy()
def r2_oos(forecast):
return 1 - ((y[test] - forecast[test]) ** 2).sum() / ((y[test] - benchmark[test]) ** 2).sum()Linear regressions
First, one predictor at a time, then all nine together, the “kitchen sink.” The first column is the R^2 of a regression on the whole sample up to 1999, the evidence a researcher would have had in 2000. The second is the out-of-sample R^2 of the forecasts re-estimated every year.
def linear_forecasts(cols):
forecast = np.full(len(data), np.nan)
for year in years:
est, out = estimation_sample(year), data.index.year == year
A = lambda rows: np.c_[np.ones(rows.sum()), data.loc[rows, cols]]
beta = np.linalg.lstsq(A(est), y[est], rcond=None)[0]
forecast[out] = A(out) @ beta
return forecast
def r2_in_sample(cols):
est = estimation_sample(2000)
A = np.c_[np.ones(est.sum()), data.loc[est, cols]]
resid = y[est] - A @ np.linalg.lstsq(A, y[est], rcond=None)[0]
return 1 - (resid ** 2).sum() / ((y[est] - y[est].mean()) ** 2).sum()
rows = []
for col in predictors + ["all nine"]:
cols = predictors if col == "all nine" else [col]
rows.append({"predictors": col,
"R2 up to 1999": r2_in_sample(cols),
"R2 out of sample (2000-2025)": r2_oos(linear_forecasts(cols))})
pd.DataFrame(rows).set_index("predictors").round(3)| R2 up to 1999 | R2 out of sample (2000-2025) | |
|---|---|---|
| predictors | ||
| dp | 0.002 | -0.003 |
| ep | 0.004 | -0.016 |
| bm | 0.007 | -0.006 |
| tbl | 0.003 | 0.001 |
| tms | 0.003 | -0.014 |
| dfy | 0.003 | -0.004 |
| ntis | 0.011 | -0.033 |
| svar | 0.000 | -0.010 |
| infl | 0.003 | -0.007 |
| all nine | 0.034 | -0.117 |
A neural network
The network has one hidden layer of 16 units. Each year we keep the last 12 years of the estimation sample as a validation sample, train on the earlier months, and keep the weights from the epoch with the lowest validation loss: this is early stopping. The weight_decay argument penalizes large weights, another guard against overfitting. The function below trains one network this way and also returns its training and validation losses.
def train_network(X_train, y_train, X_valid, y_valid, seed):
torch.manual_seed(seed)
net = nn.Sequential(nn.Linear(len(predictors), 16), nn.ReLU(), nn.Linear(16, 1))
opt = torch.optim.Adam(net.parameters(), lr=0.001, weight_decay=1e-3)
history, best_loss = [], np.inf
for epoch in range(3000):
opt.zero_grad()
loss = ((net(X_train) - y_train) ** 2).mean()
loss.backward()
opt.step()
with torch.no_grad():
valid_loss = ((net(X_valid) - y_valid) ** 2).mean().item()
history.append((loss.item(), valid_loss))
if valid_loss < best_loss:
best_loss = valid_loss
best_weights = {k: v.clone() for k, v in net.state_dict().items()}
net.load_state_dict(best_weights)
return net, historyA network’s forecast depends on its random starting weights, so each year we train five networks from different starting weights and average their forecasts, as Gu et al. (2020) do. Each year’s networks see the predictors standardized with the means and standard deviations of that year’s estimation sample. With 26 years and five networks a year, the loop trains 130 networks and takes a few minutes.
n_seeds = 5
to_tensor = lambda a: torch.tensor(np.asarray(a, dtype="float32"))
target = to_tensor(y[:, None])
nn_forecast = np.full(len(data), np.nan)
z_scores = pd.DataFrame(np.nan, index=data.index, columns=predictors)
for year in years:
est, out = estimation_sample(year), data.index.year == year
valid = np.zeros(len(data), dtype=bool)
valid[np.flatnonzero(est)[-144:]] = True # last 12 years of the estimation sample
train = est & ~valid
mu, sd = data.loc[est, predictors].mean(), data.loc[est, predictors].std()
Z = (data[predictors] - mu) / sd
z_scores[out] = Z[out]
Z = to_tensor(Z)
forecasts = []
for seed in range(n_seeds):
net, history = train_network(Z[train], target[train], Z[valid], target[valid], seed)
if year == years[0] and seed == 0:
first_history = history
with torch.no_grad():
forecasts.append(net(Z[out]).numpy().ravel())
nn_forecast[out] = np.mean(forecasts, axis=0)The losses of the first network, trained on data up to 1999, show the usual pattern: the training loss keeps falling, while the validation loss levels off above it. Early stopping keeps the weights from the epoch with the lowest validation loss, marked by the dotted line.
history = pd.DataFrame(first_history, columns=["Training", "Validation"])
fig, ax = plt.subplots(figsize=(7, 3.5))
history.plot(ax=ax)
ax.axvline(history["Validation"].idxmin(), color="0.5", ls=":", lw=1)
ax.set_yscale("log")
ax.set_xlabel("Epoch")
ax.set_ylabel("Mean squared error")
plt.show()Now the comparison that matters, on the 26 years of forecasts:
kitchen_sink = linear_forecasts(predictors)
pd.DataFrame(
{"R2 out of sample (2000-2025)": [r2_oos(kitchen_sink), r2_oos(nn_forecast)]},
index=["Linear, all nine", f"Neural network, {n_seeds} seeds"],
).round(3)| R2 out of sample (2000-2025) | |
|---|---|
| Linear, all nine | -0.117 |
| Neural network, 5 seeds | -0.539 |
Both models lose to the historical average, the network by much more. The next figure shows when. It accumulates, month by month, the benchmark’s squared error minus the model’s: the line rises in months when the model beats the historical average and falls when it loses.
dates = data.index[test].to_timestamp()
fig, ax = plt.subplots(figsize=(7, 3.5))
for label, forecast in [("Linear, all nine", kitchen_sink), ("Neural network", nn_forecast)]:
gain = (y[test] - benchmark[test]) ** 2 - (y[test] - forecast[test]) ** 2
ax.plot(dates, gain.cumsum(), label=label)
ax.axhline(0, color="0.6", lw=0.7)
ax.set_ylabel("Cumulative gain over\nthe historical average")
ax.legend(frameon=False)
plt.show()Why the models fail
Most of the loss comes in two episodes, the financial crisis of 2008 and 2009 and the COVID crash of March 2020. In both, some predictors took values far outside anything in the estimation sample. The table shows how far, in units of the estimation sample’s standard deviation, for each month’s forecast:
z_scores[test].agg(["min", "max"]).round(1)| dp | ep | bm | tbl | tms | dfy | ntis | svar | infl | |
|---|---|---|---|---|---|---|---|---|---|
| min | -3.5 | -5.6 | -2.0 | -1.2 | -2.5 | -0.8 | -3.1 | -0.5 | -4.0 |
| max | 0.1 | 0.4 | -0.6 | 0.7 | 2.4 | 3.2 | 0.3 | 12.3 | 2.1 |
Stock variance (svar) is the extreme case. The next figure puts it under the forecasts.
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 5), sharex=True)
ax1.plot(dates, benchmark[test], label="Historical average", color="0.4")
ax1.plot(dates, kitchen_sink[test], label="Linear, all nine", lw=0.8)
ax1.plot(dates, nn_forecast[test], label="Neural network", lw=0.8)
ax1.set_ylabel("Forecast premium")
ax1.legend(frameon=False, fontsize=8)
ax2.plot(dates, z_scores.loc[test, "svar"], color="0.3", lw=0.8)
ax2.set_ylabel("Stock variance\n(standard deviations)")
plt.show()In October 2008 and March 2020, stock variance was about 10 and 12 standard deviations above its average in the estimation sample, values no model had seen. A linear model extrapolates along a straight line, and its forecasts move a few percent. A network extrapolates in ways that depend on its weights, and here it forecast large losses in early 2009, just as the market began to recover. Averaging five networks removes the luck of a single set of starting weights, but not the extrapolation. Re-estimating every year does not help either: the models learn from each crisis only after it has happened. Neither problem shows up in the training sample, which is why models are judged on data they have not seen.
Takeaways
- A neural network learns a strong, stable relation from plenty of data with little effort, as with payoffs and option prices.
- Monthly stock returns offer the opposite: a weak signal, short samples, and predictors whose behavior changes over time. Flexibility then hurts more than it helps.
- Gu et al. (2020) do find gains from machine learning, with tens of thousands of stocks, many characteristics, and models re-estimated as new data arrive. Even then the out-of-sample R^2 is a percent or two a month.
- Whether flexibility must hurt in market timing is an open question. Kelly et al. (2024) prove that, with enough shrinkage, a model with far more parameters than observations can predict returns better than a small one. Their empirical model is a very wide network whose first-layer weights are drawn at random and never trained: thousands of random nonlinear transformations of the Welch and Goyal predictors, with only the output weights fitted by ridge regression on rolling 12-month windows. The out-of-sample R^2 stays small, but the timing strategy built on the forecasts earns a Sharpe ratio above 0.4. Nagel (2025) shows that with 12 observations and thousands of parameters the forecast becomes a weighted average of the last 12 returns, mostly the recent ones, so the strategy is in effect volatility-timed momentum, which happened to do well historically, rather than information extracted from the predictors. Kelly and Malamud (2025) reply that this critique has little bearing on their results.
Try it
- Set
n_seedsto 1 and then to 20. How much does the network’s out-of-sample R^2 change, and why? - Drop
svarand refit both models. What happens to their losses in 2008, 2009 and 2020? - Replace the expanding estimation sample with a rolling one of the last 30 years. Does forgetting the distant past help or hurt?
- Campbell and Thompson (2008) argue that investors would rule out a negative equity premium and set any negative forecast to zero. Goyal et al. (2024) apply the same restriction in their out-of-sample tests. Set the negative forecasts of both models to zero, for example with
np.maximum(nn_forecast, 0), and recompute the out-of-sample R^2. Which model gains more, and in which months? - Build a small version of Kelly et al. (2024). Divide each month’s premium by the square root of the average squared premium over the previous 12 months, so that returns have roughly unit volatility. Draw P/2 random vectors \boldsymbol{\omega}_i with independent standard normal entries, and from the standardized predictors \mathbf{x}_t build the P features \sin(2\,\boldsymbol{\omega}_i'\mathbf{x}_t) and \cos(2\,\boldsymbol{\omega}_i'\mathbf{x}_t). Each month, fit a ridge regression without intercept of the premium on the previous month’s features over the last 12 months, forecast the next month, and hold that forecast times the market, the timing strategy. For P = 2, 12, 120, 1200 and a small and a large ridge penalty, compute the out-of-sample R^2 and the strategy’s Sharpe ratio. Then, as Nagel (2025) suggests, compare with a strategy that holds the average standardized premium of the last 12 months. What does the comparison tell you about where the gains come from?