0

我正在使用 IB API 流式传输实时价格数据,我想将其放入数据框中进行分析。我的数据包括一个没有时间戳的实时流媒体价格。

我想我需要使用自动添加的行号创建新行,并将价格插入价格列。

我尝试定义数据框并告诉价格去向如下:

def tick_df(self, reqId,
            contract):  # this stores price dataframe by creating an empty dataframe and setting the index to the time column
    self.bardata[reqId] = pd.DataFrame(columns=['index', 'price'])
    self.reqMktData(reqId, contract, "", False, False, [])
    self.bardata[reqId].index = [x for x in range(1, len(self.bardata[reqId].values) + 1)]
    return self.bardata[reqId]

def tickPrice(self, reqId, tickType, price, attrib):  # this function prints the price
    if tickType == 2 and reqId == 102:
        self.bardata[reqId].loc[self.bardata[reqId].index] = price

我一直在使用类似于这里的方法(https://github.com/PythonForForex/Interactive-brokers-python-api-guide/blob/master/GOOG_five_percent.py)。但是,由于我只是在流式传输价格,因此我无法使用时间戳来创建新行。

4

1 回答 1

1

我不知道这是不是你需要的。在一个循环中,我生成附加到数据框的随机价格。

import numpy as np
import pandas as pd

_price = 1.1300 # first price in the series
_std = 0.0005  # volatility (stadard deviation)
df = pd.DataFrame(columns=['price'])

for i in range(1000):
    _wn = np.random.normal(loc=0, scale=_std, size=1)  # random white noise
    _price = _price + _wn[0]  # random price
    df = df.append({'price':_price}, ignore_index=True)

df

我使用外汇时间序列,我不会构思没有时间的时间序列,以防万一你有同样的“问题”,我包括一个带有时间戳的版本:

import numpy as np
import pandas as pd
from datetime import datetime

_price = 1.1300  # first price in the series
_std = 0.0005  # volatility (stadard deviation)
df = pd.DataFrame(columns=['price', 'time'])

for i in range(1000):
    _wn = np.random.normal(loc=0, scale=_std, size=1)  # random white noise
    _price = _price + _wn[0] # random price
    _time = datetime.now()
    df = df.append({'price':_price, 'time':_time}, ignore_index=True)
    
df

如果这是您需要的,请告诉我。

于 2022-01-10T20:18:31.413 回答