0

当我试图获取没有历史数据的合约的历史数据时,我陷入了一种无限循环。
在下面的代码中,我试图获取一个股票期权的 3 次罢工和一次到期的历史数据。存在第 1 次和第 3 次罢工的历史数据,但没有第 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):
        print(bar.date, bar.close)

    def historicalDataEnd(self, reqId: int, start: str, end: str):
        print("HistoricalDataEnd. ReqId:", reqId, "from", start, "to", end)
        self.disconnect()
        print("finished")

def get_option_histo_prices(strike:str):

    app = TestApp()
    app.connect("127.0.0.1", 7496, 5)

    time.sleep(1)

    contract = Contract()

    contract.symbol = "UNH"
    contract.lastTradeDateOrContractMonth = "20200619"
    contract.secType = "OPT"   
    contract.right = "C"
    contract.exchange = "SMART"
    contract.currency = "USD"
    contract.multiplier = "100" 

    contract.strike = strike

    app.reqHistoricalData(1, contract, "","1 W", "8 hours", "TRADES", 1, 1, False, [])

    app.run()


for strike in ["280","140","240"]:
    try:
        prices = get_option_histo_prices(strike)
    except:
        print("no data for",strike)

我获得了第一次罢工的历史数据,但随后收到以下错误消息

错误:1 162 历史市场数据服务错误消息:HMDS 查询未返回数据:UNH 200619C00140000@SMART Trades

之后代码卡住了,它继续运行,就像它处于无限循环中一样。例外情况可能有更好的事情要做。

4

1 回答 1

0

我很确定在 python 中你可以做一个

try:
   #get your historical data
except HDMS query returned no data:
    #continue/break/go back to data collecting
于 2020-06-15T21:52:02.227 回答