TradePoseResearch
How to build 4-hour bars: daylight saving time makes backtests depend on their start date
Backtest mechanics

How to build 4-hour bars: daylight saving time makes backtests depend on their start date

Run the same 4-hour SuperTrend strategy on the same prices twice, once starting in November and once in August, and the trades in the overlapping period should be identical. They are not. This post explains what the problem is, why the default calls in both Polars and pandas run into it, and what the correct way to cut the bars costs in speed.

Conclusion

When 1-minute or 15-minute data is combined into 4-hour bars, the usual resampling functions align only the first bar to the local clock and then add 4 elapsed hours for each bar after it. When daylight saving time switches, the local clock moves by 1 hour, so every later 4-hour bar is shifted by 1 hour; which way it is shifted depends on whether the first row of the data was in winter or summer time. In a simulated 4-hour SuperTrend strategy, the two start dates differ in 32 entries. The fix is to let each row pick its bucket from its own time on the evaluation timezone’s wall clock, and then the two start dates produce identical trades. This needs a timezone conversion on every row, but because consecutive rows fall into the same bucket, 10 years of 1-minute data resample into 4-hour bars in 178 milliseconds, bit-identical to Polars.

That is the conclusion. Each section below is the evidence for one claim; follow the sections or the evidence links into the strategy report for the data on every parameter set.

The problem: a different start date gives a different strategy

Research often runs the same strategy twice: once over the whole selection and validation periods, and once with a warmup that starts just before the validation period. Both runs agree on the selection period, but the validation trades differ, by enough to change the conclusion.

Narrowing it down step by step:

  1. Only the 4-hour strategies diverge. The 1-hour and daily strategies in the same study are identical trade by trade in both runs.
  2. It is not the hour the run starts. Starting at 22:00 or 23:00 on the same day, or a week later, gives the same result.
  3. It is not the length of history. SuperTrend’s bands are recursive, so history length could matter. But runs with start dates spread over four years fall into two groups: the ones starting in winter time agree with each other, the ones starting in summer time agree with each other, and the two groups differ.

The dividing line is whether the start date was in winter time or summer time.

In this post, New York winter time is EST (Eastern Standard Time, UTC−5) and summer time is EDT (Eastern Daylight Time, UTC−4).

Simulation: one strategy, two start dates

The following simulation uses synthetic 15-minute prices. The strategy is a 4-hour SuperTrend (ATR 6 bars × 3.5) that reads the last completed 4-hour bar and goes short during New York 09:30–16:00 while the trend is up, exiting at a flip or at 16:00. The two runs differ only in the start date; we compare their 2026 trades:

How the 4-hour bars are cutStart 2021-11-14 (winter)Start 2025-08-03 (summer)Entries found on only one sideIdentical trades
First bucket aligned, then +4 hours each160 trades176 trades8 + 24148
Local wall clock169 trades169 trades0169

Trades on the same day show the difference directly:

DateWinter startSummer start
2026-01-13Enter 09:30 → exit on the 12:00 flipEnter 09:30 → exit on the 15:00 flip
2026-01-20Enter 09:30 → exit 16:00Enter 11:00 → exit 16:00
2026-03-02No tradeEnter 09:30 → exit 16:00

The winter-start run flips at 12:00, the summer-start run at 11:00 or 15:00. A flip can only happen when a 4-hour bar closes, so these times reveal that the two sets of buckets are 1 hour apart.

Simulated data:

Both tables are computed on randomly generated 15-minute prices, not on actual US100 prices. The numbers only show the shape of the difference.

The cause: only the first bucket follows the local clock

The data is already converted to New York time, so why does this happen? Because a timezone conversion changes the label of a timestamp, not the instant it refers to. The 15-minute bars are correct; the problem is the rule that combines them.

Polars’ group_by_dynamic(every="4h") and pandas’ resample("4h") both work like this:

  1. First bucket: the first row is truncated to a 4-hour boundary in local time. This step does use the timezone.
  2. Every bucket after it: add 4 elapsed hours.

When daylight saving time switches, the local clock moves by 1 hour but elapsed time does not, so every bucket after the switch is 1 hour off on the local clock:

from datetime import datetime, date
from polars import DataFrame, col, datetime_range, len as count

def bars(start):
    ts = datetime_range(start, datetime(2026, 7, 1), "15m",
                        time_zone="America/New_York", eager=True)
    return DataFrame({"ts": ts})

def starts(df, day):
    g = df.group_by_dynamic("ts", every="4h", start_by="window").agg(count())
    return [t.strftime("%H:%M") for t in g.filter(col("ts").dt.date() == day)["ts"]]

winter = bars(datetime(2025, 11, 16, 18))  # first row in winter time
summer = bars(datetime(2025, 8, 3, 18))    # first row in summer time
print(starts(winter, date(2026, 1, 8)), starts(summer, date(2026, 1, 8)))
print(starts(winter, date(2026, 6, 10)), starts(summer, date(2026, 6, 10)))
DateCounted from winterCounted from summer
2026-01-08 (winter)00:00, 04:00, 08:00, 12:00…03:00, 07:00, 11:00, 15:00…
2026-06-10 (summer)01:00, 05:00, 09:00, 13:00…00:00, 04:00, 08:00, 12:00…

Each start date is aligned with the local clock for only half the year, and not a single 4-hour bar in the overlapping period is the same. pandas’ Series.resample("4h") gives the same result on the same data.

Daily bars are not affected: 1d is a calendar unit in both Polars and pandas, and every bucket starts at local midnight. Timeframes of 1 hour and below are not affected either: shifted by 1 hour, they still land on the hour. The affected timeframes are 2, 3, 4, 6, 8 and 12 hours.

What this affects

  • Backtests cannot be reproduced. The same strategy’s result depends on the season its backtest starts in. When the selection and validation runs start on different dates, you are comparing two different strategies.
  • Live trading drifts away from the research. Each live computation only loads a recent stretch of history as warmup, so its start date keeps moving forward. The way 4-hour bars are cut therefore changes twice a year, and the live strategy is not the one the research validated.
  • A 4-hour bar loses its fixed meaning. “The 4-hour bar that closes at 12:00 New York time” becomes 11:00 or 13:00 for half the year, and rules written in terms of the session (the first bar after the open, the last bar before the close) fall out of place with it.

The fix: cut buckets on the evaluation timezone’s wall clock

The rule fits in one sentence: each row picks its bucket from its own time on the local clock. 4-hour bars always start at local 00:00, 04:00, 08:00, 12:00, 16:00 and 20:00, in winter and in summer. The timezone database handles the daylight saving rules; there is no need to work out the switch dates yourself.

We also compared another approach: cutting every sub-day bar in UTC. It also makes the result independent of the start date, but the start of a 4-hour bar in New York then moves by 1 hour with the seasons, which contradicts the purpose of writing strategy rules in local time. So we cut on the wall clock.

With Polars

Replace group_by_dynamic with dt.truncate plus group_by. On timezone-aware timestamps, dt.truncate already truncates in local time:

from polars import col

bars_4h = (
    df.group_by(col("ts").dt.truncate("4h"))
      .agg(col("open").first(), col("high").max(),
           col("low").min(), col("close").last(),
           col("volume").sum())
      .sort("ts")
)

With pandas or other tools

Without Polars the idea is the same: compute the group key yourself, and make the key keep its timezone:

from numpy import array
from pandas import Timedelta

is_dst = array([t.dst() != Timedelta(0) for t in df.index])
key = df.index.floor("4h", ambiguous=is_dst, nonexistent="shift_forward")
bars_4h = df.groupby(key).agg(
    {"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"})

In any language, check your own code against these four points:

  1. Truncate the group key in local time; do not step forward from the first bucket by a fixed length.
  2. Keep the timezone or UTC offset in the group key. Truncating the local time with the timezone stripped looks right too, but on the fall-back day 01:00–02:00 happens twice, and a 1-hour bar would merge both into one bar of eight 15-minute bars.
  3. Publish a higher-timeframe value only when the next bucket starts; do not compute the completion time as “bucket label + 4 hours”. On switch days the bucket is not 4 hours long: a fixed length makes the value arrive 1 hour late on the spring-forward day, and on the fall-back day it is read before the bucket has closed, which is a look at the future.
  4. A sub-day timeframe must divide 24 hours, so that buckets restart at midnight every day. Reject timeframes such as 5 hours outright.

Buckets on switch days

A direct consequence of cutting on the wall clock: the bucket that contains the switch is not 4 hours long.

Day (New York)The 00:00 bucket15-minute bars inside
Normal day4 hours16
Spring forward (second Sunday of March)3 hours12
Fall back (first Sunday of November)5 hours20

US switches happen at 2 a.m. on a Sunday, when indices and gold are closed, so in practice these markets never see them; only instruments that trade around the clock get these two bars of a different length.

The invariant: a source bar must not straddle buckets

With the new cut comes one more rule: every source bar’s full interval must fall inside a single target bucket. A source bar that crosses a bucket boundary has no correct answer: counted in the earlier bucket, it lets that bucket see prices from the next one; counted in the later bucket, it leaves the earlier bucket missing part of its prices. So the resampling must stop with an error instead of quietly assigning the bar to one side.

Source dataEvaluation timezoneTargetResult
1, 5, 15, 30 minutesNew York, London, Sydney, Tokyo4 hoursWorks
15 minutesIndia (UTC+5:30), Adelaide (UTC+9:30/+10:30)4 hoursWorks
1 hour cut on UTC hoursIndia (UTC+5:30)4 hoursError: local 00:00 is 18:30 UTC, so every 1-hour bar straddles a boundary
30 minutes cut on UTCNepal (UTC+5:45)4 hoursError: 30-minute bars straddle the local hour
2 hours cut on UTCNew York in winter4 hoursError; in New York summer time they happen to align and work
15 minutesLord Howe Island (summer time shifts only 30 minutes)4 hoursWorks; the switch bucket is 3.5 or 4.5 hours

When the error appears, the remedy is to use finer source data. The timezone conversion itself is not the problem; the error means the source data is too coarse to cut bars in this timezone without looking ahead. With 1-minute or 15-minute data in New York time, you will never hit it.

Performance: winning back the speed

The old code was fast precisely because it was wrong: only the first row needed a timezone conversion, and every later bucket was an integer addition. The correct cut has to place every row on the local clock.

10 years of 1-minute data (5,258,880 rows), New York time, Apple M2, median of 5 runs:

TargetFirst bucket aligned, then fixed steps (wrong)Polars dt.truncateOne conversion per bucket
4 hours36 ms421 ms178 ms
5 minutes263 ms625 ms346 ms
1 day34 ms409 ms174 ms
4 hours (UTC, no daylight saving)38 ms—41 ms

dt.truncate converts every row twice: from UTC to local time, truncate, and then the bucket start from local time back to UTC. The second conversion is the expensive one, because a local time may not exist (spring forward) or may map to two instants (fall back).

The optimization rests on one observation: consecutive rows almost always fall into the same bucket with the same UTC offset. It works in two steps:

  1. Look up the UTC offset once per row (a binary search on the timezone’s transition table), and compute the local time and its bucket with integer arithmetic.
  2. The bucket’s start instant depends only on “local bucket + this row’s offset”. When both match the previous row, reuse the previous result, so the expensive local-to-UTC conversion runs about once per bucket. Nonexistent and ambiguous times are resolved by the same rules as Polars.

What remains is mostly the per-row offset lookup. Splitting the data into chunks and processing them on multiple threads would make it faster still; that has not been done yet.

Making sure the optimized result did not change

Hand-written conversions are most likely to break on rare timezone rules, so we compared against Polars dt.truncate as an independent reference:

  • Fixed tests: 11 timezones (including Lord Howe’s half-hour daylight saving, the midnight switches of Santiago and Havana, and the historical offset changes of Tehran, Casablanca and Moscow) × 15 minutes up to 1 day × millisecond, microsecond and nanosecond precision, bit-identical; inputs on which Polars raises an error raise on both sides.
  • Full timezone sweep: every timezone in the timezone database, every minute within two days of every offset change from 1900 to 2040, × 11 timeframes from 15 minutes to 1 day: 0 differences.
  • An edge case the sweep found: Casey Station in Antarctica jumped straight from UTC+8 to UTC+11 on 2016-10-22, so the hour after the spring-forward gap still does not exist. Normal timezones never reach this branch; after the sweep it became a fixed test.

Two more checks make sure nothing else changed:

  • Other timeframes are unchanged: before the change, digests of the old output were recorded for 1, 5, 15 and 30 minutes, 1 hour and 1 day across several timezones; after the change they are bit-identical. Temporarily switching the grouping back to the old code makes the wall-clock tests fail while the digests still pass, which confirms the digests recorded the output from before the change.
  • Live warmup is reproducible: at many random computation times (including around the switches), resampling only the most recent 20 to 120 days of history gives every complete 4-hour bar, and the previous bar’s close, exactly as the full history does.
Limitations of this post:

The trade tables are computed on randomly generated prices; they show the shape of the difference, not actual US100 trades. The performance numbers were measured on a single machine (Apple M2) with single-threaded timezone conversion, and will differ on other machines and data sizes. In timezones where the switch happens at midnight itself (for example Santiago, Chile), local 00:00 does not exist on the switch day and that bucket starts at the first moment after the gap.

Questions this study answers

Should the same strategy give the same result when the backtest starts on a different date?

It should. When bars are cut as “first bucket aligned, then fixed 4-hour steps”, the result depends on whether the start date is in winter or summer time; once buckets are cut on the evaluation timezone’s wall clock, each bar’s start depends only on its own timestamp, and the two start dates produce identical trades.

How can I check whether my own backtest code has this problem?

Take a strategy on a 2- to 12-hour timeframe, backtest it once from January and once from July, and compare the bar starts and the trades in the overlapping period. The fix is to use a timezone-aware local truncation as the group key, and to publish higher-timeframe values only when the next bucket starts.

Questions raised along the way

The correct cut is much slower than the wrong one. Is it worth it?

It is, and the gap can be narrowed. A timezone conversion per row is the price of correctness; by using the fact that consecutive rows share a bucket, 10 years of 1-minute data resample into 4-hour bars in 178 milliseconds instead of 421, bit-identical to Polars.

I only have 1-hour data and want a 4-hour strategy in Indian time. What can I do?

1-hour bars cut on UTC hours all straddle Indian local hours, so they cannot form 4-hour bars without looking ahead. Use 30-minute or finer data instead.

Method and data

Research setup, data and calculations; the identifiers needed to reproduce the study are under data sources.

Changelog

2026-10-24 19:52 first published
Cite this article

TradePose Research (2026). "How to build 4-hour bars: daylight saving time makes backtests depend on their start date." TradePose Research Notes.

@article{tradepose2026resampledaylightsavingwallclock, title = {How to build 4-hour bars: daylight saving time makes backtests depend on their start date}, author = {TradePose Research}, journal = {TradePose Research Notes}, year = {2026} }