May cohort is now open: How to secure your spot:

Backtest powerful intraday trading strategies

Multi-timeframe (MTF) analysis lets traders build powerful intraday trading strategies.

It does this by analyzing asset prices during different timeframes throughout the trading day.

The problem is most people get MTF wrong.

It requires a vector-based backtest to speed up the operations making it easy to introduce look-ahead bias.

When a backtest introduces look-ahead bias, it will overstate performance.

So how do we do MTF analysis “the right way?”

By reading today’s newsletter, you’ll be able to use VectorBT Pro (VBT) to to MTF the right way.

Backtest powerful intraday trading strategies

Many vector-based backtesters assume events take place at the same timestamp as the data provided by the exchange.

This is typically the opening time of a bar.

VBT takes a different approach.

It assumes the timing of most events is unknown and occurs between the opening (best-case) and closing (worst-case) times of a bar.

To do this, VBT uses a set of features designed to resample data in the most sensitive way, without looking into the future.

Sound complicated?

It’s only a few lines of Python code. Let’s see how it works!

Imports and set up

Using the latest version of VBT, the star-import (*) loads all the relevant libraries for us. (Don’t worry, it won’t pollute your namespace.)

Many vector-based backtesters assume events take place at the same timestamp as the data provided by the exchange.

This is typically the opening time of a bar.

VBT takes a different approach.

It assumes the timing of most events is unknown and occurs between the opening (best-case) and closing (worst-case) times of a bar.

To do this, VBT uses a set of features designed to resample data in the most sensitive way, without looking into the future.

Sound complicated?

It’s only a few lines of Python code. Let’s see how it works!

from vectorbtpro import *
vbt.settings.set_theme("dark")
vbt.settings.plotting.auto_rangebreaks = True

Grab the data of a higher frequency for your favorite asset. We’ll use hourly TSLA.

data = vbt.YFData.pull("TSLA", start="2023", end="2024", timeframe="hourly")

Multi-timeframe indicators

Instruct VBT to calculate the fast and slow SMA indicators across multiple timeframes.

fast_sma = data.run(
    "talib:sma", 
    timeframe=["1h", "4h", "1d"], 
    timeperiod=vbt.Default(20),
    skipna=True
)
slow_sma = data.run(
    "talib:sma", 
    timeframe=["1h", "4h", "1d"], 
    timeperiod=vbt.Default(50),
    skipna=True
)

Under the hood, data is first resampled to the target timeframe. Then, the TA-Lib indicator is applied only to non-missing values. Finally, the result is realigned back to the original timeframe in a way that eliminates the possibility of look-ahead bias.

VBT makes it easy to visualize the results.

fast_sma.real.vbt.plot().show_png()
Backtest powerful intraday trading strategies It requires a vector-based backtest to speed up the operations making it easy to introduce look-ahead bias.

We can see the line corresponding to the highest frequency is smooth, whereas the line representing the lowest frequency appears stepped since the indicator values are updated less frequently.

Build a unified portfolio

Next, we’ll set up a portfolio that goes long whenever the fast SMA crosses above the slow SMA and go short when the opposite occurs, across each timeframe.

Since hourly signals occur more frequently than daily signals, we’ll allocate less capital to more frequent signals.

We’ll allocate 5% of the equity to hourly signals, 10% to 4-hour signals, and 20% to daily signals.

We’ll begin with a cash balance of $10,000, shared across all timeframes. Additionally, we’ll implement a 20% trailing stop loss (TSL).

pf = vbt.PF.from_signals(
    data, 
    long_entries=fast_sma.real_crossed_above(slow_sma), 
    short_entries=fast_sma.real_crossed_below(slow_sma), 
    size=[[0.05, 0.1, 0.2]],
    size_type="valuepercent",
    init_cash=10_000,
    group_by=["pf", "pf", "pf"],
    cash_sharing=True,
    tsl_stop=0.2
)

Plot the cumulative return for each timeframe and compare these to the cumulative return of the entire portfolio.

fig = (
    pf
    .get_cumulative_returns()
    .vbt
    .plot(trace_kwargs=dict(line_color="gray", line_dash="dot"))
)
fig = pf.get_cumulative_returns(group_by=False).vbt.plot(fig=fig)
fig.show_png()
Backtest powerful intraday trading strategies It requires a vector-based backtest to speed up the operations making it easy to introduce look-ahead bias.

To dive deeper into one of the timeframes, we can plot the indicators alongside the executed trade signals.

Here, we can observe that the majority of positions on the daily timeframe were closed out by the TSL.

fig = fast_sma.real.vbt.plot(
    column="1d", 
    trace_kwargs=dict(name="Fast", line_color="limegreen")
)
fig = slow_sma.real.vbt.plot(
    column="1d", 
    trace_kwargs=dict(name="Slow", line_color="orangered"),
    fig=fig
)
fig = pf.plot_trade_signals(column="1d", fig=fig)
fig.show_png()
Backtest powerful intraday trading strategies It requires a vector-based backtest to speed up the operations making it easy to introduce look-ahead bias.

Timeframe product

Since our MTF indicators share the same index, we can combine one timeframe with another. Lets generate signals from the crossover of two timeframes and identify the pair of timeframes that yield the highest expectancy.

fast_sma_real = fast_sma.real.vbt.rename_levels({"sma_timeframe": "fast_sma_timeframe"})
slow_sma_real = slow_sma.real.vbt.rename_levels({"sma_timeframe": "slow_sma_timeframe"})
fast_sma_real, slow_sma_real = fast_sma_real.vbt.x(slow_sma_real)
long_entries = fast_sma_real.vbt.crossed_above(slow_sma_real)
short_entries = fast_sma_real.vbt.crossed_below(slow_sma_real)
pf = vbt.PF.from_signals(data, long_entries=long_entries, short_entries=short_entries)
pf.trades.expectancy.sort_values(ascending=False)

I looks like the 1 hour fast MA and 4 hour slow MA achieve the highest expectancy of a profitable trade.

Next steps

Timeframe is yet another parameter of your strategy that can be tweaked. For example, you can go to uncharted territory and test more unconventional timeframes like “1h 30min” to discover potentially novel insights. Similar to other parameters, timeframes should also undergo cross-validation.

However, unlike regular parameters, timeframes should be regarded as a distinct dimension that provides a unique perspective on your strategy.