You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何使用ib_insync库获取未到期期权合约的历史数据?

Fetching Intraday Historical Data for Unexpired Options with ib_insync

Absolutely, you can retrieve hourly (or finer-grained) historical data for unexpired options contracts using the ib_insync library—this is fully supported by IBKR's TWS API, and ib_insync wraps the necessary calls in a Python-friendly way. Here's a step-by-step guide with code examples:

Step 1: Set Up the IB Connection

First, establish a connection to your running TWS or IB Gateway instance. Make sure TWS is configured to allow API access (check "Enable Active X and Socket Clients" in TWS Settings > API).

from ib_insync import IB, Option, util
import pandas as pd

# Initialize IB client and connect
ib = IB()
# Use port 7497 for TWS paper trading, 7496 for live; 4001/4002 for IB Gateway
ib.connect('127.0.0.1', 7497, clientId=1)

Step 2: Define or Locate Your Target Option Contract

Options require precise contract details to avoid errors. You can either define the contract directly or search for valid unexpired contracts for an underlying asset.

Option 1: Define the Contract Manually

Specify the underlying symbol, expiration date (format: YYYYMMDD), strike price, option type (CALL/PUT), exchange, and currency:

# Example: AAPL $200 Call expiring June 21, 2024
target_option = Option(
    symbol='AAPL',
    lastTradeDateOrContractMonth='20240621',
    strike=200,
    right='CALL',
    exchange='SMART',
    currency='USD'
)

# Validate the contract exists (recommended)
contract_details = ib.reqContractDetails(target_option)
if not contract_details:
    print("Error: No matching contract found. Double-check your parameters.")
    ib.disconnect()
    exit()
# Use the first valid contract from the results
valid_option = contract_details[0].contract

Option 2: Search for All Unexpired Options on an Underlying

If you don't know the exact contract details, search for all options on the underlying and filter for unexpired ones:

from ib_insync import Stock
from datetime import datetime

# Define the underlying stock
underlying = Stock('AAPL', 'SMART', 'USD')

# Request all option contracts for the underlying
option_chains = ib.reqSecDefOptParams(
    underlying.symbol, '', underlying.secType, underlying.conId
)

# Filter for unexpired contracts
current_date = datetime.now().strftime('%Y%m%d')
unexpired_chains = [chain for chain in option_chains if any(exp > current_date for exp in chain.expirations)]

# Pick an expiration and strike from the filtered chains
target_expiry = unexpired_chains[0].expirations[0]
target_strike = unexpired_chains[0].strikes[len(unexpired_chains[0].strikes)//2]

# Build the option contract
target_option = Option(
    symbol='AAPL',
    lastTradeDateOrContractMonth=target_expiry,
    strike=target_strike,
    right='CALL',
    exchange='SMART',
    currency='USD'
)
valid_option = ib.reqContractDetails(target_option)[0].contract

Step 3: Request Historical Intraday Data

Use ib.reqHistoricalData() to pull the data. Configure parameters to get your desired granularity and time range:

# Request hourly data for the last 30 days
bars = ib.reqHistoricalData(
    contract=valid_option,
    endDateTime='',  # Leave empty to get data up to now
    durationStr='30 D',  # Time range to fetch (e.g., '1 D', '7 D', '1 M')
    barSizeSetting='1 hour',  # Granularity: '1 min', '5 mins', '1 hour', etc.
    whatToShow='MIDPOINT',  # Options: 'TRADES', 'BID', 'ASK', 'MIDPOINT'
    useRTH=True,  # Set to False to include pre/post market data
    keepUpToDate=False,  # Disable real-time updates (we want historical only)
    formatDate=1  # Return dates as Python datetime objects
)

# Convert the bar data to a pandas DataFrame for analysis
df = util.df(bars)
print(df[['date', 'open', 'high', 'low', 'close', 'volume']].head())

Key Notes & Troubleshooting

  • Data Permissions: Ensure your IBKR account has permission to access option historical data. If you get empty results, check your account settings or contact IBKR support.
  • Liquidity Limits: Low-liquidity options may not have intraday data available (IBKR only stores data for contracts with trading activity). Stick to actively traded options for finer granularity.
  • Rate Limits: Avoid making too many rapid requests—IBKR enforces API rate limits to prevent abuse.
  • Contract Validity: Always validate contracts with reqContractDetails() to avoid invalid contract errors.

Once you're done, don't forget to disconnect the IB client:

ib.disconnect()

内容的提问来源于stack exchange,提问作者khrizz

火山引擎 最新活动