如何解决将 Python 对象从盈透证券转换为 R 数据帧
我使用 Python 和 R 的组合进行股票市场分析,使用盈透证券进行数据检索。 Interactive brokers 支持 Python API,但不支持 R API,所以我使用 Python 调用与 Interactive brokers 交互,然后将数据转换为 R。但是,我一直在尝试将 Python 数据结构转换为 R 数据帧。在此示例中,我订阅了实时刻度数据馈送并尝试将数据转换为数据帧。我试过在 Python 端使用 Pandas,哪种有效,但给了我环境变量,而不是我想看到的数据。当我尝试在 R 端转换数据时,我得到:“as.data.frame.default(x[[i]],optional = TRUE) 中的错误:无法强制类 'c("ib_insync.objects.TickByTickAllLast ","python.builtin.tuple",' 到 data.frame"
这是我的 R 代码:
library(reticulate)
use_python("/usr/local/bin/python3.7")
source_python("testPythonCalls.py")
# Connect to IB
connection <- ibConnect(as.integer(7497),as.integer(600))
# Set up the NQ Futures contract
contract <- ibFuturesContract('NQ',as.integer(20210319),'GLOBEX')
# Subscribe to Real Time Bars
# Request Tick by Tick Data
#Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks.
#Parameters: contract (Contract) – Contract of interest.
#tickType (str) – One of ‘Last’,‘AllLast’,‘Bidask’ or ‘MidPoint’.
#numberOfTicks (int) – Number of ticks or 0 for unlimited.
#ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
#Return type: Ticker
ticks <- ibReqTickByTickData(contract,'Last',as.integer(0),TRUE)
# Show the ticks
print (ticks)
# Here's my attempt to convert the list to a data frame on the R side
df <- as.data.frame(as.list(ticks))
# Here's my attempt to convert the data to a data frame on the Python side
df <- ibTickByTickDataDF(ticks)
print (df)
# Turn off real time Feed
ibCancelTickByTickData(contract,'Last')
# disconnect
ibdisconnect()
这是我的 Python 代码:
from ib_insync import *
import pandas as pd
# Connect to IB; args are (IP address,device number,client ID)
def ibConnect(port,clientID):
ib.sleep(0)
connectAttempts=0
while not ibisConnected():
connectAttempts += 1
connection = ib.connect('127.0.0.1',port,clientID)
ib.sleep(0)
if connectAttempts > 10:
print ("Unable to connect to Interactive brokers")
return ()
# disconnect from IB
def ibdisconnect():
ib.disconnect()
ib.sleep(0)
return
# Check to see if IB is connected
def ibisConnected():
isConnected = ib.isConnected()
return isConnected
# Set up a futures contract
def ibFuturesContract(symbol,expirationDate,exchange):
futuresContract = Future(symbol,exchange)
return futuresContract
#Subscribe to tick-by-tick data and return the Ticker that holds the ticks in ticker.tickByTicks.
#Parameters: contract (Contract) – Contract of interest.
#tickType (str) – One of ‘Last’,‘Bidask’ or ‘MidPoint’.
#numberOfTicks (int) – Number of ticks or 0 for unlimited.
#ignoreSize (bool) – Ignore bid/ask ticks that only update the size.
#Return type: Ticker
def ibReqTickByTickData(contract,tickType,numberOfTicks,ignoreSize):
ibTicks = ib.reqTickByTickData (contract,ignoreSize)
ib.sleep(2)
return (ibTicks.tickByTicks)
# Convert the Tick By Tick Data to a data frame
def ibTickByTickDataDF(ticks):
df = pd.DataFrame (ticks)
#index=[time],#columns=[bid,bidsize,ask,askSize,last,lastSize,prevBid,prevBidSize,prevAsk,prevAskSize,prevLast,prevLastSize,volume,open,high,low,close,halted])
# index=[ticks.time],columns=['time','bid','bidSize'])
# df.loc[0]=(ticks.time,ticks.price,ticks.size)
return (df)
# Unsubscribe from tick by tick data
def ibCancelTickByTickData(contract,tickType):
ib.cancelTickByTickData(contract,tickType)
return
ib = IB()
global ibTicks
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。