Skip to content
Cyber Week: Lifetime access, $59.99. Pay once, no subscription. Get Quantzee →
On this page
Glossary Index

Trading Glossary

Backtrader

By Rajeev Gupta

TL;DR

Backtrader is a free, open-source Python library that replays price history one bar at a time and lets your strategy class react to each bar, with a built-in broker that handles orders, commissions and slippage. It is still a good way to learn how a backtest really works. It is also no longer actively developed: the last release on PyPI is version 1.9.78.123 from April 2023, and the licence is GPLv3.

What Is Backtrader?

Backtrader is a Python framework for backtesting trading strategies and, through a few broker connectors, running them live. It first appeared around 2015, written by a single developer who goes by mementum on GitHub. You write a Strategy class, hand it data, and the engine calls your next() method once per bar, the same way it would be called in a live session.

That bar-by-bar loop is the main reason people pick it over a quick pandas script. The engine controls what your strategy can see at each step, and it has a real order model behind it: market, close, limit, stop, stop-limit, trailing stops, OCO and bracket orders. A fast vectorised test just assumes you got the price you wanted. Backtrader makes you ask for it and then decides, bar by bar, whether you would have got it.

The rest of the toolkit is what you would expect from something built for retail quants: several data feeds at once, several timeframes in one strategy (with resampling and replay), more than 120 built-in indicators, optional TA-Lib support, position sizers, analyzers for Sharpe and drawdown, and a plotting function that draws the chart for you.

Backtrader Explained — the event-driven engine, its order types, and how a bar-by-bar backtest runs.

Is Backtrader Still Maintained? (Checked 7 November 2026)

This is the first thing to settle before you build anything on it, so here are the facts as they stand on PyPI and GitHub today.

ItemWhat I found
Latest release on PyPI1.9.78.123, uploaded 19 April 2023
LicenceGPLv3 (GPL-3.0)
Official repogithub.com/mementum/backtrader, not archived, about 23,700 stars, 64 open issues and pull requests
Python versions listed3 (classifiers stop at 3.7), but it ran fine for me on Python 3.14
Docs and communitybacktrader.com docs are still up; the forum on the home page is switched off (“it was being abused”)

So the honest answer is “stable but frozen”. There has been no release in more than three years, and the open issues are not being worked through. For learning and for most plain stock or futures backtests that is fine, because the core loop does not need much updating. For a new long-term project you should know what you are signing up for.

If you want something that is still moving, there are three community forks. They are not the same thing, so check each one before you install it:

  • backtrader2 is a bug-fix fork. Its PyPI release (1.9.76.123) dates from July 2020 and the repo’s last push was in March 2024, so it is quiet too.
  • backtrader-next (on PyPI as backtrader-next) is more ambitious. Version 2.3.7 came out in March 2026, it needs Python 3.11 or newer, and its README lists faster indicators built with Numba and new HTML reports. It claims a speed-up in one benchmark; I have not reproduced that number, so treat it as the author’s claim.
  • cloudQuant/backtrader is another optimised fork with recent commits.

One more warning, because it trips people up in search. The name is shared. backtrader.io is an unrelated cloud trade copier for futures traders, and the bt library on PyPI (MIT licence) is a different package built around portfolio allocation. Neither is the library on this page.

Install and Run Your First Strategy

Installation is one line and it has no required dependencies:

pip install backtrader
pip install matplotlib   # only if you want cerebro.plot()
pip install yfinance     # only for the free Yahoo data used below

Backtrader’s old built-in Yahoo downloader stopped working years ago, so the usual route is to pull a DataFrame yourself and wrap it in bt.feeds.PandasData. Here is a complete moving-average crossover, with the pieces that most tutorials skip: a sizer, the broker settings and three analyzers.

import backtrader as bt
import yfinance as yf

df = yf.download("SPY", start="2018-01-01", end="2024-12-31",
                 auto_adjust=True, multi_level_index=False, progress=False)

class SmaCross(bt.Strategy):
    params = dict(fast=20, slow=50)

    def __init__(self):
        fast = bt.ind.SMA(self.data.close, period=self.p.fast)
        slow = bt.ind.SMA(self.data.close, period=self.p.slow)
        self.cross = bt.ind.CrossOver(fast, slow)   # +1 up-cross, -1 down-cross

    def next(self):
        if not self.position and self.cross > 0:
            self.buy()
        elif self.position and self.cross < 0:
            self.close()

cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.PandasData(dataname=df))
cerebro.addstrategy(SmaCross)
cerebro.addsizer(bt.sizers.PercentSizer, percents=95)
cerebro.broker.setcash(100_000)
cerebro.broker.setcommission(commission=0.001)      # 0.1% of trade value
cerebro.broker.set_slippage_perc(0.0005)            # 0.05% each way

cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharpe", riskfreerate=0.0)
cerebro.addanalyzer(bt.analyzers.DrawDown, _name="dd")
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades")

strat = cerebro.run()[0]
print("Final value:", round(cerebro.broker.getvalue(), 2))
print("Sharpe:", strat.analyzers.sharpe.get_analysis()["sharperatio"])
print("Max drawdown %:", strat.analyzers.dd.get_analysis().max.drawdown)
print("Closed trades:", strat.analyzers.trades.get_analysis().total.closed)

I ran exactly this on 7 November 2026 with backtrader 1.9.78.123 on Python 3.14. A few things worth knowing about how it is put together:

  • Indicators are created once in __init__ and read in next(). Never rebuild them inside next().
  • self.data.close[0] is the bar you are on now, [-1] is the previous bar. There is no [1], because the future does not exist.
  • next() is not called until the slowest indicator has enough bars. With a 50-bar average, your first 49 bars are skipped silently. That is the “warm-up” and it is why a short test can show fewer trades than you expect.
  • Without addsizer, Backtrader buys a single unit per order. On a daily SPY test that is one share and the results look tiny. Always set a sizer.

What Happens When You Call self.buy()

This is the part of the manual people skim and later get wrong, so it deserves its own section. When your next() runs, the bar’s close has already happened. Backtrader will not fill you at a price you have already seen. A market order is filled at the open of the next bar. A Close order is filled at the close of the next bar. Limit and stop orders are checked against the next bar’s open, high and low, and if the bar gaps through your price, you get the open and not your level.

That is closer to real trading than the “buy at today’s close” shortcut, and it is also why Backtrader results often look a little worse than a quick vectorised test of the same idea.

There are two switches to know about:

  • cerebro.broker.set_coc(True) is “cheat on close”: the order fills at the same bar’s close. Use it only if you really do send market-on-close orders, otherwise you are giving yourself a better fill than you could have had.
  • bt.Cerebro(cheat_on_open=True) lets you decide in a separate next_open() method just before the open, which is how you model entering at a known opening price.

One correction to an idea you will see repeated: “event-driven means no look-ahead bias”. It does not. The engine will not hand you tomorrow’s bar, but you can still leak the future through your own code, for example by loading a data file where the date column is shifted, or by using a daily bar’s high or low to make a decision that you then fill at that same day’s open. Test the logic, not the framework.

Commissions and Slippage: The Two Lines Most Backtests Skip

By default, Backtrader’s broker charges nothing and fills perfectly. Add costs as soon as the strategy works at all.

Commission has two modes, and the mode is chosen by whether you pass margin:

# Stocks / ETFs / crypto: a percentage of trade value
cerebro.broker.setcommission(commission=0.001)            # 0.1%

# Futures: a fixed amount per contract, with margin and a multiplier
cerebro.broker.setcommission(commission=2.0, margin=2000.0, mult=10.0)

If you set margin, Backtrader treats commission as a fixed amount per contract and mult as the contract multiplier. If you do not, it treats commission as a fraction of trade value. Mixing the two up is the most common reason a futures backtest has costs that are far too small.

Slippage is set on the broker too, and the method names matter, because this is where people get lost in the docs:

cerebro.broker.set_slippage_perc(0.0005)   # 0.05% worse than the fill price, each way
cerebro.broker.set_slippage_fixed(0.02)    # or a fixed 2 cents / 2 price units

In version 1.9.78.123 the full signature is set_slippage_perc(perc, slip_open=True, slip_limit=True, slip_match=True, slip_out=False) (the same arguments apply to set_slippage_fixed). If you set both, the percentage wins. A short guide to the flags:

  • slip_open: also slip fills that happen at the next bar’s open, which includes ordinary market orders.
  • slip_limit: let limit orders still fill if slippage pushes the price beyond the limit, by capping the price at the limit.
  • slip_match: if slippage would push the price outside the bar’s high-low range, cap it at the bar’s high or low. Turn it off and such an order is not filled on that bar.
  • slip_out: allow a fill outside the bar’s range. Leave this off unless you are modelling something very illiquid.

On my own run of the strategy above (SPY daily bars, January 2018 to the end of 2024, 20/50 simple-moving-average cross, 95% of equity per trade, $100,000 start), the final value was about $164,900 with no costs and about $158,400 with 0.1% commission and 0.05% slippage. Both runs made 14 round trips. Maximum drawdown went from 26.5% to 27.6% and the Sharpe ratio from 0.61 to 0.57. That is a toy rule on one instrument, not a strategy to trade. The point is the size of the gap: even on 14 trades in seven years, costs took about $6,500 out of the result, and a system that trades every day pays that bill far faster. We measured the same effect on a much larger grid in our zero-cost versus real-cost backtest, and the slippage glossary entry explains what the cost actually represents.

Reading the Results: Analyzers

Backtrader’s cerebro.broker.getvalue() tells you where you ended up, but not whether the ride was survivable. Analyzers add the missing numbers:

AnalyzerWhat you get
bt.analyzers.SharpeRatioAnnualised Sharpe from the strategy’s returns (you choose the risk-free rate)
bt.analyzers.DrawDownCurrent and maximum drawdown, in percent and in money
bt.analyzers.TradeAnalyzerCounts of won/lost trades, streaks, average and best/worst P&L
bt.analyzers.TimeReturnReturns per period, useful for building your own equity curve
bt.analyzers.SQNSystem Quality Number, a trade-level quality score

The PyFolio integration still exists in the source, but the README now marks it as deprecated. If you want a full tear sheet, export the returns and use a separate library such as QuantStats (a common pairing with Backtrader). Read the numbers with the usual caution: a good Sharpe ratio on a handful of trades is mostly luck, and max drawdown from one historical path is a floor on what you might see, not a ceiling.

Optimising Parameters Without Fooling Yourself

cerebro.optstrategy runs your strategy across a grid and returns every result. It uses multiple CPU cores through the maxcpus setting.

cerebro = bt.Cerebro(maxcpus=1)
cerebro.adddata(bt.feeds.PandasData(dataname=df))
cerebro.optstrategy(SmaCross, fast=range(10, 31, 10), slow=[50, 100])
results = cerebro.run()          # six runs: 3 fast values x 2 slow values

I ran this too, and it returned six results, one per combination. Each element is a list holding an OptReturn object, so to read the analyzers from an optimisation you have to add them before run() and dig them out of that object.

The risk is not the code, it is the temptation. Run a few hundred combinations, pick the best, and you have found the combination that fit this particular history, not an edge. Before you believe any grid winner, read overfitting in trading, split your data, and test the survivor on a window the optimiser never saw. Walk-forward testing is the clean way to do that. With a large grid, a vectorised engine is also a lot quicker, which is where VectorBT earns its place.

Backtrader vs. VectorBT: Which One Do You Need?

BacktraderVectorBT
ArchitectureEvent-driven — processes one bar at a time via next()Vectorized — operates on entire NumPy arrays of price data at once
SpeedSlower (Python loop per bar)Much faster for large parameter sweeps (array operations)
Best forStrategies needing realistic order/fill simulation, complex position state, or live-broker deploymentRapid research: testing many parameter combinations or strategy variants quickly
Look-ahead biasThe engine only hands you past bars, but your own code can still leak the futureEasy to get wrong: one missing .shift(1) on a signal array and the future leaks in
Live trading pathHas broker integrations (Interactive Brokers, Oanda, Visual Chart, and community add-ons)Primarily a research/backtesting tool — not designed as a live execution framework
MaintenanceLast release April 2023Release 1.2.0 on PyPI in October 2026
Learning curveModerate — event-driven strategy classesModerate — requires comfort with NumPy/pandas array thinking
Typical role in a systematic workflowFinal-stage validation with realistic order/cost modeling before going liveFirst-stage broad parameter search across many candidate configurations

The practical takeaway: these two tools are often used together, not as competitors. VectorBT does the wide parameter search, because it can test thousands of combinations in the time Backtrader tests dozens. Backtrader (or the Strategy Tester in TradingView) then re-tests the handful that survive, with next-bar fills and costs. For a code-level look at how a vectorised engine leaks the future, see our Python backtesting libraries comparison.

Other Python Backtesting Libraries Worth Knowing

If you are choosing today, here is where Backtrader sits against the usual alternatives. Versions and licences are from PyPI on 7 November 2026.

LibraryLatest on PyPILicenceNote
Backtrader1.9.78.123 (Apr 2023)GPLv3Mature, great docs, frozen
backtrader-next2.3.7 (Mar 2026)GPL-3.0Fork, Python 3.11+, newer features
VectorBT1.2.0 (Oct 2026)Commons Clause (restricts selling the software)Fast array-based research
Backtesting.py0.6.6 (Jul 2026)AGPL-3.0Small, simple API, easy first project
zipline-reloaded3.2.1 (Oct 2026)Apache-2.0Maintained fork of Quantopian’s Zipline

Licences matter more than they look. GPLv3 and AGPL are “copyleft”: using the library privately for your own research is fine, but if you build a product or service on top of it and distribute or host it, those licences can require you to publish your own source. If that is your plan, read the licence or ask a lawyer first. This is general information, not legal advice.

Connecting Backtrader to a Broker

The README lists live data and trading through Interactive Brokers (it needs the IbPy library installed from GitHub), Visual Chart, and Oanda. Look at the dates before you rely on any of them. The README describes the Oanda connector as REST only and says the newer v20 API did not support streaming when it was written. IBKR Campus, which has published several Backtrader articles, adds a note that its API team does not support the software. Plenty of people run it live anyway, but treat the broker side as something you will probably have to patch yourself, and paper trade it first.

How Quantzee Uses This

Backtrader is the Python half of a workflow many systematic traders run. The idea gets tested here, with next-bar fills and costs switched on. If it survives, the rule is rebuilt as a Pine Script strategy and checked in TradingView’s Strategy Tester on the chart you will actually trade, where Quantzee’s non-repainting indicators can act as the entry filters. Each stage catches different mistakes. Python catches cost and sample-size problems. The chart catches the “that signal repaints” problem, which Python never sees because you fed it clean historical bars. For how to run the chart-side test, see how to backtest a TradingView indicator.

Quantzee provides analytical software, not investment advice. Nothing here is a recommendation to trade any instrument or strategy.

Common Mistakes

  • Trusting the default broker: Backtrader starts with zero commission and perfect fills. A strategy that looks excellent at zero cost can be unprofitable once you add realistic costs. Put setcommission and set_slippage_perc in your template so they are never missing.
  • Forgetting the sizer: Without addsizer, every order is one unit. Your returns will be a rounding error and you will blame the strategy.
  • Using cheat_on_close without meaning to: If your live system cannot send a market-on-close order, filling at the same bar’s close gives you a price you could not have had.
  • Look-ahead through the data: Misaligned dates, adjusted prices that were restated after the fact, or an indicator that uses the current bar’s high before the bar is finished can all leak the future.
  • Optimising without a holdout: cerebro.optstrategy makes it easy to find the best past parameters. It will not tell you whether they work out of sample.
  • Reading the first bars as signals: The warm-up period skips the first period bars of every indicator, so very short tests carry almost no information.
  • Treating a frozen library as a maintained one: Pin the version in your requirements.txt and test after any change to Python, pandas or matplotlib. The last release predates the current versions of all three.
  • Blaming the backtest for a plotting error: cerebro.plot() needs matplotlib, and the plotting code is much older than current matplotlib releases. I did not get a clean plot test through on my setup, so if the chart fails while the numbers are fine, check the matplotlib version first and pin an older one before you suspect the strategy.

Putting This Into Practice

If you are comparing a Python framework against doing the work on-chart, how to backtest a TradingView indicator sets out what each approach can and cannot measure. Either way, a single equity curve is not enough evidence — our equity curve simulator and drawdown distribution piece explains why you should size off the 95th-percentile drawdown rather than the one your backtest reported. When the Python result and the live result disagree, why backtest and live trading results diverge lists the usual suspects.

FAQ

What does Backtrader do?

Backtrader is a Python framework that replays historical prices bar by bar, calls your strategy on each bar, and simulates the orders, commissions and slippage your strategy would have run into. You get a final account value plus whatever statistics you attach with analyzers. It can also connect to a few brokers for live trading.

Is Backtrader still maintained?

Not actively. The last release on PyPI is 1.9.78.123 from April 2023, and the official GitHub repo has open issues that nobody is closing. The library still works for ordinary backtests (it ran on Python 3.14 for me), but if you want ongoing development, look at the forks such as backtrader-next, or at VectorBT or Backtesting.py for new projects.

What is the latest Backtrader version?

1.9.78.123, released in April 2023. The last number in the version is how many indicators were built in at the time, not a build counter.

Is Backtrader free, and can I use it commercially?

It is free to download and use. The licence is GPLv3, which allows private use and modification but can require you to share your own source if you distribute software that includes it. Selling or hosting a product built on it is a licence question, so check before you commit. The real costs are your data, a server if you run live, and broker fees.

How do I set slippage in Backtrader?

Call cerebro.broker.set_slippage_perc(0.0005) for a percentage (0.0005 is 0.05%) or cerebro.broker.set_slippage_fixed(0.02) for a fixed price amount. If you set both, the percentage is used. The extra flags slip_open, slip_limit, slip_match and slip_out control which fills get slipped and whether the price is capped at the bar’s high or low.

How do I add commissions in Backtrader?

Use cerebro.broker.setcommission(commission=0.001) for a percentage of trade value (stocks, ETFs, crypto). For futures, pass margin and mult too, for example setcommission(commission=2.0, margin=2000.0, mult=10.0). In that mode the commission is a fixed amount per contract.

Where is the Backtrader documentation?

The official docs and blog are at backtrader.com, with a Quickstart that builds a strategy one step at a time, and a reference for indicators, analyzers, data feeds and brokers. The GitHub README lists the feature set and install notes. Because development has stopped, the docs are accurate for the code as it is, but some data-feed examples (Yahoo downloads in particular) no longer work, so load your own CSV or DataFrame.

Is Backtrader better than Pine Script for backtesting?

They do different jobs. Backtrader gives you full control of data, costs and analytics in Python. Pine Script runs on TradingView’s data, shows the trades on the chart, and can fire alerts. Many traders test the idea in Python and then confirm it in Pine on the chart they trade.

Can Backtrader handle multiple assets or timeframes?

Yes. Add several data feeds with cerebro.adddata and reach each through self.datas. Add a second timeframe of the same instrument with cerebro.resampledata. Multi-asset logic inside one strategy class gets complicated quickly, so keep the first version simple.

Does Backtrader require coding experience?

Yes. It is a Python library, not a no-code tool. You need to be comfortable with classes and functions. Traders who do not code usually start with TradingView’s Strategy Tester instead.

Can I backtest for free?

Yes. Backtrader, VectorBT, Backtesting.py and zipline-reloaded are all free to install, and TradingView’s Strategy Tester needs no code at all. The part that usually costs money is clean historical data, especially intraday data and options history.

Can ChatGPT backtest a trading strategy?

A chat model can write the Backtrader code for you, and that is a useful way to get a first draft. It does not run your backtest on real data, and it cannot know whether the code has look-ahead bias or missing costs. Run the code yourself, read every order it produces, and check the first few trades by hand.

Can I use Backtrader to test a Quantzee-style signal logic before building it in Pine Script?

Yes. Prototype the rule in Backtrader with costs on, check that it survives, then rebuild it in Pine Script for the live chart. Do the second step before you trade it, because a signal that looks clean on historical bars can still repaint on a live chart.

Related Terms

FAQ

Frequently Asked Questions

Put It Into Practice

See how Quantzee applies Backtrader

AI Adaptive Quant Toolkit uses these concepts in live, non-repainting signals on TradingView.

Explore AI Adaptive Quant Toolkit