跳转到内容

历史行情

get_historical_data() 是对原始历史 K 线回调的同步封装。它对应原始 TWS API 的:

reqHistoricalData(
reqId, contract, endDateTime, durationStr, barSizeSetting,
whatToShow, useRTH, formatDate, keepUpToDate, chartOptions
)
-> historicalData(reqId, bar)
-> historicalDataEnd(reqId, start, end)

同步封装会收集所有 historicalData() 回调,在收到 historicalDataEnd() 后返回 BarData 列表。

def get_historical_data(
self,
contract,
end_date_time,
duration_str,
bar_size_setting,
what_to_show,
use_rth=True,
format_date=1,
timeout=30,
):
req_id = self.get_next_valid_id()
self.reqHistoricalData(
req_id,
contract,
end_date_time,
duration_str,
bar_size_setting,
what_to_show,
use_rth,
format_date,
False,
[],
)
return self._wait_for_response(req_id, "historical_data", timeout)
参数中文含义示例
contract要查询的合约AAPL 股票合约
end_date_time结束时间;空字符串表示可用的最新时间""
duration_str回看多长时间"1 D""1 W""1 M"
bar_size_settingK 线周期"5 mins""1 hour""1 day"
what_to_show数据类型"TRADES""MIDPOINT""BID""ASK"
use_rth是否只使用常规交易时段True
format_date日期格式1 返回可读字符串,2 返回 Unix 时间
timeout等待历史数据结束回调的秒数30
from ibapi.contract import Contract
from ibapi.sync_wrapper import TWSSyncWrapper, ResponseTimeout
def stock_contract(symbol: str, currency: str = "USD") -> Contract:
contract = Contract()
contract.symbol = symbol
contract.secType = "STK"
contract.exchange = "SMART"
contract.currency = currency
contract.primaryExchange = "NASDAQ"
return contract
app = TWSSyncWrapper(timeout=30)
try:
if not app.connect_and_start("127.0.0.1", 7497, 949):
raise RuntimeError("连接 TWS API 失败")
bars = app.get_historical_data(
contract=stock_contract("AAPL"),
end_date_time="", # 空字符串表示请求最近可用时间之前的数据
duration_str="1 D", # 回看 1 天
bar_size_setting="5 mins", # 每根 K 线 5 分钟
what_to_show="TRADES", # 成交数据
use_rth=True, # 只要常规交易时段
format_date=1, # 返回可读时间字符串
timeout=30,
)
print(f"BAR_COUNT={len(bars)}")
for bar in bars[:3]:
print(
bar.date,
bar.open,
bar.high,
bar.low,
bar.close,
bar.volume,
)
except ResponseTimeout:
print("历史数据请求超时:没有在超时时间内收到 historicalDataEnd 回调")
finally:
app.disconnect_and_stop()
BAR_COUNT=78
FIRST_DATE=20260612 09:30:00 US/Eastern
FIRST_OPEN=295.9
FIRST_HIGH=297.14
FIRST_LOW=294.89
FIRST_CLOSE=295.35
FIRST_VOLUME=1472090

78 根 5 分钟 K 线对应美股常规交易时段 6.5 小时。这个结果说明连接、合约、历史数据 farm 和参数组合都正常。

get_historical_data() 返回的是 BarData 对象列表。常用字段如下:

字段中文含义
dateK 线开始时间或日期
open开盘价
high最高价
low最低价
close收盘价
volume成交量
wap加权平均价
barCount该 K 线内的成交笔数或聚合数量
中文含义常见用途
TRADES成交价数据股票、期货等常规 K 线
MIDPOINT买卖中间价外汇、点差较重要的品种
BID买价分析买盘报价
ASK卖价分析卖盘报价
BID_ASK买卖价组合价差分析
HISTORICAL_VOLATILITY历史波动率期权相关分析
OPTION_IMPLIED_VOLATILITY期权隐含波动率期权相关分析

不是所有品种都支持所有 what_to_show。如果请求失败,先换成最常用的 TRADESMIDPOINT 验证合约和连接。

现象常见原因处理方式
ResponseTimeout请求过大、网络慢、没有收到结束回调缩小 duration_str,增大 timeout
返回空列表非交易日、合约不准确或数据不可用先用 get_contract_details() 确认合约
权限错误账户没有对应历史数据权限换延迟/可用数据类型,或说明权限限制
数据时间看起来不对没处理交易所时区保存原始 bar.datetimeZoneId

IBKR Campus: TWS API Documentation