Objective
Most look-ahead bugs are not exotic: they are two series joined on the wrong clock. By the end you should be able to store and convert timestamps safely, align data from markets with different hours and holidays, distinguish when something happened from when you could have known it, and write an as-of join that never peeks.
Store in UTC, display in local time
Every timestamp should be time-zone aware and stored in UTC. Local exchange time is a presentation choice. Naive timestamps ("2024-03-12 16:00", no zone) are the root of most bugs, because the same string means different instants in New York and London, and the offset between them changes during the year.
Daylight saving does not start on the same day everywhere. The US moves clocks forward on the second Sunday of March, the UK and EU on the last Sunday of March; in autumn the UK and EU move back on the last Sunday of October, the US on the first Sunday of November. For two to three weeks in each season the New York–London gap is four hours instead of five. Japan does not observe daylight saving at all.
import pandas as pd
for d in ["2024-03-04", "2024-03-12", "2024-04-02"]:
ny_close = pd.Timestamp(f"{d} 16:00", tz="America/New_York")
ldn_close = pd.Timestamp(f"{d} 16:30", tz="Europe/London")
print(d, "NY close in London:", ny_close.tz_convert("Europe/London").strftime("%H:%M"),
"| London close in UTC:", ldn_close.tz_convert("UTC").strftime("%H:%M"),
"| gap (h):", (ny_close - ldn_close) / pd.Timedelta("1h"))
2024-03-04 NY close in London: 21:00 | London close in UTC: 16:30 | gap (h): 4.5
2024-03-12 NY close in London: 20:00 | London close in UTC: 16:30 | gap (h): 3.5
2024-04-02 NY close in London: 21:00 | London close in UTC: 15:30 | gap (h): 4.5
A strategy that "trades US stocks at 21:00 London time" would trade an hour after the close for three weeks of 2024. A strategy hard-coded to read the London close at 16:30 UTC would read a price an hour late for seven months.
Exchange calendars
Each exchange has its own holidays, half days (US equities close at 13:00 on the day after Thanksgiving and usually on Christmas Eve) and occasional unscheduled closures. Consequences:
- Do not align on a union of dates and forward-fill silently. If London is closed and New York is open, a forward-filled London price produces a zero return today and a two-day return tomorrow. That is the stale-price problem from lesson 1, created by you.
- Count horizons in trading days of the instrument, not calendar days, and be explicit when you mix them.
- Use a maintained calendar (an exchange-calendar library or the vendor's) rather than a weekday rule; holidays change (Juneteenth became a US market holiday in 2022).
Event time and publication time
Every data point has at least two times:
- Event time: when the thing happened or the period it describes (quarter ended 31 March; the trade executed at 15:59:59.9).
- Publication (knowledge) time: when it became available to you (earnings released 25 April at 16:05 New York time; the trade was reported 30 ms later; the vendor loaded it at 02:00 the next morning).
A backtest must key on the time you could have used it. A daily database that stamps an after-close earnings release with the release date makes it look tradable at that day's close, which it was not. Macro releases have both a reference period and a release time, and many are revised later (lesson 4).
Worked example
close-to-close across time zones
Tokyo closes at 15:00 local time (06:00 UTC) and New York at 16:00 Eastern (21:00 UTC in winter). Suppose both indices are driven only by global news arriving uniformly around the clock. What is the correlation between their close-to-close returns on the same calendar date, and between New York on date and Tokyo on date ? Which of these relationships can be traded?
Show solutionHide solution
A close-to-close return on date covers the 24 hours ending at that market's close. In UTC:
- Tokyo, date : 06:00 on to 06:00 on .
- New York, date : 21:00 on to 21:00 on .
- New York, date : 21:00 on to 21:00 on .
With news arriving uniformly, the covariance of two returns is proportional to the overlap of their windows, and each window is 24 hours long, so correlation = overlap / 24.
Same date: the overlap is 21:00 on to 06:00 on , 9 hours, so the correlation is .
New York with Tokyo : the overlap is 06:00 to 21:00 on , 15 hours, so the correlation is .
The two add up to 1: all the common news shows up in one or the other. Measured naively, the "same day" correlation understates the true link and New York appears to predict Tokyo the next day. That lead-lag is real and tradable (New York's close is known before Tokyo opens), but it is mostly a measurement artefact rather than slow information diffusion, and it is already priced in at Tokyo's open. The untradable mistake is the reverse: using New York's date- return as a feature for Tokyo's date- return, because New York closes 15 hours after Tokyo. Joining the two series on the date column does exactly this. The usual fixes are to use returns over synchronous windows (for example from futures that trade around the clock) or to shift each series to the time it becomes known.
As-of joins
The basic point-in-time operation is: "for each row on the left, take the most recent row on the right whose timestamp is at or before mine". In pandas this is merge_asof. Both frames must be sorted by the key.
direction="backward"(the default) takes the last right-hand row at or before the left time. This is the only direction that cannot peek."forward"and"nearest"can match a row from the future.allow_exact_matches=Falseexcludes a right-hand row with the identical timestamp. Use it when an equal timestamp may be a consequence of the left-hand event (a quote update triggered by the trade itself).tolerancecaps how stale the match may be, so a quote from an hour ago is not silently used.by=matches within a group, such as a ticker.
Worked example
matching trades to the prevailing quote
Classify each trade as buyer- or seller-initiated by comparing its price with the mid of the quote prevailing just before it. A quote stamped at the same instant as a trade may already reflect that trade.
Show solutionHide solution
import pandas as pd
trades = pd.DataFrame({
"time": pd.to_datetime(["09:30:00.120", "09:30:00.450", "09:30:01.000", "09:30:02.300"],
format="%H:%M:%S.%f"),
"price": [100.02, 100.05, 100.01, 100.06],
})
quotes = pd.DataFrame({
"time": pd.to_datetime(["09:30:00.100", "09:30:00.400", "09:30:01.000", "09:30:01.900"],
format="%H:%M:%S.%f"),
"bid": [100.00, 100.03, 100.00, 100.04],
"ask": [100.02, 100.05, 100.02, 100.06],
})
# Each trade gets the latest quote strictly before it (quote at the same
# microsecond may be the trade's own consequence).
out = pd.merge_asof(trades, quotes, on="time", direction="backward",
allow_exact_matches=False, tolerance=pd.Timedelta("1s"))
out["mid"] = (out.bid + out.ask) / 2
out["side"] = (out.price > out.mid).map({True: "buy", False: "sell"})
out["time"] = out["time"].dt.strftime("%H:%M:%S.%f").str[:-3]
print(out.to_string(index=False))
time price bid ask mid side
09:30:00.120 100.02 100.00 100.02 100.01 buy
09:30:00.450 100.05 100.03 100.05 100.04 buy
09:30:01.000 100.01 100.03 100.05 100.04 sell
09:30:02.300 100.06 100.04 100.06 100.05 buy
The third trade at 09:30:01.000 is matched to the 09:30:00.400 quote, not the one stamped at the same instant. That later quote (bid 100.00, ask 100.02) is what the market looked like after a seller hit the bid; using it would put the trade at the mid and misclassify it. In real data, prefer a trade-reporting delay correction over guessing, and treat trades exactly at the mid separately (for example with a tick test) rather than calling them sells, as this short version does.
The same function handles daily research: merge_asof(prices, fundamentals, left_on="decision_time", right_on="published_at", by="ticker") attaches to each decision only what had been published by then.
Knowledge check
You attach the most recent analyst rating to each daily price row with merge_asof(prices, ratings, on='time', direction='nearest'). What is wrong?
Knowledge check
A company reports earnings at 16:05 New York time on a Tuesday, and your daily database stamps the release with Tuesday's date. In a daily close-to-close backtest, which is the first return a strategy reacting to the release can honestly earn?
Knowledge check
In 2024 the US moved its clocks forward on 10 March and the UK on 31 March. Between those dates, what time in London did the New York 16:00 close occur?
Key takeaways
- Store time-zone-aware UTC timestamps; convert to exchange time only for display and for calendar logic. Daylight-saving dates differ across countries.
- Align on each market's own trading calendar; a silent forward-fill invents stale prices.
- Every data point has an event time and a publication time; backtests key on publication time plus any processing delay.
- Close-to-close returns from markets with different closes overlap only partly: same-date correlations are understated, and joining on the date can use a later close to "predict" an earlier one.
merge_asofwithdirection="backward"is the safe join; addallow_exact_matches=Falseand atolerancewhen equal timestamps or stale matches are a risk.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).