Start investing in Bitcoin with Pix, in a few minutesSponsoredOpen free account
Overfitting in Trading: Why robots with perfect backtest fail
Trading

Overfitting in Trading: Why robots with perfect backtest fail

Overfitting in trading is adjusting the strategy to the noise of the past. Here's how to identify, an example in Python and how to avoid with out-of-sample and walk-forward.

Photo: Unsplash

By Boletim Bitcoin newsroom

. 6 min reading.

Overfitting in trading is adjusting a strategy to the history until it “decorates” the past, including random noise, rather than capturing a behavior that repeats itself. The result is the perfect backtest robot that loses money so it goes to the real account. It is the most common, and most expensive, mistake of someone who starts in algorithmic trading.

In short: The more parameters and the more combinations you test, the greater the chance that the best result will be lucky. To protect yourself, use few parameters, reserve data outside the sample, walk-forward, include costs and be wary of perfect capital curves. A robust robot performs reasonable performance in a wide range of parameters, not just at one point.

What is overfitting, in plain language?

The term comes from statistics and machine learning. A “on-adjusted” model explains very well the data that it has seen and the new ones badly, as shown in the classic figure of the Wikipedia entry.

Graphic with dots of two classes separated by a smooth line and a full line of curves that adjusts to each point The green line surrounds each point and hits 100% of the known data; Black is simpler and makes some mistakes. In new data, black tends to do better. It's the same dilemma as a robot with dozens of filters. Credit: Chabacano, CC BY-SA 4.0 license, via Wikimedia Commons.

In trading, the “green line” is the strategy that has a time filter, a day of the week filter, three averages, IFR between 37 and 61 and a stop of 143 points. Each filter eliminates some past losses. Together, they create a rule that only works in that specific past.

Want to buy bitcoin?Deposit in reais with PIX and buy BTC and other cryptos in a few minutes.Open account

Why does the perfect backtest deceive?

Because the market has a lot of noise. If you test enough combinations, some will look brilliant by chance, just as, among a thousand people throwing coin, someone hits ten guys in a row.

Researchers David Bailey, Jonathan Borwein, Marcos López de Prado and Qiji Zhu called it backtest overfitting In an article published in 2014 in the news of the American Mathematical Society. The conclusion: the more configurations you test, the more likely the best backtest is over-adjusted, and almost no one tells you how many attempts you made (Summary at SSRN). The authors also argue that under certain conditions the expected result outside the sample can be negative, not just zero.

3 parameterswith 20 values each
8.000Different backtests (20 × 20 × 20)
1"Champion" that can be just luck

Example in Python: The training champion in the test

The code below tests 174 combinations of moving averages in a training period (in-sample) and applies the best pair to a test period (out-of-sample) that did not participate in the choice:

import itertools
import pandas as pd

df = pd.read_csv("btcusdt_1d.csv", parse_dates=["date"], index_col="date")
treino = df.loc[:"2022-12-31", "close"]   # in-sample
teste = df.loc["2023-01-01":, "close"]    # out-of-sample

def backtest(close, r, l, custo=0.001):
    rapida = close.rolling(r).mean()
    lenta = close.rolling(l).mean()
    pos = (rapida > lenta).astype(int).shift(1).fillna(0)
    ret = pos * close.pct_change().fillna(0) - pos.diff().abs().fillna(0) * custo
    return (1 + ret).prod() - 1

grade = [(r, l) for r, l in itertools.product(range(5, 55, 5), range(20, 210, 10)) if r < l]
resultados = {p: backtest(treino, *p) for p in grade}
melhor = max(resultados, key=resultados.get)

print(f"Combinações testadas: {len(grade)}")
print(f"Melhor no treino {melhor}: {resultados[melhor]:.1%}")
print(f"Mesmos parâmetros no teste: {backtest(teste, *melhor):.1%}")

What matters is not the exact number, which depends on the data, but the comparison. If the return of the test is much worse than the training, the “champion” probably explored noise. An even better exercise is to look at the entire table of results: if the neighbors of the best pair also go well, there is a stable region; If the best is an isolated peak surrounded by damage, it is overfitting. The fundamentals of the test are in backtest and the base code in Python for trading.

Signs that your strategy is over-optimized

Signs of robustness

  • Few parameters, with explainable logic
  • Similar result in wide ranges of values
  • Works, with less brightness, on other assets
  • Out-of-sample consistent with in-sample
  • Hundreds of sample operations

Overfitting signs

  • Capital curve almost straight
  • "broken" parameters such as 37, 143, 61
  • Changes from profit to loss with minimum adjustment
  • Filters created to avoid specific losses
  • Few operations and very high hit rate

How to avoid overfitting: the method

Defenses against overoptimization

  1. Hypothesis before the dataHave a reason for the rule to work (trend, average reversal) before opening the optimizer.
  2. Few parametersEach extra parameter multiplies the combinations and the chance to find luck.
  3. Book the out-of-sampleSeparate 20% to 30% of the most recent history and test it once.
  4. Walk-forwardOptimize in a window, test the following, proceed and join only the test snippets.
  5. Choose the plateau, not the peakPrefer parameters in the middle of a good region, not the most isolated.
  6. Testing in other marketsA trend idea that only works on an asset is suspicious.
  7. Include costs and count the attemptsWrite down how many versions you tested; The more, the more demanding the validation should be.

Walk-forward in practice

The method was presented by Robert Pardo in 1992, according to the Wikipedia. Example with data from 2019 to 2026:

GameOptimizes inTest in
12019 a 20201st semester of 2021
22nd without. from 2019 to 1st without. of 20212nd half of 2021
32020 a 20211st semester of 2022
…advances 6 months…
Endup to 1st without. of 20262nd half of 2026

The performance that counts is the sum of the test semesters, which simulates how the robot would be re-optimized and used in real life.

Tools that help (and can get in the way)

MetaTrader 5 has complete optimization and a fast genetic algorithm, which seeks the best combinations by crossing and mutating parameter sets, according to the Help about optimization types. It is powerful, and therefore dangerous: the genetic algorithm finds the peak of luck very efficiently. Use together with the “Forward” option of the tester, which reserves 1/2, 1/3 or 1/4 of the period for validation (Tester help). details in the guide MQL5 Expert Advisor.

In TradingView, a cousin of overfitting is the repainting: Scripts that calculate different in history and in real time, for example using candlestick data still open or larger graphical time without confirmation, depending on the Repainting documentation. The result is the same: beautiful backtest, real bad operation. The Pine Script Tutorial Shows how to avoid.

The video below, in Portuguese, shows how to separate optimization and validation data and why the best result of the optimizer is rarely the most reliable.

Overfitting and robots sold on the internet

Many marketed robots display backtests of years without a single bad week. This perfection is, almost always, a sign of over-optimization or logic such as Martingale and Grid without a stop, which accumulate small gains to a huge loss. Before paying for a robot, verifiable real historical piece, explanation of logic and demo account testing. the differences between these logics are in robot strategies, and the most common blows in scams with cryptocurrencies.

Warning: An overoptimized robot does not fail slowly. As it has been set to avoid past losses, the first new situation often takes up the entire position size. Always have a stop, daily loss limit and risk management independent of the strategy.

Conclusion

Overfitting is not resolved with more optimization, but with less: fewer parameters, fewer attempts and more validation on new data. The right question in front of a backtest is not “how much did it win?”, but “how many versions were tested until it got here and how did it turn out in the data it didn't see?”. For the overview, see What is Algorithmic Trading?.

Informational content, not investment advice.

Frequently asked questions

What is overfitting in trading?

It is when a strategy or robot is adjusted so much to the history that it starts to capture the random noise of that period, and not a real pattern. The backtest is excellent, but the live performance collapses.

How do I know if my robot is over-optimized?

Common signs: Many parameters, a result that changes a lot with small changes in values, poor performance in the out-of-sample period and too perfect capital curve in history.

How to avoid overfitting?

Use few parameters, reserve out-of-sample data, walk-forward, test other assets and periods, include costs, and prefer stable parameter regions instead of the isolated peak.

Is optimizing parameters always bad?

No. Optimize is useful for understanding the sensitivity of the strategy. The problem is choosing the best result of hundreds of trials and treating it as a future expectation without validation on new data.

References

  1. Bailey, Borwein, Lopez of Prado and Zhu: Pseudo-Mathematics and Financial Charlatanism (SSRN, 2014)
  2. Wikipedia: Overfitting
  3. Wikipedia: Walk forward optimization
  4. Investopedia: Overfitting
  5. MetaTrader 5: Types of Optimization
  6. MetaTrader 5: Strategy Test (Forward Test)
  7. TradingView: Pine Script docs, Repainting
  • overfitting
  • overoptimization
  • backtest
  • walk-forward
  • out-of-sample
  • trading robot

This content is informative and is not an investment recommendation. found an error? Write to contato@boletimbitcoin.com.

Read also

Start in crypto today

Open your free account, deposit with PIX and access Spot, Futures, Copy Trading and Trading Robots in one app.

  • Easy deposits
  • Copy trading
  • Grid and DCA bots
  • All-in-one app
Advertising. Crypto involves risk, invest responsibly.
Create free account