【发布时间】:2020-06-14 11:09:01
【问题描述】:
在下面的代码中,我试图检索一些期权价格的历史价格。我正在查看 4 个月的历史,条形大小为 8 小时。我以 Apple 为例,我正在尝试下载 6 次行使价和一次到期的看涨期权价格。这需要疯狂的时间......
当我运行下面的代码时,第 1 次打击需要 20 秒,第 2 次打击需要 1770 秒,第 3 次打击需要 3400 秒,第 4 次打击需要 840 秒,第 5 次打击需要 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)
【问题讨论】:
标签: python api interactive-brokers tws