Help With YahooFinance Data
-
I am trying to get some YahooFinance Data to backtest my strategy. Below is the code that I am running.
import backtrader as bt import backtrader.feeds as btfeeds from datetime import datetime cerebro = bt.Cerebro() cerebro.broker.setcash(100000) data = btfeeds.YahooFinanceData(dataname="MSFT", fromdate=datetime(2016, 6, 25), todate=datetime(2021, 6, 25)) cerebro.adddata(data) cerebro.run()
This is the error that I am getting:
Traceback (most recent call last): File "c:\Users\risha\PycharmProjects\PythonDataScience\BacktraderBacktesting\TestingData.py", line 10, in <module> 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: 'MSFT'
Could someone please help me solve this?
-
@rishabmah5 Please use yfinance to download data from yahoo finance.
pip install yfinance
And use this code
import yfinance as yf import backtrader as bt data = bt.feeds.PandasData(dataname=yf.download('TSLA', '2018-01-01', '2019-01-01')) cerebro = bt.Cerebro() cerebro.adddata(data)
-
@dim-trader
Thank you soo much -
@rishabmah5 This is a known error that was just fixed on Backtrader2 today. See here for the fix. You can install backtrader two, or just add the one line in to your backtrader library in
feeds/yahoo.py
-
from datetime import datetime import backtrader as bt from backtrader import plot import yfinance as yf # Create a subclass of Strategy to define the indicators and logic class SmaCross(bt.Strategy): # list of parameters which are configurable for the strategy params = dict( pfast=50, # period for the fast moving average pslow=200 # period for the slow moving average ) def __init__(self): sma1 = bt.ind.SMA(period=self.p.pfast) # fast moving average sma2 = bt.ind.SMA(period=self.p.pslow) # slow moving average self.crossover = bt.ind.CrossOver(sma1, sma2) # crossover signal def next(self): if not self.position: # not in the market if self.crossover > 0: # if fast crosses slow to the upside self.buy() # enter long elif self.crossover < 0: # in the market & cross to the downside self.close() # close long position cerebro = bt.Cerebro() # create a "Cerebro" engine instance cerebro.broker.setcash(100000) # Create a data feed data = bt.feeds.PandasData(dataname=yf.download('KPITTECH.NS', '2019-01-01', '2021-07-06')) cerebro.adddata(data) # Add the data feed cerebro.addstrategy(SmaCross) # Add the trading strategy cerebro.run() # run it all cerebro.plot() # and plot it with a single command this is my code⬆️ and this is the error⬇️ Traceback (most recent call last): File "/Users/madhurjodhwani/Desktop/python/hey.py", line 37, in <module> cerebro.plot() # and plot it with a single command File "/opt/homebrew/lib/python3.9/site-packages/backtrader/cerebro.py", line 974, in plot from . import plot File "/opt/homebrew/lib/python3.9/site-packages/backtrader/plot/__init__.py", line 42, in <module> from .plot import Plot, Plot_OldSync File "/opt/homebrew/lib/python3.9/site-packages/backtrader/plot/plot.py", line 44, in <module> from . import locator as loc File "/opt/homebrew/lib/python3.9/site-packages/backtrader/plot/locator.py", line 35, in <module> from matplotlib.dates import (HOURS_PER_DAY, MIN_PER_HOUR, SEC_PER_MIN, ImportError: cannot import name 'warnings' from 'matplotlib.dates' (/opt/homebrew/lib/python3.9/site-packages/matplotlib/dates.py)
I am trying to run cerebro.plot() and it is giving this error, also I am new to finance and wnant to learn this bactrader,is there any course or any videos to help me with this?
-
@madhoon Google:
backtrader https://stackoverflow.com/questions/63471764/importerror-cannot-import-name-warnings-from-matplotlib-dates
First response: Stack Overflow
-
@run-out Correction:
Google: ImportError: cannot import name 'warnings' from 'matplotlib.dates'
-
@madhoon said in Help With YahooFinance Data:
I actually had the same issue myself. For some reason, the cerebro.plot() only works with a specific version of matplotlib. Go to your terminal and run
pip install matplotlib==3.2.2.
That will allow you to plot the graphs.
-
@run-out Got it,thank you, hey, I am looking for a detailed course on studying the backtrader, any help?
-
@madhoon I haven't heard of any courses. Docs, community and our old pal google. Good luck!
-
It seems like the issue you're encountering is due to Backtrader not being able to find the data file 'MSFT'. To resolve this, you can try using the Yahoo Finance API to fetch data dynamically instead of reading it from a local file. Here's a modified version of your code:
import backtrader as bt
import backtrader.feeds as btfeeds
from datetime import datetimeclass MyStrategy(bt.Strategy):
def init(self):
self.dataclose = self.datas[0].closedef next(self): if self.dataclose[0] < self.dataclose[-1]: # Buy logic here pass elif self.dataclose[0] > self.dataclose[-1]: # Sell logic here pass
cerebro = bt.Cerebro()
cerebro.broker.setcash(100000)data = btfeeds.YahooFinanceData(dataname="MSFT", fromdate=datetime(2016, 6, 25), todate=datetime(2021, 6, 25))
cerebro.adddata(data)
cerebro.addstrategy(MyStrategy)cerebro.run()
This code sets up a simple Backtrader strategy and fetches the data directly from Yahoo Finance using the YahooFinanceData feed. Make sure you have an active internet connection when running this code.
Your Backtrader issue is a bit like having an unexpected glitch during Christmas preparations. Just as you troubleshoot and find solutions to ensure your strategy runs smoothly, during Christmas, we often encounter unforeseen challenges and adapt to create a joyful and memorable holiday experience. Both require patience, problem-solving, and a positive spirit.
-
Hourly chauffeur services have emerged as a convenient and luxurious transportation option for those seeking personalized and flexible travel experiences. Unlike traditional taxi services or ride-sharing apps, hourly chauffeur services provide passengers with a dedicated professional driver and a high-end vehicle for a specified period.
-
Eco-friendly lanyards are not only kinder to the planet but also serve as a symbol of environmental consciousness. They allow individuals and organizations to proudly display their commitment to sustainability and inspire others to make environmentally responsible choices in their daily lives.