pandas,python:收集,使用和保存实时数据

时间:2015-05-20 19:15:26

标签: python pandas

在下面的Python(2.7.9)代码中,我通过TWS API和IBpy通过回调接收实时股票数据。随着感兴趣的数据,出价,询问,最后价格和最后交易规模进入,它进入了一个pandas(0.16.1)数据框。此外,我在数据框'bidVol'中添加了一列,其中最后几行代码以交易价格完成交易或交易量的运行总和。目前,我在'bidVol'列中获得了针对给定股票的出价交换的总股票。我想用78列替换单个'bidVol'列,每列一个交易日的五分钟间隔产生一列。 我怎么会:

1)在9:30到4:00之间以5分钟的间隔创建带有时钟时间标题的其他列,因此数据框的标题如下所示:

'symbol','security','exchange','currency','9:30','9:35',...,'3:55'

2)然后将在给定时间间隔内以买价完成的交易量加到各自的列中?

 from __future__ import print_function
 import pandas as pd
 import numpy
 from ib.opt import ibConnection, message
 from ib.ext.Contract import Contract
 from ib.ext.TickType import TickType as tt
 from time import sleep

 # establish universe of stocks to watch...

 contracts = pd.DataFrame([
        ['FGEN', 'STK', 'SMART', 'USD'],
        ['AAPL', 'STK', 'SMART', 'USD'],
        ['GILD', 'STK', 'SMART', 'USD'],
        ['INTC', 'STK', 'SMART', 'USD'],
        ['MSFT', 'STK', 'SMART', 'USD']

 ])

 # create column names for DataFrame

 contracts.columns = ['symbol', 'security', 'exchange', 'currency']

 # add specific column names to match name returned by tickType.getField()
 contracts['bidPrice'] = 0
 contracts['askPrice'] = 0
 contracts['lastPrice'] = 0
 contracts['lastSize'] = 0
 contracts['bidVol'] = 0
 def error_handler(msg):
        print(msg)

 def my_callback_handler(msg):
        if msg.field in [tt.BID, tt.ASK, tt.LAST]:
               # now store response in the data frame
                 contracts.loc[msg.tickerId, tt.getField(msg.field)] =   msg.price
        elif msg.field in [tt.LAST_SIZE]:
                 contracts.loc[msg.tickerId, tt.getField(msg.field)] = msg.size
                 if msg.field == tt.LAST_SIZE:
                         if contracts.loc[msg.tickerId, 'bidPrice'] ==    contracts.loc[msg.tickerId, 'lastPrice']:
                        contracts.loc[msg.tickerId, 'bidVol'] += contracts.loc[msg.tickerId, 'lastSize']

                             print(contracts.values)

1 个答案:

答案 0 :(得分:1)

在代码顶部附近插入以下代码:

from datetime import *

def fivemin():
    """Generate time string in 5 minute intervals"""
    dt0 = datetime.now()
    dt1 = dt0.replace(minute=5*(int)(dt0.minute/5),second=0,microsecond=0)
    return dt1.time().strftime('%H:%M')

error_handler的定义之上,添加以下内容:

ds = datetime.now().replace(hour=9,minute=30,second=0,microsecond=0)
for i in range(79):
    d_i = ds+timedelta(minutes=5*i)
    contracts[d_i.strftime('%H:%M') = 0

然后将contracts...bidVol行替换为以下内容:

contracts.loc[msg.tickerId, fivemin()] += contracts.loc[msg.tickerId, 'lastSize']