4. HistoryPanelクラス
履歴データクラス HistoryPanel:
HistoryPanel データ構造とスライス
HistoryPanel は本質的に 3 次元の numpy.ndarray であり、3 つの軸は以下を表します。
軸 0 / レベル: 機器の寸法;各レベルは株式または指数に対応し、ラベル リストは
sharesです。軸 1 / 行: 時間ディメンション;各行は時点に対応し、ラベル リストは
hdatesです。軸 2 / 列: 履歴データ型のディメンション。各列はデータ型に対応しており、ラベルのリストは
htypesです。
これら 3 つの軸ラベルを使用すると、角括弧を使用して HistoryPanel を柔軟にスライスできます``[]``. The basic rule is [htype_slicer, share_slicer, date_slicer]; when dimensions are omitted, the single-segment form (e.g., hp['close']) still returns a sub-HistoryPanel (with axis labels). For a raw matrix, use .values / .to_numpy()。
時間軸 (3 番目の軸) も以下をサポートしています。 pandas.Timestamp, a list of time labels, a 1D bool list of length L = len(hdates), or a 1D numpybool array; the read-only property hp.loc[key]`⟦ CODE11⟧`hp[:, :, key]. A grid-level (M, L, N) boolean mask is not part of the loc / third-axis indexing semantics; use :meth:`~qteasy.HistoryPanel.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 では、複数の機器、複数の時点、および複数のデータ型にわたる履歴データを一元管理するために使用される 3 次元データ コンテナーです。
- HistoryPanel は本質的に 3 次元の
numpy.ndarrayであり、3 つの軸は商品 (株) と時間を表します。 (hdates) と履歴データ型 (htypes) をサポートし、任意の軸に沿った柔軟なスライスと再ラベル付け、および相互変換をサポートします。
- pandas DataFrame、get_history_data および視覚化スタックのデータ コンテナーとして機能します
コアブリッジ (例:
HistoryPanel.plot()andqt.candleの間)。
インデックス作成と配列のエクスポート: ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧⟦コード15⟧⟦コード16⟧⟦コード17⟧⟦コード18⟧⟦コード19⟧⟦コード20⟧⟦コード21⟧⟦コード22⟧⟦コード23⟧⟦コード24⟧。
人間工学指向の API: 有効な Python 識別子であり、 ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧ ⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧)。ユーザー ドキュメント: Sphinx HistoryPanel ページおよびチュートリアル「HistoryPanel を使用した履歴データの操作と分析」 (§6 および §6.1)。
より詳細な構造の説明 (軸ラベル、スライス例、ラベル管理など) については、ドキュメント「HistoryPanel クラス」の関連セクションを参照してください。
- __eq__(other: Any) Any[ソース]
要素ごとの
self == other; unsupported types returnNotImplemented。- パラメータ:
other (Any) -- 右オペランド。
- 戻り値:
boolarray when comparable; otherwiseNotImplemented。- 戻り値の型:
numpy.ndarray or NotImplemented
- __ge__(other: Any) ndarray[ソース]
selfandotherusinggefrom theoperatormodule; returns anumpy.ndarraywith dtypeboolの要素ごとの比較と同等です (サブパネル)。- パラメータ:
other (Any) -- 右オペランド。セマンティクスは
__lt__()と同じです。- 戻り値:
ブール値の結果配列。
- 戻り値の型:
numpy.ndarray
- __getattr__(name: str) Any[ソース]
有効な識別子の列名を
self[name](読み取り専用) として解決します。非識別子または不明な列名の場合は、括弧インデックスを使用します。列の割り当てには、引き続き
hp['col'] = ...を使用します。これはパンダの属性ベースの書き込みパスと一致しません。- パラメータ:
name (str) -- 属性名。
htypes列 (空ではないパネル) に対応するには、有効な Python 識別子である必要があります。- 戻り値:
self[name]; on an empty panel, delegates to__getitem__と同一のサブパネルで、空のサブパネルを返します。- 戻り値の型:
- 例外:
AttributeError -- 無効な識別子、または現在のパネルに存在しない列名 (英語では括弧インデックスの使用を要求)。
メモ
既存のメソッド名/記述子 (例:
where,values) take precedence over column names: columns with the same name must still be accessed ashp['where']and the like. Non-identifier column names (e.g.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 / share / hdates の 3 つの軸に沿ってスライスし、正しい軸ラベルを持つサブ``HistoryPanel`` を返します。
最初のスライスはデータ型 (htypes)、2 番目は商品 (shares)、3 番目は時間 (hdates) です。省略した場合は、その軸がすべてを選択します。裸の
ndarray, usesub.valuesorsub.to_numpy(). A subpanel’svaluesmay share memory with the parent panel (NumPy view rules); if you need an independent copy, usesubpanel(..., copy=True)or ``sub.copy()``が必要な場合。__setitem__, the entirevaluesblock of the parent panel will be replaced: by default, a subpanel withcopy=Falsewill not show the new column name, and itsvaluesmay still point to the old array before the column expansion; the sub-object obtained bysubpanel(copy=True)を介して 親オブジェクト に新しい列を追加する場合は影響を受けません。親パネルの既存の列を**上書き**すると、サブビューと共有されるスライスされたデータが親バッファーとともに更新されます(それが依然として同じ基礎となるブロック上のビューである限り)。空のパネルの場合 (
is_empty), indexing with any key returns an emptyHistoryPanel)。メモ
時間軸(3番目のセグメント) `⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧` (boolean dtype) with length equal to ``row_count``; consistent with the ``key`` accepted by :attr:`loc`. Grid-level ``(M, L, N)`` boolean arrays are **not used as third-axis indices; please use
どこ()。- パラメータ:
keys (list, tuple, slice, str, int or None) -- スライスキー; 3 タプル
(htypes, shares, hdates)は過去の動作と一致しています。- 戻り値:
サブパネル。行列を取得するには、その
.values/.to_numpy()を使用します。- 戻り値の型:
サンプル
>>> 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[ソース]
selfandotherusinggtfrom theoperatormodule; returns anumpy.ndarraywith dtypeboolの要素ごとの比較と同等です (サブパネル)。- パラメータ:
other (Any) -- 右オペランド。セマンティクスは
__lt__()と同じです。- 戻り値:
ブール値の結果配列。
- 戻り値の型:
numpy.ndarray
- __le__(other: Any) ndarray[ソース]
selfandotherusinglefrom theoperatormodule; returns anumpy.ndarraywith dtypeboolの要素ごとの比較と同等です (サブパネル)。- パラメータ:
other (Any) -- 右オペランド。セマンティクスは
__lt__()と同じです。- 戻り値:
ブール値の結果配列。
- 戻り値の型:
numpy.ndarray
- __lt__(other: Any) ndarray[ソース]
selfandotherusingltfrom theoperatormodule; returns anumpy.ndarraywith dtypeboolの要素ごとの比較と同等です (サブパネル)。- パラメータ:
other (Any) -- スカラー、ブロードキャスト可能な
ndarray, or anotherHistoryPanel(整列ルールを満たさなければなりません)。- 戻り値:
ブール値の結果配列。
- 戻り値の型:
numpy.ndarray
- 例外:
TypeError -- サポートされていないオペランドの種類 (英語)。
ValueError -- ルール (英語) に従って 2 つのパネルを整列またはブロードキャストできない場合に発生します。
- __ne__(other: Any) Any[ソース]
要素ごとの
self != other; unsupported types returnNotImplemented。- パラメータ:
other (Any) -- 右オペランド。
- 戻り値:
boolarray when comparable; otherwiseNotImplemented。- 戻り値の型:
numpy.ndarray or NotImplemented
- __setitem__(key: Any, value: Any) None[ソース]
列名を指定して列を追加するか、既存の列 (
htypesの 3 番目の軸) を上書きします。ランタイム 空ではない**文字列のみを受け入れます``key``; multi-column batch assignment is provided by later APIs such as ``assign``. ``value`` will be broadcast to ``(share count, time length)`` and persisted as ``float64``; existing column names are **silently overwritten, with semantics aligned with pandas single-column assignment. Appending a new column on the parent panel will replace the entire `⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧⟦コード15⟧⟦コード16⟧⟦コード17⟧⟦コード18⟧`影響を受けません。親が既存の列を**上書き**すると、基礎となるブロックを親と共有するサブビューも親とともに更新されます。
- パラメータ:
key (Any) -- 列名 (htype)。
str; non-strraisesTypeError, and an empty string raisesValueError(英語メッセージ) である必要があります。value (Any) --
np.asarray’d and broadcast to(M, L)(scalar,(M, L),(M, L, 1)などの数値)。
- 戻り値:
このオブジェクトをその場で変更します。何も返しません。
- 戻り値の型:
None
- 例外:
TypeError --
keyis notstr(英語メッセージ) の場合に発生します。ValueError -- パネルが空の場合に発生します (英語メッセージ)。
サンプル
>>> 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)[ソース]
現在の
HistoryPaneldata (already handled uniformly byplot()) に基づいてローソク足チャートをプロットします。メモ
新しいビジュアライゼーションでは、
HistoryPanel.plot()を直接呼び出し、htypes /layout を使用してローソク足や出来高などのチャート タイプを出力するかどうかを制御することをお勧めします。内部的には、このメソッドは視覚化サブモジュールの統合されたエントリ ポイントに委任されます。その動作は
plot()と一貫しており、セマンティック エイリアスとしてのみ存在します。
- property column_count
HistoryPanelの列数または履歴データの数を取得します
- property columns
HistoryPanel の履歴データを表す辞書を返し、履歴データを列インデックスにマッピングします。これにより、株式コードごとのデータの内部スライスが容易になります。
- copy(deep: bool = True) HistoryPanel[ソース]
新しい HistoryPanel オブジェクトをコピーして作成します。
デフォルトで**ディープコピー**を返します。これは、新しいオブジェクトと元のオブジェクトが相互に基礎となる``values`` array; when you need to match NumPy’s view semantics and share underlying data in performance-sensitive scenarios, set ``deep=False``に影響を与えないことを意味します。
- パラメータ:
deep (bool, default True) -- 基礎となる数値配列
valuesをディープコピーするかどうか: - True: ディープコピー。コピーを変更しても元のオブジェクトには影響しません。 - False: 浅いコピー (基礎となる配列を共有します)。コピーを変更すると、元のオブジェクトに同期的に影響します。- 戻り値:
新しくコピーされたオブジェクト。軸ラベル (
shares/hdates/htypes) は元のオブジェクトのラベルと同じです。- 戻り値の型:
サンプル
>>> 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])[ソース]
HistoryPanel の Nan 値は with_value で埋められます
- パラメータ:
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)[ソース]
HistoryPanel の最初の数行をマルチインデックス データフレームの形式で返します。デフォルトは 5 行です。
- パラメータ:
row_count (int, default 5) -- 印刷する行数
- 戻り値:
データフレーム、列として share と htype によってマルチインデックスが付けられ、最初の row_count 行のみ * 、列として 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)[ソース]
HistoryPanel の最後の数行をマルチインデックス データフレームの形式で返します。デフォルトは 5 行です。
- パラメータ:
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 で過去の日付タイムスタンプのリストを取得します。
- head(row_count=5)[ソース]
HistoryPanel の最初の数行を返します (デフォルトは 5 行)
- パラメータ:
row_count (int, default 5) -- 印刷する行数
- 戻り値:
データフレーム、列として share と htype によってマルチインデックスが付けられ、最初の row_count 行のみ * 、列として 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 数値です。戻り値
2 つのシーケンス番号間のすべてのデータを返します。返される型は、すべての share および htypes データを含む HistoryPanel です。
- パラメータ:
start_index (pd.TimeStamp) -- 開始日インデックス
end_index (pd.TimeStamp) -- 終了日インデックス
- 戻り値:
out -- 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)[ソース]
1 つの HistoryPanel オブジェクトを別の HistoryPanel オブジェクトに接続して、新しい HistoryPanel を生成します。
新しい HistoryPanel の行、列、およびレイヤーのラベルは、2 つの元の HistoryPanel の行、列、およびレイヤーのラベルを結合したものです。つまり、新しい HistoryPanel の行、列、およびレイヤーのラベルには、2 つの HistoryPanel オブジェクトの対応するラベルが完全に含まれています。
- パラメータ:
other (HistoryPanel) -- もう一方の HistoryPanel はマージされます
same_shares (bool, Default False) -- 2 つの HP のシェアが同じ場合、時間を節約するためにシェア ディメンションのラベルの結合を省略できます。デフォルトは False です。
same_htypes (bool, Default False) -- 2 つの HP の htypes が同じ場合、時間を節約するために htypes ディメンションのラベルのマージを省略できます。デフォルトは False です。
same_hdates (bool, Default False) -- 2 つの HP の hdate が同じ場合、時間を節約するために hdate ディメンションのラベルの結合を省略できます。デフォルトは 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 と share に基づいてチャート タイプを自動的に選択し、チャートをプロットします。
このメソッドは既存のデータのみを使用し、新しい計算は実行しません。チャートのタイプは、htypes に基づいて内部レジストリによって決定されます (例: OHLC→K ライン、ボリューム→ボリューム、3 つの MACD 列→MACD チャート、それ以外の場合→ライン チャート)。単一楽器および複数楽器のオーバーレイ/スタック レイアウト、matplotlib ベースの静的プロットおよび Plotly ベースのインタラクティブ チャートをサポートします。
- パラメータ:
shares (str or sequence of str, optional) -- プロットに含めるティッカーのサブセット。デフォルトでは、HistoryPanel のすべての共有が使用されます。
layout ({'overlay', 'stack', 'auto'}, default 'auto') -- マルチインストゥルメントレイアウトモード。 'overlay' は同じグループ内でオーバーレイし、'stack' は複数のグループを別々の行に表示します。'auto' の場合、
HP_OVERLAY_GROUP_SHARE_COUNTはその数の楽器に対してのみオーバーレイを使用し、残りにはスタックを使用します。interactive (bool, default False) -- True の場合、Plotly インタラクティブ バックエンドを使用します (plotly と anywidget/ipywidgets のインストールが必要です)。 False の場合、matplotlib 静的バックエンドを使用します。
highlight (dict or str, optional) -- ハイライト設定:
{'condition': 'max'|'min' or a boolean array, 'style': {...}}、または短縮形の 'max' / 'min' を指定できます。plotly_backend_app ({'auto', 'FigureWidget', 'html'}, default 'auto') -- 以下の場合にのみ有効です`⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧`。
max_shares_per_figure (int, default 5) -- 単一のチャートに表示する株の最大数。要求された共有数がこの値を超えると、ページが分割されます。
pageパラメータを使用して、表示するページを選択できます。page (int, default 1) -- 表示するページ番号 (1 から始まる)。シェア数が
max_shares_per_figure,page=1is page 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 ローソク足 メイン チャートを出力すると、上部の OHLC サマリー領域が表示されます。静的チャートの場合、タイムライン上の 最後の バーのサマリーに固定されます。インタラクティブなグラフの場合、最初はそれに一致し、棒をクリックした後にクリックされた棒が更新されます (ユーザーに表示される概要テキストは英語です)。ローソク足のメイン チャートがない場合 (クローズ ラインのみなど)、このサマリー エリアは表示されません。
サンプル
>>> 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_klineK ライン データをフェッチし、オプションで
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
HistoryPanel の日付辞書を返します。このディクショナリは日付を行インデックスにリンクしているため、内部的にはデータをより速くスライスしたりアクセスしたりできます。
- 戻り値:
日付辞書
- 戻り値の型:
dict
- segment(start_date=None, end_date=None)[ソース]
- HistoryPanel の日付セグメントを取得します。start_date と end_date は両方とも日付型データです。戻り値
これにより、2 つの日付間のすべてのデータが返されます。返されるタイプは、すべての share および htypes データを含む HistoryPanel です。
- パラメータ:
start_date (开始日期) --
end_date (结束日期) --
- 戻り値:
out -- 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の各寸法のサイズを取得します
HistoryPanel で株式または資産の種類の数を取得します。
HistoryPanel - 在庫リストのレイヤーラベルを返します
- slice(shares=None, htypes=None)[ソース]
- 株式またはデータ型の HistoryPanel のセグメントを取得します。株式と htypes はリストまたはカンマ区切り文字にすることができます
、取得する株式またはデータの種類を示します。
- パラメータ:
shares (str or list of str) -- 必要な在庫のリスト
htypes (str or list of str) -- 必要なデータ型のリスト
- 戻り値:
out -- 株式のデータと、shares と htypes で指定されたデータ型を含む A 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 オブジェクトには 3 次元データが含まれているため、変換中に htype または share パラメータのいずれかを指定する必要があります
- パラメータ:
htype (str or int,) -- DataFrame を生成する必要があるデータ型スライスを示します。このパラメータが指定された場合、htype に対応するスライスを見つけた後、htype に対応するすべての株式と日付のすべてのデータが DataFrame に変換されます。型が str の場合は htype の名前を示し、型が int の場合は htype が配置されている列番号を表します。
share (str or int,) -- DataFrame を生成する必要がある株式コード スライスを示します。このパラメータが指定された場合、共有に対応するスライスを見つけた後、共有に対応するすべてのデータ型と日付のすべてのデータが DataFrame に変換されます。型が str の場合は株式コードを表し、型が int の場合は共有が配置されているレイヤー番号を表します。
dropna (bool, Default False) -- True の場合、NaN 値を削除します
inf_as_na (bool, Default False) -- True の場合、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 / share / hdates に沿ってサブパネルを選択します。
`⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧`サブパネルは通常、新しい列を自動的に含めることはありません。また、列が追加される前のバッファを引き続き参照する可能性があります。
- パラメータ:
htypes (str, sequence, slice or int, optional) -- 列 (データ型) の選択。セマンティクスは
panel[htypes, ...]の最初のセグメントと同じです。shares (str, sequence, slice or int, optional) -- 楽器レベルの選択。セマンティクスは
panel[:, shares, ...]の 2 番目のセグメントと同じです。hdates (str, sequence, slice or int, optional) -- 時間軸の選択。セマンティクスは
panel[..., hdates]の 3 番目のセグメントと同じです。copy (bool, default True) -- True の場合、スライス結果の配列コピーを作成します。
- 戻り値:
選択した軸サブセットによって形成されるサブパネル。空の入力は空のパネルに対応します。
- 戻り値の型:
メモ
copy=Falsein__getitem__: after the parent__setitem__appends columns, acopy=Falsechild object usually does not include the new columns; for a stable snapshot, keepcopy=True(デフォルト) によるスライスと同様です。
- tail(row_count=5)[ソース]
HistoryPanel の最後の数行を返します。デフォルトは 5 行です。
- パラメータ:
row_count (int, default 5) -- 印刷する行数
- 戻り値:
データフレーム、列として share と htype によってマルチインデックスが付けられ、最後の row_count 行のみ * 、列として 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 を dict に変換します。キーは share または htype、値は対応する
pandas.DataFrameです。- パラメータ:
by (str, default 'share') --
'share'/'shares', split along the share axis: dict keys are stock tickers and values are the correspondingDataFrame; when set to'htype'/'htypes', split along the data-type axis: dict keys are historical data type names and values are the corresponding ``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; usecopy=Trueと同じ形状の ndarray を返します。空のパネルは、形状
(0, 0, 0). When non-empty,copy=Falsehas the same semantics asnumpy.asarray(self.values)and can share memory with the internal buffer. If you later append new columns to the parent object via__setitem__, the parent object will replace the entire underlying buffer; the array previously obtained withcopy=Falseの形状を持つ float 配列を返します。新しい列は**自動的に含まれない**ため、信頼できるスナップショットとみなされなくなります。現在のパネルの。- パラメータ:
copy (bool, default False) -- True の場合、配列のコピーを返します。戻り値を変更しても、このオブジェクトのデータには影響しません。
- 戻り値:
空のパネルの
values;(0, 0, 0)と同じ形状の 3D 配列。- 戻り値の型:
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.]]])
HistoryPanel 内の単一株のすべてのデータ型をデータフレームにスライスします。
このメソッドは、列としての
slice_to_dataframe(share=...). The returned DataFrame uses time as the index and allhtypesの糖衣構文であり、単一銘柄のフルインジケーター分析に適しています。- パラメータ:
share (str or int) -- 株価ティッカーまたはレベルインデックス。セマンティクスは
shareparameter inslice_to_dataframe(share=...)と同じです。- 戻り値:
行インデックスは
hdates, columns arehtypesで、すべての時点におけるこの銘柄のすべての履歴データが含まれています。- 戻り値の型:
pandas.DataFrame
- unstack(by: str = 'share') dict[ソース]
メソッド self.to_df_dict() のエイリアスであるメソッド self.to_df_dict() と同等です。
- パラメータ:
by (str, {'share', 'htype'}, default 'share') -- スタックを解除するかどうかを share または htype で指定します。デフォルトは share です。
- 戻り値:
スタックを解除した後の結果は、キーが share または htype、値が対応する 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
現在のオブジェクトの内部 3D データ バッファを返します (
_valuesと同じ参照)。空でない場合は、同じメモリを指します。
to_numpy(copy=False); modifying the return value will directly modify this object's data. When appending new columns via__setitem__, the internals may replace the entire array; thevaluesheld by subviews (__getitem__/ ``subpanel(copy=False)` ⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧⟦コード15⟧⟦コード16⟧`保管する前に内部に。- 戻り値:
空のパネルの
(level_count, row_count, column_count);Noneを整形します。- 戻り値の型:
numpy.ndarray or None
- HistoryPanel は本質的に 3 次元の
HistoryPanel オブジェクトは、記述統計、ローリング ウィンドウ計算、リターンとリスク メトリックの計算、ローソク足 (K ライン) やテクニカル インジケーターの計算など、一般的に使用される財務データの統計と集計方法を提供します。詳細は以下のとおりです。
基本的な統計と集計
次のメソッドは、HistoryPanel の 3D データに対してパンダのような統計機能を提供します。
- HistoryPanel.describe(by: Optional[str] = 'share', percentiles: tuple = (0.25, 0.5, 0.75), include: str = 'numeric', ddof: int = 1) DataFrame[ソース]
pandas.DataFrame.describe と同様に、HistoryPanel の基本的な記述統計を計算します。
数値データの個数、平均、標準、最小、最大、指定された分位数などの記述統計を、シェア別、履歴データ型 (htype) 別、またはグローバルな観点から計算できます。
- パラメータ:
by ({'share', 'htype', None}, default 'share') -- 統計の観点: - 'share': 列 (htype、stat) を含む MultiIndex に連結された、株式ごとの結果を説明します。 - 'htype': すべての株式および時間にわたる各 htype の分布。 - なし: すべての数値を単一の全体的なサンプル プールとして扱います。
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の場合にのみ有効になります。
- 戻り値:
インデックス/列構造が 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': 各株式の時間軸にわたる平均を計算し、インデックスを株式として、列を htype として持つデータフレームを返します。 - '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[ソース]
シェアまたはデータタイプ (ddof=1) ごとに、HistoryPanel の標準偏差統計を計算します。
- パラメータ:
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
研究とマスク(どこで)
ブロードキャスト可能な条件を bool array with the same shape as values, for use with the mask= parameter of subsequent research APIs (e.g., cumulative return, normalization, portfolio aggregation, etc.). A 2D (M, L) condition will be replicated along the htype axis to (M, L, N) に正規化します。詳細については、メソッド docstring とチュートリアル「HistoryPanel を使用した履歴データの操作と分析」を参照してください。
- HistoryPanel.where(condition: Union[ndarray, Callable[[HistoryPanel], ndarray]]) ndarray[ソース]
Research API の
values, for use by parameters such asmask=と同じ形状の bool マスクに条件をブロードキャストします。このオブジェクトは変更されません。返される配列には、配列のようなオブジェクトを返す
dtype=booland shape(number of shares, time length, number of htypes), consistent withpanel.values. The condition can be an array (broadcastable to the above shape) or acallable(panel)が含まれています。研究マスクは、Backtester での NaN 価格の取り扱いとは無関係です。
0/1のような整数は、NumPy のルールに従って bool に変換されます。**正確に**の形状を持つ配列``(M, L)`` is treated as “each
(share, time)uses the same boolean value for allhtype”. Internally it is first converted to(M, L, 1)and then broadcast to ``(M, L, N)` ⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧⟦コード15⟧⟦コード16⟧`そして放送。- パラメータ:
condition (numpy.ndarray or callable) -- 配列のようなもの: 最初に
np.asarray(..., dtype=bool), then broadcast toself.shape. If it is acallable, callcondition(self)to get an array and then process it. A barestris not accepted and will raiseTypeError(英語)。- 戻り値:
self.shape(a copy; does not share the write buffer with internalvaluesと同じ形状の 3D bool 配列)。- 戻り値の型:
numpy.ndarray
- 例外:
TypeError --
conditionisstr(英語) の場合に発生します。ValueError -- 戻り値を bool 配列に変換できない場合、または
self.shape(英語) にブロードキャストできない場合に発生します。
メモ
⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7 ⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧。
mask=parameters ofcum_return,normalize, andportfoliocan directly use the return value of this method, or any array of the same shape withdtype=bool。その他のシナリオについては、Sphinx HistoryPanel API のチュートリアル「HistoryPanel を使用して履歴データを操作および分析する」および「調査とマスキング (場所)」サブセクションを参照してください。サンプル
空のパネルは
(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)is semantically equivalent to(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(...)`` directly to the mask= parameter of cum_ret urn() and normalize() (broadcasting rules are the same as where)。
列属性へのアクセス、比較、および loc (pandas との違い)
属性アクセス: 有効な識別子である列名には、次を使用できます。 ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧)同じ名前の列と競合しても、ドット アクセスは依然として API に解決されます。列には括弧を使用します。
比較: `⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7 ⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧`も一致するか、両側が単一列のスライスである必要があります (たとえば、2 つの列を比較する)。
位置インデックス作成: ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧。
算術とコピー:
hp + 1andhp * arrreturn a newHistoryPanelなどの算術演算は、元のオブジェクトを変更しません。hp += 1andhp *= arrなどのインプレース演算子は、元のオブジェクトを明示的に変更します。hp.copy(deep=True)(default) returns a deep copy; modifying the copy does not affect the original object.hp.copy(deep=False)は基礎となる配列を共有します。コピーを変更すると、元のオブジェクトに同期的に影響します。
plot との統合: (M,L) マスクを使用したハイライト
研究シナリオでは、イベント日/シグナル/トレード可能なユニバースは一般に 2D ブール行列 mask_ml with shape (M, L) (number of instruments × time length). HistoryPanel.plot()’s highlight を出力し、この 2D マスクを現在の図内のハイライトされたポイントにマッピングすることができます。
サブセット マスク:
mask_ml.shape == (M_plot, L), whereM_plotis the number of shares selected by thisplot(shares=...)の場合、プロット共有順序で一致します。完全マスク:
mask_ml.shape == (M_all, L)(M_all == len(hp.shares)) の場合、共有名によって現在のプロット サブセットを抽出します (位置によるサイレント トランケーションは禁止されています)。オーバーレイ:
layout='overlay'と 2 つの金融商品がオーバーレイされる場合、デフォルトではプライマリのみが強調表示されます (Plotly の既存の強調表示セマンティクスと一致)。
例::
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(時間軸) に沿ってサブパネルを選択するための読み取り専用インデクサー。⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧`(M,L,N)` boolean conditions, use
どこ()and the subsequentmask=; do not pass grid-level conditions intoloc。- 戻り値:
軽量のプロキシ。
[...]を使用すると、時間軸に沿ってサブパネルを選択します。- 戻り値の型:
_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 は、複数の列を一度に導出または更新できるパンダのような列レベルの DSL を提供します。既存の列または新しく追加された列に基づいて 1 回の呼び出しで新しい要素を構築することをサポートし、新しいパネルを返すか、元のパネル上の所定の位置に列を拡張することをサポートします。
- HistoryPanel.assign(*, inplace: bool = False, **kwargs: Any) HistoryPanel[ソース]
列 (htype) をバッチで導出または更新し、一度に複数の列の追加または上書きをサポートします。
assign()は、パンダのような列レベルの DSL を提供します。一度に複数の新しい列に名前を付け、呼び出し可能または配列/スカラーを介して 1 回の呼び出しでそれらを派生できます。同じ呼び出し内で、後で定義された列は、前に新しく追加された列に依存する可能性があります。このメソッドは、新しいパネルを返すことと、元のパネル上のその場で列を拡張/上書きすることの両方をサポートします。- パラメータ:
inplace (bool, default False) --
True, append/overwrite columns in place on the currentHistoryPaneland return itself; whenFalse, append/overwrite columns on a copy of the current data and return a new ``HistoryPanel``のとき。**kwargs -- 各キーワード引数のキーは新しい列名 (htype) であり、空ではない文字列である必要があります。値は
Callable[[HistoryPanel], np.ndarray], or an array/scalar that can benp.asarray-ed and broadcast to(M, L)になります。
- 戻り値:
inplace=False, return a new panel with the added columns; when ``inplace=True``のときは元のパネルに戻します。- 戻り値の型:
- 例外:
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
断面と正規化: ランク / zscore
rank and zscore are used for “daily cross-sectional ranking/standardization” and “per-share time-series rolling standardization” in lightweight factor research. zscore explicitly distinguishes two semantics via method:
method='cs': 日付を修正し、共有次元に沿って横断的な標準化を実行します。method='ts': fix the share and perform rolling standardization along the time axis (requireswindow)。
- HistoryPanel.rank(by: str, *, axis: str = 'share', method: str = 'average', new_htype: Optional[str] = None) HistoryPanel[ソース]
断面 (共有ディメンション) を日ごとに時間の経過とともにランク付けし、1 つの列を追加して、新しいパネルを返します。
- パラメータ:
by (str) -- ランキングに参加するカラム名(htype)。最初に:meth:_resolve_price_htype によって解析され、
close|bなどの調整されたサフィックス列がサポートされます。axis ({'share'}, default 'share') -- 現在、シェア ディメンションに沿った横断的なランキングのみがサポートされています。
method ({'average', 'min', 'max', 'first', 'dense'}, default 'average') -- 同点の値 (同点) のランクを処理する方法。セマンティクスはパンダ
Series.rank(method=...)と一致します。new_htype (str, optional) -- 出力列名。 None の場合、デフォルトは
rank_{by}になります。
- 戻り値:
ランキング列を追加した後の新しいパネル。元のオブジェクトは変更されません。空のパネルは空のパネルを返します。
- 戻り値の型:
- 例外:
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) を計算し、1 つの列を追加して、新しいパネルを返します。
このメソッドは、
methodパラメーターを介して 2 つの一般的なセマンティクスを明示的に区別します。method='cs'(断面): 各時点を修正し、共有次元に沿って断面正規化を実行します。method='ts'(時系列ローリング): 各シェアを固定し、時間軸に沿ってローリング正規化を実行します。
- パラメータ:
by (str) -- 正規化に参加する列名 (htype)。最初に:meth:_resolve_price_htype によって解析され、
close|bなどの調整されたサフィックス列がサポートされます。method ({'cs', 'ts'}, default 'cs') -- 正規化セマンティクス: クロスセクション (cs) または時系列ローリング (ts)。
window (int, optional) --
method='ts'; must be a positive integer; must be None whenmethod='cs'の場合のローリング ウィンドウの長さ (バーの数)。new_htype (str, optional) -- 出力列名。 None の場合、デフォルトは
cs_z_{by}orts_z_{by}_{window}になります。
- 戻り値:
zscore 列が追加された新しいパネル。元のオブジェクトは変更されません。空のパネルは空のパネルを返します。
- 戻り値の型:
- 例外:
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
一致しない 2 つの HistoryPanel objects (e.g., division, subtraction, correlation, etc.), if their shares or hdates に対して要素ごとの操作を実行する必要がある場合、NumPy ブロードキャストによりサイレントミスアラインメントが発生する可能性があります。したがって、このプロジェクトは明示的なアラインメント エントリ ポイントを提供します。
align_to():sharesandhdatesby labels, supportsjoin='inner'|'outer', and fills missing values with ``fill_value``を整列させます。resample(): 時間軸に沿ってリサンプリングします。曖昧な集計セマンティクスによって引き起こされる「一見成功しているように見えても解釈できない結果」を避けるために、agg=(covering allhtypes) を明示的に指定する必要があります。
- HistoryPanel.align_to(other: HistoryPanel, *, join: str = 'inner', fill_value: float = nan) Tuple[HistoryPanel, HistoryPanel][ソース]
サイレントな位置ずれを避けるために、shares 軸と hdates 軸に沿ったラベルによって 2 つの HistoryPanel を位置合わせします。
このメソッドは、iloc/position による位置合わせを**しません**。軸ラベルを使用して明示的に位置合わせを実行するだけです。位置合わせ後、まったく同じ
shares,hdates, andhtypes; missing grid points are filled withfill_valueを持つ 2 つの新しいパネルが返されます。- パラメータ:
other (HistoryPanel) -- 位置合わせする別のパネル。
join ({'inner', 'outer'}, default 'inner') -- アライメント方法: -
inner: take the intersection of both shares and hdates; -outer: take the union of both shares and hdates. The output order is stable: for the intersection, follow the order ofself; for the union, putselffirst, then append elements that appear inotherbut not inself。fill_value (float, default np.nan) -- 位置合わせ後に欠落している位置の値を埋めます。
- 戻り値:
(self_aligned, other_aligned)を揃えました。- 戻り値の型:
- 例外:
TypeError --
otheris not aHistoryPanel(英語メッセージ) の場合に発生します。ValueError --
joinis invalid, or when the twohtypesが完全に同一ではない場合に発生します (英語のメッセージ)。
サンプル
>>> 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) に沿ってリサンプリングし、新しいパネルを返します。
あいまいな集計セマンティクスによって引き起こされるサイレントな不整合を回避するために、このメソッドでは現在のパネルに
aggto be provided explicitly, and it must cover allhtypesが必要です。- パラメータ:
rule (str) -- pandas 互換のリサンプリング ルール文字列 (
'W','M','5D'など)。agg (dict, required) -- 集計ルールの辞書:
{htype_name: agg_name}, whereagg_namesupports'first'|'last'|'min'|'max'|'sum'|'mean'. Must cover allhtypes。
- 戻り値:
リサンプリング後の新しいパネル。元のオブジェクトは変更されません。空のパネルは空のパネルを返します。
- 戻り値の型:
- 例外:
ValueError --
aggis missing, does not cover all columns, contains unknown column names, the aggregation method is invalid, orruleが無効な場合に発生します (英語のメッセージ付き)。
サンプル
>>> 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はバーの整数です。- パラメータ:
window (int) -- ローリング ウィンドウの長さ。
min_periods (int, optional) -- 有効な観測値の最小数。これより小さい場合、結果は
NaN. Defaults to the same aswindowになります。center (bool, default False) -- 中央に配置されたウィンドウを使用するかどうか。セマンティクスは
pandas.Series.rollingと一致します。by ({'share', 'htype'}, default 'share') -- ローリングのグループ化モードを指定します。 - 'share': 各株の htype ごとに個別にローリングします (最も一般的)。 - 'htype': すべての株式にわたって各 htype を個別にロールします。
- 戻り値:
ローリングウィンドウ統計オブジェクト。 means()、std()、min()、max() などの呼び出しをサポートします。
- 戻り値の型:
サンプル
>>> 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()によって作成され、ウィンドウ パラメーターの固定の組み合わせに対応し、新しい HistoryPanel を返すmean/std/sum/min/max/applyなどのメソッドを提供します。- apply(func: Callable[[ndarray], float], raw: bool = False, **kwargs) HistoryPanel[ソース]
ローリング ウィンドウにカスタム関数を適用します。
- パラメータ:
func (callable) -- ウィンドウ ベクトルを受け取り、スカラーを返すカスタム関数。
raw (bool, default False) --
True, pass anndarrayto func; otherwise pass a ``Series``の場合。**kwargs -- 他のパラメータは func に渡されます。
- 戻り値:
カスタム関数を適用した後のローリング結果パネル。 share/hdates/htypes ラベルは変更されません。
- 戻り値の型:
メモ
pandas と同じ: ウィンドウ内の有効なサンプルの数が
min_periods未満の場合、結果は NaN になります。funcはスカラー数値を返す必要があります。配列または数値以外の型を返すと、パンダでエラーが発生したり、予期しない結果が生成されたりする可能性があります。
サンプル
>>> 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[ソース]
ローリング ウィンドウの最大値を計算し、新しいパネルを返します。
- 戻り値:
ローリング最大結果パネル。ラベルは元のパネルと一致します。
- 戻り値の型:
- mean() HistoryPanel[ソース]
ローリング ウィンドウ平均を計算し、新しいパネルを返します。
- 戻り値:
ラベルが元のパネルと一致する、移動平均結果パネル。
- 戻り値の型:
- min() HistoryPanel[ソース]
ローリング ウィンドウの最小値を計算し、新しいパネルを返します。
- 戻り値:
元のパネルと一貫したラベルが付いたローリング最小結果パネル。
- 戻り値の型:
- std() HistoryPanel[ソース]
ローリング ウィンドウの標準偏差を計算し、新しいパネルを返します。
- 戻り値:
ローリング標準偏差結果パネル。ラベルは元のパネルと一致します。
- 戻り値の型:
- sum() 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) -- 戻り間隔内のバーの数。
as_panel (bool, default False) -- False の場合、DataFrame (index=time、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[ソース]
時間軸に沿って 1 株あたりの累積利益を計算し (研究指向)、新しいパネルを返します。
デフォルトでは、
closecolumn (resolved via_resolve_price_htype(), supportingclose|betc.). The output column name iscumret_<user-provided column name>, consistent withreturns()using theret_<price_htype>命名戦略に基づいて計算されます。 NaN または非正の価格が時間パスに沿って表示される場合、その時点以降の後続の結果はすべて NaN (パス ブレーク) になります。- パラメータ:
htypes (str, sequence of str, optional) -- 計算に参加する列名。
None, only processcloseの場合 (解析後)。method ({'simple', 'log'}, default 'simple') --
simple: from the first valid positive pricet0,p_t/p_{t0}-1;log:log(p_t)-log(p_{t0})。mask (numpy.ndarray, optional) --
where(); と同じブロードキャスト ルール計算前の位置はFalseare treated as missing (NaN) です。
- 戻り値:
shares/hdatesは元のパネルと同じです。累積収益列のみが含まれます。- 戻り値の型:
- 例外:
ValueError --
methodis invalid, columns cannot be parsed,maskcannot be broadcast, or the output column name conflicts with existinghtypesのときに (英語で) 発生します。
サンプル
>>> 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_indexas the denominator; if that time point is excluded bymask, isNaN, or is 0, then the entire time series output for that (share, column) will beNaN. The output column name isnorm_<user-provided column name>の有効な価格が使用されます。- パラメータ:
htypes (str, sequence of str, optional) -- 計算に参加する列。
None, onlycloseの場合 (解析後)。base_index (int, default 0) -- 時間軸上の基本インデックス (0 から開始)。範囲外の場合は
ValueError(英語) を発生させます。mask (numpy.ndarray, optional) --
where()と同じブロードキャスト ルール。
- 戻り値:
元のパネルと同じ
shares/hdates。正規化された列のみが含まれます。- 戻り値の型:
- 例外:
ValueError -- 列を解決できない場合、
maskcannot be broadcast,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[ソース]
複数の株式を株式次元 (リサーチ指向) に沿ってポートフォリオ シリーズに集約し、新しいパネルを返します。
デフォルトは
benchmark_output='none'; ifbenchmarkis set, you can attach benchmark rows withtag_along, or keep only excess-prefixed columns withexcess_only(ポートフォリオからベンチマークを引いたもの、列名の前に「excess」が付きます)。groupsisNone, aggregate the entire panel into one row namednew_share_name. Whengroupsis not empty, the keys are output share labels (in insertion order) and the values are lists of original shares within each group; shares must not overlap across groups. Whenallow_ungrouped='error'の場合、各パネル共有は 1 つのグループにのみ属している必要があります。groupsisNoneandbenchmarkis specified, the benchmark share does not participate in portfolio aggregation (to avoid mixing index and individual-stock weights), and is only used fortag_alongorexcess_only; if no share is available after exclusion (e.g., the panel contains only the benchmark), raise ``ValueError``のとき。maskare consistent withwhere()のブロードキャスト ルール。無効なグリッド点は集計に参加しません。- パラメータ:
htypes (str or sequence of str, default 'close') -- 集計に参加する列名。
_resolve_price_htype()によって解決されました。mode ({'equal', 'weighted'}, default 'equal') -- 均等加重平均、または
weightsと併用される加重平均。weights (numpy.ndarray, optional) --
(M,)or(M, L), aligned with the order ofself.shares; used only when ``mode='weighted'``の形をします。mask (numpy.ndarray, optional) --
where()と同じブロードキャスト ルール。groups (dict, optional) -- グループ名→グループ内の共有タグの一覧を出力します。
benchmark (str, optional) -- ベンチマークシェア。
self.sharesになければなりません。benchmark_output ({'none', 'tag_along', 'excess_only'}, default 'none') -- ベンチマーク出力フォーム。
benchmark, only ``'none'``がない場合は許可されます。new_share_name (str, default 'PORTFOLIO') -- ``groups``がない場合の合成行の共有名。
normalize_weights (bool, default True) -- 重み付けを行う場合、重み付けされた合計 (数値的には「sum(w*x)/sum(w)」と同等) を計算する前に、集計に参加しているメンバーの重みを正規化します。
allow_ungrouped ({'error', 'exclude'}, default 'error') --
groupsが空でない場合、すべてのシェアをカバーする必要があるかどうか。
- 戻り値:
新しいオブジェクト。
hdatesと時間の長さは元のパネルと一致しています。- 戻り値の型:
- 例外:
ValueError -- 無効なパラメーター、パネル内にない共有、重複するグループ、マスクをブロードキャストできないなど (英語)。
- 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) -- ローリング ウィンドウの長さ (バーの数)。
price_htype (str, default 'close') -- 収益の計算に使用される価格タイプ。
method ({'simple', 'log'}, default 'simple') -- 戻り値の計算方法は returns() と一致します。
annualize (bool, default True) -- 年率化するかどうか (sqrt(periods_per_year) を掛ける)。
periods_per_year (int, optional) -- 年換算した場合の年間バー。指定されておらず、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[ソース]
指定されたベンチマーク収益シリーズと比較して、各銘柄のアルファ/ベータなどの指標を計算します。
- パラメータ:
benchmark (Series or DataFrame) -- 基準価格の時系列。インデックスは HistoryPanel.hdates と一致するか、少なくとも重複している必要があります。 DataFrame が提供されている場合、最初の列のみが基準価格として使用されます。
price_htype (str, default 'close') -- 収益の計算に使用される価格タイプ。
method ({'simple', 'log'}, default 'simple') -- 戻り値の計算方法は returns() と一致します。
freq (str, optional) -- 'D'、'W'、'M' など、アルファを年換算するときに年間のバー数を推測するために使用される頻度文字列を返します。
annualize (bool, default True) -- アルファを年換算するかどうか。
- 戻り値:
指数は株式です。列は ['alpha'、'beta'、'r2'、'n_obs'] です。
- 戻り値の型:
pandas.DataFrame
ローソク足とテクニカル指標
プライマリ エントリ ポイント: Research_preset
research_preset is used to quickly assemble a “commonly used column set that can be plotted directly” (e.g., OHLCV + MACD + MA), avoiding implicit indicator computation during plotting. If input columns are missing, it raises an English ValueError は、どの列が欠落しているかを示します。
- HistoryPanel.research_preset(name: str, *, inplace: bool = False) HistoryPanel[ソース]
プリセットに基づいて調査によく使用される列セットをすばやく生成し、結果パネルを返します。
このメソッドは、
HistoryPanelの「最初のエントリ ポイント」として機能することを目的としています。バックテスト セマンティクスを導入することなく、OHLCV と一般的に使用されるテクニカル指標列 (MACD や移動平均など) を直接プロットしたり、さらなる調査のために素早く組み立てます。- パラメータ:
name (str) -- プリセット名。現在サポートされているもの: -
'ohlcv_macd_ma': requires the panel to contain at leastopen/high/low/close/vol, and generatesmacd_12_26_9,macd_signal_12_26_9,macd_hist_12_26_9, andsma_20。inplace (bool, default False) -- True の場合、プリセット列を元のパネルに追加し、元のパネルを返します。 False の場合、追加された列を含む新しいパネルを返します。
- 戻り値:
HistoryPanelafter appending preset columns. Wheninplace=Trueは、元のオブジェクトを返します。- 戻り値の型:
- 例外:
ValueError -- プリセット名が無効な場合、またはプリセットに必要な入力列が欠落している場合に発生します (エラー メッセージは英語です)。
- HistoryPanel.kline
ローソク足テクニカル指標アクセサー。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') -- 入力として使用される 1 次元時系列のデータ型。
shares (list of str, optional) -- 計算する株式のリスト。デフォルトでは、すべての共有が使用されます。
as_panel (bool, default True) -- True の場合、htypes の末尾に出力列が追加された新しい HistoryPanel を返します。 False の場合、MultiIndex 列を含む DataFrame (time × [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)[ソース]
指定された商品、データ型、頻度を指定して、ローカル データ ソースから履歴データを取得し、戦略で直接使用できる構造に組み立てます。
必要なデータ型を指定するには、 ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧、この関数は、HistoryPanel、または計測器/データ型ごとにグループ化された DataFrame の辞書を返します。データ型推論、頻度変換、trade_time_only などの高度な使用方法については、ドキュメント「履歴データの取得 get_history_data」の関連セクションを参照してください。
- パラメータ:
htype_names (str or list of str, optional) -- 取得する履歴データ名のコレクション。カンマ区切りの文字列にすることができます (例:
'open, high, low, close') or a list (e.g.,['open', 'high', 'low', 'close']). If empty, the system will infer available htypes based on parameters such asfreq/asset_type)。htypes (list of DataType, optional, deprecated) -- 履歴データ型オブジェクトのリスト。セマンティクスは
htype_names. Prefer the newhtype_names/data_typesインターフェイスに似ています。data_types (list of DataType, optional) -- フェッチされる履歴データ型のコレクション。正当なデータ型オブジェクトである必要があります。この引数が指定された場合、htype_names は無視されます。それ以外の場合、可能な htype は htype_names 引数に基づいて作成されます。
data_source (DataSource, optional) -- 履歴データへのアクセスが必要なデータ ソース
shares (str or list of str, optional) -- セキュリティコードの収集。カンマ区切りの文字列にすることができます (例:
'000001.SZ, 000002.SZ') or a list (e.g.,['000001.SZ', '000002.SZ'])。symbols (str or list of str, optional) -- セキュリティコードの収集。カンマ区切りの文字列にすることができます (例:
'000001, 000002') or a list (e.g.,['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 が指定されていない場合、テーブル内の最新の行がフェッチされ、行を使用してデータをフェッチする速度は、date を使用する場合よりも大幅に遅くなります。
freq (str, optional) -- 頻度;などの分間隔をサポートします。 ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7 ⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧ (ローソク足など)。
asset_type (str or list of str, optional) -- 資産タイプのフィルター。カンマ区切りの文字列にすることができます (例: ⟦コード0⟧⟦コード1⟧⟦コード2⟧⟦コード3⟧⟦コード4⟧⟦コード5⟧⟦コード6⟧⟦コード7⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧、など
adj (str, optional, deprecated) -- 廃止された調整オプション(
none/n,back/``b`⟦CODE7 ⟧⟦コード8⟧⟦コード9⟧⟦コード10⟧⟦コード11⟧⟦コード12⟧⟦コード13⟧⟦コード14⟧`)。as_data_frame (bool, default True) --
HistoryPanelwhenTrue; returns a dictionary ofDataFramewhen ``False``を返します。group_by (str, default 'shares') -- DataFrame の辞書を返すときのグループ化キー。一般的には
'shares'/'share'/'s'or'htypes'/'htype'/'h'。**kwargs -- 基礎となるデータ取得/周波数変換に渡される追加パラメーター (例:
drop_nan,resample_method, etc.). For detailed available values and semantics, see the documentation “Historical Data Retrieval get_history_data” and theinfer_data_typesメモ)。
- 戻り値:
HistoryPanel --
as_data_frameが False の場合、要求されたすべてのデータを含む HistoryPanel オブジェクトを返します。pandas.DataFrame の辞書 --
as_data_frameis True, returns a dict of DataFrames grouped bygroup_byの場合。
サンプル
>>> 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)[ソース]
複数の
DataFrameobjects into a singleHistoryPanelを組み合わせます。- パラメータ:
dfs (list of pandas.DataFrame or dict of pandas.DataFrame) -- 積み重ねられるテーブル。
list, you usually need to explicitly provide axis labels withshares/htypes; when adictの場合、そのキーはデフォルトのラベル ソースとして使用できます。dataframe_as ({'shares', 'htypes'}, default 'shares') --
'shares'means eachDataFramecorresponds to one instrument (columns are htypes);'htypes'means eachDataFrameは 1 つのデータ型に対応します (列は共有です)。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``。
- 戻り値:
複数の単一インデックス データ ボックスで構成される 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_return, portfolio, plot, etc. are geared toward exploration and quick checks; formal backtesting (settlement, fees, signal types, data windows that avoid look-ahead functions, etc.) is still handled by Strategy / Operator / Backtester で。読者は、この API ページと合わせて読むことをお勧めします。
チュートリアル Using HistoryPanel to manipulate and analyze historical data §9 (リサーチ →
FactorSorter/Operator)、§10 (マルチソース データ パネリング)、§11 (pandas / statsmodels へのエクスポート);設計ノート:doc:HistoryPanel and the optional FactorResearch layer <../design/10-historypanel-factor-research-layer> (独立因子統計モジュールを追加するかどうかに関する評価結論)。