AI & Machine Learning

Is Your Trading Model Seeing the Future?

Ionut Claudiu Fratila · Published Nov 29, 2026 · 8 min read · —
Machine LearningData Leakagescikit-learnpandasMetaTrader 5Validation
Candlestick chart on a monitor with the time axis visible

A machine learning model for trading is only as honest as the data it was trained and tested on. If one feature quietly uses a bar that had not yet closed, or data that had not yet been published, the evaluation will look better than anything the model can reproduce on new data. Nothing crashes and no error appears.

This is data leakage, or look-ahead bias, and it is something we check for when reviewing trading ML code, including code written by AI assistants. This article walks through where future data usually gets in, and the documented tools in Python, scikit-learn, pandas and MetaTrader 5 that keep it out.

What Leakage Means for Trading Data

scikit-learn defines data leakage as using information that would not be available at prediction time when building the model. It warns that this gives over-optimistic estimates, for example from cross-validation, and poorer behaviour on genuinely new data. Its general rule is never to call fit on the test data (scikit-learn, Common pitfalls: Data leakage).

For market data, that means only bars that had closed, and data that had been published, when the model would have run.

The Unfinished Bar

In MQL5, CopyRates counts bar positions from the present to the past, so start position 0 is the current bar. The array it fills still holds the oldest bar first unless it is set as a series with ArraySetAsSeries, as MetaQuotes’ own example does. MetaQuotes notes that requesting start_pos=0 with count=1 returns the current, uncompleted bar (MQL5 Reference, CopyRates). In the MetaTrader 5 Python package, copy_rates_from returns bars whose open time is less than or equal to the requested date, so the time on each bar is its open time, not its close (MQL5 Reference, copy_rates_from).

So a feature row stamped with a bar’s open time but built from its close uses information from the end of the bar. In our view, training rows should use closed bars only, and live inference should start from position 1, the last closed bar, rather than position 0. In MQL5 that is CopyRates(_Symbol, _Period, 1, count, rates). In Python it is copy_rates_from_pos(symbol, timeframe, 1, count), whose array runs oldest to newest, so the last closed bar is its last row (MQL5 Reference, copy_rates_from_pos). The exception is a model deliberately trained on intrabar data.

Rolling Windows and Shifted Labels

pandas makes rolling features easy, and its defaults matter. DataFrame.rolling labels each window at its right edge (center=False, meaning the result sits on the last row of the window) and by default uses closed=‘right’, meaning the current row is included in the window. Setting closed=‘left’ means the window stops just before the current row. Setting center=True places the result in the middle of the window, which means it uses later rows (pandas, DataFrame.rolling).

So by default a rolling feature always includes the row it sits on. That is only safe if that row’s bar has closed when the prediction is made. If rows are stamped at the bar’s open time, or the label describes that same bar, the feature includes the bar being predicted. A centred window always reaches forward. For a fixed window, rolling(n, closed=‘left’) gives the same values as rolling(n) followed by shift(1): both use only the n rows before the current one.

Labels usually come from DataFrame.shift, which moves data by a number of periods, positive or negative (pandas, DataFrame.shift). A label for “the next bar” uses a negative shift: shift(-1) pulls the following row’s value onto the current row, which is future data by design. A feature should only ever use a positive shift, such as shift(1) for the previous row’s value, or no shift at all. A simple review step is to list every shift in the feature code and check the sign.

Joining Data by Time

Many models combine bars with a slower dataset, such as a daily series or a higher timeframe. pandas.merge_asof joins on the nearest key rather than an exact match. Its default, direction=‘backward’, takes the last row on the right whose time is less than or equal to the row on the left. The ‘forward’ and ‘nearest’ options can take later rows. allow_exact_matches=False makes the match strictly earlier in a backward join, tolerance limits how old a match can be, and both sides must be sorted by the key (pandas, merge_asof).

Join on the time the data became available, not the period it describes, using a backward join. A ‘forward’ or ‘nearest’ join leaks by construction. A daily bar stamped 00:00, joined backward to a 10:00 row, pulls in today’s unfinished high, low and close.

Time zones are the quieter version of the same fault. MetaQuotes’ Python reference says MetaTrader 5 stores tick and bar open times ‘in UTC time zone (without the shift)’, and that Python datetimes passed to these functions should be created in UTC (copy_rates_from). In practice the stored values follow the broker’s trade-server clock: MetaQuotes notes that chart times correspond to server time (MQL5 Book, Local and server time). That clock can differ from UTC by a few hours, and the offset can change with daylight saving. Before joining MT5 bars with data in UTC, local or exchange time, convert both to one true UTC clock using the broker’s server offset. Otherwise one series can shift against the other by hours, which may place later information on earlier rows.

Preprocessing Fitted on Everything

Scaling and imputation look harmless, but they learn from the data they are fitted on. scikit-learn’s example is normalisation: the average used must be the training subset’s average, not the average of all the data. It names StandardScaler, SimpleImputer and PCA as transforms where this applies, and shows feature selection run on the full dataset producing a misleading result. The documented fix is to split first, use fit_transform on the training data and transform on the test data, or wrap the steps in a Pipeline, which applies the right method to the right subset during cross-validation and tuning (Common pitfalls).

The mirror-image fault is applying different preprocessing to later data, including in production, which changes the feature space the model sees (Common pitfalls: Inconsistent preprocessing). For a model deployed into MetaTrader 5, exporting the scaler with the pipeline, rather than rewriting it by hand in MQL5, removes one place for training and live code to drift apart.

Why Standard Cross-Validation Misleads

scikit-learn notes that KFold and ShuffleSplit assume samples are independent and identically distributed. Time-series data is not: nearby samples are correlated, so standard random splits, even without shuffling, give poor estimates of how a model generalises. It also warns that shuffling time-ordered data can produce an overfit model and an inflated validation score, because test samples end up artificially similar to training samples close in time. train_test_split returns a random split too (scikit-learn, Cross-validation).

TimeSeriesSplit exists because other methods “would lead to training on future data and evaluating on past data”. Each split trains on earlier folds and tests on the next one. max_train_size caps how much history each training set may use, and gap sets how many samples are left out between the end of each training set and the start of its test set (scikit-learn, TimeSeriesSplit). The gap counts samples (rows), not bars, which matters when bars are missing or symbols are stacked.

That gap is useful when a label looks ahead. If each label is built from the next N bars, the last N training labels overlap the test period. Setting gap to at least N removes that overlap. This is our engineering reading of the parameter; the documentation defines gap but does not discuss label horizons.

Tuning is the last leak. scikit-learn warns that adjusting hyperparameters until the test score is best lets knowledge of the test set leak into the model, and recommends a held-back final test set, with cross-validation used for tuning (Cross-validation). In practice, the most recent block of history should be used once, at the end. The run should also be repeatable: scikit-learn notes that the default random_state=None makes repeated fit and split calls differ, and advises passing an integer or seeded generator instead (Common pitfalls: Controlling randomness).

Limits and Caveats

Preventing leakage makes an evaluation honest. It does not make a model useful, and nothing here suggests that any model or strategy will work. We make no claims about how any model performs.

A clean time-series split is still one view of the past, not evidence of future behaviour. The history a terminal returns can change: MetaQuotes notes that CopyRates returns what is ready when it times out while downloading continues, and that available bars are limited by ‘Max. bars in chart’ (MQL5 Reference, CopyRates). So a training set is only as consistent as its source; record the server and the bar range used. The gap-and-label-horizon point is our inference, not scikit-learn’s wording. And this article covers Python, scikit-learn, pandas and MetaTrader 5 only; other ML libraries have their own splitters and defaults.

Conclusion

Is your trading model seeing the future? It is worth assuming it might be until each of these points has been checked: closed bars only, the sign of every shift, the direction and time key of every join, both sides converted to one true UTC clock, preprocessing fitted on training data inside a Pipeline, time-ordered validation with a gap, a final hold-out touched once, and fixed random seeds. None needs new software.

This is the groundwork behind our Machine Learning Models service, and the same checks form part of Strategy Optimisation & Testing and AI Code Rescue reviews. If you have a model pipeline you would like checked, you can tell us about it here.

Drafted with AI assistance; reviewed, edited and approved by Ionut Claudiu Fratila.