1

我有以下代码,它使用来自 Interactive Brokers 的 IbPy 下载历史数据,并将其保存到 csv。我不想将其保存到 csv,而是直接将数据输入到 pandas 数据帧(绕过 csv 位)。

任何人都可以帮忙吗?

from time import sleep, strftime, localtime  
from ib.ext.Contract import Contract  
from ib.opt import ibConnection, message  


new_symbolinput = ['ES', 'NQ']
newDataList = []  
dataDownload = []  

def historical_data_handler(msg):  
    global newDataList  
    print (msg.reqId, msg.date, msg.close)
    if ('finished' in str(msg.date)) == False:  
        new_symbol = new_symbolinput[msg.reqId]  
        dataStr = '%s, %s, %s' % (new_symbol, strftime("%Y-%m-%d", localtime(int(msg.date))), msg.close)  
        newDataList = newDataList + [dataStr]
    else:  
        new_symbol = new_symbolinput[msg.reqId]  
        filename = 'minutetrades' + new_symbol + '.csv'  
        csvfile = open('csv_day_test/' + filename,'w')  
        for item in newDataList:  
            csvfile.write('{} \n'.format(item))
        csvfile.close()  
        newDataList = []  
        global dataDownload  
        dataDownload.append(new_symbol)  

con = ibConnection()  
con.register(historical_data_handler, message.historicalData)  
con.connect()  

symbol_id = 0  
for i in new_symbolinput:  
    print (i)  
    qqq = Contract()  
    qqq.m_symbol = i  
    qqq.m_secType = 'FUT'  
    qqq.m_exchange = 'GLOBEX'  
    qqq.m_currency = 'USD'
    qqq.m_expiry = '201609'
    con.reqHistoricalData(symbol_id, qqq, '', '1 W', '1 day', 'TRADES', 1, 2)  

    symbol_id = symbol_id + 1  
    sleep(10)  

print (dataDownload) 
filename = 'downloaded_symbols.csv'  
csvfile = open('csv_day_test/' + filename,'w')  
for item in dataDownload:  
    csvfile.write('%s \n' % item)  
csvfile.close()
4

2 回答 2

1

def history_data_handler(msg)中替换以下代码;这将直接写入数据帧。

  else:
df_new = pd.DataFrame( columns=['Code', 'Date', 'Close'])
j = 0
for i in newDataList:
    df_new.loc[j] = i.split(',')
    j = j + 1
df_new.set_index('Date',inplace=True)
#print df_new

考虑将值msg.close直接写入 df,而不是首先放入字符串并拆分。

于 2016-11-28T09:04:11.063 回答
0

更新的答案:

将条形数据转换为数据框的文档更新:

# convert to pandas dataframe
df = util.df(bars)
于 2021-03-26T16:33:55.450 回答