我正在下载5只股票('A','AAP','AAPL','ABBV','ABC')的15Y数据(每日收盘价)。问题是我得到了一些重复的东西。第一个没有问题,'A',我得到了正确的数据量。对于第二个,'AAP',我有两倍的正确行数,似乎数据被下载了两次。最后3只股票也有同样的问题,我有三倍于正确行数的股票。我附上了一个屏幕截图显示的csv文件的大小,这些文件应该有相同的大小,如果一切都很好。
我怀疑问题来自于调用reqHistoricalData后的10秒暂停;它可能太长了。我如何避免重复的行,以及如何暂停适当的时间(不是太长也不是太短)?
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()
发布于 2020-12-08 08:58:15
您不会清除请求之间的列表。
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中)。
发布于 2021-01-18 04:33:13
你的复制品每周五都会送来。您请求,比方说星期五(第一次迭代),在接下来的两次迭代(星期六和星期日)中,API返回第一个可能的交易日(上周五)的数据。否则5秒的等待时间就足够了。
https://stackoverflow.com/questions/65172516
复制相似问题