Global variables 从reqHistoricalData中提取多个合同无效

Global variables 从reqHistoricalData中提取多个合同无效,global-variables,interactive-brokers,ibpy,Global Variables,Interactive Brokers,Ibpy,我试图将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',

我试图将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”中的两个数据帧的头部时(它们是相同的):


仅仅看一下数据,就好像你在2天内的行数是应该的两倍。在处理来自IB的回复之前,
hist=[]
将连续运行两次。因此,您必须在一个列表中获取SPY和AAPL的所有数据

尝试清除数据处理程序的已完成分支中的hist。我认为你也应该在那里要求签订下一份合同。然后,如果您需要更多数据,您可以设置
睡眠(10)
,以避免违反起搏规则

[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