Backtrader PandasData Datetime and Column Mapping Fixes
With backtrader pandasdata datetime column handling, datetime=None reads the DataFrame index, so it must be a sorted DatetimeIndex. Other fields are matched by name or mapped explicitly, and a missing field must be set to None.
- PandasData uses the DataFrame index as the datetime by default (datetime=None), so the index must be a sorted, unique, tz-naive DatetimeIndex.
- Each OHLCV parameter accepts a column name, an integer position, None (field absent) or -1 (auto-detect by name).
- Intraday data needs timeframe=bt.TimeFrame.Minutes and compression set, or the feed is treated as daily.
- An empty plot almost always means zero bars after fromdate/todate, all-NaN closes, or an indicator period longer than the data.
- Run a validate_feed(df) check and a tiny printing strategy before relying on any backtest output.
How does the backtrader pandasdata datetime column work?
bt.feeds.PandasData takes a DataFrame as dataname and resolves each line (datetime, open, high, low, close, volume, openinterest) to a column when the feed starts. The defaults are datetime=None, open=-1, high=-1, low=-1, close=-1, volume=-1, openinterest=-1.
datetime=None means the index is the timestamp. The feed calls to_pydatetime() on each index value, so the index must be a pandas DatetimeIndex. A string index or a plain Date column is the single most common reason for a failed feed.
For the price fields, -1 means auto-detect by name. Matching is case-insensitive by default (the nocase parameter is True), so 'Open' usually resolves to the open line. 'Adj Close' never matches anything, and the tuple column names of a MultiIndex never match, so those fields come back missing or NaN.
An integer position (for example close=4) maps by column order in the DataFrame, not by name. None means the field does not exist and the line is filled with NaN. If a column such as openinterest is absent, set openinterest=None explicitly instead of relying on the -1 default.
| Parameter value | Meaning | Typical use |
|---|---|---|
| datetime=None | Use the DataFrame index | Index is already a DatetimeIndex |
| datetime='Date' | Use that column as timestamp | Date column left in the frame |
| datetime=-1 | Auto-detect a column named datetime | Column literally called datetime |
| close='Close' | Map line to this column name | Vendor or Yahoo headers |
| close=4 | Map line to column position 4 | Fixed layout, easy to get wrong |
| openinterest=None | Field absent | No open interest in the data |
| volume=-1 | Auto-detect by name | Lowercase or capitalised names |
What do the symptoms mean? Cause and fix table
Most failures fall into a handful of patterns. Match what you see to the likely cause before changing code.
| Symptom | Likely cause | Fix |
|---|---|---|
| AttributeError: 'str' object has no attribute 'to_pydatetime' | Index holds strings | df.index = pd.to_datetime(df.index) |
| AttributeError on 'Index' object | Index is a RangeIndex because Date is still a column | Use index_col='Date' or pass datetime='Date' |
| KeyError on a column name | Mapped name does not match the header (spaces, case, MultiIndex) | Print df.columns, flatten or rename |
| Empty plot, len(data)==0 | fromdate/todate exclude every row, or tz mismatch | Match type and tz of the index, or drop the filters |
| Empty plot, bars exist, no trades | Indicator period longer than bar count | Lower the period or load more history |
| Plot shows flat or missing candles | All-NaN close or fields mapped to None | Check df.isna().sum() |
| Weird or out-of-order candles | Index unsorted or duplicate timestamps | sort_index(), remove duplicates |
| Intraday data shown as one bar per day | Timeframe left at the Days default | timeframe=bt.TimeFrame.Minutes, compression=5 |
| High below low in the data | Integer positions mapped in the wrong order | Map by name instead |
| Odd error on the whole feed | Path string passed as dataname | Load with pandas or use GenericCSVData |
How do I clean a DataFrame before passing it to PandasData?
Recipe A is the shortest path: normalise names, make the index a clean DatetimeIndex, and sort. This works for yfinance, ccxt-derived frames and most vendor files.
Newer yfinance versions return MultiIndex columns such as ('Close', 'AAPL') even for one ticker. Flatten them first, otherwise name matching fails.
Timezone-aware indexes are another trap: backtrader works with naive datetimes, and comparing them with aware fromdate/todate values raises errors or filters out everything. Decide on a timezone explicitly, convert, then strip it.
import pandas as pd
import backtrader as bt
df = pd.read_csv('prices.csv', parse_dates=['Date'], index_col='Date')
# yfinance MultiIndex columns -> flat names
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.droplevel(1)
df = df.rename(columns=str.lower) # 'Open' -> 'open'
df.index = pd.to_datetime(df.index)
if df.index.tz is not None: # convert, then drop tz
df.index = df.index.tz_convert('UTC').tz_localize(None)
df = df[~df.index.duplicated(keep='last')].sort_index()
df = df.dropna(subset=['open', 'high', 'low', 'close'])
data = bt.feeds.PandasData(dataname=df, openinterest=None)How do I map non-default column names explicitly?
Recipe B skips renaming and maps every field by name. It is the most robust option because a wrong name fails loudly instead of silently filling NaN.
Prefer names over integer positions. Mapping by position depends on column order, and a vendor frame ordered open, close, high, low will silently swap high and low if you assume the OHLC order.
df = pd.read_csv('prices.csv', parse_dates=['Date'], index_col='Date')
data = bt.feeds.PandasData(
dataname=df,
datetime=None, # index is already the Date
open='Open', high='High', low='Low', close='Close',
volume='Volume',
openinterest=None, # column does not exist
)
# Date left as a normal column instead:
# df = pd.read_csv('prices.csv', parse_dates=['Date'])
# data = bt.feeds.PandasData(dataname=df, datetime='Date',
# open='Open', high='High', low='Low', close='Close',
# volume='Volume', openinterest=None) Why is my intraday data read as daily, or my plot empty?
The feed defaults to timeframe=bt.TimeFrame.Days and compression=1. For minute bars, declare the real granularity so resampling, analyzers and the plot axis behave correctly.
fromdate and todate are compared against the feed datetimes. Pass naive datetime objects that match the index, because an aware value against a naive index, or a range outside the data, gives zero bars.
Even with bars loaded, an indicator such as a 200-period moving average delays next() until 200 bars exist. With 150 bars the strategy never runs and the plot looks empty.
import datetime as dt
data = bt.feeds.PandasData(
dataname=df,
timeframe=bt.TimeFrame.Minutes,
compression=5,
fromdate=dt.datetime(2024, 1, 2, 9, 30),
todate=dt.datetime(2024, 3, 29, 16, 0),
openinterest=None,
) How do I validate the feed before cerebro.run()?
Run a structural check on the DataFrame, then a tiny strategy that proves the feed delivers bars. The function below asserts the index type, order, duplicates, NaNs, column names and OHLC sanity.
If the quick strategy prints nothing, check len(data) and your fromdate/todate first.
- Print df.dtypes, df.index[:3] and df.isna().sum() to see types and gaps.
- Call validate_feed(df) and fix whatever it asserts.
- Add the feed to cerebro and run the Probe strategy with a single bar of history.
- Confirm len(data) is above 0 and that the printed open and close match the first CSV rows.
def validate_feed(df):
need = ['open', 'high', 'low', 'close', 'volume']
assert isinstance(df.index, pd.DatetimeIndex), f'index is {type(df.index)}'
assert df.index.tz is None, 'index is tz-aware'
assert df.index.is_monotonic_increasing, 'index not sorted'
assert df.index.duplicated().sum() == 0, 'duplicate timestamps'
missing = [c for c in need if c not in df.columns]
assert not missing, f'missing columns: {missing}'
assert not df[need[:4]].isna().any().any(), 'NaN in OHLC'
assert (df.high >= df[['open', 'close']].max(axis=1)).all(), 'high < open/close'
assert (df.low <= df[['open', 'close']].min(axis=1)).all(), 'low > open/close'
return True
class Probe(bt.Strategy):
def next(self):
d = self.data
print(len(d), d.datetime.datetime(0), d.open[0], d.close[0])
validate_feed(df)
cerebro = bt.Cerebro()
feed = bt.feeds.PandasData(dataname=df, openinterest=None)
cerebro.adddata(feed)
cerebro.addstrategy(Probe)
cerebro.run()
print('bars loaded:', len(feed))How do I add extra columns or load files without pandas?
To expose an extra column such as an adjusted close, subclass PandasData and add a line plus a matching parameter. The -1 default auto-detects the column by name, so give a name explicitly if the header differs.
Never pass a file path to PandasData as dataname. It expects a DataFrame. For files, either load with pandas first or use GenericCSVData, which parses the CSV itself and needs explicit column positions and a dtformat.
class PandasPlus(bt.feeds.PandasData):
lines = ('adj_close',)
params = (('adj_close', -1),)
data = PandasPlus(dataname=df, openinterest=None) # df has 'adj_close'
# in a strategy: self.data.adj_close[0]
# File alternative, columns by 0-based position:
data = bt.feeds.GenericCSVData(
dataname='prices.csv',
dtformat='%Y-%m-%d',
datetime=0, open=1, high=2, low=3, close=4, volume=5,
openinterest=-1, # -1 here means column absent
headers=True,
)Common questions
Can PandasData use a Date column instead of the index?
Yes. Pass datetime='Date' (the column name) and the feed reads timestamps from that column. The column must be a datetime64 dtype, so use parse_dates or pd.to_datetime first.
Why does openinterest cause problems when my data has none?
The default is -1, which tries to auto-detect a column named openinterest. When none exists, the safest fix is to pass openinterest=None so the line is deliberately empty instead of depending on detection.
Do I need to adjust yfinance data before loading it?
You need flat, consistent column names and a tz-naive sorted index. Prices may already be split and dividend adjusted depending on the download option, so decide which close you want and map that column to close.
Why do my dates show as 1970 or look shifted?
A numeric epoch index, such as milliseconds from ccxt, was not converted. Use pd.to_datetime(df['ts'], unit='ms'), then set it as the index. Timezone conversion before tz_localize(None) also determines which wall-clock times you see.
Can I change the DataFrame after creating the feed?
Avoid it. The feed reads from the frame when cerebro starts, so edits after construction can produce inconsistent bars. Finish all cleaning, then create PandasData as the last step.