Howwise RSS
Trading Software8 min read

Backtrader SMA Crossover No Trades: Warm-Up and Fixes

Short answer

A Backtrader SMA crossover with no trades is usually warm-up: next() is not called until every indicator has a value, so SMA(50) skips 49 bars and CrossOver needs one more, giving a first signal at bar 51 at the earliest.

Key takeaways
  • Backtrader does not call next() until every indicator has produced a value, and the strategy minperiod is the maximum over all indicators.
  • bt.indicators.CrossOver needs one previous bar, so with SMA(10) and SMA(50) the earliest possible cross is detected on bar 51.
  • If the feed has fewer bars than the slowest period, next() never runs and Backtrader reports no error, so assert len(df) before cerebro.run().
  • Test for a cross event (CrossOver > 0), not a state (fast > slow), or you will buy on the first valid bar.
  • Orders placed in next() fill on the following bar, so the first trade appears one bar after the first signal.

Why does my Backtrader SMA crossover place no trades?

Most of the time it is normal warm-up, not a bug. An SMA(N) averages N closes, so it has no valid value until bar N. Backtrader calls this the minimum period (minperiod) of the indicator.

The strategy's minperiod is the largest minperiod among its indicators. Until the bar count reaches it, Backtrader calls prenext() instead of next(), and your trading logic inside next() never runs. With SMA(10) and SMA(50) the minperiod is 50, so bars 1 to 49 are skipped.

A crossover adds one more bar. A cross is a comparison between the current and the previous bar, so bt.indicators.CrossOver has minperiod max(fast, slow) + 1. With SMA(10), SMA(50) and CrossOver, next() first fires on bar 51.

The failure that confuses beginners is short data. If the feed has 40 bars and the slow SMA is 50, no indicator ever becomes valid, next() is never called, and cerebro.run() finishes cleanly with zero trades and no warning.

How is minperiod calculated when indicators are combined?

Backtrader propagates minperiod through the indicator graph. An indicator's minperiod is the minperiod of its inputs plus its own extra requirement, minus one where the indicator's first output coincides with its first full window. The strategy then takes the maximum over everything it owns.

Formula for parallel indicators: strategy minperiod = max(minperiod of each indicator). For a fast SMA(10) and slow SMA(50) that is 50, not 60.

Formula for chained indicators: the periods add, minus one for each link. An SMA(10) of an SMA(50) needs 50 + 10 - 1 = 59 bars. An indicator built on RSI(14) inherits the RSI's minperiod before adding its own, and a smoothed RSI such as SMA(RSI, 5) has a larger warm-up than either part alone.

SetupStrategy minperiodFirst next() call
SMA(10) + SMA(50)50bar 50
SMA(10) + SMA(50) + CrossOver51bar 51
SMA(SMA(50), 10)59bar 59
SMA(10), SMA(50), SMA(200) + CrossOver(10,50)200bar 200
Any of the above on 1 hour bars resampled from 1 minute datasame count, in resampled bars60 times more raw bars
Tip: You cannot skip warm-up by setting minperiod to 0. If your own logic needs extra history, call self.addminperiod(n) in __init__ to raise the strategy's minperiod.

What is the difference between prenext, nextstart and next?

prenext() runs on every bar while at least one indicator is still warming up. nextstart() runs exactly once, on the first bar where all indicators are valid, and its default implementation simply calls next(). next() then runs on every later bar.

The script below is runnable with synthetic data. It prints the bar number where each stage begins, plus the first bar where CrossOver fires. Needs backtrader, pandas and numpy installed.

import backtrader as bt, numpy as np, pandas as pd

class Probe(bt.Strategy):
    params = (('fast', 10), ('slow', 50))

    def __init__(self):
        f = bt.ind.SMA(period=self.p.fast)
        s = bt.ind.SMA(period=self.p.slow)
        self.cross = bt.ind.CrossOver(f, s)
        self.last_pre = 0
        self.first_signal = None
        self.order = None

    def prenext(self):
        self.last_pre = len(self)

    def nextstart(self):
        print(f'last prenext bar={self.last_pre}, '
              f'nextstart bar={len(self)}, minperiod={self._minperiod}')
        super().nextstart()   # calls next()

    def next(self):
        if self.cross[0] != 0 and self.first_signal is None:
            self.first_signal = len(self)
            print(f'first CrossOver signal on bar {len(self)}: {self.cross[0]:+.0f}')
        if self.order:        # an order is pending
            return
        if not self.position and self.cross[0] > 0:
            self.order = self.buy(size=1)
        elif self.position and self.cross[0] < 0:
            self.order = self.close()

    def notify_order(self, order):
        if order.status in (order.Completed, order.Canceled, order.Margin, order.Rejected):
            print(f'bar {len(self)} order status: {order.getstatusname()}')
            self.order = None

rng = np.random.default_rng(7)
close = 100 + np.cumsum(rng.normal(0, 1, 400))
idx = pd.bdate_range('2022-01-03', periods=400)
df = pd.DataFrame({'open': close, 'high': close + 1, 'low': close - 1,
                   'close': close, 'volume': 1000}, index=idx)

assert len(df) > 50 + 1, 'feed shorter than slowest period + 1: next() will never run'
cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.PandasData(dataname=df))
cerebro.addstrategy(Probe, fast=10, slow=50)
cerebro.broker.setcash(10000)
cerebro.run()

How do I check the data is long enough before running?

Do the arithmetic before cerebro.run(). The feed must exceed the strategy minperiod, and it should leave enough bars afterwards to see several crossovers. A workable rule of thumb is slow period + 1 + at least 5 to 10 times the slow period, which is far more than the bare minimum but gives the signal logic room to produce events.

Inside next(), len(self.data) and len(self) both count the bars processed so far. For a single-feed strategy they are identical, so comparing them tells you nothing about how long the feed is. To get the loaded length, use len(df) before cerebro.run(), or self.data.buflen() once the data is loaded.

self._minperiod shows the computed warm-up. Printing len(self) at the first next() call, as in the script above, is the most direct way to answer how many bars were skipped.

  1. Compute needed = slow + 1 for CrossOver (add more for chained indicators using the table above).
  2. Assert len(df) > needed before building the feed, and warn if len(df) < needed * 6.
  3. In the strategy, print self._minperiod from nextstart() and compare with the bar count you expected.
  4. If nextstart() never prints, the feed is too short or empty. Print len(df) and df.index.min() / df.index.max() after loading.
  5. Also check how many rows survive the fromdate/todate arguments, since they apply after loading and cut the bars the indicators can use.
slow = 50
needed = slow + 1
assert len(df) > needed, f'only {len(df)} bars, need more than {needed}'
if len(df) < needed * 6:
    print('warning: few bars after warm-up, expect very few crossovers')

How do I write crossover logic without off-by-one errors?

In Backtrader, [0] is the current bar and [-1] is the previous bar. Negative indexes go back in time, and [1] would be the future, which does not exist in live running. Mixing this up gives look-ahead errors or IndexErrors.

The most common logic error is testing a state instead of an event. fast[0] > slow[0] is true on every bar of an uptrend, so the strategy buys on the first valid bar if the fast SMA already sits above the slow one. A cross is the transition: above now, not above on the previous bar.

CrossOver returns +1 on the bar where fast crosses above slow, -1 where it crosses below, and 0 otherwise. A hand-written equivalent is below. Using <= for the previous bar means an equal value counts as not yet above, so a cross out of equality is caught once. Using < would miss it, and using >= on both bars could fire twice.

def __init__(self):
    self.fast = bt.ind.SMA(period=10)
    self.slow = bt.ind.SMA(period=50)
    self.cross = bt.ind.CrossOver(self.fast, self.slow)
    self.order = None

def next(self):
    if self.order:                 # pending order: do not stack another
        return
    # hand-written equivalent of cross > 0
    up = self.fast[0] > self.slow[0] and self.fast[-1] <= self.slow[-1]
    down = self.fast[0] < self.slow[0] and self.fast[-1] >= self.slow[-1]
    if not self.position and up:   # same as self.cross[0] > 0
        self.order = self.buy()
    elif self.position and down:   # same as self.cross[0] < 0
        self.order = self.close()
Warning: The hand-written version needs self.fast[-1], so it requires one extra bar of history, which is exactly why the first detectable cross is on bar slow + 1. Also remember the fill timing: an order placed in next() executes at the next bar's open by default, so the first trade appears one bar after the first signal. See our next-bar-open article for details.

What else causes no trades after warm-up is over?

If nextstart() printed and CrossOver fired but the trade log is still empty, the problem is downstream of the indicators. Use this table to isolate it, and log order statuses in notify_order() so rejections are visible.

SymptomLikely causeFix
next() never called, no errorFeed shorter than minperiodLoad more history or lower periods; add the pre-run assertion
nextstart bar is much later than expectedChained indicator or resampled dataPrint self._minperiod; count periods in resampled bars
Signal prints but order status is Margin or RejectedCash too small, or sizer asks for more than cash allowsCheck broker.getcash() against price times size; see our margin article
Order Completed with size 0 or no order at allDefault sizer is 1 share but your own size is computed as 0 by integer roundingPrint the computed size; use a fixed size to test
Feed has 0 or few rowsWrong datetime or column mapping, unsorted dates, wrong date formatPrint df.head() and df.index.is_monotonic_increasing; see our PandasData article
Fewer bars than the file holdsfromdate/todate cut the data, or the date parse made everything NaTPrint len(df) after filters, and the first and last timestamps
Buy only once, then nothingPosition stays open, or self.order never clearedReset self.order in notify_order() on Completed, Canceled, Margin, Rejected
Trade fires on the very first valid barState test (fast > slow) instead of cross eventUse CrossOver or add the [-1] comparison

How do I fix warm-up problems and read the plot correctly?

There are two honest fixes. Either lower the periods, passing them as parameters with cerebro.addstrategy(Probe, fast=5, slow=20) or optstrategy, or give the feed more history. If you want trades to start on a given date, load data from earlier than that date and let the warm-up consume the extra bars. Do not set fromdate to your trading start, because it removes the bars the indicators need.

The plot shows indicator lines beginning late, and the first values in an indicator's array are NaN. This is expected: Backtrader pads the warm-up region with NaN rather than inventing values. Comparisons with NaN are false, which is another reason signals stay silent early.

Resampled or replayed data multiplies the effect. Periods count bars of the resampled timeframe, so SMA(50) on 1 hour bars built from 1 minute data needs about 50 hours of raw data, and a partial first bar can add one more. If you add both the raw and resampled feeds, the strategy minperiod is driven by the slowest indicator on any feed, and next() waits for all of them.

Use self.addminperiod(n) when your own logic reads self.data.close[-n] or similar and no indicator covers that range. This raises the strategy minperiod so that next() is not called until the history exists.

Common questions

Is it a bug if prenext() runs hundreds of times?

Not by itself. prenext() runs once per bar until all indicators are valid, so a slow SMA(200) or a chained indicator means about 200 calls. It is only suspicious if it runs on every bar of the feed, which points to short data or a longer minperiod than you expected.

Can I trade during prenext()?

You can place orders in prenext(), but indicator values there are NaN, so signals are unreliable. The cleaner approach is to let the warm-up finish. If you need trading in the warm-up window, use a shorter indicator for that period or override prenext() with a simpler rule.

Why does my trade appear one bar after fast > slow becomes true?

CrossOver does not lag. It reports +1 on the same bar where fast is strictly above slow, after the last non-zero difference was negative. The delay you see comes from execution: an order placed in next() fills at the next bar's open by default. If fast and slow are exactly equal on one bar, the signal waits until the first bar where fast is strictly above.

How many bars do I need for a meaningful SMA crossover test?

The minimum is slow + 1, but with only that many bars you will see zero or one cross. Aim for several multiples of the slow period so there are multiple crossovers, and remember that fills happen on the bar after the signal.

Why are there no trades even though the data is long enough and the signal prints?

Check notify_order() output. Margin, Rejected or Canceled statuses mean the broker refused the order, usually due to cash, size or a pending order blocking later logic. If no order object is created at all, the sizing or position check in your own code is skipping it.

Related topics:backtraderpythonbacktestingsma crossoverindicators