Interactive Brokers API in Python: download historical prices with ib_async

As with my posts on IPO and insider trading data, I want to make it as easy as possible for anyone to get and download data. So I made a script for those who are interested in Interactive Brokers (IBKR), and it downloads a year of daily Apple prices into a pandas DataFrame, a table in Python.
The connection runs through Trader Workstation. Your Python code sends requests to Trader Workstation on your computer, and Trader Workstation passes them to IBKR.
I connect with ib_async and use a paper account on its default port, 7497. I think that it is important that you use a paper account first and connect to that, so that you learn how the script works and what it does on fake money, if I could phrase it that way. If you do something wrong, it could be costly with a real account, but with a paper account, you are protected.
The same code runs against a live account when Trader Workstation is logged into the live session, and the connection uses the live port, 7496.
The code needs Trader Workstation to be open and logged in, and every request in this tutorial is read-only.
What you end up with
- A Python connection to an IBKR paper account
- Daily bars for a stock, in a pandas DataFrame
What you need
- An IBKR account with a paper-trading login
- Trader Workstation installed and logged into the paper account
- Market-data subscriptions for the stock on the live account, shared with the paper account. Without them, the historical request may return no bars or a subscription error.
- Python with
ib_asyncand pandas:pip install ib_async pandas.ib_asyncis the maintained successor toib_insync, andutil.df()needs pandas to build a DataFrame.
Step 1. Importing and connecting
IB() creates the object Python uses to communicate with Trader Workstation. ib.connect(...) opens the connection: host tells Python where Trader Workstation runs, port selects the session, and clientId identifies the connection.
In a Jupyter notebook, add util.startLoop() so the notebook can continue running while it waits for replies from Trader Workstation. Leave this line out in an ordinary .py file.
from ib_async import IB, Stock, Forex, util
util.startLoop() # let ib_async use the notebook's event loop (Jupyter only)Before connecting, open Trader Workstation in paper mode and enable the API: Configure, then API, then Settings, then Enable ActiveX and Socket Clients. This was a bit difficult for me to realize, because it was not as clear as with LSEG Workspace. Even after you have the program up and logged in, you still need to go into Settings and check these items. Note the socket port, 7497 by default for paper trading, and leave Read-Only API enabled, which blocks orders submitted through the API.
ib = IB()
ib.connect(
"127.0.0.1", # the computer running Trader Workstation
7497, # the socket port set in Trader Workstation
clientId=1,
readonly=True, # Trader Workstation is in read-only mode
)
ib.reqMarketDataType(3) # allow delayed data when live data is unavailable7496 is the default port for live trading, and IB Gateway uses 4002 for paper and 4001 for live. Whichever you use, the port in the code must match the socket port in Trader Workstation, and clientId can be any non-negative integer that no other open connection uses.
Step 2. Downloading the price history
First, identify the stock. Stock("AAPL", "SMART", "USD") means Apple shares in US dollars, using IBKR’s SMART routing. ib.qualifyContracts(aapl) matches this description to IBKR’s exact contract. The request asks for one year of daily prices, and util.df(bars) converts the returned bars into a pandas DataFrame.
aapl = Stock("AAPL", "SMART", "USD") # the contract: which instrument
ib.qualifyContracts(aapl) # fill in IBKR's official contract details
bars = ib.reqHistoricalData(
aapl,
endDateTime="", # empty means up to now
durationStr="1 Y", # how far back
barSizeSetting="1 day", # one bar per trading day
whatToShow="ADJUSTED_LAST", # closes adjusted for splits and dividends
useRTH=True, # regular hours only
)
df = util.df(bars) # the bars as a pandas DataFrameThe result has one row per trading day, with the date, open, high, low, close and volume.
whatToShow="ADJUSTED_LAST" adjusts prices for splits and dividends, and "TRADES" adjusts for splits only. It is important to adjust for splits and dividends. If you only want the price levels, it matters less, but when you compute returns, for example, for a trading signal, you need to include the splits and dividends.
reqMarketDataType(3) tells Trader Workstation to return delayed data when live data is unavailable, but that may not be enough for a historical request. I think that with all types of data, it is good to know what you are paying for, because if you are not paying for anything, you may lack access to things and get few prices, for example. So if your request returns no bars or a subscription error, check the account’s market-data subscriptions.
When you are finished, close the connection.
ib.disconnect()Conclusion
So the conclusion is that you can connect Python to IBKR directly on your computer with ib_async, and a paper account lets you test the script on fake money first.
References
ib-api-reloaded. (n.d.). ib_async documentation. https://ib-api-reloaded.github.io/ib_async/
Interactive Brokers. (n.d.-a). Installing & configuring TWS for the API. IBKR Campus. https://www.interactivebrokers.com/campus/trading-lessons/installing-configuring-tws-for-the-api/
Interactive Brokers. (n.d.-b). TWS API documentation. https://www.interactivebrokers.com/docs/tws-api/doc/
Read next
- Interactive Brokers data in Python Daily price history of stocks through an Interactive Brokers account.
- Download daily prices for listed and delisted stocks with LSEG Workspace in Python Another source I use for daily price history. It downloads the Swedish stocks an LSEG screen returns, active and delisted, into one CSV.
- How to backtest a trading strategy in Python with bt What to do once the prices are in a table: a momentum strategy run end to end on simulated daily returns, with trading costs charged.
Disclaimer: a getting-started guide on a paper account. No orders are placed. Not investment advice.