我试图将reqHistoricalData的结果存储到数据帧的字典中,其中每个键都是自动收报机名称,值是相应的时间序列数据帧。
def historical_data_handler(msg):
global hist, df
if "finished" in msg.date:
df = pd.DataFrame(index=np.arange(0, len(hist)), columns=('date', 'open', 'high', 'low', 'close', 'volume'))
for index, msg in enumerate(hist):
df.loc[index,'date':'volume'] = datetime.strptime(msg.date, '%Y%m%d %H:%M:%S'), msg.open, msg.high, msg.low, msg.close, msg.volume
else:
hist.append(msg)
def error_handler(msg):
print(msg)
con = ibConnection(port=7496,clientId=75)
con.register(historical_data_handler, message.historicalData)
con.register(error_handler, message.Error)
con.connect()
print("Connection to IB is ", con.isConnected(), " and starting data pull")
contracts = ["SPY", "AAPL"]
result = {}
for ct in contracts:
hist = []
spec = Contract()
spec.m_symbol = ct
spec.m_secType = 'STK'
spec.m_exchange = 'SMART'
spec.m_currency = 'USD'
spec.m_expiry = '' # For futures
con.reqHistoricalData(0, spec, '', '2 D', '5 mins', 'TRADES', 0, 1)
print(spec.m_symbol, hist, df)
result[ct] = df
print("Connection is terminated ", con.disconnect(), " after finishing pulling data")
代码的行为不是我所期望的。当我查看我的“结果”字典时。 “SPY”和“APPL”的值相同。我认为我如何定义全局变量有一些问题,因为它们似乎没有在for循环中正确更新。
非常感谢任何帮助,谢谢!
当我查看存储在“result”中的两个数据帧的头部时(它们是相同的):
[326 rows x 6 columns]
SPY date open high low close volume
0 2018-02-09 04:00:00 261.08 261.16 260.92 260.99 68
1 2018-02-09 04:05:00 260.99 261 260.86 260.99 59
[326 rows x 6 columns]
AAPL date open high low close volume
0 2018-02-09 04:00:00 261.08 261.16 260.92 260.99 68
1 2018-02-09 04:05:00 260.99 261 260.86 260.99 59
答案 0 :(得分:1)
只是查看数据,看起来您的行数大约是2天的两倍。在处理来自IB的回复之前,hist = []
连续运行两次。因此,您必须在一个列表中获取SPY和AAPL的所有数据。
尝试在数据处理程序的已完成分支中清除hist。我认为你应该在那里要求下一份合同。然后,如果您要求更多数据,则可以设置sleep(10)
以避免违规行为。