Curve Fitting and Over-Optimisation in Expert Advisors
Curve fitting, or over-optimisation, is when an expert advisor's inputs are tuned so closely to historical data that the backtest captures random noise rather than a repeatable market behaviour. The tell-tale sign is a superb backtest followed by poor or negative live results. You cannot eliminate the risk entirely, but you can reduce it sharply by using few parameters, demanding many trades, preferring stable parameter regions over single peaks, and judging every system on data it was never optimised on.
Key takeaways
- Every optimisation run is a search; the more combinations you test, the better the best one looks by pure chance.
- Robust settings sit on broad plateaus where neighbouring values also work; fitted settings are isolated spikes.
- Reserve out-of-sample data before you start and touch it once. Re-optimising after peeking turns it into in-sample data.
- Rules of thumb: few free parameters, hundreds of trades, logic you can explain in a sentence, and results that hold on related pairs.
- Passing these checks lowers the odds of fooling yourself; it does not prove a future edge.
What curve fitting actually is
Price data contains two things: whatever structure genuinely repeats (perhaps a tendency for trends to persist on certain timeframes, or for ranges to hold in quiet sessions) and a much larger amount of randomness. A trading rule with adjustable inputs can be bent to fit both. When you optimise, the tester cannot tell which part of the profit came from structure and which from luck in that specific sample. It simply rewards whatever settings produced the best number.
A simple analogy: give a dartboard to 8,000 people blindfolded and one of them will hit the bullseye several times. Picking that person and backing them next round is curve fitting. The skill you think you selected was never there.
In MetaTrader the process looks innocent. You load an EA with a moving average period, an RSI threshold, a stop loss, a take profit, a trading-hours filter and a day-of-week filter, tick "Optimisation", and let the genetic algorithm find the best result. The report shows a profit factor of 2.4 and a smooth curve. None of that tells you how much was luck.
Why the best backtest is usually lucky: the multiple testing problem
This is the concept most retail EA developers skip, and it explains why so many optimised systems fail.
Suppose an EA has three inputs, each tested across 20 values. That is 20 x 20 x 20 = 8,000 combinations. Imagine, for the sake of argument, that the strategy has no edge at all, so each combination's true risk-adjusted return is zero and its backtest result is pure noise. Over two years of data, the random variation in an annualised Sharpe ratio is roughly 1 divided by the square root of the number of years, about 0.7. The best of many independent noisy results tends to land around the square root of (2 x ln N) standard deviations above zero. For N = 8,000 that is about 4.2, so the luckiest combination would show a Sharpe of roughly 4.2 x 0.7, or about 3.
A Sharpe ratio of 3 looks like an exceptional strategy. In this thought experiment it is a random number generator. In practice combinations are correlated, so the effective number of independent tests is smaller and the inflation less extreme, but the principle stands: the reported best result is biased upwards by the search itself, and the bias grows with every extra parameter, value and re-run.
| Combinations tested (independent) | Approximate "best by luck" in standard deviations | Implied luck Sharpe on 2 years of data |
|---|---|---|
| 10 | 2.1 | about 1.5 |
| 100 | 3.0 | about 2.1 |
| 1,000 | 3.7 | about 2.6 |
| 8,000 | 4.2 | about 3.0 |
| 100,000 | 4.8 | about 3.4 |
These are rough approximations meant to show scale, not precise statistics. Two practical lessons follow. Keep a log of how many variations you actually tried, including the ones you abandoned. And treat the optimiser's top result as the most likely to disappoint.
Degrees of freedom: count your knobs
Every input you optimise, every filter you add after seeing a losing period, and every rule like "skip Fridays" is a degree of freedom. Each one gives the system more ability to bend around the past. A useful sanity ratio is trades per free parameter. Practitioners differ on exact thresholds, but a system with 6 optimised parameters and 120 trades has about 20 trades per parameter, which is thin. The same system with 900 trades over many years is much more convincing.
Hidden degrees of freedom count too:
- Choosing the pair because it backtested best out of the 28 majors and crosses.
- Choosing the timeframe after testing several.
- Choosing the start date of the test to avoid a bad year.
- Adding an exception after seeing one big loss ("don't trade during the 2020 crash").
- Re-running the optimisation after changing the code, again and again.
None of these show up in the tester's input list, yet each is a selection made with knowledge of the result.
Plateaus versus peaks: reading the optimisation surface
MetaTrader 5 can display optimisation results as a 2D heat map or 3D surface for any two inputs. This is one of the most useful anti-overfitting tools available, and it is free.
A robust setting sits in a broad region where neighbouring values produce similar results: if a 50-period average works, 45 and 55 also work, if slightly less well. A fitted setting is a narrow spike: 50 is excellent, 48 and 52 lose money. Real market behaviour does not know about the exact number 50, so a sharp peak is almost always noise.
| What you see | Likely interpretation | What to do |
|---|---|---|
| Wide plateau of positive results across many values | Possible genuine effect | Pick a value from the middle of the plateau, not its highest point |
| Single bright cell surrounded by losses | Fitted noise | Reject; do not "zoom in" around it |
| Positive only in a thin diagonal stripe | Two inputs compensating each other; really one degree of freedom | Fix one input and re-examine |
| Positive across almost everything | Either a strong effect or a bug (look-ahead, unrealistic costs) | Check the code and the cost model before celebrating |
The last row matters. Results that are good everywhere often mean the EA accidentally reads future data (for example, using the current bar's close to decide an entry at the current bar's open) or the test is using a zero spread. Our walkthrough of how to backtest an EA in MT5 covers settings that prevent the most common look-ahead and cost errors.
Out-of-sample testing done properly
The basic defence is to split your data. Optimise on one portion (in-sample), then run the chosen settings unchanged on a portion the optimiser never saw (out-of-sample). MetaTrader 5's tester has a "Forward" option that does this automatically, reserving a half, third, quarter or custom date range for the forward test.
The rule that makes it work: you may look at the out-of-sample result once. If you dislike it, go back, change the system, and test again on the same out-of-sample data, then that data has become part of your optimisation. After several rounds you have simply curve fitted to the whole dataset with extra steps. Serious developers keep a final holdout period they do not touch until the very end, and they accept the verdict.
How much degradation is normal?
Some decline from in-sample to out-of-sample is expected, because the in-sample figure is inflated by selection. A drop from a profit factor of 1.8 to 1.4 is not alarming. A drop from 1.8 to 1.0 or below suggests the in-sample result was mostly fit. Compare like with like: trades per month, average trade, maximum drawdown and win rate should all be in the same neighbourhood. A system that trades three times as often out-of-sample is behaving differently, whatever its profit.
A single split is still one sample. Walk-forward testing repeats the optimise-then-test cycle across many rolling windows, which gives a much better picture of how the process, not just one parameter set, performs on unseen data.
Data and cost quality: fitting to artefacts
An EA can also be fitted to flaws in the data rather than to market noise. Typical examples:
- Interpolated ticks. MT4's default backtest generates artificial ticks from one-minute bars. Strategies with tight stops and targets inside a single bar can show fills that never existed. Tick-based testing, discussed in our page on 99.9% tick data backtesting in MT4, reduces this.
- Fixed spreads. Testing with a constant 0.5 pip spread lets an EA learn to trade at rollover, when real spreads can be many times wider.
- Gaps and missing data. Holes in history can make stops appear to fill at impossible prices.
- Broker-specific feeds. Each broker's history is slightly different. A system that only works on one broker's data is probably exploiting quirks of that feed.
If you need better history, our guide on where to download historical tick data compares the main sources and their limitations.
A practical robustness routine
Here is a sequence many systematic traders follow, adapted for MetaTrader users. It will not find an edge for you, but it will kill most false ones before they cost money.
- Write the hypothesis first. One sentence on why the edge should exist, for example "breakouts of the Asian range on GBP/USD tend to continue during the London open". If you cannot write it, you are data mining.
- Limit parameters. Aim for three or fewer optimised inputs. Fix the rest at sensible round values.
- Use coarse steps. Test moving average lengths of 20, 30, 40 and 50, not every integer. Coarse grids reduce the number of tests and the luck inflation.
- Model costs pessimistically. Use real or slightly wider spreads, include commission, and add slippage.
- Choose from the plateau. Pick the middle of a stable region, never the single top result.
- Test out-of-sample once, then walk-forward across several windows.
- Cross-validate on related markets. If a trend rule works on EUR/USD it should at least not collapse on GBP/USD or AUD/USD. Identical performance is not required; total failure is a warning.
- Perturb everything. Shift each input by 10% to 20%, delay entries by one bar, add a pip of cost. Robust systems degrade gracefully.
- Stress the equity curve with Monte Carlo simulation to see the range of drawdowns the trade sequence could have produced.
- Forward test on demo or small size for months before scaling.
Tools that help
MetaTrader 5's built-in tester covers optimisation, forward splits and heat maps. Dedicated platforms add features such as walk-forward matrices, Monte Carlo and parameter-stability reports; our comparison of forex backtesting software lists what each offers. Spreadsheet or Python analysis of exported trade lists is often enough for the perturbation and Monte Carlo steps. The tool matters less than the discipline: a clear hypothesis, limited searching, honest bookkeeping of what you tried, and willingness to discard a system you like.
Frequently asked questions
What is the difference between optimisation and curve fitting?
Optimisation is the process of searching for good input values. Curve fitting is the outcome when that search tunes the system to noise in the historical sample. Light optimisation over few parameters with coarse steps and many trades can be reasonable; heavy optimisation over many parameters almost always produces curve-fitted results that fail on new data.
How many parameters is too many for an EA?
There is no universal cut-off, but many systematic traders aim for three or fewer optimised inputs and want hundreds of trades in the test. The more parameters you add, the more trades you need to trust the result. Filters added after seeing specific losses count as parameters even if they are not inputs.
How much out-of-sample data do I need?
Enough to contain a meaningful number of trades and ideally a change in market conditions. Common splits reserve 25% to 33% of the history. A forward period with only 20 trades is too small to say much. Walk-forward testing across several windows gives a better answer than one large split.
Can a curve-fitted EA still make money?
For a while, by chance, yes. A fitted system can have a good run live simply because noise happens to cooperate. That makes it more dangerous, because early success encourages larger size just before performance reverts. Judge an EA on the robustness of its process, not on a few good live weeks.
Does the MT5 genetic algorithm cause overfitting?
The genetic algorithm itself is just a faster way to search large parameter spaces. It does not cause overfitting, but it makes it easier to test hundreds of thousands of combinations, which increases the luck inflation in the best result. Use it to explore, then validate with out-of-sample, walk-forward and perturbation tests.
Is a high profit factor in a backtest a red flag?
Not by itself, but very high values with few trades often signal fitting, look-ahead bias or unrealistic costs. Check the number of trades, the stability of nearby parameter values, and whether results survive realistic spreads, commission and slippage. A modest, stable profit factor across many trades is more credible than a spectacular one from a small sample.
This article is general information, not personal financial advice. Figures such as spreads, fees, leverage and rules change; confirm them with the provider and check the provider is authorised for your country of residence.