pythontws

Historical data for non-expired option contracts with ib_insync lib?


I would like to get historical data (ideally hourly or less) for non-expired option contracts. TWS API should provide that data (source: https://www.tradersinsight.news/ibkr-quant-news/historical-options-futures-data-using-tws-api/). I have not found a way to get that data using the beautiful ib_insync lib. Is there a way to do that? If so, how?

Thx in advance


Solution

  • This works in the same way you fetch historical data for a stock, you just need to define an Option contract as "contract" reqHistoricalData().

    For example, first, you define e.g. a monthly NVIDIA call expiring on Friday 15th March 2024:

    from ib_insync import IB, util, Option
    ib = IB()
    
    ...
    
    contract = Option(
        symbol="NVDA",
        lastTradeDateOrContractMonth="20240315",
        strike=800,
        right="C",
        exchange="SMART",
        tradingClass="NVDA"
        )
    

    Then you get the historical data, in this case 5 minute bars of the last 5 days.

    bars = ib.reqHistoricalData(
        contract=contract,
        endDateTime = "",
        durationStr = "5 D",
        barSizeSetting = "5 Mins",
        whatToShow = "TRADES",
        useRTH = True,
        formatDate = 1,
        keepUpToDate = False
        )
    

    Afterwards you proceed with df = util.df(bars) to store the data in a dataframe.