What Makes a Good Backtest Different? Design Validation Before Looking at Returns
Finding a high number in a backtest table differs from establishing why it deserves trust. Training data, configuration selection, and evaluation dates determine what a score means. Even the same model can receive scores that answer different questions.
This article splits a small artificial time series randomly and chronologically, examining both executed accuracy results and the composition of each split. It demonstrates classification-model evaluation, not a complete backtest with real prices, trades, costs, and portfolio returns.
What should be specified before seeing results?
If the question is whether information available in the past predicts the next period, evaluation should reproduce that situation.
| Item | Record |
|---|---|
| Target | What is predicted, and over which horizon? |
| Availability | When are features and training labels available? |
| Baseline | Which simple prediction or strategy is the comparator? |
| Splits | Which periods serve training, validation, and final evaluation? |
| Selection | Which metric selects candidates? |
| Search scope | How many feature, model, and configuration alternatives will be explored? |
| Changes | What changed after inspecting results? |
This does not prohibit exploration. An idea inspired by results can be recorded as new exploration; do not present it as an original hypothesis.
Match the baseline to the question. Direction-classification accuracy requires a simple classifier; trading performance requires a baseline strategy with the same assets, dates, and accounting.
Training, validation, and final testing have different roles
| Partition | Purpose |
|---|---|
| Training | Fit coefficients and preprocessing statistics |
| Validation | Select features, model settings, and window lengths |
| Final test | Evaluate the selected method |
Changing settings after inspecting a test score makes that partition part of selection. Information can enter through human decisions even when code never directly fits on test rows. Google's dataset-splitting guidance
For temporal prediction, train on information available before each evaluation point. Earlier dates alone are insufficient: unfinished labels and later releases need separate exclusion.
Fit preprocessing inside training partitions too. Estimating means or standard deviations before splitting can leak evaluation information. A Pipeline does not relieve you of choosing which rows enter fit. scikit-learn leakage guidance
The exercise below compares one fixed model under two splits, not an entire candidate-selection process. It therefore has no separate validation partition. Selecting a model from these results would not leave the same evaluation data an independent final test.
Synthetic data whose relationship changes partway through
Instead of real prices, generate a feature and binary outcome:
- Random seed:
42. - Generate 600 values each for
xand noise. - The feature at
tis the preceding value,x[t-1]. - Multiply the feature by
+0.9in the earlier regime and-0.4in the later regime. - Add noise; assign target 1 if the result is positive, otherwise 0.
Earlier regime: score[t] = 0.9 × x[t-1] + noise[t]Later regime: score[t] = -0.4 × x[t-1] + noise[t]target[t] = 1 if score[t] is positive, otherwise 0The change occurs at t=400. Excluding the first point without a preceding value leaves 599 samples, t=1~599.
This regime change is deliberately built into the example, not discovered in a market. regime describes split composition and is not a model feature.
Fix the model to a Pipeline combining standardization and logistic regression.
| Split | Training | Evaluation |
|---|---|---|
| Random | 80% after shuffling all samples | Remaining 20% |
| Chronological | Earliest 80% | Final 20% |
Both have 479 training and 120 evaluation rows, but different dates and regime mixtures.
Runnable code
The code retains the original data-generation conditions, preserves the original t, and prints partition composition and a simple baseline.
The baseline always predicts the majority class in training. It does not choose that class from evaluation outcomes.
import platformimport numpy as npimport pandas as pdimport scipyimport sklearnfrom sklearn.linear_model import LogisticRegressionfrom sklearn.metrics import accuracy_scorefrom sklearn.pipeline import make_pipelinefrom sklearn.preprocessing import StandardScalerrng = np.random.default_rng(42)n = 600x = rng.normal(size=n)noise = rng.normal(scale=0.8, size=n)# t=0은 직전 특징이 없으므로 제외한다.t = np.arange(1, n)coefficient = np.where(t < 400, 0.9, -0.4)score = coefficient * x[:-1] + noise[1:]df = pd.DataFrame({ "t": t, "lag1": x[:-1], "target": (score > 0).astype(int), "regime": np.where(t < 400, "early", "late"),})X = df[["lag1"]]y = df["target"]cut = int(len(df) * 0.8)shuffled = rng.permutation(len(df))splits = { "random": (shuffled[:cut], shuffled[cut:]), "time": ( np.arange(cut), np.arange(cut, len(df)), ),}print("versions:", { "python": platform.python_version(), "numpy": np.__version__, "pandas": pd.__version__, "scipy": scipy.__version__, "scikit-learn": sklearn.__version__,})for name, (train, test) in splits.items(): model = make_pipeline( StandardScaler(), LogisticRegression( C=1.0, solver="lbfgs", max_iter=1000, ), ) model.fit(X.iloc[train], y.iloc[train]) prediction = model.predict(X.iloc[test]) # 학습 자료의 다수 클래스. 동률이면 0을 선택한다. majority = int(y.iloc[train].mean() > 0.5) baseline = np.full(len(test), majority) print(f"\n{name}") for role, rows in [("train", train), ("test", test)]: part = df.iloc[rows] print(role, { "n": len(part), "t_min": int(part["t"].min()), "t_max": int(part["t"].max()), "early": int((part["regime"] == "early").sum()), "late": int((part["regime"] == "late").sum()), }) print( "model_accuracy:", f"{accuracy_score(y.iloc[test], prediction):.4f}", ) print("majority_class:", majority) print( "baseline_accuracy:", f"{accuracy_score(y.iloc[test], baseline):.4f}", )NumPy, pandas, SciPy, and scikit-learn are required. The checked environment was:
Python 3.12.14NumPy 2.5.4pandas 3.1.0SciPy 1.18.1scikit-learn 1.9.1Execution results: Inspect composition before accuracy
These results were obtained while preparing the revision on October 24, 2026. They do not reconstruct the original article's historical run. Neither the seed nor generation coefficients were changed after inspecting scores.
| Split | Partition | Rows | Time range | Earlier regime | Later regime |
|---|---|---|---|---|---|
| Random | Training | 479 | Scattered across 1–599 | 315 | 164 |
| Random | Evaluation | 120 | Scattered across 5–597 | 84 | 36 |
| Chronological | Training | 479 | 1–479 | 399 | 80 |
| Chronological | Evaluation | 120 | 480–599 | 0 | 120 |
Both training partitions had majority class 0.
| Evaluation measure | Random split | Chronological split |
|---|---|---|
| Logistic-regression accuracy | 60.83% | 30.83% |
| Training-majority baseline accuracy | 53.33% | 57.50% |
First, the models solve different evaluation sets. The random evaluation mixes 84 earlier-regime and 36 later-regime rows; the chronological evaluation consists entirely of 120 later-regime rows.
Second, chronological training already includes some later-regime data. It ends at t=479, including 80 post-change samples. Saying it never saw the changed relationship would be incorrect.
Third, random training contains observations later than some evaluation points. It does not reproduce forecasting from information available at each past time, regardless of whether its accuracy is higher.
Fourth, the chronological model underperforms the simple baseline here. The comparison is 30.83% versus 57.50% for these synthetic inputs and fixed settings, not a general verdict against logistic regression.
Why the 30-percentage-point gap is not a measured leakage effect
The accuracy gap is 30 percentage points, but it cannot all be attributed to future-data exposure. Changing the split also changes:
- Training dates and regime proportions.
- Evaluation dates and regime proportions.
- Fitted preprocessing statistics and coefficients.
This is not a controlled experiment isolating each factor's contribution. Both models fit preprocessing only on their own training sets, so full-dataset standardization is not an explanation for this result.
Nor does it establish that random splits always score higher. This is one deliberately changing synthetic sample, not a study across other seeds and generation conditions.
The question is which evaluation reproduces the intended research situation, not which produces the highest score. Forecasting later observations from past data requires preserving order and availability. scikit-learn TimeSeriesSplit
Accuracy is not return. The code has no weights, execution timing, costs, or profit calculation, so it cannot establish which method earned more money.
What comes after one chronological split?
This example trains once and evaluates the final interval. A walk-forward extension would repeatedly train on preceding observations and evaluate the next interval:
Train on past data → evaluate the next intervalMove the evaluation origin forwardTrain on the then-available past → evaluate the next intervalAggregate the evaluation errorsEvery training set must precede its corresponding evaluation. Moving the forecast origin and collecting errors is the basic time-series cross-validation structure. Forecasting: Principles and Practice
| Window | Training data |
|---|---|
| Expanding | Keep the start fixed and accumulate history |
| Rolling | Retain a fixed-length recent history |
This example does not establish which is better. Window type and length are selection decisions; record alternatives tried. For financial labels spanning multiple periods, inspect labels crossing boundaries. Leaving a few empty rows between splits does not by itself resolve availability problems.
Retain the history of changes made after seeing tests
Repeatedly selecting settings on the same data and retaining only the best output obscures the selection process. Backtest-overfitting research examines the effects of searching and choosing among many candidates. Bailey et al., The Probability of Backtest Overfitting
A final test can reveal a need for changes. Preserve the earlier record and document:
Previously evaluated method and resultInformation learned from that resultWhat changed and whyWhich data informed the changeWhat remains available for additional evaluationWithout new data, report the result as exploration using the existing evaluation period. Renaming it a final test does not restore independence.
The same applies when using the series' already published real ETF baseline period for later model comparisons: disclose what has already been inspected.
This exercise establishes partition composition and classification accuracy. Evaluating an actual strategy also needs execution, holdings, cost accounting, and risk metrics. The next article, Loss Paths and Trading Costs, addresses that layer.
Report an error or share feedback
Open a draft with this article’s title and URL. Review the message and recipient before sending.
Open email draftIf no email app opens, copy these details into your usual email service.
Related posts
Quant & Data Research Designing a Logistic Regression Comparison: Timing, Evaluation, and Failure Handling
A design for comparing logistic regression with a baseline: timing, common evaluation periods, costs, and failure handling, distinguished from actual model results.
Quant & Data Research Do Transaction Costs Change the Conclusion? Accounting for Entry, Full Replacement, and Liquidation
Account for purchase budgets and costs at entry, full replacement, and liquidation; check costs, turnover, and cash constraints in a synthetic ledger.