TradeBot Check
Trading involves a risk of losing money. Nothing on this site is financial advice and past results do not guarantee future results. Risk disclosure
Guide · 2026-11-21

How to run your first backtest in Python: a moving average crossover in 20 lines

A backtest replays a rule on past prices so you can see how it would have behaved. It cannot predict the future, but it quickly shows whether an idea is worth more work. This guide runs a classic moving average crossover with Backtesting.py. The example is illustrative only: no result here is a promise of any return.

What you need

  • Python 3 and a terminal.
  • Backtesting.py, free and open source (AGPL-3.0): pip install backtesting.
  • Optional, for your own prices: yfinance (pip install yfinance).

Step by step

  1. Write the strategy. Save this as first_backtest.py:
    from backtesting import Backtest, Strategy
    from backtesting.lib import crossover
    from backtesting.test import SMA, GOOG
    class SmaCross(Strategy):
      def init(self):
        price = self.data.Close
        self.ma1 = self.I(SMA, price, 10)
        self.ma2 = self.I(SMA, price, 20)
      def next(self):
        if crossover(self.ma1, self.ma2):
          self.buy()
        elif crossover(self.ma2, self.ma1):
          self.sell()
    The rule: buy when the 10-period average crosses above the 20-period one, sell when it crosses back below.
  2. Run it with costs. Add at the bottom:
    bt = Backtest(GOOG, SmaCross, commission=.002, exclusive_orders=True)
    stats = bt.run()
    print(stats)
    bt.plot()
    The commission value charges a fee on every trade, so the result is not flattered by free trading. bt.plot() opens an interactive chart of the trades.
  3. Read the numbers with suspicion. Look at the number of trades, the worst drop (drawdown) and the result compared with simply holding the asset, not only at the final profit.
  4. Swap in your own prices. Download daily data with yfinance and pass it to Backtest instead of GOOG. The table needs the columns Open, High, Low, Close and Volume, so print data.head() first and rename or flatten the columns if they differ.

Make it better

  • Test other periods and other assets, not just the one where the idea looks good.
  • Split your data: tune on one stretch and check on another that you did not touch. Our guide to backtesting without fooling yourself explains why.
  • Read a fuller report of returns and risk with QuantStats.
  • Compare other backtesting libraries in our comparisons.

Good to know

Backtesting.py is licensed AGPL-3.0: if you use it inside a web service offered to others, you must publish your code. yfinance is not an official Yahoo API; its own documentation says it is intended for research and educational use, that Yahoo's API is for personal use only, and that it can stop working if Yahoo changes something. A good backtest does not guarantee anything about the future, and a bot should be tried in simulated mode with risk limits before any real money.

See more ideas

Browse the use cases or the tool directory. Custom trading bots are coming soon: notify me when it opens.

Before you start

What does Backtesting.py cost and what licence does it use?

Free (open source). Licence: AGPL-3.0. Prices change, so check the official website before you decide.

What should I know before using Backtesting.py?

AGPL-3.0 license: if you use it inside a web service offered to others, you must publish your code.

What does yfinance cost and what licence does it use?

Free (open source). Licence: Apache-2.0. Prices change, so check the official website before you decide.

What should I know before using yfinance?

Not affiliated with or endorsed by Yahoo. Its own documentation says the tool is intended for research and educational purposes and that the Yahoo Finance API is for personal use only: read their terms. Since it is not an official API, it can stop working whenever Yahoo changes something.

What does QuantStats cost and what licence does it use?

Free and open source. Licence: Apache-2.0. Prices change, so check the official website before you decide.

What should I know before using QuantStats?

Metrics work on return series, not individual trades, so trade-level statistics can differ. The README says full documentation is still coming soon. Needs Python 3.10 or later plus pandas, numpy, scipy, matplotlib, seaborn and yfinance. Past statistics describe history only and are illustrative, not a promise of future results.

Tools in this guide

  • Backtesting.py: Lightweight Python library to backtest a strategy on one asset with very little code.
  • yfinance: Python library to download prices and history from Yahoo Finance; widely used for research and learning.
  • QuantStats: Python library that turns a series of returns into performance and risk metrics, charts and a full HTML tearsheet, handy for reviewing any backtest or portfolio.
  • ta (Technical Analysis Library in Python): Python library built on Pandas and NumPy that adds 43 technical indicators (volume, volatility, trend and momentum) to a price table with a few lines of code.

Compare your options

Want a bot like this when custom bots open? Get notified · more bot ideas

Coming soon

Coming soon: custom bots

We are preparing a service to code, backtest and automate trading and statistics bots to your own rules. It is not available yet: follow our Telegram channel to know when it opens.

Tools mentioned in this guide

More guides