Backtrader - 索引错误:列表索引超出范围
我正在尝试通过下面的脚本 "backtrader_impact.py" 从我生成的一个叫 "impact.csv" 的csv文件中加载自定义数据。
但是,在执行 "cerebro.adddata(data)" 时,我遇到了一个错误:IndexError: list index out of range(索引错误:列表索引超出范围)。
File "C:\...\backtrader\feeds\csvgeneric.py", line 151, in _loadline
csvfield = linetokens[csvidx]
IndexError: list index out of range
backtrader_impact.py:
import backtrader as bt
class ImpactCSVData(bt.feeds.GenericCSVData):
lines = ('impact_score',)
params = (
('dtformat', '%Y/%m/%d %H:%M:%S'), # Datetime format
('datetime', 0), # Index of the datetime column in the CSV
('impact_score', 1), # Index of the impact_score column in the CSV
('timeframe', bt.TimeFrame.Minutes), # Timeframe (adjust accordingly)
)
data = ImpactCSVData(
dataname='alpaca_backtrader/impact.csv', # Path to your CSV file
)
cerebro = bt.Cerebro()
cerebro.adddata(data)
# cerebro.addstrategy(YourStrategy)
cerebro.run()
# cerebro.plot()
impact.csv:
datetime,impact_score
2023/01/13 00:00:00,96
2023/01/13 00:15:00,75
2023/01/13 00:30:00,58
我尝试通过在 backtrader\feeds\csvgeneric.py(在 backtrader 包中)添加一些打印语句来进行调试:
for linefield in (x for x in self.getlinealiases() if x != 'datetime'):
# Get the index created from the passed params
csvidx = getattr(self.params, linefield)
if csvidx is None or csvidx < 0:
# the field will not be present, assignt the "nullvalue"
print(f"Processing line tokens: {linetokens}, with csvidx: {csvidx}")
csvfield = self.p.nullvalue
else:
# get it from the token
# FIXME: failing here. trying to access index 4 of list of 2 items
print(f"Processing line tokens: {linetokens}, with csvidx: {csvidx}")
csvfield = linetokens[csvidx]
if csvfield == '':
# if empty ... assign the "nullvalue"
print(f"Processing line tokens: {linetokens}, with csvidx: {csvidx}")
csvfield = self.p.nullvalue
What is printed:
Processing line tokens: ['2023/01/13 00:00:00', '96'], with csvidx: 4
出于某种原因,它试图访问 linetokens 的索引 4,但 linetokens 只有 ['2023/01/13 00:00:00', '96'],长度只有 2。
希望能得到你的帮助!谢谢。
1 个回答
0
我在想把自定义的csv文件导入数据源时也遇到了同样的问题。GenericCSVData()
这个类的问题在于,它会强制寻找日期、开盘价、最高价、最低价、最低价、收盘价和成交量这几列,而不管你的文件里有什么。
你代码的第一个问题是,你输入的csv文件只有两列,但这个类需要六列。当它试图查找data.csv[3]
时,就会超出范围。
第二个问题是,你没有输入impact_score
的值。你应该调整一下lines = ('impact_score', 7)
,然后在自定义数据源里要明确你的数据的索引。
data = ImpactCSVData(
dataname='alpaca_backtrader/impact.csv',
datetime=0,
open=1,
high=2,
low=3,
close=4,
volume=5,
openinterest=6,
impact_score=7
)
After this you can fill in your CSV file with dummy data for OHLCV and then you can access the impact score like you mentioned.