Multitimeframe backtesting code needed - Sample

Hello,
I want to backtest data on multitimeframe.
1min, 5min and 15 min
Lets say I want to buy if close is above supertrend on 1min, 5min and 15 min timeframe. Can you provide sample code for the same?

Hi @spatwa3001 ,

Here’s the pseudocode for the backtesting logic.

import pandas as pd
import ta

# Load data from CSVs 
df_1min = pd.read_csv("1min_data.csv")
df_5min = pd.read_csv("5min_data.csv")
df_15min = pd.read_csv("15min_data.csv")

df_1min['datetime'] = pd.to_datetime(df_1min['datetime'])
df_5min['datetime'] = pd.to_datetime(df_5min['datetime'])
df_15min['datetime'] = pd.to_datetime(df_15min['datetime'])

df_1min.set_index('datetime', inplace=True)
df_5min.set_index('datetime', inplace=True)
df_15min.set_index('datetime', inplace=True)

#  Add Supertrend for each timeframe 
df_1min['supertrend'] = ta.trend.supertrend(df_1min['high'], df_1min['low'], df_1min['close'], period=10, multiplier=3).supertrend
df_5min['supertrend'] = ta.trend.supertrend(df_5min['high'], df_5min['low'], df_5min['close'], period=10, multiplier=3).supertrend
df_15min['supertrend'] = ta.trend.supertrend(df_15min['high'], df_15min['low'], df_15min['close'], period=10, multiplier=3).supertrend


# Backtesting:
position = False
entry_price = 0
trades = []

for i in range(1, len(df_1min)):
    row = df_1min.iloc[i]
    time = row.name
    price = row['close']
    st1 = row['supertrend']
    st5 = row['st_5min']
    st15 = row['st_15min']

    # Entry condition: close > all 3 supertrend
    if price > st1 and price > st5 and price > st15 and not position:
        position = True
        entry_price = price
        print(f"[{time}] Placing BUY order at {price}")
        trades.append({'Action': 'Buy', 'Price': price, 'Time': str(time)})

    # Exit condition: close < 1min supertrend
    elif position and price < st1:
        position = False
        exit_price = price
        pnl = exit_price - entry_price
        print(f"[{time}] Placing SELL order at {price} | PnL = {pnl:.2f}")
        trades.append({'Action': 'Sell', 'Price': price, 'Time': str(time), 'PnL': pnl})

print("\nTrade Summary:")
for trade in trades:
    print(trade)