如何使用`ibpy`从Interactive Broker获取历史股票数据?

时间:2016-10-13 19:50:37

标签: python interactive-brokers

我正在尝试使用reqHistoricalData获取股票的历史数据。我想回顾1年,但我的功能只打印本周的数据。

conn.connect()

conn.reqCurrentTime()

oid=cid #cid = 105

contract = make_contract2(265598, 'STK', 'SMART', 'SMART', 'USD') #AAPL

endtime = strftime('%Y%m%d %H:%M:%S')

conn.reqHistoricalData(1,contract,endtime,"1 Y","1 day","TRADES",1,1)

time.sleep(5)

conn.cancelHistoricalData(1);


sleep(5)

print('disconnecting')

time.sleep(1) #Simply to give the program time to print messages sent from IB

conn.disconnect()

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:-1)

只需循环一周(1年= 52周):

for t in range(52,-1,-1):
    #for t in range(int(delta/5),-1,-1):
        #print t
        d=datetime.datetime.today()-datetime.timedelta(weeks=t)
        d=d.strftime("%Y%m%d")
        con.reqHistoricalData(1,contract,'{} 16:00:00'.format(d),"1 W","1 day","TRADES",1,1)
        sleep(5)