6,020 daily log returns, mean -0.00013, daily standard deviation 0.0100
Purged cross-validation in Python: why a model with no predictive power can score 90% accuracy
This is another tutorial where I want you to be mindful of backtesting, because in this case, you can get a mechanical look-ahead bias. When your outcome variable includes future data, some in-sample data can show up in out-of-sample results when you test the model. In this example, a model with no predictive power scores 90.5% accuracy, and 50.3% once I drop the training days whose outcomes overlap the test data.
Say you have 120 observations: 100 in-sample and 20 out-of-sample, and the outcome is the sign of the return over the next 20 days. If you are tested on the first out-of-sample observation, number 101, and you knew that at observation 100 the sign was plus, what would be the most logical bet? Probably plus again, because 19 of the 20 returns are the same ones you saw at the prior observation when you were trained.
The fix is to purge: drop the training days near the boundary whose outcomes overlap the test period. The animation below shows how purging the data helps prevent information leakage.
Step 1. Simulating the data
I simulate the returns myself, so I know up front that there is nothing to predict. Each day’s return is
\[r_t = 0.01\,z_t,\]
where \(z_t\) is a standard normal draw, so the returns have a mean of zero and a standard deviation of 1% a day.
import numpy as np
import pandas as pd
HORIZON = 20
N = 6_000
random_generator = np.random.default_rng(7)
total_days = N + HORIZON
dates = pd.bdate_range("2000-01-03", periods=total_days)
daily_moves = random_generator.normal(0, 0.01, total_days)
ret = pd.Series(daily_moves, index=dates)
print(f"{len(ret):,} daily log returns, mean {ret.mean():+.5f}, "
f"daily standard deviation {ret.std():.4f}")Step 2. Defining the outcome: up or down over the next 20 days
Day \(t\) is labeled 1 if the sum of the next 20 log returns is positive and 0 if it is not:
\[y_t = \begin{cases} 1 & \text{if } r_{t+1} + r_{t+2} + \dots + r_{t+20} > 0, \\ 0 & \text{otherwise.} \end{cases}\]
rolling_20_day_sum = ret.rolling(HORIZON).sum()
future = rolling_20_day_sum.shift(-HORIZON)
future_of_labelled_days = future.iloc[:N]
rose_over_next_20_days = future_of_labelled_days > 0
y = rose_over_next_20_days.astype(int).to_numpy()
print(f"{len(y):,} labels, {y.mean():.1%} of them positive")6,000 labels, 48.4% of them positive
Step 3. Measuring how much neighboring labels overlap
Two neighboring labels share 19 of their 20 returns, and they agree about 91% of the time.
day = 100
next_day = day + 1
print(f"day {day}'s label uses returns {next_day} to {day + HORIZON}")
print(f"day {next_day}'s label uses returns {next_day + 1} to {next_day + HORIZON}")
print(f"the two overlap on returns {next_day + 1} to {day + HORIZON}: {HORIZON - 1} of {HORIZON}")day 100's label uses returns 101 to 120
day 101's label uses returns 102 to 121
the two overlap on returns 102 to 120: 19 of 20
label_today = y[:-1]
label_next_day = y[1:]
labels_match = label_today == label_next_day
agree = labels_match.mean()
print(f"neighboring labels agree {agree:.0%} of the time")neighboring labels agree 91% of the time
Step 4. Running the naive test
I test one day at a time and train only on the 252 days before it. The model’s only feature is the day’s number, and it copies the label of the nearest training day, which is always the day before the test day.
from sklearn.model_selection import TimeSeriesSplit
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
day_numbers = np.arange(N)
X = day_numbers.reshape(-1, 1)
def walk_forward(gap):
splitter = TimeSeriesSplit(n_splits=3_600, test_size=1, max_train_size=252, gap=gap)
true_labels = []
predictions = []
for train_rows, test_rows in splitter.split(X):
model = KNeighborsClassifier(n_neighbors=1)
model.fit(X[train_rows], y[train_rows])
predicted_labels = model.predict(X[test_rows])
predictions.append(predicted_labels[0])
true_labels.append(y[test_rows][0])
return accuracy_score(true_labels, predictions)
naive = walk_forward(gap=0)
print(f"walk-forward, no gap: {naive:.1%}")walk-forward, no gap: 90.5%
The model scores 90.5%, even though the feature predicts nothing and the returns contain no signal.
I chose the most extreme case to make the problem as intuitive as possible, because it gets less intuitive with larger data sets, more features, and so on.
Step 5. Looking at what the model copied
def first_split(gap):
splitter = TimeSeriesSplit(n_splits=3_600, test_size=1, max_train_size=252, gap=gap)
train_rows, test_rows = next(splitter.split(X))
last_training_day = train_rows[-1]
test_day = test_rows[0]
days_apart = test_day - last_training_day
shared_returns = max(HORIZON - days_apart, 0)
return last_training_day, test_day, days_apart, shared_returns
last_training_day, test_day, days_apart, shared_returns = first_split(gap=0)
print(f"last training day: {last_training_day}")
print(f"test day: {test_day}")
print(f"days apart: {days_apart}")
print(f"returns their labels share: {shared_returns} of {HORIZON}")last training day: 2399
test day: 2400
days apart: 1
returns their labels share: 19 of 20
Step 6. Purging the overlap
With gap=20 in scikit-learn’s TimeSeriesSplit, the 20 days before each test day are left out of training.
I want the reader to take away that it is important to understand how you define your outcome variable, because if you have look-ahead bias like this, you need to fix it, in this case by purging, so your model is not asked about things it already knew.
last_training_day, test_day, days_apart, shared_returns = first_split(gap=HORIZON)
print(f"last training day {last_training_day}, test day {test_day}, "
f"{days_apart} days apart, labels share {shared_returns} returns")
purged = walk_forward(gap=HORIZON)
print(f"walk-forward, {HORIZON}-day gap: {purged:.1%}")last training day 2379, test day 2400, 21 days apart, labels share 0 returns
walk-forward, 20-day gap: 50.3%
Accuracy falls to 50.3%, close to the 50% of a coin flip.
Step 7. Comparing the results
import matplotlib.pyplot as plt
RED, TEAL, GREY = "#C0392B", "#17868A", "#888888"
BG, INK, GRID, SPINE, AXIS_TEXT = "#FCEFE3", "#1f1f1f", "#EADCCC", "#D5C6B4", "#4a4a4a"
def style_chart(figure, axis):
figure.patch.set_facecolor(BG)
axis.set_facecolor(BG)
axis.grid(True, axis="y", color=GRID, lw=1.0)
axis.set_axisbelow(True)
for side in ("top", "right"):
axis.spines[side].set_visible(False)
for side in ("left", "bottom"):
axis.spines[side].set_color(SPINE)
axis.tick_params(axis="both", length=0, colors=INK, pad=6)
axis.xaxis.label.set_color(AXIS_TEXT)
axis.yaxis.label.set_color(AXIS_TEXT)
axis.title.set_color(INK)
legend = axis.get_legend()
if legend is not None:
for text, handle in zip(legend.get_texts(), legend.legend_handles):
if hasattr(handle, "get_color"):
text.set_color(handle.get_color())
else:
text.set_color(handle.get_facecolor())
bar_labels = ["naive\n(no gap)", f"purged\n({HORIZON}-day gap)", "chance\n(50%)"]
bar_heights = [naive * 100, purged * 100, 50.0]
plt.figure(figsize=(7, 4.5))
bars = plt.bar(bar_labels, bar_heights, color=[RED, TEAL, GREY])
plt.ylim(0, 100)
plt.ylabel("accuracy (%)")
plt.title("Accuracy with no gap, with a 20-day gap, and by chance")
plt.bar_label(bars, fmt="%.1f%%", padding=3, color=INK)
style_chart(plt.gcf(), plt.gca())
plt.tight_layout()
plt.savefig("purging_accuracy.png", dpi=120, bbox_inches="tight", facecolor=BG)
plt.show()
Ignoring the overlap raises the measured accuracy by 40.2 percentage points, from 50.3% to 90.5%.
Limitations
This is a tutorial, so a limitations section is a bit misleading here. But of course, the outcome variable only cares about direction, and profit can matter more, because you may have a bigger problem if your model is a coin flip and you trade large sizes.
The example is extreme, but that is on purpose.
Purging is one thing, but there are other things you need to be mindful of, such as features rescaled with a mean computed over the whole sample, including test days.
Conclusion
So the conclusion is that backtesting has several biases, and it is important to make your backtest as robust as possible by eliminating them, and this is one of them.
References
Jansen, S. (2020). Machine learning for algorithmic trading: Predictive models to extract signals from market and alternative data for systematic trading strategies with Python (2nd ed.). Packt Publishing.
López de Prado, M. (2018). Advances in financial machine learning. Wiley.
scikit-learn developers. (n.d.). TimeSeriesSplit. scikit-learn. https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.TimeSeriesSplit.html
Read next
- Backtest overfitting: when out-of-sample becomes in-sample How a hold-out gets used up once you start tuning against it.
- Sharpe ratio bootstrap in Python: the best of 216 strategies reached 0.72 by chance Separating a real edge from luck with a bootstrap.
Disclaimer: a teaching example on simulated data. The returns are generated and contain no signal by construction. Not investment advice.