I am trying to write a backtesting strategy on Backtrader in Python, and below is the code that is giving me the error. I am using the latest version of backtrader as of July 2, 2021.
import backtrader as bt
import backtrader.feeds as btfeeds
from datetime import datetime
cerebro = bt.Cerebro()
cerebro.broker.setcash(100000)
data = btfeeds.YahooFinanceData(dataname="SPY", fromdate=datetime(2016, 6, 25),
todate=datetime(2021, 6, 25))
cerebro.adddata(data)
cerebro.run()
The error that I am getting is
Traceback (most recent call last): File "c:\Users\risha\PycharmProjects\PythonDataScience\BacktraderBacktesting\TestingData.py", line 9, in cerebro.run() File "C:\Users\risha\anaconda3\lib\site-packages\backtrader\cerebro.py", line 1127, in run runstrat = self.runstrategies(iterstrat) File "C:\Users\risha\anaconda3\lib\site-packages\backtrader\cerebro.py", line 1210, in runstrategies data._start() File "C:\Users\risha\anaconda3\lib\site-packages\backtrader\feed.py", line 203, in _start self.start() File "C:\Users\risha\anaconda3\lib\site-packages\backtrader\feeds\yahoo.py", line 355, in start super(YahooFinanceData, self).start() File "C:\Users\risha\anaconda3\lib\site-packages\backtrader\feeds\yahoo.py", line 94, in start super(YahooFinanceCSVData, self).start() File "C:\Users\risha\anaconda3\lib\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: 'SPY'
I am confused on why this is happening. I have tried running this by adding a strategy in Cebro as well, but that still caused the same error. Could someone please help me fix this issue?
I actually figured out the solution. If you use, the code:
import yfinance as yf
data = bt.feeds.PandasData(dataname=yf.download('SPY', '2015-07-06', '2021-07-01', auto_adjust=True))
This will allow you to get the data from online for any ticker. You will also have to use:
pip install yfinance
before you run this code.