Hour-of-Day and Day-of-Week Filters for EAs: How to Tell a Real Pattern From a Curve Fit

Break an Expert Advisor's (EA's) backtest down by hour of the day or by day of the week and some cells will look worse than others. They always do. Remove the worst ones and the backtest improves, also always, because you have just deleted losing trades with hindsight. The question is whether the bad hours were bad for a reason that will persist, or whether they were simply where the losses happened to land in this history.

Time filters are among the easiest ways to curve-fit an EA without noticing, because each one feels like a small, sensible tidy-up. This guide shows how to test them properly: getting the clock right, deciding the reason first, measuring each time bucket with its uncertainty, testing the whole table against chance, and confirming that any filter you keep holds up on data it never saw.

One point up front: a time filter chosen after looking at the results is a hypothesis, not a finding. Everything below is about deciding whether the hypothesis has earned a place in the EA.

Why time filters are easy to overfit

The arithmetic works against you. A breakdown by hour on five weekdays has 120 cells. Even if every trade's result were pure chance, the cells would differ, and the worst of 120 would look strikingly bad. Each cell holds only a small share of the trades, so its average is noisy.

Then the choices multiply. You might try hour filters, weekday filters, both together, different start and end times, and different filters for long and short trades. Each version is another look at the same history. Our guide to data-mining bias explains why the best of many tries looks better than it is, even when none of them has an edge. A time filter is a small version of the same problem.

Step 1: Get the clock right

Before reading any time breakdown, make sure you know which clock the timestamps use.

  • Server time is the broker's choice. MT5 reports trade times in the trade server's time zone. It is often an offset from UTC, and it may shift when daylight saving changes. Confirm your broker's rules rather than assuming them.
  • Daylight saving moves sessions. A session that opens at a fixed local time in one region moves by an hour against server time for part of the year if the server's offset and that region change on different dates. An "hour 9" filter can quietly cover two different market hours across the year. Our guide to testing breakout EAs shows this effect on session filters.
  • Decide which time you are bucketing. Most breakdowns use the entry time. If the effect you suspect is about exits, such as poor fills around a daily rollover, bucket by exit time as well and compare.
  • Convert to one reference clock. If you can, convert every timestamp to UTC, or to the local time of the market session you think matters, before building the table.

Step 2: Write the reason before you look

A filter with a mechanism behind it is a much better hypothesis than one found by scanning a table. Write the reason down first, together with the hours it predicts. Reasonable mechanisms include:

  • Liquidity and spread. Spreads are typically wider in quiet hours and around the daily rollover, which raises the cost of every trade placed then.
  • Session structure. Some strategies depend on activity around particular session opens or overlaps.
  • Scheduled events. Recurring releases at fixed times can dominate a short-term strategy's results in those hours.
  • The strategy's own logic. An EA that enters on the first bar of the week behaves differently on that day by design.

If the table later shows a pattern your written reason didn't predict, treat it as a new idea to test on fresh data, not as a filter to add now.

Step 3: Tabulate results by hour and weekday

Use per-trade results net of costs, in units that are comparable across trades. Multiples of the initial risk (often written R) work well when every trade has a stop. Otherwise use a fixed position size or volatility units. Then report the count and the uncertainty for each bucket, not just its total.

import numpy as np
import pandas as pd

def by_time_bucket(trades: pd.DataFrame, col: str) -> pd.DataFrame:
    """trades: one row per trade with a result column 'r' (net of costs) and a time-bucket column."""
    g = trades.groupby(col)["r"]
    return pd.DataFrame({"trades": g.size(), "mean_r": g.mean(),
                         "std_error": g.std(ddof=1) / np.sqrt(g.size())})

# trades["hour"] = trades["open_time"].dt.hour         # after converting to your reference clock
# trades["weekday"] = trades["open_time"].dt.day_name()
# print(by_time_bucket(trades, "hour"))

Read the table with the count first. A bucket with a dozen trades has a standard error so wide that its mean says very little. If most buckets are that thin, the honest conclusion is that the backtest can't tell the hours apart, and a filter would be a guess.

Step 4: Test the whole table against chance

The question is not "is the worst hour bad?" but "do the hours differ more than chance would produce?". A permutation test answers that by shuffling the time labels among the trades many times. Each shuffle keeps the trade results and the bucket sizes but breaks any real link between time and result.

def time_label_permutation_test(trades: pd.DataFrame, col: str, n: int = 2000,
                                min_trades: int = 30, seed: int = 3):
    """Gap between best and worst bucket mean, real vs shuffled labels. Buckets below min_trades are ignored."""
    rng = np.random.default_rng(seed)
    r = trades["r"].to_numpy()
    labels = trades[col].to_numpy()

    def gap(lbl):
        stats = pd.Series(r).groupby(lbl).agg(["mean", "size"])
        stats = stats[stats["size"] >= min_trades]
        return stats["mean"].max() - stats["mean"].min()

    real = gap(labels)
    shuffled = np.array([gap(rng.permutation(labels)) for _ in range(n)])
    return real, (shuffled >= real).mean()

Reading the permutation result

  • The second value is the share of shuffles with a gap at least as large as the real one. A large share means the differences between hours are about what random labelling produces. A small share means they are larger than shuffling usually produces, in this history. It is not the probability that the pattern continues.
  • It tests the table, not a cell. A small share says the hours differ somewhere. It doesn't license removing whichever hour looks worst, which is still a choice made with hindsight.
  • Shuffling assumes trades are independent. Trades on the same day, or during the same volatile week, often move together. If your trades cluster, shuffle whole days or weeks of trades rather than single trades, or the test will look more confident than it should.
  • Every breakdown you test counts. Hours, weekdays and their combination are three tests. Run the ones you planned in Step 2, and report all of them.

Step 5: Prefer blocks to single cells

Real time effects tend to be smooth: liquidity fades over a few hours, it doesn't vanish for one hour and return. So:

  • Filter contiguous blocks of hours rather than scattered single hours.
  • Check the neighbours. If excluding 02:00–05:00 helps, excluding 01:00–05:00 or 02:00–06:00 should help in a similar way. A result that only works at one exact start and end time is fitted to those times.
  • Keep weekday filters rare. Five weekdays give few buckets, but each holds a fifth of the trades and is easily dominated by a handful of large results. Check how much of a weekday's result comes from its largest few trades.

Step 6: Check it holds year by year and out of sample

Repeat the breakdown for each year, or each half of the test, separately. A real time effect should appear, at least roughly, in most periods. A "bad Thursday" that is bad in one year and ordinary in the rest is usually one year's events, not a weekday effect.

Then apply the filter, with its hours fixed, to data that played no part in choosing it. Compare filtered and unfiltered results on that data, with the same costs. Our guide to out-of-sample testing explains how to keep that data clean, including why you should not go back and adjust the hours after seeing the out-of-sample result.

Step 7: Separate costs from edge

Some time filters are really cost filters. If trades placed around the daily rollover lose more because spreads are wider then, the filter is removing expensive trades, not trades with a worse signal. That can be a perfectly good reason to keep it, but it changes how you test it:

  • Check the spread the backtest used at those hours. If the test used a fixed spread, it may have understated the cost, and the live effect could be larger than the backtest suggests.
  • Look at the result before costs. If the hours differ only after costs, a direct cost guard, such as a maximum-spread check, may do the job more precisely than a clock rule.
  • Re-check after any change of broker or account type, since spreads and rollover timing differ between them.

Common time-filter mistakes

  1. Choosing hours from the full backtest table and reporting the improved backtest as evidence.
  2. Mixing clocks, so the same filter covers different market hours across the year.
  3. Ignoring trade counts and reading thin buckets as if their averages were reliable.
  4. Testing many breakdowns and keeping whichever looks strongest.
  5. Filtering scattered single hours whose neighbours behave differently.
  6. Skipping the year-by-year check, so one unusual year defines the filter.
  7. Treating a cost effect as an edge effect, or the reverse.

Time-filter checklist

  • Timestamps converted to one reference clock, with daylight saving handled
  • Entry and exit times bucketed separately where the mechanism could involve either
  • Reason and predicted hours written down before looking at the breakdown
  • Bucket table includes trade counts and standard errors, using results net of costs
  • Permutation test run on the whole table, with days or weeks shuffled if trades cluster
  • Filters chosen as contiguous blocks, with neighbouring start and end times tested
  • Breakdown repeated for each year or half of the test
  • Final filter fixed, then tested out of sample with realistic spreads at those hours

Frequently asked questions

Do day-of-week filters work for EAs?

Sometimes there is a real reason for a weekday to differ, such as a strategy that depends on the week's first session or a recurring event. More often, a weekday that looks bad in a backtest is the result of a few large trades. Check how much of the weekday's result comes from its largest trades, whether the effect appears in most years, and whether it holds on out-of-sample data.

How many trades do I need per hour to trust a time filter?

There is no fixed number, because it depends on how variable each trade's result is. Calculate the standard error of each bucket's average: if the ranges for different hours overlap heavily, the backtest can't distinguish them, however many trades the whole test contains.

Should my EA use broker server time or UTC?

Use whichever the EA's rules are written in, but know exactly how it maps to the market hours you care about. Server time is set by the broker and may shift with daylight saving. Many developers convert to UTC or to the relevant session's local time inside the EA, and test across daylight saving changes.

Is a trading-hours filter curve fitting?

It can be. A filter based on a written reason, chosen as a contiguous block, stable across neighbouring times and across years, and confirmed on unseen data is a reasonable design choice. A filter found by removing the worst cells of a backtest table and confirmed only on that same backtest is curve fitting.

What is a permutation test for time filters?

It shuffles the time labels among your trades many times, keeping the trade results, and measures how far apart the best and worst time buckets are after each shuffle. If the real gap is no larger than most shuffled gaps, the differences between hours are about what chance alone produces in that history.

Want a second pair of eyes?

Start with our free Sample Stress-Test Report. It walks one anonymized, illustrative strategy through a full stress test, start to finish, so you can see what rigorous validation looks like before you test your own.

Read the Sample Stress-Test Report

Want your own backtest checked? The Strategy Audit + 60-minute call is a paid service at a launch price of £100, credited in full against our build and portfolio offers. You send an MT4/MT5 Strategy Tester report or trade-list CSV; what we can check depends on the files you supply, and walk-forward and parameter sweeps are not included because they need the strategy itself. It is analysis of strategy testing, not investment advice, and does not promise any trading or evaluation outcome. See the Strategy Audit

Disclaimers

CollosoTrading provides educational content and analytical services for retail and professional algorithmic traders. We do not provide regulated investment advice, financial advice, or personal recommendations. Trading derivatives, leveraged products, and CFDs carries a high level of risk and may result in losses exceeding deposits. Past performance, including any verified or unverified historical results referenced on this site, is not indicative of future results. Consult an independent regulated financial adviser before making investment decisions.

All figures are backtests or simulations unless marked LIVE. Hypothetical or backtested performance results have inherent limitations and may not reflect actual trading. No representation is made that any account will or is likely to achieve profits or losses similar to those shown. Individual results vary. This article contains no performance figures; the code examples produce your own test results. We do not guarantee the outcome of any prop firm challenge.