Interactive brokers - can't retrieve historical data
I took some sample code from the quickstart. The code below works perfectly fine with EURUSD CSV data that I used. I'm now trying to use historical data from IB as I'll be planning to use them to trade live.
# Create a Stratey class TestStrategy(bt.Strategy): params = ( ('maperiod', 15), ) def log(self, txt, dt=None): ''' Logging function fot this strategy''' dt = dt or self.datas.datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): # Keep a reference to the "close" line in the data dataseries self.dataclose = self.datas.close # To keep track of pending orders and buy price/commission self.order = None self.buyprice = None self.buycomm = None # Add a MovingAverageSimple indicator self.sma = bt.indicators.SimpleMovingAverage( self.datas, period=self.params.maperiod) # Indicators for the plotting show bt.indicators.ExponentialMovingAverage(self.datas, period=25) bt.indicators.WeightedMovingAverage(self.datas, period=25, subplot=True) bt.indicators.StochasticSlow(self.datas) bt.indicators.MACDHisto(self.datas) rsi = bt.indicators.RSI(self.datas) bt.indicators.SmoothedMovingAverage(rsi, period=10) bt.indicators.ATR(self.datas, plot=False) def notify_order(self, order): if order.status in [order.Submitted, order.Accepted]: # Buy/Sell order submitted/accepted to/by broker - Nothing to do return # Check if an order has been completed # Attention: broker could reject order if not enough cash if order.status in [order.Completed]: if order.isbuy(): self.log( 'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.buyprice = order.executed.price self.buycomm = order.executed.comm else: # Sell self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' % (order.executed.price, order.executed.value, order.executed.comm)) self.bar_executed = len(self) elif order.status in [order.Canceled, order.Margin, order.Rejected]: self.log('Order Canceled/Margin/Rejected') # Write down: no pending order self.order = None def notify_trade(self, trade): if not trade.isclosed: return self.log('OPERATION PROFIT, GROSS %.2f, NET %.2f' % (trade.pnl, trade.pnlcomm)) def next(self): # Simply log the closing price of the series from the reference self.log('Close, %.2f' % self.dataclose) # Check if an order is pending ... if yes, we cannot send a 2nd one if self.order: return # Check if we are in the market if not self.position: # Not yet ... we MIGHT BUY if ... if self.dataclose > self.sma: # BUY, BUY, BUY!!! (with all possible default parameters) self.log('BUY CREATE, %.2f' % self.dataclose) # Keep track of the created order to avoid a 2nd order self.order = self.buy() else: if self.dataclose < self.sma: # SELL, SELL, SELL!!! (with all possible default parameters) self.log('SELL CREATE, %.2f' % self.dataclose) # Keep track of the created order to avoid a 2nd order self.order = self.sell() if __name__ == '__main__': cerebro = bt.Cerebro() # Add a strategy cerebro.addstrategy(TestStrategy) cerebro.addsizer(bt.sizers.FixedSize, stake=1000) # Create a Data Feed # data = bt.feeds.PandasData(dataname=df) # Connect to IB data ibstore = bt.stores.IBStore(host='127.0.0.1', port=7496, clientId=35) # Create a Data Feed data = ibstore.getdata(dataname='EUR.USD-CASH-IDEALPRO', fromdate=datetime.datetime(2018, 1, 1), todate=datetime.datetime(2019, 12, 31), timeframe=bt.TimeFrame.Days ) # Add the Data Feed to Cerebro cerebro.adddata(data) # Set our desired cash start cerebro.broker.setcash(100000.0) # Set the commission - 0.1% ... divide by 100 to remove the % cerebro.broker.setcommission(commission=0.001) cerebro.addanalyzer(btanalyzers.SharpeRatio, _name='mysharpe') print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue()) cerebro.run() print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())
the below is only giving the portfolio starting and end value but nothing has happened in between. again, with the CSV data I used, a lot of information from the log was being printed. The default parameters like historical are set to False. I can't really see what should be changed.
Starting Portfolio Value: 100000.00 Final Portfolio Value: 100000.00
I don't think that you can easily get data for 2018 - 2019 with
ib. If I remember correctly, you should have several millions on the account and spend several thousands in commissions to get that deep. Google
ib historical data limitationsor something like this.
thanks, I'll look into this. only going back 2 years, I don't see any reason why it would be a problem. I don't know their policy but it seems odd to me. How would they expect to attract people if they can't properly backtest, unless they have deep pockets of course
IB is the brokerage company, not data provider. This is not their business. Common approach is to get data from the data providers for backtests.