I am trying to use the backtrader
package in Python 3.8 to run a backtest on AAPL
historical stock prices obtained from Yahoo Finance using backtrader
's YahooFinanceData
module.
Problem: The data appears to be downloaded from Yahoo Finance, but during the backtesting process, we get an error:
FileNotFoundError: [Errno 2] No such file or directory: 'AAPL'
Any idea how we can solve this problem?
System:
Python Code to Reproduce Error
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)
Error Stack
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'
Yahoo Finance have changed their output recently, specifically the content type of the API response('text/csv' is expected but 'text/plain' is returned). To fix it you have to change to code in the file backtrader/feeds/yahoo.py
In line 330, replace:
if 'text/csv' not in ctype:
With:
if ctype not in ['text/csv', 'text/plain']:
There is a pull request open with backtrader to fix this in the package, but it has not been commited yet.
The error is that the request to Yahoo API fails, and backtrader
then falls back to trying to read local copies of the data but in a way that also fails. The Yahoo API changed a few years ago and backtrader
hasn't been updated since then. This is a big issue as even the tutorial example is broken!
The change @mathias-thorsen mentioned in his answer was proposed to be included in backtrader
in this Pull Request , but it was closed. backtrader
has slowed development and a fork backtrader2
is vying to be its successor. backtrader2
found that a difference fix resolved the root cause of the Yahoo API request failing. They proposed the same fix into the upstream backtrader
in this Pull Request and it was recently merged. With the creator gone though, there's no way to publish a new release to PyPI. backtrader2
also cannot yet take over the PyPI namespace for backtrader
( https://pypi.org/project/backtrader/ ).
So how do you install the fixed version of backtrader
or the more updated backtrader2
if they aren't published on PyPI? You could install the latest development version from GitHub using either
pip install git+https://github.com/mementum/backtrader.git#egg=backtrader
pip install git+https://github.com/backtrader2/backtrader.git#egg=backtrader
There's also an issue when backtrader
uses of the latest matplotlib
, where the fix has been merged, but with no release. You can find similar approaches to install from source ( https://stackoverflow.com/a/66871735/6068036 ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.