Interactive Brokers data in Python
Interactive Brokers account holders get price history through Trader Workstation (TWS). Run pip install ib_async pandas. The script saves one long-format CSV in FOLDER (default Downloads), overwriting any file of the same name.
If a script does not work as it should, email me.
Daily stock prices
One row per stock and trading day over the past year, here for Apple and Microsoft, with IBKR’s contract number, the open, high, low and close prices adjusted for splits and dividends, and the volume in regular trading hours. Open Trader Workstation, sign in to the paper account and enable the API in read-only mode. The stocks need market-data subscriptions. If an error stops the script, run ib.disconnect() before the next run to free client id 1.
Choose these settings in the code:
SYMBOLS, the stock symbols. For another market, change the exchange and currency inStock(symbol, "SMART", "USD").durationStr, how far back, such as “5 Y”.7497, the socket port set in Trader Workstation, 7497 for the paper account.clientId, 1 unless another program uses it.FOLDER, the output folder.
from pathlib import Path
import pandas as pd
from ib_async import IB, Stock, util
SYMBOLS = ["AAPL", "MSFT"] # US stocks (for another market, change the exchange and currency below)
FOLDER = Path.home() / "Downloads" # change this to the folder for the CSV file
util.startLoop() # let ib_async use the notebook's event loop (delete this line in a .py file)
# Step 1. Connect to Trader Workstation
ib = IB()
ib.connect(
"127.0.0.1", # the computer running Trader Workstation
7497, # the socket port set in Trader Workstation
clientId=1, # change it if another program already uses 1
readonly=True, # Trader Workstation is in read-only mode
)
ib.reqMarketDataType(3) # delayed data where the account has no live subscription
# Step 2. One year of daily prices for each stock
frames = []
for symbol in SYMBOLS:
contract = Stock(symbol, "SMART", "USD") # the contract, with symbol, exchange and currency
ib.qualifyContracts(contract) # fill in IBKR's official contract details
assert contract.conId, f"IBKR does not know {symbol} with this exchange and currency."
bars = ib.reqHistoricalData(
contract,
endDateTime="", # empty means up to now
durationStr="1 Y", # how far back
barSizeSetting="1 day", # one bar per trading day
whatToShow="ADJUSTED_LAST", # prices adjusted for splits and dividends
useRTH=True, # regular hours only
)
assert bars, f"No prices came back for {symbol}. Check the symbol and the market-data subscription."
frames.append(util.df(bars).assign(symbol=symbol, con_id=contract.conId))
ib.disconnect()
# Step 3. Long format, one row per stock and trading day, saved as one CSV file
panel = pd.concat(frames, ignore_index=True)[["date", "symbol", "con_id", "open", "high", "low", "close",
"volume"]]
FOLDER.mkdir(parents=True, exist_ok=True)
panel.to_csv(FOLDER / "ibkr_daily_prices.csv", index=False)
print(len(panel), "rows saved")Full post: Interactive Brokers API in Python: download historical prices with ib_async