2019-10-02: The community is currently in read-only mode
Not able to fetch live data from IB but works with Yahoofinance
Tomas last edited by
Im trying to fetch data from Interactive Brokers, however it simply throws me the following error when I try to plot the data
(base) D:\backtrader projects>D:\Python\python.exe "d:\backtrader projects\strategies\testytest.py" Server Version: 76 TWS Time at connection:20190421 18:33:13 CET 21-Apr-19 18:33:19 DEBUG CACHEDIR=C:\Users\Tomas_000\.matplotlib 21-Apr-19 18:33:19 DEBUG Using fontManager instance from C:\Users\Tomas_000\.matplotlib\fontlist-v300.json Traceback (most recent call last): File "d:\backtrader projects\strategies\testytest.py", line 64, in <module> cerebro.plot() File "D:\Python\lib\site-packages\backtrader\cerebro.py", line 996, in plot plotter.show() File "D:\Python\lib\site-packages\backtrader\plot\plot.py", line 795, in show self.mpyplot.show() AttributeError: 'Plot_OldSync' object has no attribute 'mpyplot'
However if I try to run the exact same code but instead comment out the IBData feed and insert a yahoo datafeed it will work and plot the graph as wanted.
My code is
from __future__ import (absolute_import, division, print_function, unicode_literals) import backtrader as bt import datetime # For datetime objects import os.path # To manage paths import sys # To find out the script name (in argv) import math from backtrader.indicators import Indicator, MovAv, RelativeStrengthIndex, Highest, Lowest class TestStrategy(bt.Strategy): def __init__(self): # Keep a reference to the "close" line in the data dataseries self.dataclose = self.datas.close def next(self): print(self.dataclose) if __name__ == '__main__': #Variable for our starting cash startcash = 10000 #Create an instance of cerebro cerebro = bt.Cerebro() #Add the strategy cerebro.addstrategy(TestStrategy) # Add Sizer #cerebro.addsizer(LongOnly) # Activate optimization StrategyOptimizationEnabled = False #Add our strategy if StrategyOptimizationEnabled == True: cerebro.optstrategy(TestStrategy, maperiod=range(14,21)) #Get Apple data from Yahoo Finance. THIS ACTUALLY WORKS BUT IBDATA DOESNT WORK # data = bt.feeds.YahooFinanceData( # dataname="AAPL", # fromdate = datetime.datetime(2019,1,1), # todate = datetime.datetime(2020,1,1) # ) #Get Twitter data from Yahoo Finance. store = bt.stores.IBStore(port=7497) data = store.getdata(dataname='TWTR', timeframe=bt.TimeFrame.Ticks, fromdate=datetime.datetime(2019,1,1), todate=datetime.datetime(2020,1,1)) cerebro.resampledata(data, timeframe=bt.TimeFrame.Seconds, compression=10) #Add the data to Cerebro #cerebro.resampledata(data, timeframe=bt.TimeFrame.Minutes, compression=15) # Set our desired cash start cerebro.broker.setcash(startcash) # Run over everything opt_runs = cerebro.run() # Set the commission cerebro.broker.setcommission(commission=0.005) # Plot the result cerebro.plot()
Incredible feat. Just let us know how you get Yahoo to give you ticks from 2019-01-01 to 2020-01-01.
You may of course consider:
- Am I producing debugging information?
- Have I activated the
debugmode of the Interactive Brokers data?
10-secondsasking for too many when looking backwards to
- Am I attempting a historical download or do I want to trade real-time?
- Am I talking to the Fake-Data Demo, Paper Trading Account or Live Trading Account?
- Do I have the right data permissions?
That's the minimum information you should have at hand. Algotrading involves engineering and being thorough. And sorry, comparing a
Yahoodownload with connecting to a live broker (even if in Fake Data mode) is not really a comparison.
Cedric last edited by
Did you find a solution yet? I have the same problem. I can 'connect' with yahoo by using YahooFinanceData() and I am able to plot it. Despite that, when trying to use IB, the same error appears. The output tells me that there is a connection but when I want to plot it I get 'Plot_OldSync' object has no attribute 'mpyplot'. I already reinstalled most packages, I followed installations on github and medium but nothing seems to work. I try to do this on Jupyter Notebook and made a new environment.
I guess you miss the important point:
A Yahoo connection is just like opening a file and the amount of things you can do is limited
TWS(i.e.: IB) is connecting to a live data source which offers multiple possibilities and has several restrictions.
If you don't let the world know what you are doing (code) and say what you are trying to achieve (historical download, other ...), there is no possible help.
Cedric last edited by
Thank you for the fast response. I will describe my situation.
Now, I want to get historical data from IB to do some backtesting. I have a paper trading account and followed this article 'https://medium.com/@danjrod/interactive-brokers-in-python-with-backtrader-23dea376b2fc' to get the right settings. As already said, I work in a jupyter notebook.
This is my code:
from __future__ import (absolute_import, division, print_function, unicode_literals) !pip install https://github.com/blampe/IbPy/archive/master.zip import pandas as pd import backtrader as bt from datetime import datetime !pip install backtrader[plotting] %matplotlib inline # Create a subclass of Strategy to define the indicators and logi class EMA(bt.Strategy): # list of parameters which are configurable for the strategy params = dict( pfast=7, # period for the fast moving average pslow=10 # period for the slow moving average ) def __init__(self): sma1 = bt.ind.ExponentialMovingAverage(period=self.p.pfast) # fast moving average sma2 = bt.ind.ExponentialMovingAverage(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() ibstore = bt.stores.IBStore(host='127.0.0.1', port=7497, clientId=35) data = ibstore.getdata(dataname='AAPL-STK-SMART-USD', fromdate=datetime(2017, 5, 1), todate=datetime(2018, 8, 20)) cerebro.adddata(data) cerebro.addstrategy(EMA) cerebro.run() cerebro.plot()
Response: AttributeError: 'Plot_OldSync' object has no attribute 'mpyplot'
Thanks in advance and sorry for not making clear the situation at first.
Now, I want to get historical data from IB to do some backtesting.
You are NOT downloading historical data.
I have a paper trading account and followed this article 'https://medium.com/@danjrod/interactive-brokers-in-python-with-backtrader-23dea376b2fc'
The article DOES NOT describe backtesting at any point, it describes real-time trading (with emphasis in ..."use paper trading or the demo first")
See the documentation: Docs - Interactive Brokers - https://www.backtrader.com/docu/live/ib/ib/ for historical downloads, especially the
You may even want to specify the timeframe and compression. It is not the same to request
1-secondbars than to request