Howwise RSS
Trading Software7 min read

Backtrader IndexError: Array Assignment Index Out of Range

Short answer

A backtrader index out of range error, including 'array assignment index out of range', comes from reading or writing line buffers that are short, empty or reused: uneven feeds, too-early data[-n] access, or a reused feed. Align feeds, guard next(), recreate feeds.

Key takeaways
  • Backtrader aligns feeds by datetime against data0, not by row index, and a feed with no bar at that time repeats its previous bar.
  • next() runs only after the largest minperiod across all feeds and indicators is met, so late-starting feeds delay every strategy.
  • Reindexing every feed to one calendar with ffilled prices, zero volume and a padded flag removes most misalignment errors.
  • Build per-data indicators in __init__ with enumerate(self.datas) and named feeds instead of hard-coding self.datas[2].
  • Recreate PandasData objects for every cerebro run, because reused feeds carry exhausted or mis-sized buffers.

What causes the backtrader index out of range error with array assignment?

Backtrader stores every line (open, close, indicator output) in a LineBuffer. In the default mode this wraps Python's array.array, and the message 'array assignment index out of range' comes from writes to a line buffer, because array.array raises that exact message only on assignment. A backtrader index out of range error is a symptom, not a diagnosis.

The read-side causes produce a different message, 'array index out of range'. These include accessing data.close[-5] before five bars exist, an empty DataFrame that yields zero bars, and a feed that is exhausted while others continue. An indexed self.datas[i] past the end of what was added raises 'list index out of range', because self.datas is a plain Python list. Reusing a feed object that already ran in a previous cerebro.run() leaves buffers in an inconsistent state and can surface as any of these.

Do not confuse this with the lookback problem. If len(data) < indicator period, backtrader normally just stays in prenext() and never errors. The IndexError appears when your own code reads past what exists, or when buffers are in an inconsistent state.

How does Backtrader synchronize feeds with different dates?

data0 is the master clock. On each cycle backtrader loads the next bar of data0, then advances every other feed only if that feed's next bar has a datetime less than or equal to the master's current datetime. If a feed has no bar for that time, it keeps its previous bar and its values are stale.

So alignment is by datetime, never by row index. If data1 starts later than data0, data1 holds no valid bars at first, and len(data1) stays 0. Reading data1.close[0] then fails or returns junk. A feed that ends early simply repeats its last bar until data0 ends.

Holidays matter here: a stock feed and a crypto feed (7 days a week) differ in length, and if the crypto feed is data0 the stock feed repeats Friday's close over the weekend.

Minimum period mechanics: when does next() actually run?

Each indicator adds its period to the minperiod of the data it uses, and the strategy minperiod is the maximum across all feeds and indicators. prenext() is called until every one is satisfied, then nextstart() once, then next() on each bar.

Because all feeds are considered, one late-starting feed pushes the start of the whole strategy to its first usable bar. Cross-feed indicators such as a spread of data1 and data0 take the longest minperiod of their inputs.

With runonce=True (the default) indicators are computed vectorized across whole buffers using once() methods, which assume buffers are fully loaded and consistent. Unequal lengths, or custom indicators without a correct once(), can raise array errors there. runonce=False forces bar-by-bar next() computation, which is slower but far more tolerant.

SettingBehaviourUse when
runonce=TrueVectorized once(), fast, assumes full buffersClean, aligned data
runonce=FalseEvent-style next(), tolerant of uneven feedsDebugging unequal lengths
exactbars=False (default)Keeps all bars in memoryPlotting, reused feeds
exactbars=1/-1/-2Memory-saving, disables plotting and some featuresHuge datasets only
Tip: First test: cerebro.run(runonce=False). If the error disappears, the cause is in a once() path or uneven buffers, and you should align the data.

Minimal reproducible example: two feeds with different start dates

The script below builds two feeds where the second starts 30 bars later and reads its value unguarded. Run it with an indicator whose period is longer than the shorter feed to also see the lookback behaviour.

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

def make(start, n):
    idx = pd.bdate_range(start, periods=n)
    p = np.linspace(100, 120, n)
    return pd.DataFrame({'open':p,'high':p+1,'low':p-1,'close':p,'volume':1000}, index=idx)

df0 = make('2023-01-02', 100)
df1 = make('2023-02-13', 70)   # starts later

class Bad(bt.Strategy):
    def __init__(self):
        self.sma = bt.ind.SMA(self.datas[1], period=10)
    def next(self):
        # hard-coded index, no guard, assumes both feeds aligned
        spread = self.datas[0].close[0] - self.datas[1].close[-5]
        print(len(self.datas[0]), len(self.datas[1]), spread)

cerebro = bt.Cerebro()
cerebro.adddata(bt.feeds.PandasData(dataname=df0), name='A')
cerebro.adddata(bt.feeds.PandasData(dataname=df1), name='B')
cerebro.addstrategy(Bad)
cerebro.run()

How do I diagnose which feed or indicator is short?

Check feeds before running, then print per-bar state inside the strategy. Look for zero lengths, mismatched dates and repeated stale bars.

  1. Before cerebro.run(), print len(df), df.index.is_monotonic_increasing, df.index.has_duplicates, df.index.tz and df.isna().sum() for every DataFrame.
  2. Confirm the DataFrame is not empty and the index is a DatetimeIndex. PandasData uses the index as datetime by default (datetime=None).
  3. In next(), print name, len(d) and d.datetime.date(0) for every feed and compare them to data0.
  4. After a run, d.buflen() gives the total bars loaded for that feed. Compare these across feeds.
  5. Run once with runonce=False and once with True to isolate vectorized failures.
class Diag(bt.Strategy):
    def prenext(self):
        self.log('PRE')
    def next(self):
        self.log('RUN')
    def log(self, tag):
        m = self.data0.datetime.date(0)
        for d in self.datas:
            stale = len(d) == 0 or d.datetime.date(0) != m
            dt = d.datetime.date(0) if len(d) else None
            print(tag, d._name, 'len', len(d), 'date', dt, 'STALE' if stale else '')
Warning: Timezone-aware indexes mixed with naive ones cause silent misalignment or comparison errors. Strip with df.index = df.index.tz_localize(None) after converting to one zone (usually UTC).

How do I align feeds with pandas so the error goes away?

The most robust fix is to give every feed identical rows before backtrader sees it. Choose a union calendar to keep all days, or an intersection to keep only common days. Intersection loses data but avoids padded bars entirely.

Prefer the union plus a flag column for padded bars, so the strategy can refuse to trade symbols with no real bar that day. Never backfill: it leaks future prices (look-ahead bias). Leading NaNs before a symbol's first real bar should stay out of the feed or be flagged, not filled.

def align(frames, how='union'):
    idx = None
    for df in frames.values():
        idx = df.index if idx is None else (idx.union(df.index) if how=='union' else idx.intersection(df.index))
    out = {}
    for k, df in frames.items():
        df = df[~df.index.duplicated(keep='last')].sort_index()
        r = df.reindex(idx)
        r['padded'] = r['close'].isna().astype(float)
        r['close'] = r['close'].ffill()
        for c in ('open','high','low'):
            r[c] = r[c].fillna(r['close'])
        r['volume'] = r['volume'].fillna(0)
        r = r.dropna(subset=['close'])   # leading rows before first real bar
        out[k] = r
    return out

class PData(bt.feeds.PandasData):
    lines = ('padded',)
    params = (('padded', -1),)   # -1 = auto-detect column by name

aligned = align({'A': df0, 'B': df1})
cerebro = bt.Cerebro()
for name, df in aligned.items():
    cerebro.adddata(PData(dataname=df), name=name)
Tip: After dropping leading rows, feeds still start on different dates. Either use the intersection start for every feed or use fromdate (next section) to cut all to the same window.

Which fix fits which symptom? Decision table plus safe next() patterns

Fix 2 is fromdate/todate on every feed. They must be datetime objects (datetime.datetime(2023,2,13)), not strings, and the data must actually begin on or before that date or the feed starts at its own first bar.

Fix 3 is a guard in next(). Skip a symbol when its bar is stale, and override prenext() to call next() only if you accept that some indicators are not yet ready. Check len(indicator) or the indicator value for NaN before use.

Loop with enumerate(self.datas), create indicators per data in __init__, keep them in a dict keyed by d._name, and add feeds with cerebro.adddata(data, name='AAPL'). Never hard-code self.datas[2]. Resampled feeds must be added with cerebro.resampledata(data, timeframe=bt.TimeFrame.Weeks) after the base feed, so data1 is the slower one.

SymptomLikely causeFix
IndexError on data1[-n] earlyReading before enough barsGuard with len(d) > n, or align and trim
Bars off, repeated pricesDifferent calendars, stale barsReindex with union calendar and padded flag
Strategy starts very lateLate feed sets max minperiodUse fromdate/todate or per-feed logic
next() never runsA feed is empty or too shortCheck len(df), index parse, column mapping
Error on second cerebro.run()Feed object reusedRecreate PandasData each run
Error only when vectorizedonce() path with uneven buffersrunonce=False, then align
Error in plot or analyzerShort data or odd buffersTest without plot, align, exactbars=False
class Safe(bt.Strategy):
    def __init__(self):
        self.smas = {d._name: bt.ind.SMA(d, period=20) for d in self.datas}
    def prenext(self):
        self.next()          # run even when some feeds are not ready
    def next(self):
        m = self.data0.datetime.date(0)
        for i, d in enumerate(self.datas):
            if len(d) < 1 or d.datetime.date(0) != m:
                continue      # empty or stale bar
            sma = self.smas[d._name]
            if len(sma) == 0 or sma[0] != sma[0]:   # not ready or NaN
                continue
            print(d._name, d.close[0], sma[0])
Warning: prenext() calling next() bypasses the minperiod protection, so every indicator access must be guarded as shown or you recreate the IndexError.

Other triggers and a final checklist

Wrong column mapping is a common source of a backtrader index out of range failure: PandasData expects columns named open, high, low, close, volume, openinterest by default, case-sensitive for auto-detection. Rename or pass close=3-style column indexes. Adding the same feed object twice, or reusing one after cerebro.run(), leaves buffers already filled; always create new PandasData objects per run, and do not rely on exactbars to cure it.

Version issues: older backtrader (1.9.78.123) with NumPy 1.24+ can fail on removed aliases such as np.bool, and pinned pandas versions can break PandasData parsing. Pin compatible versions in a virtual environment.

Checklist: non-empty frames, sorted unique DatetimeIndex, tz handled, NaNs handled, one calendar, named feeds, per-data indicators, guarded next(), fresh feeds per run, runonce=False when debugging.

Common questions

Why does Backtrader give different results when I change which feed is data0?

data0 is the master clock, so its calendar decides when next() fires and which other bars are considered stale. A crypto feed as data0 produces weekend bars where stock feeds repeat Friday. Put the intended trading calendar first, or align all feeds.

Does Backtrader pad missing bars automatically?

No. It repeats the previous bar of a feed that has no data at the master's datetime, but it does not create a flagged or zero-volume bar. Pad explicitly with pandas if the strategy must know a bar was missing.

Is it safe to use fromdate with PandasData?

Yes, provided it is a datetime object and matches the index type. It trims earlier rows but cannot create rows if the data starts later, so a late feed still starts at its own first bar.

Can I run cerebro twice with the same data feeds?

Not reliably. Feeds keep loaded buffers and iteration state, so build fresh PandasData objects and a fresh Cerebro for every run, for example in a function that returns configured Cerebro.

Why does my indicator return nan on a late-starting feed?

Until the indicator has its period of real bars it has no valid value. Check len(indicator) and NaN before use, or set the strategy to skip that symbol until enough bars exist.

Related topics:backtraderpythonpandasbacktestingdata-feeds