ValidationIntermediate24 min read

The gap that knew the future: cleaning data without anticipating answers

Detect future information in imputation, interpolation, windows and temporal joins before evaluating a robot or training a model.

At ten, an observation is missing. At eleven, a value of twelve arrives. The cleaning function reaches backward and places that twelve in the gap at ten. The missing-value warning disappears, the model accepts the matrix, and the backtest improves. What also disappears, although it is absent from the log, is the wait required to know the observation.

Future information does not enter only through a column called “tomorrow’s return.” It can travel inside a mean calculated over the whole sample, an interpolation, a centered indicator, or a revised version of a series. A transformation that is mathematically correct can be wrong for a historical decision.

Here we examine how to complete and transform data while respecting information available at each moment. All values, decisions, and numerical datasets are hypothetical educational examples. They do not represent Atlas results, model capabilities, or robot profitability. The initial context is Forex, but the problems concern the experiment’s temporal design.

Our main question will not be which method removes the most gaps. It will be which procedure we could actually have executed when the robot needed to decide. That distinction changes how imputers are fitted, which samples are retained, and how a pipeline is checked before its metrics are interpreted.

1. Every feature needs an availability date

A feature is admissible when every observation and operation needed to produce it was available under the decision’s contract. Its row date does not guarantee that condition. A statistic can be labelled with the day it describes while using observations published later; a moving average can appear in the current row while containing later values if its window is centered.

Think of a feature as a small recipe. Its ingredients are original observations; its utensils include learned parameters, cleaning rules, and calendars. Reconstructing a decision requires knowing which ingredients existed and which versions of those utensils were fixed. Looking only at the final output’s date leaves most of that dependency hidden.

Availability is inherited from the components. If a feature combines two observations and the second arrives later, it cannot be ready before that observation. If it also requires an imputation model that has not finished fitting, that time matters too. A simplified study may ignore small computation delays, but it should declare the simplification.

Suppose a signal at 10:00 requires a quotation known at 09:59 and an aggregate published at 10:02. The complete signal does not exist at ten. Delaying only the price column does not solve the aggregate’s problem. Sorting the rows correctly does not solve it either: a clean ordering can still contain values with incorrect availability.

A minimal feature record should identify its source, transformation, knowledge time, and missing-value policy. Add whether it can be revised and whether it depends on fitted parameters. This record lets you discuss a particular decision without having to infer its meaning from an abbreviated name such as “feature_17.”

The article on Forex data timestamps develops zones, intervals, and receipt times. Here we assume those clocks have been interpreted correctly so we can focus on what happens afterward: how a transformation can reintroduce future information even when the original observations were correctly timestamped.

2. Fitting a mean also learns from the dataset

An imputer replacing missing observations with a mean learns a parameter: that mean. However simple it is, it needs an authorized fitting set. If reserved evaluation observations participate in its calculation, part of the future distribution has already influenced how the past is represented and how the model is evaluated.

Scikit-learn recommends separating training and evaluation before learned preprocessing and fitting transformations only on the corresponding training set. Its guidance includes imputation among the operations requiring this precaution. scikit-learn, preventing preprocessing leakage.

Construct a training column containing 2, missing, and 4. The mean of its observed values is three. A later evaluation column contains 10 and 12. Calculating a global mean while ignoring the gap gives two plus four plus ten plus twelve, divided by four: seven. The missing row becomes three or seven depending on which information is permitted to influence the fit.

Now a hypothetical rule activates a condition when the value exceeds five. With replacement learned only from training, the row contains three and does not activate the condition. With global replacement, it contains seven and does. Choosing the fitting set has changed a decision without changing the rule. No complex network is needed to produce this leakage.

This does not mean three is a good estimate of the missing value. It means that estimate respects the established information boundary. Temporal validity and predictive quality are different questions. A causal imputation can be unhelpful; one using the future can appear highly accurate while being impossible to reproduce when an actual decision arrives.

When evaluating multiple temporal cutoffs, refit the imputer within each permitted training set. Do not reuse a mean calculated over the entire history merely because it is considered “cleaning.” The learned parameter belongs to the same procedure version as the model and should be recoverable alongside it.

The permitted mean of two and four is three; including evaluation values ten and twelve changes the replacement to seven.
A cleaning parameter can leak information without directly using the target label.

The problem returns during normalization. If the authorized training minimum and maximum are two and four, a scale subtracting the minimum and dividing by the range transforms four into one. Using the future maximum of twelve transforms that same four into two divided by ten, or zero point two. A threshold applied to the scaled feature can change even though the observed value is identical. Imputation and scaling are not minor exceptions around the model: they determine the representation the model receives.

A transformed future observation falling outside the training interval does not justify retroactively refitting the scale. It may indicate distribution change or simply a previously unseen value. Decide beforehand whether to preserve it, cap it using a fixed rule, or trigger review. Each choice has different consequences. Expanding the extremes using the entire evaluation and recalculating earlier decisions erases precisely the change that the system would have had to confront without advance knowledge.

3. Backward filling answers with the next observation

Imagine three equally spaced moments: at nine we observe eight, at ten the value is missing, and at eleven we observe twelve. Backward filling takes the next valid observation and uses it in an earlier gap. In this sequence, the row at ten becomes twelve, a value that had not yet arrived.

Pandas documents bfill as using the next valid observation. This is legitimate for some reconstruction tasks, but its definition does not guarantee that its outputs were known at each row’s time. pandas, backward filling.

A function’s processing direction is not a causal guarantee. An operation can iterate forward through a file while consulting later values; another can process complete batches and produce exactly the same output as a valid incremental implementation. What matters is which dependencies each output uses, rather than how its iteration is written.

In the example, a decision at ten cannot rely on twelve. A decision made after eleven might use a retrospective reconstruction if the task permits it and does not pretend that reconstruction existed earlier. Describing a historical gap for a report, for instance, is a different question from simulating a historical order.

The same table can describe the past and still be unsuitable for simulating it. Label cleaned products according to their purpose. A completed series used to visualize trends should not silently enter a robot’s feature set. When both activities share files, retain names and provenance that prevent confusion about permitted uses.

When you find backward filling in AI-generated code, neither reject it without context nor accept it because it removed errors. Ask which decisions will consume the output and at what time. Then construct a minimal sample with a gap before a large change. That test exposes whether the procedure anticipates information that did not yet exist.

4. Interpolation must explain which endpoints it knows

Interpolation looks less suspicious because it creates a smooth transition. In the sequence eight, missing, twelve, linear interpolation between equally spaced points assigns ten to the middle. The number does not directly copy the future, but it depends on it: if the final value were twenty, the middle would become fourteen.

Pandas distinguishes interpolation methods and their treatment of the index. An ordinary linear option and a time-based option do not necessarily mean the same thing with irregular intervals. The mathematical choice must match the axis you intend to represent. pandas, missing-value interpolation.

For a decision made at ten, the endpoint at eleven is still unknown. You cannot obtain the interpolated ten between eight and twelve using the same information available then. Calling it an “estimate” does not remove that dependency. An estimate usable in real time must be formulated from already known observations and accept the resulting error.

Now consider irregular times: eight at nine, a gap at a quarter past nine, and twelve at ten. Interpolation proportional to time assigns nine to the gap because one quarter of the interval has elapsed and the total change is four. Treating all three rows as equally spaced produces ten. Both calculations can be correctly executed; they answer different assumptions, and both need the future endpoint to reconstruct the gap.

Visual smoothness does not demonstrate availability. Indeed, a series completed with later information may look more stable precisely where observations were missing under difficult conditions. If that stability influences a volatility filter, the model may reject or accept trades because of a property created during reconstruction.

One alternative delays use until both endpoints are known and defines the feature as a retrospective reconstruction. Another uses a causal forecast for the missing value. Another preserves the absence and abstains. These are not equivalent substitutes; each changes the question, delay, and error risk that must be evaluated.

Eight and twelve allow interpolation of ten between them, but twelve is still future information for the middle decision.
An interpolation can be geometrically coherent and temporally inadmissible.

5. Carrying the last value avoids one future and creates another problem

Forward filling uses the last known observation. In our sequence, the gap at ten would receive eight. Assuming eight was available, this does not consult the future observation of twelve. However, it preserves an old value and may conceal that the system has gone some time without receiving new information.

Known does not mean recent, and recent does not mean executable. A slowly updated external indicator may reasonably persist for a specified period. A quotation used to simulate execution requires other conditions. Do not apply the same carry-forward policy to both columns merely because they are numeric.

Add observation age to its state. If the last observation arrived at 09:00 and the decision is at 09:20, its age is twenty minutes. If the permitted limit was fifteen, the observation is no longer admissible. At 09:10, its age would be ten minutes and it would pass that criterion. The limit should not be discovered retrospectively by selecting whichever version earns more; justify it from the feature’s use and evaluate it as part of the design.

A replacement needs an expiry policy. It may limit elapsed time, the number of missing observations, or continuity within a session. These restrictions are not equivalent when gaps are irregular. Three rows can represent three minutes or several hours. Choose the measure that answers the actual requirement.

Also decide what happens across a boundary: a new session, a provider change, a process restart, or a modification to the series definition. Carrying a value across these boundaries may preserve information that is no longer comparable. Validity depends on semantics, rather than only on the previous value being available.

In a report, distinguish original observations from carried values. You can analyze how many decisions use old information and whether their behavior changes with age. That review describes an operational dependence. It does not automatically turn an association between age and outcome into a predictive signal that can be incorporated without fresh evaluation.

6. A centered window can move the future into the present

Suppose five values become known successively: 2, 4, 6, 8, and 10. A trailing three-observation average calculated on the third row, including the already available current value, uses 2, 4, and 6: it equals four. A three-observation average centered on that row uses 4, 6, and 8: it equals six, but requires the fourth observation.

The pandas rolling documentation distinguishes centered labels and window rules. Understanding a particular call requires inspecting which observations enter it, rather than relying on the name “moving average.” pandas, rolling windows.

A statistic’s plotted location does not reveal when it can be calculated. A centered smoothed curve may help describe trends after the sample has been observed. Using it as a signal at its center date anticipates the future half of its window. Moving the drawing does not change its dependencies; moving its use time can, provided that use is defined correctly.

Even a trailing window requires checking the current observation. If the decision occurs before a candle closes, its final close cannot participate yet. If the decision occurs afterward and the close is available, it may be admissible. A universal recommendation to “always shift one row” is too vague: it depends on when the robot decides and what each row represents.

To audit a feature, write the exact rows used by one output. Mark which are available at that instant and which are previously learned parameters. This list removes ambiguity. It also reveals functions normalizing by the entire day’s maximum even when the decision takes place halfway through the morning and that maximum can still change.

Do not try to compensate for future dependence by changing the execution price or adding costs. These errors belong to different layers. A model can have very conservative commissions while still receiving impossible knowledge. First repair the information set; then interpret performance under an explicit execution model.

At the third row a trailing average uses two, four and six; a centered average uses four, six and future eight.
A window should be reviewed as a set of dependencies, not simply as a curve.

7. The nearest join can choose a later observation

Combining sources with different frequencies can leave gaps when dates must match exactly. A proximity join appears to solve them, but “nearest” does not mean “already known.” If the decision is at 10:00, an update at 10:01 is closer than one at 09:55; it still belongs to the future.

The merge_asof documentation distinguishes backward, forward, and nearest searches. Direction is part of the semantics and can be combined with tolerance and grouping. The function does not independently know which column represents availability for your strategy. pandas, temporal proximity joins.

In the example, a causal search by availability would select the 09:55 observation if it satisfies the age policy. With a three-minute tolerance, no observation is valid at ten: the previous one is five minutes old and the following one does not exist yet. The correct outcome is absence, rather than an obligation to find some neighbor.

A missing match also reveals information about the system. It may indicate that the source updates too slowly for the rule or that the tolerance is incompatible with the intended use. Removing that warning by selecting the nearest neighbor avoids confronting a real design limitation.

Also group by the appropriate identity before searching for matches. An earlier timestamp from another instrument or another series version is not a valid substitute merely because it is close. The join must respect both time and the object being described. Inspect examples containing multiple entities so that the test does not work only because it contains one simple column.

For exact ties, define event order. If publication and decision share a coarse-resolution timestamp, you may not know which happened first. Allowing equality needs justification consistent with the availability model. You can adopt an explicit delay or mark the case uncertain; rounding timestamps should not decide it accidentally.

8. A series’ final version may not have existed then

An economic observation may be revised after its initial publication. Downloading a historical series today can therefore provide values reflecting knowledge acquired after the decisions you want to simulate. Shifting the series by one day does not guarantee repair: the revision may have happened weeks or months later.

FRED distinguishes historical information available today from knowledge periods accessible through ALFRED. Its real-time-period documentation describes this version dimension. It helps explain the issue without guaranteeing that every variable has the temporal resolution your robot requires. Federal Reserve Bank of St. Louis, real-time periods.

Imagine a value referring to January, published as 1.2 in February and revised to 0.8 in March. A February decision might know 1.2 depending on its exact date, but cannot know the March revision. A current table retaining only 0.8 does not reconstruct that decision’s information. The described period, publication date, and version are separate dimensions.

Do not confuse correcting an observation with correcting the history of knowledge. A later version may better describe the economic phenomenon while being less suitable for reconstructing a historical decision. The task determines which view is needed. Preserving both with their provenance is better than declaring one universally correct for every use.

The same caution applies to provider corrections, classification changes, and reconstructed aggregates. They are not all economic revisions, but each can alter what appears today for a past date. If the material does not retain versions, acknowledge that limitation. Do not invent original availability that cannot be justified.

A version history does not automatically resolve intraday timing either. A publication date without an hour may be insufficient for a strategy trading minutes around an announcement. Match the conclusion to the available resolution. A daily study may permit an explicit conservative convention; an intraday study may require another dataset.

9. Missingness can be part of the phenomenon

Gaps are not interchangeable accidents. A feature may be missing because it requires more history, because a source was disconnected, because a condition makes it inapplicable, or because the provider stopped publishing it. Replacing every case with the same mean erases distinctions that can affect both the model and interpretation of its result.

First classify the absence. “There are not yet enough observations for a twenty-period average” differs from “three rows were lost during an interruption.” The first may call for a warm-up period. The second may require restricting use until continuity is restored. The appropriate action depends on meaning and the experiment’s rules.

A missingness indicator preserves some context behind a replacement. You can record whether a value was observed or imputed, its age, and the known reason for its absence. This does not guarantee that a model learns a stable relationship; it at least avoids presenting a substituted number as though it were an original observation.

SimpleImputer documentation includes replacement strategies and an option to add missing-value indicators. The tool handles particular operations; choosing a valid meaning for each gap remains the researcher’s decision. scikit-learn, SimpleImputer.

Be careful about accidentally learning the infrastructure. If every training absence belongs to a provider-failure episode and that episode coincides with a particular outcome, the model may use missingness as an indirect label for the episode. An operational relationship may exist, but its persistence after changing sources or removing the interruption has not been established.

Evaluate decisions with original, imputed, and excessively old observations separately. Also report abstentions and excluded opportunities. An apparently better result may come from removing the most difficult contexts rather than estimating missing values more accurately. That distinction matters when judging what behavior the complete procedure could deliver.

A record retains the original value, used value, method, age and permission to decide.
The final number needs provenance for the decision to be auditable.

10. A complex imputer remains subject to the same clock

Replacing a mean with nearest neighbors, a regression, or a more complex model does not remove the temporal boundary. The replacement may now depend on other features, learned parameters, and selection decisions. Each must respect authorized training and the availability of the row being completed.

Suppose you estimate a missing feature using two other columns. If one contains the next trade’s outcome, the imputer directly incorporates a future answer even if the final model never receives that column. If it uses a statistic calculated over the whole sample, the dependency is indirect. Examine the observation’s complete journey, rather than only the final estimator’s inputs.

A pipeline organizes the procedure; it does not automatically prove causality. It can help keep fitting and transformation together, but it cannot know whether a column was built with future information before entering. Nor does it correct an incorrectly defined validation calendar. Both layers are needed: fitting boundaries and temporally admissible features.

Also decide how to handle columns that are completely absent in a training set. A mean does not exist without valid observations. The behavior may be to reject the feature, use a previously defined constant, or abstain when the feature is required. Do not let a technically convenient solution silently change the feature set between training and evaluation.

When comparing imputation methods, include operational cost: required features, delay, stability under change, and the ability to explain why a replacement occurred. A method improving a retrospective metric while requiring an unavailable source is not an executable alternative under the same contract. The comparison must keep that condition explicit.

Finally, separate evaluation of imputation error from evaluation of the robot. You can hide known values to measure reconstruction quality, but that artificial missingness pattern may not represent real gaps. Reconstructing numbers with lower error does not guarantee better economic decisions either. These are related tests with different objectives and their own limitations.

11. The altered-future test

A powerful check runs the transformation on a temporal prefix and compares that prefix with the same segment after future observations are appended. For a causal feature with initial state and parameters fixed in the same way, adding future information should not change earlier outputs. If they change, there is a dependency to investigate.

In the interpolation example, first process eight and a gap. Then append twelve. If the value assigned to the earlier gap changes to ten, that output depended on knowing the later endpoint. This may be correct for retrospective reconstruction, but invalidates treating it as information already available at the earlier decision.

Future invariance tests dependency; it does not guarantee complete validity. A system can pass while using a revised input column that already contains future information at its source. It can also legitimately fail if you compare models refitted on different datasets. Hold fixed the state and parameters whose causality you intend to examine so the test answers a precise question.

Another variant deliberately replaces later values with extreme quantities and checks whether earlier signals change. This exposes global means, scaling using complete-sample extremes, and joins selecting future neighbors. Thousands of trades are unnecessary: a small sample designed around the boundary can be more revealing.

Include a positive control: a deliberately noncausal transformation that the test should detect. Also include a simple causal transformation whose output should remain unchanged. If both pass or both fail for unrelated reasons, the testing procedure needs revision. An alarm unable to distinguish cases contributes little information.

Complement this check with traces of a few decisions. For every used value, record the original observation, method, parameters, and availability date. Invariance looks for a global property; a trace explains a particular decision. Together, they locate problems without relying exclusively on a suspiciously good performance metric.

Appending or modifying future observations should not change earlier causal features when parameters and initial state are fixed.
The control compares past outputs; it distinguishes refitting a model from transforming with a fixed one.

You can finish the audit with a pocket-sized decision. Fix its time at ten, a missing feature, and a training mean of three already calculated earlier. The latest valid external observation is eight and arrived at 09:50; the tolerance is fifteen minutes. A revision published at 10:05 has value twelve. The permitted procedure uses three as its learned replacement and eight as still-valid external information. It neither uses twelve nor recalculates the mean with it.

Then move only the decision clock to 10:10 while preserving the absence of new observations from the source that published eight. That value is now twenty minutes old and expires. The other feature’s revision can be known, but it does not rejuvenate the old external observation. This example requires separate states for each feature: a single “row updated” label is insufficient when columns come from different sources and calendars.

Finally, change the future revision from twelve to one hundred and repeat the original decision at ten. Its inputs must remain unchanged. If they change, find the transformation or join that allowed the revision across the boundary. You have built a small test with an unambiguous answer and a causal explanation, without yet needing to measure any profitability. The same trace can become a permanent regression case when the cleaning procedure is modified later.

12. A missing-value policy can also decide not to trade

Cleaning should not aim to put a number in every cell at any price. It should produce information whose meaning and availability match the rule. Sometimes this permits imputation; sometimes it requires waiting, reducing the feature set, or abstaining. Each response is part of the behavior being evaluated.

Write a short policy before comparing results: which gaps are admissible, which method serves each feature, which data fit it, when a value expires, and what happens when a valid input cannot be produced. Preserve an explicit reason for every abstention. This distinguishes “the signal did not activate” from “the system lacked enough information to evaluate the signal.”

The opportunity set must survive cleaning. Retain a record of intended decisions even when some never reach the model. Keeping only complete rows can erase the measure of how long the procedure remains unable to operate. That operational availability matters when interpreting any subsequent result.

In TradeAndRoll, the initial scope is Forex and market CSV data belong exclusively to the demo. Reviewing that material alongside rules and source code enables these checks; it does not imply that every external feature, revision history, or platform is included. Verify the particular rule’s information requirements and distinguish delivered material from anything that would need to be obtained separately.

The natural continuation is to examine walk-forward retraining: the imputer, scaling, and model must remain coherent with each fitting date. Cleaning calculated once over the complete history can undermine a temporal evaluation that appears to separate its training sets carefully.

When a backtest improves after filling gaps, the first question is not whether you discovered a superior technique. Ask what new information each decision received and where it came from. Answering with examples, traces, and verifiable limits provides a stronger basis for evaluating the model. If the gap knows the future, the table is more complete, but the investigation is not.

A missing observation in the present cannot be filled using an observation that arrives later.
Completing a table and reconstructing available information are different tasks.
Back to the Blog