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 頁的同時,結合: