我正在尝试使用Python 3.8 中的backtrader
包对使用's模块AAPL
从 Yahoo Finance 获得的历史股票价格进行回测。backtrader
YahooFinanceData
问题:数据似乎是从雅虎财经下载的,但在回测过程中,我们得到一个错误:
FileNotFoundError:[Errno 2] 没有这样的文件或目录:'AAPL'
知道我们如何解决这个问题吗?
系统:
- Mac OS X 10.15.3
- Python 3.8.0
- 反向交易者 1.9.74.123
重现错误的 Python 代码
from datetime import datetime
import backtrader as bt
class SmaSignal(bt.Signal):
param = (('period', 20), )
def __init__(self):
self.lines.signal = self.data - bt.ind.SMA(period=self.p.period)
data = bt.feeds.YahooFinanceData(dataname='AAPL',
fromdate=datetime(2018, 1, 1),
todate=datetime(2018, 12, 31))
cerebro = bt.Cerebro(stdstats=False)
cerebro.adddata(data)
cerebro.broker.setcash(1000.0)
cerebro.add_signal(bt.SIGNAL_LONG, SmaSignal)
cerebro.addobserver(bt.observers.BuySell)
cerebro.addobserver(bt.observers.Value)
print(f'Starting Portfolio Value: {cerebro.broker.getvalue():.2f}')
cerebro.run()
print(f'Final Portfolio Value: {cerebro.broker.getvalue():.2f}')
cerebro.plot(iplot=True, volume=False)
错误堆栈
Traceback (most recent call last):
File "02.py", line 21, in <module>
cerebro.run()
File "/Users/x/opt/anaconda3/envs/test/lib/python3.8/site-packages/backtrader/cerebro.py", line 1127, in run
runstrat = self.runstrategies(iterstrat)
File "/Users/x/opt/anaconda3/envs/test/lib/python3.8/site-packages/backtrader/cerebro.py", line 1210, in runstrategies
data._start()
File "/Users/x/opt/anaconda3/envs/test/lib/python3.8/site-packages/backtrader/feed.py", line 203, in _start
self.start()
File "/Users/x/opt/anaconda3/envs/test/lib/python3.8/site-packages/backtrader/feeds/yahoo.py", line 352, in start
super(YahooFinanceData, self).start()
File "/Users/x/opt/anaconda3/envs/test/lib/python3.8/site-packages/backtrader/feeds/yahoo.py", line 94, in start
super(YahooFinanceCSVData, self).start()
File "/Users/x/opt/anaconda3/envs/test/lib/python3.8/site-packages/backtrader/feed.py", line 674, in start
self.f = io.open(self.p.dataname, 'r')
FileNotFoundError: [Errno 2] No such file or directory: 'AAPL'