Python Interactive Brokers API对于历史期权价格来说非常慢



在下面的代码中,我试图检索一些期权价格的历史价格。我正在查看 4 个月的历史记录,条形大小为 8 小时。我以苹果为例,我正在尝试下载 6 次行使价和一次到期的看涨期权价格。这需要花费大量的时间...

当我运行下面的代码时,第一次罢工的数据需要 20 秒,第二次罢工需要 1770 秒,第三次罢工需要 3400 秒,第四次罢工需要 840 秒,第五次罢工需要 560 秒,最后一次罢工需要 460 秒。下载所有内容大约需要 2 个小时。出了什么问题,我能做些什么来让它更快?

import time
import pandas as pd
import collections
import datetime as dt
from ibapi.client import EClient
from ibapi.wrapper import EWrapper
from ibapi.contract import Contract
from ibapi.common import BarData
class TestApp(EClient, EWrapper):
def __init__(self):
EClient.__init__(self, self)
self.data=collections.defaultdict(list)
def error(self, reqId:int, errorCode:int, errorString:str):
print("Error: ", reqId, "", errorCode, "", errorString)
def historicalData(self, reqId:int, bar:BarData):
self.data["date"].append(bar.date)
self.data["price"].append(bar.close)
def historicalDataEnd(self, reqId: int, start: str, end: str):
print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
self.df = pd.DataFrame.from_dict(self.data)
self.disconnect()
print("finished")

def get_option_histo_prices_test(ticker:str,expiry:str,strike:str):
app = TestApp()
app.connect("127.0.0.1", 7496, 5)
time.sleep(1)
contract = Contract()
contract.secType = "OPT"   
contract.right = "C"
contract.exchange = "SMART"
contract.currency = "USD"
contract.multiplier = "100" 
contract.symbol = ticker
contract.lastTradeDateOrContractMonth = expiry
contract.strike = strike
app.reqHistoricalData(1, contract,"","4 M", "8 hours", "ASK", 1, 1, False, [])
app.run()
return app.df
ticker = "AAPL"
expiry = "20200619"
start_time_initial = time.time()
for strike in ["300","280","240","220","180","160"]:
start_time = time.time()
prices = get_option_histo_prices_test(ticker,expiry,strike)
end_time = time.time()
print (end_time - start_time)
end_time_final = time.time()
print("it took",end_time_final - start_time_initial)

将"ASK"替换为"TRADES"有效。IT 需要 20 秒,而不是之前的 2 小时。

相关内容

  • 没有找到相关文章

最新更新