
天勤量化获取1分钟图最高价的方法
天勤量化(TqSdk)提供简洁的K线序列订阅接口,获取1分钟图最高价的核心步骤是调用get_kline_serial函数并指定合约、周期和序列长度,函数返回的pandas DataFrame包含high列。
订阅1分钟K线序列
使用get_kline_serial订阅分钟线,参数duration_seconds设为60代表1分钟周期,data_length决定返回的K线数量,最大可设8964根。代码示例如下:
from tqsdk import TqApi, TqAuth
api = TqApi(auth=TqAuth("用户名", "密码"))
klines = api.get_kline_serial("SHFE.rb2405", duration_seconds=60, data_length=200)
while True:
api.wait_update()
if api.is_changing(klines.iloc[-1], "high"):
latest_high = klines.iloc[-1]["high"]
print("最新1分钟K线最高价:", latest_high)
klines是DataFrame对象,行索引从0开始,最新K线位于iloc[-1]。high列存储当前K线周期内的最高价,当该值发生变化时is_changing返回True。

获取历史1分钟最高价
get_kline_serial返回的DataFrame可直接切片获取历史序列。取过去N根1分钟K线的最高价最大值:
import numpy as np
high_series = klines["high"]
max_high_20 = high_series.iloc[-20:].max()
print("最近20根1分钟K线最高价:", max_high_20)
max_high_all = high_series.max()
print("序列内最高价:", max_high_all)
注意data_length越大,内存占用越高,实盘通常100-500根足够。klines的datetime列是纳秒时间戳,可转换为可读时间。
实时监控最高价突破
监控价格是否突破前一根1分钟K线最高价,可用于日内策略。代码示例:
prev_high = klines.iloc[-2]["high"]
current_high = klines.iloc[-1]["high"]
last_price = klines.iloc[-1]["close"]
if last_price > prev_high:
print("价格突破前一根1分钟最高价")
close为最新价,high为当前K线最高价。注意在K线未走完时最高价仍会更新,策略信号应等K线收盘确认。
多合约与多周期
同时订阅多个合约的最高价,循环调用get_kline_serial即可。不同周期混合使用,只需修改duration_seconds,如300代表5分钟。代码片段:
symbols = ["SHFE.rb2405", "DCE.i2405", "CZCE.MA405"]
klines_dict = {}
for sym in symbols:
klines_dict[sym] = api.get_kline_serial(sym, 60, data_length=100)
while True:
api.wait_update()
for sym, k in klines_dict.items():
print(sym, "1分钟最高价:", k.iloc[-1]["high"])
该循环每收到行情更新打印一次最高价,wait_update保证数据同步。若需节省带宽,可仅在is_changing为True时读取。
最高价在量化策略中的应用
1分钟最高价常用于日内突破、海龟交易、ATR通道。最高价序列计算真实波幅:
tr = np.maximum(klines["high"] - klines["low"],
np.abs(klines["high"] - klines["close"].shift(1)))
atr = tr.rolling(14).mean()
print("当前ATR:", atr.iloc[-1])
shift(1)将前一根收盘价对齐到当前行。结合最高价与ATR可设置止损止盈。期货主力合约换月时,代码需对应调整。
天勤量化的K线序列在盘中实时更新,最高价随tick变化,收盘后固定。避免在非交易时段读取无更新数据。若需获取当日最高价,对当日K线取high列最大值:
from datetime import datetime
today = datetime.now().strftime("%Y-%m-%d")
klines["date"] = klines["datetime"].apply(lambda x: datetime.fromtimestamp(x/1e9).strftime("%Y-%m-%d"))
today_high = klines[klines["date"] == today]["high"].max()
print("当日1分钟最高价:", today_high)
时间戳除以1e9转为秒,再转日期。该方式依赖data_length覆盖当日K线,夜盘与日盘日期不同需分别处理。
常见错误与注意事项
get_kline_serial必须在TqApi实例化之后调用。未登录或权限不足会返回空序列。high列为NaN可能是新合约尚无成交。期货主力连续合约代码如KQ.m@SHFE.rb,同样可获取1分钟最高价。data_length超过8964会报错。wait_update需在循环中调用,否则数据不会刷新。
实盘中建议将最高价写入变量而非反复访问DataFrame,减少开销。使用klines.iloc[-1]["high"]时确保至少有一根K线。若需获取分钟最高价对应的时间,读取klines.iloc[-1]["datetime"]转换即可。
股票场景使用天勤量化获取1分钟最高价,合约代码格式如SSE.600000,参数相同。股票无夜盘,K线序列仅日盘生成。期货与股票通用high列,策略逻辑可复用。
掌握get_kline_serial与high列操作,即可在量化系统中灵活使用1分钟最高价。