当我试图运行在github上找到的backtrader示例设置代码时,我遇到了这个错误。在做了一些研究后,我发现这个错误可能源于Yahoo Finance API过期或不再与backtrader包兼容。我计划使用在线数据馈送进行我想要做的回溯测试,所以有人知道我如何解决yahoo数据馈送问题吗?一些在线来源建议深入研究源代码。我已经尝试了这些建议,但都没有效果。
from datetime import datetime
import backtrader as bt
class SmaCross(bt.SignalStrategy):
def __init__(self):
sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
crossover = bt.ind.CrossOver(sma1, sma2)
self.signal_add(bt.SIGNAL_LONG, crossover)
cerebro = bt.Cerebro()
cerebro.addstrategy(SmaCross)
data0 = bt.feeds.YahooFinanceData(dataname='AAPL', fromdate=datetime(2011, 1, 1),
todate=datetime(2012, 12, 31))
cerebro.adddata(data0)
cerebro.run()
cerebro.plot()错误堆栈:
---------------------------------------------------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-2-4abfaa589128> in <module>
12 cerebro.adddata(data0)
13
---> 14 cerebro.run()
15 cerebro.plot()
~/opt/anaconda3/lib/python3.8/site-packages/backtrader/cerebro.py in run(self, **kwargs)
1125 # let's skip process "spawning"
1126 for iterstrat in iterstrats:
-> 1127 runstrat = self.runstrategies(iterstrat)
1128 self.runstrats.append(runstrat)
1129 if self._dooptimize:
~/opt/anaconda3/lib/python3.8/site-packages/backtrader/cerebro.py in runstrategies(self, iterstrat, predata)
1208 if self._exactbars < 1: # datas can be full length
1209 data.extend(size=self.params.lookahead)
-> 1210 data._start()
1211 if self._dopreload:
1212 data.preload()
~/opt/anaconda3/lib/python3.8/site-packages/backtrader/feed.py in _start(self)
201
202 def _start(self):
--> 203 self.start()
204
205 if not self._started:
~/opt/anaconda3/lib/python3.8/site-packages/backtrader/feeds/yahoo.py in start(self)
354
355 # Prepared a "path" file - CSV Parser can take over
--> 356 super(YahooFinanceData, self).start()
357
358
~/opt/anaconda3/lib/python3.8/site-packages/backtrader/feeds/yahoo.py in start(self)
92
93 def start(self):
---> 94 super(YahooFinanceCSVData, self).start()
95
96 if not self.params.reverse:
~/opt/anaconda3/lib/python3.8/site-packages/backtrader/feed.py in start(self)
672 else:
673 # Let an exception propagate to let the caller know
--> 674 self.f = io.open(self.p.dataname, 'r')
675
676 if self.p.headers:
FileNotFoundError: [Errno 2] No such file or directory: 'AAPL'发布于 2021-07-09 23:50:13
这是本周突然出现的一个问题。我们已经在Backtrader2 here上修复了这个问题。创建Backtrader2是为了保持紧急的错误修复是最新的,因为最初的backtrader现在是一个封闭的回购。
如果您愿意,只有一行更改。您可以调整您的本地backtrader文件以匹配以下内容:https://github.com/backtrader2/backtrader/pull/67/files
在文件backtrader/feeds/yahoo.py中,您将在第269行找到以下代码:
crumb = None
sess = requests.Session()在下一行添加以下代码:
sess.headers['User-Agent'] = 'backtrader'https://stackoverflow.com/questions/68305725
复制相似问题