IBKR Backtesting with Python: Test Your Strategy Before Going Live
To backtest a strategy on IBKR you download historical data through the IBKR API and run the test in Python. The API gives you the data and executes live orders, but it has no backtesting engine of its own. This guide shows the full path: pulling history from Interactive Brokers, running a backtest with realistic costs, reading the results, and avoiding the mistakes that make a backtest look better than live trading will be.
How backtesting on IBKR actually works
There are three parts, and it helps to keep them separate:
- Data. Historical bars come from IBKR through TWS or IB Gateway.
- Backtest. Your Python code applies the strategy rules to that data and records every simulated trade.
- Live code. The same signal logic later runs against the live API on your paper account, then your live account.
If the signal logic is one function used by both the backtest and the live bot, what you tested is what you trade. If they are two separate versions, they will drift apart.
Step 1: Download historical data from IBKR
You need TWS or IB Gateway running with the API enabled, and a market data subscription for the instrument. This example uses ib_async, the maintained successor to ib_insync.
pip install ib_async pandas
import pandas as pd
from ib_async import IB, Stock, util
ib = IB()
ib.connect("127.0.0.1", 4002, clientId=2) # IB Gateway, paper account
contract = Stock("SPY", "SMART", "USD")
ib.qualifyContracts(contract)
def download(contract, bar_size="1 hour", chunk="1 M", chunks=24):
end = ""
frames = []
for _ in range(chunks):
bars = ib.reqHistoricalData(
contract, endDateTime=end, durationStr=chunk,
barSizeSetting=bar_size, whatToShow="TRADES", useRTH=True)
if not bars:
break
frames.append(util.df(bars))
end = bars[0].date # continue backwards from the oldest bar
ib.sleep(2) # stay under the pacing limits
df = pd.concat(frames).drop_duplicates("date").sort_values("date")
return df.set_index("date")
df = download(contract)
df.to_csv("spy_1h.csv")
Things to know about IBKR historical data:
- Requests are limited. Each bar size has a maximum duration per request, and too many requests in a short time cause a pacing violation (error 162). That is why the code downloads in chunks with a pause.
- Save the data. Download once, store it in a file, and run your backtests from the file. Do not request the same history every run.
useRTHmatters.Truereturns regular trading hours only. Use the same setting your live strategy will use.- Splits and dividends.
TRADESdata is adjusted for splits but not dividends. For long daily tests on stocks,ADJUSTED_LASTincludes dividend adjustments, and it only works with an emptyendDateTime. - History depth is limited for small bar sizes. For many years of minute or tick data you may need a dedicated data vendor.
Step 2: Write the strategy as a function
The example is a moving average crossover, chosen because it is short. Replace it with your own rules.
def add_signal(data, fast=20, slow=50):
data = data.copy()
data["fast"] = data["close"].rolling(fast).mean()
data["slow"] = data["close"].rolling(slow).mean()
data["signal"] = (data["fast"] > data["slow"]).astype(int) # 1 = long, 0 = flat
return data
Step 3: Run the backtest with costs
def backtest(data, cost_per_side=0.0005):
data = add_signal(data)
# act on the bar AFTER the signal, never on the same bar
data["position"] = data["signal"].shift(1).fillna(0)
data["ret"] = data["close"].pct_change().fillna(0)
trades = data["position"].diff().abs().fillna(0)
data["strategy"] = data["position"] * data["ret"] - trades * cost_per_side
data["equity"] = (1 + data["strategy"]).cumprod()
return data
result = backtest(pd.read_csv("spy_1h.csv", index_col="date", parse_dates=True))
Two lines decide whether this test is honest. The shift(1) makes the strategy trade on the bar after the signal, because in live trading you only know a bar's close once it has closed. The cost_per_side charges commission and slippage on every entry and exit. Set it from your real IBKR commissions and the typical spread of the instrument.
Step 4: Read the results
import numpy as np
def report(data, bars_per_year=252 * 7): # about 7 hourly bars per session
eq = data["equity"]
strat = data["strategy"]
drawdown = (eq / eq.cummax() - 1).min()
sharpe = strat.mean() / strat.std() * np.sqrt(bars_per_year)
entries = int((data["position"].diff() > 0).sum())
print(f"Total return: {eq.iloc[-1] - 1:.1%}")
print(f"Max drawdown: {drawdown:.1%}")
print(f"Sharpe ratio: {sharpe:.2f}")
print(f"Trades: {entries}")
report(result)
- Max drawdown is the largest fall from a peak. Ask whether you would keep the bot running through it.
- Sharpe ratio compares return with volatility. It is more useful for comparing versions of a strategy than as an absolute score.
- Number of trades tells you how much to trust everything else. A few dozen trades prove very little.
- Compare with buy and hold. If holding the instrument did better with similar drawdown, the strategy adds nothing.
Using a backtesting library
The pandas approach above is enough for simple bar-based rules. For stop losses, take profits, position sizing and several instruments, a library saves work. backtrader, backtesting.py and vectorbt are common choices, and all of them accept a pandas DataFrame, so the data you downloaded from IBKR works as it is.
Mistakes that make a backtest lie
- Lookahead bias. Using information from a bar before it has closed. Always shift signals.
- No costs. Strategies that trade often can turn from profit to loss once commissions and slippage are included.
- Overfitting. Trying hundreds of parameter combinations and keeping the best one finds noise, not an edge. Choose parameters on one period and check them on a later period the optimiser never saw.
- Too little data. Test across different market conditions, including a falling market.
- Unrealistic fills. A backtest assumes you get the price on the bar. Limit orders may not fill, and market orders in thin markets fill worse.
- Survivorship bias. Testing only on stocks that exist today ignores the ones that were delisted.
From backtest to live
- Run the strategy on your IBKR paper account with the same signal function.
- After a few weeks, backtest the same period and compare trade by trade. Differences show you what the backtest is missing.
- Go live with small size and repeat the comparison with real fills.
Frequently asked questions
Does IBKR have a built-in backtester for the API?
No. The API provides historical data and order execution. The backtest itself runs in your own code or a backtesting library.
Is IBKR historical data free?
It is available through the API to accounts with the relevant market data subscriptions. There is no separate charge per request.
How many years of data do I need?
Enough to cover different market conditions and produce a meaningful number of trades. For a daily strategy that usually means many years. For an intraday strategy, one to two years is often what the data allows.
Why are my live results worse than the backtest?
The usual causes are costs set too low, signals that used unclosed bars, fills that would not have happened, and parameters fitted to the past.
Want your strategy tested and automated?
We backtest client strategies and build the live bots that trade them. See IBKR trading bot development, or read the next step in how to build an IBKR trading bot in Python.
This article is for education. It is not financial advice, and past results do not guarantee future performance.