"""Pull live IBKR futures chains and plot forward curves. Default test case: python scripts/live/plot_ibkr_forward_curve.py That connects to TWS paper-trading on 127.0.0.1:7497, pulls the default commodity futures set listed up to 3 years forward, and writes a PNG plus CSV under data/processed/futures_forward_curves/. Prereqs: - TWS or IB Gateway running with API socket access enabled. - Futures market data subscriptions/permissions for the requested contracts. - Python packages: ib_async, matplotlib. """ from __future__ import annotations import argparse import math from collections.abc import Iterable from dataclasses import dataclass from datetime import date, datetime, timedelta from pathlib import Path from typing import Any import pandas as pd REPO_ROOT = Path(__file__).resolve().parents[2] DEFAULT_SYMBOLS = ["WTI", "BZ", "NG", "GC", "SI", "PL", "PA", "HG", "ZW", "ZC", "ZS", "SB"] SYMBOL_ALIASES = { "WTI": "CL", # IBKR uses CL for WTI futures. NYMEX classifies the underlying crude oil as light and sweet. } DEFAULT_EXCHANGES = { "CL": "NYMEX", # WTI crude oil "WTI": "NYMEX", # The code resolves this alias to CL before IBKR requests. "GC": "COMEX", # Gold "SI": "COMEX", # Silver "HG": "COMEX", # Copper "PL": "NYMEX", # Platinum "PA": "NYMEX", # Palladium "NG": "NYMEX", # Natural gas at Henry Hub "BZ": "NYMEX", # Brent crude oil "ZC": "CBOT", # Corn "SB": "NYBOT", # Sugar No. 11 "ZW": "CBOT", # Chicago wheat "ZS": "CBOT", # Soybeans } DEFAULT_EXCHANGE_CANDIDATES = { "ZC": ["CBOT", "ECBOT"], # IBKR often requires CBOT. Some feeds use ECBOT. "ZW": ["CBOT", "ECBOT"], "ZS": ["CBOT", "ECBOT"], "SB": ["NYBOT", "ICEUS"], # IBKR commonly uses NYBOT for ICE US softs. } DEFAULT_LABELS = { "WTI": "WTI Light Sweet Crude Oil", "CL": "WTI Light Sweet Crude Oil", "GC": "Gold", "SI": "Silver", "HG": "Copper", "PL": "Platinum", "PA": "Palladium", "NG": "Henry Hub Natural Gas", "BZ": "Brent Crude Oil", "ZC": "Corn", "SB": "Sugar No. 11", "ZW": "Chicago Wheat", "ZS": "Soybeans", } COMMODITY_GROUPS = { "WTI": "Energy", "CL": "Energy", "BZ": "Energy", "NG": "Energy", "GC": "Metals", "SI": "Metals", "PL": "Metals", "PA": "Metals", "HG": "Metals", "ZW": "Agriculture", "ZC": "Agriculture", "ZS": "Agriculture", "SB": "Agriculture", } SYMBOL_SORT_ORDER = {symbol: idx for idx, symbol in enumerate(DEFAULT_SYMBOLS)} CURVE_COLORS = [ "#69d2e7", "#f5c542", "#f48fb1", "#a3e635", "#c084fc", "#fb923c", "#38bdf8", "#f87171", "#34d399", "#e879f9", ] MARKET_DATA_TYPES = { "live": 1, "frozen": 2, "delayed": 3, "delayed-frozen": 4, } MARKET_DATA_CHOICES = ["auto", *sorted(MARKET_DATA_TYPES)] AUTO_MARKET_DATA_SEQUENCE = ["live", "delayed"] SYMBOL_MARKET_DATA_SEQUENCES = { "SB": ["delayed"], } @dataclass(frozen=True) class CurvePoint: root: str label: str exchange: str local_symbol: str contract_month: str expiry: date price: float price_asof: date | None price_source: str market_data_type: str bid: float | None ask: float | None last: float | None close: float | None volume: float | None con_id: int | None def _month_end(year: int, month: int) -> date: if month == 12: return date(year, 12, 31) return date(year, month + 1, 1) - timedelta(days=1) def parse_ib_expiry(value: str) -> date: """Parse IBKR lastTradeDateOrContractMonth values like YYYYMM or YYYYMMDD.""" value = str(value).strip() if len(value) == 8: return datetime.strptime(value, "%Y%m%d").date() if len(value) == 6: year = int(value[:4]) month = int(value[4:6]) return _month_end(year, month) raise ValueError(f"Cannot parse IBKR futures expiry: {value!r}") def add_years(day: date, years: int) -> date: try: return day.replace(year=day.year + years) except ValueError: # A non-leap target year uses February 28 instead of February 29. return day.replace(month=2, day=28, year=day.year + years) def has_horizon_coverage(expiries: Iterable[date], horizon: date, tolerance_days: int) -> bool: """Return true when at least one expiry lands close enough to the target horizon.""" earliest_accepted = horizon - timedelta(days=tolerance_days) return any(expiry >= earliest_accepted for expiry in expiries) def _as_float_or_none(value: Any) -> float | None: try: out = float(value) except (TypeError, ValueError): return None if not math.isfinite(out): return None return out def _positive(value: Any) -> float | None: out = _as_float_or_none(value) if out is None or out <= 0: return None return out def _as_int_or_none(value: Any) -> int | None: try: return int(value) except (TypeError, ValueError): return None def _bar_date_to_date(value: Any) -> date | None: if isinstance(value, datetime): return value.date() if isinstance(value, date): return value text = str(value).strip() if not text: return None for fmt in ("%Y%m%d", "%Y-%m-%d"): try: return datetime.strptime(text[:10], fmt).date() except ValueError: continue return None def choose_curve_price(ticker: Any) -> tuple[float | None, str]: """Choose a curve price from an IBKR ticker. Midpoint is preferred because back-month last trades can be stale. If no usable bid/ask exists, fall back to ib_async's marketPrice(), then last, then close. """ bid = _positive(getattr(ticker, "bid", None)) ask = _positive(getattr(ticker, "ask", None)) if bid is not None and ask is not None and ask >= bid: return (bid + ask) / 2.0, "mid" market_price = None market_price_method = getattr(ticker, "marketPrice", None) if callable(market_price_method): market_price = _positive(market_price_method()) if market_price is not None: return market_price, "marketPrice" last = _positive(getattr(ticker, "last", None)) if last is not None: return last, "last" close = _positive(getattr(ticker, "close", None)) if close is not None: return close, "close" return None, "missing" def choose_historical_price(bars: Iterable[Any]) -> tuple[float | None, date | None]: """Choose the latest positive close from IBKR historical bars.""" for bar in reversed(list(bars)): price = _positive(getattr(bar, "close", None)) if price is not None: return price, _bar_date_to_date(getattr(bar, "date", None)) return None, None def parse_exchange_map(items: list[str]) -> dict[str, str]: out = dict(DEFAULT_EXCHANGES) for item in items: if "=" not in item: raise ValueError(f"Exchange override must look like ROOT=EXCHANGE, got {item!r}") root, exchange = item.split("=", 1) root = root.strip().upper() exchange = exchange.strip().upper() if not root or not exchange: raise ValueError(f"Exchange override must look like ROOT=EXCHANGE, got {item!r}") out[root] = exchange return out def resolve_ib_root(root: str) -> str: return SYMBOL_ALIASES.get(root.upper(), root.upper()) def exchange_candidates(root: str, primary_exchange: str) -> list[str]: """Return venue names to try for a root, preserving the configured primary first.""" out = [primary_exchange.upper()] for candidate in DEFAULT_EXCHANGE_CANDIDATES.get(root.upper(), []): candidate = candidate.upper() if candidate not in out: out.append(candidate) return out def commodity_group(root: str) -> str: return COMMODITY_GROUPS.get(root.upper(), "Other") def symbol_sort_key(root: str) -> int: return SYMBOL_SORT_ORDER.get(root.upper(), len(SYMBOL_SORT_ORDER)) def market_data_type_sequence(value: str, root: str | None = None) -> list[str]: if value == "auto": if root is not None and root.upper() in SYMBOL_MARKET_DATA_SEQUENCES: return list(SYMBOL_MARKET_DATA_SEQUENCES[root.upper()]) return list(AUTO_MARKET_DATA_SEQUENCE) if value not in MARKET_DATA_TYPES: raise ValueError(f"Unknown market data type: {value!r}") return [value] def load_ib_async() -> tuple[Any, Any]: try: from ib_async import IB, Future except ImportError as exc: raise SystemExit( "Missing dependency: ib_async. Install requirements or run " "`python -m pip install ib_async matplotlib`." ) from exc return IB, Future def discover_futures_contracts( ib: Any, future_factory: Any, root: str, exchange: str, currency: str, asof: date, horizon: date, max_contracts: int | None, ) -> list[Any]: template = future_factory(symbol=resolve_ib_root(root), exchange=exchange, currency=currency) details = ib.reqContractDetails(template) contracts: list[Any] = [] seen: set[int | str] = set() for detail in details: contract = detail.contract last_trade = str(getattr(contract, "lastTradeDateOrContractMonth", "") or "") if not last_trade: continue try: expiry = parse_ib_expiry(last_trade) except ValueError: continue if expiry < asof or expiry > horizon: continue key = getattr(contract, "conId", None) or getattr(contract, "localSymbol", last_trade) if key in seen: continue seen.add(key) contracts.append(contract) contracts.sort( key=lambda c: parse_ib_expiry(str(getattr(c, "lastTradeDateOrContractMonth", ""))) ) if max_contracts is not None: contracts = contracts[:max_contracts] return contracts def discover_futures_contracts_with_fallbacks( ib: Any, future_factory: Any, root: str, primary_exchange: str, currency: str, asof: date, horizon: date, max_contracts: int | None, ) -> tuple[list[Any], str | None, list[str]]: attempts: list[str] = [] for exchange in exchange_candidates(root, primary_exchange): try: contracts = discover_futures_contracts( ib=ib, future_factory=future_factory, root=root, exchange=exchange, currency=currency, asof=asof, horizon=horizon, max_contracts=max_contracts, ) except Exception as exc: # noqa: BLE001 attempts.append(f"{exchange}: {exc}") continue if contracts: attempts.append(f"{exchange}: {len(contracts)} contracts") return contracts, exchange, attempts attempts.append(f"{exchange}: no contracts") return [], None, attempts def fetch_curve_points( ib: Any, contracts: list[Any], root: str, label: str, exchange: str, market_data_type: str, ) -> list[CurvePoint]: if not contracts: return [] tickers = ib.reqTickers(*contracts) points: list[CurvePoint] = [] for contract, ticker in zip(contracts, tickers, strict=True): price, source = choose_curve_price(ticker) if price is None: continue last_trade = str(getattr(contract, "lastTradeDateOrContractMonth", "")) expiry = parse_ib_expiry(last_trade) points.append( CurvePoint( root=root, label=label, exchange=exchange, local_symbol=str(getattr(contract, "localSymbol", "") or ""), contract_month=last_trade[:6], expiry=expiry, price=float(price), price_asof=None, price_source=source, market_data_type=market_data_type, bid=_as_float_or_none(getattr(ticker, "bid", None)), ask=_as_float_or_none(getattr(ticker, "ask", None)), last=_as_float_or_none(getattr(ticker, "last", None)), close=_as_float_or_none(getattr(ticker, "close", None)), volume=_as_float_or_none(getattr(ticker, "volume", None)), con_id=_as_int_or_none(getattr(contract, "conId", None)), ) ) return points def fetch_historical_curve_points( ib: Any, contracts: list[Any], root: str, label: str, exchange: str, lookback_days: int, ) -> list[CurvePoint]: """Fallback to recent daily closes when quote snapshots return no prices.""" if not contracts: return [] points: list[CurvePoint] = [] for contract in contracts: last_trade = str(getattr(contract, "lastTradeDateOrContractMonth", "")) try: bars = ib.reqHistoricalData( contract, endDateTime="", durationStr=f"{lookback_days} D", barSizeSetting="1 day", whatToShow="TRADES", useRTH=False, formatDate=1, ) except Exception: continue price, price_asof = choose_historical_price(bars) if price is None: continue expiry = parse_ib_expiry(last_trade) points.append( CurvePoint( root=root, label=label, exchange=exchange, local_symbol=str(getattr(contract, "localSymbol", "") or ""), contract_month=last_trade[:6], expiry=expiry, price=float(price), price_asof=price_asof, price_source="historical_close", market_data_type="historical", bid=None, ask=None, last=None, close=float(price), volume=None, con_id=_as_int_or_none(getattr(contract, "conId", None)), ) ) return points def points_to_frame(points: list[CurvePoint]) -> pd.DataFrame: rows = [ { "root": p.root, "commodity_group": commodity_group(p.root), "symbol_order": symbol_sort_key(p.root), "label": p.label, "exchange": p.exchange, "local_symbol": p.local_symbol, "contract_month": p.contract_month, "expiry": p.expiry, "price": p.price, "price_asof": p.price_asof, "price_source": p.price_source, "market_data_type": p.market_data_type, "bid": p.bid, "ask": p.ask, "last": p.last, "close": p.close, "volume": p.volume, "con_id": int(p.con_id) if p.con_id is not None else None, } for p in points ] if not rows: return pd.DataFrame() return pd.DataFrame(rows).sort_values(["symbol_order", "expiry"]).reset_index(drop=True) def plot_curves(df: pd.DataFrame, output_path: Path, asof: date, horizon: date) -> None: try: import matplotlib.dates as mdates import matplotlib.pyplot as plt except ImportError as exc: raise SystemExit( "Missing dependency: matplotlib. Install requirements or run " "`python -m pip install matplotlib`." ) from exc ordered = df.sort_values(["symbol_order", "expiry"]) if "symbol_order" in df else df roots = list(ordered["root"].drop_duplicates()) ncols = 2 if len(roots) > 1 else 1 nrows = math.ceil(len(roots) / ncols) fig, axes = plt.subplots( nrows=nrows, ncols=ncols, figsize=(15, 3.9 * nrows), sharex=False, constrained_layout=True, ) fig.patch.set_facecolor("#111827") flat_axes = list(axes.ravel()) if hasattr(axes, "ravel") else [axes] for idx, (ax, root) in enumerate(zip(flat_axes, roots, strict=False)): sub = df[df["root"] == root].sort_values("expiry") label = str(sub["label"].iloc[0]) color = CURVE_COLORS[idx % len(CURVE_COLORS)] ax.set_facecolor("#182235") ax.plot( sub["expiry"], sub["price"], marker="o", linewidth=1.8, markersize=4.5, color=color, markerfacecolor=color, markeredgecolor="#0b1020", markeredgewidth=0.6, ) ax.set_title( f"{root} Forward Curve - {label}", loc="left", fontsize=12, fontweight="bold", color="#f8fafc", ) ax.set_ylabel("Price") ax.yaxis.label.set_color("#cbd5e1") ax.grid(True, color="#334155", linewidth=0.7, alpha=0.75) ax.spines[["top", "right"]].set_visible(False) ax.spines[["left", "bottom"]].set_color("#64748b") ax.tick_params(axis="both", colors="#cbd5e1", labelsize=9) for idx, row in sub.reset_index(drop=True).iterrows(): if idx == 0 or idx == len(sub) - 1 or idx % 4 == 0: ax.annotate( str(row["local_symbol"] or row["contract_month"]), xy=(row["expiry"], row["price"]), xytext=(0, 8), textcoords="offset points", ha="center", fontsize=8, color="#e2e8f0", ) ax.xaxis.set_major_locator(mdates.MonthLocator(interval=3)) ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m")) ax.tick_params(axis="x", rotation=35) for ax in flat_axes[len(roots):]: ax.set_visible(False) fig.suptitle( f"IBKR Futures Forward Curves | as of {asof.isoformat()} | through {horizon.isoformat()}", fontsize=14, fontweight="bold", color="#f8fafc", ) output_path.parent.mkdir(parents=True, exist_ok=True) fig.savefig(output_path, dpi=160, facecolor=fig.get_facecolor()) plt.close(fig) def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser( description="Pull IBKR futures chains and chart forward curves up to N years forward." ) parser.add_argument("--host", default="127.0.0.1", help="TWS/IB Gateway API host") parser.add_argument( "--port", type=int, default=7497, help="API port. Common defaults: TWS paper=7497, TWS live=7496, IBG paper=4002.", ) parser.add_argument("--client-id", type=int, default=19, help="IBKR API client id") parser.add_argument( "--symbols", nargs="+", default=DEFAULT_SYMBOLS, help="Futures root symbols to chart. Default: WTI BZ NG GC SI PL PA HG ZW ZC ZS SB", ) parser.add_argument( "--exchange-map", nargs="*", default=[], help="Optional root exchange overrides, e.g. CL=NYMEX GC=COMEX", ) parser.add_argument("--currency", default="USD", help="Contract currency") parser.add_argument("--years-forward", type=int, default=3, help="Forward curve horizon") parser.add_argument( "--require-full-horizon", action="store_true", help="Skip symbols whose listed contracts do not reach close to --years-forward.", ) parser.add_argument( "--horizon-tolerance-days", type=int, default=45, help="Tolerance used with --require-full-horizon. Default: 45 days.", ) parser.add_argument( "--market-data-type", choices=MARKET_DATA_CHOICES, default="auto", help="IBKR market data type to request. auto tries live, then delayed.", ) parser.add_argument( "--max-contracts-per-symbol", type=int, default=None, help="Optional cap after date filtering; useful when testing permissions.", ) parser.add_argument( "--no-historical-fallback", action="store_true", help="Do not use recent daily historical closes when snapshots return no prices.", ) parser.add_argument( "--historical-lookback-days", type=int, default=10, help="Daily-bar lookback for historical close fallback. Default: 10.", ) parser.add_argument( "--output", type=Path, default=None, help="PNG output path. Defaults to data/processed/futures_forward_curves/ibkr_forward_curve_YYYYMMDD.png", ) parser.add_argument( "--csv", type=Path, default=None, help="CSV output path. Defaults to same stem as the PNG.", ) parser.add_argument("--no-csv", action="store_true", help="Skip CSV output") return parser.parse_args() def main() -> None: args = parse_args() asof = date.today() horizon = add_years(asof, args.years_forward) symbols = [s.upper() for s in args.symbols] exchanges = parse_exchange_map(args.exchange_map) default_dir = REPO_ROOT / "data" / "processed" / "futures_forward_curves" output_path = args.output or default_dir / f"ibkr_forward_curve_{asof:%Y%m%d}.png" csv_path = args.csv or output_path.with_suffix(".csv") IB, Future = load_ib_async() ib = IB() all_points: list[CurvePoint] = [] skipped: list[tuple[str, str]] = [] try: print(f"Connecting to IBKR at {args.host}:{args.port} (clientId={args.client_id})...") ib.connect(args.host, args.port, clientId=args.client_id) for root in symbols: exchange = exchanges.get(root) if exchange is None: reason = f"no exchange configured. Pass --exchange-map {root}=EXCHANGE" skipped.append((root, reason)) print(f"Skipping {root}: {reason}.") continue ib_root = resolve_ib_root(root) root_note = f" as {ib_root}" if ib_root != root else "" candidates = exchange_candidates(root, exchange) print( f"Discovering {root}{root_note} contracts on " f"{'/'.join(candidates)} through {horizon.isoformat()}..." ) contracts, resolved_exchange, discovery_attempts = discover_futures_contracts_with_fallbacks( ib=ib, future_factory=Future, root=root, primary_exchange=exchange, currency=args.currency, asof=asof, horizon=horizon, max_contracts=args.max_contracts_per_symbol, ) if not contracts or resolved_exchange is None: reason = f"no listed contracts found ({'; '.join(discovery_attempts)})" skipped.append((root, reason)) print(f" skipping {root}: {reason}") continue if resolved_exchange != exchange: print(f" using exchange fallback: {resolved_exchange}") if args.require_full_horizon and not has_horizon_coverage( ( parse_ib_expiry(str(getattr(c, "lastTradeDateOrContractMonth", ""))) for c in contracts ), horizon=horizon, tolerance_days=args.horizon_tolerance_days, ): reason = ( f"no contract within {args.horizon_tolerance_days} days " f"of {horizon.isoformat()}" ) skipped.append((root, reason)) print( f" skipping {root}: {reason}" ) continue print(f" found {len(contracts)} listed contracts; requesting quotes...") points: list[CurvePoint] = [] quote_errors: list[str] = [] for market_data_type in market_data_type_sequence(args.market_data_type, root=root): try: ib.reqMarketDataType(MARKET_DATA_TYPES[market_data_type]) points = fetch_curve_points( ib=ib, contracts=contracts, root=root, label=DEFAULT_LABELS.get(root, root), exchange=resolved_exchange, market_data_type=market_data_type, ) except Exception as exc: # noqa: BLE001 quote_errors.append(f"{market_data_type}: {exc}") points = [] if points: print(f" using {market_data_type} data with {len(points)} priced contracts") break if not points and not args.no_historical_fallback: print( f" no snapshot prices; trying {args.historical_lookback_days}D " "historical closes..." ) points = fetch_historical_curve_points( ib=ib, contracts=contracts, root=root, label=DEFAULT_LABELS.get(root, root), exchange=resolved_exchange, lookback_days=args.historical_lookback_days, ) if points: print(f" using historical closes with {len(points)} priced contracts") if not points: reason = "no usable snapshot or historical prices returned" if quote_errors: reason = f"{reason} ({'; '.join(quote_errors)})" skipped.append((root, reason)) print(f" skipping {root}: {reason}") continue all_points.extend(points) finally: if ib.isConnected(): ib.disconnect() df = points_to_frame(all_points) if df.empty: raise SystemExit( "No curve points returned. Check that TWS/IB Gateway is logged in, API socket access " "is enabled, and your account has the relevant futures market-data permissions." ) if not args.no_csv: csv_path.parent.mkdir(parents=True, exist_ok=True) df.to_csv(csv_path, index=False) print(f"Wrote data: {csv_path}") plot_curves(df, output_path=output_path, asof=asof, horizon=horizon) print(f"Wrote chart: {output_path}") summary = df.sort_values("symbol_order").groupby("root", sort=False).agg( group=("commodity_group", "first"), contracts=("local_symbol", "count"), first_expiry=("expiry", "min"), last_expiry=("expiry", "max"), data_type=("market_data_type", lambda s: ",".join(dict.fromkeys(s.astype(str)))), missing_mid=("price_source", lambda s: int((s != "mid").sum())), ) print("\nCurve summary:") print(summary.to_string()) if skipped: print("\nSkipped markets / proxy candidates:") for root, reason in skipped: print(f" {root}: {reason}") if __name__ == "__main__": main()