Coverage for data_pipeline/ib_backfill.py: 100%

103 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-22 12:55 +0000

1"""Interactive Brokers historical-data backfill for futures/options - 

2mirrors yfinance_backfill.py's shape (pure helpers + one deferred-import 

3boundary + orchestration), using `ib_insync` (add to requirements/dev.txt 

4only, never requirements.txt - same "dev-only dependency" convention as 

5yfinance). 

6 

7This module is ONLY for the offline historical-bars-to-local-Lean-zip step. 

8It does NOT touch live/paper trading, which stays entirely on Lean's own 

9InteractiveBrokersBrokerage (lean.json's ib-account/ib-user-name/ 

10ib-password/ib-trading-mode fields and the environments.live-interactive 

11block - both untouched by this module). Lean's backtesting environment 

12(environments.backtesting in lean.json) is hardcoded to FileSystemDataFeed + 

13SubscriptionDataReaderHistoryProvider - it never talks to IB no matter what 

14lean.json's ib-* fields hold - so historical futures/options bars still 

15need a separate, offline data-prep step to land as local Lean-format zip 

16files before any backtest can use them. That is this module's entire job. 

17 

18Connects to the same local TWS/IB Gateway process using 

19config.json's phase_v2.ib.host/port/client_id (a second, independent 

20client-id socket connection alongside whatever Lean's own brokerage uses 

21when live-deployed - standard IB API pattern, Gateway supports multiple 

22simultaneous API clients). "IB ready" requires BOTH: 

23 1. config.json's phase_v2.ib.enabled == true (Aether's own app-level 

24 feature flag), AND 

25 2. lean.json's ib-account/ib-user-name are both non-empty (Lean's own 

26 credential fields - untouched, read-only from this module's 

27 perspective). 

28Every public function below raises IBNotConfiguredError, never a raw 

29traceback, when either check fails - see aq_cli.py::cmd_fetch()/cmd_ib() 

30for how that's surfaced to the user. 

31""" 

32 

33from __future__ import annotations 

34 

35import json 

36import logging 

37from pathlib import Path 

38from typing import Any 

39 

40logger = logging.getLogger(__name__) 

41 

42ROOT = Path(__file__).resolve().parents[1] 

43CONFIG_PATH = ROOT / "config.json" 

44LEAN_CONFIG_PATH = ROOT / "lean.json" 

45CONTRACT_SPECS_PATH = ROOT / "data" / "reference" / "futures_contract_specs.json" 

46 

47 

48class IBNotConfiguredError(Exception): 

49 """Raised by every public function in this module when 

50 phase_v2.ib.enabled is false in config.json, or lean.json's 

51 ib-account/ib-user-name are missing - never a raw ConnectionError, so 

52 callers (fetch.py's ASSET_CLASS_CONFIG dispatch, aq fetch's CLI) can 

53 catch one specific, documented exception type and print a clear 

54 message instead of a traceback.""" 

55 

56 

57def ib_enabled(config: dict, lean_config: dict) -> bool: 

58 """Pure, no I/O. True only when config.json's phase_v2.ib.enabled is 

59 truthy AND lean.json's ib-account/ib-user-name are both non-empty - 

60 the toggle and the credentials live in two different, purpose- 

61 appropriate files, cross-checked here.""" 

62 ib_config = config.get("phase_v2", {}).get("ib", {}) 

63 if not ib_config.get("enabled", False): 

64 return False 

65 return bool(lean_config.get("ib-account")) and bool(lean_config.get("ib-user-name")) 

66 

67 

68def ib_readiness_status(config: dict, lean_config: dict) -> str: 

69 """One of "disabled" / "enabled_but_lean_credentials_missing" / 

70 "ready" - the three states aq_cli.py::cmd_ib() reports (a real 

71 connect/disconnect round-trip is a separate, heavier check layered on 

72 top of this pure classification, see attempt_connection() below).""" 

73 ib_config = config.get("phase_v2", {}).get("ib", {}) 

74 if not ib_config.get("enabled", False): 

75 return "disabled" 

76 if not (lean_config.get("ib-account") and lean_config.get("ib-user-name")): 

77 return "enabled_but_lean_credentials_missing" 

78 return "ready" 

79 

80 

81def load_futures_contract_specs(path: Path = CONTRACT_SPECS_PATH) -> dict: 

82 try: 

83 with path.open("r", encoding="utf-8") as handle: 

84 data = json.load(handle) 

85 except (OSError, json.JSONDecodeError) as exc: 

86 logger.warning("load_futures_contract_specs(%s): unreadable — %s", path, exc) 

87 return {} 

88 return {key: value for key, value in data.items() if not key.startswith("_")} 

89 

90 

91# --------------------------------------------------------------------------- 

92# The only functions that import ib_insync - deferred, mirrors 

93# yfinance_backfill.fetch_yahoo_ohlcv()'s deferred `import yfinance`. 

94# --------------------------------------------------------------------------- 

95 

96 

97def connect_ib(config: dict, lean_config: dict) -> Any: 

98 """Raises IBNotConfiguredError if not ib_enabled(config, lean_config). 

99 Never called at import time - this module must stay importable with 

100 ib_insync absent when IB is disabled, same convention as 

101 yfinance_backfill.py.""" 

102 if not ib_enabled(config, lean_config): 

103 raise IBNotConfiguredError( 

104 "IB is not configured: run 'aq config set phase_v2.ib.enabled true' and fill in " 

105 "lean.json's ib-account/ib-user-name first (see 'aq ib status')." 

106 ) 

107 

108 from ib_insync import IB # deferred - dev-only dependency, never in requirements.txt 

109 

110 ib_config = config["phase_v2"]["ib"] 

111 ib = IB() 

112 ib.connect( 

113 str(ib_config.get("host", "127.0.0.1")), 

114 int(ib_config.get("port", 7497)), 

115 clientId=int(ib_config.get("client_id", 7)), 

116 timeout=float(ib_config.get("connect_timeout_seconds", 10)), 

117 readonly=True, 

118 ) 

119 return ib 

120 

121 

122def disconnect_ib(ib: Any) -> None: 

123 ib.disconnect() 

124 

125 

126def attempt_connection(config: dict, lean_config: dict) -> tuple[bool, str]: 

127 """Best-effort connect/disconnect round-trip for aq_cli.py::cmd_ib()'s 

128 "reachable" tri-state check. Returns (True, "reachable") or 

129 (False, <reason>) - never raises (any connection failure is caught and 

130 reported, since this is a diagnostic command, not a data operation).""" 

131 try: 

132 ib = connect_ib(config, lean_config) 

133 except IBNotConfiguredError as exc: 

134 return False, str(exc) 

135 except Exception as exc: # any connection failure is reported, never raised 

136 return False, f"connection failed — {exc}" 

137 else: 

138 disconnect_ib(ib) 

139 return True, "reachable" 

140 

141 

142def _bar_rows_from_ib(bars: list) -> list[dict]: 

143 """Normalizes ib_insync's BarData objects (each with .date/.open/.high/ 

144 .low/.close/.volume) into the same row shape fetch_yahoo_ohlcv() 

145 returns, so they slot into scale_for_lean()/write_lean_zip() unchanged.""" 

146 rows = [] 

147 for bar in bars: 

148 bar_date = bar.date.date() if hasattr(bar.date, "date") else bar.date 

149 rows.append( 

150 { 

151 "date": bar_date, 

152 "open": float(bar.open), 

153 "high": float(bar.high), 

154 "low": float(bar.low), 

155 "close": float(bar.close), 

156 "volume": float(bar.volume), 

157 } 

158 ) 

159 return rows 

160 

161 

162def fetch_future_historical_bars( 

163 ib: Any, 

164 ticker: str, 

165 contract_spec: dict, 

166 start: str, 

167 end: str, 

168 contract_month: str | None = None, 

169) -> list[dict]: 

170 """Historical daily bars for `ticker`'s future via ib_insync + 

171 reqHistoricalData. contract_month=None (default): the continuous 

172 front-month contract (ContFuture) - correct for live/current sizing, 

173 but each call only ever sees "whatever is currently front-month," not 

174 a stable historical series. contract_month="YYYYMM": a SPECIFIC dated 

175 Future(...) contract instead - lets a caller fetch e.g. both an 

176 "ES_FRONT" and "ES_NEXT" ticker (aq_cli.py's --contract-month, 

177 grouped via --family-ticker) for a real historical front/next-month 

178 term-structure pair (train.py::build_derivatives_macro_features_by_date()), 

179 which a single continuous series can't provide on its own. 

180 

181 Returns [] (never raises) on any IB-side failure or empty response, 

182 matching fetch_yahoo_ohlcv()'s "one bad symbol never aborts a multi- 

183 asset run" convention.""" 

184 from ib_insync import ContFuture, Future, util 

185 

186 try: 

187 if contract_month: 

188 contract = Future( 

189 ticker, lastTradeDateOrContractMonth=contract_month, 

190 exchange=contract_spec.get("exchange", "CME"), currency="USD", 

191 ) 

192 else: 

193 contract = ContFuture(ticker, exchange=contract_spec.get("exchange", "CME"), currency="USD") 

194 ib.qualifyContracts(contract) 

195 duration_days = max((util.parseIBDatetime(end) - util.parseIBDatetime(start)).days, 1) 

196 bars = ib.reqHistoricalData( 

197 contract, 

198 endDateTime=end, 

199 durationStr=f"{duration_days} D", 

200 barSizeSetting="1 day", 

201 whatToShow="TRADES", 

202 useRTH=True, 

203 formatDate=1, 

204 ) 

205 except Exception as exc: 

206 logger.warning("fetch_future_historical_bars(%s): fetch failed — %s", ticker, exc) 

207 return [] 

208 

209 return _bar_rows_from_ib(bars or []) 

210 

211 

212def fetch_option_chain_snapshot(ib: Any, underlying_ticker: str, expiry: str) -> list[dict]: 

213 """One row per (strike, right) for underlying_ticker's chain at expiry 

214 - {strike, right, expiry, bid, ask, last, volume, open_interest} - 

215 the raw chain snapshot features/options_greeks.py's compute_greeks() 

216 consumes to attach delta/gamma/theta/vega/iv before 

217 portfolio/options_strategy.py selects a contract. Returns [] on any 

218 failure - never raises.""" 

219 from ib_insync import Option, Stock 

220 

221 try: 

222 underlying = Stock(underlying_ticker, "SMART", "USD") 

223 ib.qualifyContracts(underlying) 

224 chain_params = ib.reqSecDefOptParams(underlying.symbol, "", underlying.secType, underlying.conId) 

225 strikes: set[float] = set() 

226 for param in chain_params: 

227 if expiry in param.expirations: 

228 strikes.update(param.strikes) 

229 

230 rows: list[dict] = [] 

231 for strike in sorted(strikes): 

232 for right in ("C", "P"): 

233 option = Option(underlying_ticker, expiry, float(strike), right, "SMART") 

234 ib.qualifyContracts(option) 

235 ticker_data = ib.reqMktData(option, "", False, False) 

236 ib.sleep(0.2) 

237 rows.append( 

238 { 

239 "strike": float(strike), 

240 "right": "call" if right == "C" else "put", 

241 "expiry": expiry, 

242 "bid": float(ticker_data.bid) if ticker_data.bid == ticker_data.bid else None, 

243 "ask": float(ticker_data.ask) if ticker_data.ask == ticker_data.ask else None, 

244 "last": float(ticker_data.last) if ticker_data.last == ticker_data.last else None, 

245 "volume": float(ticker_data.volume) if ticker_data.volume == ticker_data.volume else None, 

246 "open_interest": None, 

247 } 

248 ) 

249 return rows 

250 except Exception as exc: 

251 logger.warning("fetch_option_chain_snapshot(%s, %s): fetch failed — %s", underlying_ticker, expiry, exc) 

252 return [] 

253 

254 

255def fetch_option_historical_bars( 

256 ib: Any, 

257 underlying_ticker: str, 

258 expiry: str, 

259 strike: float, 

260 right: str, 

261 start: str, 

262 end: str, 

263) -> list[dict]: 

264 """Historical daily bars for one specific option contract. Same 

265 OHLCV row shape as futures/equities. Returns [] on any failure - 

266 never raises.""" 

267 from ib_insync import Option, util 

268 

269 try: 

270 ib_right = "C" if right.lower() == "call" else "P" 

271 contract = Option(underlying_ticker, expiry, float(strike), ib_right, "SMART") 

272 ib.qualifyContracts(contract) 

273 duration_days = max((util.parseIBDatetime(end) - util.parseIBDatetime(start)).days, 1) 

274 bars = ib.reqHistoricalData( 

275 contract, 

276 endDateTime=end, 

277 durationStr=f"{duration_days} D", 

278 barSizeSetting="1 day", 

279 whatToShow="TRADES", 

280 useRTH=True, 

281 formatDate=1, 

282 ) 

283 except Exception as exc: 

284 logger.warning("fetch_option_historical_bars(%s %s %s%s): fetch failed — %s", underlying_ticker, expiry, strike, right, exc) 

285 return [] 

286 

287 return _bar_rows_from_ib(bars or [])