Forge Fate
Quant & Data Research

Why shift(1) Is Not Enough: A Time Contract for Signals, Execution, and Labels

6 min read

Moving a signal back by one row does not by itself establish that a strategy avoids future information. First define which return interval each row stores, when a signal becomes available, and when its order is assumed to execute.

The same issue applies to training. A sample dated in the past cannot enter training if its outcome is still unresolved. Moving signals does not remove leakage from preprocessing statistics estimated over the entire dataset.

This article checks four timing rules with small synthetic examples:

  • Do earlier signals remain unchanged when future prices change?
  • Does a new position receive only returns earned after execution?
  • Are unfinished labels excluded from training?
  • Does fitted preprocessing remain unchanged when values outside the training window change?

The blog also publishes a baseline backtest using real ETF data. This article does not validate that entire implementation. Its purpose is to demonstrate timing contracts and tests in independent, small examples.

First define which row stores a return

Each row represents an observed trading day, assumed to be in chronological order with no missing trading days.

r[i] stores the return from the preceding row's close to the current row's close.

text
r[i] = price[i] / price[i - 1] - 1

Signals and execution follow this contract:

TimeAction
After the close at t becomes availableGenerate a signal using prices through t
Close at t+1Assume the corresponding weight change executes
Close at t+2Observe the first close-to-close return belonging to the new weight

A signal generated at t therefore first applies to r[t+2]. The return r[t+1] covers the interval ending at execution and belongs to the previous holdings.

Under these assumptions, the alignment is:

text
Weight applied to return row i = signal from row i-2

This does not mean every strategy requires shift(2). Alignment depends on whether returns are stored at the start or end of their intervals and whether execution occurs at the next open or close.

pandas shift moves values by a specified number of periods. A row shift does not determine exchange calendars or execution conditions. Shifting a date index with freq is a separate operation. pandas DataFrame.shift documentation

Check 1: Reverse the direction of a future price move

Use these prices:

text
Original prices: [100, 110, 105, 120]Modified prices: [100, 110, 105,   1]

The signal is 1 when the price exceeds the preceding observation and 0 otherwise. The first row is 0 because no preceding price exists.

The correct signals are:

text
Original signals: [0, 1, 0, 1]Modified signals: [0, 1, 0, 0]

Changing the final price may change the final signal, but the first three must remain identical.

Reversing the direction of the final move makes the test more discriminating than simply increasing its size. Changing the last price from 120 to 999, for example, leaves both above 105 and preserves the final upward signal.

The test also includes a faulty implementation that pulls the next row's signal into the current row. Changing the final price then changes an earlier signal, so this implementation must fail.

Check 2: Separate execution from return attribution

For signals [0, 1, 0, 1] and execution at the next observed trading day's close, the weights applied to return rows are:

RowSignal generated on this rowWeight applied to the return ending on this row
000
110
200
311

The buy signal on row 1 executes at the close of row 2. Its holdings first earn the return from row 2 to row 3.

A faulty one-row shift returns [0, 0, 1, 0], attributing returns one interval too early under this contract.

The test does more than compare a manually written incorrect array. It calls the faulty one-row-shift function and confirms that it fails the same expected-value check.

Empty and single-row inputs are tested too. Initial holdings are zero. Signals near the end are not assigned unobserved future returns.

Check 3: A past signal date does not guarantee a completed label

Set the training cutoff to 2025-01-06 and use these synthetic samples:

RowSignal dateLabel end dateLabelFeature
02025-01-012025-01-020100
12025-01-022025-01-031110
22025-01-032025-01-061120
32025-01-06UnresolvedUnresolved999

This example uses a conservative date-level rule:

text
Sample signal date < training cutoffLabel end date < training cutoffLabel value exists

Only rows 0 and 1 are eligible for training.

Row 2 has a label in the table because the dataset was assembled after its outcome became known. That does not establish that the label was available at the training cutoff. This example excludes labels ending on the same date.

Row 3 may be a prediction target, but without an outcome it cannot be a training sample.

Excluding all same-day labels is not a universal rule. Using them requires comparing the price-receipt timestamp with the actual training cutoff. Those timestamps are unavailable here, so the example uses a strict date boundary.

The faulty implementation changes < to <=. It selects row 2 as well and is detected as violating this example's contract.

Check 4: Actually fit preprocessing on the selected rows

Showing that two arrays have different means does not establish that a pipeline uses the correct rows. Connect the row-selection function to the fitted preprocessor.

This example uses a small mean-centering preprocessor with no external packages:

  • fit() stores the mean of the training values.
  • transform() subtracts the stored mean from its input.
  • It performs neither standard-deviation scaling nor model training.

The eligible features are [100, 110], giving a fitted mean of 105. Transforming 120 with that preprocessor gives 15.

Next, change only the two excluded rows substantially:

text
Row 2: 120 → 12000Row 3: 999 → 9999

Correct selection leaves the fitted mean at 105 and the transformation of the same input 120 at 15. A faulty preprocessor fitted on every row changes both its mean and its output.

Keep the transformation input 120 fixed. This distinguishes output changes caused by a different input from changes caused by contamination of the fitted state.

scikit-learn's leakage guidance also explains fitting preprocessing statistics only on training data and applying the same transformation afterward. This test concerns a custom mean-centering example; it is not a test of StandardScaler or a production model pipeline. scikit-learn common pitfalls

Complete runnable example

Save the following as timing_checks.py and run python3 timing_checks.py. It uses only the standard library. Do not use -O, which disables assert checks.

python
from datetime import datefrom statistics import fmeandef make_signal(prices):    if not prices:        return []    return [0] + [        int(b > a)        for a, b in zip(prices, prices[1:])    ]def held_weight(signals):    return [        0 if i < 2 else signals[i - 2]        for i in range(len(signals))    ]def training_indices(rows, cutoff):    return [        i for i, row in enumerate(rows)        if row["signal"] < cutoff        and row["end"] is not None        and row["end"] < cutoff        and row["label"] is not None    ]class MeanCenterer:    # 교육용 평균 중심화. 표준편차로 나누지는 않는다.    def fit(self, values):        if not values:            raise ValueError("학습 행이 없습니다")        self.mean_ = fmean(values)        return self    def transform(self, values):        return [value - self.mean_ for value in values]def fit_at(rows, cutoff):    indices = training_indices(rows, cutoff)    return MeanCenterer().fit([rows[i]["x"] for i in indices])D = date.fromisoformatCUTOFF = D("2025-01-06")ROWS = [    dict(        signal=D("2025-01-01"), end=D("2025-01-02"),        label=0, x=100,    ),    dict(        signal=D("2025-01-02"), end=D("2025-01-03"),        label=1, x=110,    ),    dict(        signal=D("2025-01-03"), end=D("2025-01-06"),        label=1, x=120,    ),    dict(        signal=D("2025-01-06"), end=None,        label=None, x=999,    ),]# 검사는 구현 함수를 인자로 받아 직접 실행한다.def check_signal(fn):    original = fn([100, 110, 105, 120])    changed = fn([100, 110, 105, 1])    assert original[:3] == changed[:3], \        "미래값이 과거 신호를 변경했습니다"    assert original == [0, 1, 0, 1]def check_execution(fn):    assert fn([0, 1, 0, 1]) == [0, 0, 0, 1], \        "수익 귀속이 너무 빠릅니다"    assert fn([]) == []    assert fn([1]) == [0]def check_training(fn):    assert fn(ROWS, CUTOFF) == [0, 1], \        "학습 경계를 넘는 행이 포함됐습니다"def check_preprocessing(fn):    changed = [dict(row) for row in ROWS]    changed[2]["x"] = 12000    changed[3]["x"] = 9999    before = fn(ROWS, CUTOFF)    after = fn(changed, CUTOFF)    assert before.mean_ == after.mean_, \        "학습창 밖 값이 적합 평균을 변경했습니다"    assert before.mean_ == 105    assert before.transform([120]) == after.transform([120]) == [15]    assert before.mean_ == 105, \        "변환 중 평균을 다시 적합했습니다"# 아래 네 함수는 검사의 검출 능력을 확인하기 위한 오류 구현이다.def bad_signal(prices):    return make_signal(prices)[1:] + [0]def bad_execution(signals):    return [        0 if i == 0 else signals[i - 1]        for i in range(len(signals))    ]def bad_training(rows, cutoff):    return [        i for i, row in enumerate(rows)        if row["signal"] < cutoff        and row["end"] is not None        and row["end"] <= cutoff        and row["label"] is not None    ]def bad_fit(rows, cutoff):    return MeanCenterer().fit([row["x"] for row in rows])CASES = [    ("signal", check_signal, make_signal, bad_signal),    ("execution", check_execution, held_weight, bad_execution),    ("training", check_training, training_indices, bad_training),    ("preprocessing", check_preprocessing, fit_at, bad_fit),]for name, check, correct, broken in CASES:    check(correct)    print(f"{name}: 정상 구현 PASS")    try:        check(broken)    except AssertionError as error:        print(f"{name}: 오류 구현 검출 — {error}")    else:        raise RuntimeError(f"{name}: 오류 구현을 놓쳤습니다")

The output checked with Python 3.14.5 while preparing the revision on October 22, 2026 was:

text
signal: 정상 구현 PASSsignal: 오류 구현 검출 — 미래값이 과거 신호를 변경했습니다execution: 정상 구현 PASSexecution: 오류 구현 검출 — 수익 귀속이 너무 빠릅니다training: 정상 구현 PASStraining: 오류 구현 검출 — 학습 경계를 넘는 행이 포함됐습니다preprocessing: 정상 구현 PASSpreprocessing: 오류 구현 검출 — 학습창 밖 값이 적합 평균을 변경했습니다

The Korean output labels mean “correct implementation PASS” and “faulty implementation detected.” The four errors respectively report future values changing past signals, returns attributed too early, training-boundary violations, and excluded values changing the fitted mean.

The four correct implementations passed their checks, and the four deliberately faulty implementations failed their corresponding checks. These are results from the newly written synthetic example, not a claim to have reproduced historical runs from the original article.

What these checks establish—and what remains open

The verified scope is the small functions and inputs visible in the code.

CheckedNot yet checked
Earlier signals remain unchanged after a future price changeLeakage across a complete indicator and data-merge pipeline
Return attribution follows the specified close-execution assumptionActual order availability, fills, and market impact
Training rows follow the date boundaryReal publication/receipt timestamps and revision histories
Mean-centering is fitted on selected rowsEvery preprocessing and training stage in a real model
Four faulty implementations are detectedEvery possible timing error

The example assumes adjacent rows represent consecutive observed trading days. Real data requires separate checks for the next trading day, missing trading-day observations, and market holidays.

For multiple ETFs, equal array lengths do not justify positional alignment. Align by asset and trading date, and check feature windows and data availability.

Applying this approach to a real runner requires testing the signal generation, return attribution, training-row selection, and preprocessing paths that the runner actually uses. Copying these example functions alone will not detect regressions in different production code.

An extension to the logistic-regression label and training-time design could start by inspecting selected rows and fitted preprocessing state at each retraining point.

Report an error or share feedback

Open a draft with this article’s title and URL. Review the message and recipient before sending.

To: [email protected]

Open email draft

If no email app opens, copy these details into your usual email service.

Contact information