Why must the test period come after the training period?
Fit the same model on returns with no predictive signal, once with a random split and once with a chronological split, and see how overlapping 20-day labels make the random split look predictive.
After this lesson, you can split price data into training and test periods so that no training label uses a price from the test period.
What does a forward label know?
A label is the outcome a model predicts, here a stock’s return over the next 20 days, and it is known only 20 days later. The labels of two neighbouring days share 19 of their 20 daily returns, so their correlation is close to 1.
Here \(P_t\) is the close on day \(t\), \(x_t\) the past 20-day return, which is known at the close of day \(t\), and \(y_t\) the forward 20-day return, which is known at the close of day \(t + 20\).
The example is 2,520 days of a made-up stock with independent daily returns, normal with a mean of 0 and a standard deviation of 1%, so the past holds no information about the future. The model’s features are the day number and the past return. .shift(20) puts the close of 20 days earlier on each row and .shift(-20) the close of 20 days later, and .dropna() keeps the 2,480 rows with all values.
The labels of neighbouring days have a correlation of 0.96.
How well does a model score on random days?
A random split scores an R² of 0.92 on returns that cannot be predicted, because the training set holds the neighbours of each test day, whose labels share most of their returns with the test label.
train_test_split shuffles the rows and puts 20% of them in the test set, and random_state=0 fixes the shuffle. KNeighborsRegressor(n_neighbors=5) predicts the mean label of the five training rows with the closest features, and with the day number as a feature, the closest rows are the neighbouring days. .score() gives the test R², one minus the model’s squared errors divided by those of predicting the test mean.
The following box fits the model on a random split.
Trained on the first 80% of the days and tested on the rest, the same model scores an R² of −0.15, worse than predicting the test mean. The test starts on day 2,004, and training ends on day 1,983, whose label uses the close of day 2,003.
chronological_score cuts the rows at the start of the test period and leaves out the purge rows before it, the 20 rows whose labels would use closes from the test period. .iloc[:cut - purge] takes the training rows and .iloc[cut:] the test rows.
The following box fits the model on the earlier days and scores it on the later days.