gpt4 book ai didi

python - pandas,python : collecting, 使用和保存实时数据

转载 作者:太空宇宙 更新时间:2023-11-03 17:42:13 24 4
gpt4 key购买 nike

在下面的 Python (2.7.9) 代码中,我通过 TWS API 和 IBpy 的回调接收实时股票数据。当感兴趣的数据(出价、要价、最后价格和最后交易规模)进入时,它会进入 pandas (0.16.1) 数据框架。另外,我在数据框“bidVol”中添加了一列,其中最后几行代码放置了以买入价完成的交易或交易量的运行总和。目前,我在“bidVol”列中获取给定股票的出价交换的总股数。我想用 78 列替换单个“bidVol”列,每一列代表交易日五分钟间隔内生成的总计。我会怎样:

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

“符号”、“证券”、“交易所”、“货币”、“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)

最佳答案

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

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']

关于python - pandas,python : collecting, 使用和保存实时数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30358504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com