Download options chains data with the IBKR API

November 30, 2024
Facebook logo.
Twitter logo.
LinkedIn logo.
Get this code in Google Colab

Download options chains data with the IBKR API

Interactive Brokers (IB) is one of the best out there.

You can trade on dozens of markets from more than 100 countries. It has advanced features for trading and risk management along with a great API.

But there is one problem.

The native Python IB API is pretty hard to use. It is based on a request callback pattern and runs asynchronously. This makes it tough for beginners to get started.

Lucky for us we have ib_insync.

By reading today’s newsletter, you’ll be able to download options data and build options chains with ib_insync.

Let's go!

Download options chains data with the IBKR API

Real-time market data is essential for active traders.

The Python library ib_insync offers an easy way to manage stock options data with Interactive Brokers.

Ib_insync integrates with the Interactive Brokers API, easing the complexities of working with the native IB API. You start by setting up an Interactive Brokers account, installing ib_insync, and connecting to the IB Gateway or Trader Workstation. From there, retrieving options data involves defining options contracts and requesting market data.

Professionals use ib_insync with their production trading strategies by accessing and analyzing detailed stock options data. The library's user-friendly design and comprehensive documentation make it great for both seasoned traders and beginners. By using ib_insync, you can get options data easily.

Let's see how it works.

Connect to the Interactive Brokers API

We start by connecting to the Interactive Brokers API, which allows us to retrieve financial data for various instruments. This is done using the ib_insync library, which provides an easy-to-use interface for interacting with Interactive Brokers.

We establish a connection by specifying the host, port, and client ID.

1from ib_insync import *
2util.startLoop()
3
4ib = IB()
5ib.connect('127.0.0.1', 7497, clientId=12)

We create an instance of IB and use it to connect to the local TWS application at the specified host and port. The clientId is a unique identifier for your connection, allowing multiple connections from the same machine.

The util.startLoop() function enables the asynchronous event loop required by ib_insync when being run in Jupyter Notebook.

Retrieve the current market price of Nvidia stock

Next, we define the stock symbol for NVIDIA and request its current market price. We create a stock contract using the Stock class and specify the ticker symbol, exchange, and currency. Then, we qualify the contract and request the market price.

1nvda = Stock("NVDA", "SMART", "USD")
2ib.qualifyContracts(nvda)
3[ticker] = ib.reqTickers(nvda)
4nvdaValue = ticker.marketPrice()

We define a stock contract for Nvidia by specifying its ticker symbol, exchange, and currency. We then request the ticker information using reqTickers, which retrieves the current market price and other data for the specified contract. The market price is extracted from the ticker object and stored in the nvdaValue variable.

Request option chain data for Nvidia

We request the option chain for Nvidia to explore available options data. We use the reqSecDefOptParams method to obtain option parameters like trading class, exchange, strikes, and expirations.

We filter the chain to find the specific options available for Nvidia on the SMART exchange.

1chains = ib.reqSecDefOptParams(nvda.symbol, "", nvda.secType, nvda.conId)
2chain = next(c for c in chains if c.tradingClass == "NVDA" and c.exchange == "SMART")
3
4strikes = [
5    strike for strike in chain.strikes
6    if strike % 5 == 0
7    and nvdaValue - 20 < strike < nvdaValue + 20
8]
9
10expirations = sorted(exp for exp in chain.expirations)[:3]
11rights = ["C", "P"]

We filter the results to isolate options with a trading class of "NVDA" on the "SMART" exchange. We then create a list of strike prices in increments of 5, within 20 units of the current market price. We also select the upcoming three expiration dates and both call ("C") and put ("P") options.

Request market data for Nvidia options

We create option contracts for NVIDIA based on filtered strikes, expirations, and rights. Then, we qualify these contracts and request tickers to get market data. Finally, we compile the relevant contract data into a structured format for analysis.

1contracts = [
2    Option("NVDA", expiration, strike, right, "SMART", tradingClass="NVDA")
3    for right in rights
4    for expiration in expirations
5    for strike in strikes
6]
7
8contracts = ib.qualifyContracts(*contracts)
9tickers = ib.reqTickers(*contracts)
10
11contractData = [
12    (
13        t.contract.lastTradeDateOrContractMonth, 
14        t.contract.strike, 
15        t.contract.right,
16        t.time,
17        t.close,
18        nvdaValue,
19    )
20    for t
21    in tickers
22]
23
24fields = [
25    "expiration", 
26    "strike", 
27    "right", 
28    "time", 
29    "undPrice",
30    "close", 
31]
32
33util.df([dict(zip(fields, t)) for t in contractData])

We generate option contracts for NVIDIA by iterating over the available strikes, expirations, and rights. The Option class is used to define each contract's attributes. We then qualify the contracts to ensure they are valid for trading.

The reqTickers method retrieves market data, including last trade date, strike price, option type, time, and closing price. The data is structured and converted into a DataFrame for easier analysis and visualization using util.df.

Your next steps

Now that you've learned how to retrieve stock and option data using Interactive Brokers, consider exploring different stocks or option strategies. Try modifying the stock symbol or adjusting the range of strike prices and expirations to see how it affects the options data.

Experimenting with these parameters will give you deeper insights into option trading and how market conditions impact option pricing.

Man with glasses and a wristwatch, wearing a white shirt, looking thoughtfully at a laptop with a data screen in the background.