首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用python IB API堆叠数据

使用python IB API堆叠数据
EN

Stack Overflow用户
提问于 2020-12-07 04:01:05
回答 2查看 264关注 0票数 0

我正在下载5只股票('A','AAP','AAPL','ABBV','ABC')的15Y数据(每日收盘价)。问题是我得到了一些重复的东西。第一个没有问题,'A',我得到了正确的数据量。对于第二个,'AAP',我有两倍的正确行数,似乎数据被下载了两次。最后3只股票也有同样的问题,我有三倍于正确行数的股票。我附上了一个屏幕截图显示的csv文件的大小,这些文件应该有相同的大小,如果一切都很好。

我怀疑问题来自于调用reqHistoricalData后的10秒暂停;它可能太长了。我如何避免重复的行,以及如何暂停适当的时间(不是太长也不是太短)?

代码语言:javascript
运行
复制
import pandas as pd
import datetime as dt
import time
import collections
import threading
import os

from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.common import BarData

path = r"D:\trading\data\debug\\" 

class IBapi(EWrapper, EClient):
    def __init__(self):
        EClient.__init__(self, self)
        self.data=collections.defaultdict(list)

    def nextValidId(self, orderId: int):
        super().nextValidId(orderId)
        self.nextorderId = orderId
        print('The next valid order id is: ', self.nextorderId)

    def error(self, reqId, errorCode, errorString):
        super().error(reqId, errorCode, errorString)
        print("Error. Id:", reqId, "Code:", errorCode, "Msg:", errorString)
        
    def historicalData(self, reqId:int, bar:BarData):
        self.data["date"].append(bar.date)
        self.data["close"].append(bar.close)
        self.df = pd.DataFrame.from_dict(self.data)

tickers = ["A","AAP","AAPL","ABBV","ABC"]

def run_loop():
    app.run()


app = IBapi()
app.connect("127.0.0.1", 7496, 5)
app.nextorderId = None

# Start the socket in a thread
api_thread = threading.Thread(target=run_loop, daemon=True)
api_thread.start()

# Check if the API is connected via orderid
while True:
    if isinstance(app.nextorderId, int):
        print('connected')
        break
    else:
        print('waiting for connection')
        time.sleep(1)
        
n_id = app.nextorderId

for ticker in tickers:    
    contract = Contract()
    contract.symbol = ticker
    contract.secType = "STK"
    contract.exchange = "SMART"
    contract.currency = "USD" 

    app.reqHistoricalData(n_id, contract, "","15 Y", "1 day", "TRADES", 1, 1, False, [])
    time.sleep(10)
    app.df.to_csv(path + ticker + ".csv")
        
    n_id = n_id + 1
    

app.disconnect()
EN

回答 2

Stack Overflow用户

发布于 2020-12-08 08:58:15

您不会清除请求之间的列表。

代码语言:javascript
运行
复制
def historicalData(self, reqId:int, bar:BarData):
        # just keeps adding data to list
        self.data["date"].append(bar.date)
        self.data["close"].append(bar.close)
        # makes a new dataframe on every single bar
        self.df = pd.DataFrame.from_dict(self.data)

historicalDataEnd方法中,您可以创建数据帧并将其保存到文件中。记录下报价器和reqId,这样你就知道哪个报价器结束了。

您应该在两次调用之间仍有10秒的延迟,但不要指望在10秒内返回数据。如果它没有到达,你将得到一个空文件(或者在你的例子中,所有以前的报价器数据,这似乎已经发生在ABC中)。

票数 0
EN

Stack Overflow用户

发布于 2021-01-18 04:33:13

你的复制品每周五都会送来。您请求,比方说星期五(第一次迭代),在接下来的两次迭代(星期六和星期日)中,API返回第一个可能的交易日(上周五)的数据。否则5秒的等待时间就足够了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65172516

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档