library(tidyverse)
library(nanoparquet)
library(tidymodels)
sample_start <- "1973-01-01"
sample_end <- "2023-12-31"
test_start <- "2000-01-01"
validation_start <- "1995-01-01"
macro_names <- c("dp", "tbl", "tms", "dfy", "svar")
features <- c("ret_lag_1", "momentum_12", macro_names)
hidden_units <- 5
decays <- c(1, 3, 10, 30, 100, 300, 1000)
n_networks <- 5
epochs <- 500
ridge_lambda <- 1e-4
months_per_year <- 12
anomalies <- read_parquet("data/osap_long_short_returns.parquet") |>
mutate(date = floor_date(date, "month")) |>
filter(date >= sample_start, date <= sample_end) |>
select(date, where(\(x) !anyNA(x)))
returns <- as.matrix(select(anomalies, -date)) / 100
estimation_returns <- returns[anomalies$date < test_start, ]
# Macro predictors of month t - 1 are known when month t starts
macro <- read_parquet("data/macro_predictors.parquet") |>
transmute(date = date %m+% months(1), across(all_of(macro_names))) |>
mutate(across(all_of(macro_names), \(x) {
(x - mean(x[date < test_start])) / sd(x[date < test_start])
}))
panel <- anomalies |>
pivot_longer(-date, names_to = "anomaly", values_to = "ret") |>
mutate(ret = ret / 100) |>
arrange(anomaly, date) |>
mutate(
ret_lag_1 = lag(ret),
momentum_12 = slider::slide_dbl(
lag(ret),
mean,
.before = 11,
.complete = TRUE
),
.by = anomaly
) |>
left_join(macro, join_by(date)) |>
drop_na()
train <- filter(panel, date < test_start)
test_rows <- panel$date >= test_startExercise 9: Neural network forecasts
This exercise goes with lecture 13. The tasks forecast the return of each anomaly with a neural network instead of the random forest of the lecture and uses the forecasts as expected returns in a portfolio, as the lecture does with the forests. The data are the panel of lecture 13: one row per anomaly and month, with the return, last month’s return, the average return over the last 12 months (factor momentum) and five macro predictors. The estimation sample runs until 1999, the test sample from 2000 to 2023. Exercise 10 compares what the forecast portfolios trade.
Neural network forecasts
Exercises:
- Build the panel of lecture 13 from the anomalies with complete returns from January 1973 to December 2023 (exercise 7) and the macro predictors
dp,tbl,tms,dfyandsvarinmacro_predictors.parquet. Lag the macro predictors by one month, so that they are known when the month starts, and standardize them with their mean and standard deviation until 1999. How many anomaly-months are in the training sample (until 1999) and in the test sample? - Standardize the seven predictors with the means and standard deviations of the training sample, and divide the returns by their standard deviation in the training sample. Why does a value of the weight decay only mean something once the returns are scaled?
- Specify a network with one hidden layer of five neurons, the logistic activation and a linear output:
mlp()with the enginennetin R,MLPRegressor()withsolver="lbfgs"from scikit-learn in Python, at most 500 iterations. Choose the weight decay from the grid 1, 3, 10, 30, 100, 300, 1000 withtune_grid()orGridSearchCV(): fit the network on 1974–1994 and compute the forecast error in the validation years 1995–1999. Which decay do you choose? - Fit five networks with the chosen decay on the whole training sample, each from a different random start (seeds 1 to 5), and average their forecasts. Compute the out-of-sample \(R^2\) in the test sample, \(R^2_{oos} = 1 - \sum (r_{i,t} - \hat r_{i,t})^2 / \sum r_{i,t}^2\), which compares the forecasts with a forecast of zero, as in Gu, Kelly, and Xiu (2020). Compare it with OLS on the same seven predictors.
- Use the forecasts as expected returns in the mean-variance weights of lecture 13, \(\omega_t = (\hat\Sigma + \lambda I)^{-1}\hat\mu_t\), with the covariance matrix of the estimation sample 1973–1999 and the ridge penalty \(\lambda = 10^{-4}\) of exercise 7. Compute the annualized Sharpe ratio of this forecast portfolio in the estimation sample (1974–1999) and in the test sample. How does it compare with the ridge SDF of exercise 7, whose weights stay constant?
Solutions:
The panel is built as in lecture 13. The forecasts need 12 months of past returns, so the panel starts in January 1974. ridge_lambda is the penalty that cross-validation chose in exercise 7.
from datetime import date
import numpy as np
import polars as pl
from sklearn.base import clone
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GridSearchCV, PredefinedSplit
from sklearn.neural_network import MLPRegressor
sample_start = date(1973, 1, 1)
sample_end = date(2023, 12, 31)
test_start = date(2000, 1, 1)
validation_start = date(1995, 1, 1)
macro_names = ["dp", "tbl", "tms", "dfy", "svar"]
features = ["ret_lag_1", "momentum_12", *macro_names]
hidden_units = 5
decays = [1, 3, 10, 30, 100, 300, 1000]
n_networks = 5
max_iterations = 500
ridge_lambda = 1e-4
months_per_year = 12
anomalies = (
pl.read_parquet("data/osap_long_short_returns.parquet")
.with_columns(pl.col("date").dt.truncate("1mo"))
.filter(pl.col("date").is_between(sample_start, sample_end))
)
complete = [
c for c in anomalies.columns if c != "date" and anomalies[c].null_count() == 0
]
returns = anomalies.select(complete).to_numpy() / 100
estimation_returns = returns[(anomalies["date"] < test_start).to_numpy()]
# Macro predictors of month t - 1 are known when month t starts
in_estimation = pl.col("date") < test_start
macro = (
pl.read_parquet("data/macro_predictors.parquet")
.select(pl.col("date").dt.offset_by("1mo"), *macro_names)
.with_columns(
(
(pl.col(c) - pl.col(c).filter(in_estimation).mean())
/ pl.col(c).filter(in_estimation).std()
).alias(c)
for c in macro_names
)
)
panel = (
anomalies.select("date", *complete)
.unpivot(index="date", variable_name="anomaly", value_name="ret")
.with_columns(pl.col("ret") / 100)
.sort("anomaly", "date")
.with_columns(
ret_lag_1=pl.col("ret").shift(1).over("anomaly"),
momentum_12=pl.col("ret").shift(1).rolling_mean(12).over("anomaly"),
)
.join(macro, on="date", how="left")
.drop_nulls()
)
train = panel.filter(pl.col("date") < test_start)
test_rows = (panel["date"] >= test_start).to_numpy()158 anomalies have complete returns. The panel runs from January 1974 to December 2023, with 49,296 anomaly-months in the training sample (158 anomalies times 312 months) and 45,504 in the test sample (288 months).
The weight decay adds \(\lambda \sum_k \theta_k^2\), the decay times the sum of the squared weights and constants of the network, to the sum of squared forecast errors. The squared errors depend on the unit of the returns: in percent, they are 10,000 times larger than in decimals, and the same decay would penalize the weights much less. Measured in units of their standard deviation, the returns have a variance of one, so a decay of 300 means the same whatever the unit of the returns. The predictors are standardized for a similar reason: the penalty treats all weights alike, so all inputs should be on the same scale.
Both nnet(), the engine behind mlp(), and MLPRegressor() minimize the sum of squared errors plus the decay times the sum of squared weights, so the same number means the same penalty. scikit-learn divides both terms by twice the number of observations (its documentation says that the penalty “is divided by the sample size”), which does not change the solution. One difference remains: nnet() also penalizes the constant of each neuron, scikit-learn does not.
The workflow is that of the forest in lecture 13, with the network as the model. The network’s penalty is the weight decay, and tune() leaves it open. The decay is chosen on one split instead of folds: estimation until 1994, validation 1995–1999. make_splits() and manual_rset() (R) or PredefinedSplit() (Python, \(-1\) for the estimation months and \(0\) for the validation months) turn this split into a resample for tune_grid() or GridSearchCV(). The metric is the default of each package: the root mean squared error in R, the negative mean squared error in Python, both of the scaled returns.
# The predictors standardized with the training sample, and the return in
# units of its standard deviation there, which gives the weight decay a scale
ret_sd <- sd(train$ret)
scaled_panel <- panel |>
mutate(
across(all_of(features), \(x) {
(x - mean(x[date < test_start])) / sd(x[date < test_start])
}),
ret_scaled = ret / ret_sd
)
scaled_train <- filter(scaled_panel, date < test_start)
# Estimate until validation_start, choose the weight decay on the years after
validation_split <- make_splits(
filter(scaled_train, date < validation_start),
assessment = filter(scaled_train, date >= validation_start)
)
network_model <- mlp(
hidden_units = hidden_units,
penalty = tune(),
epochs = epochs
) |>
set_engine("nnet") |>
set_mode("regression")
network_workflow <- workflow() |>
add_variables(outcomes = ret_scaled, predictors = all_of(features)) |>
add_model(network_model)
set.seed(1) # tune_grid() draws the random starts of the networks
network_tuning <- tune_grid(
network_workflow,
manual_rset(list(validation_split), ids = "validation"),
grid = tibble(penalty = decays)
)
best_decay <- select_best(network_tuning, metric = "rmse")
collect_metrics(network_tuning) |>
filter(.metric == "rmse") |>
select(penalty, rmse = mean)# The predictors standardized with the training sample, and the return in
# units of its standard deviation there, which gives the weight decay a scale
ret_sd = train["ret"].std()
scaled_panel = panel.with_columns(
[
(pl.col(c) - pl.col(c).filter(in_estimation).mean())
/ pl.col(c).filter(in_estimation).std()
for c in features
],
ret_scaled=pl.col("ret") / ret_sd,
)
scaled_train = scaled_panel.filter(in_estimation)
# Estimate until validation_start (-1), choose the weight decay on the years
# after (0)
validation_split = PredefinedSplit(
np.where(scaled_train["date"] < validation_start, -1, 0)
)
network_model = MLPRegressor(
hidden_layer_sizes=(hidden_units,),
activation="logistic",
solver="lbfgs",
max_iter=max_iterations,
random_state=1,
)
x_train = scaled_train.select(features).to_numpy()
y_train = scaled_train["ret_scaled"].to_numpy()
network_search = GridSearchCV(
network_model,
{"alpha": decays},
scoring="neg_mean_squared_error",
cv=validation_split,
)
network_search.fit(x_train, y_train)
pl.DataFrame(
{"decay": decays, "rmse": np.sqrt(-network_search.cv_results_["mean_test_score"])}
)#> # A tibble: 7 × 2
#> penalty rmse
#> <dbl> <dbl>
#> 1 1 1.24
#> 2 3 1.13
#> 3 10 1.15
#> 4 30 1.12
#> 5 100 1.12
#> 6 300 1.12
#> 7 1000 1.12Both languages choose a decay of 300. In R, as the output above shows, the root mean squared error of the scaled returns in the validation years falls from 1.24 with a decay of 1 to 1.12 for the decays from 30 to 1000; select_best() compares the unrounded errors, which are smallest at 300. With little weight decay, the network fits noise of 1974–1994 that does not come back in 1995–1999. Python’s errors differ a little (1.25 with a decay of 1, 1.12 with 300), because its networks start from other random weights, but they are also lowest at 300. The errors for decays from 30 to 1000 are almost the same, so the exact choice in this range matters little.
scikit-learn may warn that L-BFGS stopped after 500 iterations before it converged; in our run, this happens once while choosing the decay and does not change the choice.
The ensemble averages five networks that differ only in their random starting weights. The forecasts are converted back to returns with ret_sd.
# An ensemble: the average forecast of networks from different random starts
network_forecasts <- map(seq_len(n_networks), \(seed) {
set.seed(seed)
network_fit <- network_workflow |>
finalize_workflow(best_decay) |>
fit(scaled_train)
predict(network_fit, scaled_panel)$.pred * ret_sd
})
network_forecast <- reduce(network_forecasts, `+`) / n_networks
ols_fit <- lm(reformulate(features, response = "ret"), data = train)
ols_forecast <- predict(ols_fit, panel)
oos_r2 <- function(forecast) {
1 -
sum((panel$ret[test_rows] - forecast[test_rows])^2) /
sum(panel$ret[test_rows]^2)
}
c(ols = oos_r2(ols_forecast), network = oos_r2(network_forecast))# An ensemble: the average forecast of networks from different random starts
network_forecasts = []
for seed in range(1, n_networks + 1):
network = clone(network_search.best_estimator_).set_params(random_state=seed)
network.fit(x_train, y_train)
network_forecasts.append(
network.predict(scaled_panel.select(features).to_numpy()) * ret_sd
)
network_forecast = np.mean(network_forecasts, axis=0)
ols_forecast = (
LinearRegression()
.fit(train.select(features).to_numpy(), train["ret"].to_numpy())
.predict(panel.select(features).to_numpy())
)
def oos_r2(forecast):
realized = panel["ret"].to_numpy()[test_rows]
return 1 - np.sum((realized - forecast[test_rows]) ** 2) / np.sum(realized**2)
{"ols": oos_r2(ols_forecast), "network": oos_r2(network_forecast)}#> ols network
#> 0.006457806 0.012358983 The ensemble of networks has an out-of-sample \(R^2\) of 1.24% in R and 1.27% in Python, about twice the 0.65% of OLS. OLS has no random start, so its \(R^2\) is the same in both languages; the networks differ somewhat, because R and Python draw different starting weights and use different optimizers.
For the portfolio, the forecasts go into a matrix with one row per month and one column per anomaly, in the order of the return matrix. Because \(\hat\Sigma + \lambda I\) is symmetric, the weights of all months are the forecast matrix times its inverse.
sharpe_ratio <- function(x) mean(x) / sd(x) * sqrt(months_per_year)
panel_dates <- sort(unique(panel$date))
to_matrix <- function(values) {
panel |>
transmute(date, anomaly, value = values) |>
pivot_wider(names_from = anomaly, values_from = value) |>
arrange(date) |>
select(all_of(colnames(returns))) |>
as.matrix()
}
panel_returns <- to_matrix(panel$ret)
covariance <- cov(estimation_returns)
forecast_weights <- function(forecast) {
to_matrix(forecast) %*% solve(covariance + ridge_lambda * diag(ncol(returns)))
}
forecast_sharpe <- function(forecast) {
portfolio_return <- rowSums(forecast_weights(forecast) * panel_returns)
c(
estimation = sharpe_ratio(portfolio_return[panel_dates < test_start]),
test = sharpe_ratio(portfolio_return[panel_dates >= test_start])
)
}
ridge_weights <- solve(
crossprod(estimation_returns) +
nrow(estimation_returns) * ridge_lambda * diag(ncol(returns)),
colSums(estimation_returns)
)
rbind(
ols = forecast_sharpe(ols_forecast),
network = forecast_sharpe(network_forecast),
ridge_sdf = c(
estimation = NA,
test = sharpe_ratio(
returns[anomalies$date >= test_start, ] %*% ridge_weights
)
)
)def sharpe_ratio(x):
return np.mean(x) / np.std(x, ddof=1) * np.sqrt(months_per_year)
panel_dates = panel["date"].unique().sort().to_numpy()
def to_matrix(values):
return (
panel.select("date", "anomaly", value=pl.Series(values))
.pivot(on="anomaly", index="date", values="value")
.sort("date")
.select(complete)
.to_numpy()
)
panel_returns = to_matrix(panel["ret"])
covariance = np.cov(estimation_returns, rowvar=False)
def forecast_weights(forecast):
return to_matrix(forecast) @ np.linalg.inv(
covariance + ridge_lambda * np.eye(len(complete))
)
def forecast_sharpe(forecast):
portfolio_return = (forecast_weights(forecast) * panel_returns).sum(axis=1)
return {
"estimation": sharpe_ratio(portfolio_return[panel_dates < test_start]),
"test": sharpe_ratio(portfolio_return[panel_dates >= test_start]),
}
ridge_weights = np.linalg.solve(
estimation_returns.T @ estimation_returns
+ estimation_returns.shape[0] * ridge_lambda * np.eye(len(complete)),
estimation_returns.sum(axis=0),
)
{
"ols": forecast_sharpe(ols_forecast),
"network": forecast_sharpe(network_forecast),
"ridge_sdf": sharpe_ratio(
returns[(anomalies["date"] >= test_start).to_numpy()] @ ridge_weights
),
}The table collects the Sharpe ratios that the code prints and the out-of-sample \(R^2\) of the ensemble chunk:
| Portfolio | Out-of-sample \(R^2\) | Sharpe ratio 1974–1999 | Sharpe ratio 2000–2023 |
|---|---|---|---|
| Forecasts: OLS | 0.65% | 8.68 | 1.13 |
| Forecasts: neural network, R | 1.24% | 9.23 | 1.36 |
| Forecasts: neural network, Python | 1.27% | 9.20 | 1.37 |
| Ridge SDF, constant weights | 2.89 |
The better forecasts of the network also make a better portfolio than OLS. Both forecast portfolios, however, earn less than half the Sharpe ratio of the ridge SDF in the test sample, although they use the same covariance matrix and penalty: only the expected returns change every month. Their Sharpe ratios of around 9 until 1999 are in-sample, because the forecasts are fitted on these years.