4. HistoryPanel 类

历史数据类 HistoryPanel 及相关辅助函数。

HistoryPanel 数据结构与切片

HistoryPanel 本质上是一个三维 numpy.ndarray,三个轴分别表示:

  • axis 0 / levels: 标的维度,每一层对应一只股票或一个指数,标签列表为 shares

  • axis 1 / rows: 时间维度,每一行对应一个时间点,标签列表为 hdates

  • axis 2 / columns: 历史数据类型维度,每一列对应一种数据类型,标签列表为 htypes

借助这三个轴标签,可以通过方括号 [] 对 HistoryPanel 进行灵活切片,基本规则为 [htype_slicer, share_slicer, date_slicer];省略维度时与单段写法 (如 hp['close'])仍返回子 HistoryPanel (带轴标签),裸矩阵请用 .values / .to_numpy()

时间轴 (第三段)还支持:单个 pandas.Timestamp、时间标签列表、长度 L = len(hdates) 的一维 bool 列表或 numpy 一维 bool 数组;与只读属性 hp.loc[key] 等价于 hp[:, :, key]。格点级 (M, L, N) 布尔掩码不属于 loc / 第三轴索引语义,请用 where()

典型写法示例:

hp['close']                       # 所有标的的收盘价
hp['close,open,high']            # 所有标的的多种价量数据
hp[:, '000300.SH']               # 单一标的的全部历史数据
hp['close:high', ['000300.SH', '000500.SH'], '20100101:20101231']
                                 # 多标的、数据类型与时间区间联合切片
hp.loc[0:5]                       # 与 hp[:, :, 0:5] 等价,按时间轴截取
class qteasy.HistoryPanel(values: Optional[ndarray] = None, levels=None, rows=None, columns=None)[源代码]

qteasy 中用于统一管理多标的、多时间点、多数据类型历史数据的三维数据容器。

HistoryPanel 本质是一个三维 numpy.ndarray,三条轴分别表示标的 (shares)、时间

(hdates)和历史数据类型 (htypes),支持按任意轴灵活切片、重标记以及与

pandas DataFrame 之间的互相转换,并作为 get_history_data 与可视化栈

(如 HistoryPanel.plot()qt.candle)之间的核心桥梁。

索引与数组出口__getitem__ 始终返回带正确轴标签的子 HistoryPanel;需要 裸 ndarray 时用 .values.to_numpy(copy=...)单列原地赋值 panel['列名'] = value__setitem__ 实现 (仅非空面板、仅 str 键), 值广播为 (标的数, 时间长度) 并以 float64 存储;覆盖已有列或追加新列。 子面板与父对象共享缓冲时的语义见 __getitem__ / subpanel / __setitem__ 各方法说明。

体验向 API:合法 Python 标识符且存在于 htypes 的列名可用属性只读访问 (如 panel.close, 等价 panel['close']);比较运算 (如 panel.close > panel.open)返回 numpy 布尔数组; panel.loc[key] 等价 panel[:, :, key],仅沿时间轴筛选 (不接 where 的三维掩码)。 用户文档见 Sphinx HistoryPanel 页与教程「使用 HistoryPanel 操作和分析历史数据」 (§6 及 §6.1)。

更详细的结构说明 (轴标签、切片示例、标签管理等)见文档「HistoryPanel 类」相关章节。

__eq__(other: Any) Any[源代码]

逐元素 self == other;不支持的类型返回 NotImplemented

参数:

other (Any) – 右操作数。

返回:

可比较时为 bool 数组;否则 NotImplemented

返回类型:

numpy.ndarray or NotImplemented

__ge__(other: Any) ndarray[源代码]

等价于以 operator 模块的 ge 逐元素比较 selfother;返回 dtype 为 boolnumpy.ndarray (非子面板)。

参数:

other (Any) – 右操作数;语义同 __lt__()

返回:

布尔结果数组。

返回类型:

numpy.ndarray

__getattr__(name: str) Any[源代码]

将合法标识符列名解析为 self[name] (只读);非标识符或未知列名请用方括号索引。

列赋值仍请使用 hp['col'] = ...;不与 pandas 的属性写路径对齐。

参数:

name (str) – 属性名;须为合法 Python 标识符才可能对应到 htypes 列 (非空面板)。

返回:

self[name] 相同的子面板;空面板上委托 __getitem__,返回空子面板。

返回类型:

HistoryPanel

抛出:

AttributeError – 非法标识符、或当前面板中不存在的列名 (英文,提示使用 bracket indexing)。

备注

已有方法名 / 描述符 (如 wherevalues)优先于列名:同名列仍须用 hp['where'] 等形式访问。非标识符列名 (如 close|b)不可用点号。

示例

>>> import pandas as pd
>>> import numpy as np
>>> hp = HistoryPanel(
...     np.arange(24, dtype=float).reshape(2, 3, 4),
...     levels=['A', 'B'],
...     rows=pd.date_range('2020-01-01', periods=3),
...     columns=['a', 'b', 'c', 'd'],
... )
>>> np.allclose(hp.a.values, hp['a'].values)
True
__getitem__(keys=None) HistoryPanel[源代码]

按 htypes / shares / hdates 三轴切片,返回带正确轴标签的子 HistoryPanel

第一个切片为数据类型 (htypes),第二个为标的 (shares),第三个为时间 (hdates);省略时该轴为全选。 需要裸 ndarray 时请使用 sub.valuessub.to_numpy()。子面板 values 可能与父面板 共享内存 (numpy 视图规则);需要独立副本请用 subpanel(..., copy=True)sub.copy()

父对象 上使用 __setitem__ 追加新列时,会替换父面板整块 values:默认 copy=False 的子面板 不会 出现新列名,且其 values 可能仍指向扩列前的旧数组; subpanel(copy=True) 得到的子对象不受影响。在父面板上 覆盖 已有列时,与子视图共享的 切片数据会随父缓冲一并更新 (仍为同一底层块上的视图时)。

空面板 (is_empty)上任意索引均返回空的 HistoryPanel

备注

时间轴 (第三段 ``hdates``)slice / 整数 / 区间字符串外,还支持:在 rows 字典中可查的 单个时间标签 (如 pandas.Timestamp)、时间标签列表,以及 长度等于 row_count 的一维 bool 列表或一维 numpy.ndarray (布尔 dtype);与 loc 所接受的 key 一致。格点级 (M, L, N) 布尔数组 用作第三轴索引, 请使用 where()

参数:

keys (list, tuple, slice, str, int or None) – 切片键;三元组 (htypes, shares, hdates) 与历史行为一致。

返回:

子面板;取矩阵请用其 .values / .to_numpy()

返回类型:

HistoryPanel

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                   levels=['000001', '000002', '000003'],
...                   rows=pd.date_range('2015-01-05', periods=10),
...                   columns=['open', 'high', 'low', 'close', 'volume'])
>>> sub = hp['close']
>>> isinstance(sub, HistoryPanel)
True
>>> sub.shape
(3, 10, 1)
>>> sub.htypes
['close']
>>> np.all(sub.values == 40)
True
__gt__(other: Any) ndarray[源代码]

等价于以 operator 模块的 gt 逐元素比较 selfother;返回 dtype 为 boolnumpy.ndarray (非子面板)。

参数:

other (Any) – 右操作数;语义同 __lt__()

返回:

布尔结果数组。

返回类型:

numpy.ndarray

__le__(other: Any) ndarray[源代码]

等价于以 operator 模块的 le 逐元素比较 selfother;返回 dtype 为 boolnumpy.ndarray (非子面板)。

参数:

other (Any) – 右操作数;语义同 __lt__()

返回:

布尔结果数组。

返回类型:

numpy.ndarray

__lt__(other: Any) ndarray[源代码]

等价于以 operator 模块的 lt 逐元素比较 selfother;返回 dtype 为 boolnumpy.ndarray (非子面板)。

参数:

other (Any) – 标量、可广播 ndarray 或另一 HistoryPanel (须满足对齐规则)。

返回:

布尔结果数组。

返回类型:

numpy.ndarray

抛出:
  • TypeError – 不支持的操作数类型 (英文)。

  • ValueError – 两面板无法按规则对齐或广播时抛出 (英文)。

__ne__(other: Any) Any[源代码]

逐元素 self != other;不支持的类型返回 NotImplemented

参数:

other (Any) – 右操作数。

返回:

可比较时为 bool 数组;否则 NotImplemented

返回类型:

numpy.ndarray or NotImplemented

__setitem__(key: Any, value: Any) None[源代码]

按列名原地追加一列或覆盖已有列 (htypes 第三轴)。

仅接受运行期为 非空 字符串的 key;多列批量赋值由后续 assign 等 API 提供。 value 将广播到 (share 数, 时间长度) 并以 float64 落盘;已存在列名 静默覆盖, 语义对齐 pandas 单列赋值。父面板上 追加 新列会替换整块 valuessubpanel(copy=False) / __getitem__ 子视图通常 看不到 新列且可能仍指向旧缓冲;subpanel(..., copy=True)to_numpy(copy=True) 不受影响。父 覆盖 已有列时,与父共享底层块的子视图会随父更新。

参数:
  • key (Any) – 列名 (htype)。须为 str;非 strTypeError,空字符串抛 ValueError (英文信息)。

  • value (Any) – 可 np.asarray 且可广播到 (M, L) 的数值 (标量、(M, L)(M, L, 1) 等)。

返回:

原地修改本对象,无返回值。

返回类型:

None

抛出:
  • TypeErrorkey 不是 str 时抛出 (英文信息)。

  • ValueError – 面板为空、key 为空字符串、或 value 无法广播到 (M, L) 时抛出 (英文信息)。

示例

>>> hp = HistoryPanel(np.ones((2, 5, 2)), levels=['A', 'B'],
...                   rows=pd.date_range('2020-01-01', periods=5),
...                   columns=['open', 'close'])
>>> hp['twice_close'] = hp['close'].values * 2
>>> 'twice_close' in hp.htypes
True
>>> hp['const'] = 0.5
>>> np.all(hp.values[:, :, hp.htypes.index('const')] == 0.5)
True
as_type(dtype)[源代码]

将HistoryPanel的数据类型转换为dtype类型,dtype只能为’float’或’int’

参数:

dtype (str, {'float', 'int'}) – 需要转换的目标数据类型

返回类型:

self

抛出:

AssertionError – 当输入的数据类型不正确或输入除float/int外的其他数据类型时

candle(*args, **kwargs)[源代码]

基于当前 HistoryPanel 数据绘制蜡烛图 (已由 plot() 统一处理)

备注

  • 新版可视化推荐直接调用 HistoryPanel.plot(),并通过 htypes / layout 控制是否输出 K 线、成交量等图表类型。

  • 本方法在内部会委托给可视化子模块的统一入口实现,行为与 plot() 保持 一致,仅作为语义化别名存在。

property column_count

获取HistoryPanel的列数量或历史数据数量

property columns

返回一个字典,代表HistoryPanel的历史数据,将历史数据与列号进行对应 这样便于内部根据股票代码对数据进行切片

copy(deep: bool = True) HistoryPanel[源代码]

复制一个新的 HistoryPanel 对象。

默认返回 深拷贝,即新对象与原对象的 values 底层数组互不影响;当需要与 NumPy 视图语义保持一致、在性能敏感场景中共享底层数据时,可设置 deep=False

参数:

deep (bool, default True) –

是否深拷贝底层数值数组 values

  • True:深拷贝,修改副本不影响原对象;

  • False:浅拷贝 (共享底层数组),修改副本会同步影响原对象。

返回:

复制后的新对象,轴标签 (shares/hdates/htypes)与原对象一致。

返回类型:

HistoryPanel

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy import HistoryPanel
>>> hp = HistoryPanel(
...     np.arange(12, dtype=float).reshape(2, 3, 2),
...     levels=['A', 'B'],
...     rows=pd.date_range('2020-01-01', periods=3),
...     columns=['close', 'open'],
... )
>>> hp
share 0, label: A
            close  open
2020-01-01    0.0   1.0
2020-01-02    2.0   3.0
2020-01-03    4.0   5.0
share 1, label: B
            close  open
2020-01-01    6.0   7.0
2020-01-02    8.0   9.0
2020-01-03   10.0  11.0
>>> hp2 = hp.copy()  # deep=True
>>> hp2.values[0, 0, 0] = -1.0
>>> hp2
share 0, label: A
            close  open
2020-01-01   -1.0   1.0
2020-01-02    2.0   3.0
2020-01-03    4.0   5.0
share 1, label: B
            close  open
2020-01-01    6.0   7.0
2020-01-02    8.0   9.0
2020-01-03   10.0  11.0
>>> hp
share 0, label: A
            close  open
2020-01-01    0.0   1.0
2020-01-02    2.0   3.0
2020-01-03    4.0   5.0
share 1, label: B
            close  open
2020-01-01    6.0   7.0
2020-01-02    8.0   9.0
2020-01-03   10.0  11.0
>>> hp3 = hp.copy(deep=False)
>>> hp3.values[0, 0, 0] = -2.0
>>> hp3
share 0, label: A
            close  open
2020-01-01   -2.0   1.0
2020-01-02    2.0   3.0
2020-01-03    4.0   5.0
share 1, label: B
            close  open
2020-01-01    6.0   7.0
2020-01-02    8.0   9.0
2020-01-03   10.0  11.0
>>> hp
share 0, label: A
            close  open
2020-01-01   -2.0   1.0
2020-01-02    2.0   3.0
2020-01-03    4.0   5.0
share 1, label: B
            close  open
2020-01-01    6.0   7.0
2020-01-02    8.0   9.0
2020-01-03   10.0  11.0
ffill(init_val=nan)[源代码]

前向填充缺失值,当历史数据中存在缺失值时,使用缺失值以前 的最近有效数据填充缺失值

参数:

init_val (float, 如果Nan值出现在第一行时,没有前序有效数据,则使用这个值来填充,默认为np.nan) –

返回:

out

返回类型:

HistoryPanel, 填充后的HistoryPanel对象

示例

>>> hp = HistoryPanel(np.array([[[1, 2, 3], [4, np.nan, 6]], [[np.nan, 8, 9], [np.nan, np.nan, 12]]]),
...                   levels=['000001', '000002'], rows=['2015-01-01', '2015-01-02'],
...                   columns=['open', 'high', 'low'])
>>> hp
share 0, label: 000001
            open  high  low
2015-01-01   1.0   2.0  3.0
2015-01-02   4.0   NaN  6.0
share 1, label: 000002
            open  high   low
2015-01-01   NaN   8.0   9.0
2015-01-02   NaN   NaN  12.0
>>> hp.ffill()
share 0, label: 000001
            open  high  low
2015-01-01   1.0   2.0  3.0
2015-01-02   4.0   2.0  6.0
share 1, label: 000002
            open  high   low
2015-01-01   NaN   8.0   9.0
2015-01-02   NaN   8.0  12.0
>>> hp.ffill(init_val=3)
share 0, label: 000001
            open  high  low
2015-01-01   1.0   2.0  3.0
2015-01-02   4.0   2.0  6.0
share 1, label: 000002
            open  high   low
2015-01-01   3.0   8.0   9.0
2015-01-02   3.0   8.0  12.0
fillinf(with_val: Union[int, float])[源代码]

使用with_value来填充HistoryPanel中的所有inf值

参数:

with_val (float or int) – 填充的值

返回:

out

返回类型:

HistoryPanel, 填充后的HistoryPanel对象

fillna(with_val: Union[int, float])[源代码]

使用with_value来填充HistoryPanel中的所有nan值

参数:

with_val (float or int) – 填充的值

返回:

out

返回类型:

HistoryPanel, 填充后的HistoryPanel对象

flatten(along=None)[源代码]

等同于HistoryPanel.flatten_to_dataframe()

参数:

along (str, {'col', 'row', 'column'} Default: 'row') – 平铺HistoryPanel的每一层时,沿行方向还是列方向平铺, ‘col’或’column’表示沿列方向平铺,’row’表示沿行方向平铺

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020]],
...                                    [[2.3, 2.5, 20010], [2.6, 3.2, 20020]]]),
...                          levels=['000300', '000001'],
...                          rows=['2020-01-01', '2020-01-02'],
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close  open        vol
2020-01-01   12.3  12.5  1020010.0
2020-01-02   12.6  13.2  1020020.0
share 1, label: 000001
            close  open      vol
2020-01-01    2.3   2.5  20010.0
2020-01-02    2.6   3.2  20020.0
>>> hp.flatten(along='col')
           000300                  000001
            close  open        vol  close open      vol
2020-01-01   12.3  12.5  1020010.0    2.3  2.5  20010.0
2020-01-02   12.6  13.2  1020020.0    2.6  3.2  20020.0
>>> hp.flatten(along='row')
                   close  open        vol
000300 2020-01-01   12.3  12.5  1020010.0
       2020-01-02   12.6  13.2  1020020.0
000001 2020-01-01    2.3   2.5    20010.0
       2020-01-02    2.6   3.2    20020.0
flatten_to_dataframe(along='row')[源代码]

将一个HistoryPanel”展平”成为一个DataFrame

HistoryPanel的多层数据会被”平铺”到DataFrame的列,变成一个MultiIndex,或者多层数据 会被平铺到DataFrame的行,同样变成一个MultiIndex,平铺到行还是列取决于along参数

参数:

along (str, {'col', 'row', 'column'} Default: 'row') – 平铺HistoryPanel的每一层时,沿行方向还是列方向平铺, ‘col’或’column’表示沿列方向平铺,’row’表示沿行方向平铺

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020]],
...                                    [[2.3, 2.5, 20010], [2.6, 3.2, 20020]]]),
...                          levels=['000300', '000001'],
...                          rows=['2020-01-01', '2020-01-02'],
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close  open        vol
2020-01-01   12.3  12.5  1020010.0
2020-01-02   12.6  13.2  1020020.0
share 1, label: 000001
            close  open      vol
2020-01-01    2.3   2.5  20010.0
2020-01-02    2.6   3.2  20020.0
>>> hp.flatten_to_dataframe(along='col')
           000300                  000001
            close  open        vol  close open      vol
2020-01-01   12.3  12.5  1020010.0    2.3  2.5  20010.0
2020-01-02   12.6  13.2  1020020.0    2.6  3.2  20020.0
>>> hp.flatten_to_dataframe(along='row')
                   close  open        vol
000300 2020-01-01   12.3  12.5  1020010.0
       2020-01-02   12.6  13.2  1020020.0
000001 2020-01-01    2.3   2.5    20010.0
       2020-01-02    2.6   3.2    20020.0
flattened_head(row_count=5)[源代码]

以multi-index DataFrame的形式返回HistoryPanel的最初几行,默认五行

参数:

row_count (int, default 5) – 打印的行数

返回:

  • dataframe, multi-indexed by share and htype as columns, with only first row_count rows

  • 一个dataframe,以share和htype为列的多重索引,只包含前row_count行

示例

>>> data = np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020], [12.9, 13.0, 1020030],
...                   [12.3, 12.5, 1020040], [12.6, 13.2, 1020050], [12.9, 13.0, 1020060]],
...                  [[2.3, 2.5, 20010], [2.6, 2.8, 20020], [2.9, 3.0, 20030],
...                   [2.3, 2.5, 20040], [2.6, 2.8, 20050], [2.9, 3.0, 20060]]])
>>> hp = HistoryPanel(values=data,
...                          levels=['000300', '000001'],
...                          rows=pd.date_range('2020-01-01', periods=6),
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close,  open,   vol
2020-01-01  12.3,   12.5,   1020010
2020-01-02  12.6,   13.2,   1020020
2020-01-03  12.9,   13.0,   1020030
2020-01-04  12.3,   12.5,   1020040
2020-01-05  12.6,   13.2,   1020050
2020-01-06  12.9,   13.0,   1020060
share 1, label: 000001:
            close,  open,   vol
2020-01-01  2.3,    2.5,    20010
2020-01-02  2.6,    3.2,    20020
2020-01-03  2.9,    3.0,    20030
2020-01-04  2.3,    2.5,    20040
2020-01-05  2.6,    3.2,    20050
2020-01-06  2.9,    3.0,    20060
>>> hp.flattened_head(3)
            000300                  000001
            close,  open,   vol,    close,  open,   vol
2020-01-01  12.3,   12.5,   1020010 2.3,    2.5,    20010
2020-01-02  12.6,   13.2,   1020020 2.6,    3.2,    20020
2020-01-03  12.9,   13.0,   1020030 2.9,    3.0,    20030
flattened_tail(row_count=5)[源代码]

以multi-index DataFrame的形式返回HistoryPanel的最后几行,默认五行

参数:

row_count (int, default 5) – 打印的行数

返回:

  • dataframe, multi-indexed by share and htype as columns, with only last row_count rows

  • 一个dataframe,以share和htype为列的多重索引,只包含后row_count行

示例

>>> data = np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020], [12.9, 13.0, 1020030],
...                   [12.3, 12.5, 1020040], [12.6, 13.2, 1020050], [12.9, 13.0, 1020060]],
...                  [[2.3, 2.5, 20010], [2.6, 2.8, 20020], [2.9, 3.0, 20030],
...                   [2.3, 2.5, 20040], [2.6, 2.8, 20050], [2.9, 3.0, 20060]]])
>>> hp = HistoryPanel(values=data,
...                          levels=['000300', '000001'],
...                          rows=pd.date_range('2020-01-01', periods=6),
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close,  open,   vol
2020-01-01  12.3,   12.5,   1020010
2020-01-02  12.6,   13.2,   1020020
2020-01-03  12.9,   13.0,   1020030
2020-01-04  12.3,   12.5,   1020040
2020-01-05  12.6,   13.2,   1020050
2020-01-06  12.9,   13.0,   1020060
share 1, label: 000001:
            close,  open,   vol
2020-01-01  2.3,    2.5,    20010
2020-01-02  2.6,    3.2,    20020
2020-01-03  2.9,    3.0,    20030
2020-01-04  2.3,    2.5,    20040
2020-01-05  2.6,    3.2,    20050
2020-01-06  2.9,    3.0,    20060
>>> hp.flattened_tail(3)
            000300                  000001
            close,  open,   vol,    close,  open,   vol
2020-01-04  12.3,   12.5,   1020040 2.3,    2.5,    20040
2020-01-05  12.6,   13.2,   1020050 2.6,    3.2,    20050
2020-01-06  12.9,   13.0,   1020060 2.9,    3.0,    20060
property hdate_count

获取HistoryPanel的历史数据类型数量

property hdates

获取HistoryPanel的历史日期时间戳list

head(row_count=5)[源代码]

返回HistoryPanel的最初几行,默认五行

参数:

row_count (int, default 5) – 打印的行数

返回:

  • dataframe, multi-indexed by share and htype as columns, with only first row_count rows

  • 一个dataframe,以share和htype为列的多重索引,只包含前row_count行

示例

>>> data = np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020], [12.9, 13.0, 1020030],
...                   [12.3, 12.5, 1020040], [12.6, 13.2, 1020050], [12.9, 13.0, 1020060]],
...                  [[2.3, 2.5, 20010], [2.6, 2.8, 20020], [2.9, 3.0, 20030],
...                   [2.3, 2.5, 20040], [2.6, 2.8, 20050], [2.9, 3.0, 20060]]])
>>> hp = HistoryPanel(values=data,
...                          levels=['000300', '000001'],
...                          rows=pd.date_range('2020-01-01', periods=6),
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close,  open,   vol
2020-01-01  12.3,   12.5,   1020010
2020-01-02  12.6,   13.2,   1020020
2020-01-03  12.9,   13.0,   1020030
2020-01-04  12.3,   12.5,   1020040
2020-01-05  12.6,   13.2,   1020050
2020-01-06  12.9,   13.0,   1020060
share 1, label: 000001:
            close,  open,   vol
2020-01-01  2.3,    2.5,    20010
2020-01-02  2.6,    3.2,    20020
2020-01-03  2.9,    3.0,    20030
2020-01-04  2.3,    2.5,    20040
2020-01-05  2.6,    3.2,    20050
2020-01-06  2.9,    3.0,    20060
>>> hp.head(3)
share 0, label: 000300
            close,  open,   vol,
2020-01-01  12.3,   12.5,   1020010
2020-01-02  12.6,   13.2,   1020020
2020-01-03  12.9,   13.0,   1020030
share 1, label: 000001
            close,  open,   vol
2020-01-01  2.3,    2.5,    20010
2020-01-02  2.6,    3.2,    20020
2020-01-03  2.9,    3.0,    20030
property htype_count

获取HistoryPanel的历史数据类型数量

property htypes

获取HistoryPanel的历史数据类型列表

info()[源代码]

打印本HistoryPanel对象的信息

返回类型:

None

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                          levels=['000001', '000002', '000003'],
...                          rows=pd.date_range('2015-01-05', periods=10),
...                          columns=['open', 'high', 'low', 'close', 'volume'])
>>> hp.info()
<class 'qteasy.history.HistoryPanel'>
History Panel at 0x12215a850
Datetime Range: 10 entries, 2015-01-05 00:00:00 to 2015-01-14 00:00:00
Historical Data Types (total 5 data types):
['open', 'high', 'low', 'close', 'volume']
Shares (total 3 shares):
['000001', '000002', '000003']
non-null values for each share and data type:
        open  high  low  close  volume
000001    10    10   10     10      10
000002    10    10   10     10      10
000003    10    10   10     10      10
memory usage: 1344 bytes
property is_empty

判断HistoryPanel是否为空

isegment(start_index=None, end_index=None)[源代码]
获取HistoryPanel的一个片段,start_index和end_index都是int数,表示日期序号,返回

这两个序号代表的日期之间的所有数据,返回的类型为一个HistoryPanel,包含所有share和 htypes的数据

参数:
  • start_index (pd.TimeStamp) – 开始日期序号

  • end_index (pd.TimeStamp) – 结束日期序号

返回:

out – 一个HistoryPanel,包含start_date到end_date之间所有share和htypes的数据

返回类型:

HistoryPanel

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                          levels=['000001', '000002', '000003'],
...                          rows=pd.date_range('2015-01-05', periods=10),
...                          columns=['open', 'high', 'low', 'close', 'volume'])
>>> hp.isegment(2, 5)
share 0, label: 000100
            open  high  low  close  volume
2015-01-07    10    20   30     40      50
2015-01-08    10    20   30     40      50
2015-01-09    10    20   30     40      50
share 1, label: 000200
            open  high  low  close  volume
2015-01-07    10    20   30     40      50
2015-01-08    10    20   30     40      50
2015-01-09    10    20   30     40      50
share 2, label: 000300
            open  high  low  close  volume
2015-01-07    10    20   30     40      50
2015-01-08    10    20   30     40      50
2015-01-09    10    20   30     40      50
join(other, same_shares: bool = False, same_htypes: bool = False, same_hdates: bool = False, fill_value: float = nan)[源代码]

将一个HistoryPanel对象与另一个HistoryPanel对象连接起来,生成一个新的HistoryPanel:

新HistoryPanel的行、列、层标签分别是两个原始HistoryPanel的行、列、层标签的并集,也就是说,新的HistoryPanel的行、列 层标签完全包含两个HistoryPanel对象的对应标签。

参数:
  • other (HistoryPanel) – 需要合并的另一个HistoryPanel

  • same_shares (bool, Default False) – 两个HP的shares是否相同,如果相同,可以省去shares维度的标签合并,以节省时间。默认False,

  • same_htypes (bool, Default False) – 两个HP的htypes是否相同,如果相同,可以省去htypes维度的标签合并,以节省时间。默认False,

  • same_hdates (bool, Default False) – 两个HP的hdates是否相同,如果相同,可以省去hdates维度的标签合并,以节省时间。默认False,

  • fill_value (float, Default np.nan) – 空数据填充值,当组合后的HP存在空数据时,应该以什么值填充,默认为np.nan

返回类型:

HistoryPanel, 一个新的History Panel对象

示例

>>> # 如果两个HistoryPanel中包含标签相同的数据,那么新的HistoryPanel中将包含调用join方法的HistoryPanel对象的相应数据。例如:
>>> hp1 = HistoryPanel(np.array([[[8, 9, 9], [7, 5, 5], [4, 8, 4], [1, 0, 7], [8, 7, 9]],
...                                     [[2, 3, 3], [5, 4, 6], [2, 8, 7], [3, 3, 4], [8, 8, 7]]]),
...                           levels=['000200', '000300'],
...                           rows=pd.date_range('2020-01-01', periods=5),
...                           columns=['close', 'open', 'high'])
>>> hp2 = HistoryPanel(np.array([[[8, 9, 9], [7, 5, 5], [4, 8, 4], [1, 0, 7], [8, 7, 9]],
...                                     [[2, 3, 3], [5, 4, 6], [2, 8, 7], [3, 3, 4], [8, 8, 7]]]),
...                           levels=['000400', '000500'],
...                           rows=pd.date_range('2020-01-01', periods=5),
...                           columns=['close', 'open', 'high'])
>>> hp1
share 0, label: 000200
            close  open  high
2020-01-01      8     9     9
2020-01-02      7     5     5
2020-01-03      4     8     4
2020-01-04      1     0     7
2020-01-05      8     7     9
share 1, label: 000300
            close  open  high
2020-01-01      2     3     3
2020-01-02      5     4     6
2020-01-03      2     8     7
2020-01-04      3     3     4
2020-01-05      8     8     7
>>> hp2
share 0, label: 000400
            close  open  high
2020-01-01      8     9     9
2020-01-02      7     5     5
2020-01-03      4     8     4
2020-01-04      1     0     7
2020-01-05      8     7     9
share 1, label: 000500
            close  open  high
2020-01-01      2     3     3
2020-01-02      5     4     6
2020-01-03      2     8     7
2020-01-04      3     3     4
2020-01-05      8     8     7
>>> hp1.join(hp2)
share 0, label: 000200
len()[源代码]

返回HistoryPanel对象的长度,即日期个数

返回:

日期个数

返回类型:

int

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                          levels=['000001', '000002', '000003'],
...                          rows=pd.date_range('2015-01-05', periods=10),
...                          columns=['open', 'high', 'low', 'close', 'volume'])
>>> hp.len()
10
property level_count

返回HistoryPanel中股票或资产品种的数量

property levels

返回 HistoryPanel 的层标签字典(股票代码到层下标的映射)。

在库内部可与 values 组合做按层索引;外部请优先使用方括号切片访问各层数据。

plot(shares: Optional[Union[str, Iterable[str]]] = None, layout: str = 'auto', interactive: bool = False, highlight: Optional[Any] = None, plotly_backend_app: str = 'auto', group_titles: Optional[Sequence[str]] = None, max_shares_per_figure: int = 5, page: int = 1, **kwargs)[源代码]

根据 HistoryPanel 中已有的 htypes 与 shares 自动选择图表类型并绘制图表。

本方法只消费已有数据不做新增计算,图表类型由内部注册表基于 htypes 决定 (如 OHLC→K 线,vol→成交量,MACD 三列→MACD 图,其余→折线),支持单标的与多标 的 overlay/stack 布局,以及基于 matplotlib 的静态图和基于 Plotly 的交互式图表。

参数:
  • shares (str or sequence of str, optional) – 要参与绘图的标的子集;默认使用 HistoryPanel 的全部 shares。

  • layout ({'overlay', 'stack', 'auto'}, default 'auto') – 多标的布局方式;’overlay’ 为同组叠加,’stack’ 为多组分行展示,’auto’ 时 HP_OVERLAY_GROUP_SHARE_COUNT 只标的用 overlay,其余用 stack。

  • interactive (bool, default False) – 为 True 时使用 Plotly 交互后端 (需安装 plotly 及 anywidget/ipywidgets); 为 False 时使用 matplotlib 静态后端。

  • highlight (dict or str, optional) – 高亮配置,可为 {'condition': 'max'|'min' 或布尔数组, 'style': {...}}, 或简写为 ‘max’ / ‘min’。

  • plotly_backend_app ({'auto', 'FigureWidget', 'html'}, default 'auto') – 仅当 interactive=True 时有效。在 Notebook 中选择 Plotly 呈现方式: 'auto' 优先 FigureWidget,失败则回退 HTML 包装;'FigureWidget' 强制 Widget,失败抛错;'html' 强制 HTML 包装,失败抛错。非 Notebook 脚本环境下 'auto' 仍可能返回原始 Figure

  • max_shares_per_figure (int, default 5) – 单张图中最多展示的 share 数量。当请求 shares 数量超过该值时,会按页分割; 可通过 page 参数选择要展示的页码。

  • page (int, default 1) – 要展示的页码 (1-based)。当 shares 数量超过 max_shares_per_figure 时, page=1 为第 1 页,page=2 为第 2 页,以此类推。

  • **kwargs – 预留的扩展参数,当前版本中不使用。

返回:

interactive=False 时返回 matplotlib Figure; interactive=True 时依 plotly_backend_app 返回 FigureWidget、HTML 包装器或原始 Figure。

返回类型:

matplotlib.figure.Figure or plotly.graph_objs.FigureWidget or _PlotlyFigureWrapper

备注

当注册表产出 完整 OHLC K 线 主图时,会显示顶部 OHLC 摘要区:静态图固定为时间轴上 最后一根 bar 的摘要;交互图初始与之一致,点击某 bar 后更新为该 bar (面向用户的 摘要文案为英文)。无 K 线主图 (例如仅 close 折线)时不显示该摘要区。

示例

>>> import qteasy as qt
>>> hp = qt.get_history_data(htype_names='open, high, low, close, vol',
...                          shares='000300.SH', rows=200)
>>> fig = hp.plot()
>>> fig_interactive = hp.plot(interactive=True, highlight='max')

参见

qt.get_kline

获取 K 线数据并可选 as_panel=True 得到 HistoryPanel。

re_label(shares: Optional[Union[str, list]] = None, htypes: Optional[Union[str, list]] = None, hdates: Optional[Union[str, list]] = None) None[源代码]

给HistoryPanel对象的层、行、列标签重新赋值

参数:
  • shares (str or list of str) – 股票列表

  • htypes (str or list of str) – 数据类型列表

  • hdates (str or list of str) – 日期列表

返回类型:

None

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                          levels=['000001', '000002', '000003'],
...                          rows=pd.date_range('2015-01-05', periods=10),
...                          columns=['open', 'high', 'low', 'close', 'volume'])
>>> hp.re_label(shares=['000100', '000200', '000300'], htypes=['typeA', 'typeB', 'typeC', 'typeD', 'typeE'])
>>> hp
share 0, label: 000100
            typeA  typeB  typeC  typeD  typeE
2015-01-05     10     20     30     40     50
2015-01-06     10     20     30     40     50
2015-01-07     10     20     30     40     50
2015-01-08     10     20     30     40     50
2015-01-09     10     20     30     40     50
2015-01-10     10     20     30     40     50
2015-01-11     10     20     30     40     50
2015-01-12     10     20     30     40     50
2015-01-13     10     20     30     40     50
2015-01-14     10     20     30     40     50
share 1, label: 000200
            typeA  typeB  typeC  typeD  typeE
2015-01-05     10     20     30     40     50
2015-01-06     10     20     30     40     50
2015-01-07     10     20     30     40     50
2015-01-08     10     20     30     40     50
2015-01-09     10     20     30     40     50
2015-01-10     10     20     30     40     50
2015-01-11     10     20     30     40     50
2015-01-12     10     20     30     40     50
2015-01-13     10     20     30     40     50
2015-01-14     10     20     30     40     50
share 2, label: 000300
            typeA  typeB  typeC  typeD  typeE
2015-01-05     10     20     30     40     50
2015-01-06     10     20     30     40     50
2015-01-07     10     20     30     40     50
2015-01-08     10     20     30     40     50
2015-01-09     10     20     30     40     50
2015-01-10     10     20     30     40     50
2015-01-11     10     20     30     40     50
2015-01-12     10     20     30     40     50
2015-01-13     10     20     30     40     50
2015-01-14     10     20     30     40     50
property row_count

获取HistoryPanel的行数量

property rows

返回Hi storyPanel的日期字典,通过这个字典建立日期与行号的联系: 因此内部可以较快地进行数据切片或数据访问

返回:

日期字典

返回类型:

dict

segment(start_date=None, end_date=None)[源代码]
获取HistoryPanel的一个日期片段,start_date和end_date都是日期型数据,返回

这两个日期之间的所有数据,返回的类型为一个HistoryPanel,包含所有share和 htypes的数据

参数:
  • start_date (开始日期) –

  • end_date (结束日期) –

返回:

out – 一个HistoryPanel,包含start_date到end_date之间所有share和htypes的数据

返回类型:

HistoryPanel

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                          levels=['000001', '000002', '000003'],
...                          rows=pd.date_range('2015-01-05', periods=10),
...                          columns=['open', 'high', 'low', 'close', 'volume'])
>>> hp.segment('2015-01-07', '2015-01-10')
share 0, label: 000100
            open  high  low  close  volume
2015-01-07    10    20   30     40      50
2015-01-08    10    20   30     40      50
2015-01-09    10    20   30     40      50
2015-01-10    10    20   30     40      50
share 1, label: 000200
            open  high  low  close  volume
2015-01-07    10    20   30     40      50
2015-01-08    10    20   30     40      50
2015-01-09    10    20   30     40      50
2015-01-10    10    20   30     40      50
share 2, label: 000300
            open  high  low  close  volume
2015-01-07    10    20   30     40      50
2015-01-08    10    20   30     40      50
2015-01-09    10    20   30     40      50
2015-01-10    10    20   30     40      50
property shape

获取HistoryPanel的各个维度的尺寸

property share_count

获取HistoryPanel中股票或资产品种的数量

property shares

返回HistoryPanel的层标签——股票列表

slice(shares=None, htypes=None)[源代码]
获取HistoryPanel的一个股票或数据种类片段,shares和htypes可以为列表或逗号分隔字符

串,表示需要获取的股票或数据的种类。

参数:
  • shares (str or list of str) – 需要的股票列表

  • htypes (str or list of str) – 需要的数据类型列表

返回:

out – 一个HistoryPanel,包含shares和htypes中指定的股票和数据类型的数据

返回类型:

HistoryPanel

示例

>>> hp = HistoryPanel(np.array([[[10, 20, 30, 40, 50]]*10]*3),
...                   levels=['000001', '000002', '000003'],
...                   rows=pd.date_range('2015-01-05', periods=10),
...                   columns=['open', 'high', 'low', 'close', 'volume'])
>>> hp.slice(shares='000001,000003', htypes='close, open')
share 0, label: 000001
            close  open
2015-01-05     40    10
2015-01-06     40    10
2015-01-07     40    10
2015-01-08     40    10
2015-01-09     40    10
2015-01-10     40    10
2015-01-11     40    10
2015-01-12     40    10
2015-01-13     40    10
2015-01-14     40    10
share 2, label: 000003
            close  open
2015-01-05     40    10
2015-01-06     40    10
2015-01-07     40    10
2015-01-08     40    10
2015-01-09     40    10
2015-01-10     40    10
2015-01-11     40    10
2015-01-12     40    10
2015-01-13     40    10
2015-01-14     40    10
slice_to_dataframe(htype: Optional[Union[str, int]] = None, share: Optional[Union[str, int]] = None, dropna: bool = False, inf_as_na: bool = False) DataFrame[源代码]

将HistoryPanel对象中的指定片段转化为DataFrame

指定htype或者share,将这个htype或share对应的数据切片转化为一个DataFrame。 由于HistoryPanel对象包含三维数据,因此在转化时必须指定htype或者share参数中的一个

参数:
  • htype (str or int,) – 表示需要生成DataFrame的数据类型切片 如果给出此参数,定位该htype对应的切片后,将该htype对应的所有股票所有日期的数据转化为一个DataFrame 如果类型为str,表示htype的名称,如果类型为int,代表该htype所在的列序号

  • share (str or int,) – 表示需要生成DataFrame的股票代码切片 如果给出此参数,定位该share对应的切片后,将该share对应的所有数据类型所有日期的数据转化为一个DataFrame 如果类型为str,表示股票代码,如果类型为int,代表该share所在的层序号

  • dropna (bool, Default False) – 是否去除NaN值

  • inf_as_na (bool, Default False) – 是否将inf值当成NaN值一同去掉,当dropna为False时无效

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(values=np.array([[[1, 2, np.nan], [4, 5, 6]],
...                                    [[7, 8, np.nan], [np.inf, 11, 12]]]),
...                   levels=['000001', '000002'],
...                   rows=['2019-01-01', '2019-01-02'],
...                   columns=['open', 'high', 'low']))
>>> hp
share 0, label: 000001
            open  high  low
2019-01-01   1.0   2.0  NaN
2019-01-02   4.0   5.0  NaN
share 1, label: 000002
            open  high   low
2019-01-01   7.0   8.0   9.0
2019-01-02   inf  11.0  12.0
>>> hp.slice_to_dataframe(htype='open')
000001  000002
2019-01-01  1.0  7.0
2019-01-02  4.0  inf
>>> hp.slice_to_dataframe(share='000001')
open  high  low
2019-01-01  1.0  2.0  NaN
2019-01-02  4.0  5.0  6.0
>>> hp.slice_to_dataframe(htype='low', dropna=True)
            000001  000002
2019-01-02     6.0    12.0
subpanel(htypes: Optional[Union[str, Sequence[str], slice, int, list]] = None, shares: Optional[Union[str, Sequence[str], slice, int, list]] = None, hdates: Optional[Union[str, slice, Sequence[Any], int, list]] = None, *, copy: bool = True) HistoryPanel[源代码]

按具名参数沿 htypes / shares / hdates 取子面板,避免三元组轴顺序混淆。

None 表示该轴全选。默认 copy=True,得到与父对象数据缓冲区脱钩的副本;需要零拷贝时可设 copy=False (子面板 values 可能与父面板共享内存)。父对象上 __setitem__ 追加新列时会 替换父面板整块 valuescopy=False 子面板通常 不会 自动带上新列,且可能仍引用扩列前的缓冲区。

参数:
  • htypes (str, sequence, slice or int, optional) – 列 (数据类型)选择,语义与 panel[htypes, ...] 第一段一致。

  • shares (str, sequence, slice or int, optional) – 标的层选择,语义与 panel[:, shares, ...] 第二段一致。

  • hdates (str, sequence, slice or int, optional) – 时间轴选择,语义与 panel[..., hdates] 第三段一致。

  • copy (bool, default True) – 为 True 时对切片结果做数组拷贝。

返回:

所选轴子集构成的子面板;空输入对应空面板。

返回类型:

HistoryPanel

备注

__getitem__copy=False 切片类似:父级 __setitem__ 追加列之后,copy=False 子对象通常不含新列;需要稳定快照请保持 copy=True (默认)。

tail(row_count=5)[源代码]

返回HistoryPanel的最末几行,默认五行

参数:

row_count (int, default 5) – 打印的行数

返回:

  • dataframe, multi-indexed by share and htype as columns, with only last row_count rows

  • 一个dataframe,以share和htype为列的多重索引,只包含最后row_count行

示例

>>> data = np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020], [12.9, 13.0, 1020030],
...                   [12.3, 12.5, 1020040], [12.6, 13.2, 1020050], [12.9, 13.0, 1020060]],
...                  [[2.3, 2.5, 20010], [2.6, 2.8, 20020], [2.9, 3.0, 20030],
...                   [2.3, 2.5, 20040], [2.6, 2.8, 20050], [2.9, 3.0, 20060]]])
>>> hp = HistoryPanel(values=data,
...                          levels=['000300', '000001'],
...                          rows=pd.date_range('2020-01-01', periods=6),
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close,  open,   vol
2020-01-01  12.3,   12.5,   1020010
2020-01-02  12.6,   13.2,   1020020
2020-01-03  12.9,   13.0,   1020030
2020-01-04  12.3,   12.5,   1020040
2020-01-05  12.6,   13.2,   1020050
2020-01-06  12.9,   13.0,   1020060
share 1, label: 000001:
            close,  open,   vol
2020-01-01  2.3,    2.5,    20010
2020-01-02  2.6,    3.2,    20020
2020-01-03  2.9,    3.0,    20030
2020-01-04  2.3,    2.5,    20040
2020-01-05  2.6,    3.2,    20050
2020-01-06  2.9,    3.0,    20060
>>> hp.tail(3)
share 0, label: 000300
            close,  open,   vol
2020-01-04  12.3,   12.5,   1020040
2020-01-05  12.6,   13.2,   1020050
2020-01-06  12.9,   13.0,   1020060
share 1, label: 000001:
            close,  open,   vol
2020-01-04  2.3,    2.5,    20040
2020-01-05  2.6,    3.2,    20050
2020-01-06  2.9,    3.0,    20060
to_df_dict(by: str = 'share') dict[源代码]

将 HistoryPanel 转为字典:键为 share 或 htype,值为对应的 pandas.DataFrame

参数:

by (str, default 'share') – 取 'share' / 'shares' 时按标的维切分,字典键为股票代码,值为对应 DataFrame;取 'htype' / 'htypes' 时按数据类型维切分,字典键为 历史数据类型名,值为对应 DataFrame

返回:

df_dict

返回类型:

dict, {str: pandas.DataFrame}

示例

>>> hp = HistoryPanel(np.random.randn(2, 3, 4),
...                   rows=['2020-01-01', '2020-01-02', '2020-01-03'],
...                   levels=['000001', '000002', '000003'],
...                   columns=['close', 'open', 'high', 'low'])
>>> hp
share 0, label: 000001
            close,  open,   high,   low
2020-01-01  0.1,    0.2,    0.3,    0.4
2020-01-02  0.5,    0.6,    0.7,    0.8
2020-01-03  0.9,    1.0,    1.1,    1.2
share 1, label: 000002
            close,  open,   high,   low
2020-01-01  1.1,    1.2,    1.3,    1.4
2020-01-02  1.5,    1.6,    1.7,    1.8
2020-01-03  1.9,    2.0,    2.1,    2.2
share 2, label: 000003
            close,  open,   high,   low
2020-01-01  2.1,    2.2,    2.3,    2.4
2020-01-02  2.5,    2.6,    2.7,    2.8
2020-01-03  2.9,    3.0,    3.1,    3.2
>>> hp.to_df_dict(by='share')
{'000001':
            close,  open,   high,   low
2020-01-01  0.1,    0.2,    0.3,    0.4
2020-01-02  0.5,    0.6,    0.7,    0.8
2020-01-03  0.9,    1.0,    1.1,    1.2
, '000002':
            close,  open,   high,   low
2020-01-01  1.1,    1.2,    1.3,    1.4
2020-01-02  1.5,    1.6,    1.7,    1.8
2020-01-03  1.9,    2.0,    2.1,    2.2
, '000003':
            close,  open,   high,   low
2020-01-01  2.1,    2.2,    2.3,    2.4
2020-01-02  2.5,    2.6,    2.7,    2.8
2020-01-03  2.9,    3.0,    3.1,    3.2
}
>>> hp.to_df_dict(by='htype')
{'close':
            000001,  000002,  000003
2020-01-01  0.1,     1.1,     2.1
2020-01-02  0.5,     1.5,     2.5
2020-01-03  0.9,     1.9,     2.9
, 'open':
            000001,  000002,  000003
2020-01-01  0.2,     1.2,     2.2
2020-01-02  0.6,     1.6,     2.6
2020-01-03  1.0,     2.0,     3.0
, 'high':
            000001,  000002,  000003
2020-01-01  0.3,     1.3,     2.3
2020-01-02  0.7,     1.7,     2.7
2020-01-03  1.1,     2.1,     3.1
, 'low':
            000001,  000002,  000003
2020-01-01  0.4,     1.4,     2.4
2020-01-02  0.8,     1.8,     2.8
2020-01-03  1.2,     2.2,     3.2
}
to_multi_index_dataframe(along=None)[源代码]

等同于HistoryPanel.flatten_to_dataframe()

参数:

along (str, {'col', 'row', 'column'} Default: 'row') – 平铺HistoryPanel的每一层时,沿行方向还是列方向平铺, ‘col’或’column’表示沿列方向平铺,’row’表示沿行方向平铺

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020]],
...                                    [[2.3, 2.5, 20010], [2.6, 3.2, 20020]]]),
...                          levels=['000300', '000001'],
...                          rows=['2020-01-01', '2020-01-02'],
...                          columns=['close', 'open', 'vol'])
>>> hp
share 0, label: 000300
            close  open        vol
2020-01-01   12.3  12.5  1020010.0
2020-01-02   12.6  13.2  1020020.0
share 1, label: 000001
            close  open      vol
2020-01-01    2.3   2.5  20010.0
2020-01-02    2.6   3.2  20020.0
>>> hp.to_multi_index_dataframe(along='col')
           000300                  000001
            close  open        vol  close open      vol
2020-01-01   12.3  12.5  1020010.0    2.3  2.5  20010.0
2020-01-02   12.6  13.2  1020020.0    2.6  3.2  20020.0
>>> hp.to_multi_index_dataframe(along='row')
                   close  open        vol
000300 2020-01-01   12.3  12.5  1020010.0
       2020-01-02   12.6  13.2  1020020.0
000001 2020-01-01    2.3   2.5    20010.0
       2020-01-02    2.6   3.2    20020.0
to_numpy(copy: bool = False) ndarray[源代码]

返回与 values 相同形状的 ndarray;需要独立副本时使用 copy=True

空面板返回形状为 (0, 0, 0) 的 float 数组。非空时 copy=Falsenumpy.asarray(self.values) 语义一致,可与内部缓冲区共享内存。若之后在父对象上用 __setitem__ 追加 新列,父对象会替换 整块缓冲;此前用 copy=False 拿到的数组 不会 自动带上新列,不宜再视为当前面板的权威快照。

参数:

copy (bool, default False) – 为 True 时返回数组拷贝,修改返回值不影响本对象数据。

返回:

values 同形状的三维数组;空面板时为 (0, 0, 0)

返回类型:

numpy.ndarray

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy.history import HistoryPanel
>>> hp = HistoryPanel(
...     np.arange(12, dtype=float).reshape(2, 3, 2),
...     levels=['A', 'B'],
...     rows=pd.date_range('2020-01-01', periods=3),
...     columns=['close', 'open'],
... )
>>> hp.to_numpy(copy=True)
array([[[ 0.,  1.],
        [ 2.,  3.],
        [ 4.,  5.]],

       [[ 6.,  7.],
        [ 8.,  9.],
        [10., 11.]]])
to_share_frame(share: Union[str, int]) DataFrame[源代码]

将单一股票在 HistoryPanel 中的所有数据类型切片为一个 DataFrame。

该方法是 slice_to_dataframe(share=...) 的语法糖,返回的 DataFrame 以时间为索引、以全部 htypes 为列,适合做单股票全指标分析。

参数:

share (str or int) – 股票代码或层序号,语义与 slice_to_dataframe(share=...) 中的 share 参数一致。

返回:

行索引为 hdates,列为 htypes,包含该股票在所有时间点上的全部 历史数据。

返回类型:

pandas.DataFrame

unstack(by: str = 'share') dict[源代码]

等同于方法self.to_df_dict(), 是方法self.to_df_dict()的别称

参数:

by (str, {'share', 'htype'}, default 'share') – 指定按照share或者htype来unstack, 默认为share

返回:

unstack后的结果,是一个字典,key为share或htype,value为对应的DataFrame

返回类型:

dict

示例

>>> hp = HistoryPanel(np.random.randn(2, 3, 4),
...                   rows=['2020-01-01', '2020-01-02', '2020-01-03'],
...                   levels=['000001', '000002', '000003'],
...                   columns=['close', 'open', 'high', 'low'])
>>> hp
share 0, label: 000001
            close,  open,   high,   low
2020-01-01  0.1,    0.2,    0.3,    0.4
2020-01-02  0.5,    0.6,    0.7,    0.8
2020-01-03  0.9,    1.0,    1.1,    1.2
share 1, label: 000002
            close,  open,   high,   low
2020-01-01  1.1,    1.2,    1.3,    1.4
2020-01-02  1.5,    1.6,    1.7,    1.8
2020-01-03  1.9,    2.0,    2.1,    2.2
share 2, label: 000003
            close,  open,   high,   low
2020-01-01  2.1,    2.2,    2.3,    2.4
2020-01-02  2.5,    2.6,    2.7,    2.8
2020-01-03  2.9,    3.0,    3.1,    3.2
>>> hp.unstack(by='share')
{'000001':
            close,  open,   high,   low
2020-01-01  0.1,    0.2,    0.3,    0.4
2020-01-02  0.5,    0.6,    0.7,    0.8
2020-01-03  0.9,    1.0,    1.1,    1.2
, '000002':
            close,  open,   high,   low
2020-01-01  1.1,    1.2,    1.3,    1.4
2020-01-02  1.5,    1.6,    1.7,    1.8
2020-01-03  1.9,    2.0,    2.1,    2.2
, '000003':
            close,  open,   high,   low
2020-01-01  2.1,    2.2,    2.3,    2.4
2020-01-02  2.5,    2.6,    2.7,    2.8
2020-01-03  2.9,    3.0,    3.1,    3.2
}
>>> hp.unstack(by='htype')
{'close':
            000001,  000002,  000003
2020-01-01  0.1,     1.1,     2.1
2020-01-02  0.5,     1.5,     2.5
2020-01-03  0.9,     1.9,     2.9
, 'open':
            000001,  000002,  000003
2020-01-01  0.2,     1.2,     2.2
2020-01-02  0.6,     1.6,     2.6
2020-01-03  1.0,     2.0,     3.0
, 'high':
            000001,  000002,  000003
2020-01-01  0.3,     1.3,     2.3
2020-01-02  0.7,     1.7,     2.7
2020-01-03  1.1,     2.1,     3.1
, 'low':
            000001,  000002,  000003
2020-01-01  0.4,     1.4,     2.4
2020-01-02  0.8,     1.8,     2.8
2020-01-03  1.2,     2.2,     3.2
}
property values

返回当前对象内部的三维数据缓冲区 (与 _values 同一引用)。

非空时与 to_numpy(copy=False) 指向同一块内存;修改返回值会直接改动本对象数据。 通过 __setitem__ 追加新列时,内部可能 替换 整块数组,此前由子视图 (__getitem__ / subpanel(copy=False))持有的 values 可能仍指向扩列前的旧缓冲, 且不会自动出现新列。需要稳定快照请使用 subpanel(..., copy=True)to_numpy(copy=True)。 原地写入列时,若原数组非 float64,内部会升级为 float64 再存储。

返回:

形状 (level_count, row_count, column_count);空面板为 None

返回类型:

numpy.ndarray or None

HistoryPanel 对象提供了常用的金融数据统计与聚合方法,包括数据的描述性统计、滚动窗口计算、收益与风险指标计算,以及 K 线与技术指标计算等,具体如下:

基础统计与聚合

以下方法在 HistoryPanel 的三维数据上提供类似 pandas 的统计功能:

HistoryPanel.describe(by: Optional[str] = 'share', percentiles: tuple = (0.25, 0.5, 0.75), include: str = 'numeric', ddof: int = 1) DataFrame[源代码]

对 HistoryPanel 进行基础统计描述,类似 pandas.DataFrame.describe。

可以按标的 (share)、历史数据类型 (htype)或全局视角对数值数据做 count、 mean、std、min、max 及给定分位数等统计描述。

参数:
  • by ({'share', 'htype', None}, default 'share') – 统计视角: - ‘share’:每只股票一个 describe 结果,拼接成列为 (htype, stat) 的 MultiIndex; - ‘htype’:每个 htype 在所有股票与时间上的分布; - None:将全部数值视作一个整体样本池。

  • percentiles (tuple of float, default (0.25, 0.5, 0.75)) – 需要计算的分位数列表,值应在 (0, 1) 区间。

  • include ({'numeric', None}, default 'numeric') – 当前仅支持数值型统计,非数值列会被自动忽略。

  • ddof (int, default 1) – 计算标准差时的自由度参数,仅在 by is None 时生效。

返回:

描述性统计结果表,其 index/columns 结构取决于 by 的取值。

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(np.random.rand(2, 10, 2),
...                   levels=['000001.SZ', '000002.SZ'],
...                   rows=pd.date_range('2020-01-01', periods=10),
...                   columns=['open', 'close'])
>>> desc_share = hp.describe(by='share')
>>> desc_share
share 0, label: 000001.SZ
            open      close
count  10.000000  10.000000
mean    0.456789   0.567890
std     0.129099   0.086603
min     0.123456   0.234567
25%     0.234567   0.345678
50%     0.345678   0.456789
75%     0.567890   0.678901
share 1, label: 000002.SZ
            open      close
count  10.000000  10.000000
mean    0.345678   0.456789
std     0.149361   0.110769
min     0.012345   0.123456
25%     0.123456   0.234567
50%     0.234567   0.345678
75%     0.456789   0.567890
>>> sorted(desc_share.columns.get_level_values('stat').unique().tolist())
['25%', '50%', '75%', 'count', 'max', 'mean', 'min', 'std']
>>> desc_htype = hp.describe(by='htype')
>>> 'open' in desc_htype.index
True
HistoryPanel.mean(by: str = 'share', skipna: bool = True) DataFrame[源代码]

按标的或数据类型对 HistoryPanel 进行均值统计。

参数:
  • by ({'share', 'htype'}, default 'share') – 统计维度: - ‘share’:对每只股票在时间轴上的均值,返回 index 为 shares、columns 为 htypes 的 DataFrame; - ‘htype’:对每个 htype 在所有股票上的均值,返回转置后的 DataFrame。

  • skipna (bool, default True) – 是否在计算均值时忽略 NaN。

返回:

按指定维度聚合后的均值结果表。

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(np.random.rand(2, 3, 2),
...                   levels=['000001.SZ', '000002.SZ'],
...                   rows=pd.date_range('2020-01-01', periods=3),
...                   columns=['open', 'close'])
>>> hp.mean()
            open     close
000001.SZ  0.456789  0.567890
000002.SZ  0.345678  0.456789
HistoryPanel.std(by: str = 'share', skipna: bool = True) DataFrame[源代码]

按标的或数据类型对 HistoryPanel 进行标准差统计 (ddof=1)。

参数:
  • by ({'share', 'htype'}, default 'share') – 统计维度,语义同 mean()

  • skipna (bool, default True) – 是否在计算标准差时忽略 NaN。

返回:

按指定维度聚合后的标准差结果表。

返回类型:

pandas.DataFrame

示例

>>> hp = HistoryPanel(np.random.rand(2, 4, 2),
...                   levels=['000001.SZ', '000002.SZ'],
...                   rows=pd.date_range('2020-01-01', periods=4),
...                   columns=['open', 'close'])
>>> hp.std()
            open     close
000001.SZ  0.129099  0.086603
000002.SZ  0.149361  0.110769
HistoryPanel.min(by: str = 'share', skipna: bool = True) DataFrame[源代码]

按标的或数据类型对 HistoryPanel 进行最小值统计。

参数:
  • by ({'share', 'htype'}, default 'share') – 统计维度,语义同 mean()

  • skipna (bool, default True) – 是否在计算最小值时忽略 NaN。

返回:

按指定维度聚合后的最小值结果表。

返回类型:

pandas.DataFrame

示例

>>> data = np.array([[[1., 2.], [3., 4.]],
...                  [[5., 6.], [7., 8.]]])
>>> hp = HistoryPanel(values=data,
...                   levels=['000001.SZ', '000002.SZ'],
...                   rows=pd.date_range('2020-01-01', periods=2),
...                   columns=['open', 'close'])
>>> hp.min()
            open  close
000001.SZ   1.0    2.0
000002.SZ   5.0    6.0
HistoryPanel.max(by: str = 'share', skipna: bool = True) DataFrame[源代码]

按标的或数据类型对 HistoryPanel 进行最大值统计。

参数:
  • by ({'share', 'htype'}, default 'share') – 统计维度,语义同 mean()

  • skipna (bool, default True) – 是否在计算最大值时忽略 NaN。

返回:

按指定维度聚合后的最大值结果表。

返回类型:

pandas.DataFrame

示例

>>> data = np.array([[[1., 2.], [3., 4.]],
...                  [[5., 6.], [7., 8.]]])
>>> hp = HistoryPanel(values=data,
...                   levels=['000001.SZ', '000002.SZ'],
...                   rows=pd.date_range('2020-01-01', periods=2),
...                   columns=['open', 'close'])
>>> hp.max()
            open  close
000001.SZ   3.0    4.0
000002.SZ   7.0    8.0

研究与掩码 (where)

将任意可广播条件规整为与 values 同形的 bool 数组,供后续研究 API 的 mask= 参数使用 (如累计收益、归一化、组合聚合等)。二维 (M, L) 条件会沿 htype 轴复制到 (M, L, N);详见方法 docstring 与教程「使用 HistoryPanel 操作和分析历史数据」。

HistoryPanel.where(condition: Union[ndarray, Callable[[HistoryPanel], ndarray]]) ndarray[源代码]

将条件广播为与 values 同形的 bool 掩码,供研究 API 的 mask= 等参数使用。

不改变本对象。返回数组为 dtype=bool、形状 (share 数, 时间长度, htype 数),与 panel.values 一致。条件可为数组 (可广播到上述形状)或 callable(panel) 返回类数组。

研究向掩码与 Backtester 中 NaN 价格处理无关。整数 0/1 等会按 numpy 规则转为 bool。

形状 恰好为 (M, L) 的数组视为「每个 (share, 时间) 对所有 htype 共用同一布尔值」, 内部会先变为 (M, L, 1) 再广播到 (M, L, N) (因标准 numpy 无法将二维 (M,L) 直接广播到三维)。 一维 (M,) 与二维 (M, 1) 视为仅随标的变化,会展开为 (M, 1, 1) 再广播。

参数:

condition (numpy.ndarray or callable) – 类数组:先 np.asarray(..., dtype=bool) 再广播到 self.shape。 若为 callable,则调用 condition(self) 得到数组后再处理。 裸 str 不接受,将引发 TypeError (英文)。

返回:

self.shape 相同的三维 bool 数组 (拷贝,与内部 values 不共享写缓冲)。

返回类型:

numpy.ndarray

抛出:
  • TypeErrorconditionstr 时抛出 (英文)。

  • ValueError – 无法将返回值转为 bool 数组或无法广播到 self.shape 时抛出 (英文)。

备注

condition 可为 富比较 的直接结果 (自 2.2.8 起):例如 panel.where(panel.close > 100.0)panel.where(panel['close'] > panel['open']),其中 > 等对 HistoryPanel 与标量 / 可广播数组 / 另一面板 (须满足对齐规则)返回 numpy.ndarraydtype=bool),再由本方法 广播到与 panel.values 同形。

cum_returnnormalizeportfoliomask= 可直接使用本方法返回值或与其同形、 dtype=bool 的数组。 更多场景见文档「使用 HistoryPanel 操作和分析历史数据」教程与 Sphinx HistoryPanel API 中 「研究与掩码 (where)」小节。

示例

空面板得到 (0,0,0) 的 bool 数组:

>>> empty = HistoryPanel()
>>> empty.where(True).shape
(0, 0, 0)

values 同形的比较结果可直接传入:

>>> import pandas as pd
>>> hp = HistoryPanel(
...     np.arange(24, dtype=float).reshape(2, 3, 4),
...     levels=['A', 'B'],
...     rows=pd.date_range('2020-01-01', periods=3),
...     columns=['a', 'b', 'c', 'd'],
... )
>>> m = hp.where(hp.values > 10)
>>> m.shape == hp.shape
True
>>> not bool(m[0, 0, 0]) and bool(m[-1, -1, -1])
True

标量 True / False 填满整块:

>>> import numpy as np
>>> hp.where(True).all() and not hp.where(False).any()
True

(M, L) 条件沿 htype 轴广播 (例如事件日):

>>> ev = np.zeros((2, 3), dtype=bool)
>>> ev[:, 1] = True
>>> m2 = hp.where(ev)
>>> bool(m2[0, 1, 0]) and bool(m2[0, 1, 3])
True

(M, L, 1)(M, L) 语义一致,沿 htype 维复制:

>>> c_ml1 = (hp.values[:, :, :1] > 10)
>>> m2b = hp.where(c_ml1)
>>> m2b.shape == hp.shape
True

使用 lambda 基于面板数据构造条件:

>>> m3 = hp.where(lambda p: p.values[:, :, 0] >= 3)
>>> m3.shape == hp.shape
True

复合布尔条件:

>>> m4 = hp.where(lambda p: (p.values >= 5) & (p.values <= 18))
>>> m4.dtype == bool
True

以下为与教程互补的稍长示例 (不依赖网络;可与 docstring 中 doctest 对照):

import numpy as np
import pandas as pd
from qteasy import HistoryPanel

# 最小面板:M=2, L=3, N=4
hp = HistoryPanel(
    np.arange(24, dtype=float).reshape(2, 3, 4),
    levels=['A', 'B'],
    rows=pd.date_range('2020-01-01', periods=3),
    columns=['a', 'b', 'c', 'd'],
)
# Event window on time axis: last row True for all shares and htypes
M, L, N = hp.shape
event_ml = np.zeros((M, L), dtype=bool)
event_ml[:, -1] = True
mask_event = hp.where(event_ml)
assert mask_event[:, -1, :].all() and not mask_event[:, 0, :].any()

可将 mask = hp.where(...) 直接传入 cum_return()normalize()mask= 参数 (广播规则与 where 一致)。

列属性访问、比较与 loc (与 pandas 的差异)

  • 属性:合法标识符列名可用 hp.close (只读),等价 hp['close'];含 | 等非法标识符的列名、以及未知名仍须用 hp['...']。赋值请统一 hp['col'] = ...。已有方法 / 描述符 (如 wherevalues)与同名列冲突时,点号仍解析为 API,列请用方括号。

  • 比较hp > 0hp['close'] > hp['open'] 等返回 numpy.ndarray (布尔 dtype),不返回 HistoryPanel;可与 hp.where(...) 衔接。两侧均为面板时须 shareshdates 一致;htypes 须一致,或两侧均为单列切片 (如两列比较)。

  • loc 索引hp.loc[k] 等价 hp[:, :, k],仅沿时间轴 (hdates)筛选;不接受 where(M, L, N) 布尔立方,格点掩码请 where + mask=

  • 算术与拷贝

    • hp + 1hp * arr 等算术运算会返回新的 HistoryPanel,不修改原对象。

    • hp += 1hp *= arr 等就地运算符会显式修改原对象。

    • hp.copy(deep=True) (默认)返回深拷贝,修改副本不影响原对象;hp.copy(deep=False) 共享底层数组,修改副本会同步影响原对象。

plot 的衔接:用 (M,L) mask 做高亮

在研究场景中,事件日/信号/可交易池常见输出为二维布尔矩阵 mask_ml,形状为 (M, L) (标的数 × 时间长度)。 HistoryPanel.plot()highlight 支持把该二维 mask 映射到当前图形中的高亮点:

  • 子集 mask:若 mask_ml.shape == (M_plot, L),其中 M_plot 为本次 plot(shares=...) 选中的 share 数,则按绘图 share 顺序对应;

  • 全量 mask:若 mask_ml.shape == (M_all, L)M_all == len(hp.shares)),则按 share 名抽取当前绘图子集 (禁止按位置静默截断);

  • overlay:当 layout='overlay' 且两标的叠加时,默认 primary-only 显示高亮 (与 Plotly highlight 既有语义一致)。

示例:

import numpy as np
hp = ...  # 已构造好的 HistoryPanel
M, L, N = hp.shape
mask_ml = np.zeros((M, L), dtype=bool)
mask_ml[:, -1] = True
fig = hp.plot(highlight={'condition': mask_ml})
HistoryPanel.loc

沿 hdates (时间轴)选取子面板的只读索引器。

hp.loc[key]hp[:, :, key] 等价,用于切片、时间标签、标签列表、: 或 长度等于 row_count 的一维布尔掩码。格点级 (M,L,N) 布尔条件请用 where() 与后续 mask=;格点级条件不要传入 loc

返回:

轻量代理;对其使用 [...] 即按时间轴取子面板。

返回类型:

_HistoryPanelLocIndexer

示例

>>> import pandas as pd
>>> import numpy as np
>>> hp = HistoryPanel(
...     np.arange(8, dtype=float).reshape(2, 4, 1),
...     levels=['A', 'B'],
...     rows=pd.date_range('2020-01-01', periods=4),
...     columns=['close'],
... )
>>> hp.loc[0:2]
share 0, label: A
            close
2020-01-01    0.0
2020-01-02    1.0
share 1, label: B
            close
2020-01-01    4.0
2020-01-02    5.0

列级 DSL:assign

assign 提供类似 pandas 的列级 DSL,可以一次性派生或更新多列,支持在单次调用中基于已有列或刚新增的列构造新因子;支持返回新面板或在原面板上原地扩列。

HistoryPanel.assign(*, inplace: bool = False, **kwargs: Any) HistoryPanel[源代码]

批量派生或更新列 (htypes),支持多列一次性追加或覆盖。

assign() 提供类似 pandas 的列级 DSL:可以同时为多个新列命名,并通过 可调用对象或数组/标量在单次调用中完成派生;同一次调用中,后定义的列 可以依赖前面刚新增的列。该方法既支持返回新面板,也支持在原面板上原地 扩列/覆盖。

参数:
  • inplace (bool, default False) – 为 True 时在当前 HistoryPanel 上原地追加/覆盖列并返回自身; 为 False 时在当前数据的拷贝上追加/覆盖列并返回新 HistoryPanel

  • **kwargs – 每个关键字参数的键为新列名 (htype),必须为非空字符串;值可以是 Callable[[HistoryPanel], np.ndarray],也可以是可被 np.asarray 且可广播到 (M, L) 的数组/标量。

返回:

inplace=False 时返回新增列后的新面板;inplace=True 时返回原面板。

返回类型:

HistoryPanel

抛出:
  • ValueError – 面板为空、列名为空字符串,或可调用对象/数组返回的结果无法广播到 (M, L) 时抛出 (英文信息)。

  • TypeError – 列名不是字符串时抛出 (英文信息)。

简短示例 (可与 where() 联用):

# 假设 hp 已含 'close' 列
# mask = hp.where(hp.close > 100.0)           # 比较结果为 bool ndarray,再规整为 (M,L,N)
# sub = hp.loc[0:20]                          # 等价 hp[:, :, 0:20],按时间轴截取
# L = len(hp.hdates)
# sub2 = hp.loc[[True]*3 + [False]*(L - 3)]   # 一维 bool 长度须等于 L

横截面与标准化:rank / zscore

rankzscore 用于轻量因子研究中的“逐日截面排名/标准化”与“逐股时序滚动标准化”。 zscore 通过 method 显式区分两种语义:

  • method='cs':固定日期,在 share 维做截面标准化;

  • method='ts':固定 share,在时间轴上做滚动标准化 (需要 window)。

HistoryPanel.rank(by: str, *, axis: str = 'share', method: str = 'average', new_htype: Optional[str] = None) HistoryPanel[源代码]

按时间逐日对横截面 (share 维)做排名并追加一列返回新面板。

参数:
  • by (str) – 参与排名的列名 (htype)。会先经 _resolve_price_htype() 解析,支持 close|b 等复权后缀列。

  • axis ({'share'}, default 'share') – 目前仅支持沿 share 维做截面排名。

  • method ({'average', 'min', 'max', 'first', 'dense'}, default 'average') – 并列值 (tie)的排名处理方式,语义与 pandas Series.rank(method=...) 一致。

  • new_htype (str, optional) – 输出列名;为 None 时默认使用 rank_{by}

返回:

追加排名列后的新面板;不修改原对象。空面板返回空面板。

返回类型:

HistoryPanel

抛出:

ValueError – 当参数非法、列不存在、或输出列名冲突时抛出 (英文信息)。

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy import HistoryPanel
>>> hp = HistoryPanel(
...     np.array([[[1.0], [2.0]], [[2.0], [1.0]]]),
...     levels=['s1', 's2'],
...     rows=pd.date_range('2023-01-01', periods=2),
...     columns=['close'],
... )
>>> hp2 = hp.rank(by='close')
>>> 'rank_close' in hp2.htypes
True
HistoryPanel.zscore(by: str, *, method: str = 'cs', window: Optional[int] = None, new_htype: Optional[str] = None) HistoryPanel[源代码]

对指定列计算标准化分数 (zscore)并追加一列返回新面板。

本方法通过 method 参数显式区分两种常用语义:

  • method='cs' (cross-sectional):固定每个时间点,在 share 维做截面标准化;

  • method='ts' (time-series rolling):固定每个 share,在时间轴上做滚动标准化。

参数:
  • by (str) – 参与标准化的列名 (htype)。会先经 _resolve_price_htype() 解析,支持 close|b 等复权后缀列。

  • method ({'cs', 'ts'}, default 'cs') – 标准化语义:截面 (cs)或时序滚动 (ts)。

  • window (int, optional) – method='ts' 时的滚动窗口长度 (bar 数),必须为正整数;method='cs' 时必须为 None。

  • new_htype (str, optional) – 输出列名;为 None 时默认使用 cs_z_{by}ts_z_{by}_{window}

返回:

追加 zscore 列后的新面板;不修改原对象。空面板返回空面板。

返回类型:

HistoryPanel

抛出:

ValueError – 当参数非法、列不存在、或输出列名冲突时抛出 (英文信息)。

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy import HistoryPanel
>>> hp = HistoryPanel(
...     np.array([[[1.0], [2.0]], [[3.0], [4.0]]]),
...     levels=['s1', 's2'],
...     rows=pd.date_range('2023-01-01', periods=2),
...     columns=['x'],
... )
>>> hp_cs = hp.zscore(by='x', method='cs')
>>> hp_ts = hp.zscore(by='x', method='ts', window=2)

对齐与重采样:align_to / resample

当你需要对两个 HistoryPanel 做逐元素运算 (例如相除、相减、相关性等)时,若两者的 shareshdates 不一致,NumPy 广播可能产生静默错行 (silent misalignment)。因此本项目提供显式对齐入口:

  • align_to():按标签对齐 shareshdates,支持 join='inner'|'outer',缺失处填 fill_value

  • resample():沿时间轴重采样,必须显式提供 agg= (覆盖全部 htypes),避免聚合语义不明导致“看似成功但结果不可解释”。

HistoryPanel.align_to(other: HistoryPanel, *, join: str = 'inner', fill_value: float = nan) Tuple[HistoryPanel, HistoryPanel][源代码]

将两个 HistoryPanel 沿 shares 与 hdates 轴按标签对齐,避免 silent 错行。

本方法**不会**按 iloc/位置对齐;仅使用 axis labels 做显式对齐。对齐后返回两块 新的面板,它们具有完全一致的 shareshdateshtypes,缺失格点用 fill_value 填充。

参数:
  • other (HistoryPanel) – 需要对齐的另一个面板。

  • join ({'inner', 'outer'}, default 'inner') –

    对齐方式:

    • inner:取两者 shares 与 hdates 的交集;

    • outer:取两者 shares 与 hdates 的并集。

    输出顺序为稳定顺序:交集以 self 的顺序为准;并集为 self 在前、再追加 other 中未出现元素。

  • fill_value (float, default np.nan) – 对齐后缺失位置的填充值。

返回:

对齐后的 (self_aligned, other_aligned)

返回类型:

(HistoryPanel, HistoryPanel)

抛出:
  • TypeErrorother 不是 HistoryPanel 时抛出 (英文信息)。

  • ValueErrorjoin 非法、或两者 htypes 不完全一致时抛出 (英文信息)。

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy import HistoryPanel
>>> hp1 = HistoryPanel(np.array([[[1.0],[2.0]]]), levels=['s1'],
...                   rows=pd.date_range('2023-01-01', periods=2), columns=['x'])
>>> hp2 = HistoryPanel(np.array([[[10.0],[11.0]]]), levels=['s2'],
...                   rows=pd.date_range('2023-01-02', periods=2), columns=['x'])
>>> a1, a2 = hp1.align_to(hp2, join='outer', fill_value=np.nan)
>>> a1.shares
['s1', 's2']
HistoryPanel.resample(rule: str, *, agg: Optional[dict] = None) HistoryPanel[源代码]

沿时间轴 (hdates)按规则重采样并返回新面板。

为避免聚合语义不明导致 silent 错行,本方法要求显式提供 agg,并且必须覆盖 当前面板的全部 htypes

参数:
  • rule (str) – pandas 兼容的重采样规则字符串,如 'W''M''5D' 等。

  • agg (dict, required) – 聚合规则字典:{htype_name: agg_name},其中 agg_name 支持 'first'|'last'|'min'|'max'|'sum'|'mean'。必须覆盖全部 htypes

返回:

重采样后的新面板;不修改原对象。空面板返回空面板。

返回类型:

HistoryPanel

抛出:

ValueError – 当 agg 缺失、未覆盖全部列、包含未知列名、聚合方法非法或 rule 非法时抛出 (英文信息)。

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy import HistoryPanel
>>> idx = pd.date_range('2023-01-01', periods=10, freq='D')
>>> hp = HistoryPanel(np.arange(10, dtype=float).reshape(1, 10, 1),
...                   levels=['s1'], rows=idx, columns=['x'])
>>> out = hp.resample('W', agg={'x': 'last'})
>>> out.hdates
[Timestamp('2023-01-01 00:00:00'), Timestamp('2023-01-08 00:00:00')]

滚动窗口

使用滚动窗口方法可以在 HistoryPanel 的时间维度上进行滑动计算,支持常见的滚动平均、滚动标准差等操作:

HistoryPanel.rolling(window: int, min_periods: Optional[int] = None, center: bool = False, by: str = 'share') HistoryPanelRolling[源代码]

基于 HistoryPanel 构造滚动窗口统计对象。

滚动仅沿时间轴 (rows / hdates)进行,window 为整数 bar 数。

参数:
  • window (int) – 滚动窗口长度。

  • min_periods (int, optional) – 最小有效观测数,小于该数时结果为 NaN。默认与 window 相同。

  • center (bool, default False) – 是否使用居中窗口,语义与 pandas.Series.rolling 一致。

  • by ({'share', 'htype'}, default 'share') – 指定滚动的分组方式: - ‘share’: 每只股票的每个 htype 独立做滚动统计 (最常用); - ‘htype’: 每个 htype 在所有股票上独立做滚动统计。

返回:

滚动窗口统计对象,支持调用 mean(), std(), min(), max() 等

返回类型:

HistoryPanelRolling

示例

>>> hp = HistoryPanel(np.array([[[12.3, 12.5, 1020010], [12.6, 13.2, 1020020]],
...                                    [[2.3, 2.5, 20010], [2.6, 3.2, 20020]]]),
...                          levels=['000300', '000001'],
...                          rows=['2020-01-01', '2020-01-02'],
...                          columns=['close', 'open', 'vol'])
>>> hp.rolling(window=2, by='share').mean()
share 0, label: 000300
            close  open        vol
2020-01-01    NaN   NaN        NaN
2020-01-02   12.45  12.85  1020015.0
share 1, label: 000001
            close  open        vol
2020-01-01    NaN   NaN        NaN
2020-01-02    2.45   2.85  20015.0
class qteasy.history.HistoryPanelRolling(hp: HistoryPanel, window: int, min_periods: int, center: bool, by: str)[源代码]

HistoryPanel 的滚动窗口统计对象。

该对象通常由 HistoryPanel.rolling() 创建,对应一个固定的窗口 参数组合,并提供 mean/std/sum/min/max/apply 等方法,返回新的 HistoryPanel。

apply(func: Callable[[ndarray], float], raw: bool = False, **kwargs) HistoryPanel[源代码]

在滚动窗口上应用自定义函数。

参数:
  • func (callable) – 自定义函数,接受一个窗口向量并返回标量。

  • raw (bool, default False) – 为 True 时向 func 传入 ndarray,否则传入 Series

  • **kwargs – 透传给 func 的其他参数。

返回:

应用自定义函数后的滚动结果面板,shares/hdates/htypes 标签保持不变。

返回类型:

HistoryPanel

备注

  • 与 pandas 一致:当窗口内有效样本数小于 min_periods 时,结果为 NaN。

  • func 应返回标量数值;返回数组或非数值类型可能导致 pandas 报错或产生 不符合预期的结果。

示例

>>> hp = qt.get_history_data(htype_names='close', shares='000001.SZ', rows=30, as_data_frame=False)
>>> roller = hp.rolling(window=5, min_periods=5)
>>> hp_mean = roller.mean()
>>> hp_mean
share 0, label: 000001
            close
2020-01-01  NaN
2020-01-02  NaN
2020-01-03  NaN
2020-01-04  NaN
2020-01-05  10.0
2020-01-06  10.5
...
2020-01-30  11.2
>>> hp_mad = roller.apply(lambda x: float(np.mean(np.abs(x - np.mean(x)))), raw=True)
>>> hp_mad
share 0, label: 000001
            close
2020-01-01  NaN
2020-01-02  NaN
2020-01-03  NaN
2020-01-04  NaN
2020-01-05  0.0
2020-01-06  0.5
...
2020-01-30  0.4
max() HistoryPanel[源代码]

计算滚动窗口最大值并返回新面板。

返回:

滚动最大值结果面板,标签与原面板一致。

返回类型:

HistoryPanel

mean() HistoryPanel[源代码]

计算滚动窗口均值并返回新面板。

返回:

滚动均值结果面板,标签与原面板一致。

返回类型:

HistoryPanel

min() HistoryPanel[源代码]

计算滚动窗口最小值并返回新面板。

返回:

滚动最小值结果面板,标签与原面板一致。

返回类型:

HistoryPanel

std() HistoryPanel[源代码]

计算滚动窗口标准差并返回新面板。

返回:

滚动标准差结果面板,标签与原面板一致。

返回类型:

HistoryPanel

sum() HistoryPanel[源代码]

计算滚动窗口求和并返回新面板。

返回:

滚动求和结果面板,标签与原面板一致。

返回类型:

HistoryPanel

收益与风险指标

HistoryPanel.returns(price_htype: str = 'close', method: str = 'simple', periods: int = 1, as_panel: bool = False, dropna: bool = False)[源代码]

基于指定价格序列计算收益率。

参数:
  • price_htype (str, default 'close') – 用于计算收益率的价格类型,必须在 htypes 中存在。

  • method ({'simple', 'log'}, default 'simple') –

    • simple: r_t = p_t / p_{t-periods} - 1

    • log: r_t = log(p_t) - log(p_{t-periods})

  • periods (int, default 1) – 收益率间隔的 bar 数。

  • as_panel (bool, default False) – False 返回 DataFrame (index=时间,columns=shares); True 返回 HistoryPanel (htypes 仅含 ret_{price_htype})。

  • dropna (bool, default False) – True 时删除全为 NaN 的起始行。

返回类型:

pandas.DataFrame or HistoryPanel

HistoryPanel.cum_return(htypes: Optional[Union[str, Sequence[str]]] = None, *, method: str = 'simple', mask: Optional[ndarray] = None) HistoryPanel[源代码]

沿时间维逐标的计算累计收益 (研究向),返回新面板。

默认对 close 列 (经 _resolve_price_htype() 解析,支持 close|b 等)计算。 输出列名为 cumret_<用户传入的列名>,与 returns() 使用 ret_<price_htype> 的策略一致。 若时间路径上出现 NaN 或非正价格,自该点起后续结果均为 NaN (路径断开)。

参数:
  • htypes (str, sequence of str, optional) – 参与计算的列名;None 时仅处理 close (解析后)。

  • method ({'simple', 'log'}, default 'simple') – simple:自首个有效正价 t0p_t/p_{t0}-1loglog(p_t)-log(p_{t0})

  • mask (numpy.ndarray, optional) – 与 where() 相同广播规则;为 False 的位置在计算前视为缺失 (NaN)。

返回:

shares / hdates 与原面板一致,仅含累计收益列。

返回类型:

HistoryPanel

抛出:

ValueError – 非法 method、列无法解析、mask 无法广播、或输出列名与现有 htypes 冲突时抛出 (英文)。

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy.history import HistoryPanel
>>> hp = HistoryPanel(
...     np.array([[[10.0], [11.0], [12.0]]]),
...     levels=['S'],
...     rows=pd.date_range('2023-01-01', periods=3),
...     columns=['close'],
... )
>>> cr = hp.cum_return(method='simple')
>>> cr
share 0, label: S
            cumret_close
2023-01-01          0.0
2023-01-02          0.1
2023-01-03          0.2
HistoryPanel.normalize(htypes: Optional[Union[str, Sequence[str]]] = None, *, base_index: int = 0, mask: Optional[ndarray] = None) HistoryPanel[源代码]

将指定列按基准时点缩放到相对 1.0 (研究向),返回新面板。

默认以 base_index 处有效价格为分母;该时点被 mask 排除、为 NaN 或为 0 时, 该 (share, 列) 整条时间序列输出均为 NaN。输出列名为 norm_<用户传入的列名>

参数:
  • htypes (str, sequence of str, optional) – 参与计算的列;None 时仅 close (解析后)。

  • base_index (int, default 0) – 时间轴上的基准下标 (从 0 起);越界时抛出 ValueError (英文)。

  • mask (numpy.ndarray, optional) – 与 where() 相同广播规则。

返回:

与原面板相同的 shares / hdates,仅含归一化列。

返回类型:

HistoryPanel

抛出:

ValueError – 列无法解析、mask 无法广播、base_index 越界、或输出列名冲突时抛出 (英文)。

示例

>>> import numpy as np
>>> import pandas as pd
>>> from qteasy.history import HistoryPanel
>>> hp = HistoryPanel(
...     np.array([[[10.0], [20.0], [40.0]]]),
...     levels=['S'],
...     rows=pd.date_range('2023-01-01', periods=3),
...     columns=['close'],
... )
>>> nm = hp.normalize(base_index=0)
>>> nm
share 0, label: S
            norm_close
2023-01-01        1.0
2023-01-02        2.0
2023-01-03        4.0
HistoryPanel.portfolio(htypes: Union[str, Sequence[str]] = 'close', *, mode: str = 'equal', weights: Optional[ndarray] = None, mask: Optional[ndarray] = None, groups: Optional[Dict[str, Sequence[str]]] = None, benchmark: Optional[str] = None, benchmark_output: str = 'none', new_share_name: str = 'PORTFOLIO', normalize_weights: bool = True, allow_ungrouped: str = 'error') HistoryPanel[源代码]

沿 share 维将多标的聚合成组合序列 (研究向),返回新面板。

默认 benchmark_output='none';若设置 benchmark,可用 tag_along 附加基准行, 或用 excess_only 仅保留 excess 前缀列(组合减基准,列名带 excess 前缀)。

groupsNone 时,全面板聚成一行,名称为 new_share_namegroups 非空时,键为输出 share 标签 (按插入序排列),值为组内原始 share 列表; 组间 share 不得重叠。allow_ungrouped='error' 时,每个面板 share 必须恰好属于一组。

groupsNone 且指定了 benchmark 时,基准 share 不参与组合聚合 (避免把指数与个股权重混在一起), 仅用于 tag_alongexcess_only;若剔除后无可用 share (例如面板仅含基准)则抛出 ValueError

mask 广播规则与 where() 一致;无效格点不参与聚合。

参数:
  • htypes (str or sequence of str, default 'close') – 参与聚合的列名;经 _resolve_price_htype() 解析。

  • mode ({'equal', 'weighted'}, default 'equal') – 等权平均或与 weights 联用的加权平均。

  • weights (numpy.ndarray, optional) – 形状 (M,)(M, L),与 self.shares 顺序对齐;仅 mode='weighted' 时使用。

  • mask (numpy.ndarray, optional) – 与 where() 相同广播规则。

  • groups (dict, optional) – 输出组名 → 组内 share 标签列表。

  • benchmark (str, optional) – 基准 share,须在 self.shares 中。

  • benchmark_output ({'none', 'tag_along', 'excess_only'}, default 'none') – 基准输出形态;无 benchmark 时仅允许 'none'

  • new_share_name (str, default 'PORTFOLIO') – 无 groups 时合成行的 share 名。

  • normalize_weights (bool, default True) – 加权时,在参与聚合的成员上对权重做归一后再加权求和 (与 sum(w*x)/sum(w) 数值一致)。

  • allow_ungrouped ({'error', 'exclude'}, default 'error') – groups 非空时,是否要求覆盖全部 share。

返回:

新对象;hdates 与时间长度与原面板一致。

返回类型:

HistoryPanel

抛出:

ValueError – 参数非法、share 不在面板、组重叠、mask 无法广播等 (英文)。

HistoryPanel.volatility(window: int = 20, price_htype: str = 'close', method: str = 'simple', annualize: bool = True, periods_per_year: Optional[int] = None, as_panel: bool = False)[源代码]

基于收益率序列计算滚动波动率 (标准差)。

参数:
  • window (int, default 20) – 滚动窗口长度 (bar 数)。

  • price_htype (str, default 'close') – 用于计算收益率的价格类型。

  • method ({'simple', 'log'}, default 'simple') – 收益率计算方式,与 returns() 一致。

  • annualize (bool, default True) – 是否年化 (乘以 sqrt(periods_per_year))。

  • periods_per_year (int, optional) – 年化时每年 bar 数;未指定且 annualize=True 时尝试从时间间隔推断,无法推断则报错。

  • as_panel (bool, default False) – 返回形式同 returns()。

返回类型:

pandas.DataFrame or HistoryPanel

HistoryPanel.alpha_beta(benchmark: Union[Series, DataFrame], price_htype: str = 'close', method: str = 'simple', freq: Optional[str] = None, annualize: bool = True) DataFrame[源代码]

计算各股票相对于给定基准收益率序列的 alpha / beta 等指标。

参数:
  • benchmark (Series or DataFrame) – 基准价格时间序列,index 应与 HistoryPanel.hdates 对齐或至少有交集。 DataFrame 时只使用第一列作为基准价格。

  • price_htype (str, default 'close') – 用于计算收益率的价格类型。

  • method ({'simple', 'log'}, default 'simple') – 收益率计算方式,与 returns() 一致。

  • freq (str, optional) – 收益率频率字符串,用于 alpha 年化时推断每年 bar 数,如 ‘D’、’W’、’M’。

  • annualize (bool, default True) – 是否对 alpha 进行年化。

返回:

index 为 shares,列为 [‘alpha’, ‘beta’, ‘r2’, ‘n_obs’]。

返回类型:

pandas.DataFrame

K 线与技术指标

第一入口:research_preset

research_preset 用于快速拼出「可直接 plot 的常用列集合」 (例如 OHLCV + MACD + MA),避免在绘图阶段隐式计算指标。缺少输入列时会抛出英文 ValueError 并给出缺列提示。

HistoryPanel.research_preset(name: str, *, inplace: bool = False) HistoryPanel[源代码]

按预设快速生成研究常用列集合,并返回结果面板。

该方法旨在作为 HistoryPanel 的“第一入口”:在不引入回测语义的前提下, 快速拼出 OHLCV + 常用技术指标列 (如 MACD、均线)以便直接绘图或继续做研究。

参数:
  • name (str) –

    预设名称。目前支持:

    • 'ohlcv_macd_ma':要求面板至少包含 open/high/low/close/vol,并生成 macd_12_26_9macd_signal_12_26_9macd_hist_12_26_9sma_20

  • inplace (bool, default False) – 为 True 时在原面板上原地追加预设列并返回原面板;为 False 时返回新增列后的新面板。

返回:

追加预设列后的 HistoryPanel。当 inplace=True 时返回原对象。

返回类型:

HistoryPanel

抛出:

ValueError – 当预设名称非法,或缺少预设所需的输入列时抛出 (错误信息为英文)。

HistoryPanel.kline

K 线技术指标访问器,提供 sma、ema、bbands、macd、kdj 等方法。

HistoryPanel.apply_ta(func_name: str, htype: str = 'close', shares: Optional[Iterable[str]] = None, as_panel: bool = True, **kwargs)[源代码]

调用 qteasy.tafuncs 中的技术指标函数,并在多股票上广播计算。

参数:
  • func_name (str) – qteasy.tafuncs 中的函数名称,如 ‘sma’、’ema’ 等。

  • htype (str, default 'close') – 作为输入的一维时间序列的数据类型。

  • shares (list of str, optional) – 需要计算的股票列表,默认使用全部 shares。

  • as_panel (bool, default True) – True 时返回新的 HistoryPanel,在 htypes 末尾追加输出列; False 时返回 MultiIndex 列的 DataFrame (时间×[share, output_name])。

HistoryPanel.candle_pattern(name: str, price_htypes: tuple[str, str, str, str] = ('open', 'high', 'low', 'close'), as_panel: bool = False, **kwargs)[源代码]

基于 ta-lib 形态函数计算蜡烛形态信号。

参数:
  • name (str) – 形态函数名称,如 ‘cdlhammer’。

  • price_htypes (tuple of str, default ('open','high','low','close')) – OHLC 对应的 htypes 名称。

  • as_panel (bool, default False) – False 返回 DataFrame (时间×股票),True 返回单一 htype 的 HistoryPanel。

qteasy级别的历史数据处理函数

qteasy 还提供了若干独立于 HistoryPanel 类的函数,支持更灵活的历史数据处理与分析:

qteasy.get_history_data(htypes=None, *, htype_names=None, data_types=None, data_source=None, shares=None, symbols=None, start=None, end=None, freq=None, rows=None, asset_type=None, adj=None, as_data_frame=None, group_by=None, **kwargs)[源代码]

根据给定的标的、数据类型与频率,从本地数据源获取历史数据并组装为策略可直接使用的结构。

可以通过 htype_namesdata_types 指定需要的数据种类,并结合 shares / symbols、时间区间与 freq 控制取数范围;根据 as_data_framegroup_by 的设置,函数返回 HistoryPanel 或按标的/数据类型分组的 DataFrame 字典。关于数据类型 推断、频率转换和 trade_time_only 等高级用法,详见文档「历史数据获取 get_history_data」 相关章节。

参数:
  • htype_names (str or list of str, optional) – 需要获取的历史数据名称集合;可为逗号分隔字符串(如 'open, high, low, close') 或列表(如 ['open', 'high', 'low', 'close'])。若为空,系统会结合 freq / asset_type 等参数推断可用的 htypes。

  • htypes (list of DataType, optional, deprecated) – 历史数据类型对象列表;语义与 htype_names 类似,优先使用 htype_names / data_types 新接口。

  • data_types (list of DataType, optional) – 需要获取的历史数据类型集合,必须是合法的数据类型对象。 如果给出了本参数,htype_names会被忽略,否则根据htype_names参数创建可能的htypes

  • data_source (DataSource, optional) – 需要获取历史数据的数据源

  • shares (str or list of str, optional) – 证券代码集合;可为逗号分隔字符串(如 '000001.SZ, 000002.SZ')或列表 (如 ['000001.SZ', '000002.SZ'])。

  • symbols (str or list of str, optional) – 证券代码集合;可为逗号分隔字符串(如 '000001, 000002')或列表 (如 ['000001', '000002'])。

  • start (str, optional) – YYYYMMDD HH:MM:SS 格式的日期/时间,获取的历史数据的开始日期/时间(如果可用)

  • end (str, optional) – YYYYMMDD HH:MM:SS 格式的日期/时间,获取的历史数据的结束日期/时间(如果可用)

  • rows (int, default 10) – 获取的历史数据的行数,如果指定了start和end,则忽略此参数,且获取的数据的时间范围为[start, end] 如果未指定start和end,则获取数据表中最近的rows条数据,使用row来获取数据时,速度比使用日期慢得多

  • freq (str, optional) – 频率;支持 1min/5min/15min/30min 等分钟周期,以及 H/D/W/M 等小时/日/周/月周期(如 K 线)。

  • asset_type (str or list of str, optional) – 资产类型过滤;可用逗号分隔字符串(如 'E, IDX')或列表(如 ['E', 'IDX'])。 常见取值包括 anyEIDXFTFD 等。

  • adj (str, optional, deprecated) – 已弃用的复权选项(none/nback/bforward/fw/f)。 新代码请在 htype 中显式使用复权列名(如 close|b)。

  • as_data_frame (bool, default True) – True 时返回 HistoryPanelFalse 时返回 DataFrame 字典。

  • group_by (str, default 'shares') – 返回 DataFrame 字典时的分组键;常用 'shares'/'share'/'s''htypes'/'htype'/'h'

  • **kwargs – 透传给底层取数/频率转换的附加参数(如 drop_nanresample_method 等)。 详细可选值与语义见文档「历史数据获取 get_history_data」及 infer_data_types 说明。

返回:

  • HistoryPanel – 当 as_data_frame 为 False 时,返回包含所有请求数据的 HistoryPanel 对象。

  • dict of pandas.DataFrame – 当 as_data_frame 为 True 时,返回按 group_by 分组的 DataFrame 字典。

示例

>>> import qteasy as qt
# 给出历史数据类型和证券代码,起止时间,可以获取该时间段内该股票的历史数据
>>> qt.get_history_data(htype_names='open, high, low, close, vol', shares='000001.SZ', start='20191225', end='20200110')
{'000001.SZ':
             open   high    low  close         vol
2019-12-25  16.45  16.56  16.24  16.30   414917.98
2019-12-26  16.34  16.48  16.32  16.47   372033.86
2019-12-27  16.53  16.93  16.43  16.63  1042574.72
2019-12-30  16.46  16.63  16.10  16.57   976970.31
2019-12-31  16.57  16.63  16.31  16.45   704442.25
2020-01-02  16.65  16.95  16.55  16.87  1530231.87
2020-01-03  16.94  17.31  16.92  17.18  1116194.81
2020-01-06  17.01  17.34  16.91  17.07   862083.50
2020-01-07  17.13  17.28  16.95  17.15   728607.56
2020-01-08  17.00  17.05  16.63  16.66   847824.12
2020-01-09  16.81  16.93  16.53  16.79  1031636.65
2020-01-10  16.79  16.81  16.52  16.69   585548.45
}
>>> # 除了股票的价格数据以外,也可以获取基金、指数的价格数据,如下面的代码获取000300.SH的指数价格
>>> qt.get_history_data(htype_names='close', shares='000300.SH', start='20191225', end='20200105')
{'000300.SH':
              close
2019-12-25  3990.87
2019-12-26  4025.99
2019-12-27  4022.03
2019-12-30  4081.63
2019-12-31  4096.58
2020-01-02  4152.24
2020-01-03  4144.96
}
>>> # 以及基金的净值数据
>>> qt.get_history_data(htype_names='unit_nav, accum_nav', shares='000001.OF', start='20191225', end='20200105')
{'000001.OF':
            unit_nav  accum_nav
2019-12-25     1.086      3.547
2019-12-26     1.096      3.557
2019-12-27     1.091      3.552
2019-12-30     1.100      3.561
2019-12-31     1.105      3.566
2020-01-02     1.123      3.584
2020-01-03     1.127      3.588
}
>>> # 不光价格数据,其他类型的数据也可以同时获取:
>>> qt.get_history_data(htype_names='close, pe, pb', shares='000001.SZ', start='20191225', end='20200105')
{'000001.SZ':
            close       pe      pb
2019-12-25  16.30  12.7454  1.1798
2019-12-26  16.47  12.8784  1.1921
2019-12-27  16.63  13.0035  1.2036
2019-12-30  16.57  12.9566  1.1993
2019-12-31  16.45  12.8627  1.1906
2020-01-02  16.87  13.1911  1.2210
2020-01-03  17.18  13.4335  1.2434
}
>>> # 可以同时混合获取多只股票、指数、多种数据类型的数据,如果某些数据类型缺失,会用NaN填充,注意000001.SZ是股票平安银行,000001.SH是上证指数
>>> qt.get_history_data(htype_names='close, pe, pb, total_mv, eps', shares='000001.SZ, 000001.SH', start='20191225', end='20200105')
{'000001.SZ':
            close       pe      pb      total_mv   eps
2019-12-25  16.30  12.7454  1.1798  3.163165e+07   NaN
2019-12-26  16.47  12.8784  1.1921  3.196155e+07   NaN
2019-12-27  16.63  13.0035  1.2036  3.227204e+07   NaN
2019-12-30  16.57  12.9566  1.1993  3.215561e+07   NaN
2019-12-31  16.45  12.8627  1.1906  3.192274e+07  1.54
2020-01-02  16.87  13.1911  1.2210  3.273778e+07  1.54
2020-01-03  17.18  13.4335  1.2434  3.333937e+07  1.54,
'000001.SH':
              close     pe    pb      total_mv  eps
2019-12-25  2981.88  13.74  1.38  3.987686e+13  NaN
2019-12-26  3007.35  13.85  1.39  4.020871e+13  NaN
2019-12-27  3005.04  13.85  1.39  4.019086e+13  NaN
2019-12-30  3040.02  14.00  1.40  4.064796e+13  NaN
2019-12-31  3050.12  14.05  1.41  4.079249e+13  NaN
2020-01-02  3085.20  14.22  1.42  4.128453e+13  NaN
2020-01-03  3083.79  14.22  1.42  4.127933e+13  NaN
}
>>> # 通过设置freq参数,可以获取不同频率的K线数据,如设置freq='H'可以获取1小时频率的数据
>>> qt.get_history_data(htype_names='open:b, high:b, low:b, close:b', shares='000001.SZ', start='20191229', end='20200106', freq='H', asset_type='E')
 {'000001.SZ':
                           open        high         low       close
2019-12-30 10:00:00  1796.92174  1796.92174  1796.92174  1796.92174
2019-12-30 11:00:00  1790.37160  1800.19681  1758.71259  1786.00484
2019-12-30 14:00:00  1811.11371  1813.29709  1795.83005  1806.74695
2019-12-30 15:00:00  1805.65526  1808.93033  1793.64667  1808.93033
2019-12-31 10:00:00  1808.93033  1808.93033  1808.93033  1808.93033
2019-12-31 11:00:00  1806.74695  1806.74695  1780.54639  1788.18822
2019-12-31 14:00:00  1786.00484  1788.18822  1781.63808  1786.00484
2019-12-31 15:00:00  1786.00484  1796.92174  1783.82146  1795.83005
2020-01-02 10:00:00  1817.66385  1817.66385  1817.66385  1817.66385
2020-01-02 11:00:00  1819.84723  1848.23117  1807.83864  1840.58934
2020-01-02 14:00:00  1842.77272  1847.13948  1828.58075  1843.86441
2020-01-02 15:00:00  1843.86441  1844.95610  1836.22258  1841.68103
2020-01-03 10:00:00  1849.32286  1849.32286  1849.32286  1849.32286
2020-01-03 11:00:00  1849.32286  1879.89018  1849.32286  1877.70680
2020-01-03 14:00:00  1863.51483  1889.71539  1863.51483  1884.25694
2020-01-03 15:00:00  1884.25694  1884.25694  1872.24835  1875.52342
}
>>> # 可以设置b_days_only参数来将价格填充到非交易日,形成完整的日期序列
>>> qt.get_history_data(htype_names='open, high, low, close, vol', shares='000001.SZ', start='20191225', end='20200105', b_days_only=False)
{'000001.SZ':
              open   high    low  close         vol
 2019-12-25  16.45  16.56  16.24  16.30   414917.98
 2019-12-26  16.34  16.48  16.32  16.47   372033.86
 2019-12-27  16.53  16.93  16.43  16.63  1042574.72
 2019-12-28  16.53  16.93  16.43  16.63  1042574.72
 2019-12-29  16.53  16.93  16.43  16.63  1042574.72
 2019-12-30  16.46  16.63  16.10  16.57   976970.31
 2019-12-31  16.57  16.63  16.31  16.45   704442.25
 2020-01-01  16.57  16.63  16.31  16.45   704442.25
 2020-01-02  16.65  16.95  16.55  16.87  1530231.87
 2020-01-03  16.94  17.31  16.92  17.18  1116194.81
 2020-01-04  16.94  17.31  16.92  17.18  1116194.81
 2020-01-05  16.94  17.31  16.92  17.18  1116194.81
 }
>>> # 使用特殊的htypes,可以获取特定的数据,如指数权重数据,下面的代码获取000001.SZ在HS300指数重的权重数据,单位为百分比
>>> qt.get_history_data(htype_names='wt_id:000300.SH', shares='000001.SZ, 000002.SZ', start='20191225', end='20200105')
{'000001.SZ':
            wt_idx:000300.SH
2020-01-02        1.1714
2020-01-03        1.1714,
'000002.SZ':
            wt_idx:000300.SH
2020-01-02        1.3595
2020-01-03        1.3595
}
qteasy.stack_dataframes(dfs: Union[list, dict], dataframe_as: str = 'shares', shares: Optional[Iterable] = None, htypes: Optional[Iterable] = None, fill_value: Optional[Any] = None)[源代码]

将多个 DataFrame 组合为一个 HistoryPanel

参数:
  • dfs (list of pandas.DataFrame or dict of pandas.DataFrame) – 待堆叠的数据表;list 时通常需配合 shares/htypes 显式给出轴标签, dict 时可用键作为默认标签来源。

  • dataframe_as ({'shares', 'htypes'}, default 'shares') – 'shares' 表示每个 DataFrame 对应一个标的(列为 htype);'htypes' 表示 每个 DataFrame 对应一种数据类型(列为 share)。

  • shares (str or list of str, optional) – 输出面板在 dataframe_as='shares' 时的层标签;可为逗号分隔字符串或列表。

  • htypes (str or list of str, optional) – 输出面板在 dataframe_as='htypes' 时的列标签;可为逗号分隔字符串或列表。

  • fill_value (int or float, optional) – 对齐缺失位置时使用的填充值;默认 NaN

返回:

一个由多个单index的数据框组成的HistoryPanel对象

返回类型:

HistoryPanel

示例

>>> df1 = pd.DataFrame([[1, 2, 3], [4, 5, 6]], index=['20210101', '20210102'], columns=['open', 'close', 'low'])
>>> df2 = pd.DataFrame([[7, 8, 9], [10, 11, 12]], index=['20210101', '20210102'], columns=['open', 'close', 'low'])
>>> df3 = pd.DataFrame([[13, 14, 15], [16, 17, 18]], index=['20210101', '20210102'], columns=['open', 'close', 'low'])
>>> dataframes = [df1, df2, df3]
>>> hp = stack_dataframes(dataframes, dataframe_as='shares', shares='000001.SZ, 000002.SZ, 000003.SZ')
>>> hp
share 0, label: 000001.SZ
         open  close   low
20210101  1.0    2.0   3.0
20210102  4.0    5.0   6.0
share 1, label: 000002.SZ
          open  close   low
20210101   7.0    8.0   9.0
20210102  10.0   11.0  12.0
share 2, label: 000003.SZ
          open  close   low
20210101  13.0   14.0  15.0
20210102  16.0   17.0  18.0

研究与正式回测的边界 (扩展阅读)

HistoryPanel 上的 cum_returnportfolioplot 等面向**探索与粗验**;正式回测 (交割、费用、信号类型、防未来函数的数据窗口等)仍由 Strategy / Operator / Backtester 负责。推荐读者在阅读本 API 页的同时,结合: