KB / ARTICLE

历史数据获取

策略文档修订 R1发布于 2026-11-05

本文介绍获取单标的、多标的历史 K 线数据与标的信息的方法。

set_history_depth(depth)

设置策略需要保留的历史 Bar 数量。

参数 类型 说明
depth int 非负整数;0 表示不保留历史 Bar

返回值:None。应不小于策略中最大的历史窗口。推荐在 on_start() 中调用,并保证 depth >= count。如果深度为 0,调用历史查询会抛出 RuntimeError。

from qmfquant import  IntParam, Strategy


class MyStrategy(Strategy):
    window = IntParam(20, ge=2, le=250, title="均线周期", description="计算均线使用的 K 线数量")

    def on_start(self) -> None:
        self.set_history_depth(int(self.params.window))
        self.log(f"参数就绪:window={self.params.window} ")

双流历史:history(symbol, normalized_field, count, history_cutoff, freq)

双流模式(Bar 与 Tick 并存)下,获取历史数据必须显式指定 freq,以区分取的是 K 线序列还是 Tick 序列。

参数 类型 说明
symbol str 标的代码
normalized_field str 标准化字段名。K 线常用 open / high / low / close / volume;Tick 常用 price / volume
count int 需要的历史条数
history_cutoff 时间或 None 历史截止时点;默认截止到当前事件可见时点,避免读到未来数据
freq str 必选。"bar" 取 K 线;"tick" 取 Tick

返回值:按从旧到新排列的序列。values[-1] 是当前可见的最新值。

from qmfquant import  Strategy


class MyStrategy(Strategy):

    def on_bar(self, bar) -> None:
        # 取最近 20 根已完成 K 线的收盘价
        closes = self.history(
            symbol=bar.symbol,
            normalized_field="close",
            count=20,
            history_cutoff=None,
            freq="bar",
        )

    def on_tick(self, tick) -> None:
        # 取最近 100 个 Tick 的最新价
        ticks = self.history(
            symbol=tick.symbol,
            normalized_field="price",
            count=100,
            history_cutoff=None,
            freq="tick",
        )

使用规则:

  • freq 必须与你要计算的对象一致:均线、突破、横截面评分用 "bar";盘口、逐笔监控用 "tick"。
  • 不要在 Tick 回调里用 freq="bar" 却把未收盘的当前秒误当成已完成日线。
  • history_cutoff 用于明确“算到哪一根/哪一笔为止”。盘前、定时器、on_before_trading 中尤其应避免省略截止语义后误读当日未完成数据。
  • 数据不足时不要直接交易,先检查长度或 NaN。

get_history(count, symbol=None, field="close")

取得某个字段最近 count 个 Bar 的数组。这是 Bar 策略最常用的便捷接口。

参数 类型 默认值 说明
count int 无 需要的 Bar 数量
symbol str \ None None 标的代码;省略时使用当前标的
field str "close" open、high、low、close、volume 等字段

返回值:一维 numpy.ndarray,dtype 为 float64。这是数组,不是 list,也不是字典。数据不足时,数组前部会以 NaN 补齐。数组始终按从旧到新排列:values[-1] 是当前可见的最新值。

多周期策略可以多传一个 freq,取已经 subscribe_bars 过的窗口,例如 self.get_history(20, symbol, "close", freq="15min")。省略时取任务基础周期;在 on_window_bar 里省略则自动对到当前窗口。这个 freq 是 "15min" / "1h" / "1d" 这类周期标签。上文 history(..., freq="bar"|"tick") 用来区分 K 线流和 Tick 流,两者不要混用。

from qmfquant import  Strategy


class MyStrategy(Strategy):

    def on_bar(self, bar) -> None:
        closes = self.get_history(20, bar.symbol, "close")
        if np.isnan(closes).any():
            return

常见错误:

  • 没有先调用 set_history_depth():抛出 RuntimeError。
  • 在没有当前 Bar/Tick 的阶段省略 symbol:无法自动确定标的,应明确传入。
  • 请求的 count 大于已积累数据:前部出现 NaN,策略应等待。
  • 把 Tick 序列当成 K 线来算均线:双流场景请改用 history(..., freq="bar") 或 history(..., freq="tick")。

get_history_map(count, symbols, field="close")

批量取得多个标的的历史字段。返回值:字典 dict[str, numpy.ndarray]。键是标的代码,值是一维 float64 数组。不是 list[dict]。

from qmfquant import  Strategy


class MyStrategy(Strategy):

    def on_bar(self, bar) -> None:
        history_map = self.get_history_map(20, ["510300.SH", "510500.SH"], field="close")
        for symbol, closes in history_map.items():
            if np.isnan(closes).any():
                continue

传入单个字符串时也会返回字典,而不是直接返回数组。各标的历史不足时分别补 NaN。

get_history_df(count, symbol=None)

取得最近若干根 K 线表格。返回值:pandas.DataFrame,不是 list[dict]。行顺序从旧到新,第 0 行最旧。用 df["close"] 取列。

参数 参数名称 参数类型 描述
open 开盘价 float64 该根 K 线开盘价
high 最高价 float64 该根 K 线最高价
low 最低价 float64 该根 K 线最低价
close 收盘价 float64 该根 K 线收盘价
volume 成交量 float64 该根 K 线成交量

标的信息查询

方法 参数 返回值 说明
get_instrument(symbol) symbol: str InstrumentSnapshot 查询单个标的静态信息;不存在时抛出 KeyError
get_instruments(symbols=None) 标的列表或 None dict[str, InstrumentSnapshot] 批量查询
get_instrument_field(symbol, field) 标的、字段名 对应字段值 字段不存在时抛出 KeyError
get_instrument_config(symbol, fields=None) 标的、字段 单值、字典或完整快照 fields=None 时返回完整快照
from qmfquant import  Strategy


class MyStrategy(Strategy):

    def on_bar(self, bar) -> None:
        info = self.get_instrument(bar.symbol)
        self.log(f"最小价位={info.tick_size} 每手={info.lot_size}")

这些接口在 on_start 即可使用。查询不存在的标的或字段会抛出 KeyError。

get_instrument() 返回 InstrumentSnapshot 对象,用 info.tick_size 读取。get_instruments() 返回字典,键是标的代码,值是同一个对象类型。get_instrument_field(symbol, "lot_size") 返回该字段本身的值;本次股票样本的每手为 float 100.0。字段表见「外置参数与数据对象」。


相关阅读

已复制到剪贴板
策略文档修订 R1

返回策略文档板块

评论