Upload folder using huggingface_hub (part 2)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/dataset/utils.py +142 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/dataset/weight.py +27 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/filter.py +375 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/inst_processor.py +22 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/ops.py +1681 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/pit.py +72 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/__init__.py +6 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/file_storage.py +379 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/storage.py +494 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/log.py +262 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/__init__.py +8 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/base.py +110 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/__init__.py +0 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/ensemble.py +132 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/group.py +115 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/__init__.py +0 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/base.py +45 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/__init__.py +7 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/dataset.py +77 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/model.py +75 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/task.py +56 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/__init__.py +14 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/base.py +147 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/poet.py +83 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/shrink.py +259 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/structured.py +94 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/trainer.py +619 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/utils.py +26 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/__init__.py +8 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/aux_info.py +43 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/__init__.py +0 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/backtest.py +384 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/naive_config_parser.py +106 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/train_onpolicy.py +269 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/utils.py +29 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/__init__.py +8 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/base.py +65 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/integration.py +82 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/native.py +234 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/pickle_styled.py +296 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/interpreter.py +141 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/__init__.py +38 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/interpreter.py +257 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/network.py +140 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/policy.py +237 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/reward.py +99 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/simulator_qlib.py +141 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/simulator_simple.py +362 -0
- Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/state.py +101 -0
.gitattributes
CHANGED
|
@@ -60,3 +60,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/expanding.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 62 |
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/rolling.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
| 60 |
*.webm filter=lfs diff=lfs merge=lfs -text
|
| 61 |
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/expanding.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 62 |
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/rolling.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/expanding.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
|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
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from typing import Union, List, TYPE_CHECKING
|
| 6 |
+
from qlib.utils import init_instance_by_config
|
| 7 |
+
|
| 8 |
+
if TYPE_CHECKING:
|
| 9 |
+
from qlib.data.dataset import DataHandler
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def get_level_index(df: pd.DataFrame, level: Union[str, int]) -> int:
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
get the level index of `df` given `level`
|
| 16 |
+
|
| 17 |
+
Parameters
|
| 18 |
+
----------
|
| 19 |
+
df : pd.DataFrame
|
| 20 |
+
data
|
| 21 |
+
level : Union[str, int]
|
| 22 |
+
index level
|
| 23 |
+
|
| 24 |
+
Returns
|
| 25 |
+
-------
|
| 26 |
+
int:
|
| 27 |
+
The level index in the multiple index
|
| 28 |
+
"""
|
| 29 |
+
if isinstance(level, str):
|
| 30 |
+
try:
|
| 31 |
+
return df.index.names.index(level)
|
| 32 |
+
except (AttributeError, ValueError):
|
| 33 |
+
# NOTE: If level index is not given in the data, the default level index will be ('datetime', 'instrument')
|
| 34 |
+
return ("datetime", "instrument").index(level)
|
| 35 |
+
elif isinstance(level, int):
|
| 36 |
+
return level
|
| 37 |
+
else:
|
| 38 |
+
raise NotImplementedError(f"This type of input is not supported")
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def fetch_df_by_index(
|
| 42 |
+
df: pd.DataFrame,
|
| 43 |
+
selector: Union[pd.Timestamp, slice, str, list, pd.Index],
|
| 44 |
+
level: Union[str, int],
|
| 45 |
+
fetch_orig=True,
|
| 46 |
+
) -> pd.DataFrame:
|
| 47 |
+
"""
|
| 48 |
+
fetch data from `data` with `selector` and `level`
|
| 49 |
+
|
| 50 |
+
selector are assumed to be well processed.
|
| 51 |
+
`fetch_df_by_index` is only responsible for get the right level
|
| 52 |
+
|
| 53 |
+
Parameters
|
| 54 |
+
----------
|
| 55 |
+
selector : Union[pd.Timestamp, slice, str, list]
|
| 56 |
+
selector
|
| 57 |
+
level : Union[int, str]
|
| 58 |
+
the level to use the selector
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
Data of the given index.
|
| 63 |
+
"""
|
| 64 |
+
# level = None -> use selector directly
|
| 65 |
+
if level is None or isinstance(selector, pd.MultiIndex):
|
| 66 |
+
return df.loc(axis=0)[selector]
|
| 67 |
+
# Try to get the right index
|
| 68 |
+
idx_slc = (selector, slice(None, None))
|
| 69 |
+
if get_level_index(df, level) == 1:
|
| 70 |
+
idx_slc = idx_slc[1], idx_slc[0]
|
| 71 |
+
if fetch_orig:
|
| 72 |
+
for slc in idx_slc:
|
| 73 |
+
if slc != slice(None, None):
|
| 74 |
+
return df.loc[pd.IndexSlice[idx_slc],] # noqa: E231
|
| 75 |
+
else: # pylint: disable=W0120
|
| 76 |
+
return df
|
| 77 |
+
else:
|
| 78 |
+
return df.loc[pd.IndexSlice[idx_slc],] # noqa: E231
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def fetch_df_by_col(df: pd.DataFrame, col_set: Union[str, List[str]]) -> pd.DataFrame:
|
| 82 |
+
from .handler import DataHandler # pylint: disable=C0415
|
| 83 |
+
|
| 84 |
+
if not isinstance(df.columns, pd.MultiIndex) or col_set == DataHandler.CS_RAW:
|
| 85 |
+
return df
|
| 86 |
+
elif col_set == DataHandler.CS_ALL:
|
| 87 |
+
return df.droplevel(axis=1, level=0)
|
| 88 |
+
else:
|
| 89 |
+
return df.loc(axis=1)[col_set]
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def convert_index_format(df: Union[pd.DataFrame, pd.Series], level: str = "datetime") -> Union[pd.DataFrame, pd.Series]:
|
| 93 |
+
"""
|
| 94 |
+
Convert the format of df.MultiIndex according to the following rules:
|
| 95 |
+
- If `level` is the first level of df.MultiIndex, do nothing
|
| 96 |
+
- If `level` is the second level of df.MultiIndex, swap the level of index.
|
| 97 |
+
|
| 98 |
+
NOTE:
|
| 99 |
+
the number of levels of df.MultiIndex should be 2
|
| 100 |
+
|
| 101 |
+
Parameters
|
| 102 |
+
----------
|
| 103 |
+
df : Union[pd.DataFrame, pd.Series]
|
| 104 |
+
raw DataFrame/Series
|
| 105 |
+
level : str, optional
|
| 106 |
+
the level that will be converted to the first one, by default "datetime"
|
| 107 |
+
|
| 108 |
+
Returns
|
| 109 |
+
-------
|
| 110 |
+
Union[pd.DataFrame, pd.Series]
|
| 111 |
+
converted DataFrame/Series
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
if get_level_index(df, level=level) == 1:
|
| 115 |
+
df = df.swaplevel().sort_index()
|
| 116 |
+
return df
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def init_task_handler(task: dict) -> DataHandler:
|
| 120 |
+
"""
|
| 121 |
+
initialize the handler part of the task **inplace**
|
| 122 |
+
|
| 123 |
+
Parameters
|
| 124 |
+
----------
|
| 125 |
+
task : dict
|
| 126 |
+
the task to be handled
|
| 127 |
+
|
| 128 |
+
Returns
|
| 129 |
+
-------
|
| 130 |
+
Union[DataHandler, None]:
|
| 131 |
+
returns
|
| 132 |
+
"""
|
| 133 |
+
# avoid recursive import
|
| 134 |
+
from .handler import DataHandler # pylint: disable=C0415
|
| 135 |
+
|
| 136 |
+
h_conf = task["dataset"]["kwargs"].get("handler")
|
| 137 |
+
if h_conf is not None:
|
| 138 |
+
handler = init_instance_by_config(h_conf, accept_types=DataHandler)
|
| 139 |
+
task["dataset"]["kwargs"]["handler"] = handler
|
| 140 |
+
return handler
|
| 141 |
+
else:
|
| 142 |
+
raise ValueError("The task does not contains a handler part.")
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/dataset/weight.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Reweighter:
|
| 6 |
+
def __init__(self, *args, **kwargs):
|
| 7 |
+
"""
|
| 8 |
+
To initialize the Reweighter, users should provide specific methods to let reweighter do the reweighting (such as sample-wise, rule-based).
|
| 9 |
+
"""
|
| 10 |
+
raise NotImplementedError()
|
| 11 |
+
|
| 12 |
+
def reweight(self, data: object) -> object:
|
| 13 |
+
"""
|
| 14 |
+
Get weights for data
|
| 15 |
+
|
| 16 |
+
Parameters
|
| 17 |
+
----------
|
| 18 |
+
data : object
|
| 19 |
+
The input data.
|
| 20 |
+
The first dimension is the index of samples
|
| 21 |
+
|
| 22 |
+
Returns
|
| 23 |
+
-------
|
| 24 |
+
object:
|
| 25 |
+
the weights info for the data
|
| 26 |
+
"""
|
| 27 |
+
raise NotImplementedError(f"This type of input is not supported")
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/filter.py
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
from abc import abstractmethod
|
| 6 |
+
|
| 7 |
+
import re
|
| 8 |
+
import pandas as pd
|
| 9 |
+
import numpy as np
|
| 10 |
+
import abc
|
| 11 |
+
|
| 12 |
+
from .data import Cal, DatasetD
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class BaseDFilter(abc.ABC):
|
| 16 |
+
"""Dynamic Instruments Filter Abstract class
|
| 17 |
+
|
| 18 |
+
Users can override this class to construct their own filter
|
| 19 |
+
|
| 20 |
+
Override __init__ to input filter regulations
|
| 21 |
+
|
| 22 |
+
Override filter_main to use the regulations to filter instruments
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
def __init__(self):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
@staticmethod
|
| 29 |
+
def from_config(config):
|
| 30 |
+
"""Construct an instance from config dict.
|
| 31 |
+
|
| 32 |
+
Parameters
|
| 33 |
+
----------
|
| 34 |
+
config : dict
|
| 35 |
+
dict of config parameters.
|
| 36 |
+
"""
|
| 37 |
+
raise NotImplementedError("Subclass of BaseDFilter must reimplement `from_config` method")
|
| 38 |
+
|
| 39 |
+
@abstractmethod
|
| 40 |
+
def to_config(self):
|
| 41 |
+
"""Construct an instance from config dict.
|
| 42 |
+
|
| 43 |
+
Returns
|
| 44 |
+
----------
|
| 45 |
+
dict
|
| 46 |
+
return the dict of config parameters.
|
| 47 |
+
"""
|
| 48 |
+
raise NotImplementedError("Subclass of BaseDFilter must reimplement `to_config` method")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class SeriesDFilter(BaseDFilter):
|
| 52 |
+
"""Dynamic Instruments Filter Abstract class to filter a series of certain features
|
| 53 |
+
|
| 54 |
+
Filters should provide parameters:
|
| 55 |
+
|
| 56 |
+
- filter start time
|
| 57 |
+
- filter end time
|
| 58 |
+
- filter rule
|
| 59 |
+
|
| 60 |
+
Override __init__ to assign a certain rule to filter the series.
|
| 61 |
+
|
| 62 |
+
Override _getFilterSeries to use the rule to filter the series and get a dict of {inst => series}, or override filter_main for more advanced series filter rule
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
def __init__(self, fstart_time=None, fend_time=None, keep=False):
|
| 66 |
+
"""Init function for filter base class.
|
| 67 |
+
Filter a set of instruments based on a certain rule within a certain period assigned by fstart_time and fend_time.
|
| 68 |
+
|
| 69 |
+
Parameters
|
| 70 |
+
----------
|
| 71 |
+
fstart_time: str
|
| 72 |
+
the time for the filter rule to start filter the instruments.
|
| 73 |
+
fend_time: str
|
| 74 |
+
the time for the filter rule to stop filter the instruments.
|
| 75 |
+
keep: bool
|
| 76 |
+
whether to keep the instruments of which features don't exist in the filter time span.
|
| 77 |
+
"""
|
| 78 |
+
super(SeriesDFilter, self).__init__()
|
| 79 |
+
self.filter_start_time = pd.Timestamp(fstart_time) if fstart_time else None
|
| 80 |
+
self.filter_end_time = pd.Timestamp(fend_time) if fend_time else None
|
| 81 |
+
self.keep = keep
|
| 82 |
+
|
| 83 |
+
def _getTimeBound(self, instruments):
|
| 84 |
+
"""Get time bound for all instruments.
|
| 85 |
+
|
| 86 |
+
Parameters
|
| 87 |
+
----------
|
| 88 |
+
instruments: dict
|
| 89 |
+
the dict of instruments in the form {instrument_name => list of timestamp tuple}.
|
| 90 |
+
|
| 91 |
+
Returns
|
| 92 |
+
----------
|
| 93 |
+
pd.Timestamp, pd.Timestamp
|
| 94 |
+
the lower time bound and upper time bound of all the instruments.
|
| 95 |
+
"""
|
| 96 |
+
trange = Cal.calendar(freq=self.filter_freq)
|
| 97 |
+
ubound, lbound = trange[0], trange[-1]
|
| 98 |
+
for _, timestamp in instruments.items():
|
| 99 |
+
if timestamp:
|
| 100 |
+
lbound = timestamp[0][0] if timestamp[0][0] < lbound else lbound
|
| 101 |
+
ubound = timestamp[-1][-1] if timestamp[-1][-1] > ubound else ubound
|
| 102 |
+
return lbound, ubound
|
| 103 |
+
|
| 104 |
+
def _toSeries(self, time_range, target_timestamp):
|
| 105 |
+
"""Convert the target timestamp to a pandas series of bool value within a time range.
|
| 106 |
+
Make the time inside the target_timestamp range TRUE, others FALSE.
|
| 107 |
+
|
| 108 |
+
Parameters
|
| 109 |
+
----------
|
| 110 |
+
time_range : D.calendar
|
| 111 |
+
the time range of the instruments.
|
| 112 |
+
target_timestamp : list
|
| 113 |
+
the list of tuple (timestamp, timestamp).
|
| 114 |
+
|
| 115 |
+
Returns
|
| 116 |
+
----------
|
| 117 |
+
pd.Series
|
| 118 |
+
the series of bool value for an instrument.
|
| 119 |
+
"""
|
| 120 |
+
# Construct a whole dict of {date => bool}
|
| 121 |
+
timestamp_series = {timestamp: False for timestamp in time_range}
|
| 122 |
+
# Convert to pd.Series
|
| 123 |
+
timestamp_series = pd.Series(timestamp_series)
|
| 124 |
+
# Fill the date within target_timestamp with TRUE
|
| 125 |
+
for start, end in target_timestamp:
|
| 126 |
+
timestamp_series[Cal.calendar(start_time=start, end_time=end, freq=self.filter_freq)] = True
|
| 127 |
+
return timestamp_series
|
| 128 |
+
|
| 129 |
+
def _filterSeries(self, timestamp_series, filter_series):
|
| 130 |
+
"""Filter the timestamp series with filter series by using element-wise AND operation of the two series.
|
| 131 |
+
|
| 132 |
+
Parameters
|
| 133 |
+
----------
|
| 134 |
+
timestamp_series : pd.Series
|
| 135 |
+
the series of bool value indicating existing time.
|
| 136 |
+
filter_series : pd.Series
|
| 137 |
+
the series of bool value indicating filter feature.
|
| 138 |
+
|
| 139 |
+
Returns
|
| 140 |
+
----------
|
| 141 |
+
pd.Series
|
| 142 |
+
the series of bool value indicating whether the date satisfies the filter condition and exists in target timestamp.
|
| 143 |
+
"""
|
| 144 |
+
fstart, fend = list(filter_series.keys())[0], list(filter_series.keys())[-1]
|
| 145 |
+
filter_series = filter_series.astype("bool") # Make sure the filter_series is boolean
|
| 146 |
+
timestamp_series[fstart:fend] = timestamp_series[fstart:fend] & filter_series
|
| 147 |
+
return timestamp_series
|
| 148 |
+
|
| 149 |
+
def _toTimestamp(self, timestamp_series):
|
| 150 |
+
"""Convert the timestamp series to a list of tuple (timestamp, timestamp) indicating a continuous range of TRUE.
|
| 151 |
+
|
| 152 |
+
Parameters
|
| 153 |
+
----------
|
| 154 |
+
timestamp_series: pd.Series
|
| 155 |
+
the series of bool value after being filtered.
|
| 156 |
+
|
| 157 |
+
Returns
|
| 158 |
+
----------
|
| 159 |
+
list
|
| 160 |
+
the list of tuple (timestamp, timestamp).
|
| 161 |
+
"""
|
| 162 |
+
# sort the timestamp_series according to the timestamps
|
| 163 |
+
timestamp_series.sort_index()
|
| 164 |
+
timestamp = []
|
| 165 |
+
_lbool = None
|
| 166 |
+
_ltime = None
|
| 167 |
+
_cur_start = None
|
| 168 |
+
for _ts, _bool in timestamp_series.items():
|
| 169 |
+
# there is likely to be NAN when the filter series don't have the
|
| 170 |
+
# bool value, so we just change the NAN into False
|
| 171 |
+
if np.isnan(_bool):
|
| 172 |
+
_bool = False
|
| 173 |
+
if _lbool is None:
|
| 174 |
+
_cur_start = _ts
|
| 175 |
+
_lbool = _bool
|
| 176 |
+
_ltime = _ts
|
| 177 |
+
continue
|
| 178 |
+
if (_lbool, _bool) == (True, False):
|
| 179 |
+
if _cur_start:
|
| 180 |
+
timestamp.append((_cur_start, _ltime))
|
| 181 |
+
elif (_lbool, _bool) == (False, True):
|
| 182 |
+
_cur_start = _ts
|
| 183 |
+
_lbool = _bool
|
| 184 |
+
_ltime = _ts
|
| 185 |
+
if _lbool:
|
| 186 |
+
timestamp.append((_cur_start, _ltime))
|
| 187 |
+
return timestamp
|
| 188 |
+
|
| 189 |
+
def __call__(self, instruments, start_time=None, end_time=None, freq="day"):
|
| 190 |
+
"""Call this filter to get filtered instruments list"""
|
| 191 |
+
self.filter_freq = freq
|
| 192 |
+
return self.filter_main(instruments, start_time, end_time)
|
| 193 |
+
|
| 194 |
+
@abstractmethod
|
| 195 |
+
def _getFilterSeries(self, instruments, fstart, fend):
|
| 196 |
+
"""Get filter series based on the rules assigned during the initialization and the input time range.
|
| 197 |
+
|
| 198 |
+
Parameters
|
| 199 |
+
----------
|
| 200 |
+
instruments : dict
|
| 201 |
+
the dict of instruments to be filtered.
|
| 202 |
+
fstart : pd.Timestamp
|
| 203 |
+
start time of filter.
|
| 204 |
+
fend : pd.Timestamp
|
| 205 |
+
end time of filter.
|
| 206 |
+
|
| 207 |
+
.. note:: fstart/fend indicates the intersection of instruments start/end time and filter start/end time.
|
| 208 |
+
|
| 209 |
+
Returns
|
| 210 |
+
----------
|
| 211 |
+
pd.Dataframe
|
| 212 |
+
a series of {pd.Timestamp => bool}.
|
| 213 |
+
"""
|
| 214 |
+
raise NotImplementedError("Subclass of SeriesDFilter must reimplement `getFilterSeries` method")
|
| 215 |
+
|
| 216 |
+
def filter_main(self, instruments, start_time=None, end_time=None):
|
| 217 |
+
"""Implement this method to filter the instruments.
|
| 218 |
+
|
| 219 |
+
Parameters
|
| 220 |
+
----------
|
| 221 |
+
instruments: dict
|
| 222 |
+
input instruments to be filtered.
|
| 223 |
+
start_time: str
|
| 224 |
+
start of the time range.
|
| 225 |
+
end_time: str
|
| 226 |
+
end of the time range.
|
| 227 |
+
|
| 228 |
+
Returns
|
| 229 |
+
----------
|
| 230 |
+
dict
|
| 231 |
+
filtered instruments, same structure as input instruments.
|
| 232 |
+
"""
|
| 233 |
+
lbound, ubound = self._getTimeBound(instruments)
|
| 234 |
+
start_time = pd.Timestamp(start_time or lbound)
|
| 235 |
+
end_time = pd.Timestamp(end_time or ubound)
|
| 236 |
+
_instruments_filtered = {}
|
| 237 |
+
_all_calendar = Cal.calendar(start_time=start_time, end_time=end_time, freq=self.filter_freq)
|
| 238 |
+
_filter_calendar = Cal.calendar(
|
| 239 |
+
start_time=self.filter_start_time and max(self.filter_start_time, _all_calendar[0]) or _all_calendar[0],
|
| 240 |
+
end_time=self.filter_end_time and min(self.filter_end_time, _all_calendar[-1]) or _all_calendar[-1],
|
| 241 |
+
freq=self.filter_freq,
|
| 242 |
+
)
|
| 243 |
+
_all_filter_series = self._getFilterSeries(instruments, _filter_calendar[0], _filter_calendar[-1])
|
| 244 |
+
for inst, timestamp in instruments.items():
|
| 245 |
+
# Construct a whole map of date
|
| 246 |
+
_timestamp_series = self._toSeries(_all_calendar, timestamp)
|
| 247 |
+
# Get filter series
|
| 248 |
+
if inst in _all_filter_series:
|
| 249 |
+
_filter_series = _all_filter_series[inst]
|
| 250 |
+
else:
|
| 251 |
+
if self.keep:
|
| 252 |
+
_filter_series = pd.Series({timestamp: True for timestamp in _filter_calendar})
|
| 253 |
+
else:
|
| 254 |
+
_filter_series = pd.Series({timestamp: False for timestamp in _filter_calendar})
|
| 255 |
+
# Calculate bool value within the range of filter
|
| 256 |
+
_timestamp_series = self._filterSeries(_timestamp_series, _filter_series)
|
| 257 |
+
# Reform the map to (start_timestamp, end_timestamp) format
|
| 258 |
+
_timestamp = self._toTimestamp(_timestamp_series)
|
| 259 |
+
# Remove empty timestamp
|
| 260 |
+
if _timestamp:
|
| 261 |
+
_instruments_filtered[inst] = _timestamp
|
| 262 |
+
return _instruments_filtered
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
class NameDFilter(SeriesDFilter):
|
| 266 |
+
"""Name dynamic instrument filter
|
| 267 |
+
|
| 268 |
+
Filter the instruments based on a regulated name format.
|
| 269 |
+
|
| 270 |
+
A name rule regular expression is required.
|
| 271 |
+
"""
|
| 272 |
+
|
| 273 |
+
def __init__(self, name_rule_re, fstart_time=None, fend_time=None):
|
| 274 |
+
"""Init function for name filter class
|
| 275 |
+
|
| 276 |
+
Parameters
|
| 277 |
+
----------
|
| 278 |
+
name_rule_re: str
|
| 279 |
+
regular expression for the name rule.
|
| 280 |
+
"""
|
| 281 |
+
super(NameDFilter, self).__init__(fstart_time, fend_time)
|
| 282 |
+
self.name_rule_re = name_rule_re
|
| 283 |
+
|
| 284 |
+
def _getFilterSeries(self, instruments, fstart, fend):
|
| 285 |
+
all_filter_series = {}
|
| 286 |
+
filter_calendar = Cal.calendar(start_time=fstart, end_time=fend, freq=self.filter_freq)
|
| 287 |
+
for inst, timestamp in instruments.items():
|
| 288 |
+
if re.match(self.name_rule_re, inst):
|
| 289 |
+
_filter_series = pd.Series({timestamp: True for timestamp in filter_calendar})
|
| 290 |
+
else:
|
| 291 |
+
_filter_series = pd.Series({timestamp: False for timestamp in filter_calendar})
|
| 292 |
+
all_filter_series[inst] = _filter_series
|
| 293 |
+
return all_filter_series
|
| 294 |
+
|
| 295 |
+
@staticmethod
|
| 296 |
+
def from_config(config):
|
| 297 |
+
return NameDFilter(
|
| 298 |
+
name_rule_re=config["name_rule_re"],
|
| 299 |
+
fstart_time=config["filter_start_time"],
|
| 300 |
+
fend_time=config["filter_end_time"],
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
def to_config(self):
|
| 304 |
+
return {
|
| 305 |
+
"filter_type": "NameDFilter",
|
| 306 |
+
"name_rule_re": self.name_rule_re,
|
| 307 |
+
"filter_start_time": str(self.filter_start_time) if self.filter_start_time else self.filter_start_time,
|
| 308 |
+
"filter_end_time": str(self.filter_end_time) if self.filter_end_time else self.filter_end_time,
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
class ExpressionDFilter(SeriesDFilter):
|
| 313 |
+
"""Expression dynamic instrument filter
|
| 314 |
+
|
| 315 |
+
Filter the instruments based on a certain expression.
|
| 316 |
+
|
| 317 |
+
An expression rule indicating a certain feature field is required.
|
| 318 |
+
|
| 319 |
+
Examples
|
| 320 |
+
----------
|
| 321 |
+
- *basic features filter* : rule_expression = '$close/$open>5'
|
| 322 |
+
- *cross-sectional features filter* : rule_expression = '$rank($close)<10'
|
| 323 |
+
- *time-sequence features filter* : rule_expression = '$Ref($close, 3)>100'
|
| 324 |
+
"""
|
| 325 |
+
|
| 326 |
+
def __init__(self, rule_expression, fstart_time=None, fend_time=None, keep=False):
|
| 327 |
+
"""Init function for expression filter class
|
| 328 |
+
|
| 329 |
+
Parameters
|
| 330 |
+
----------
|
| 331 |
+
fstart_time: str
|
| 332 |
+
filter the feature starting from this time.
|
| 333 |
+
fend_time: str
|
| 334 |
+
filter the feature ending by this time.
|
| 335 |
+
rule_expression: str
|
| 336 |
+
an input expression for the rule.
|
| 337 |
+
"""
|
| 338 |
+
super(ExpressionDFilter, self).__init__(fstart_time, fend_time, keep=keep)
|
| 339 |
+
self.rule_expression = rule_expression
|
| 340 |
+
|
| 341 |
+
def _getFilterSeries(self, instruments, fstart, fend):
|
| 342 |
+
# do not use dataset cache
|
| 343 |
+
try:
|
| 344 |
+
_features = DatasetD.dataset(
|
| 345 |
+
instruments,
|
| 346 |
+
[self.rule_expression],
|
| 347 |
+
fstart,
|
| 348 |
+
fend,
|
| 349 |
+
freq=self.filter_freq,
|
| 350 |
+
disk_cache=0,
|
| 351 |
+
)
|
| 352 |
+
except TypeError:
|
| 353 |
+
# use LocalDatasetProvider
|
| 354 |
+
_features = DatasetD.dataset(instruments, [self.rule_expression], fstart, fend, freq=self.filter_freq)
|
| 355 |
+
rule_expression_field_name = list(_features.keys())[0]
|
| 356 |
+
all_filter_series = _features[rule_expression_field_name]
|
| 357 |
+
return all_filter_series
|
| 358 |
+
|
| 359 |
+
@staticmethod
|
| 360 |
+
def from_config(config):
|
| 361 |
+
return ExpressionDFilter(
|
| 362 |
+
rule_expression=config["rule_expression"],
|
| 363 |
+
fstart_time=config["filter_start_time"],
|
| 364 |
+
fend_time=config["filter_end_time"],
|
| 365 |
+
keep=config["keep"],
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
def to_config(self):
|
| 369 |
+
return {
|
| 370 |
+
"filter_type": "ExpressionDFilter",
|
| 371 |
+
"rule_expression": self.rule_expression,
|
| 372 |
+
"filter_start_time": str(self.filter_start_time) if self.filter_start_time else self.filter_start_time,
|
| 373 |
+
"filter_end_time": str(self.filter_end_time) if self.filter_end_time else self.filter_end_time,
|
| 374 |
+
"keep": self.keep,
|
| 375 |
+
}
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/inst_processor.py
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import abc
|
| 2 |
+
import json
|
| 3 |
+
import pandas as pd
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class InstProcessor:
|
| 7 |
+
@abc.abstractmethod
|
| 8 |
+
def __call__(self, df: pd.DataFrame, instrument, *args, **kwargs):
|
| 9 |
+
"""
|
| 10 |
+
process the data
|
| 11 |
+
|
| 12 |
+
NOTE: **The processor could change the content of `df` inplace !!!!! **
|
| 13 |
+
User should keep a copy of data outside
|
| 14 |
+
|
| 15 |
+
Parameters
|
| 16 |
+
----------
|
| 17 |
+
df : pd.DataFrame
|
| 18 |
+
The raw_df of handler or result from previous processor.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
def __str__(self):
|
| 22 |
+
return f"{self.__class__.__name__}:{json.dumps(self.__dict__, sort_keys=True, default=str)}"
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/ops.py
ADDED
|
@@ -0,0 +1,1681 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
from __future__ import division
|
| 6 |
+
from __future__ import print_function
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from typing import Union, List, Type
|
| 12 |
+
from scipy.stats import percentileofscore
|
| 13 |
+
from .base import Expression, ExpressionOps, Feature, PFeature
|
| 14 |
+
from ..log import get_module_logger
|
| 15 |
+
from ..utils import get_callable_kwargs
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from ._libs.rolling import rolling_slope, rolling_rsquare, rolling_resi
|
| 19 |
+
from ._libs.expanding import expanding_slope, expanding_rsquare, expanding_resi
|
| 20 |
+
except ImportError:
|
| 21 |
+
print(
|
| 22 |
+
"#### Do not import qlib package in the repository directory in case of importing qlib from . without compiling #####"
|
| 23 |
+
)
|
| 24 |
+
raise
|
| 25 |
+
except ValueError:
|
| 26 |
+
print("!!!!!!!! A error occurs when importing operators implemented based on Cython.!!!!!!!!")
|
| 27 |
+
print("!!!!!!!! They will be disabled. Please Upgrade your numpy to enable them !!!!!!!!")
|
| 28 |
+
# We catch this error because some platform can't upgrade there package (e.g. Kaggle)
|
| 29 |
+
# https://www.kaggle.com/general/293387
|
| 30 |
+
# https://www.kaggle.com/product-feedback/98562
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
np.seterr(invalid="ignore")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
#################### Element-Wise Operator ####################
|
| 37 |
+
class ElemOperator(ExpressionOps):
|
| 38 |
+
"""Element-wise Operator
|
| 39 |
+
|
| 40 |
+
Parameters
|
| 41 |
+
----------
|
| 42 |
+
feature : Expression
|
| 43 |
+
feature instance
|
| 44 |
+
|
| 45 |
+
Returns
|
| 46 |
+
----------
|
| 47 |
+
Expression
|
| 48 |
+
feature operation output
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __init__(self, feature):
|
| 52 |
+
self.feature = feature
|
| 53 |
+
|
| 54 |
+
def __str__(self):
|
| 55 |
+
return "{}({})".format(type(self).__name__, self.feature)
|
| 56 |
+
|
| 57 |
+
def get_longest_back_rolling(self):
|
| 58 |
+
return self.feature.get_longest_back_rolling()
|
| 59 |
+
|
| 60 |
+
def get_extended_window_size(self):
|
| 61 |
+
return self.feature.get_extended_window_size()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ChangeInstrument(ElemOperator):
|
| 65 |
+
"""Change Instrument Operator
|
| 66 |
+
In some case, one may want to change to another instrument when calculating, for example, to
|
| 67 |
+
calculate beta of a stock with respect to a market index.
|
| 68 |
+
This would require changing the calculation of features from the stock (original instrument) to
|
| 69 |
+
the index (reference instrument)
|
| 70 |
+
Parameters
|
| 71 |
+
----------
|
| 72 |
+
instrument: new instrument for which the downstream operations should be performed upon.
|
| 73 |
+
i.e., SH000300 (CSI300 index), or ^GPSC (SP500 index).
|
| 74 |
+
|
| 75 |
+
feature: the feature to be calculated for the new instrument.
|
| 76 |
+
Returns
|
| 77 |
+
----------
|
| 78 |
+
Expression
|
| 79 |
+
feature operation output
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
def __init__(self, instrument, feature):
|
| 83 |
+
self.instrument = instrument
|
| 84 |
+
self.feature = feature
|
| 85 |
+
|
| 86 |
+
def __str__(self):
|
| 87 |
+
return "{}('{}',{})".format(type(self).__name__, self.instrument, self.feature)
|
| 88 |
+
|
| 89 |
+
def load(self, instrument, start_index, end_index, *args):
|
| 90 |
+
# the first `instrument` is ignored
|
| 91 |
+
return super().load(self.instrument, start_index, end_index, *args)
|
| 92 |
+
|
| 93 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 94 |
+
return self.feature.load(instrument, start_index, end_index, *args)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class NpElemOperator(ElemOperator):
|
| 98 |
+
"""Numpy Element-wise Operator
|
| 99 |
+
|
| 100 |
+
Parameters
|
| 101 |
+
----------
|
| 102 |
+
feature : Expression
|
| 103 |
+
feature instance
|
| 104 |
+
func : str
|
| 105 |
+
numpy feature operation method
|
| 106 |
+
|
| 107 |
+
Returns
|
| 108 |
+
----------
|
| 109 |
+
Expression
|
| 110 |
+
feature operation output
|
| 111 |
+
"""
|
| 112 |
+
|
| 113 |
+
def __init__(self, feature, func):
|
| 114 |
+
self.func = func
|
| 115 |
+
super(NpElemOperator, self).__init__(feature)
|
| 116 |
+
|
| 117 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 118 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 119 |
+
return getattr(np, self.func)(series)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class Abs(NpElemOperator):
|
| 123 |
+
"""Feature Absolute Value
|
| 124 |
+
|
| 125 |
+
Parameters
|
| 126 |
+
----------
|
| 127 |
+
feature : Expression
|
| 128 |
+
feature instance
|
| 129 |
+
|
| 130 |
+
Returns
|
| 131 |
+
----------
|
| 132 |
+
Expression
|
| 133 |
+
a feature instance with absolute output
|
| 134 |
+
"""
|
| 135 |
+
|
| 136 |
+
def __init__(self, feature):
|
| 137 |
+
super(Abs, self).__init__(feature, "abs")
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class Sign(NpElemOperator):
|
| 141 |
+
"""Feature Sign
|
| 142 |
+
|
| 143 |
+
Parameters
|
| 144 |
+
----------
|
| 145 |
+
feature : Expression
|
| 146 |
+
feature instance
|
| 147 |
+
|
| 148 |
+
Returns
|
| 149 |
+
----------
|
| 150 |
+
Expression
|
| 151 |
+
a feature instance with sign
|
| 152 |
+
"""
|
| 153 |
+
|
| 154 |
+
def __init__(self, feature):
|
| 155 |
+
super(Sign, self).__init__(feature, "sign")
|
| 156 |
+
|
| 157 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 158 |
+
"""
|
| 159 |
+
To avoid error raised by bool type input, we transform the data into float32.
|
| 160 |
+
"""
|
| 161 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 162 |
+
# TODO: More precision types should be configurable
|
| 163 |
+
series = series.astype(np.float32)
|
| 164 |
+
return getattr(np, self.func)(series)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class Log(NpElemOperator):
|
| 168 |
+
"""Feature Log
|
| 169 |
+
|
| 170 |
+
Parameters
|
| 171 |
+
----------
|
| 172 |
+
feature : Expression
|
| 173 |
+
feature instance
|
| 174 |
+
|
| 175 |
+
Returns
|
| 176 |
+
----------
|
| 177 |
+
Expression
|
| 178 |
+
a feature instance with log
|
| 179 |
+
"""
|
| 180 |
+
|
| 181 |
+
def __init__(self, feature):
|
| 182 |
+
super(Log, self).__init__(feature, "log")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
class Mask(NpElemOperator):
|
| 186 |
+
"""Feature Mask
|
| 187 |
+
|
| 188 |
+
Parameters
|
| 189 |
+
----------
|
| 190 |
+
feature : Expression
|
| 191 |
+
feature instance
|
| 192 |
+
instrument : str
|
| 193 |
+
instrument mask
|
| 194 |
+
|
| 195 |
+
Returns
|
| 196 |
+
----------
|
| 197 |
+
Expression
|
| 198 |
+
a feature instance with masked instrument
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
def __init__(self, feature, instrument):
|
| 202 |
+
super(Mask, self).__init__(feature, "mask")
|
| 203 |
+
self.instrument = instrument
|
| 204 |
+
|
| 205 |
+
def __str__(self):
|
| 206 |
+
return "{}({},{})".format(type(self).__name__, self.feature, self.instrument.lower())
|
| 207 |
+
|
| 208 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 209 |
+
return self.feature.load(self.instrument, start_index, end_index, *args)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class Not(NpElemOperator):
|
| 213 |
+
"""Not Operator
|
| 214 |
+
|
| 215 |
+
Parameters
|
| 216 |
+
----------
|
| 217 |
+
feature : Expression
|
| 218 |
+
feature instance
|
| 219 |
+
|
| 220 |
+
Returns
|
| 221 |
+
----------
|
| 222 |
+
Feature:
|
| 223 |
+
feature elementwise not output
|
| 224 |
+
"""
|
| 225 |
+
|
| 226 |
+
def __init__(self, feature):
|
| 227 |
+
super(Not, self).__init__(feature, "bitwise_not")
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
#################### Pair-Wise Operator ####################
|
| 231 |
+
class PairOperator(ExpressionOps):
|
| 232 |
+
"""Pair-wise operator
|
| 233 |
+
|
| 234 |
+
Parameters
|
| 235 |
+
----------
|
| 236 |
+
feature_left : Expression
|
| 237 |
+
feature instance or numeric value
|
| 238 |
+
feature_right : Expression
|
| 239 |
+
feature instance or numeric value
|
| 240 |
+
|
| 241 |
+
Returns
|
| 242 |
+
----------
|
| 243 |
+
Feature:
|
| 244 |
+
two features' operation output
|
| 245 |
+
"""
|
| 246 |
+
|
| 247 |
+
def __init__(self, feature_left, feature_right):
|
| 248 |
+
self.feature_left = feature_left
|
| 249 |
+
self.feature_right = feature_right
|
| 250 |
+
|
| 251 |
+
def __str__(self):
|
| 252 |
+
return "{}({},{})".format(type(self).__name__, self.feature_left, self.feature_right)
|
| 253 |
+
|
| 254 |
+
def get_longest_back_rolling(self):
|
| 255 |
+
if isinstance(self.feature_left, (Expression,)):
|
| 256 |
+
left_br = self.feature_left.get_longest_back_rolling()
|
| 257 |
+
else:
|
| 258 |
+
left_br = 0
|
| 259 |
+
|
| 260 |
+
if isinstance(self.feature_right, (Expression,)):
|
| 261 |
+
right_br = self.feature_right.get_longest_back_rolling()
|
| 262 |
+
else:
|
| 263 |
+
right_br = 0
|
| 264 |
+
return max(left_br, right_br)
|
| 265 |
+
|
| 266 |
+
def get_extended_window_size(self):
|
| 267 |
+
if isinstance(self.feature_left, (Expression,)):
|
| 268 |
+
ll, lr = self.feature_left.get_extended_window_size()
|
| 269 |
+
else:
|
| 270 |
+
ll, lr = 0, 0
|
| 271 |
+
|
| 272 |
+
if isinstance(self.feature_right, (Expression,)):
|
| 273 |
+
rl, rr = self.feature_right.get_extended_window_size()
|
| 274 |
+
else:
|
| 275 |
+
rl, rr = 0, 0
|
| 276 |
+
return max(ll, rl), max(lr, rr)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
class NpPairOperator(PairOperator):
|
| 280 |
+
"""Numpy Pair-wise operator
|
| 281 |
+
|
| 282 |
+
Parameters
|
| 283 |
+
----------
|
| 284 |
+
feature_left : Expression
|
| 285 |
+
feature instance or numeric value
|
| 286 |
+
feature_right : Expression
|
| 287 |
+
feature instance or numeric value
|
| 288 |
+
func : str
|
| 289 |
+
operator function
|
| 290 |
+
|
| 291 |
+
Returns
|
| 292 |
+
----------
|
| 293 |
+
Feature:
|
| 294 |
+
two features' operation output
|
| 295 |
+
"""
|
| 296 |
+
|
| 297 |
+
def __init__(self, feature_left, feature_right, func):
|
| 298 |
+
self.func = func
|
| 299 |
+
super(NpPairOperator, self).__init__(feature_left, feature_right)
|
| 300 |
+
|
| 301 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 302 |
+
assert any(
|
| 303 |
+
[isinstance(self.feature_left, (Expression,)), self.feature_right, Expression]
|
| 304 |
+
), "at least one of two inputs is Expression instance"
|
| 305 |
+
if isinstance(self.feature_left, (Expression,)):
|
| 306 |
+
series_left = self.feature_left.load(instrument, start_index, end_index, *args)
|
| 307 |
+
else:
|
| 308 |
+
series_left = self.feature_left # numeric value
|
| 309 |
+
if isinstance(self.feature_right, (Expression,)):
|
| 310 |
+
series_right = self.feature_right.load(instrument, start_index, end_index, *args)
|
| 311 |
+
else:
|
| 312 |
+
series_right = self.feature_right
|
| 313 |
+
check_length = isinstance(series_left, (np.ndarray, pd.Series)) and isinstance(
|
| 314 |
+
series_right, (np.ndarray, pd.Series)
|
| 315 |
+
)
|
| 316 |
+
if check_length:
|
| 317 |
+
warning_info = (
|
| 318 |
+
f"Loading {instrument}: {str(self)}; np.{self.func}(series_left, series_right), "
|
| 319 |
+
f"The length of series_left and series_right is different: ({len(series_left)}, {len(series_right)}), "
|
| 320 |
+
f"series_left is {str(self.feature_left)}, series_right is {str(self.feature_right)}. Please check the data"
|
| 321 |
+
)
|
| 322 |
+
else:
|
| 323 |
+
warning_info = (
|
| 324 |
+
f"Loading {instrument}: {str(self)}; np.{self.func}(series_left, series_right), "
|
| 325 |
+
f"series_left is {str(self.feature_left)}, series_right is {str(self.feature_right)}. Please check the data"
|
| 326 |
+
)
|
| 327 |
+
try:
|
| 328 |
+
res = getattr(np, self.func)(series_left, series_right)
|
| 329 |
+
except ValueError as e:
|
| 330 |
+
get_module_logger("ops").debug(warning_info)
|
| 331 |
+
raise ValueError(f"{str(e)}. \n\t{warning_info}") from e
|
| 332 |
+
else:
|
| 333 |
+
if check_length and len(series_left) != len(series_right):
|
| 334 |
+
get_module_logger("ops").debug(warning_info)
|
| 335 |
+
return res
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class Power(NpPairOperator):
|
| 339 |
+
"""Power Operator
|
| 340 |
+
|
| 341 |
+
Parameters
|
| 342 |
+
----------
|
| 343 |
+
feature_left : Expression
|
| 344 |
+
feature instance
|
| 345 |
+
feature_right : Expression
|
| 346 |
+
feature instance
|
| 347 |
+
|
| 348 |
+
Returns
|
| 349 |
+
----------
|
| 350 |
+
Feature:
|
| 351 |
+
The bases in feature_left raised to the exponents in feature_right
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
def __init__(self, feature_left, feature_right):
|
| 355 |
+
super(Power, self).__init__(feature_left, feature_right, "power")
|
| 356 |
+
|
| 357 |
+
|
| 358 |
+
class Add(NpPairOperator):
|
| 359 |
+
"""Add Operator
|
| 360 |
+
|
| 361 |
+
Parameters
|
| 362 |
+
----------
|
| 363 |
+
feature_left : Expression
|
| 364 |
+
feature instance
|
| 365 |
+
feature_right : Expression
|
| 366 |
+
feature instance
|
| 367 |
+
|
| 368 |
+
Returns
|
| 369 |
+
----------
|
| 370 |
+
Feature:
|
| 371 |
+
two features' sum
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
def __init__(self, feature_left, feature_right):
|
| 375 |
+
super(Add, self).__init__(feature_left, feature_right, "add")
|
| 376 |
+
|
| 377 |
+
|
| 378 |
+
class Sub(NpPairOperator):
|
| 379 |
+
"""Subtract Operator
|
| 380 |
+
|
| 381 |
+
Parameters
|
| 382 |
+
----------
|
| 383 |
+
feature_left : Expression
|
| 384 |
+
feature instance
|
| 385 |
+
feature_right : Expression
|
| 386 |
+
feature instance
|
| 387 |
+
|
| 388 |
+
Returns
|
| 389 |
+
----------
|
| 390 |
+
Feature:
|
| 391 |
+
two features' subtraction
|
| 392 |
+
"""
|
| 393 |
+
|
| 394 |
+
def __init__(self, feature_left, feature_right):
|
| 395 |
+
super(Sub, self).__init__(feature_left, feature_right, "subtract")
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
class Mul(NpPairOperator):
|
| 399 |
+
"""Multiply Operator
|
| 400 |
+
|
| 401 |
+
Parameters
|
| 402 |
+
----------
|
| 403 |
+
feature_left : Expression
|
| 404 |
+
feature instance
|
| 405 |
+
feature_right : Expression
|
| 406 |
+
feature instance
|
| 407 |
+
|
| 408 |
+
Returns
|
| 409 |
+
----------
|
| 410 |
+
Feature:
|
| 411 |
+
two features' product
|
| 412 |
+
"""
|
| 413 |
+
|
| 414 |
+
def __init__(self, feature_left, feature_right):
|
| 415 |
+
super(Mul, self).__init__(feature_left, feature_right, "multiply")
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class Div(NpPairOperator):
|
| 419 |
+
"""Division Operator
|
| 420 |
+
|
| 421 |
+
Parameters
|
| 422 |
+
----------
|
| 423 |
+
feature_left : Expression
|
| 424 |
+
feature instance
|
| 425 |
+
feature_right : Expression
|
| 426 |
+
feature instance
|
| 427 |
+
|
| 428 |
+
Returns
|
| 429 |
+
----------
|
| 430 |
+
Feature:
|
| 431 |
+
two features' division
|
| 432 |
+
"""
|
| 433 |
+
|
| 434 |
+
def __init__(self, feature_left, feature_right):
|
| 435 |
+
super(Div, self).__init__(feature_left, feature_right, "divide")
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
class Greater(NpPairOperator):
|
| 439 |
+
"""Greater Operator
|
| 440 |
+
|
| 441 |
+
Parameters
|
| 442 |
+
----------
|
| 443 |
+
feature_left : Expression
|
| 444 |
+
feature instance
|
| 445 |
+
feature_right : Expression
|
| 446 |
+
feature instance
|
| 447 |
+
|
| 448 |
+
Returns
|
| 449 |
+
----------
|
| 450 |
+
Feature:
|
| 451 |
+
greater elements taken from the input two features
|
| 452 |
+
"""
|
| 453 |
+
|
| 454 |
+
def __init__(self, feature_left, feature_right):
|
| 455 |
+
super(Greater, self).__init__(feature_left, feature_right, "maximum")
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
class Less(NpPairOperator):
|
| 459 |
+
"""Less Operator
|
| 460 |
+
|
| 461 |
+
Parameters
|
| 462 |
+
----------
|
| 463 |
+
feature_left : Expression
|
| 464 |
+
feature instance
|
| 465 |
+
feature_right : Expression
|
| 466 |
+
feature instance
|
| 467 |
+
|
| 468 |
+
Returns
|
| 469 |
+
----------
|
| 470 |
+
Feature:
|
| 471 |
+
smaller elements taken from the input two features
|
| 472 |
+
"""
|
| 473 |
+
|
| 474 |
+
def __init__(self, feature_left, feature_right):
|
| 475 |
+
super(Less, self).__init__(feature_left, feature_right, "minimum")
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class Gt(NpPairOperator):
|
| 479 |
+
"""Greater Than Operator
|
| 480 |
+
|
| 481 |
+
Parameters
|
| 482 |
+
----------
|
| 483 |
+
feature_left : Expression
|
| 484 |
+
feature instance
|
| 485 |
+
feature_right : Expression
|
| 486 |
+
feature instance
|
| 487 |
+
|
| 488 |
+
Returns
|
| 489 |
+
----------
|
| 490 |
+
Feature:
|
| 491 |
+
bool series indicate `left > right`
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
def __init__(self, feature_left, feature_right):
|
| 495 |
+
super(Gt, self).__init__(feature_left, feature_right, "greater")
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
class Ge(NpPairOperator):
|
| 499 |
+
"""Greater Equal Than Operator
|
| 500 |
+
|
| 501 |
+
Parameters
|
| 502 |
+
----------
|
| 503 |
+
feature_left : Expression
|
| 504 |
+
feature instance
|
| 505 |
+
feature_right : Expression
|
| 506 |
+
feature instance
|
| 507 |
+
|
| 508 |
+
Returns
|
| 509 |
+
----------
|
| 510 |
+
Feature:
|
| 511 |
+
bool series indicate `left >= right`
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
def __init__(self, feature_left, feature_right):
|
| 515 |
+
super(Ge, self).__init__(feature_left, feature_right, "greater_equal")
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
class Lt(NpPairOperator):
|
| 519 |
+
"""Less Than Operator
|
| 520 |
+
|
| 521 |
+
Parameters
|
| 522 |
+
----------
|
| 523 |
+
feature_left : Expression
|
| 524 |
+
feature instance
|
| 525 |
+
feature_right : Expression
|
| 526 |
+
feature instance
|
| 527 |
+
|
| 528 |
+
Returns
|
| 529 |
+
----------
|
| 530 |
+
Feature:
|
| 531 |
+
bool series indicate `left < right`
|
| 532 |
+
"""
|
| 533 |
+
|
| 534 |
+
def __init__(self, feature_left, feature_right):
|
| 535 |
+
super(Lt, self).__init__(feature_left, feature_right, "less")
|
| 536 |
+
|
| 537 |
+
|
| 538 |
+
class Le(NpPairOperator):
|
| 539 |
+
"""Less Equal Than Operator
|
| 540 |
+
|
| 541 |
+
Parameters
|
| 542 |
+
----------
|
| 543 |
+
feature_left : Expression
|
| 544 |
+
feature instance
|
| 545 |
+
feature_right : Expression
|
| 546 |
+
feature instance
|
| 547 |
+
|
| 548 |
+
Returns
|
| 549 |
+
----------
|
| 550 |
+
Feature:
|
| 551 |
+
bool series indicate `left <= right`
|
| 552 |
+
"""
|
| 553 |
+
|
| 554 |
+
def __init__(self, feature_left, feature_right):
|
| 555 |
+
super(Le, self).__init__(feature_left, feature_right, "less_equal")
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
class Eq(NpPairOperator):
|
| 559 |
+
"""Equal Operator
|
| 560 |
+
|
| 561 |
+
Parameters
|
| 562 |
+
----------
|
| 563 |
+
feature_left : Expression
|
| 564 |
+
feature instance
|
| 565 |
+
feature_right : Expression
|
| 566 |
+
feature instance
|
| 567 |
+
|
| 568 |
+
Returns
|
| 569 |
+
----------
|
| 570 |
+
Feature:
|
| 571 |
+
bool series indicate `left == right`
|
| 572 |
+
"""
|
| 573 |
+
|
| 574 |
+
def __init__(self, feature_left, feature_right):
|
| 575 |
+
super(Eq, self).__init__(feature_left, feature_right, "equal")
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class Ne(NpPairOperator):
|
| 579 |
+
"""Not Equal Operator
|
| 580 |
+
|
| 581 |
+
Parameters
|
| 582 |
+
----------
|
| 583 |
+
feature_left : Expression
|
| 584 |
+
feature instance
|
| 585 |
+
feature_right : Expression
|
| 586 |
+
feature instance
|
| 587 |
+
|
| 588 |
+
Returns
|
| 589 |
+
----------
|
| 590 |
+
Feature:
|
| 591 |
+
bool series indicate `left != right`
|
| 592 |
+
"""
|
| 593 |
+
|
| 594 |
+
def __init__(self, feature_left, feature_right):
|
| 595 |
+
super(Ne, self).__init__(feature_left, feature_right, "not_equal")
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
class And(NpPairOperator):
|
| 599 |
+
"""And Operator
|
| 600 |
+
|
| 601 |
+
Parameters
|
| 602 |
+
----------
|
| 603 |
+
feature_left : Expression
|
| 604 |
+
feature instance
|
| 605 |
+
feature_right : Expression
|
| 606 |
+
feature instance
|
| 607 |
+
|
| 608 |
+
Returns
|
| 609 |
+
----------
|
| 610 |
+
Feature:
|
| 611 |
+
two features' row by row & output
|
| 612 |
+
"""
|
| 613 |
+
|
| 614 |
+
def __init__(self, feature_left, feature_right):
|
| 615 |
+
super(And, self).__init__(feature_left, feature_right, "bitwise_and")
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
class Or(NpPairOperator):
|
| 619 |
+
"""Or Operator
|
| 620 |
+
|
| 621 |
+
Parameters
|
| 622 |
+
----------
|
| 623 |
+
feature_left : Expression
|
| 624 |
+
feature instance
|
| 625 |
+
feature_right : Expression
|
| 626 |
+
feature instance
|
| 627 |
+
|
| 628 |
+
Returns
|
| 629 |
+
----------
|
| 630 |
+
Feature:
|
| 631 |
+
two features' row by row | outputs
|
| 632 |
+
"""
|
| 633 |
+
|
| 634 |
+
def __init__(self, feature_left, feature_right):
|
| 635 |
+
super(Or, self).__init__(feature_left, feature_right, "bitwise_or")
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
#################### Triple-wise Operator ####################
|
| 639 |
+
class If(ExpressionOps):
|
| 640 |
+
"""If Operator
|
| 641 |
+
|
| 642 |
+
Parameters
|
| 643 |
+
----------
|
| 644 |
+
condition : Expression
|
| 645 |
+
feature instance with bool values as condition
|
| 646 |
+
feature_left : Expression
|
| 647 |
+
feature instance
|
| 648 |
+
feature_right : Expression
|
| 649 |
+
feature instance
|
| 650 |
+
"""
|
| 651 |
+
|
| 652 |
+
def __init__(self, condition, feature_left, feature_right):
|
| 653 |
+
self.condition = condition
|
| 654 |
+
self.feature_left = feature_left
|
| 655 |
+
self.feature_right = feature_right
|
| 656 |
+
|
| 657 |
+
def __str__(self):
|
| 658 |
+
return "If({},{},{})".format(self.condition, self.feature_left, self.feature_right)
|
| 659 |
+
|
| 660 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 661 |
+
series_cond = self.condition.load(instrument, start_index, end_index, *args)
|
| 662 |
+
if isinstance(self.feature_left, (Expression,)):
|
| 663 |
+
series_left = self.feature_left.load(instrument, start_index, end_index, *args)
|
| 664 |
+
else:
|
| 665 |
+
series_left = self.feature_left
|
| 666 |
+
if isinstance(self.feature_right, (Expression,)):
|
| 667 |
+
series_right = self.feature_right.load(instrument, start_index, end_index, *args)
|
| 668 |
+
else:
|
| 669 |
+
series_right = self.feature_right
|
| 670 |
+
series = pd.Series(np.where(series_cond, series_left, series_right), index=series_cond.index)
|
| 671 |
+
return series
|
| 672 |
+
|
| 673 |
+
def get_longest_back_rolling(self):
|
| 674 |
+
if isinstance(self.feature_left, (Expression,)):
|
| 675 |
+
left_br = self.feature_left.get_longest_back_rolling()
|
| 676 |
+
else:
|
| 677 |
+
left_br = 0
|
| 678 |
+
|
| 679 |
+
if isinstance(self.feature_right, (Expression,)):
|
| 680 |
+
right_br = self.feature_right.get_longest_back_rolling()
|
| 681 |
+
else:
|
| 682 |
+
right_br = 0
|
| 683 |
+
|
| 684 |
+
if isinstance(self.condition, (Expression,)):
|
| 685 |
+
c_br = self.condition.get_longest_back_rolling()
|
| 686 |
+
else:
|
| 687 |
+
c_br = 0
|
| 688 |
+
return max(left_br, right_br, c_br)
|
| 689 |
+
|
| 690 |
+
def get_extended_window_size(self):
|
| 691 |
+
if isinstance(self.feature_left, (Expression,)):
|
| 692 |
+
ll, lr = self.feature_left.get_extended_window_size()
|
| 693 |
+
else:
|
| 694 |
+
ll, lr = 0, 0
|
| 695 |
+
|
| 696 |
+
if isinstance(self.feature_right, (Expression,)):
|
| 697 |
+
rl, rr = self.feature_right.get_extended_window_size()
|
| 698 |
+
else:
|
| 699 |
+
rl, rr = 0, 0
|
| 700 |
+
|
| 701 |
+
if isinstance(self.condition, (Expression,)):
|
| 702 |
+
cl, cr = self.condition.get_extended_window_size()
|
| 703 |
+
else:
|
| 704 |
+
cl, cr = 0, 0
|
| 705 |
+
return max(ll, rl, cl), max(lr, rr, cr)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
#################### Rolling ####################
|
| 709 |
+
# NOTE: methods like `rolling.mean` are optimized with cython,
|
| 710 |
+
# and are super faster than `rolling.apply(np.mean)`
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
class Rolling(ExpressionOps):
|
| 714 |
+
"""Rolling Operator
|
| 715 |
+
The meaning of rolling and expanding is the same in pandas.
|
| 716 |
+
When the window is set to 0, the behaviour of the operator should follow `expanding`
|
| 717 |
+
Otherwise, it follows `rolling`
|
| 718 |
+
|
| 719 |
+
Parameters
|
| 720 |
+
----------
|
| 721 |
+
feature : Expression
|
| 722 |
+
feature instance
|
| 723 |
+
N : int
|
| 724 |
+
rolling window size
|
| 725 |
+
func : str
|
| 726 |
+
rolling method
|
| 727 |
+
|
| 728 |
+
Returns
|
| 729 |
+
----------
|
| 730 |
+
Expression
|
| 731 |
+
rolling outputs
|
| 732 |
+
"""
|
| 733 |
+
|
| 734 |
+
def __init__(self, feature, N, func):
|
| 735 |
+
self.feature = feature
|
| 736 |
+
self.N = N
|
| 737 |
+
self.func = func
|
| 738 |
+
|
| 739 |
+
def __str__(self):
|
| 740 |
+
return "{}({},{})".format(type(self).__name__, self.feature, self.N)
|
| 741 |
+
|
| 742 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 743 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 744 |
+
# NOTE: remove all null check,
|
| 745 |
+
# now it's user's responsibility to decide whether use features in null days
|
| 746 |
+
# isnull = series.isnull() # NOTE: isnull = NaN, inf is not null
|
| 747 |
+
if isinstance(self.N, int) and self.N == 0:
|
| 748 |
+
series = getattr(series.expanding(min_periods=1), self.func)()
|
| 749 |
+
elif isinstance(self.N, float) and 0 < self.N < 1:
|
| 750 |
+
series = series.ewm(alpha=self.N, min_periods=1).mean()
|
| 751 |
+
else:
|
| 752 |
+
series = getattr(series.rolling(self.N, min_periods=1), self.func)()
|
| 753 |
+
# series.iloc[:self.N-1] = np.nan
|
| 754 |
+
# series[isnull] = np.nan
|
| 755 |
+
return series
|
| 756 |
+
|
| 757 |
+
def get_longest_back_rolling(self):
|
| 758 |
+
if self.N == 0:
|
| 759 |
+
return np.inf
|
| 760 |
+
if 0 < self.N < 1:
|
| 761 |
+
return int(np.log(1e-6) / np.log(1 - self.N)) # (1 - N)**window == 1e-6
|
| 762 |
+
return self.feature.get_longest_back_rolling() + self.N - 1
|
| 763 |
+
|
| 764 |
+
def get_extended_window_size(self):
|
| 765 |
+
if self.N == 0:
|
| 766 |
+
# FIXME: How to make this accurate and efficiently? Or should we
|
| 767 |
+
# remove such support for N == 0?
|
| 768 |
+
get_module_logger(self.__class__.__name__).warning("The Rolling(ATTR, 0) will not be accurately calculated")
|
| 769 |
+
return self.feature.get_extended_window_size()
|
| 770 |
+
elif 0 < self.N < 1:
|
| 771 |
+
lft_etd, rght_etd = self.feature.get_extended_window_size()
|
| 772 |
+
size = int(np.log(1e-6) / np.log(1 - self.N))
|
| 773 |
+
lft_etd = max(lft_etd + size - 1, lft_etd)
|
| 774 |
+
return lft_etd, rght_etd
|
| 775 |
+
else:
|
| 776 |
+
lft_etd, rght_etd = self.feature.get_extended_window_size()
|
| 777 |
+
lft_etd = max(lft_etd + self.N - 1, lft_etd)
|
| 778 |
+
return lft_etd, rght_etd
|
| 779 |
+
|
| 780 |
+
|
| 781 |
+
class Ref(Rolling):
|
| 782 |
+
"""Feature Reference
|
| 783 |
+
|
| 784 |
+
Parameters
|
| 785 |
+
----------
|
| 786 |
+
feature : Expression
|
| 787 |
+
feature instance
|
| 788 |
+
N : int
|
| 789 |
+
N = 0, retrieve the first data; N > 0, retrieve data of N periods ago; N < 0, future data
|
| 790 |
+
|
| 791 |
+
Returns
|
| 792 |
+
----------
|
| 793 |
+
Expression
|
| 794 |
+
a feature instance with target reference
|
| 795 |
+
"""
|
| 796 |
+
|
| 797 |
+
def __init__(self, feature, N):
|
| 798 |
+
super(Ref, self).__init__(feature, N, "ref")
|
| 799 |
+
|
| 800 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 801 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 802 |
+
# N = 0, return first day
|
| 803 |
+
if series.empty:
|
| 804 |
+
return series # Pandas bug, see: https://github.com/pandas-dev/pandas/issues/21049
|
| 805 |
+
elif self.N == 0:
|
| 806 |
+
series = pd.Series(series.iloc[0], index=series.index)
|
| 807 |
+
else:
|
| 808 |
+
series = series.shift(self.N) # copy
|
| 809 |
+
return series
|
| 810 |
+
|
| 811 |
+
def get_longest_back_rolling(self):
|
| 812 |
+
if self.N == 0:
|
| 813 |
+
return np.inf
|
| 814 |
+
return self.feature.get_longest_back_rolling() + self.N
|
| 815 |
+
|
| 816 |
+
def get_extended_window_size(self):
|
| 817 |
+
if self.N == 0:
|
| 818 |
+
get_module_logger(self.__class__.__name__).warning("The Ref(ATTR, 0) will not be accurately calculated")
|
| 819 |
+
return self.feature.get_extended_window_size()
|
| 820 |
+
else:
|
| 821 |
+
lft_etd, rght_etd = self.feature.get_extended_window_size()
|
| 822 |
+
lft_etd = max(lft_etd + self.N, lft_etd)
|
| 823 |
+
rght_etd = max(rght_etd - self.N, rght_etd)
|
| 824 |
+
return lft_etd, rght_etd
|
| 825 |
+
|
| 826 |
+
|
| 827 |
+
class Mean(Rolling):
|
| 828 |
+
"""Rolling Mean (MA)
|
| 829 |
+
|
| 830 |
+
Parameters
|
| 831 |
+
----------
|
| 832 |
+
feature : Expression
|
| 833 |
+
feature instance
|
| 834 |
+
N : int
|
| 835 |
+
rolling window size
|
| 836 |
+
|
| 837 |
+
Returns
|
| 838 |
+
----------
|
| 839 |
+
Expression
|
| 840 |
+
a feature instance with rolling average
|
| 841 |
+
"""
|
| 842 |
+
|
| 843 |
+
def __init__(self, feature, N):
|
| 844 |
+
super(Mean, self).__init__(feature, N, "mean")
|
| 845 |
+
|
| 846 |
+
|
| 847 |
+
class Sum(Rolling):
|
| 848 |
+
"""Rolling Sum
|
| 849 |
+
|
| 850 |
+
Parameters
|
| 851 |
+
----------
|
| 852 |
+
feature : Expression
|
| 853 |
+
feature instance
|
| 854 |
+
N : int
|
| 855 |
+
rolling window size
|
| 856 |
+
|
| 857 |
+
Returns
|
| 858 |
+
----------
|
| 859 |
+
Expression
|
| 860 |
+
a feature instance with rolling sum
|
| 861 |
+
"""
|
| 862 |
+
|
| 863 |
+
def __init__(self, feature, N):
|
| 864 |
+
super(Sum, self).__init__(feature, N, "sum")
|
| 865 |
+
|
| 866 |
+
|
| 867 |
+
class Std(Rolling):
|
| 868 |
+
"""Rolling Std
|
| 869 |
+
|
| 870 |
+
Parameters
|
| 871 |
+
----------
|
| 872 |
+
feature : Expression
|
| 873 |
+
feature instance
|
| 874 |
+
N : int
|
| 875 |
+
rolling window size
|
| 876 |
+
|
| 877 |
+
Returns
|
| 878 |
+
----------
|
| 879 |
+
Expression
|
| 880 |
+
a feature instance with rolling std
|
| 881 |
+
"""
|
| 882 |
+
|
| 883 |
+
def __init__(self, feature, N):
|
| 884 |
+
super(Std, self).__init__(feature, N, "std")
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
class Var(Rolling):
|
| 888 |
+
"""Rolling Variance
|
| 889 |
+
|
| 890 |
+
Parameters
|
| 891 |
+
----------
|
| 892 |
+
feature : Expression
|
| 893 |
+
feature instance
|
| 894 |
+
N : int
|
| 895 |
+
rolling window size
|
| 896 |
+
|
| 897 |
+
Returns
|
| 898 |
+
----------
|
| 899 |
+
Expression
|
| 900 |
+
a feature instance with rolling variance
|
| 901 |
+
"""
|
| 902 |
+
|
| 903 |
+
def __init__(self, feature, N):
|
| 904 |
+
super(Var, self).__init__(feature, N, "var")
|
| 905 |
+
|
| 906 |
+
|
| 907 |
+
class Skew(Rolling):
|
| 908 |
+
"""Rolling Skewness
|
| 909 |
+
|
| 910 |
+
Parameters
|
| 911 |
+
----------
|
| 912 |
+
feature : Expression
|
| 913 |
+
feature instance
|
| 914 |
+
N : int
|
| 915 |
+
rolling window size
|
| 916 |
+
|
| 917 |
+
Returns
|
| 918 |
+
----------
|
| 919 |
+
Expression
|
| 920 |
+
a feature instance with rolling skewness
|
| 921 |
+
"""
|
| 922 |
+
|
| 923 |
+
def __init__(self, feature, N):
|
| 924 |
+
if N != 0 and N < 3:
|
| 925 |
+
raise ValueError("The rolling window size of Skewness operation should >= 3")
|
| 926 |
+
super(Skew, self).__init__(feature, N, "skew")
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
class Kurt(Rolling):
|
| 930 |
+
"""Rolling Kurtosis
|
| 931 |
+
|
| 932 |
+
Parameters
|
| 933 |
+
----------
|
| 934 |
+
feature : Expression
|
| 935 |
+
feature instance
|
| 936 |
+
N : int
|
| 937 |
+
rolling window size
|
| 938 |
+
|
| 939 |
+
Returns
|
| 940 |
+
----------
|
| 941 |
+
Expression
|
| 942 |
+
a feature instance with rolling kurtosis
|
| 943 |
+
"""
|
| 944 |
+
|
| 945 |
+
def __init__(self, feature, N):
|
| 946 |
+
if N != 0 and N < 4:
|
| 947 |
+
raise ValueError("The rolling window size of Kurtosis operation should >= 5")
|
| 948 |
+
super(Kurt, self).__init__(feature, N, "kurt")
|
| 949 |
+
|
| 950 |
+
|
| 951 |
+
class Max(Rolling):
|
| 952 |
+
"""Rolling Max
|
| 953 |
+
|
| 954 |
+
Parameters
|
| 955 |
+
----------
|
| 956 |
+
feature : Expression
|
| 957 |
+
feature instance
|
| 958 |
+
N : int
|
| 959 |
+
rolling window size
|
| 960 |
+
|
| 961 |
+
Returns
|
| 962 |
+
----------
|
| 963 |
+
Expression
|
| 964 |
+
a feature instance with rolling max
|
| 965 |
+
"""
|
| 966 |
+
|
| 967 |
+
def __init__(self, feature, N):
|
| 968 |
+
super(Max, self).__init__(feature, N, "max")
|
| 969 |
+
|
| 970 |
+
|
| 971 |
+
class IdxMax(Rolling):
|
| 972 |
+
"""Rolling Max Index
|
| 973 |
+
|
| 974 |
+
Parameters
|
| 975 |
+
----------
|
| 976 |
+
feature : Expression
|
| 977 |
+
feature instance
|
| 978 |
+
N : int
|
| 979 |
+
rolling window size
|
| 980 |
+
|
| 981 |
+
Returns
|
| 982 |
+
----------
|
| 983 |
+
Expression
|
| 984 |
+
a feature instance with rolling max index
|
| 985 |
+
"""
|
| 986 |
+
|
| 987 |
+
def __init__(self, feature, N):
|
| 988 |
+
super(IdxMax, self).__init__(feature, N, "idxmax")
|
| 989 |
+
|
| 990 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 991 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 992 |
+
if self.N == 0:
|
| 993 |
+
series = series.expanding(min_periods=1).apply(lambda x: x.argmax() + 1, raw=True)
|
| 994 |
+
else:
|
| 995 |
+
series = series.rolling(self.N, min_periods=1).apply(lambda x: x.argmax() + 1, raw=True)
|
| 996 |
+
return series
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
class Min(Rolling):
|
| 1000 |
+
"""Rolling Min
|
| 1001 |
+
|
| 1002 |
+
Parameters
|
| 1003 |
+
----------
|
| 1004 |
+
feature : Expression
|
| 1005 |
+
feature instance
|
| 1006 |
+
N : int
|
| 1007 |
+
rolling window size
|
| 1008 |
+
|
| 1009 |
+
Returns
|
| 1010 |
+
----------
|
| 1011 |
+
Expression
|
| 1012 |
+
a feature instance with rolling min
|
| 1013 |
+
"""
|
| 1014 |
+
|
| 1015 |
+
def __init__(self, feature, N):
|
| 1016 |
+
super(Min, self).__init__(feature, N, "min")
|
| 1017 |
+
|
| 1018 |
+
|
| 1019 |
+
class IdxMin(Rolling):
|
| 1020 |
+
"""Rolling Min Index
|
| 1021 |
+
|
| 1022 |
+
Parameters
|
| 1023 |
+
----------
|
| 1024 |
+
feature : Expression
|
| 1025 |
+
feature instance
|
| 1026 |
+
N : int
|
| 1027 |
+
rolling window size
|
| 1028 |
+
|
| 1029 |
+
Returns
|
| 1030 |
+
----------
|
| 1031 |
+
Expression
|
| 1032 |
+
a feature instance with rolling min index
|
| 1033 |
+
"""
|
| 1034 |
+
|
| 1035 |
+
def __init__(self, feature, N):
|
| 1036 |
+
super(IdxMin, self).__init__(feature, N, "idxmin")
|
| 1037 |
+
|
| 1038 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1039 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1040 |
+
if self.N == 0:
|
| 1041 |
+
series = series.expanding(min_periods=1).apply(lambda x: x.argmin() + 1, raw=True)
|
| 1042 |
+
else:
|
| 1043 |
+
series = series.rolling(self.N, min_periods=1).apply(lambda x: x.argmin() + 1, raw=True)
|
| 1044 |
+
return series
|
| 1045 |
+
|
| 1046 |
+
|
| 1047 |
+
class Quantile(Rolling):
|
| 1048 |
+
"""Rolling Quantile
|
| 1049 |
+
|
| 1050 |
+
Parameters
|
| 1051 |
+
----------
|
| 1052 |
+
feature : Expression
|
| 1053 |
+
feature instance
|
| 1054 |
+
N : int
|
| 1055 |
+
rolling window size
|
| 1056 |
+
|
| 1057 |
+
Returns
|
| 1058 |
+
----------
|
| 1059 |
+
Expression
|
| 1060 |
+
a feature instance with rolling quantile
|
| 1061 |
+
"""
|
| 1062 |
+
|
| 1063 |
+
def __init__(self, feature, N, qscore):
|
| 1064 |
+
super(Quantile, self).__init__(feature, N, "quantile")
|
| 1065 |
+
self.qscore = qscore
|
| 1066 |
+
|
| 1067 |
+
def __str__(self):
|
| 1068 |
+
return "{}({},{},{})".format(type(self).__name__, self.feature, self.N, self.qscore)
|
| 1069 |
+
|
| 1070 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1071 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1072 |
+
if self.N == 0:
|
| 1073 |
+
series = series.expanding(min_periods=1).quantile(self.qscore)
|
| 1074 |
+
else:
|
| 1075 |
+
series = series.rolling(self.N, min_periods=1).quantile(self.qscore)
|
| 1076 |
+
return series
|
| 1077 |
+
|
| 1078 |
+
|
| 1079 |
+
class Med(Rolling):
|
| 1080 |
+
"""Rolling Median
|
| 1081 |
+
|
| 1082 |
+
Parameters
|
| 1083 |
+
----------
|
| 1084 |
+
feature : Expression
|
| 1085 |
+
feature instance
|
| 1086 |
+
N : int
|
| 1087 |
+
rolling window size
|
| 1088 |
+
|
| 1089 |
+
Returns
|
| 1090 |
+
----------
|
| 1091 |
+
Expression
|
| 1092 |
+
a feature instance with rolling median
|
| 1093 |
+
"""
|
| 1094 |
+
|
| 1095 |
+
def __init__(self, feature, N):
|
| 1096 |
+
super(Med, self).__init__(feature, N, "median")
|
| 1097 |
+
|
| 1098 |
+
|
| 1099 |
+
class Mad(Rolling):
|
| 1100 |
+
"""Rolling Mean Absolute Deviation
|
| 1101 |
+
|
| 1102 |
+
Parameters
|
| 1103 |
+
----------
|
| 1104 |
+
feature : Expression
|
| 1105 |
+
feature instance
|
| 1106 |
+
N : int
|
| 1107 |
+
rolling window size
|
| 1108 |
+
|
| 1109 |
+
Returns
|
| 1110 |
+
----------
|
| 1111 |
+
Expression
|
| 1112 |
+
a feature instance with rolling mean absolute deviation
|
| 1113 |
+
"""
|
| 1114 |
+
|
| 1115 |
+
def __init__(self, feature, N):
|
| 1116 |
+
super(Mad, self).__init__(feature, N, "mad")
|
| 1117 |
+
|
| 1118 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1119 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1120 |
+
# TODO: implement in Cython
|
| 1121 |
+
|
| 1122 |
+
def mad(x):
|
| 1123 |
+
x1 = x[~np.isnan(x)]
|
| 1124 |
+
return np.mean(np.abs(x1 - x1.mean()))
|
| 1125 |
+
|
| 1126 |
+
if self.N == 0:
|
| 1127 |
+
series = series.expanding(min_periods=1).apply(mad, raw=True)
|
| 1128 |
+
else:
|
| 1129 |
+
series = series.rolling(self.N, min_periods=1).apply(mad, raw=True)
|
| 1130 |
+
return series
|
| 1131 |
+
|
| 1132 |
+
|
| 1133 |
+
class Rank(Rolling):
|
| 1134 |
+
"""Rolling Rank (Percentile)
|
| 1135 |
+
|
| 1136 |
+
Parameters
|
| 1137 |
+
----------
|
| 1138 |
+
feature : Expression
|
| 1139 |
+
feature instance
|
| 1140 |
+
N : int
|
| 1141 |
+
rolling window size
|
| 1142 |
+
|
| 1143 |
+
Returns
|
| 1144 |
+
----------
|
| 1145 |
+
Expression
|
| 1146 |
+
a feature instance with rolling rank
|
| 1147 |
+
"""
|
| 1148 |
+
|
| 1149 |
+
def __init__(self, feature, N):
|
| 1150 |
+
super(Rank, self).__init__(feature, N, "rank")
|
| 1151 |
+
|
| 1152 |
+
# for compatiblity of python 3.7, which doesn't support pandas 1.4.0+ which implements Rolling.rank
|
| 1153 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1154 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1155 |
+
|
| 1156 |
+
rolling_or_expending = series.expanding(min_periods=1) if self.N == 0 else series.rolling(self.N, min_periods=1)
|
| 1157 |
+
if hasattr(rolling_or_expending, "rank"):
|
| 1158 |
+
return rolling_or_expending.rank(pct=True)
|
| 1159 |
+
|
| 1160 |
+
def rank(x):
|
| 1161 |
+
if np.isnan(x[-1]):
|
| 1162 |
+
return np.nan
|
| 1163 |
+
x1 = x[~np.isnan(x)]
|
| 1164 |
+
if x1.shape[0] == 0:
|
| 1165 |
+
return np.nan
|
| 1166 |
+
return percentileofscore(x1, x1[-1]) / 100
|
| 1167 |
+
|
| 1168 |
+
return rolling_or_expending.apply(rank, raw=True)
|
| 1169 |
+
|
| 1170 |
+
|
| 1171 |
+
class Count(Rolling):
|
| 1172 |
+
"""Rolling Count
|
| 1173 |
+
|
| 1174 |
+
Parameters
|
| 1175 |
+
----------
|
| 1176 |
+
feature : Expression
|
| 1177 |
+
feature instance
|
| 1178 |
+
N : int
|
| 1179 |
+
rolling window size
|
| 1180 |
+
|
| 1181 |
+
Returns
|
| 1182 |
+
----------
|
| 1183 |
+
Expression
|
| 1184 |
+
a feature instance with rolling count of number of non-NaN elements
|
| 1185 |
+
"""
|
| 1186 |
+
|
| 1187 |
+
def __init__(self, feature, N):
|
| 1188 |
+
super(Count, self).__init__(feature, N, "count")
|
| 1189 |
+
|
| 1190 |
+
|
| 1191 |
+
class Delta(Rolling):
|
| 1192 |
+
"""Rolling Delta
|
| 1193 |
+
|
| 1194 |
+
Parameters
|
| 1195 |
+
----------
|
| 1196 |
+
feature : Expression
|
| 1197 |
+
feature instance
|
| 1198 |
+
N : int
|
| 1199 |
+
rolling window size
|
| 1200 |
+
|
| 1201 |
+
Returns
|
| 1202 |
+
----------
|
| 1203 |
+
Expression
|
| 1204 |
+
a feature instance with end minus start in rolling window
|
| 1205 |
+
"""
|
| 1206 |
+
|
| 1207 |
+
def __init__(self, feature, N):
|
| 1208 |
+
super(Delta, self).__init__(feature, N, "delta")
|
| 1209 |
+
|
| 1210 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1211 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1212 |
+
if self.N == 0:
|
| 1213 |
+
series = series - series.iloc[0]
|
| 1214 |
+
else:
|
| 1215 |
+
series = series - series.shift(self.N)
|
| 1216 |
+
return series
|
| 1217 |
+
|
| 1218 |
+
|
| 1219 |
+
# TODO:
|
| 1220 |
+
# support pair-wise rolling like `Slope(A, B, N)`
|
| 1221 |
+
class Slope(Rolling):
|
| 1222 |
+
"""Rolling Slope
|
| 1223 |
+
This operator calculate the slope between `idx` and `feature`.
|
| 1224 |
+
(e.g. [<feature_t1>, <feature_t2>, <feature_t3>] and [1, 2, 3])
|
| 1225 |
+
|
| 1226 |
+
Usage Example:
|
| 1227 |
+
- "Slope($close, %d)/$close"
|
| 1228 |
+
|
| 1229 |
+
# TODO:
|
| 1230 |
+
# Some users may want pair-wise rolling like `Slope(A, B, N)`
|
| 1231 |
+
|
| 1232 |
+
Parameters
|
| 1233 |
+
----------
|
| 1234 |
+
feature : Expression
|
| 1235 |
+
feature instance
|
| 1236 |
+
N : int
|
| 1237 |
+
rolling window size
|
| 1238 |
+
|
| 1239 |
+
Returns
|
| 1240 |
+
----------
|
| 1241 |
+
Expression
|
| 1242 |
+
a feature instance with linear regression slope of given window
|
| 1243 |
+
"""
|
| 1244 |
+
|
| 1245 |
+
def __init__(self, feature, N):
|
| 1246 |
+
super(Slope, self).__init__(feature, N, "slope")
|
| 1247 |
+
|
| 1248 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1249 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1250 |
+
if self.N == 0:
|
| 1251 |
+
series = pd.Series(expanding_slope(series.values), index=series.index)
|
| 1252 |
+
else:
|
| 1253 |
+
series = pd.Series(rolling_slope(series.values, self.N), index=series.index)
|
| 1254 |
+
return series
|
| 1255 |
+
|
| 1256 |
+
|
| 1257 |
+
class Rsquare(Rolling):
|
| 1258 |
+
"""Rolling R-value Square
|
| 1259 |
+
|
| 1260 |
+
Parameters
|
| 1261 |
+
----------
|
| 1262 |
+
feature : Expression
|
| 1263 |
+
feature instance
|
| 1264 |
+
N : int
|
| 1265 |
+
rolling window size
|
| 1266 |
+
|
| 1267 |
+
Returns
|
| 1268 |
+
----------
|
| 1269 |
+
Expression
|
| 1270 |
+
a feature instance with linear regression r-value square of given window
|
| 1271 |
+
"""
|
| 1272 |
+
|
| 1273 |
+
def __init__(self, feature, N):
|
| 1274 |
+
super(Rsquare, self).__init__(feature, N, "rsquare")
|
| 1275 |
+
|
| 1276 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1277 |
+
_series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1278 |
+
if self.N == 0:
|
| 1279 |
+
series = pd.Series(expanding_rsquare(_series.values), index=_series.index)
|
| 1280 |
+
else:
|
| 1281 |
+
series = pd.Series(rolling_rsquare(_series.values, self.N), index=_series.index)
|
| 1282 |
+
series.loc[np.isclose(_series.rolling(self.N, min_periods=1).std(), 0, atol=2e-05)] = np.nan
|
| 1283 |
+
return series
|
| 1284 |
+
|
| 1285 |
+
|
| 1286 |
+
class Resi(Rolling):
|
| 1287 |
+
"""Rolling Regression Residuals
|
| 1288 |
+
|
| 1289 |
+
Parameters
|
| 1290 |
+
----------
|
| 1291 |
+
feature : Expression
|
| 1292 |
+
feature instance
|
| 1293 |
+
N : int
|
| 1294 |
+
rolling window size
|
| 1295 |
+
|
| 1296 |
+
Returns
|
| 1297 |
+
----------
|
| 1298 |
+
Expression
|
| 1299 |
+
a feature instance with regression residuals of given window
|
| 1300 |
+
"""
|
| 1301 |
+
|
| 1302 |
+
def __init__(self, feature, N):
|
| 1303 |
+
super(Resi, self).__init__(feature, N, "resi")
|
| 1304 |
+
|
| 1305 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1306 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1307 |
+
if self.N == 0:
|
| 1308 |
+
series = pd.Series(expanding_resi(series.values), index=series.index)
|
| 1309 |
+
else:
|
| 1310 |
+
series = pd.Series(rolling_resi(series.values, self.N), index=series.index)
|
| 1311 |
+
return series
|
| 1312 |
+
|
| 1313 |
+
|
| 1314 |
+
class WMA(Rolling):
|
| 1315 |
+
"""Rolling WMA
|
| 1316 |
+
|
| 1317 |
+
Parameters
|
| 1318 |
+
----------
|
| 1319 |
+
feature : Expression
|
| 1320 |
+
feature instance
|
| 1321 |
+
N : int
|
| 1322 |
+
rolling window size
|
| 1323 |
+
|
| 1324 |
+
Returns
|
| 1325 |
+
----------
|
| 1326 |
+
Expression
|
| 1327 |
+
a feature instance with weighted moving average output
|
| 1328 |
+
"""
|
| 1329 |
+
|
| 1330 |
+
def __init__(self, feature, N):
|
| 1331 |
+
super(WMA, self).__init__(feature, N, "wma")
|
| 1332 |
+
|
| 1333 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1334 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1335 |
+
# TODO: implement in Cython
|
| 1336 |
+
|
| 1337 |
+
def weighted_mean(x):
|
| 1338 |
+
w = np.arange(len(x)) + 1
|
| 1339 |
+
w = w / w.sum()
|
| 1340 |
+
return np.nanmean(w * x)
|
| 1341 |
+
|
| 1342 |
+
if self.N == 0:
|
| 1343 |
+
series = series.expanding(min_periods=1).apply(weighted_mean, raw=True)
|
| 1344 |
+
else:
|
| 1345 |
+
series = series.rolling(self.N, min_periods=1).apply(weighted_mean, raw=True)
|
| 1346 |
+
return series
|
| 1347 |
+
|
| 1348 |
+
|
| 1349 |
+
class EMA(Rolling):
|
| 1350 |
+
"""Rolling Exponential Mean (EMA)
|
| 1351 |
+
|
| 1352 |
+
Parameters
|
| 1353 |
+
----------
|
| 1354 |
+
feature : Expression
|
| 1355 |
+
feature instance
|
| 1356 |
+
N : int, float
|
| 1357 |
+
rolling window size
|
| 1358 |
+
|
| 1359 |
+
Returns
|
| 1360 |
+
----------
|
| 1361 |
+
Expression
|
| 1362 |
+
a feature instance with regression r-value square of given window
|
| 1363 |
+
"""
|
| 1364 |
+
|
| 1365 |
+
def __init__(self, feature, N):
|
| 1366 |
+
super(EMA, self).__init__(feature, N, "ema")
|
| 1367 |
+
|
| 1368 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1369 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1370 |
+
|
| 1371 |
+
def exp_weighted_mean(x):
|
| 1372 |
+
a = 1 - 2 / (1 + len(x))
|
| 1373 |
+
w = a ** np.arange(len(x))[::-1]
|
| 1374 |
+
w /= w.sum()
|
| 1375 |
+
return np.nansum(w * x)
|
| 1376 |
+
|
| 1377 |
+
if self.N == 0:
|
| 1378 |
+
series = series.expanding(min_periods=1).apply(exp_weighted_mean, raw=True)
|
| 1379 |
+
elif 0 < self.N < 1:
|
| 1380 |
+
series = series.ewm(alpha=self.N, min_periods=1).mean()
|
| 1381 |
+
else:
|
| 1382 |
+
series = series.ewm(span=self.N, min_periods=1).mean()
|
| 1383 |
+
return series
|
| 1384 |
+
|
| 1385 |
+
|
| 1386 |
+
#################### Pair-Wise Rolling ####################
|
| 1387 |
+
class PairRolling(ExpressionOps):
|
| 1388 |
+
"""Pair Rolling Operator
|
| 1389 |
+
|
| 1390 |
+
Parameters
|
| 1391 |
+
----------
|
| 1392 |
+
feature_left : Expression
|
| 1393 |
+
feature instance
|
| 1394 |
+
feature_right : Expression
|
| 1395 |
+
feature instance
|
| 1396 |
+
N : int
|
| 1397 |
+
rolling window size
|
| 1398 |
+
|
| 1399 |
+
Returns
|
| 1400 |
+
----------
|
| 1401 |
+
Expression
|
| 1402 |
+
a feature instance with rolling output of two input features
|
| 1403 |
+
"""
|
| 1404 |
+
|
| 1405 |
+
def __init__(self, feature_left, feature_right, N, func):
|
| 1406 |
+
# TODO: in what case will a const be passed into `__init__` as `feature_left` or `feature_right`
|
| 1407 |
+
self.feature_left = feature_left
|
| 1408 |
+
self.feature_right = feature_right
|
| 1409 |
+
self.N = N
|
| 1410 |
+
self.func = func
|
| 1411 |
+
|
| 1412 |
+
def __str__(self):
|
| 1413 |
+
return "{}({},{},{})".format(type(self).__name__, self.feature_left, self.feature_right, self.N)
|
| 1414 |
+
|
| 1415 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1416 |
+
assert any(
|
| 1417 |
+
[isinstance(self.feature_left, Expression), self.feature_right, Expression]
|
| 1418 |
+
), "at least one of two inputs is Expression instance"
|
| 1419 |
+
|
| 1420 |
+
if isinstance(self.feature_left, Expression):
|
| 1421 |
+
series_left = self.feature_left.load(instrument, start_index, end_index, *args)
|
| 1422 |
+
else:
|
| 1423 |
+
series_left = self.feature_left # numeric value
|
| 1424 |
+
if isinstance(self.feature_right, Expression):
|
| 1425 |
+
series_right = self.feature_right.load(instrument, start_index, end_index, *args)
|
| 1426 |
+
else:
|
| 1427 |
+
series_right = self.feature_right
|
| 1428 |
+
|
| 1429 |
+
if self.N == 0:
|
| 1430 |
+
series = getattr(series_left.expanding(min_periods=1), self.func)(series_right)
|
| 1431 |
+
else:
|
| 1432 |
+
series = getattr(series_left.rolling(self.N, min_periods=1), self.func)(series_right)
|
| 1433 |
+
return series
|
| 1434 |
+
|
| 1435 |
+
def get_longest_back_rolling(self):
|
| 1436 |
+
if self.N == 0:
|
| 1437 |
+
return np.inf
|
| 1438 |
+
if isinstance(self.feature_left, Expression):
|
| 1439 |
+
left_br = self.feature_left.get_longest_back_rolling()
|
| 1440 |
+
else:
|
| 1441 |
+
left_br = 0
|
| 1442 |
+
|
| 1443 |
+
if isinstance(self.feature_right, Expression):
|
| 1444 |
+
right_br = self.feature_right.get_longest_back_rolling()
|
| 1445 |
+
else:
|
| 1446 |
+
right_br = 0
|
| 1447 |
+
return max(left_br, right_br)
|
| 1448 |
+
|
| 1449 |
+
def get_extended_window_size(self):
|
| 1450 |
+
if isinstance(self.feature_left, Expression):
|
| 1451 |
+
ll, lr = self.feature_left.get_extended_window_size()
|
| 1452 |
+
else:
|
| 1453 |
+
ll, lr = 0, 0
|
| 1454 |
+
if isinstance(self.feature_right, Expression):
|
| 1455 |
+
rl, rr = self.feature_right.get_extended_window_size()
|
| 1456 |
+
else:
|
| 1457 |
+
rl, rr = 0, 0
|
| 1458 |
+
if self.N == 0:
|
| 1459 |
+
get_module_logger(self.__class__.__name__).warning(
|
| 1460 |
+
"The PairRolling(ATTR, 0) will not be accurately calculated"
|
| 1461 |
+
)
|
| 1462 |
+
return -np.inf, max(lr, rr)
|
| 1463 |
+
else:
|
| 1464 |
+
return max(ll, rl) + self.N - 1, max(lr, rr)
|
| 1465 |
+
|
| 1466 |
+
|
| 1467 |
+
class Corr(PairRolling):
|
| 1468 |
+
"""Rolling Correlation
|
| 1469 |
+
|
| 1470 |
+
Parameters
|
| 1471 |
+
----------
|
| 1472 |
+
feature_left : Expression
|
| 1473 |
+
feature instance
|
| 1474 |
+
feature_right : Expression
|
| 1475 |
+
feature instance
|
| 1476 |
+
N : int
|
| 1477 |
+
rolling window size
|
| 1478 |
+
|
| 1479 |
+
Returns
|
| 1480 |
+
----------
|
| 1481 |
+
Expression
|
| 1482 |
+
a feature instance with rolling correlation of two input features
|
| 1483 |
+
"""
|
| 1484 |
+
|
| 1485 |
+
def __init__(self, feature_left, feature_right, N):
|
| 1486 |
+
super(Corr, self).__init__(feature_left, feature_right, N, "corr")
|
| 1487 |
+
|
| 1488 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1489 |
+
res: pd.Series = super(Corr, self)._load_internal(instrument, start_index, end_index, *args)
|
| 1490 |
+
|
| 1491 |
+
# NOTE: Load uses MemCache, so calling load again will not cause performance degradation
|
| 1492 |
+
series_left = self.feature_left.load(instrument, start_index, end_index, *args)
|
| 1493 |
+
series_right = self.feature_right.load(instrument, start_index, end_index, *args)
|
| 1494 |
+
res.loc[
|
| 1495 |
+
np.isclose(series_left.rolling(self.N, min_periods=1).std(), 0, atol=2e-05)
|
| 1496 |
+
| np.isclose(series_right.rolling(self.N, min_periods=1).std(), 0, atol=2e-05)
|
| 1497 |
+
] = np.nan
|
| 1498 |
+
return res
|
| 1499 |
+
|
| 1500 |
+
|
| 1501 |
+
class Cov(PairRolling):
|
| 1502 |
+
"""Rolling Covariance
|
| 1503 |
+
|
| 1504 |
+
Parameters
|
| 1505 |
+
----------
|
| 1506 |
+
feature_left : Expression
|
| 1507 |
+
feature instance
|
| 1508 |
+
feature_right : Expression
|
| 1509 |
+
feature instance
|
| 1510 |
+
N : int
|
| 1511 |
+
rolling window size
|
| 1512 |
+
|
| 1513 |
+
Returns
|
| 1514 |
+
----------
|
| 1515 |
+
Expression
|
| 1516 |
+
a feature instance with rolling max of two input features
|
| 1517 |
+
"""
|
| 1518 |
+
|
| 1519 |
+
def __init__(self, feature_left, feature_right, N):
|
| 1520 |
+
super(Cov, self).__init__(feature_left, feature_right, N, "cov")
|
| 1521 |
+
|
| 1522 |
+
|
| 1523 |
+
#################### Operator which only support data with time index ####################
|
| 1524 |
+
# Convention
|
| 1525 |
+
# - The name of the operators in this section will start with "T"
|
| 1526 |
+
|
| 1527 |
+
|
| 1528 |
+
class TResample(ElemOperator):
|
| 1529 |
+
def __init__(self, feature, freq, func):
|
| 1530 |
+
"""
|
| 1531 |
+
Resampling the data to target frequency.
|
| 1532 |
+
The resample function of pandas is used.
|
| 1533 |
+
|
| 1534 |
+
- the timestamp will be at the start of the time span after resample.
|
| 1535 |
+
|
| 1536 |
+
Parameters
|
| 1537 |
+
----------
|
| 1538 |
+
feature : Expression
|
| 1539 |
+
An expression for calculating the feature
|
| 1540 |
+
freq : str
|
| 1541 |
+
It will be passed into the resample method for resampling basedn on given frequency
|
| 1542 |
+
func : method
|
| 1543 |
+
The method to get the resampled values
|
| 1544 |
+
Some expression are high frequently used
|
| 1545 |
+
"""
|
| 1546 |
+
self.feature = feature
|
| 1547 |
+
self.freq = freq
|
| 1548 |
+
self.func = func
|
| 1549 |
+
|
| 1550 |
+
def __str__(self):
|
| 1551 |
+
return "{}({},{})".format(type(self).__name__, self.feature, self.freq)
|
| 1552 |
+
|
| 1553 |
+
def _load_internal(self, instrument, start_index, end_index, *args):
|
| 1554 |
+
series = self.feature.load(instrument, start_index, end_index, *args)
|
| 1555 |
+
|
| 1556 |
+
if series.empty:
|
| 1557 |
+
return series
|
| 1558 |
+
else:
|
| 1559 |
+
if self.func == "sum":
|
| 1560 |
+
return getattr(series.resample(self.freq), self.func)(min_count=1)
|
| 1561 |
+
else:
|
| 1562 |
+
return getattr(series.resample(self.freq), self.func)()
|
| 1563 |
+
|
| 1564 |
+
|
| 1565 |
+
TOpsList = [TResample]
|
| 1566 |
+
OpsList = [
|
| 1567 |
+
ChangeInstrument,
|
| 1568 |
+
Rolling,
|
| 1569 |
+
Ref,
|
| 1570 |
+
Max,
|
| 1571 |
+
Min,
|
| 1572 |
+
Sum,
|
| 1573 |
+
Mean,
|
| 1574 |
+
Std,
|
| 1575 |
+
Var,
|
| 1576 |
+
Skew,
|
| 1577 |
+
Kurt,
|
| 1578 |
+
Med,
|
| 1579 |
+
Mad,
|
| 1580 |
+
Slope,
|
| 1581 |
+
Rsquare,
|
| 1582 |
+
Resi,
|
| 1583 |
+
Rank,
|
| 1584 |
+
Quantile,
|
| 1585 |
+
Count,
|
| 1586 |
+
EMA,
|
| 1587 |
+
WMA,
|
| 1588 |
+
Corr,
|
| 1589 |
+
Cov,
|
| 1590 |
+
Delta,
|
| 1591 |
+
Abs,
|
| 1592 |
+
Sign,
|
| 1593 |
+
Log,
|
| 1594 |
+
Power,
|
| 1595 |
+
Add,
|
| 1596 |
+
Sub,
|
| 1597 |
+
Mul,
|
| 1598 |
+
Div,
|
| 1599 |
+
Greater,
|
| 1600 |
+
Less,
|
| 1601 |
+
And,
|
| 1602 |
+
Or,
|
| 1603 |
+
Not,
|
| 1604 |
+
Gt,
|
| 1605 |
+
Ge,
|
| 1606 |
+
Lt,
|
| 1607 |
+
Le,
|
| 1608 |
+
Eq,
|
| 1609 |
+
Ne,
|
| 1610 |
+
Mask,
|
| 1611 |
+
IdxMax,
|
| 1612 |
+
IdxMin,
|
| 1613 |
+
If,
|
| 1614 |
+
Feature,
|
| 1615 |
+
PFeature,
|
| 1616 |
+
] + [TResample]
|
| 1617 |
+
|
| 1618 |
+
|
| 1619 |
+
class OpsWrapper:
|
| 1620 |
+
"""Ops Wrapper"""
|
| 1621 |
+
|
| 1622 |
+
def __init__(self):
|
| 1623 |
+
self._ops = {}
|
| 1624 |
+
|
| 1625 |
+
def reset(self):
|
| 1626 |
+
self._ops = {}
|
| 1627 |
+
|
| 1628 |
+
def register(self, ops_list: List[Union[Type[ExpressionOps], dict]]):
|
| 1629 |
+
"""register operator
|
| 1630 |
+
|
| 1631 |
+
Parameters
|
| 1632 |
+
----------
|
| 1633 |
+
ops_list : List[Union[Type[ExpressionOps], dict]]
|
| 1634 |
+
- if type(ops_list) is List[Type[ExpressionOps]], each element of ops_list represents the operator class, which should be the subclass of `ExpressionOps`.
|
| 1635 |
+
- if type(ops_list) is List[dict], each element of ops_list represents the config of operator, which has the following format:
|
| 1636 |
+
|
| 1637 |
+
.. code-block:: text
|
| 1638 |
+
|
| 1639 |
+
{
|
| 1640 |
+
"class": class_name,
|
| 1641 |
+
"module_path": path,
|
| 1642 |
+
}
|
| 1643 |
+
|
| 1644 |
+
Note: `class` should be the class name of operator, `module_path` should be a python module or path of file.
|
| 1645 |
+
"""
|
| 1646 |
+
for _operator in ops_list:
|
| 1647 |
+
if isinstance(_operator, dict):
|
| 1648 |
+
_ops_class, _ = get_callable_kwargs(_operator)
|
| 1649 |
+
else:
|
| 1650 |
+
_ops_class = _operator
|
| 1651 |
+
|
| 1652 |
+
if not issubclass(_ops_class, (Expression,)):
|
| 1653 |
+
raise TypeError("operator must be subclass of ExpressionOps, not {}".format(_ops_class))
|
| 1654 |
+
|
| 1655 |
+
if _ops_class.__name__ in self._ops:
|
| 1656 |
+
get_module_logger(self.__class__.__name__).warning(
|
| 1657 |
+
"The custom operator [{}] will override the qlib default definition".format(_ops_class.__name__)
|
| 1658 |
+
)
|
| 1659 |
+
self._ops[_ops_class.__name__] = _ops_class
|
| 1660 |
+
|
| 1661 |
+
def __getattr__(self, key):
|
| 1662 |
+
if key not in self._ops:
|
| 1663 |
+
raise AttributeError("The operator [{0}] is not registered".format(key))
|
| 1664 |
+
return self._ops[key]
|
| 1665 |
+
|
| 1666 |
+
|
| 1667 |
+
Operators = OpsWrapper()
|
| 1668 |
+
|
| 1669 |
+
|
| 1670 |
+
def register_all_ops(C):
|
| 1671 |
+
"""register all operator"""
|
| 1672 |
+
logger = get_module_logger("ops")
|
| 1673 |
+
|
| 1674 |
+
from qlib.data.pit import P, PRef # pylint: disable=C0415
|
| 1675 |
+
|
| 1676 |
+
Operators.reset()
|
| 1677 |
+
Operators.register(OpsList + [P, PRef])
|
| 1678 |
+
|
| 1679 |
+
if getattr(C, "custom_ops", None) is not None:
|
| 1680 |
+
Operators.register(C.custom_ops)
|
| 1681 |
+
logger.debug("register custom operator {}".format(C.custom_ops))
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/pit.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
"""
|
| 4 |
+
Qlib follow the logic below to supporting point-in-time database
|
| 5 |
+
|
| 6 |
+
For each stock, the format of its data is <observe_time, feature>. Expression Engine support calculation on such format of data
|
| 7 |
+
|
| 8 |
+
To calculate the feature value f_t at a specific observe time t, data with format <period_time, feature> will be used.
|
| 9 |
+
For example, the average earning of last 4 quarters (period_time) on 20190719 (observe_time)
|
| 10 |
+
|
| 11 |
+
The calculation of both <period_time, feature> and <observe_time, feature> data rely on expression engine. It consists of 2 phases.
|
| 12 |
+
1) calculation <period_time, feature> at each observation time t and it will collasped into a point (just like a normal feature)
|
| 13 |
+
2) concatenate all th collasped data, we will get data with format <observe_time, feature>.
|
| 14 |
+
Qlib will use the operator `P` to perform the collapse.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
from qlib.data.ops import ElemOperator
|
| 20 |
+
from qlib.log import get_module_logger
|
| 21 |
+
from .data import Cal
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class P(ElemOperator):
|
| 25 |
+
def _load_internal(self, instrument, start_index, end_index, freq):
|
| 26 |
+
_calendar = Cal.calendar(freq=freq)
|
| 27 |
+
resample_data = np.empty(end_index - start_index + 1, dtype="float32")
|
| 28 |
+
|
| 29 |
+
for cur_index in range(start_index, end_index + 1):
|
| 30 |
+
cur_time = _calendar[cur_index]
|
| 31 |
+
# To load expression accurately, more historical data are required
|
| 32 |
+
start_ws, end_ws = self.feature.get_extended_window_size()
|
| 33 |
+
if end_ws > 0:
|
| 34 |
+
raise ValueError(
|
| 35 |
+
"PIT database does not support referring to future period (e.g. expressions like `Ref('$$roewa_q', -1)` are not supported"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
# The calculated value will always the last element, so the end_offset is zero.
|
| 39 |
+
try:
|
| 40 |
+
s = self._load_feature(instrument, -start_ws, 0, cur_time)
|
| 41 |
+
resample_data[cur_index - start_index] = s.iloc[-1] if len(s) > 0 else np.nan
|
| 42 |
+
except FileNotFoundError:
|
| 43 |
+
get_module_logger("base").warning(f"WARN: period data not found for {str(self)}")
|
| 44 |
+
return pd.Series(dtype="float32", name=str(self))
|
| 45 |
+
|
| 46 |
+
resample_series = pd.Series(
|
| 47 |
+
resample_data, index=pd.RangeIndex(start_index, end_index + 1), dtype="float32", name=str(self)
|
| 48 |
+
)
|
| 49 |
+
return resample_series
|
| 50 |
+
|
| 51 |
+
def _load_feature(self, instrument, start_index, end_index, cur_time):
|
| 52 |
+
return self.feature.load(instrument, start_index, end_index, cur_time)
|
| 53 |
+
|
| 54 |
+
def get_longest_back_rolling(self):
|
| 55 |
+
# The period data will collapse as a normal feature. So no extending and looking back
|
| 56 |
+
return 0
|
| 57 |
+
|
| 58 |
+
def get_extended_window_size(self):
|
| 59 |
+
# The period data will collapse as a normal feature. So no extending and looking back
|
| 60 |
+
return 0, 0
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
class PRef(P):
|
| 64 |
+
def __init__(self, feature, period):
|
| 65 |
+
super().__init__(feature)
|
| 66 |
+
self.period = period
|
| 67 |
+
|
| 68 |
+
def __str__(self):
|
| 69 |
+
return f"{super().__str__()}[{self.period}]"
|
| 70 |
+
|
| 71 |
+
def _load_feature(self, instrument, start_index, end_index, cur_time):
|
| 72 |
+
return self.feature.load(instrument, start_index, end_index, cur_time, self.period)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/__init__.py
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from .storage import CalendarStorage, InstrumentStorage, FeatureStorage, CalVT, InstVT, InstKT
|
| 5 |
+
|
| 6 |
+
__all__ = ["CalendarStorage", "InstrumentStorage", "FeatureStorage", "CalVT", "InstVT", "InstKT"]
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/file_storage.py
ADDED
|
@@ -0,0 +1,379 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import struct
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Iterable, Union, Dict, Mapping, Tuple, List
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from qlib.utils.time import Freq
|
| 12 |
+
from qlib.utils.resam import resam_calendar
|
| 13 |
+
from qlib.config import C
|
| 14 |
+
from qlib.data.cache import H
|
| 15 |
+
from qlib.log import get_module_logger
|
| 16 |
+
from qlib.data.storage import CalendarStorage, InstrumentStorage, FeatureStorage, CalVT, InstKT, InstVT
|
| 17 |
+
|
| 18 |
+
logger = get_module_logger("file_storage")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FileStorageMixin:
|
| 22 |
+
"""FileStorageMixin, applicable to FileXXXStorage
|
| 23 |
+
Subclasses need to have provider_uri, freq, storage_name, file_name attributes
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
# NOTE: provider_uri priority:
|
| 28 |
+
# 1. self._provider_uri : if provider_uri is provided.
|
| 29 |
+
# 2. provider_uri in qlib.config.C
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def provider_uri(self):
|
| 33 |
+
return C["provider_uri"] if getattr(self, "_provider_uri", None) is None else self._provider_uri
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def dpm(self):
|
| 37 |
+
return (
|
| 38 |
+
C.dpm
|
| 39 |
+
if getattr(self, "_provider_uri", None) is None
|
| 40 |
+
else C.DataPathManager(self._provider_uri, C.mount_path)
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
@property
|
| 44 |
+
def support_freq(self) -> List[str]:
|
| 45 |
+
_v = "_support_freq"
|
| 46 |
+
if hasattr(self, _v):
|
| 47 |
+
return getattr(self, _v)
|
| 48 |
+
if len(self.provider_uri) == 1 and C.DEFAULT_FREQ in self.provider_uri:
|
| 49 |
+
freq_l = filter(
|
| 50 |
+
lambda _freq: not _freq.endswith("_future"),
|
| 51 |
+
map(lambda x: x.stem, self.dpm.get_data_uri(C.DEFAULT_FREQ).joinpath("calendars").glob("*.txt")),
|
| 52 |
+
)
|
| 53 |
+
else:
|
| 54 |
+
freq_l = self.provider_uri.keys()
|
| 55 |
+
freq_l = [Freq(freq) for freq in freq_l]
|
| 56 |
+
setattr(self, _v, freq_l)
|
| 57 |
+
return freq_l
|
| 58 |
+
|
| 59 |
+
@property
|
| 60 |
+
def uri(self) -> Path:
|
| 61 |
+
if self.freq not in self.support_freq:
|
| 62 |
+
raise ValueError(f"{self.storage_name}: {self.provider_uri} does not contain data for {self.freq}")
|
| 63 |
+
return self.dpm.get_data_uri(self.freq).joinpath(f"{self.storage_name}s", self.file_name)
|
| 64 |
+
|
| 65 |
+
def check(self):
|
| 66 |
+
"""check self.uri
|
| 67 |
+
|
| 68 |
+
Raises
|
| 69 |
+
-------
|
| 70 |
+
ValueError
|
| 71 |
+
"""
|
| 72 |
+
if not self.uri.exists():
|
| 73 |
+
raise ValueError(f"{self.storage_name} not exists: {self.uri}")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class FileCalendarStorage(FileStorageMixin, CalendarStorage):
|
| 77 |
+
def __init__(self, freq: str, future: bool, provider_uri: dict = None, **kwargs):
|
| 78 |
+
super(FileCalendarStorage, self).__init__(freq, future, **kwargs)
|
| 79 |
+
self.future = future
|
| 80 |
+
self._provider_uri = None if provider_uri is None else C.DataPathManager.format_provider_uri(provider_uri)
|
| 81 |
+
self.enable_read_cache = True # TODO: make it configurable
|
| 82 |
+
self.region = C["region"]
|
| 83 |
+
|
| 84 |
+
@property
|
| 85 |
+
def file_name(self) -> str:
|
| 86 |
+
return f"{self._freq_file}_future.txt" if self.future else f"{self._freq_file}.txt".lower()
|
| 87 |
+
|
| 88 |
+
@property
|
| 89 |
+
def _freq_file(self) -> str:
|
| 90 |
+
"""the freq to read from file"""
|
| 91 |
+
if not hasattr(self, "_freq_file_cache"):
|
| 92 |
+
freq = Freq(self.freq)
|
| 93 |
+
if freq not in self.support_freq:
|
| 94 |
+
# NOTE: uri
|
| 95 |
+
# 1. If `uri` does not exist
|
| 96 |
+
# - Get the `min_uri` of the closest `freq` under the same "directory" as the `uri`
|
| 97 |
+
# - Read data from `min_uri` and resample to `freq`
|
| 98 |
+
|
| 99 |
+
freq = Freq.get_recent_freq(freq, self.support_freq)
|
| 100 |
+
if freq is None:
|
| 101 |
+
raise ValueError(f"can't find a freq from {self.support_freq} that can resample to {self.freq}!")
|
| 102 |
+
self._freq_file_cache = freq
|
| 103 |
+
return self._freq_file_cache
|
| 104 |
+
|
| 105 |
+
def _read_calendar(self) -> List[CalVT]:
|
| 106 |
+
# NOTE:
|
| 107 |
+
# if we want to accelerate partial reading calendar
|
| 108 |
+
# we can add parameters like `skip_rows: int = 0, n_rows: int = None` to the interface.
|
| 109 |
+
# Currently, it is not supported for the txt-based calendar
|
| 110 |
+
|
| 111 |
+
if not self.uri.exists():
|
| 112 |
+
self._write_calendar(values=[])
|
| 113 |
+
|
| 114 |
+
with self.uri.open("r") as fp:
|
| 115 |
+
res = []
|
| 116 |
+
for line in fp.readlines():
|
| 117 |
+
line = line.strip()
|
| 118 |
+
if len(line) > 0:
|
| 119 |
+
res.append(line)
|
| 120 |
+
return res
|
| 121 |
+
|
| 122 |
+
def _write_calendar(self, values: Iterable[CalVT], mode: str = "wb"):
|
| 123 |
+
with self.uri.open(mode=mode) as fp:
|
| 124 |
+
np.savetxt(fp, values, fmt="%s", encoding="utf-8")
|
| 125 |
+
|
| 126 |
+
@property
|
| 127 |
+
def uri(self) -> Path:
|
| 128 |
+
return self.dpm.get_data_uri(self._freq_file).joinpath(f"{self.storage_name}s", self.file_name)
|
| 129 |
+
|
| 130 |
+
@property
|
| 131 |
+
def data(self) -> List[CalVT]:
|
| 132 |
+
self.check()
|
| 133 |
+
# If cache is enabled, then return cache directly
|
| 134 |
+
if self.enable_read_cache:
|
| 135 |
+
key = "orig_file" + str(self.uri)
|
| 136 |
+
if key not in H["c"]:
|
| 137 |
+
H["c"][key] = self._read_calendar()
|
| 138 |
+
_calendar = H["c"][key]
|
| 139 |
+
else:
|
| 140 |
+
_calendar = self._read_calendar()
|
| 141 |
+
if Freq(self._freq_file) != Freq(self.freq):
|
| 142 |
+
_calendar = resam_calendar(
|
| 143 |
+
np.array(list(map(pd.Timestamp, _calendar))), self._freq_file, self.freq, self.region
|
| 144 |
+
)
|
| 145 |
+
return _calendar
|
| 146 |
+
|
| 147 |
+
def _get_storage_freq(self) -> List[str]:
|
| 148 |
+
return sorted(set(map(lambda x: x.stem.split("_")[0], self.uri.parent.glob("*.txt"))))
|
| 149 |
+
|
| 150 |
+
def extend(self, values: Iterable[CalVT]) -> None:
|
| 151 |
+
self._write_calendar(values, mode="ab")
|
| 152 |
+
|
| 153 |
+
def clear(self) -> None:
|
| 154 |
+
self._write_calendar(values=[])
|
| 155 |
+
|
| 156 |
+
def index(self, value: CalVT) -> int:
|
| 157 |
+
self.check()
|
| 158 |
+
calendar = self._read_calendar()
|
| 159 |
+
return int(np.argwhere(calendar == value)[0])
|
| 160 |
+
|
| 161 |
+
def insert(self, index: int, value: CalVT):
|
| 162 |
+
calendar = self._read_calendar()
|
| 163 |
+
calendar = np.insert(calendar, index, value)
|
| 164 |
+
self._write_calendar(values=calendar)
|
| 165 |
+
|
| 166 |
+
def remove(self, value: CalVT) -> None:
|
| 167 |
+
self.check()
|
| 168 |
+
index = self.index(value)
|
| 169 |
+
calendar = self._read_calendar()
|
| 170 |
+
calendar = np.delete(calendar, index)
|
| 171 |
+
self._write_calendar(values=calendar)
|
| 172 |
+
|
| 173 |
+
def __setitem__(self, i: Union[int, slice], values: Union[CalVT, Iterable[CalVT]]) -> None:
|
| 174 |
+
calendar = self._read_calendar()
|
| 175 |
+
calendar[i] = values
|
| 176 |
+
self._write_calendar(values=calendar)
|
| 177 |
+
|
| 178 |
+
def __delitem__(self, i: Union[int, slice]) -> None:
|
| 179 |
+
self.check()
|
| 180 |
+
calendar = self._read_calendar()
|
| 181 |
+
calendar = np.delete(calendar, i)
|
| 182 |
+
self._write_calendar(values=calendar)
|
| 183 |
+
|
| 184 |
+
def __getitem__(self, i: Union[int, slice]) -> Union[CalVT, List[CalVT]]:
|
| 185 |
+
self.check()
|
| 186 |
+
return self._read_calendar()[i]
|
| 187 |
+
|
| 188 |
+
def __len__(self) -> int:
|
| 189 |
+
return len(self.data)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
class FileInstrumentStorage(FileStorageMixin, InstrumentStorage):
|
| 193 |
+
INSTRUMENT_SEP = "\t"
|
| 194 |
+
INSTRUMENT_START_FIELD = "start_datetime"
|
| 195 |
+
INSTRUMENT_END_FIELD = "end_datetime"
|
| 196 |
+
SYMBOL_FIELD_NAME = "instrument"
|
| 197 |
+
|
| 198 |
+
def __init__(self, market: str, freq: str, provider_uri: dict = None, **kwargs):
|
| 199 |
+
super(FileInstrumentStorage, self).__init__(market, freq, **kwargs)
|
| 200 |
+
self._provider_uri = None if provider_uri is None else C.DataPathManager.format_provider_uri(provider_uri)
|
| 201 |
+
self.file_name = f"{market.lower()}.txt"
|
| 202 |
+
|
| 203 |
+
def _read_instrument(self) -> Dict[InstKT, InstVT]:
|
| 204 |
+
if not self.uri.exists():
|
| 205 |
+
self._write_instrument()
|
| 206 |
+
|
| 207 |
+
_instruments = dict()
|
| 208 |
+
df = pd.read_csv(
|
| 209 |
+
self.uri,
|
| 210 |
+
sep="\t",
|
| 211 |
+
usecols=[0, 1, 2],
|
| 212 |
+
names=[self.SYMBOL_FIELD_NAME, self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD],
|
| 213 |
+
dtype={self.SYMBOL_FIELD_NAME: str},
|
| 214 |
+
parse_dates=[self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD],
|
| 215 |
+
)
|
| 216 |
+
for row in df.itertuples(index=False):
|
| 217 |
+
_instruments.setdefault(row[0], []).append((row[1], row[2]))
|
| 218 |
+
return _instruments
|
| 219 |
+
|
| 220 |
+
def _write_instrument(self, data: Dict[InstKT, InstVT] = None) -> None:
|
| 221 |
+
if not data:
|
| 222 |
+
with self.uri.open("w") as _:
|
| 223 |
+
pass
|
| 224 |
+
return
|
| 225 |
+
|
| 226 |
+
res = []
|
| 227 |
+
for inst, v_list in data.items():
|
| 228 |
+
_df = pd.DataFrame(v_list, columns=[self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD])
|
| 229 |
+
_df[self.SYMBOL_FIELD_NAME] = inst
|
| 230 |
+
res.append(_df)
|
| 231 |
+
|
| 232 |
+
df = pd.concat(res, sort=False)
|
| 233 |
+
df.loc[:, [self.SYMBOL_FIELD_NAME, self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD]].to_csv(
|
| 234 |
+
self.uri, header=False, sep=self.INSTRUMENT_SEP, index=False
|
| 235 |
+
)
|
| 236 |
+
df.to_csv(self.uri, sep="\t", encoding="utf-8", header=False, index=False)
|
| 237 |
+
|
| 238 |
+
def clear(self) -> None:
|
| 239 |
+
self._write_instrument(data={})
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def data(self) -> Dict[InstKT, InstVT]:
|
| 243 |
+
self.check()
|
| 244 |
+
return self._read_instrument()
|
| 245 |
+
|
| 246 |
+
def __setitem__(self, k: InstKT, v: InstVT) -> None:
|
| 247 |
+
inst = self._read_instrument()
|
| 248 |
+
inst[k] = v
|
| 249 |
+
self._write_instrument(inst)
|
| 250 |
+
|
| 251 |
+
def __delitem__(self, k: InstKT) -> None:
|
| 252 |
+
self.check()
|
| 253 |
+
inst = self._read_instrument()
|
| 254 |
+
del inst[k]
|
| 255 |
+
self._write_instrument(inst)
|
| 256 |
+
|
| 257 |
+
def __getitem__(self, k: InstKT) -> InstVT:
|
| 258 |
+
self.check()
|
| 259 |
+
return self._read_instrument()[k]
|
| 260 |
+
|
| 261 |
+
def update(self, *args, **kwargs) -> None:
|
| 262 |
+
if len(args) > 1:
|
| 263 |
+
raise TypeError(f"update expected at most 1 arguments, got {len(args)}")
|
| 264 |
+
inst = self._read_instrument()
|
| 265 |
+
if args:
|
| 266 |
+
other = args[0] # type: dict
|
| 267 |
+
if isinstance(other, Mapping):
|
| 268 |
+
for key in other:
|
| 269 |
+
inst[key] = other[key]
|
| 270 |
+
elif hasattr(other, "keys"):
|
| 271 |
+
for key in other.keys():
|
| 272 |
+
inst[key] = other[key]
|
| 273 |
+
else:
|
| 274 |
+
for key, value in other:
|
| 275 |
+
inst[key] = value
|
| 276 |
+
for key, value in kwargs.items():
|
| 277 |
+
inst[key] = value
|
| 278 |
+
|
| 279 |
+
self._write_instrument(inst)
|
| 280 |
+
|
| 281 |
+
def __len__(self) -> int:
|
| 282 |
+
return len(self.data)
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
class FileFeatureStorage(FileStorageMixin, FeatureStorage):
|
| 286 |
+
def __init__(self, instrument: str, field: str, freq: str, provider_uri: dict = None, **kwargs):
|
| 287 |
+
super(FileFeatureStorage, self).__init__(instrument, field, freq, **kwargs)
|
| 288 |
+
self._provider_uri = None if provider_uri is None else C.DataPathManager.format_provider_uri(provider_uri)
|
| 289 |
+
self.file_name = f"{instrument.lower()}/{field.lower()}.{freq.lower()}.bin"
|
| 290 |
+
|
| 291 |
+
def clear(self):
|
| 292 |
+
with self.uri.open("wb") as _:
|
| 293 |
+
pass
|
| 294 |
+
|
| 295 |
+
@property
|
| 296 |
+
def data(self) -> pd.Series:
|
| 297 |
+
return self[:]
|
| 298 |
+
|
| 299 |
+
def write(self, data_array: Union[List, np.ndarray], index: int = None) -> None:
|
| 300 |
+
if len(data_array) == 0:
|
| 301 |
+
logger.info(
|
| 302 |
+
"len(data_array) == 0, write"
|
| 303 |
+
"if you need to clear the FeatureStorage, please execute: FeatureStorage.clear"
|
| 304 |
+
)
|
| 305 |
+
return
|
| 306 |
+
if not self.uri.exists():
|
| 307 |
+
# write
|
| 308 |
+
index = 0 if index is None else index
|
| 309 |
+
with self.uri.open("wb") as fp:
|
| 310 |
+
np.hstack([index, data_array]).astype("<f").tofile(fp)
|
| 311 |
+
else:
|
| 312 |
+
if index is None or index > self.end_index:
|
| 313 |
+
# append
|
| 314 |
+
index = 0 if index is None else index
|
| 315 |
+
with self.uri.open("ab+") as fp:
|
| 316 |
+
np.hstack([[np.nan] * (index - self.end_index - 1), data_array]).astype("<f").tofile(fp)
|
| 317 |
+
else:
|
| 318 |
+
# rewrite
|
| 319 |
+
with self.uri.open("rb+") as fp:
|
| 320 |
+
_old_data = np.fromfile(fp, dtype="<f")
|
| 321 |
+
_old_index = _old_data[0]
|
| 322 |
+
_old_df = pd.DataFrame(
|
| 323 |
+
_old_data[1:], index=range(_old_index, _old_index + len(_old_data) - 1), columns=["old"]
|
| 324 |
+
)
|
| 325 |
+
fp.seek(0)
|
| 326 |
+
_new_df = pd.DataFrame(data_array, index=range(index, index + len(data_array)), columns=["new"])
|
| 327 |
+
_df = pd.concat([_old_df, _new_df], sort=False, axis=1)
|
| 328 |
+
_df = _df.reindex(range(_df.index.min(), _df.index.max() + 1))
|
| 329 |
+
_df["new"].fillna(_df["old"]).values.astype("<f").tofile(fp)
|
| 330 |
+
|
| 331 |
+
@property
|
| 332 |
+
def start_index(self) -> Union[int, None]:
|
| 333 |
+
if not self.uri.exists():
|
| 334 |
+
return None
|
| 335 |
+
with self.uri.open("rb") as fp:
|
| 336 |
+
index = int(np.frombuffer(fp.read(4), dtype="<f")[0])
|
| 337 |
+
return index
|
| 338 |
+
|
| 339 |
+
@property
|
| 340 |
+
def end_index(self) -> Union[int, None]:
|
| 341 |
+
if not self.uri.exists():
|
| 342 |
+
return None
|
| 343 |
+
# The next data appending index point will be `end_index + 1`
|
| 344 |
+
return self.start_index + len(self) - 1
|
| 345 |
+
|
| 346 |
+
def __getitem__(self, i: Union[int, slice]) -> Union[Tuple[int, float], pd.Series]:
|
| 347 |
+
if not self.uri.exists():
|
| 348 |
+
if isinstance(i, int):
|
| 349 |
+
return None, None
|
| 350 |
+
elif isinstance(i, slice):
|
| 351 |
+
return pd.Series(dtype=np.float32)
|
| 352 |
+
else:
|
| 353 |
+
raise TypeError(f"type(i) = {type(i)}")
|
| 354 |
+
|
| 355 |
+
storage_start_index = self.start_index
|
| 356 |
+
storage_end_index = self.end_index
|
| 357 |
+
with self.uri.open("rb") as fp:
|
| 358 |
+
if isinstance(i, int):
|
| 359 |
+
if storage_start_index > i:
|
| 360 |
+
raise IndexError(f"{i}: start index is {storage_start_index}")
|
| 361 |
+
fp.seek(4 * (i - storage_start_index) + 4)
|
| 362 |
+
return i, struct.unpack("f", fp.read(4))[0]
|
| 363 |
+
elif isinstance(i, slice):
|
| 364 |
+
start_index = storage_start_index if i.start is None else i.start
|
| 365 |
+
end_index = storage_end_index if i.stop is None else i.stop - 1
|
| 366 |
+
si = max(start_index, storage_start_index)
|
| 367 |
+
if si > end_index:
|
| 368 |
+
return pd.Series(dtype=np.float32)
|
| 369 |
+
fp.seek(4 * (si - storage_start_index) + 4)
|
| 370 |
+
# read n bytes
|
| 371 |
+
count = end_index - si + 1
|
| 372 |
+
data = np.frombuffer(fp.read(4 * count), dtype="<f")
|
| 373 |
+
return pd.Series(data, index=pd.RangeIndex(si, si + len(data)))
|
| 374 |
+
else:
|
| 375 |
+
raise TypeError(f"type(i) = {type(i)}")
|
| 376 |
+
|
| 377 |
+
def __len__(self) -> int:
|
| 378 |
+
self.check()
|
| 379 |
+
return self.uri.stat().st_size // 4 - 1
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/storage.py
ADDED
|
@@ -0,0 +1,494 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import re
|
| 5 |
+
from typing import Iterable, overload, Tuple, List, Text, Union, Dict
|
| 6 |
+
|
| 7 |
+
import numpy as np
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from qlib.log import get_module_logger
|
| 10 |
+
|
| 11 |
+
# calendar value type
|
| 12 |
+
CalVT = str
|
| 13 |
+
|
| 14 |
+
# instrument value
|
| 15 |
+
InstVT = List[Tuple[CalVT, CalVT]]
|
| 16 |
+
# instrument key
|
| 17 |
+
InstKT = Text
|
| 18 |
+
|
| 19 |
+
logger = get_module_logger("storage")
|
| 20 |
+
|
| 21 |
+
"""
|
| 22 |
+
If the user is only using it in `qlib`, you can customize Storage to implement only the following methods:
|
| 23 |
+
|
| 24 |
+
class UserCalendarStorage(CalendarStorage):
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def data(self) -> Iterable[CalVT]:
|
| 28 |
+
'''get all data
|
| 29 |
+
|
| 30 |
+
Raises
|
| 31 |
+
------
|
| 32 |
+
ValueError
|
| 33 |
+
If the data(storage) does not exist, raise ValueError
|
| 34 |
+
'''
|
| 35 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `data` method")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class UserInstrumentStorage(InstrumentStorage):
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def data(self) -> Dict[InstKT, InstVT]:
|
| 42 |
+
'''get all data
|
| 43 |
+
|
| 44 |
+
Raises
|
| 45 |
+
------
|
| 46 |
+
ValueError
|
| 47 |
+
If the data(storage) does not exist, raise ValueError
|
| 48 |
+
'''
|
| 49 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `data` method")
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class UserFeatureStorage(FeatureStorage):
|
| 53 |
+
|
| 54 |
+
def __getitem__(self, s: slice) -> pd.Series:
|
| 55 |
+
'''x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step]
|
| 56 |
+
|
| 57 |
+
Returns
|
| 58 |
+
-------
|
| 59 |
+
pd.Series(values, index=pd.RangeIndex(start, len(values))
|
| 60 |
+
|
| 61 |
+
Notes
|
| 62 |
+
-------
|
| 63 |
+
if data(storage) does not exist:
|
| 64 |
+
if isinstance(i, int):
|
| 65 |
+
return (None, None)
|
| 66 |
+
if isinstance(i, slice):
|
| 67 |
+
# return empty pd.Series
|
| 68 |
+
return pd.Series(dtype=np.float32)
|
| 69 |
+
'''
|
| 70 |
+
raise NotImplementedError(
|
| 71 |
+
"Subclass of FeatureStorage must implement `__getitem__(s: slice)` method"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class BaseStorage:
|
| 79 |
+
@property
|
| 80 |
+
def storage_name(self) -> str:
|
| 81 |
+
return re.findall("[A-Z][^A-Z]*", self.__class__.__name__)[-2].lower()
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class CalendarStorage(BaseStorage):
|
| 85 |
+
"""
|
| 86 |
+
The behavior of CalendarStorage's methods and List's methods of the same name remain consistent
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def __init__(self, freq: str, future: bool, **kwargs):
|
| 90 |
+
self.freq = freq
|
| 91 |
+
self.future = future
|
| 92 |
+
self.kwargs = kwargs
|
| 93 |
+
|
| 94 |
+
@property
|
| 95 |
+
def data(self) -> Iterable[CalVT]:
|
| 96 |
+
"""get all data
|
| 97 |
+
|
| 98 |
+
Raises
|
| 99 |
+
------
|
| 100 |
+
ValueError
|
| 101 |
+
If the data(storage) does not exist, raise ValueError
|
| 102 |
+
"""
|
| 103 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `data` method")
|
| 104 |
+
|
| 105 |
+
def clear(self) -> None:
|
| 106 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `clear` method")
|
| 107 |
+
|
| 108 |
+
def extend(self, iterable: Iterable[CalVT]) -> None:
|
| 109 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `extend` method")
|
| 110 |
+
|
| 111 |
+
def index(self, value: CalVT) -> int:
|
| 112 |
+
"""
|
| 113 |
+
Raises
|
| 114 |
+
------
|
| 115 |
+
ValueError
|
| 116 |
+
If the data(storage) does not exist, raise ValueError
|
| 117 |
+
"""
|
| 118 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `index` method")
|
| 119 |
+
|
| 120 |
+
def insert(self, index: int, value: CalVT) -> None:
|
| 121 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `insert` method")
|
| 122 |
+
|
| 123 |
+
def remove(self, value: CalVT) -> None:
|
| 124 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `remove` method")
|
| 125 |
+
|
| 126 |
+
@overload
|
| 127 |
+
def __setitem__(self, i: int, value: CalVT) -> None:
|
| 128 |
+
"""x.__setitem__(i, o) <==> (x[i] = o)"""
|
| 129 |
+
|
| 130 |
+
@overload
|
| 131 |
+
def __setitem__(self, s: slice, value: Iterable[CalVT]) -> None:
|
| 132 |
+
"""x.__setitem__(s, o) <==> (x[s] = o)"""
|
| 133 |
+
|
| 134 |
+
def __setitem__(self, i, value) -> None:
|
| 135 |
+
raise NotImplementedError(
|
| 136 |
+
"Subclass of CalendarStorage must implement `__setitem__(i: int, o: CalVT)`/`__setitem__(s: slice, o: Iterable[CalVT])` method"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
@overload
|
| 140 |
+
def __delitem__(self, i: int) -> None:
|
| 141 |
+
"""x.__delitem__(i) <==> del x[i]"""
|
| 142 |
+
|
| 143 |
+
@overload
|
| 144 |
+
def __delitem__(self, i: slice) -> None:
|
| 145 |
+
"""x.__delitem__(slice(start: int, stop: int, step: int)) <==> del x[start:stop:step]"""
|
| 146 |
+
|
| 147 |
+
def __delitem__(self, i) -> None:
|
| 148 |
+
"""
|
| 149 |
+
Raises
|
| 150 |
+
------
|
| 151 |
+
ValueError
|
| 152 |
+
If the data(storage) does not exist, raise ValueError
|
| 153 |
+
"""
|
| 154 |
+
raise NotImplementedError(
|
| 155 |
+
"Subclass of CalendarStorage must implement `__delitem__(i: int)`/`__delitem__(s: slice)` method"
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
@overload
|
| 159 |
+
def __getitem__(self, s: slice) -> Iterable[CalVT]:
|
| 160 |
+
"""x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step]"""
|
| 161 |
+
|
| 162 |
+
@overload
|
| 163 |
+
def __getitem__(self, i: int) -> CalVT:
|
| 164 |
+
"""x.__getitem__(i) <==> x[i]"""
|
| 165 |
+
|
| 166 |
+
def __getitem__(self, i) -> CalVT:
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
Raises
|
| 170 |
+
------
|
| 171 |
+
ValueError
|
| 172 |
+
If the data(storage) does not exist, raise ValueError
|
| 173 |
+
|
| 174 |
+
"""
|
| 175 |
+
raise NotImplementedError(
|
| 176 |
+
"Subclass of CalendarStorage must implement `__getitem__(i: int)`/`__getitem__(s: slice)` method"
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def __len__(self) -> int:
|
| 180 |
+
"""
|
| 181 |
+
|
| 182 |
+
Raises
|
| 183 |
+
------
|
| 184 |
+
ValueError
|
| 185 |
+
If the data(storage) does not exist, raise ValueError
|
| 186 |
+
|
| 187 |
+
"""
|
| 188 |
+
raise NotImplementedError("Subclass of CalendarStorage must implement `__len__` method")
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
class InstrumentStorage(BaseStorage):
|
| 192 |
+
def __init__(self, market: str, freq: str, **kwargs):
|
| 193 |
+
self.market = market
|
| 194 |
+
self.freq = freq
|
| 195 |
+
self.kwargs = kwargs
|
| 196 |
+
|
| 197 |
+
@property
|
| 198 |
+
def data(self) -> Dict[InstKT, InstVT]:
|
| 199 |
+
"""get all data
|
| 200 |
+
|
| 201 |
+
Raises
|
| 202 |
+
------
|
| 203 |
+
ValueError
|
| 204 |
+
If the data(storage) does not exist, raise ValueError
|
| 205 |
+
"""
|
| 206 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `data` method")
|
| 207 |
+
|
| 208 |
+
def clear(self) -> None:
|
| 209 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `clear` method")
|
| 210 |
+
|
| 211 |
+
def update(self, *args, **kwargs) -> None:
|
| 212 |
+
"""D.update([E, ]**F) -> None. Update D from mapping/iterable E and F.
|
| 213 |
+
|
| 214 |
+
Notes
|
| 215 |
+
------
|
| 216 |
+
If E present and has a .keys() method, does: for k in E: D[k] = E[k]
|
| 217 |
+
|
| 218 |
+
If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v
|
| 219 |
+
|
| 220 |
+
In either case, this is followed by: for k, v in F.items(): D[k] = v
|
| 221 |
+
|
| 222 |
+
"""
|
| 223 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `update` method")
|
| 224 |
+
|
| 225 |
+
def __setitem__(self, k: InstKT, v: InstVT) -> None:
|
| 226 |
+
"""Set self[key] to value."""
|
| 227 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `__setitem__` method")
|
| 228 |
+
|
| 229 |
+
def __delitem__(self, k: InstKT) -> None:
|
| 230 |
+
"""Delete self[key].
|
| 231 |
+
|
| 232 |
+
Raises
|
| 233 |
+
------
|
| 234 |
+
ValueError
|
| 235 |
+
If the data(storage) does not exist, raise ValueError
|
| 236 |
+
"""
|
| 237 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `__delitem__` method")
|
| 238 |
+
|
| 239 |
+
def __getitem__(self, k: InstKT) -> InstVT:
|
| 240 |
+
"""x.__getitem__(k) <==> x[k]"""
|
| 241 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `__getitem__` method")
|
| 242 |
+
|
| 243 |
+
def __len__(self) -> int:
|
| 244 |
+
"""
|
| 245 |
+
|
| 246 |
+
Raises
|
| 247 |
+
------
|
| 248 |
+
ValueError
|
| 249 |
+
If the data(storage) does not exist, raise ValueError
|
| 250 |
+
|
| 251 |
+
"""
|
| 252 |
+
raise NotImplementedError("Subclass of InstrumentStorage must implement `__len__` method")
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
class FeatureStorage(BaseStorage):
|
| 256 |
+
def __init__(self, instrument: str, field: str, freq: str, **kwargs):
|
| 257 |
+
self.instrument = instrument
|
| 258 |
+
self.field = field
|
| 259 |
+
self.freq = freq
|
| 260 |
+
self.kwargs = kwargs
|
| 261 |
+
|
| 262 |
+
@property
|
| 263 |
+
def data(self) -> pd.Series:
|
| 264 |
+
"""get all data
|
| 265 |
+
|
| 266 |
+
Notes
|
| 267 |
+
------
|
| 268 |
+
if data(storage) does not exist, return empty pd.Series: `return pd.Series(dtype=np.float32)`
|
| 269 |
+
"""
|
| 270 |
+
raise NotImplementedError("Subclass of FeatureStorage must implement `data` method")
|
| 271 |
+
|
| 272 |
+
@property
|
| 273 |
+
def start_index(self) -> Union[int, None]:
|
| 274 |
+
"""get FeatureStorage start index
|
| 275 |
+
|
| 276 |
+
Notes
|
| 277 |
+
-----
|
| 278 |
+
If the data(storage) does not exist, return None
|
| 279 |
+
"""
|
| 280 |
+
raise NotImplementedError("Subclass of FeatureStorage must implement `start_index` method")
|
| 281 |
+
|
| 282 |
+
@property
|
| 283 |
+
def end_index(self) -> Union[int, None]:
|
| 284 |
+
"""get FeatureStorage end index
|
| 285 |
+
|
| 286 |
+
Notes
|
| 287 |
+
-----
|
| 288 |
+
The right index of the data range (both sides are closed)
|
| 289 |
+
|
| 290 |
+
The next data appending point will be `end_index + 1`
|
| 291 |
+
|
| 292 |
+
If the data(storage) does not exist, return None
|
| 293 |
+
"""
|
| 294 |
+
raise NotImplementedError("Subclass of FeatureStorage must implement `end_index` method")
|
| 295 |
+
|
| 296 |
+
def clear(self) -> None:
|
| 297 |
+
raise NotImplementedError("Subclass of FeatureStorage must implement `clear` method")
|
| 298 |
+
|
| 299 |
+
def write(self, data_array: Union[List, np.ndarray, Tuple], index: int = None):
|
| 300 |
+
"""Write data_array to FeatureStorage starting from index.
|
| 301 |
+
|
| 302 |
+
Notes
|
| 303 |
+
------
|
| 304 |
+
If index is None, append data_array to feature.
|
| 305 |
+
|
| 306 |
+
If len(data_array) == 0; return
|
| 307 |
+
|
| 308 |
+
If (index - self.end_index) >= 1, self[end_index+1: index] will be filled with np.nan
|
| 309 |
+
|
| 310 |
+
Examples
|
| 311 |
+
---------
|
| 312 |
+
.. code-block::
|
| 313 |
+
|
| 314 |
+
feature:
|
| 315 |
+
3 4
|
| 316 |
+
4 5
|
| 317 |
+
5 6
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
>>> self.write([6, 7], index=6)
|
| 321 |
+
|
| 322 |
+
feature:
|
| 323 |
+
3 4
|
| 324 |
+
4 5
|
| 325 |
+
5 6
|
| 326 |
+
6 6
|
| 327 |
+
7 7
|
| 328 |
+
|
| 329 |
+
>>> self.write([8], index=9)
|
| 330 |
+
|
| 331 |
+
feature:
|
| 332 |
+
3 4
|
| 333 |
+
4 5
|
| 334 |
+
5 6
|
| 335 |
+
6 6
|
| 336 |
+
7 7
|
| 337 |
+
8 np.nan
|
| 338 |
+
9 8
|
| 339 |
+
|
| 340 |
+
>>> self.write([1, np.nan], index=3)
|
| 341 |
+
|
| 342 |
+
feature:
|
| 343 |
+
3 1
|
| 344 |
+
4 np.nan
|
| 345 |
+
5 6
|
| 346 |
+
6 6
|
| 347 |
+
7 7
|
| 348 |
+
8 np.nan
|
| 349 |
+
9 8
|
| 350 |
+
|
| 351 |
+
"""
|
| 352 |
+
raise NotImplementedError("Subclass of FeatureStorage must implement `write` method")
|
| 353 |
+
|
| 354 |
+
def rebase(self, start_index: int = None, end_index: int = None):
|
| 355 |
+
"""Rebase the start_index and end_index of the FeatureStorage.
|
| 356 |
+
|
| 357 |
+
start_index and end_index are closed intervals: [start_index, end_index]
|
| 358 |
+
|
| 359 |
+
Examples
|
| 360 |
+
---------
|
| 361 |
+
|
| 362 |
+
.. code-block::
|
| 363 |
+
|
| 364 |
+
feature:
|
| 365 |
+
3 4
|
| 366 |
+
4 5
|
| 367 |
+
5 6
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
>>> self.rebase(start_index=4)
|
| 371 |
+
|
| 372 |
+
feature:
|
| 373 |
+
4 5
|
| 374 |
+
5 6
|
| 375 |
+
|
| 376 |
+
>>> self.rebase(start_index=3)
|
| 377 |
+
|
| 378 |
+
feature:
|
| 379 |
+
3 np.nan
|
| 380 |
+
4 5
|
| 381 |
+
5 6
|
| 382 |
+
|
| 383 |
+
>>> self.write([3], index=3)
|
| 384 |
+
|
| 385 |
+
feature:
|
| 386 |
+
3 3
|
| 387 |
+
4 5
|
| 388 |
+
5 6
|
| 389 |
+
|
| 390 |
+
>>> self.rebase(end_index=4)
|
| 391 |
+
|
| 392 |
+
feature:
|
| 393 |
+
3 3
|
| 394 |
+
4 5
|
| 395 |
+
|
| 396 |
+
>>> self.write([6, 7, 8], index=4)
|
| 397 |
+
|
| 398 |
+
feature:
|
| 399 |
+
3 3
|
| 400 |
+
4 6
|
| 401 |
+
5 7
|
| 402 |
+
6 8
|
| 403 |
+
|
| 404 |
+
>>> self.rebase(start_index=4, end_index=5)
|
| 405 |
+
|
| 406 |
+
feature:
|
| 407 |
+
4 6
|
| 408 |
+
5 7
|
| 409 |
+
|
| 410 |
+
"""
|
| 411 |
+
storage_si = self.start_index
|
| 412 |
+
storage_ei = self.end_index
|
| 413 |
+
if storage_si is None or storage_ei is None:
|
| 414 |
+
raise ValueError("storage.start_index or storage.end_index is None, storage may not exist")
|
| 415 |
+
|
| 416 |
+
start_index = storage_si if start_index is None else start_index
|
| 417 |
+
end_index = storage_ei if end_index is None else end_index
|
| 418 |
+
|
| 419 |
+
if start_index is None or end_index is None:
|
| 420 |
+
logger.warning("both start_index and end_index are None, or storage does not exist; rebase is ignored")
|
| 421 |
+
return
|
| 422 |
+
|
| 423 |
+
if start_index < 0 or end_index < 0:
|
| 424 |
+
logger.warning("start_index or end_index cannot be less than 0")
|
| 425 |
+
return
|
| 426 |
+
if start_index > end_index:
|
| 427 |
+
logger.warning(
|
| 428 |
+
f"start_index({start_index}) > end_index({end_index}), rebase is ignored; "
|
| 429 |
+
f"if you need to clear the FeatureStorage, please execute: FeatureStorage.clear"
|
| 430 |
+
)
|
| 431 |
+
return
|
| 432 |
+
|
| 433 |
+
if start_index <= storage_si:
|
| 434 |
+
self.write([np.nan] * (storage_si - start_index), start_index)
|
| 435 |
+
else:
|
| 436 |
+
self.rewrite(self[start_index:].values, start_index)
|
| 437 |
+
|
| 438 |
+
if end_index >= self.end_index:
|
| 439 |
+
self.write([np.nan] * (end_index - self.end_index))
|
| 440 |
+
else:
|
| 441 |
+
self.rewrite(self[: end_index + 1].values, start_index)
|
| 442 |
+
|
| 443 |
+
def rewrite(self, data: Union[List, np.ndarray, Tuple], index: int):
|
| 444 |
+
"""overwrite all data in FeatureStorage with data
|
| 445 |
+
|
| 446 |
+
Parameters
|
| 447 |
+
----------
|
| 448 |
+
data: Union[List, np.ndarray, Tuple]
|
| 449 |
+
data
|
| 450 |
+
index: int
|
| 451 |
+
data start index
|
| 452 |
+
"""
|
| 453 |
+
self.clear()
|
| 454 |
+
self.write(data, index)
|
| 455 |
+
|
| 456 |
+
@overload
|
| 457 |
+
def __getitem__(self, s: slice) -> pd.Series:
|
| 458 |
+
"""x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step]
|
| 459 |
+
|
| 460 |
+
Returns
|
| 461 |
+
-------
|
| 462 |
+
pd.Series(values, index=pd.RangeIndex(start, len(values))
|
| 463 |
+
"""
|
| 464 |
+
|
| 465 |
+
@overload
|
| 466 |
+
def __getitem__(self, i: int) -> Tuple[int, float]:
|
| 467 |
+
"""x.__getitem__(y) <==> x[y]"""
|
| 468 |
+
|
| 469 |
+
def __getitem__(self, i) -> Union[Tuple[int, float], pd.Series]:
|
| 470 |
+
"""x.__getitem__(y) <==> x[y]
|
| 471 |
+
|
| 472 |
+
Notes
|
| 473 |
+
-------
|
| 474 |
+
if data(storage) does not exist:
|
| 475 |
+
if isinstance(i, int):
|
| 476 |
+
return (None, None)
|
| 477 |
+
if isinstance(i, slice):
|
| 478 |
+
# return empty pd.Series
|
| 479 |
+
return pd.Series(dtype=np.float32)
|
| 480 |
+
"""
|
| 481 |
+
raise NotImplementedError(
|
| 482 |
+
"Subclass of FeatureStorage must implement `__getitem__(i: int)`/`__getitem__(s: slice)` method"
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
def __len__(self) -> int:
|
| 486 |
+
"""
|
| 487 |
+
|
| 488 |
+
Raises
|
| 489 |
+
------
|
| 490 |
+
ValueError
|
| 491 |
+
If the data(storage) does not exist, raise ValueError
|
| 492 |
+
|
| 493 |
+
"""
|
| 494 |
+
raise NotImplementedError("Subclass of FeatureStorage must implement `__len__` method")
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/log.py
ADDED
|
@@ -0,0 +1,262 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Optional, Text, Dict, Any
|
| 7 |
+
import re
|
| 8 |
+
from logging import config as logging_config
|
| 9 |
+
from time import time
|
| 10 |
+
from contextlib import contextmanager
|
| 11 |
+
|
| 12 |
+
from .config import C
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class MetaLogger(type):
|
| 16 |
+
def __new__(mcs, name, bases, attrs): # pylint: disable=C0204
|
| 17 |
+
wrapper_dict = logging.Logger.__dict__.copy()
|
| 18 |
+
for key, val in wrapper_dict.items():
|
| 19 |
+
if key not in attrs and key != "__reduce__":
|
| 20 |
+
attrs[key] = val
|
| 21 |
+
return type.__new__(mcs, name, bases, attrs)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class QlibLogger(metaclass=MetaLogger):
|
| 25 |
+
"""
|
| 26 |
+
Customized logger for Qlib.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, module_name):
|
| 30 |
+
self.module_name = module_name
|
| 31 |
+
# this feature name conflicts with the attribute with Logger
|
| 32 |
+
# rename it to avoid some corner cases that result in comparing `str` and `int`
|
| 33 |
+
self.__level = 0
|
| 34 |
+
|
| 35 |
+
@property
|
| 36 |
+
def logger(self):
|
| 37 |
+
logger = logging.getLogger(self.module_name)
|
| 38 |
+
logger.setLevel(self.__level)
|
| 39 |
+
return logger
|
| 40 |
+
|
| 41 |
+
def setLevel(self, level):
|
| 42 |
+
self.__level = level
|
| 43 |
+
|
| 44 |
+
def __getattr__(self, name):
|
| 45 |
+
# During unpickling, python will call __getattr__. Use this line to avoid maximum recursion error.
|
| 46 |
+
if name in {"__setstate__"}:
|
| 47 |
+
raise AttributeError
|
| 48 |
+
return self.logger.__getattribute__(name)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _QLibLoggerManager:
|
| 52 |
+
def __init__(self):
|
| 53 |
+
self._loggers = {}
|
| 54 |
+
|
| 55 |
+
def setLevel(self, level):
|
| 56 |
+
for logger in self._loggers.values():
|
| 57 |
+
logger.setLevel(level)
|
| 58 |
+
|
| 59 |
+
def __call__(self, module_name, level: Optional[int] = None) -> QlibLogger:
|
| 60 |
+
"""
|
| 61 |
+
Get a logger for a specific module.
|
| 62 |
+
|
| 63 |
+
:param module_name: str
|
| 64 |
+
Logic module name.
|
| 65 |
+
:param level: int
|
| 66 |
+
:return: Logger
|
| 67 |
+
Logger object.
|
| 68 |
+
"""
|
| 69 |
+
if level is None:
|
| 70 |
+
level = C.logging_level
|
| 71 |
+
|
| 72 |
+
if not module_name.startswith("qlib."):
|
| 73 |
+
# Add a prefix of qlib. when the requested ``module_name`` doesn't start with ``qlib.``.
|
| 74 |
+
# If the module_name is already qlib.xxx, we do not format here. Otherwise, it will become qlib.qlib.xxx.
|
| 75 |
+
module_name = "qlib.{}".format(module_name)
|
| 76 |
+
|
| 77 |
+
# Get logger.
|
| 78 |
+
module_logger = self._loggers.setdefault(module_name, QlibLogger(module_name))
|
| 79 |
+
module_logger.setLevel(level)
|
| 80 |
+
return module_logger
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
get_module_logger = _QLibLoggerManager()
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class TimeInspector:
|
| 87 |
+
timer_logger = get_module_logger("timer")
|
| 88 |
+
|
| 89 |
+
time_marks = []
|
| 90 |
+
|
| 91 |
+
@classmethod
|
| 92 |
+
def set_time_mark(cls):
|
| 93 |
+
"""
|
| 94 |
+
Set a time mark with current time, and this time mark will push into a stack.
|
| 95 |
+
:return: float
|
| 96 |
+
A timestamp for current time.
|
| 97 |
+
"""
|
| 98 |
+
_time = time()
|
| 99 |
+
cls.time_marks.append(_time)
|
| 100 |
+
return _time
|
| 101 |
+
|
| 102 |
+
@classmethod
|
| 103 |
+
def pop_time_mark(cls):
|
| 104 |
+
"""
|
| 105 |
+
Pop last time mark from stack.
|
| 106 |
+
"""
|
| 107 |
+
return cls.time_marks.pop()
|
| 108 |
+
|
| 109 |
+
@classmethod
|
| 110 |
+
def get_cost_time(cls):
|
| 111 |
+
"""
|
| 112 |
+
Get last time mark from stack, calculate time diff with current time.
|
| 113 |
+
:return: float
|
| 114 |
+
Time diff calculated by last time mark with current time.
|
| 115 |
+
"""
|
| 116 |
+
cost_time = time() - cls.time_marks.pop()
|
| 117 |
+
return cost_time
|
| 118 |
+
|
| 119 |
+
@classmethod
|
| 120 |
+
def log_cost_time(cls, info="Done"):
|
| 121 |
+
"""
|
| 122 |
+
Get last time mark from stack, calculate time diff with current time, and log time diff and info.
|
| 123 |
+
:param info: str
|
| 124 |
+
Info that will be logged into stdout.
|
| 125 |
+
"""
|
| 126 |
+
cost_time = time() - cls.time_marks.pop()
|
| 127 |
+
cls.timer_logger.info("Time cost: {0:.3f}s | {1}".format(cost_time, info))
|
| 128 |
+
|
| 129 |
+
@classmethod
|
| 130 |
+
@contextmanager
|
| 131 |
+
def logt(cls, name="", show_start=False):
|
| 132 |
+
"""logt.
|
| 133 |
+
Log the time of the inside code
|
| 134 |
+
|
| 135 |
+
Parameters
|
| 136 |
+
----------
|
| 137 |
+
name :
|
| 138 |
+
name
|
| 139 |
+
show_start :
|
| 140 |
+
show_start
|
| 141 |
+
"""
|
| 142 |
+
if show_start:
|
| 143 |
+
cls.timer_logger.info(f"{name} Begin")
|
| 144 |
+
cls.set_time_mark()
|
| 145 |
+
try:
|
| 146 |
+
yield None
|
| 147 |
+
finally:
|
| 148 |
+
pass
|
| 149 |
+
cls.log_cost_time(info=f"{name} Done")
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def set_log_with_config(log_config: Dict[Text, Any]):
|
| 153 |
+
"""set log with config
|
| 154 |
+
|
| 155 |
+
:param log_config:
|
| 156 |
+
:return:
|
| 157 |
+
"""
|
| 158 |
+
logging_config.dictConfig(log_config)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class LogFilter(logging.Filter):
|
| 162 |
+
def __init__(self, param=None):
|
| 163 |
+
super().__init__()
|
| 164 |
+
self.param = param
|
| 165 |
+
|
| 166 |
+
@staticmethod
|
| 167 |
+
def match_msg(filter_str, msg):
|
| 168 |
+
match = False
|
| 169 |
+
try:
|
| 170 |
+
if re.match(filter_str, msg):
|
| 171 |
+
match = True
|
| 172 |
+
except Exception:
|
| 173 |
+
pass
|
| 174 |
+
return match
|
| 175 |
+
|
| 176 |
+
def filter(self, record):
|
| 177 |
+
allow = True
|
| 178 |
+
if isinstance(self.param, str):
|
| 179 |
+
allow = not self.match_msg(self.param, record.msg)
|
| 180 |
+
elif isinstance(self.param, list):
|
| 181 |
+
allow = not any(self.match_msg(p, record.msg) for p in self.param)
|
| 182 |
+
return allow
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def set_global_logger_level(level: int, return_orig_handler_level: bool = False):
|
| 186 |
+
"""set qlib.xxx logger handlers level
|
| 187 |
+
|
| 188 |
+
Parameters
|
| 189 |
+
----------
|
| 190 |
+
level: int
|
| 191 |
+
logger level
|
| 192 |
+
|
| 193 |
+
return_orig_handler_level: bool
|
| 194 |
+
return origin handler level map
|
| 195 |
+
|
| 196 |
+
Examples
|
| 197 |
+
---------
|
| 198 |
+
|
| 199 |
+
.. code-block:: python
|
| 200 |
+
|
| 201 |
+
import qlib
|
| 202 |
+
import logging
|
| 203 |
+
from qlib.log import get_module_logger, set_global_logger_level
|
| 204 |
+
qlib.init()
|
| 205 |
+
|
| 206 |
+
tmp_logger_01 = get_module_logger("tmp_logger_01", level=logging.INFO)
|
| 207 |
+
tmp_logger_01.info("1. tmp_logger_01 info show")
|
| 208 |
+
|
| 209 |
+
global_level = logging.WARNING + 1
|
| 210 |
+
set_global_logger_level(global_level)
|
| 211 |
+
tmp_logger_02 = get_module_logger("tmp_logger_02", level=logging.INFO)
|
| 212 |
+
tmp_logger_02.log(msg="2. tmp_logger_02 log show", level=global_level)
|
| 213 |
+
|
| 214 |
+
tmp_logger_01.info("3. tmp_logger_01 info do not show")
|
| 215 |
+
|
| 216 |
+
"""
|
| 217 |
+
_handler_level_map = {}
|
| 218 |
+
qlib_logger = logging.root.manager.loggerDict.get("qlib", None) # pylint: disable=E1101
|
| 219 |
+
if qlib_logger is not None:
|
| 220 |
+
for _handler in qlib_logger.handlers:
|
| 221 |
+
_handler_level_map[_handler] = _handler.level
|
| 222 |
+
_handler.level = level
|
| 223 |
+
return _handler_level_map if return_orig_handler_level else None
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@contextmanager
|
| 227 |
+
def set_global_logger_level_cm(level: int):
|
| 228 |
+
"""set qlib.xxx logger handlers level to use contextmanager
|
| 229 |
+
|
| 230 |
+
Parameters
|
| 231 |
+
----------
|
| 232 |
+
level: int
|
| 233 |
+
logger level
|
| 234 |
+
|
| 235 |
+
Examples
|
| 236 |
+
---------
|
| 237 |
+
|
| 238 |
+
.. code-block:: python
|
| 239 |
+
|
| 240 |
+
import qlib
|
| 241 |
+
import logging
|
| 242 |
+
from qlib.log import get_module_logger, set_global_logger_level_cm
|
| 243 |
+
qlib.init()
|
| 244 |
+
|
| 245 |
+
tmp_logger_01 = get_module_logger("tmp_logger_01", level=logging.INFO)
|
| 246 |
+
tmp_logger_01.info("1. tmp_logger_01 info show")
|
| 247 |
+
|
| 248 |
+
global_level = logging.WARNING + 1
|
| 249 |
+
with set_global_logger_level_cm(global_level):
|
| 250 |
+
tmp_logger_02 = get_module_logger("tmp_logger_02", level=logging.INFO)
|
| 251 |
+
tmp_logger_02.log(msg="2. tmp_logger_02 log show", level=global_level)
|
| 252 |
+
tmp_logger_01.info("3. tmp_logger_01 info do not show")
|
| 253 |
+
|
| 254 |
+
tmp_logger_01.info("4. tmp_logger_01 info show")
|
| 255 |
+
|
| 256 |
+
"""
|
| 257 |
+
_handler_level_map = set_global_logger_level(level, return_orig_handler_level=True)
|
| 258 |
+
try:
|
| 259 |
+
yield
|
| 260 |
+
finally:
|
| 261 |
+
for _handler, _level in _handler_level_map.items():
|
| 262 |
+
_handler.level = _level
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import warnings
|
| 5 |
+
|
| 6 |
+
from .base import Model
|
| 7 |
+
|
| 8 |
+
__all__ = ["Model", "warnings"]
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/base.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
import abc
|
| 4 |
+
from typing import Text, Union
|
| 5 |
+
from ..utils.serial import Serializable
|
| 6 |
+
from ..data.dataset import Dataset
|
| 7 |
+
from ..data.dataset.weight import Reweighter
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BaseModel(Serializable, metaclass=abc.ABCMeta):
|
| 11 |
+
"""Modeling things"""
|
| 12 |
+
|
| 13 |
+
@abc.abstractmethod
|
| 14 |
+
def predict(self, *args, **kwargs) -> object:
|
| 15 |
+
"""Make predictions after modeling things"""
|
| 16 |
+
|
| 17 |
+
def __call__(self, *args, **kwargs) -> object:
|
| 18 |
+
"""leverage Python syntactic sugar to make the models' behaviors like functions"""
|
| 19 |
+
return self.predict(*args, **kwargs)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class Model(BaseModel):
|
| 23 |
+
"""Learnable Models"""
|
| 24 |
+
|
| 25 |
+
def fit(self, dataset: Dataset, reweighter: Reweighter):
|
| 26 |
+
"""
|
| 27 |
+
Learn model from the base model
|
| 28 |
+
|
| 29 |
+
.. note::
|
| 30 |
+
|
| 31 |
+
The attribute names of learned model should `not` start with '_'. So that the model could be
|
| 32 |
+
dumped to disk.
|
| 33 |
+
|
| 34 |
+
The following code example shows how to retrieve `x_train`, `y_train` and `w_train` from the `dataset`:
|
| 35 |
+
|
| 36 |
+
.. code-block:: Python
|
| 37 |
+
|
| 38 |
+
# get features and labels
|
| 39 |
+
df_train, df_valid = dataset.prepare(
|
| 40 |
+
["train", "valid"], col_set=["feature", "label"], data_key=DataHandlerLP.DK_L
|
| 41 |
+
)
|
| 42 |
+
x_train, y_train = df_train["feature"], df_train["label"]
|
| 43 |
+
x_valid, y_valid = df_valid["feature"], df_valid["label"]
|
| 44 |
+
|
| 45 |
+
# get weights
|
| 46 |
+
try:
|
| 47 |
+
wdf_train, wdf_valid = dataset.prepare(["train", "valid"], col_set=["weight"],
|
| 48 |
+
data_key=DataHandlerLP.DK_L)
|
| 49 |
+
w_train, w_valid = wdf_train["weight"], wdf_valid["weight"]
|
| 50 |
+
except KeyError as e:
|
| 51 |
+
w_train = pd.DataFrame(np.ones_like(y_train.values), index=y_train.index)
|
| 52 |
+
w_valid = pd.DataFrame(np.ones_like(y_valid.values), index=y_valid.index)
|
| 53 |
+
|
| 54 |
+
Parameters
|
| 55 |
+
----------
|
| 56 |
+
dataset : Dataset
|
| 57 |
+
dataset will generate the processed data from model training.
|
| 58 |
+
|
| 59 |
+
"""
|
| 60 |
+
raise NotImplementedError()
|
| 61 |
+
|
| 62 |
+
@abc.abstractmethod
|
| 63 |
+
def predict(self, dataset: Dataset, segment: Union[Text, slice] = "test") -> object:
|
| 64 |
+
"""give prediction given Dataset
|
| 65 |
+
|
| 66 |
+
Parameters
|
| 67 |
+
----------
|
| 68 |
+
dataset : Dataset
|
| 69 |
+
dataset will generate the processed dataset from model training.
|
| 70 |
+
|
| 71 |
+
segment : Text or slice
|
| 72 |
+
dataset will use this segment to prepare data. (default=test)
|
| 73 |
+
|
| 74 |
+
Returns
|
| 75 |
+
-------
|
| 76 |
+
Prediction results with certain type such as `pandas.Series`.
|
| 77 |
+
"""
|
| 78 |
+
raise NotImplementedError()
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
class ModelFT(Model):
|
| 82 |
+
"""Model (F)ine(t)unable"""
|
| 83 |
+
|
| 84 |
+
@abc.abstractmethod
|
| 85 |
+
def finetune(self, dataset: Dataset):
|
| 86 |
+
"""finetune model based given dataset
|
| 87 |
+
|
| 88 |
+
A typical use case of finetuning model with qlib.workflow.R
|
| 89 |
+
|
| 90 |
+
.. code-block:: python
|
| 91 |
+
|
| 92 |
+
# start exp to train init model
|
| 93 |
+
with R.start(experiment_name="init models"):
|
| 94 |
+
model.fit(dataset)
|
| 95 |
+
R.save_objects(init_model=model)
|
| 96 |
+
rid = R.get_recorder().id
|
| 97 |
+
|
| 98 |
+
# Finetune model based on previous trained model
|
| 99 |
+
with R.start(experiment_name="finetune model"):
|
| 100 |
+
recorder = R.get_recorder(recorder_id=rid, experiment_name="init models")
|
| 101 |
+
model = recorder.load_object("init_model")
|
| 102 |
+
model.finetune(dataset, num_boost_round=10)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
Parameters
|
| 106 |
+
----------
|
| 107 |
+
dataset : Dataset
|
| 108 |
+
dataset will generate the processed dataset from model training.
|
| 109 |
+
"""
|
| 110 |
+
raise NotImplementedError()
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/__init__.py
ADDED
|
File without changes
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/ensemble.py
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Ensemble module can merge the objects in an Ensemble. For example, if there are many submodels predictions, we may need to merge them into an ensemble prediction.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Union
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from qlib.utils import FLATTEN_TUPLE, flatten_dict
|
| 11 |
+
from qlib.log import get_module_logger
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Ensemble:
|
| 15 |
+
"""Merge the ensemble_dict into an ensemble object.
|
| 16 |
+
|
| 17 |
+
For example: {Rollinga_b: object, Rollingb_c: object} -> object
|
| 18 |
+
|
| 19 |
+
When calling this class:
|
| 20 |
+
|
| 21 |
+
Args:
|
| 22 |
+
ensemble_dict (dict): the ensemble dict like {name: things} waiting for merging
|
| 23 |
+
|
| 24 |
+
Returns:
|
| 25 |
+
object: the ensemble object
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
def __call__(self, ensemble_dict: dict, *args, **kwargs):
|
| 29 |
+
raise NotImplementedError(f"Please implement the `__call__` method.")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SingleKeyEnsemble(Ensemble):
|
| 33 |
+
"""
|
| 34 |
+
Extract the object if there is only one key and value in the dict. Make the result more readable.
|
| 35 |
+
{Only key: Only value} -> Only value
|
| 36 |
+
|
| 37 |
+
If there is more than 1 key or less than 1 key, then do nothing.
|
| 38 |
+
Even you can run this recursively to make dict more readable.
|
| 39 |
+
|
| 40 |
+
NOTE: Default runs recursively.
|
| 41 |
+
|
| 42 |
+
When calling this class:
|
| 43 |
+
|
| 44 |
+
Args:
|
| 45 |
+
ensemble_dict (dict): the dict. The key of the dict will be ignored.
|
| 46 |
+
|
| 47 |
+
Returns:
|
| 48 |
+
dict: the readable dict.
|
| 49 |
+
"""
|
| 50 |
+
|
| 51 |
+
def __call__(self, ensemble_dict: Union[dict, object], recursion: bool = True) -> object:
|
| 52 |
+
if not isinstance(ensemble_dict, dict):
|
| 53 |
+
return ensemble_dict
|
| 54 |
+
if recursion:
|
| 55 |
+
tmp_dict = {}
|
| 56 |
+
for k, v in ensemble_dict.items():
|
| 57 |
+
tmp_dict[k] = self(v, recursion)
|
| 58 |
+
ensemble_dict = tmp_dict
|
| 59 |
+
keys = list(ensemble_dict.keys())
|
| 60 |
+
if len(keys) == 1:
|
| 61 |
+
ensemble_dict = ensemble_dict[keys[0]]
|
| 62 |
+
return ensemble_dict
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class RollingEnsemble(Ensemble):
|
| 66 |
+
"""Merge a dict of rolling dataframe like `prediction` or `IC` into an ensemble.
|
| 67 |
+
|
| 68 |
+
NOTE: The values of dict must be pd.DataFrame, and have the index "datetime".
|
| 69 |
+
|
| 70 |
+
When calling this class:
|
| 71 |
+
|
| 72 |
+
Args:
|
| 73 |
+
ensemble_dict (dict): a dict like {"A": pd.DataFrame, "B": pd.DataFrame}.
|
| 74 |
+
The key of the dict will be ignored.
|
| 75 |
+
|
| 76 |
+
Returns:
|
| 77 |
+
pd.DataFrame: the complete result of rolling.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
def __call__(self, ensemble_dict: dict) -> pd.DataFrame:
|
| 81 |
+
get_module_logger("RollingEnsemble").info(f"keys in group: {list(ensemble_dict.keys())}")
|
| 82 |
+
artifact_list = list(ensemble_dict.values())
|
| 83 |
+
artifact_list.sort(key=lambda x: x.index.get_level_values("datetime").min())
|
| 84 |
+
artifact = pd.concat(artifact_list)
|
| 85 |
+
# If there are duplicated predition, use the latest perdiction
|
| 86 |
+
artifact = artifact[~artifact.index.duplicated(keep="last")]
|
| 87 |
+
artifact = artifact.sort_index()
|
| 88 |
+
return artifact
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
class AverageEnsemble(Ensemble):
|
| 92 |
+
"""
|
| 93 |
+
Average and standardize a dict of same shape dataframe like `prediction` or `IC` into an ensemble.
|
| 94 |
+
|
| 95 |
+
NOTE: The values of dict must be pd.DataFrame, and have the index "datetime". If it is a nested dict, then flat it.
|
| 96 |
+
|
| 97 |
+
When calling this class:
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
ensemble_dict (dict): a dict like {"A": pd.DataFrame, "B": pd.DataFrame}.
|
| 101 |
+
The key of the dict will be ignored.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
pd.DataFrame: the complete result of averaging and standardizing.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
def __call__(self, ensemble_dict: dict) -> pd.DataFrame:
|
| 108 |
+
"""using sample:
|
| 109 |
+
from qlib.model.ens.ensemble import AverageEnsemble
|
| 110 |
+
pred_res['new_key_name'] = AverageEnsemble()(predict_dict)
|
| 111 |
+
|
| 112 |
+
Parameters
|
| 113 |
+
----------
|
| 114 |
+
ensemble_dict : dict
|
| 115 |
+
Dictionary you want to ensemble
|
| 116 |
+
|
| 117 |
+
Returns
|
| 118 |
+
-------
|
| 119 |
+
pd.DataFrame
|
| 120 |
+
The dictionary including ensenbling result
|
| 121 |
+
"""
|
| 122 |
+
# need to flatten the nested dict
|
| 123 |
+
ensemble_dict = flatten_dict(ensemble_dict, sep=FLATTEN_TUPLE)
|
| 124 |
+
get_module_logger("AverageEnsemble").info(f"keys in group: {list(ensemble_dict.keys())}")
|
| 125 |
+
values = list(ensemble_dict.values())
|
| 126 |
+
# NOTE: this may change the style underlying data!!!!
|
| 127 |
+
# from pd.DataFrame to pd.Series
|
| 128 |
+
results = pd.concat(values, axis=1)
|
| 129 |
+
results = results.groupby("datetime", group_keys=False).apply(lambda df: (df - df.mean()) / df.std())
|
| 130 |
+
results = results.mean(axis=1)
|
| 131 |
+
results = results.sort_index()
|
| 132 |
+
return results
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/group.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Group can group a set of objects based on `group_func` and change them to a dict.
|
| 6 |
+
After group, we provide a method to reduce them.
|
| 7 |
+
|
| 8 |
+
For example:
|
| 9 |
+
|
| 10 |
+
group: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}}
|
| 11 |
+
reduce: {(A,B): {C1: object, C2: object}} -> {(A,B): object}
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
from qlib.model.ens.ensemble import Ensemble, RollingEnsemble
|
| 16 |
+
from typing import Callable
|
| 17 |
+
from joblib import Parallel, delayed
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class Group:
|
| 21 |
+
"""Group the objects based on dict"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, group_func=None, ens: Ensemble = None):
|
| 24 |
+
"""
|
| 25 |
+
Init Group.
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
group_func (Callable, optional): Given a dict and return the group key and one of the group elements.
|
| 29 |
+
|
| 30 |
+
For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}}
|
| 31 |
+
|
| 32 |
+
Defaults to None.
|
| 33 |
+
|
| 34 |
+
ens (Ensemble, optional): If not None, do ensemble for grouped value after grouping.
|
| 35 |
+
"""
|
| 36 |
+
self._group_func = group_func
|
| 37 |
+
self._ens_func = ens
|
| 38 |
+
|
| 39 |
+
def group(self, *args, **kwargs) -> dict:
|
| 40 |
+
"""
|
| 41 |
+
Group a set of objects and change them to a dict.
|
| 42 |
+
|
| 43 |
+
For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}}
|
| 44 |
+
|
| 45 |
+
Returns:
|
| 46 |
+
dict: grouped dict
|
| 47 |
+
"""
|
| 48 |
+
if isinstance(getattr(self, "_group_func", None), Callable):
|
| 49 |
+
return self._group_func(*args, **kwargs)
|
| 50 |
+
else:
|
| 51 |
+
raise NotImplementedError(f"Please specify valid `group_func`.")
|
| 52 |
+
|
| 53 |
+
def reduce(self, *args, **kwargs) -> dict:
|
| 54 |
+
"""
|
| 55 |
+
Reduce grouped dict.
|
| 56 |
+
|
| 57 |
+
For example: {(A,B): {C1: object, C2: object}} -> {(A,B): object}
|
| 58 |
+
|
| 59 |
+
Returns:
|
| 60 |
+
dict: reduced dict
|
| 61 |
+
"""
|
| 62 |
+
if isinstance(getattr(self, "_ens_func", None), Callable):
|
| 63 |
+
return self._ens_func(*args, **kwargs)
|
| 64 |
+
else:
|
| 65 |
+
raise NotImplementedError(f"Please specify valid `_ens_func`.")
|
| 66 |
+
|
| 67 |
+
def __call__(self, ungrouped_dict: dict, n_jobs: int = 1, verbose: int = 0, *args, **kwargs) -> dict:
|
| 68 |
+
"""
|
| 69 |
+
Group the ungrouped_dict into different groups.
|
| 70 |
+
|
| 71 |
+
Args:
|
| 72 |
+
ungrouped_dict (dict): the ungrouped dict waiting for grouping like {name: things}
|
| 73 |
+
|
| 74 |
+
Returns:
|
| 75 |
+
dict: grouped_dict like {G1: object, G2: object}
|
| 76 |
+
n_jobs: how many progress you need.
|
| 77 |
+
verbose: the print mode for Parallel.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
# NOTE: The multiprocessing will raise error if you use `Serializable`
|
| 81 |
+
# Because the `Serializable` will affect the behaviors of pickle
|
| 82 |
+
grouped_dict = self.group(ungrouped_dict, *args, **kwargs)
|
| 83 |
+
|
| 84 |
+
key_l = []
|
| 85 |
+
job_l = []
|
| 86 |
+
for key, value in grouped_dict.items():
|
| 87 |
+
key_l.append(key)
|
| 88 |
+
job_l.append(delayed(Group.reduce)(self, value))
|
| 89 |
+
return dict(zip(key_l, Parallel(n_jobs=n_jobs, verbose=verbose)(job_l)))
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
class RollingGroup(Group):
|
| 93 |
+
"""Group the rolling dict"""
|
| 94 |
+
|
| 95 |
+
def group(self, rolling_dict: dict) -> dict:
|
| 96 |
+
"""Given an rolling dict likes {(A,B,R): things}, return the grouped dict likes {(A,B): {R:things}}
|
| 97 |
+
|
| 98 |
+
NOTE: There is an assumption which is the rolling key is at the end of the key tuple, because the rolling results always need to be ensemble firstly.
|
| 99 |
+
|
| 100 |
+
Args:
|
| 101 |
+
rolling_dict (dict): an rolling dict. If the key is not a tuple, then do nothing.
|
| 102 |
+
|
| 103 |
+
Returns:
|
| 104 |
+
dict: grouped dict
|
| 105 |
+
"""
|
| 106 |
+
grouped_dict = {}
|
| 107 |
+
for key, values in rolling_dict.items():
|
| 108 |
+
if isinstance(key, tuple):
|
| 109 |
+
grouped_dict.setdefault(key[:-1], {})[key[-1]] = values
|
| 110 |
+
else:
|
| 111 |
+
raise TypeError(f"Expected `tuple` type, but got a value `{key}`")
|
| 112 |
+
return grouped_dict
|
| 113 |
+
|
| 114 |
+
def __init__(self, ens=RollingEnsemble()):
|
| 115 |
+
super().__init__(ens=ens)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/__init__.py
ADDED
|
File without changes
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/base.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Interfaces to interpret models
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
from abc import abstractmethod
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class FeatureInt:
|
| 13 |
+
"""Feature (Int)erpreter"""
|
| 14 |
+
|
| 15 |
+
@abstractmethod
|
| 16 |
+
def get_feature_importance(self) -> pd.Series:
|
| 17 |
+
"""get feature importance
|
| 18 |
+
|
| 19 |
+
Returns
|
| 20 |
+
-------
|
| 21 |
+
The index is the feature name.
|
| 22 |
+
|
| 23 |
+
The greater the value, the higher importance.
|
| 24 |
+
"""
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class LightGBMFInt(FeatureInt):
|
| 28 |
+
"""LightGBM (F)eature (Int)erpreter"""
|
| 29 |
+
|
| 30 |
+
def __init__(self):
|
| 31 |
+
self.model = None
|
| 32 |
+
|
| 33 |
+
def get_feature_importance(self, *args, **kwargs) -> pd.Series:
|
| 34 |
+
"""get feature importance
|
| 35 |
+
|
| 36 |
+
Notes
|
| 37 |
+
-----
|
| 38 |
+
parameters reference:
|
| 39 |
+
https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html?highlight=feature_importance#lightgbm.Booster.feature_importance
|
| 40 |
+
"""
|
| 41 |
+
return pd.Series(
|
| 42 |
+
self.model.feature_importance(*args, **kwargs), index=self.model.feature_name()
|
| 43 |
+
).sort_values( # pylint: disable=E1101
|
| 44 |
+
ascending=False
|
| 45 |
+
)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from .task import MetaTask
|
| 5 |
+
from .dataset import MetaTaskDataset
|
| 6 |
+
|
| 7 |
+
__all__ = ["MetaTask", "MetaTaskDataset"]
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/dataset.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import abc
|
| 5 |
+
from qlib.model.meta.task import MetaTask
|
| 6 |
+
from typing import Dict, Union, List, Tuple, Text
|
| 7 |
+
from ...utils.serial import Serializable
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class MetaTaskDataset(Serializable, metaclass=abc.ABCMeta):
|
| 11 |
+
"""
|
| 12 |
+
A dataset fetching the data in a meta-level.
|
| 13 |
+
|
| 14 |
+
A Meta Dataset is responsible for
|
| 15 |
+
|
| 16 |
+
- input tasks(e.g. Qlib tasks) and prepare meta tasks
|
| 17 |
+
|
| 18 |
+
- meta task contains more information than normal tasks (e.g. input data for meta model)
|
| 19 |
+
|
| 20 |
+
The learnt pattern could transfer to other meta dataset. The following cases should be supported
|
| 21 |
+
|
| 22 |
+
- A meta-model trained on meta-dataset A and then applied to meta-dataset B
|
| 23 |
+
|
| 24 |
+
- Some pattern are shared between meta-dataset A and B, so meta-input on meta-dataset A are used when meta model are applied on meta-dataset-B
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
def __init__(self, segments: Union[Dict[Text, Tuple], float], *args, **kwargs):
|
| 28 |
+
"""
|
| 29 |
+
The meta-dataset maintains a list of meta-tasks when it is initialized.
|
| 30 |
+
|
| 31 |
+
The segments indicates the way to divide the data
|
| 32 |
+
|
| 33 |
+
The duty of the `__init__` function of MetaTaskDataset
|
| 34 |
+
- initialize the tasks
|
| 35 |
+
"""
|
| 36 |
+
super().__init__(*args, **kwargs)
|
| 37 |
+
self.segments = segments
|
| 38 |
+
|
| 39 |
+
def prepare_tasks(self, segments: Union[List[Text], Text], *args, **kwargs) -> List[MetaTask]:
|
| 40 |
+
"""
|
| 41 |
+
Prepare the data in each meta-task and ready for training.
|
| 42 |
+
|
| 43 |
+
The following code example shows how to retrieve a list of meta-tasks from the `meta_dataset`:
|
| 44 |
+
|
| 45 |
+
.. code-block:: Python
|
| 46 |
+
|
| 47 |
+
# get the train segment and the test segment, both of them are lists
|
| 48 |
+
train_meta_tasks, test_meta_tasks = meta_dataset.prepare_tasks(["train", "test"])
|
| 49 |
+
|
| 50 |
+
Parameters
|
| 51 |
+
----------
|
| 52 |
+
segments: Union[List[Text], Tuple[Text], Text]
|
| 53 |
+
the info to select data
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
list:
|
| 58 |
+
A list of the prepared data of each meta-task for training the meta-model. For multiple segments [seg1, seg2, ... , segN], the returned list will be [[tasks in seg1], [tasks in seg2], ... , [tasks in segN]].
|
| 59 |
+
Each task is a meta task
|
| 60 |
+
"""
|
| 61 |
+
if isinstance(segments, (list, tuple)):
|
| 62 |
+
return [self._prepare_seg(seg) for seg in segments]
|
| 63 |
+
elif isinstance(segments, str):
|
| 64 |
+
return self._prepare_seg(segments)
|
| 65 |
+
else:
|
| 66 |
+
raise NotImplementedError(f"This type of input is not supported")
|
| 67 |
+
|
| 68 |
+
@abc.abstractmethod
|
| 69 |
+
def _prepare_seg(self, segment: Text):
|
| 70 |
+
"""
|
| 71 |
+
prepare a single segment of data for training data
|
| 72 |
+
|
| 73 |
+
Parameters
|
| 74 |
+
----------
|
| 75 |
+
seg : Text
|
| 76 |
+
the name of the segment
|
| 77 |
+
"""
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/model.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import abc
|
| 5 |
+
from typing import List
|
| 6 |
+
|
| 7 |
+
from .dataset import MetaTaskDataset
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class MetaModel(metaclass=abc.ABCMeta):
|
| 11 |
+
"""
|
| 12 |
+
The meta-model guiding the model learning.
|
| 13 |
+
|
| 14 |
+
The word `Guiding` can be categorized into two types based on the stage of model learning
|
| 15 |
+
- The definition of learning tasks: Please refer to docs of `MetaTaskModel`
|
| 16 |
+
- Controlling the learning process of models: Please refer to the docs of `MetaGuideModel`
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
@abc.abstractmethod
|
| 20 |
+
def fit(self, *args, **kwargs):
|
| 21 |
+
"""
|
| 22 |
+
The training process of the meta-model.
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
@abc.abstractmethod
|
| 26 |
+
def inference(self, *args, **kwargs) -> object:
|
| 27 |
+
"""
|
| 28 |
+
The inference process of the meta-model.
|
| 29 |
+
|
| 30 |
+
Returns
|
| 31 |
+
-------
|
| 32 |
+
object:
|
| 33 |
+
Some information to guide the model learning
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class MetaTaskModel(MetaModel):
|
| 38 |
+
"""
|
| 39 |
+
This type of meta-model deals with base task definitions. The meta-model creates tasks for training new base forecasting models after it is trained. `prepare_tasks` directly modifies the task definitions.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
def fit(self, meta_dataset: MetaTaskDataset):
|
| 43 |
+
"""
|
| 44 |
+
The MetaTaskModel is expected to get prepared MetaTask from meta_dataset.
|
| 45 |
+
And then it will learn knowledge from the meta tasks
|
| 46 |
+
"""
|
| 47 |
+
raise NotImplementedError(f"Please implement the `fit` method")
|
| 48 |
+
|
| 49 |
+
def inference(self, meta_dataset: MetaTaskDataset) -> List[dict]:
|
| 50 |
+
"""
|
| 51 |
+
MetaTaskModel will make inference on the meta_dataset
|
| 52 |
+
The MetaTaskModel is expected to get prepared MetaTask from meta_dataset.
|
| 53 |
+
Then it will create modified task with Qlib format which can be executed by Qlib trainer.
|
| 54 |
+
|
| 55 |
+
Returns
|
| 56 |
+
-------
|
| 57 |
+
List[dict]:
|
| 58 |
+
A list of modified task definitions.
|
| 59 |
+
|
| 60 |
+
"""
|
| 61 |
+
raise NotImplementedError(f"Please implement the `inference` method")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class MetaGuideModel(MetaModel):
|
| 65 |
+
"""
|
| 66 |
+
This type of meta-model aims to guide the training process of the base model. The meta-model interacts with the base forecasting models during their training process.
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
@abc.abstractmethod
|
| 70 |
+
def fit(self, *args, **kwargs):
|
| 71 |
+
pass
|
| 72 |
+
|
| 73 |
+
@abc.abstractmethod
|
| 74 |
+
def inference(self, *args, **kwargs):
|
| 75 |
+
pass
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/task.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from qlib.data.dataset import Dataset
|
| 5 |
+
from ...utils import init_instance_by_config
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class MetaTask:
|
| 9 |
+
"""
|
| 10 |
+
A single meta-task, a meta-dataset contains a list of them.
|
| 11 |
+
It serves as a component as in MetaDatasetDS
|
| 12 |
+
|
| 13 |
+
The data processing is different
|
| 14 |
+
|
| 15 |
+
- the processed input may be different between training and testing
|
| 16 |
+
|
| 17 |
+
- When training, the X, y, X_test, y_test in training tasks are necessary (# PROC_MODE_FULL #)
|
| 18 |
+
but not necessary in test tasks. (# PROC_MODE_TEST #)
|
| 19 |
+
- When the meta model can be transferred into other dataset, only meta_info is necessary (# PROC_MODE_TRANSFER #)
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
PROC_MODE_FULL = "full"
|
| 23 |
+
PROC_MODE_TEST = "test"
|
| 24 |
+
PROC_MODE_TRANSFER = "transfer"
|
| 25 |
+
|
| 26 |
+
def __init__(self, task: dict, meta_info: object, mode: str = PROC_MODE_FULL):
|
| 27 |
+
"""
|
| 28 |
+
The `__init__` func is responsible for
|
| 29 |
+
|
| 30 |
+
- store the task
|
| 31 |
+
- store the origin input data for
|
| 32 |
+
- process the input data for meta data
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
task : dict
|
| 37 |
+
the task to be enhanced by meta model
|
| 38 |
+
|
| 39 |
+
meta_info : object
|
| 40 |
+
the input for meta model
|
| 41 |
+
"""
|
| 42 |
+
self.task = task
|
| 43 |
+
self.meta_info = meta_info # the original meta input information, it will be processed later
|
| 44 |
+
self.mode = mode
|
| 45 |
+
|
| 46 |
+
def get_dataset(self) -> Dataset:
|
| 47 |
+
return init_instance_by_config(self.task["dataset"], accept_types=Dataset)
|
| 48 |
+
|
| 49 |
+
def get_meta_input(self) -> object:
|
| 50 |
+
"""
|
| 51 |
+
Return the **processed** meta_info
|
| 52 |
+
"""
|
| 53 |
+
return self.meta_info
|
| 54 |
+
|
| 55 |
+
def __repr__(self):
|
| 56 |
+
return f"MetaTask(task={self.task}, meta_info={self.meta_info})"
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from .base import RiskModel
|
| 5 |
+
from .poet import POETCovEstimator
|
| 6 |
+
from .shrink import ShrinkCovEstimator
|
| 7 |
+
from .structured import StructuredCovEstimator
|
| 8 |
+
|
| 9 |
+
__all__ = [
|
| 10 |
+
"RiskModel",
|
| 11 |
+
"POETCovEstimator",
|
| 12 |
+
"ShrinkCovEstimator",
|
| 13 |
+
"StructuredCovEstimator",
|
| 14 |
+
]
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/base.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import inspect
|
| 5 |
+
import numpy as np
|
| 6 |
+
import pandas as pd
|
| 7 |
+
from typing import Union
|
| 8 |
+
|
| 9 |
+
from qlib.model.base import BaseModel
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class RiskModel(BaseModel):
|
| 13 |
+
"""Risk Model
|
| 14 |
+
|
| 15 |
+
A risk model is used to estimate the covariance matrix of stock returns.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
MASK_NAN = "mask"
|
| 19 |
+
FILL_NAN = "fill"
|
| 20 |
+
IGNORE_NAN = "ignore"
|
| 21 |
+
|
| 22 |
+
def __init__(self, nan_option: str = "ignore", assume_centered: bool = False, scale_return: bool = True):
|
| 23 |
+
"""
|
| 24 |
+
Args:
|
| 25 |
+
nan_option (str): nan handling option (`ignore`/`mask`/`fill`).
|
| 26 |
+
assume_centered (bool): whether the data is assumed to be centered.
|
| 27 |
+
scale_return (bool): whether scale returns as percentage.
|
| 28 |
+
"""
|
| 29 |
+
# nan
|
| 30 |
+
assert nan_option in [
|
| 31 |
+
self.MASK_NAN,
|
| 32 |
+
self.FILL_NAN,
|
| 33 |
+
self.IGNORE_NAN,
|
| 34 |
+
], f"`nan_option={nan_option}` is not supported"
|
| 35 |
+
self.nan_option = nan_option
|
| 36 |
+
|
| 37 |
+
self.assume_centered = assume_centered
|
| 38 |
+
self.scale_return = scale_return
|
| 39 |
+
|
| 40 |
+
def predict(
|
| 41 |
+
self,
|
| 42 |
+
X: Union[pd.Series, pd.DataFrame, np.ndarray],
|
| 43 |
+
return_corr: bool = False,
|
| 44 |
+
is_price: bool = True,
|
| 45 |
+
return_decomposed_components=False,
|
| 46 |
+
) -> Union[pd.DataFrame, np.ndarray, tuple]:
|
| 47 |
+
"""
|
| 48 |
+
Args:
|
| 49 |
+
X (pd.Series, pd.DataFrame or np.ndarray): data from which to estimate the covariance,
|
| 50 |
+
with variables as columns and observations as rows.
|
| 51 |
+
return_corr (bool): whether return the correlation matrix.
|
| 52 |
+
is_price (bool): whether `X` contains price (if not assume stock returns).
|
| 53 |
+
return_decomposed_components (bool): whether return decomposed components of the covariance matrix.
|
| 54 |
+
|
| 55 |
+
Returns:
|
| 56 |
+
pd.DataFrame or np.ndarray: estimated covariance (or correlation).
|
| 57 |
+
"""
|
| 58 |
+
assert (
|
| 59 |
+
not return_corr or not return_decomposed_components
|
| 60 |
+
), "Can only return either correlation matrix or decomposed components."
|
| 61 |
+
|
| 62 |
+
# transform input into 2D array
|
| 63 |
+
if not isinstance(X, (pd.Series, pd.DataFrame)):
|
| 64 |
+
columns = None
|
| 65 |
+
else:
|
| 66 |
+
if isinstance(X.index, pd.MultiIndex):
|
| 67 |
+
if isinstance(X, pd.DataFrame):
|
| 68 |
+
X = X.iloc[:, 0].unstack(level="instrument") # always use the first column
|
| 69 |
+
else:
|
| 70 |
+
X = X.unstack(level="instrument")
|
| 71 |
+
else:
|
| 72 |
+
# X is 2D DataFrame
|
| 73 |
+
pass
|
| 74 |
+
columns = X.columns # will be used to restore dataframe
|
| 75 |
+
X = X.values
|
| 76 |
+
|
| 77 |
+
# calculate pct_change
|
| 78 |
+
if is_price:
|
| 79 |
+
X = X[1:] / X[:-1] - 1 # NOTE: resulting `n - 1` rows
|
| 80 |
+
|
| 81 |
+
# scale return
|
| 82 |
+
if self.scale_return:
|
| 83 |
+
X *= 100
|
| 84 |
+
|
| 85 |
+
# handle nan and centered
|
| 86 |
+
X = self._preprocess(X)
|
| 87 |
+
|
| 88 |
+
# return decomposed components if needed
|
| 89 |
+
if return_decomposed_components:
|
| 90 |
+
assert (
|
| 91 |
+
"return_decomposed_components" in inspect.getfullargspec(self._predict).args
|
| 92 |
+
), "This risk model does not support return decomposed components of the covariance matrix "
|
| 93 |
+
|
| 94 |
+
F, cov_b, var_u = self._predict(X, return_decomposed_components=True) # pylint: disable=E1123
|
| 95 |
+
return F, cov_b, var_u
|
| 96 |
+
|
| 97 |
+
# estimate covariance
|
| 98 |
+
S = self._predict(X)
|
| 99 |
+
|
| 100 |
+
# return correlation if needed
|
| 101 |
+
if return_corr:
|
| 102 |
+
vola = np.sqrt(np.diag(S))
|
| 103 |
+
corr = S / np.outer(vola, vola)
|
| 104 |
+
if columns is None:
|
| 105 |
+
return corr
|
| 106 |
+
return pd.DataFrame(corr, index=columns, columns=columns)
|
| 107 |
+
|
| 108 |
+
# return covariance
|
| 109 |
+
if columns is None:
|
| 110 |
+
return S
|
| 111 |
+
return pd.DataFrame(S, index=columns, columns=columns)
|
| 112 |
+
|
| 113 |
+
def _predict(self, X: np.ndarray) -> np.ndarray:
|
| 114 |
+
"""covariance estimation implementation
|
| 115 |
+
|
| 116 |
+
This method should be overridden by child classes.
|
| 117 |
+
|
| 118 |
+
By default, this method implements the empirical covariance estimation.
|
| 119 |
+
|
| 120 |
+
Args:
|
| 121 |
+
X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows).
|
| 122 |
+
|
| 123 |
+
Returns:
|
| 124 |
+
np.ndarray: covariance matrix.
|
| 125 |
+
"""
|
| 126 |
+
xTx = np.asarray(X.T.dot(X))
|
| 127 |
+
N = len(X)
|
| 128 |
+
if isinstance(X, np.ma.MaskedArray):
|
| 129 |
+
M = 1 - X.mask
|
| 130 |
+
N = M.T.dot(M) # each pair has distinct number of samples
|
| 131 |
+
return xTx / N
|
| 132 |
+
|
| 133 |
+
def _preprocess(self, X: np.ndarray) -> Union[np.ndarray, np.ma.MaskedArray]:
|
| 134 |
+
"""handle nan and centerize data
|
| 135 |
+
|
| 136 |
+
Note:
|
| 137 |
+
if `nan_option='mask'` then the returned array will be `np.ma.MaskedArray`.
|
| 138 |
+
"""
|
| 139 |
+
# handle nan
|
| 140 |
+
if self.nan_option == self.FILL_NAN:
|
| 141 |
+
X = np.nan_to_num(X)
|
| 142 |
+
elif self.nan_option == self.MASK_NAN:
|
| 143 |
+
X = np.ma.masked_invalid(X)
|
| 144 |
+
# centralize
|
| 145 |
+
if not self.assume_centered:
|
| 146 |
+
X = X - np.nanmean(X, axis=0)
|
| 147 |
+
return X
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/poet.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
|
| 3 |
+
from qlib.model.riskmodel import RiskModel
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class POETCovEstimator(RiskModel):
|
| 7 |
+
"""Principal Orthogonal Complement Thresholding Estimator (POET)
|
| 8 |
+
|
| 9 |
+
Reference:
|
| 10 |
+
[1] Fan, J., Liao, Y., & Mincheva, M. (2013). Large covariance estimation by thresholding principal orthogonal complements.
|
| 11 |
+
Journal of the Royal Statistical Society. Series B: Statistical Methodology, 75(4), 603–680. https://doi.org/10.1111/rssb.12016
|
| 12 |
+
[2] http://econweb.rutgers.edu/yl1114/papers/poet/POET.m
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
THRESH_SOFT = "soft"
|
| 16 |
+
THRESH_HARD = "hard"
|
| 17 |
+
THRESH_SCAD = "scad"
|
| 18 |
+
|
| 19 |
+
def __init__(self, num_factors: int = 0, thresh: float = 1.0, thresh_method: str = "soft", **kwargs):
|
| 20 |
+
"""
|
| 21 |
+
Args:
|
| 22 |
+
num_factors (int): number of factors (if set to zero, no factor model will be used).
|
| 23 |
+
thresh (float): the positive constant for thresholding.
|
| 24 |
+
thresh_method (str): thresholding method, which can be
|
| 25 |
+
- 'soft': soft thresholding.
|
| 26 |
+
- 'hard': hard thresholding.
|
| 27 |
+
- 'scad': scad thresholding.
|
| 28 |
+
kwargs: see `RiskModel` for more information.
|
| 29 |
+
"""
|
| 30 |
+
super().__init__(**kwargs)
|
| 31 |
+
|
| 32 |
+
assert num_factors >= 0, "`num_factors` requires a positive integer"
|
| 33 |
+
self.num_factors = num_factors
|
| 34 |
+
|
| 35 |
+
assert thresh >= 0, "`thresh` requires a positive float number"
|
| 36 |
+
self.thresh = thresh
|
| 37 |
+
|
| 38 |
+
assert thresh_method in [
|
| 39 |
+
self.THRESH_HARD,
|
| 40 |
+
self.THRESH_SOFT,
|
| 41 |
+
self.THRESH_SCAD,
|
| 42 |
+
], "`thresh_method` should be `soft`/`hard`/`scad`"
|
| 43 |
+
self.thresh_method = thresh_method
|
| 44 |
+
|
| 45 |
+
def _predict(self, X: np.ndarray) -> np.ndarray:
|
| 46 |
+
Y = X.T # NOTE: to match POET's implementation
|
| 47 |
+
p, n = Y.shape
|
| 48 |
+
|
| 49 |
+
if self.num_factors > 0:
|
| 50 |
+
Dd, V = np.linalg.eig(Y.T.dot(Y))
|
| 51 |
+
V = V[:, np.argsort(Dd)]
|
| 52 |
+
F = V[:, -self.num_factors :][:, ::-1] * np.sqrt(n)
|
| 53 |
+
LamPCA = Y.dot(F) / n
|
| 54 |
+
uhat = np.asarray(Y - LamPCA.dot(F.T))
|
| 55 |
+
Lowrank = np.asarray(LamPCA.dot(LamPCA.T))
|
| 56 |
+
rate = 1 / np.sqrt(p) + np.sqrt(np.log(p) / n)
|
| 57 |
+
else:
|
| 58 |
+
uhat = np.asarray(Y)
|
| 59 |
+
rate = np.sqrt(np.log(p) / n)
|
| 60 |
+
Lowrank = 0
|
| 61 |
+
|
| 62 |
+
lamb = rate * self.thresh
|
| 63 |
+
SuPCA = uhat.dot(uhat.T) / n
|
| 64 |
+
SuDiag = np.diag(np.diag(SuPCA))
|
| 65 |
+
R = np.linalg.inv(SuDiag**0.5).dot(SuPCA).dot(np.linalg.inv(SuDiag**0.5))
|
| 66 |
+
|
| 67 |
+
if self.thresh_method == self.THRESH_HARD:
|
| 68 |
+
M = R * (np.abs(R) > lamb)
|
| 69 |
+
elif self.thresh_method == self.THRESH_SOFT:
|
| 70 |
+
res = np.abs(R) - lamb
|
| 71 |
+
res = (res + np.abs(res)) / 2
|
| 72 |
+
M = np.sign(R) * res
|
| 73 |
+
else:
|
| 74 |
+
M1 = (np.abs(R) < 2 * lamb) * np.sign(R) * (np.abs(R) - lamb) * (np.abs(R) > lamb)
|
| 75 |
+
M2 = (np.abs(R) < 3.7 * lamb) * (np.abs(R) >= 2 * lamb) * (2.7 * R - 3.7 * np.sign(R) * lamb) / 1.7
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import numpy as np
|
| 2 |
+
from typing import Union
|
| 3 |
+
|
| 4 |
+
from qlib.model.riskmodel import RiskModel
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ShrinkCovEstimator(RiskModel):
|
| 8 |
+
"""Shrinkage Covariance Estimator
|
| 9 |
+
|
| 10 |
+
This estimator will shrink the sample covariance matrix towards
|
| 11 |
+
an identify matrix:
|
| 12 |
+
S_hat = (1 - alpha) * S + alpha * F
|
| 13 |
+
where `alpha` is the shrink parameter and `F` is the shrinking target.
|
| 14 |
+
|
| 15 |
+
The following shrinking parameters (`alpha`) are supported:
|
| 16 |
+
- `lw` [1][2][3]: use Ledoit-Wolf shrinking parameter.
|
| 17 |
+
- `oas` [4]: use Oracle Approximating Shrinkage shrinking parameter.
|
| 18 |
+
- float: directly specify the shrink parameter, should be between [0, 1].
|
| 19 |
+
|
| 20 |
+
The following shrinking targets (`F`) are supported:
|
| 21 |
+
- `const_var` [1][4][5]: assume stocks have the same constant variance and zero correlation.
|
| 22 |
+
- `const_corr` [2][6]: assume stocks have different variance but equal correlation.
|
| 23 |
+
- `single_factor` [3][7]: assume single factor model as the shrinking target.
|
| 24 |
+
- np.ndarray: provide the shrinking targets directly.
|
| 25 |
+
|
| 26 |
+
Note:
|
| 27 |
+
- The optimal shrinking parameter depends on the selection of the shrinking target.
|
| 28 |
+
Currently, `oas` is not supported for `const_corr` and `single_factor`.
|
| 29 |
+
- Remember to set `nan_option` to `fill` or `mask` if your data has missing values.
|
| 30 |
+
|
| 31 |
+
References:
|
| 32 |
+
[1] Ledoit, O., & Wolf, M. (2004). A well-conditioned estimator for large-dimensional covariance matrices.
|
| 33 |
+
Journal of Multivariate Analysis, 88(2), 365–411. https://doi.org/10.1016/S0047-259X(03)00096-4
|
| 34 |
+
[2] Ledoit, O., & Wolf, M. (2004). Honey, I shrunk the sample covariance matrix.
|
| 35 |
+
Journal of Portfolio Management, 30(4), 1–22. https://doi.org/10.3905/jpm.2004.110
|
| 36 |
+
[3] Ledoit, O., & Wolf, M. (2003). Improved estimation of the covariance matrix of stock returns
|
| 37 |
+
with an application to portfolio selection.
|
| 38 |
+
Journal of Empirical Finance, 10(5), 603–621. https://doi.org/10.1016/S0927-5398(03)00007-0
|
| 39 |
+
[4] Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O. (2010). Shrinkage algorithms for MMSE covariance
|
| 40 |
+
estimation. IEEE Transactions on Signal Processing, 58(10), 5016–5029.
|
| 41 |
+
https://doi.org/10.1109/TSP.2010.2053029
|
| 42 |
+
[5] https://www.econ.uzh.ch/dam/jcr:ffffffff-935a-b0d6-0000-00007f64e5b9/cov1para.m.zip
|
| 43 |
+
[6] https://www.econ.uzh.ch/dam/jcr:ffffffff-935a-b0d6-ffff-ffffde5e2d4e/covCor.m.zip
|
| 44 |
+
[7] https://www.econ.uzh.ch/dam/jcr:ffffffff-935a-b0d6-0000-0000648dfc98/covMarket.m.zip
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
SHR_LW = "lw"
|
| 48 |
+
SHR_OAS = "oas"
|
| 49 |
+
|
| 50 |
+
TGT_CONST_VAR = "const_var"
|
| 51 |
+
TGT_CONST_CORR = "const_corr"
|
| 52 |
+
TGT_SINGLE_FACTOR = "single_factor"
|
| 53 |
+
|
| 54 |
+
def __init__(self, alpha: Union[str, float] = 0.0, target: Union[str, np.ndarray] = "const_var", **kwargs):
|
| 55 |
+
"""
|
| 56 |
+
Args:
|
| 57 |
+
alpha (str or float): shrinking parameter or estimator (`lw`/`oas`)
|
| 58 |
+
target (str or np.ndarray): shrinking target (`const_var`/`const_corr`/`single_factor`)
|
| 59 |
+
kwargs: see `RiskModel` for more information
|
| 60 |
+
"""
|
| 61 |
+
super().__init__(**kwargs)
|
| 62 |
+
|
| 63 |
+
# alpha
|
| 64 |
+
if isinstance(alpha, str):
|
| 65 |
+
assert alpha in [self.SHR_LW, self.SHR_OAS], f"shrinking method `{alpha}` is not supported"
|
| 66 |
+
elif isinstance(alpha, (float, np.floating)):
|
| 67 |
+
assert 0 <= alpha <= 1, "alpha should be between [0, 1]"
|
| 68 |
+
else:
|
| 69 |
+
raise TypeError("invalid argument type for `alpha`")
|
| 70 |
+
self.alpha = alpha
|
| 71 |
+
|
| 72 |
+
# target
|
| 73 |
+
if isinstance(target, str):
|
| 74 |
+
assert target in [
|
| 75 |
+
self.TGT_CONST_VAR,
|
| 76 |
+
self.TGT_CONST_CORR,
|
| 77 |
+
self.TGT_SINGLE_FACTOR,
|
| 78 |
+
], f"shrinking target `{target} is not supported"
|
| 79 |
+
elif isinstance(target, np.ndarray):
|
| 80 |
+
pass
|
| 81 |
+
else:
|
| 82 |
+
raise TypeError("invalid argument type for `target`")
|
| 83 |
+
if alpha == self.SHR_OAS and target != self.TGT_CONST_VAR:
|
| 84 |
+
raise NotImplementedError("currently `oas` can only support `const_var` as target")
|
| 85 |
+
self.target = target
|
| 86 |
+
|
| 87 |
+
def _predict(self, X: np.ndarray) -> np.ndarray:
|
| 88 |
+
# sample covariance
|
| 89 |
+
S = super()._predict(X)
|
| 90 |
+
|
| 91 |
+
# shrinking target
|
| 92 |
+
F = self._get_shrink_target(X, S)
|
| 93 |
+
|
| 94 |
+
# get shrinking parameter
|
| 95 |
+
alpha = self._get_shrink_param(X, S, F)
|
| 96 |
+
|
| 97 |
+
# shrink covariance
|
| 98 |
+
if alpha > 0:
|
| 99 |
+
S *= 1 - alpha
|
| 100 |
+
F *= alpha
|
| 101 |
+
S += F
|
| 102 |
+
|
| 103 |
+
return S
|
| 104 |
+
|
| 105 |
+
def _get_shrink_target(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
|
| 106 |
+
"""get shrinking target `F`"""
|
| 107 |
+
if self.target == self.TGT_CONST_VAR:
|
| 108 |
+
return self._get_shrink_target_const_var(X, S)
|
| 109 |
+
if self.target == self.TGT_CONST_CORR:
|
| 110 |
+
return self._get_shrink_target_const_corr(X, S)
|
| 111 |
+
if self.target == self.TGT_SINGLE_FACTOR:
|
| 112 |
+
return self._get_shrink_target_single_factor(X, S)
|
| 113 |
+
return self.target
|
| 114 |
+
|
| 115 |
+
def _get_shrink_target_const_var(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
|
| 116 |
+
"""get shrinking target with constant variance
|
| 117 |
+
|
| 118 |
+
This target assumes zero pair-wise correlation and constant variance.
|
| 119 |
+
The constant variance is estimated by averaging all sample's variances.
|
| 120 |
+
"""
|
| 121 |
+
n = len(S)
|
| 122 |
+
F = np.eye(n)
|
| 123 |
+
np.fill_diagonal(F, np.mean(np.diag(S)))
|
| 124 |
+
return F
|
| 125 |
+
|
| 126 |
+
def _get_shrink_target_const_corr(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
|
| 127 |
+
"""get shrinking target with constant correlation
|
| 128 |
+
|
| 129 |
+
This target assumes constant pair-wise correlation but keep the sample variance.
|
| 130 |
+
The constant correlation is estimated by averaging all pairwise correlations.
|
| 131 |
+
"""
|
| 132 |
+
n = len(S)
|
| 133 |
+
var = np.diag(S)
|
| 134 |
+
sqrt_var = np.sqrt(var)
|
| 135 |
+
covar = np.outer(sqrt_var, sqrt_var)
|
| 136 |
+
r_bar = (np.sum(S / covar) - n) / (n * (n - 1))
|
| 137 |
+
F = r_bar * covar
|
| 138 |
+
np.fill_diagonal(F, var)
|
| 139 |
+
return F
|
| 140 |
+
|
| 141 |
+
def _get_shrink_target_single_factor(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
|
| 142 |
+
"""get shrinking target with single factor model"""
|
| 143 |
+
X_mkt = np.nanmean(X, axis=1)
|
| 144 |
+
cov_mkt = np.asarray(X.T.dot(X_mkt) / len(X))
|
| 145 |
+
var_mkt = np.asarray(X_mkt.dot(X_mkt) / len(X))
|
| 146 |
+
F = np.outer(cov_mkt, cov_mkt) / var_mkt
|
| 147 |
+
np.fill_diagonal(F, np.diag(S))
|
| 148 |
+
return F
|
| 149 |
+
|
| 150 |
+
def _get_shrink_param(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
|
| 151 |
+
"""get shrinking parameter `alpha`
|
| 152 |
+
|
| 153 |
+
Note:
|
| 154 |
+
The Ledoit-Wolf shrinking parameter estimator consists of three different methods.
|
| 155 |
+
"""
|
| 156 |
+
if self.alpha == self.SHR_OAS:
|
| 157 |
+
return self._get_shrink_param_oas(X, S, F)
|
| 158 |
+
elif self.alpha == self.SHR_LW:
|
| 159 |
+
if self.target == self.TGT_CONST_VAR:
|
| 160 |
+
return self._get_shrink_param_lw_const_var(X, S, F)
|
| 161 |
+
if self.target == self.TGT_CONST_CORR:
|
| 162 |
+
return self._get_shrink_param_lw_const_corr(X, S, F)
|
| 163 |
+
if self.target == self.TGT_SINGLE_FACTOR:
|
| 164 |
+
return self._get_shrink_param_lw_single_factor(X, S, F)
|
| 165 |
+
return self.alpha
|
| 166 |
+
|
| 167 |
+
def _get_shrink_param_oas(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
|
| 168 |
+
"""Oracle Approximating Shrinkage Estimator
|
| 169 |
+
|
| 170 |
+
This method uses the following formula to estimate the `alpha`
|
| 171 |
+
parameter for the shrink covariance estimator:
|
| 172 |
+
A = (1 - 2 / p) * trace(S^2) + trace^2(S)
|
| 173 |
+
B = (n + 1 - 2 / p) * (trace(S^2) - trace^2(S) / p)
|
| 174 |
+
alpha = A / B
|
| 175 |
+
where `n`, `p` are the dim of observations and variables respectively.
|
| 176 |
+
"""
|
| 177 |
+
trS2 = np.sum(S**2)
|
| 178 |
+
tr2S = np.trace(S) ** 2
|
| 179 |
+
|
| 180 |
+
n, p = X.shape
|
| 181 |
+
|
| 182 |
+
A = (1 - 2 / p) * (trS2 + tr2S)
|
| 183 |
+
B = (n + 1 - 2 / p) * (trS2 + tr2S / p)
|
| 184 |
+
alpha = A / B
|
| 185 |
+
|
| 186 |
+
return alpha
|
| 187 |
+
|
| 188 |
+
def _get_shrink_param_lw_const_var(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
|
| 189 |
+
"""Ledoit-Wolf Shrinkage Estimator (Constant Variance)
|
| 190 |
+
|
| 191 |
+
This method shrinks the covariance matrix towards the constand variance target.
|
| 192 |
+
"""
|
| 193 |
+
t, n = X.shape
|
| 194 |
+
|
| 195 |
+
y = X**2
|
| 196 |
+
phi = np.sum(y.T.dot(y) / t - S**2)
|
| 197 |
+
|
| 198 |
+
gamma = np.linalg.norm(S - F, "fro") ** 2
|
| 199 |
+
|
| 200 |
+
kappa = phi / gamma
|
| 201 |
+
alpha = max(0, min(1, kappa / t))
|
| 202 |
+
|
| 203 |
+
return alpha
|
| 204 |
+
|
| 205 |
+
def _get_shrink_param_lw_const_corr(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
|
| 206 |
+
"""Ledoit-Wolf Shrinkage Estimator (Constant Correlation)
|
| 207 |
+
|
| 208 |
+
This method shrinks the covariance matrix towards the constand correlation target.
|
| 209 |
+
"""
|
| 210 |
+
t, n = X.shape
|
| 211 |
+
|
| 212 |
+
var = np.diag(S)
|
| 213 |
+
sqrt_var = np.sqrt(var)
|
| 214 |
+
r_bar = (np.sum(S / np.outer(sqrt_var, sqrt_var)) - n) / (n * (n - 1))
|
| 215 |
+
|
| 216 |
+
y = X**2
|
| 217 |
+
phi_mat = y.T.dot(y) / t - S**2
|
| 218 |
+
phi = np.sum(phi_mat)
|
| 219 |
+
|
| 220 |
+
theta_mat = (X**3).T.dot(X) / t - var[:, None] * S
|
| 221 |
+
np.fill_diagonal(theta_mat, 0)
|
| 222 |
+
rho = np.sum(np.diag(phi_mat)) + r_bar * np.sum(np.outer(1 / sqrt_var, sqrt_var) * theta_mat)
|
| 223 |
+
|
| 224 |
+
gamma = np.linalg.norm(S - F, "fro") ** 2
|
| 225 |
+
|
| 226 |
+
kappa = (phi - rho) / gamma
|
| 227 |
+
alpha = max(0, min(1, kappa / t))
|
| 228 |
+
|
| 229 |
+
return alpha
|
| 230 |
+
|
| 231 |
+
def _get_shrink_param_lw_single_factor(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
|
| 232 |
+
"""Ledoit-Wolf Shrinkage Estimator (Single Factor Model)
|
| 233 |
+
|
| 234 |
+
This method shrinks the covariance matrix towards the single factor model target.
|
| 235 |
+
"""
|
| 236 |
+
t, n = X.shape
|
| 237 |
+
|
| 238 |
+
X_mkt = np.nanmean(X, axis=1)
|
| 239 |
+
cov_mkt = np.asarray(X.T.dot(X_mkt) / len(X))
|
| 240 |
+
var_mkt = np.asarray(X_mkt.dot(X_mkt) / len(X))
|
| 241 |
+
|
| 242 |
+
y = X**2
|
| 243 |
+
phi = np.sum(y.T.dot(y)) / t - np.sum(S**2)
|
| 244 |
+
|
| 245 |
+
rdiag = np.sum(y**2) / t - np.sum(np.diag(S) ** 2)
|
| 246 |
+
z = X * X_mkt[:, None]
|
| 247 |
+
v1 = y.T.dot(z) / t - cov_mkt[:, None] * S
|
| 248 |
+
roff1 = np.sum(v1 * cov_mkt[:, None].T) / var_mkt - np.sum(np.diag(v1) * cov_mkt) / var_mkt
|
| 249 |
+
v3 = z.T.dot(z) / t - var_mkt * S
|
| 250 |
+
roff3 = np.sum(v3 * np.outer(cov_mkt, cov_mkt)) / var_mkt**2 - np.sum(np.diag(v3) * cov_mkt**2) / var_mkt**2
|
| 251 |
+
roff = 2 * roff1 - roff3
|
| 252 |
+
rho = rdiag + roff
|
| 253 |
+
|
| 254 |
+
gamma = np.linalg.norm(S - F, "fro") ** 2
|
| 255 |
+
|
| 256 |
+
kappa = (phi - rho) / gamma
|
| 257 |
+
alpha = max(0, min(1, kappa / t))
|
| 258 |
+
|
| 259 |
+
return alpha
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/structured.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from typing import Union
|
| 6 |
+
from sklearn.decomposition import PCA, FactorAnalysis
|
| 7 |
+
|
| 8 |
+
from qlib.model.riskmodel import RiskModel
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class StructuredCovEstimator(RiskModel):
|
| 12 |
+
"""Structured Covariance Estimator
|
| 13 |
+
|
| 14 |
+
This estimator assumes observations can be predicted by multiple factors
|
| 15 |
+
X = B @ F.T + U
|
| 16 |
+
where `X` contains observations (row) of multiple variables (column),
|
| 17 |
+
`F` contains factor exposures (column) for all variables (row),
|
| 18 |
+
`B` is the regression coefficients matrix for all observations (row) on
|
| 19 |
+
all factors (columns), and `U` is the residual matrix with shape like `X`.
|
| 20 |
+
|
| 21 |
+
Therefore, the structured covariance can be estimated by
|
| 22 |
+
cov(X.T) = F @ cov(B.T) @ F.T + diag(var(U))
|
| 23 |
+
|
| 24 |
+
In finance domain, there are mainly three methods to design `F` [1][2]:
|
| 25 |
+
- Statistical Risk Model (SRM): latent factor models major components
|
| 26 |
+
- Fundamental Risk Model (FRM): human designed factors
|
| 27 |
+
- Deep Risk Model (DRM): neural network designed factors (like a blend of SRM & DRM)
|
| 28 |
+
|
| 29 |
+
In this implementation we use latent factor models to specify `F`.
|
| 30 |
+
Specifically, the following two latent factor models are supported:
|
| 31 |
+
- `pca`: Principal Component Analysis
|
| 32 |
+
- `fa`: Factor Analysis
|
| 33 |
+
|
| 34 |
+
Reference:
|
| 35 |
+
[1] Fan, J., Liao, Y., & Liu, H. (2016). An overview of the estimation of large covariance and
|
| 36 |
+
precision matrices. Econometrics Journal, 19(1), C1–C32. https://doi.org/10.1111/ectj.12061
|
| 37 |
+
[2] Lin, H., Zhou, D., Liu, W., & Bian, J. (2021). Deep Risk Model: A Deep Learning Solution for
|
| 38 |
+
Mining Latent Risk Factors to Improve Covariance Matrix Estimation. arXiv preprint arXiv:2107.05201.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
FACTOR_MODEL_PCA = "pca"
|
| 42 |
+
FACTOR_MODEL_FA = "fa"
|
| 43 |
+
DEFAULT_NAN_OPTION = "fill"
|
| 44 |
+
|
| 45 |
+
def __init__(self, factor_model: str = "pca", num_factors: int = 10, **kwargs):
|
| 46 |
+
"""
|
| 47 |
+
Args:
|
| 48 |
+
factor_model (str): the latent factor models used to estimate the structured covariance (`pca`/`fa`).
|
| 49 |
+
num_factors (int): number of components to keep.
|
| 50 |
+
kwargs: see `RiskModel` for more information
|
| 51 |
+
"""
|
| 52 |
+
if "nan_option" in kwargs:
|
| 53 |
+
assert kwargs["nan_option"] in [self.DEFAULT_NAN_OPTION], "nan_option={} is not supported".format(
|
| 54 |
+
kwargs["nan_option"]
|
| 55 |
+
)
|
| 56 |
+
else:
|
| 57 |
+
kwargs["nan_option"] = self.DEFAULT_NAN_OPTION
|
| 58 |
+
|
| 59 |
+
super().__init__(**kwargs)
|
| 60 |
+
|
| 61 |
+
assert factor_model in [
|
| 62 |
+
self.FACTOR_MODEL_PCA,
|
| 63 |
+
self.FACTOR_MODEL_FA,
|
| 64 |
+
], "factor_model={} is not supported".format(factor_model)
|
| 65 |
+
self.solver = PCA if factor_model == self.FACTOR_MODEL_PCA else FactorAnalysis
|
| 66 |
+
|
| 67 |
+
self.num_factors = num_factors
|
| 68 |
+
|
| 69 |
+
def _predict(self, X: np.ndarray, return_decomposed_components=False) -> Union[np.ndarray, tuple]:
|
| 70 |
+
"""
|
| 71 |
+
covariance estimation implementation
|
| 72 |
+
|
| 73 |
+
Args:
|
| 74 |
+
X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows).
|
| 75 |
+
return_decomposed_components (bool): whether return decomposed components of the covariance matrix.
|
| 76 |
+
|
| 77 |
+
Returns:
|
| 78 |
+
tuple or np.ndarray: decomposed covariance matrix or covariance matrix.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
model = self.solver(self.num_factors, random_state=0).fit(X)
|
| 82 |
+
|
| 83 |
+
F = model.components_.T # variables x factors
|
| 84 |
+
B = model.transform(X) # observations x factors
|
| 85 |
+
U = X - B @ F.T
|
| 86 |
+
cov_b = np.cov(B.T) # factors x factors
|
| 87 |
+
var_u = np.var(U, axis=0) # diagonal
|
| 88 |
+
|
| 89 |
+
if return_decomposed_components:
|
| 90 |
+
return F, cov_b, var_u
|
| 91 |
+
|
| 92 |
+
cov_x = F @ cov_b @ F.T + np.diag(var_u)
|
| 93 |
+
|
| 94 |
+
return cov_x
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/trainer.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
The Trainer will train a list of tasks and return a list of model recorders.
|
| 6 |
+
There are two steps in each Trainer including ``train`` (make model recorder) and ``end_train`` (modify model recorder).
|
| 7 |
+
|
| 8 |
+
This is a concept called ``DelayTrainer``, which can be used in online simulating for parallel training.
|
| 9 |
+
In ``DelayTrainer``, the first step is only to save some necessary info to model recorders, and the second step which will be finished in the end can do some concurrent and time-consuming operations such as model fitting.
|
| 10 |
+
|
| 11 |
+
``Qlib`` offer two kinds of Trainer, ``TrainerR`` is the simplest way and ``TrainerRM`` is based on TaskManager to help manager tasks lifecycle automatically.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import socket
|
| 15 |
+
from typing import Callable, List, Optional
|
| 16 |
+
|
| 17 |
+
from tqdm.auto import tqdm
|
| 18 |
+
|
| 19 |
+
from qlib.config import C
|
| 20 |
+
from qlib.data.dataset import Dataset
|
| 21 |
+
from qlib.data.dataset.weight import Reweighter
|
| 22 |
+
from qlib.log import get_module_logger
|
| 23 |
+
from qlib.model.base import Model
|
| 24 |
+
from qlib.utils import (
|
| 25 |
+
auto_filter_kwargs,
|
| 26 |
+
fill_placeholder,
|
| 27 |
+
flatten_dict,
|
| 28 |
+
init_instance_by_config,
|
| 29 |
+
)
|
| 30 |
+
from qlib.utils.paral import call_in_subproc
|
| 31 |
+
from qlib.workflow import R
|
| 32 |
+
from qlib.workflow.recorder import Recorder
|
| 33 |
+
from qlib.workflow.task.manage import TaskManager, run_task
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _log_task_info(task_config: dict):
|
| 37 |
+
R.log_params(**flatten_dict(task_config))
|
| 38 |
+
R.save_objects(**{"task": task_config}) # keep the original format and datatype
|
| 39 |
+
R.set_tags(**{"hostname": socket.gethostname()})
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _exe_task(task_config: dict):
|
| 43 |
+
rec = R.get_recorder()
|
| 44 |
+
# model & dataset initialization
|
| 45 |
+
model: Model = init_instance_by_config(task_config["model"], accept_types=Model)
|
| 46 |
+
dataset: Dataset = init_instance_by_config(task_config["dataset"], accept_types=Dataset)
|
| 47 |
+
reweighter: Reweighter = task_config.get("reweighter", None)
|
| 48 |
+
# model training
|
| 49 |
+
auto_filter_kwargs(model.fit)(dataset, reweighter=reweighter)
|
| 50 |
+
R.save_objects(**{"params.pkl": model})
|
| 51 |
+
# this dataset is saved for online inference. So the concrete data should not be dumped
|
| 52 |
+
dataset.config(dump_all=False, recursive=True)
|
| 53 |
+
R.save_objects(**{"dataset": dataset})
|
| 54 |
+
# fill placehorder
|
| 55 |
+
placehorder_value = {"<MODEL>": model, "<DATASET>": dataset}
|
| 56 |
+
task_config = fill_placeholder(task_config, placehorder_value)
|
| 57 |
+
# generate records: prediction, backtest, and analysis
|
| 58 |
+
records = task_config.get("record", [])
|
| 59 |
+
if isinstance(records, dict): # prevent only one dict
|
| 60 |
+
records = [records]
|
| 61 |
+
for record in records:
|
| 62 |
+
# Some recorder require the parameter `model` and `dataset`.
|
| 63 |
+
# try to automatically pass in them to the initialization function
|
| 64 |
+
# to make defining the tasking easier
|
| 65 |
+
r = init_instance_by_config(
|
| 66 |
+
record,
|
| 67 |
+
recorder=rec,
|
| 68 |
+
default_module="qlib.workflow.record_temp",
|
| 69 |
+
try_kwargs={"model": model, "dataset": dataset},
|
| 70 |
+
)
|
| 71 |
+
r.generate()
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def begin_task_train(task_config: dict, experiment_name: str, recorder_name: str = None) -> Recorder:
|
| 75 |
+
"""
|
| 76 |
+
Begin task training to start a recorder and save the task config.
|
| 77 |
+
|
| 78 |
+
Args:
|
| 79 |
+
task_config (dict): the config of a task
|
| 80 |
+
experiment_name (str): the name of experiment
|
| 81 |
+
recorder_name (str): the given name will be the recorder name. None for using rid.
|
| 82 |
+
|
| 83 |
+
Returns:
|
| 84 |
+
Recorder: the model recorder
|
| 85 |
+
"""
|
| 86 |
+
with R.start(experiment_name=experiment_name, recorder_name=recorder_name):
|
| 87 |
+
_log_task_info(task_config)
|
| 88 |
+
return R.get_recorder()
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def end_task_train(rec: Recorder, experiment_name: str) -> Recorder:
|
| 92 |
+
"""
|
| 93 |
+
Finish task training with real model fitting and saving.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
rec (Recorder): the recorder will be resumed
|
| 97 |
+
experiment_name (str): the name of experiment
|
| 98 |
+
|
| 99 |
+
Returns:
|
| 100 |
+
Recorder: the model recorder
|
| 101 |
+
"""
|
| 102 |
+
with R.start(experiment_name=experiment_name, recorder_id=rec.info["id"], resume=True):
|
| 103 |
+
task_config = R.load_object("task")
|
| 104 |
+
_exe_task(task_config)
|
| 105 |
+
return rec
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def task_train(task_config: dict, experiment_name: str, recorder_name: str = None) -> Recorder:
|
| 109 |
+
"""
|
| 110 |
+
Task based training, will be divided into two steps.
|
| 111 |
+
|
| 112 |
+
Parameters
|
| 113 |
+
----------
|
| 114 |
+
task_config : dict
|
| 115 |
+
The config of a task.
|
| 116 |
+
experiment_name: str
|
| 117 |
+
The name of experiment
|
| 118 |
+
recorder_name: str
|
| 119 |
+
The name of recorder
|
| 120 |
+
|
| 121 |
+
Returns
|
| 122 |
+
----------
|
| 123 |
+
Recorder: The instance of the recorder
|
| 124 |
+
"""
|
| 125 |
+
with R.start(experiment_name=experiment_name, recorder_name=recorder_name):
|
| 126 |
+
_log_task_info(task_config)
|
| 127 |
+
_exe_task(task_config)
|
| 128 |
+
return R.get_recorder()
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class Trainer:
|
| 132 |
+
"""
|
| 133 |
+
The trainer can train a list of models.
|
| 134 |
+
There are Trainer and DelayTrainer, which can be distinguished by when it will finish real training.
|
| 135 |
+
"""
|
| 136 |
+
|
| 137 |
+
def __init__(self):
|
| 138 |
+
self.delay = False
|
| 139 |
+
|
| 140 |
+
def train(self, tasks: list, *args, **kwargs) -> list:
|
| 141 |
+
"""
|
| 142 |
+
Given a list of task definitions, begin training, and return the models.
|
| 143 |
+
|
| 144 |
+
For Trainer, it finishes real training in this method.
|
| 145 |
+
For DelayTrainer, it only does some preparation in this method.
|
| 146 |
+
|
| 147 |
+
Args:
|
| 148 |
+
tasks: a list of tasks
|
| 149 |
+
|
| 150 |
+
Returns:
|
| 151 |
+
list: a list of models
|
| 152 |
+
"""
|
| 153 |
+
raise NotImplementedError(f"Please implement the `train` method.")
|
| 154 |
+
|
| 155 |
+
def end_train(self, models: list, *args, **kwargs) -> list:
|
| 156 |
+
"""
|
| 157 |
+
Given a list of models, finished something at the end of training if you need.
|
| 158 |
+
The models may be Recorder, txt file, database, and so on.
|
| 159 |
+
|
| 160 |
+
For Trainer, it does some finishing touches in this method.
|
| 161 |
+
For DelayTrainer, it finishes real training in this method.
|
| 162 |
+
|
| 163 |
+
Args:
|
| 164 |
+
models: a list of models
|
| 165 |
+
|
| 166 |
+
Returns:
|
| 167 |
+
list: a list of models
|
| 168 |
+
"""
|
| 169 |
+
# do nothing if you finished all work in `train` method
|
| 170 |
+
return models
|
| 171 |
+
|
| 172 |
+
def is_delay(self) -> bool:
|
| 173 |
+
"""
|
| 174 |
+
If Trainer will delay finishing `end_train`.
|
| 175 |
+
|
| 176 |
+
Returns:
|
| 177 |
+
bool: if DelayTrainer
|
| 178 |
+
"""
|
| 179 |
+
return self.delay
|
| 180 |
+
|
| 181 |
+
def __call__(self, *args, **kwargs) -> list:
|
| 182 |
+
return self.end_train(self.train(*args, **kwargs))
|
| 183 |
+
|
| 184 |
+
def has_worker(self) -> bool:
|
| 185 |
+
"""
|
| 186 |
+
Some trainer has backend worker to support parallel training
|
| 187 |
+
This method can tell if the worker is enabled.
|
| 188 |
+
|
| 189 |
+
Returns
|
| 190 |
+
-------
|
| 191 |
+
bool:
|
| 192 |
+
if the worker is enabled
|
| 193 |
+
|
| 194 |
+
"""
|
| 195 |
+
return False
|
| 196 |
+
|
| 197 |
+
def worker(self):
|
| 198 |
+
"""
|
| 199 |
+
start the worker
|
| 200 |
+
|
| 201 |
+
Raises
|
| 202 |
+
------
|
| 203 |
+
NotImplementedError:
|
| 204 |
+
If the worker is not supported
|
| 205 |
+
"""
|
| 206 |
+
raise NotImplementedError(f"Please implement the `worker` method")
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
class TrainerR(Trainer):
|
| 210 |
+
"""
|
| 211 |
+
Trainer based on (R)ecorder.
|
| 212 |
+
It will train a list of tasks and return a list of model recorders in a linear way.
|
| 213 |
+
|
| 214 |
+
Assumption: models were defined by `task` and the results will be saved to `Recorder`.
|
| 215 |
+
"""
|
| 216 |
+
|
| 217 |
+
# Those tag will help you distinguish whether the Recorder has finished traning
|
| 218 |
+
STATUS_KEY = "train_status"
|
| 219 |
+
STATUS_BEGIN = "begin_task_train"
|
| 220 |
+
STATUS_END = "end_task_train"
|
| 221 |
+
|
| 222 |
+
def __init__(
|
| 223 |
+
self,
|
| 224 |
+
experiment_name: Optional[str] = None,
|
| 225 |
+
train_func: Callable = task_train,
|
| 226 |
+
call_in_subproc: bool = False,
|
| 227 |
+
default_rec_name: Optional[str] = None,
|
| 228 |
+
):
|
| 229 |
+
"""
|
| 230 |
+
Init TrainerR.
|
| 231 |
+
|
| 232 |
+
Args:
|
| 233 |
+
experiment_name (str, optional): the default name of experiment.
|
| 234 |
+
train_func (Callable, optional): default training method. Defaults to `task_train`.
|
| 235 |
+
call_in_subproc (bool): call the process in subprocess to force memory release
|
| 236 |
+
"""
|
| 237 |
+
super().__init__()
|
| 238 |
+
self.experiment_name = experiment_name
|
| 239 |
+
self.default_rec_name = default_rec_name
|
| 240 |
+
self.train_func = train_func
|
| 241 |
+
self._call_in_subproc = call_in_subproc
|
| 242 |
+
|
| 243 |
+
def train(
|
| 244 |
+
self, tasks: list, train_func: Optional[Callable] = None, experiment_name: Optional[str] = None, **kwargs
|
| 245 |
+
) -> List[Recorder]:
|
| 246 |
+
"""
|
| 247 |
+
Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed.
|
| 248 |
+
|
| 249 |
+
Args:
|
| 250 |
+
tasks (list): a list of definitions based on `task` dict
|
| 251 |
+
train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method.
|
| 252 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 253 |
+
kwargs: the params for train_func.
|
| 254 |
+
|
| 255 |
+
Returns:
|
| 256 |
+
List[Recorder]: a list of Recorders
|
| 257 |
+
"""
|
| 258 |
+
if isinstance(tasks, dict):
|
| 259 |
+
tasks = [tasks]
|
| 260 |
+
if len(tasks) == 0:
|
| 261 |
+
return []
|
| 262 |
+
if train_func is None:
|
| 263 |
+
train_func = self.train_func
|
| 264 |
+
if experiment_name is None:
|
| 265 |
+
experiment_name = self.experiment_name
|
| 266 |
+
recs = []
|
| 267 |
+
for task in tqdm(tasks, desc="train tasks"):
|
| 268 |
+
if self._call_in_subproc:
|
| 269 |
+
get_module_logger("TrainerR").info("running models in sub process (for forcing release memroy).")
|
| 270 |
+
train_func = call_in_subproc(train_func, C)
|
| 271 |
+
rec = train_func(task, experiment_name, recorder_name=self.default_rec_name, **kwargs)
|
| 272 |
+
rec.set_tags(**{self.STATUS_KEY: self.STATUS_BEGIN})
|
| 273 |
+
recs.append(rec)
|
| 274 |
+
return recs
|
| 275 |
+
|
| 276 |
+
def end_train(self, models: list, **kwargs) -> List[Recorder]:
|
| 277 |
+
"""
|
| 278 |
+
Set STATUS_END tag to the recorders.
|
| 279 |
+
|
| 280 |
+
Args:
|
| 281 |
+
models (list): a list of trained recorders.
|
| 282 |
+
|
| 283 |
+
Returns:
|
| 284 |
+
List[Recorder]: the same list as the param.
|
| 285 |
+
"""
|
| 286 |
+
if isinstance(models, Recorder):
|
| 287 |
+
models = [models]
|
| 288 |
+
for rec in models:
|
| 289 |
+
rec.set_tags(**{self.STATUS_KEY: self.STATUS_END})
|
| 290 |
+
return models
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
class DelayTrainerR(TrainerR):
|
| 294 |
+
"""
|
| 295 |
+
A delayed implementation based on TrainerR, which means `train` method may only do some preparation and `end_train` method can do the real model fitting.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
def __init__(
|
| 299 |
+
self, experiment_name: str = None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs
|
| 300 |
+
):
|
| 301 |
+
"""
|
| 302 |
+
Init TrainerRM.
|
| 303 |
+
|
| 304 |
+
Args:
|
| 305 |
+
experiment_name (str): the default name of experiment.
|
| 306 |
+
train_func (Callable, optional): default train method. Defaults to `begin_task_train`.
|
| 307 |
+
end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`.
|
| 308 |
+
"""
|
| 309 |
+
super().__init__(experiment_name, train_func, **kwargs)
|
| 310 |
+
self.end_train_func = end_train_func
|
| 311 |
+
self.delay = True
|
| 312 |
+
|
| 313 |
+
def end_train(self, models, end_train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]:
|
| 314 |
+
"""
|
| 315 |
+
Given a list of Recorder and return a list of trained Recorder.
|
| 316 |
+
This class will finish real data loading and model fitting.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
models (list): a list of Recorder, the tasks have been saved to them
|
| 320 |
+
end_train_func (Callable, optional): the end_train method which needs at least `recorders` and `experiment_name`. Defaults to None for using self.end_train_func.
|
| 321 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 322 |
+
kwargs: the params for end_train_func.
|
| 323 |
+
|
| 324 |
+
Returns:
|
| 325 |
+
List[Recorder]: a list of Recorders
|
| 326 |
+
"""
|
| 327 |
+
if isinstance(models, Recorder):
|
| 328 |
+
models = [models]
|
| 329 |
+
if end_train_func is None:
|
| 330 |
+
end_train_func = self.end_train_func
|
| 331 |
+
if experiment_name is None:
|
| 332 |
+
experiment_name = self.experiment_name
|
| 333 |
+
for rec in models:
|
| 334 |
+
if rec.list_tags()[self.STATUS_KEY] == self.STATUS_END:
|
| 335 |
+
continue
|
| 336 |
+
end_train_func(rec, experiment_name, **kwargs)
|
| 337 |
+
rec.set_tags(**{self.STATUS_KEY: self.STATUS_END})
|
| 338 |
+
return models
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
class TrainerRM(Trainer):
|
| 342 |
+
"""
|
| 343 |
+
Trainer based on (R)ecorder and Task(M)anager.
|
| 344 |
+
It can train a list of tasks and return a list of model recorders in a multiprocessing way.
|
| 345 |
+
|
| 346 |
+
Assumption: `task` will be saved to TaskManager and `task` will be fetched and trained from TaskManager
|
| 347 |
+
"""
|
| 348 |
+
|
| 349 |
+
# Those tag will help you distinguish whether the Recorder has finished traning
|
| 350 |
+
STATUS_KEY = "train_status"
|
| 351 |
+
STATUS_BEGIN = "begin_task_train"
|
| 352 |
+
STATUS_END = "end_task_train"
|
| 353 |
+
|
| 354 |
+
# This tag is the _id in TaskManager to distinguish tasks.
|
| 355 |
+
TM_ID = "_id in TaskManager"
|
| 356 |
+
|
| 357 |
+
def __init__(
|
| 358 |
+
self,
|
| 359 |
+
experiment_name: str = None,
|
| 360 |
+
task_pool: str = None,
|
| 361 |
+
train_func=task_train,
|
| 362 |
+
skip_run_task: bool = False,
|
| 363 |
+
default_rec_name: Optional[str] = None,
|
| 364 |
+
):
|
| 365 |
+
"""
|
| 366 |
+
Init TrainerR.
|
| 367 |
+
|
| 368 |
+
Args:
|
| 369 |
+
experiment_name (str): the default name of experiment.
|
| 370 |
+
task_pool (str): task pool name in TaskManager. None for use same name as experiment_name.
|
| 371 |
+
train_func (Callable, optional): default training method. Defaults to `task_train`.
|
| 372 |
+
skip_run_task (bool):
|
| 373 |
+
If skip_run_task == True:
|
| 374 |
+
Only run_task in the worker. Otherwise skip run_task.
|
| 375 |
+
"""
|
| 376 |
+
|
| 377 |
+
super().__init__()
|
| 378 |
+
self.experiment_name = experiment_name
|
| 379 |
+
self.task_pool = task_pool
|
| 380 |
+
self.train_func = train_func
|
| 381 |
+
self.skip_run_task = skip_run_task
|
| 382 |
+
self.default_rec_name = default_rec_name
|
| 383 |
+
|
| 384 |
+
def train(
|
| 385 |
+
self,
|
| 386 |
+
tasks: list,
|
| 387 |
+
train_func: Callable = None,
|
| 388 |
+
experiment_name: str = None,
|
| 389 |
+
before_status: str = TaskManager.STATUS_WAITING,
|
| 390 |
+
after_status: str = TaskManager.STATUS_DONE,
|
| 391 |
+
default_rec_name: Optional[str] = None,
|
| 392 |
+
**kwargs,
|
| 393 |
+
) -> List[Recorder]:
|
| 394 |
+
"""
|
| 395 |
+
Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed.
|
| 396 |
+
|
| 397 |
+
This method defaults to a single process, but TaskManager offered a great way to parallel training.
|
| 398 |
+
Users can customize their train_func to realize multiple processes or even multiple machines.
|
| 399 |
+
|
| 400 |
+
Args:
|
| 401 |
+
tasks (list): a list of definitions based on `task` dict
|
| 402 |
+
train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method.
|
| 403 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 404 |
+
before_status (str): the tasks in before_status will be fetched and trained. Can be STATUS_WAITING, STATUS_PART_DONE.
|
| 405 |
+
after_status (str): the tasks after trained will become after_status. Can be STATUS_WAITING, STATUS_PART_DONE.
|
| 406 |
+
kwargs: the params for train_func.
|
| 407 |
+
|
| 408 |
+
Returns:
|
| 409 |
+
List[Recorder]: a list of Recorders
|
| 410 |
+
"""
|
| 411 |
+
if isinstance(tasks, dict):
|
| 412 |
+
tasks = [tasks]
|
| 413 |
+
if len(tasks) == 0:
|
| 414 |
+
return []
|
| 415 |
+
if train_func is None:
|
| 416 |
+
train_func = self.train_func
|
| 417 |
+
if experiment_name is None:
|
| 418 |
+
experiment_name = self.experiment_name
|
| 419 |
+
if default_rec_name is None:
|
| 420 |
+
default_rec_name = self.default_rec_name
|
| 421 |
+
task_pool = self.task_pool
|
| 422 |
+
if task_pool is None:
|
| 423 |
+
task_pool = experiment_name
|
| 424 |
+
tm = TaskManager(task_pool=task_pool)
|
| 425 |
+
_id_list = tm.create_task(tasks) # all tasks will be saved to MongoDB
|
| 426 |
+
query = {"_id": {"$in": _id_list}}
|
| 427 |
+
if not self.skip_run_task:
|
| 428 |
+
run_task(
|
| 429 |
+
train_func,
|
| 430 |
+
task_pool,
|
| 431 |
+
query=query, # only train these tasks
|
| 432 |
+
experiment_name=experiment_name,
|
| 433 |
+
before_status=before_status,
|
| 434 |
+
after_status=after_status,
|
| 435 |
+
recorder_name=default_rec_name,
|
| 436 |
+
**kwargs,
|
| 437 |
+
)
|
| 438 |
+
|
| 439 |
+
if not self.is_delay():
|
| 440 |
+
tm.wait(query=query)
|
| 441 |
+
|
| 442 |
+
recs = []
|
| 443 |
+
for _id in _id_list:
|
| 444 |
+
rec = tm.re_query(_id)["res"]
|
| 445 |
+
rec.set_tags(**{self.STATUS_KEY: self.STATUS_BEGIN})
|
| 446 |
+
rec.set_tags(**{self.TM_ID: _id})
|
| 447 |
+
recs.append(rec)
|
| 448 |
+
return recs
|
| 449 |
+
|
| 450 |
+
def end_train(self, recs: list, **kwargs) -> List[Recorder]:
|
| 451 |
+
"""
|
| 452 |
+
Set STATUS_END tag to the recorders.
|
| 453 |
+
|
| 454 |
+
Args:
|
| 455 |
+
recs (list): a list of trained recorders.
|
| 456 |
+
|
| 457 |
+
Returns:
|
| 458 |
+
List[Recorder]: the same list as the param.
|
| 459 |
+
"""
|
| 460 |
+
if isinstance(recs, Recorder):
|
| 461 |
+
recs = [recs]
|
| 462 |
+
for rec in recs:
|
| 463 |
+
rec.set_tags(**{self.STATUS_KEY: self.STATUS_END})
|
| 464 |
+
return recs
|
| 465 |
+
|
| 466 |
+
def worker(
|
| 467 |
+
self,
|
| 468 |
+
train_func: Callable = None,
|
| 469 |
+
experiment_name: str = None,
|
| 470 |
+
):
|
| 471 |
+
"""
|
| 472 |
+
The multiprocessing method for `train`. It can share a same task_pool with `train` and can run in other progress or other machines.
|
| 473 |
+
|
| 474 |
+
Args:
|
| 475 |
+
train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method.
|
| 476 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 477 |
+
"""
|
| 478 |
+
if train_func is None:
|
| 479 |
+
train_func = self.train_func
|
| 480 |
+
if experiment_name is None:
|
| 481 |
+
experiment_name = self.experiment_name
|
| 482 |
+
task_pool = self.task_pool
|
| 483 |
+
if task_pool is None:
|
| 484 |
+
task_pool = experiment_name
|
| 485 |
+
run_task(train_func, task_pool=task_pool, experiment_name=experiment_name)
|
| 486 |
+
|
| 487 |
+
def has_worker(self) -> bool:
|
| 488 |
+
return True
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
class DelayTrainerRM(TrainerRM):
|
| 492 |
+
"""
|
| 493 |
+
A delayed implementation based on TrainerRM, which means `train` method may only do some preparation and `end_train` method can do the real model fitting.
|
| 494 |
+
|
| 495 |
+
"""
|
| 496 |
+
|
| 497 |
+
def __init__(
|
| 498 |
+
self,
|
| 499 |
+
experiment_name: str = None,
|
| 500 |
+
task_pool: str = None,
|
| 501 |
+
train_func=begin_task_train,
|
| 502 |
+
end_train_func=end_task_train,
|
| 503 |
+
skip_run_task: bool = False,
|
| 504 |
+
**kwargs,
|
| 505 |
+
):
|
| 506 |
+
"""
|
| 507 |
+
Init DelayTrainerRM.
|
| 508 |
+
|
| 509 |
+
Args:
|
| 510 |
+
experiment_name (str): the default name of experiment.
|
| 511 |
+
task_pool (str): task pool name in TaskManager. None for use same name as experiment_name.
|
| 512 |
+
train_func (Callable, optional): default train method. Defaults to `begin_task_train`.
|
| 513 |
+
end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`.
|
| 514 |
+
skip_run_task (bool):
|
| 515 |
+
If skip_run_task == True:
|
| 516 |
+
Only run_task in the worker. Otherwise skip run_task.
|
| 517 |
+
E.g. Starting trainer on a CPU VM and then waiting tasks to be finished on GPU VMs.
|
| 518 |
+
"""
|
| 519 |
+
super().__init__(experiment_name, task_pool, train_func, **kwargs)
|
| 520 |
+
self.end_train_func = end_train_func
|
| 521 |
+
self.delay = True
|
| 522 |
+
self.skip_run_task = skip_run_task
|
| 523 |
+
|
| 524 |
+
def train(self, tasks: list, train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]:
|
| 525 |
+
"""
|
| 526 |
+
Same as `train` of TrainerRM, after_status will be STATUS_PART_DONE.
|
| 527 |
+
|
| 528 |
+
Args:
|
| 529 |
+
tasks (list): a list of definition based on `task` dict
|
| 530 |
+
train_func (Callable): the train method which need at least `tasks` and `experiment_name`. Defaults to None for using self.train_func.
|
| 531 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 532 |
+
|
| 533 |
+
Returns:
|
| 534 |
+
List[Recorder]: a list of Recorders
|
| 535 |
+
"""
|
| 536 |
+
if isinstance(tasks, dict):
|
| 537 |
+
tasks = [tasks]
|
| 538 |
+
if len(tasks) == 0:
|
| 539 |
+
return []
|
| 540 |
+
_skip_run_task = self.skip_run_task
|
| 541 |
+
self.skip_run_task = False # The task preparation can't be skipped
|
| 542 |
+
res = super().train(
|
| 543 |
+
tasks,
|
| 544 |
+
train_func=train_func,
|
| 545 |
+
experiment_name=experiment_name,
|
| 546 |
+
after_status=TaskManager.STATUS_PART_DONE,
|
| 547 |
+
**kwargs,
|
| 548 |
+
)
|
| 549 |
+
self.skip_run_task = _skip_run_task
|
| 550 |
+
return res
|
| 551 |
+
|
| 552 |
+
def end_train(self, recs, end_train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]:
|
| 553 |
+
"""
|
| 554 |
+
Given a list of Recorder and return a list of trained Recorder.
|
| 555 |
+
This class will finish real data loading and model fitting.
|
| 556 |
+
|
| 557 |
+
Args:
|
| 558 |
+
recs (list): a list of Recorder, the tasks have been saved to them.
|
| 559 |
+
end_train_func (Callable, optional): the end_train method which need at least `recorders` and `experiment_name`. Defaults to None for using self.end_train_func.
|
| 560 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 561 |
+
kwargs: the params for end_train_func.
|
| 562 |
+
|
| 563 |
+
Returns:
|
| 564 |
+
List[Recorder]: a list of Recorders
|
| 565 |
+
"""
|
| 566 |
+
if isinstance(recs, Recorder):
|
| 567 |
+
recs = [recs]
|
| 568 |
+
if end_train_func is None:
|
| 569 |
+
end_train_func = self.end_train_func
|
| 570 |
+
if experiment_name is None:
|
| 571 |
+
experiment_name = self.experiment_name
|
| 572 |
+
task_pool = self.task_pool
|
| 573 |
+
if task_pool is None:
|
| 574 |
+
task_pool = experiment_name
|
| 575 |
+
_id_list = []
|
| 576 |
+
for rec in recs:
|
| 577 |
+
_id_list.append(rec.list_tags()[self.TM_ID])
|
| 578 |
+
|
| 579 |
+
query = {"_id": {"$in": _id_list}}
|
| 580 |
+
if not self.skip_run_task:
|
| 581 |
+
run_task(
|
| 582 |
+
end_train_func,
|
| 583 |
+
task_pool,
|
| 584 |
+
query=query, # only train these tasks
|
| 585 |
+
experiment_name=experiment_name,
|
| 586 |
+
before_status=TaskManager.STATUS_PART_DONE,
|
| 587 |
+
**kwargs,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
TaskManager(task_pool=task_pool).wait(query=query)
|
| 591 |
+
|
| 592 |
+
for rec in recs:
|
| 593 |
+
rec.set_tags(**{self.STATUS_KEY: self.STATUS_END})
|
| 594 |
+
return recs
|
| 595 |
+
|
| 596 |
+
def worker(self, end_train_func=None, experiment_name: str = None):
|
| 597 |
+
"""
|
| 598 |
+
The multiprocessing method for `end_train`. It can share a same task_pool with `end_train` and can run in other progress or other machines.
|
| 599 |
+
|
| 600 |
+
Args:
|
| 601 |
+
end_train_func (Callable, optional): the end_train method which need at least `recorders` and `experiment_name`. Defaults to None for using self.end_train_func.
|
| 602 |
+
experiment_name (str): the experiment name, None for use default name.
|
| 603 |
+
"""
|
| 604 |
+
if end_train_func is None:
|
| 605 |
+
end_train_func = self.end_train_func
|
| 606 |
+
if experiment_name is None:
|
| 607 |
+
experiment_name = self.experiment_name
|
| 608 |
+
task_pool = self.task_pool
|
| 609 |
+
if task_pool is None:
|
| 610 |
+
task_pool = experiment_name
|
| 611 |
+
run_task(
|
| 612 |
+
end_train_func,
|
| 613 |
+
task_pool=task_pool,
|
| 614 |
+
experiment_name=experiment_name,
|
| 615 |
+
before_status=TaskManager.STATUS_PART_DONE,
|
| 616 |
+
)
|
| 617 |
+
|
| 618 |
+
def has_worker(self) -> bool:
|
| 619 |
+
return True
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/utils.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from torch.utils.data import Dataset
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class ConcatDataset(Dataset):
|
| 8 |
+
def __init__(self, *datasets):
|
| 9 |
+
self.datasets = datasets
|
| 10 |
+
|
| 11 |
+
def __getitem__(self, i):
|
| 12 |
+
return tuple(d[i] for d in self.datasets)
|
| 13 |
+
|
| 14 |
+
def __len__(self):
|
| 15 |
+
return min(len(d) for d in self.datasets)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class IndexSampler:
|
| 19 |
+
def __init__(self, sampler):
|
| 20 |
+
self.sampler = sampler
|
| 21 |
+
|
| 22 |
+
def __getitem__(self, i: int):
|
| 23 |
+
return self.sampler[i], i
|
| 24 |
+
|
| 25 |
+
def __len__(self):
|
| 26 |
+
return len(self.sampler)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from .interpreter import Interpreter, StateInterpreter, ActionInterpreter
|
| 5 |
+
from .reward import Reward, RewardCombination
|
| 6 |
+
from .simulator import Simulator
|
| 7 |
+
|
| 8 |
+
__all__ = ["Interpreter", "StateInterpreter", "ActionInterpreter", "Reward", "RewardCombination", "Simulator"]
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/aux_info.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import TYPE_CHECKING, Generic, Optional, TypeVar
|
| 7 |
+
|
| 8 |
+
from qlib.typehint import final
|
| 9 |
+
|
| 10 |
+
from .simulator import StateType
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from .utils.env_wrapper import EnvWrapper
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
__all__ = ["AuxiliaryInfoCollector"]
|
| 17 |
+
|
| 18 |
+
AuxInfoType = TypeVar("AuxInfoType")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AuxiliaryInfoCollector(Generic[StateType, AuxInfoType]):
|
| 22 |
+
"""Override this class to collect customized auxiliary information from environment."""
|
| 23 |
+
|
| 24 |
+
env: Optional[EnvWrapper] = None
|
| 25 |
+
|
| 26 |
+
@final
|
| 27 |
+
def __call__(self, simulator_state: StateType) -> AuxInfoType:
|
| 28 |
+
return self.collect(simulator_state)
|
| 29 |
+
|
| 30 |
+
def collect(self, simulator_state: StateType) -> AuxInfoType:
|
| 31 |
+
"""Override this for customized auxiliary info.
|
| 32 |
+
Usually useful in Multi-agent RL.
|
| 33 |
+
|
| 34 |
+
Parameters
|
| 35 |
+
----------
|
| 36 |
+
simulator_state
|
| 37 |
+
Retrieved with ``simulator.get_state()``.
|
| 38 |
+
|
| 39 |
+
Returns
|
| 40 |
+
-------
|
| 41 |
+
Auxiliary information.
|
| 42 |
+
"""
|
| 43 |
+
raise NotImplementedError("collect is not implemented!")
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/__init__.py
ADDED
|
File without changes
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/backtest.py
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import copy
|
| 7 |
+
import os
|
| 8 |
+
import pickle
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Dict, List, Optional, Tuple, Union, cast
|
| 12 |
+
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
import torch
|
| 16 |
+
from joblib import Parallel, delayed
|
| 17 |
+
|
| 18 |
+
from qlib.backtest import INDICATOR_METRIC, collect_data_loop, get_strategy_executor
|
| 19 |
+
from qlib.backtest.decision import BaseTradeDecision, Order, OrderDir, TradeRangeByTime
|
| 20 |
+
from qlib.backtest.executor import SimulatorExecutor
|
| 21 |
+
from qlib.backtest.high_performance_ds import BaseOrderIndicator
|
| 22 |
+
from qlib.rl.contrib.naive_config_parser import get_backtest_config_fromfile
|
| 23 |
+
from qlib.rl.contrib.utils import read_order_file
|
| 24 |
+
from qlib.rl.data.integration import init_qlib
|
| 25 |
+
from qlib.rl.order_execution.simulator_qlib import SingleAssetOrderExecution
|
| 26 |
+
from qlib.typehint import Literal
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _get_multi_level_executor_config(
|
| 30 |
+
strategy_config: dict,
|
| 31 |
+
cash_limit: float | None = None,
|
| 32 |
+
generate_report: bool = False,
|
| 33 |
+
data_granularity: str = "1min",
|
| 34 |
+
) -> dict:
|
| 35 |
+
executor_config = {
|
| 36 |
+
"class": "SimulatorExecutor",
|
| 37 |
+
"module_path": "qlib.backtest.executor",
|
| 38 |
+
"kwargs": {
|
| 39 |
+
"time_per_step": data_granularity,
|
| 40 |
+
"verbose": False,
|
| 41 |
+
"trade_type": SimulatorExecutor.TT_PARAL if cash_limit is not None else SimulatorExecutor.TT_SERIAL,
|
| 42 |
+
"generate_report": generate_report,
|
| 43 |
+
"track_data": True,
|
| 44 |
+
},
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
freqs = list(strategy_config.keys())
|
| 48 |
+
freqs.sort(key=pd.Timedelta)
|
| 49 |
+
for freq in freqs:
|
| 50 |
+
executor_config = {
|
| 51 |
+
"class": "NestedExecutor",
|
| 52 |
+
"module_path": "qlib.backtest.executor",
|
| 53 |
+
"kwargs": {
|
| 54 |
+
"time_per_step": freq,
|
| 55 |
+
"inner_strategy": strategy_config[freq],
|
| 56 |
+
"inner_executor": executor_config,
|
| 57 |
+
"track_data": True,
|
| 58 |
+
},
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
return executor_config
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _convert_indicator_to_dataframe(indicator: dict) -> Optional[pd.DataFrame]:
|
| 65 |
+
record_list = []
|
| 66 |
+
for time, value_dict in indicator.items():
|
| 67 |
+
if isinstance(value_dict, BaseOrderIndicator):
|
| 68 |
+
# HACK: for qlib v0.8
|
| 69 |
+
value_dict = value_dict.to_series()
|
| 70 |
+
try:
|
| 71 |
+
value_dict = copy.deepcopy(value_dict)
|
| 72 |
+
if value_dict["ffr"].empty:
|
| 73 |
+
continue
|
| 74 |
+
except Exception:
|
| 75 |
+
value_dict = {k: v for k, v in value_dict.items() if k != "pa"}
|
| 76 |
+
value_dict = pd.DataFrame(value_dict)
|
| 77 |
+
value_dict["datetime"] = time
|
| 78 |
+
record_list.append(value_dict)
|
| 79 |
+
|
| 80 |
+
if not record_list:
|
| 81 |
+
return None
|
| 82 |
+
|
| 83 |
+
records: pd.DataFrame = pd.concat(record_list, 0).reset_index().rename(columns={"index": "instrument"})
|
| 84 |
+
records = records.set_index(["instrument", "datetime"])
|
| 85 |
+
return records
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _generate_report(
|
| 89 |
+
decisions: List[BaseTradeDecision],
|
| 90 |
+
report_indicators: List[INDICATOR_METRIC],
|
| 91 |
+
) -> Dict[str, Tuple[pd.DataFrame, pd.DataFrame]]:
|
| 92 |
+
"""Generate backtest reports
|
| 93 |
+
|
| 94 |
+
Parameters
|
| 95 |
+
----------
|
| 96 |
+
decisions:
|
| 97 |
+
List of trade decisions.
|
| 98 |
+
report_indicators
|
| 99 |
+
List of indicator reports.
|
| 100 |
+
Returns
|
| 101 |
+
-------
|
| 102 |
+
|
| 103 |
+
"""
|
| 104 |
+
indicator_dict: Dict[str, List[pd.DataFrame]] = defaultdict(list)
|
| 105 |
+
indicator_his: Dict[str, List[dict]] = defaultdict(list)
|
| 106 |
+
|
| 107 |
+
for report_indicator in report_indicators:
|
| 108 |
+
for key, (indicator_df, indicator_obj) in report_indicator.items():
|
| 109 |
+
indicator_dict[key].append(indicator_df)
|
| 110 |
+
indicator_his[key].append(indicator_obj.order_indicator_his)
|
| 111 |
+
|
| 112 |
+
report = {}
|
| 113 |
+
decision_details = pd.concat([getattr(d, "details") for d in decisions if hasattr(d, "details")])
|
| 114 |
+
for key in indicator_dict:
|
| 115 |
+
cur_dict = pd.concat(indicator_dict[key])
|
| 116 |
+
cur_his = pd.concat([_convert_indicator_to_dataframe(his) for his in indicator_his[key]])
|
| 117 |
+
cur_details = decision_details[decision_details.freq == key].set_index(["instrument", "datetime"])
|
| 118 |
+
if len(cur_details) > 0:
|
| 119 |
+
cur_details.pop("freq")
|
| 120 |
+
cur_his = cur_his.join(cur_details, how="outer")
|
| 121 |
+
|
| 122 |
+
report[key] = (cur_dict, cur_his)
|
| 123 |
+
|
| 124 |
+
return report
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def single_with_simulator(
|
| 128 |
+
backtest_config: dict,
|
| 129 |
+
orders: pd.DataFrame,
|
| 130 |
+
split: Literal["stock", "day"] = "stock",
|
| 131 |
+
cash_limit: float | None = None,
|
| 132 |
+
generate_report: bool = False,
|
| 133 |
+
) -> Union[Tuple[pd.DataFrame, dict], pd.DataFrame]:
|
| 134 |
+
"""Run backtest in a single thread with SingleAssetOrderExecution simulator. The orders will be executed day by day.
|
| 135 |
+
A new simulator will be created and used for every single-day order.
|
| 136 |
+
|
| 137 |
+
Parameters
|
| 138 |
+
----------
|
| 139 |
+
backtest_config:
|
| 140 |
+
Backtest config
|
| 141 |
+
orders:
|
| 142 |
+
Orders to be executed. Example format:
|
| 143 |
+
datetime instrument amount direction
|
| 144 |
+
0 2020-06-01 INST 600.0 0
|
| 145 |
+
1 2020-06-02 INST 700.0 1
|
| 146 |
+
...
|
| 147 |
+
split
|
| 148 |
+
Method to split orders. If it is "stock", split orders by stock. If it is "day", split orders by date.
|
| 149 |
+
cash_limit
|
| 150 |
+
Limitation of cash.
|
| 151 |
+
generate_report
|
| 152 |
+
Whether to generate reports.
|
| 153 |
+
|
| 154 |
+
Returns
|
| 155 |
+
-------
|
| 156 |
+
If generate_report is True, return execution records and the generated report. Otherwise, return only records.
|
| 157 |
+
"""
|
| 158 |
+
init_qlib(backtest_config["qlib"])
|
| 159 |
+
|
| 160 |
+
stocks = orders.instrument.unique().tolist()
|
| 161 |
+
|
| 162 |
+
reports = []
|
| 163 |
+
decisions = []
|
| 164 |
+
for _, row in orders.iterrows():
|
| 165 |
+
date = pd.Timestamp(row["datetime"])
|
| 166 |
+
start_time = pd.Timestamp(backtest_config["start_time"]).replace(year=date.year, month=date.month, day=date.day)
|
| 167 |
+
end_time = pd.Timestamp(backtest_config["end_time"]).replace(year=date.year, month=date.month, day=date.day)
|
| 168 |
+
order = Order(
|
| 169 |
+
stock_id=row["instrument"],
|
| 170 |
+
amount=row["amount"],
|
| 171 |
+
direction=OrderDir(row["direction"]),
|
| 172 |
+
start_time=start_time,
|
| 173 |
+
end_time=end_time,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
executor_config = _get_multi_level_executor_config(
|
| 177 |
+
strategy_config=backtest_config["strategies"],
|
| 178 |
+
cash_limit=cash_limit,
|
| 179 |
+
generate_report=generate_report,
|
| 180 |
+
data_granularity=backtest_config["data_granularity"],
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
exchange_config = copy.deepcopy(backtest_config["exchange"])
|
| 184 |
+
exchange_config.update(
|
| 185 |
+
{
|
| 186 |
+
"codes": stocks,
|
| 187 |
+
"freq": backtest_config["data_granularity"],
|
| 188 |
+
}
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
simulator = SingleAssetOrderExecution(
|
| 192 |
+
order=order,
|
| 193 |
+
executor_config=executor_config,
|
| 194 |
+
exchange_config=exchange_config,
|
| 195 |
+
qlib_config=None,
|
| 196 |
+
cash_limit=None,
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
reports.append(simulator.report_dict)
|
| 200 |
+
decisions += simulator.decisions
|
| 201 |
+
|
| 202 |
+
indicator_1day_objs = [report["indicator_dict"]["1day"][1] for report in reports]
|
| 203 |
+
indicator_info = {k: v for obj in indicator_1day_objs for k, v in obj.order_indicator_his.items()}
|
| 204 |
+
records = _convert_indicator_to_dataframe(indicator_info)
|
| 205 |
+
assert records is None or not np.isnan(records["ffr"]).any()
|
| 206 |
+
|
| 207 |
+
if generate_report:
|
| 208 |
+
_report = _generate_report(decisions, [report["indicator"] for report in reports])
|
| 209 |
+
|
| 210 |
+
if split == "stock":
|
| 211 |
+
stock_id = orders.iloc[0].instrument
|
| 212 |
+
report = {stock_id: _report}
|
| 213 |
+
else:
|
| 214 |
+
day = orders.iloc[0].datetime
|
| 215 |
+
report = {day: _report}
|
| 216 |
+
|
| 217 |
+
return records, report
|
| 218 |
+
else:
|
| 219 |
+
return records
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def single_with_collect_data_loop(
|
| 223 |
+
backtest_config: dict,
|
| 224 |
+
orders: pd.DataFrame,
|
| 225 |
+
split: Literal["stock", "day"] = "stock",
|
| 226 |
+
cash_limit: float | None = None,
|
| 227 |
+
generate_report: bool = False,
|
| 228 |
+
) -> Union[Tuple[pd.DataFrame, dict], pd.DataFrame]:
|
| 229 |
+
"""Run backtest in a single thread with collect_data_loop.
|
| 230 |
+
|
| 231 |
+
Parameters
|
| 232 |
+
----------
|
| 233 |
+
backtest_config:
|
| 234 |
+
Backtest config
|
| 235 |
+
orders:
|
| 236 |
+
Orders to be executed. Example format:
|
| 237 |
+
datetime instrument amount direction
|
| 238 |
+
0 2020-06-01 INST 600.0 0
|
| 239 |
+
1 2020-06-02 INST 700.0 1
|
| 240 |
+
...
|
| 241 |
+
split
|
| 242 |
+
Method to split orders. If it is "stock", split orders by stock. If it is "day", split orders by date.
|
| 243 |
+
cash_limit
|
| 244 |
+
Limitation of cash.
|
| 245 |
+
generate_report
|
| 246 |
+
Whether to generate reports.
|
| 247 |
+
|
| 248 |
+
Returns
|
| 249 |
+
-------
|
| 250 |
+
If generate_report is True, return execution records and the generated report. Otherwise, return only records.
|
| 251 |
+
"""
|
| 252 |
+
|
| 253 |
+
init_qlib(backtest_config["qlib"])
|
| 254 |
+
|
| 255 |
+
trade_start_time = orders["datetime"].min()
|
| 256 |
+
trade_end_time = orders["datetime"].max()
|
| 257 |
+
stocks = orders.instrument.unique().tolist()
|
| 258 |
+
|
| 259 |
+
strategy_config = {
|
| 260 |
+
"class": "FileOrderStrategy",
|
| 261 |
+
"module_path": "qlib.contrib.strategy.rule_strategy",
|
| 262 |
+
"kwargs": {
|
| 263 |
+
"file": orders,
|
| 264 |
+
"trade_range": TradeRangeByTime(
|
| 265 |
+
pd.Timestamp(backtest_config["start_time"]).time(),
|
| 266 |
+
pd.Timestamp(backtest_config["end_time"]).time(),
|
| 267 |
+
),
|
| 268 |
+
},
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
executor_config = _get_multi_level_executor_config(
|
| 272 |
+
strategy_config=backtest_config["strategies"],
|
| 273 |
+
cash_limit=cash_limit,
|
| 274 |
+
generate_report=generate_report,
|
| 275 |
+
data_granularity=backtest_config["data_granularity"],
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
exchange_config = copy.deepcopy(backtest_config["exchange"])
|
| 279 |
+
exchange_config.update(
|
| 280 |
+
{
|
| 281 |
+
"codes": stocks,
|
| 282 |
+
"freq": backtest_config["data_granularity"],
|
| 283 |
+
}
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
strategy, executor = get_strategy_executor(
|
| 287 |
+
start_time=pd.Timestamp(trade_start_time),
|
| 288 |
+
end_time=pd.Timestamp(trade_end_time) + pd.DateOffset(1),
|
| 289 |
+
strategy=strategy_config,
|
| 290 |
+
executor=executor_config,
|
| 291 |
+
benchmark=None,
|
| 292 |
+
account=cash_limit if cash_limit is not None else int(1e12),
|
| 293 |
+
exchange_kwargs=exchange_config,
|
| 294 |
+
pos_type="Position" if cash_limit is not None else "InfPosition",
|
| 295 |
+
)
|
| 296 |
+
|
| 297 |
+
report_dict: dict = {}
|
| 298 |
+
decisions = list(collect_data_loop(trade_start_time, trade_end_time, strategy, executor, report_dict))
|
| 299 |
+
|
| 300 |
+
indicator_dict = cast(INDICATOR_METRIC, report_dict.get("indicator_dict"))
|
| 301 |
+
records = _convert_indicator_to_dataframe(indicator_dict["1day"][1].order_indicator_his)
|
| 302 |
+
assert records is None or not np.isnan(records["ffr"]).any()
|
| 303 |
+
|
| 304 |
+
if generate_report:
|
| 305 |
+
_report = _generate_report(decisions, [indicator_dict])
|
| 306 |
+
if split == "stock":
|
| 307 |
+
stock_id = orders.iloc[0].instrument
|
| 308 |
+
report = {stock_id: _report}
|
| 309 |
+
else:
|
| 310 |
+
day = orders.iloc[0].datetime
|
| 311 |
+
report = {day: _report}
|
| 312 |
+
return records, report
|
| 313 |
+
else:
|
| 314 |
+
return records
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def backtest(backtest_config: dict, with_simulator: bool = False) -> pd.DataFrame:
|
| 318 |
+
order_df = read_order_file(backtest_config["order_file"])
|
| 319 |
+
|
| 320 |
+
cash_limit = backtest_config["exchange"].pop("cash_limit")
|
| 321 |
+
generate_report = backtest_config.pop("generate_report")
|
| 322 |
+
|
| 323 |
+
stock_pool = order_df["instrument"].unique().tolist()
|
| 324 |
+
stock_pool.sort()
|
| 325 |
+
|
| 326 |
+
single = single_with_simulator if with_simulator else single_with_collect_data_loop
|
| 327 |
+
mp_config = {"n_jobs": backtest_config["concurrency"], "verbose": 10, "backend": "multiprocessing"}
|
| 328 |
+
torch.set_num_threads(1) # https://github.com/pytorch/pytorch/issues/17199
|
| 329 |
+
res = Parallel(**mp_config)(
|
| 330 |
+
delayed(single)(
|
| 331 |
+
backtest_config=backtest_config,
|
| 332 |
+
orders=order_df[order_df["instrument"] == stock].copy(),
|
| 333 |
+
split="stock",
|
| 334 |
+
cash_limit=cash_limit,
|
| 335 |
+
generate_report=generate_report,
|
| 336 |
+
)
|
| 337 |
+
for stock in stock_pool
|
| 338 |
+
)
|
| 339 |
+
|
| 340 |
+
output_path = Path(backtest_config["output_dir"])
|
| 341 |
+
if generate_report:
|
| 342 |
+
with (output_path / "report.pkl").open("wb") as f:
|
| 343 |
+
report = {}
|
| 344 |
+
for r in res:
|
| 345 |
+
report.update(r[1])
|
| 346 |
+
pickle.dump(report, f)
|
| 347 |
+
res = pd.concat([r[0] for r in res], 0)
|
| 348 |
+
else:
|
| 349 |
+
res = pd.concat(res)
|
| 350 |
+
|
| 351 |
+
if not output_path.exists():
|
| 352 |
+
os.makedirs(output_path)
|
| 353 |
+
|
| 354 |
+
if "pa" in res.columns:
|
| 355 |
+
res["pa"] = res["pa"] * 10000.0 # align with training metrics
|
| 356 |
+
res.to_csv(output_path / "backtest_result.csv")
|
| 357 |
+
return res
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
if __name__ == "__main__":
|
| 361 |
+
import warnings
|
| 362 |
+
|
| 363 |
+
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
| 364 |
+
warnings.filterwarnings("ignore", category=RuntimeWarning)
|
| 365 |
+
|
| 366 |
+
parser = argparse.ArgumentParser()
|
| 367 |
+
parser.add_argument("--config_path", type=str, required=True, help="Path to the config file")
|
| 368 |
+
parser.add_argument("--use_simulator", action="store_true", help="Whether to use simulator as the backend")
|
| 369 |
+
parser.add_argument(
|
| 370 |
+
"--n_jobs",
|
| 371 |
+
type=int,
|
| 372 |
+
required=False,
|
| 373 |
+
help="The number of jobs for running backtest parallely(1 for single process)",
|
| 374 |
+
)
|
| 375 |
+
args = parser.parse_args()
|
| 376 |
+
|
| 377 |
+
config = get_backtest_config_fromfile(args.config_path)
|
| 378 |
+
if args.n_jobs is not None:
|
| 379 |
+
config["concurrency"] = args.n_jobs
|
| 380 |
+
|
| 381 |
+
backtest(
|
| 382 |
+
backtest_config=config,
|
| 383 |
+
with_simulator=args.use_simulator,
|
| 384 |
+
)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/naive_config_parser.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
import os
|
| 5 |
+
import platform
|
| 6 |
+
import shutil
|
| 7 |
+
import sys
|
| 8 |
+
import tempfile
|
| 9 |
+
from importlib import import_module
|
| 10 |
+
from ruamel.yaml import YAML
|
| 11 |
+
|
| 12 |
+
DELETE_KEY = "_delete_"
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def merge_a_into_b(a: dict, b: dict) -> dict:
|
| 16 |
+
b = b.copy()
|
| 17 |
+
for k, v in a.items():
|
| 18 |
+
if isinstance(v, dict) and k in b:
|
| 19 |
+
v.pop(DELETE_KEY, False)
|
| 20 |
+
b[k] = merge_a_into_b(v, b[k])
|
| 21 |
+
else:
|
| 22 |
+
b[k] = v
|
| 23 |
+
return b
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def check_file_exist(filename: str, msg_tmpl: str = 'file "{}" does not exist') -> None:
|
| 27 |
+
if not os.path.isfile(filename):
|
| 28 |
+
raise FileNotFoundError(msg_tmpl.format(filename))
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def parse_backtest_config(path: str) -> dict:
|
| 32 |
+
abs_path = os.path.abspath(path)
|
| 33 |
+
check_file_exist(abs_path)
|
| 34 |
+
|
| 35 |
+
file_ext_name = os.path.splitext(abs_path)[1]
|
| 36 |
+
if file_ext_name not in (".py", ".json", ".yaml", ".yml"):
|
| 37 |
+
raise IOError("Only py/yml/yaml/json type are supported now!")
|
| 38 |
+
|
| 39 |
+
with tempfile.TemporaryDirectory() as tmp_config_dir:
|
| 40 |
+
with tempfile.NamedTemporaryFile(dir=tmp_config_dir, suffix=file_ext_name) as tmp_config_file:
|
| 41 |
+
if platform.system() == "Windows":
|
| 42 |
+
tmp_config_file.close()
|
| 43 |
+
|
| 44 |
+
tmp_config_name = os.path.basename(tmp_config_file.name)
|
| 45 |
+
shutil.copyfile(abs_path, tmp_config_file.name)
|
| 46 |
+
|
| 47 |
+
if abs_path.endswith(".py"):
|
| 48 |
+
tmp_module_name = os.path.splitext(tmp_config_name)[0]
|
| 49 |
+
sys.path.insert(0, tmp_config_dir)
|
| 50 |
+
module = import_module(tmp_module_name)
|
| 51 |
+
sys.path.pop(0)
|
| 52 |
+
|
| 53 |
+
config = {k: v for k, v in module.__dict__.items() if not k.startswith("__")}
|
| 54 |
+
|
| 55 |
+
del sys.modules[tmp_module_name]
|
| 56 |
+
else:
|
| 57 |
+
with open(tmp_config_file.name) as input_stream:
|
| 58 |
+
yaml = YAML(typ="safe", pure=True)
|
| 59 |
+
config = yaml.load(input_stream)
|
| 60 |
+
|
| 61 |
+
if "_base_" in config:
|
| 62 |
+
base_file_name = config.pop("_base_")
|
| 63 |
+
if not isinstance(base_file_name, list):
|
| 64 |
+
base_file_name = [base_file_name]
|
| 65 |
+
|
| 66 |
+
for f in base_file_name:
|
| 67 |
+
base_config = parse_backtest_config(os.path.join(os.path.dirname(abs_path), f))
|
| 68 |
+
config = merge_a_into_b(a=config, b=base_config)
|
| 69 |
+
|
| 70 |
+
return config
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _convert_all_list_to_tuple(config: dict) -> dict:
|
| 74 |
+
for k, v in config.items():
|
| 75 |
+
if isinstance(v, list):
|
| 76 |
+
config[k] = tuple(v)
|
| 77 |
+
elif isinstance(v, dict):
|
| 78 |
+
config[k] = _convert_all_list_to_tuple(v)
|
| 79 |
+
return config
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def get_backtest_config_fromfile(path: str) -> dict:
|
| 83 |
+
backtest_config = parse_backtest_config(path)
|
| 84 |
+
|
| 85 |
+
exchange_config_default = {
|
| 86 |
+
"open_cost": 0.0005,
|
| 87 |
+
"close_cost": 0.0015,
|
| 88 |
+
"min_cost": 5.0,
|
| 89 |
+
"trade_unit": 100.0,
|
| 90 |
+
"cash_limit": None,
|
| 91 |
+
}
|
| 92 |
+
backtest_config["exchange"] = merge_a_into_b(a=backtest_config["exchange"], b=exchange_config_default)
|
| 93 |
+
backtest_config["exchange"] = _convert_all_list_to_tuple(backtest_config["exchange"])
|
| 94 |
+
|
| 95 |
+
backtest_config_default = {
|
| 96 |
+
"debug_single_stock": None,
|
| 97 |
+
"debug_single_day": None,
|
| 98 |
+
"concurrency": -1,
|
| 99 |
+
"multiplier": 1.0,
|
| 100 |
+
"output_dir": "outputs_backtest/",
|
| 101 |
+
"generate_report": False,
|
| 102 |
+
"data_granularity": "1min",
|
| 103 |
+
}
|
| 104 |
+
backtest_config = merge_a_into_b(a=backtest_config, b=backtest_config_default)
|
| 105 |
+
|
| 106 |
+
return backtest_config
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/train_onpolicy.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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+
|
| 5 |
+
import argparse
|
| 6 |
+
import os
|
| 7 |
+
import random
|
| 8 |
+
import sys
|
| 9 |
+
import warnings
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from ruamel.yaml import YAML
|
| 12 |
+
from typing import cast, List, Optional
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
import torch
|
| 17 |
+
from qlib.backtest import Order
|
| 18 |
+
from qlib.backtest.decision import OrderDir
|
| 19 |
+
from qlib.constant import ONE_MIN
|
| 20 |
+
from qlib.rl.data.native import load_handler_intraday_processed_data
|
| 21 |
+
from qlib.rl.interpreter import ActionInterpreter, StateInterpreter
|
| 22 |
+
from qlib.rl.order_execution import SingleAssetOrderExecutionSimple
|
| 23 |
+
from qlib.rl.reward import Reward
|
| 24 |
+
from qlib.rl.trainer import Checkpoint, backtest, train
|
| 25 |
+
from qlib.rl.trainer.callbacks import Callback, EarlyStopping, MetricsWriter
|
| 26 |
+
from qlib.rl.utils.log import CsvWriter
|
| 27 |
+
from qlib.utils import init_instance_by_config
|
| 28 |
+
from tianshou.policy import BasePolicy
|
| 29 |
+
from torch.utils.data import Dataset
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def seed_everything(seed: int) -> None:
|
| 33 |
+
torch.manual_seed(seed)
|
| 34 |
+
torch.cuda.manual_seed_all(seed)
|
| 35 |
+
np.random.seed(seed)
|
| 36 |
+
random.seed(seed)
|
| 37 |
+
torch.backends.cudnn.deterministic = True
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _read_orders(order_dir: Path) -> pd.DataFrame:
|
| 41 |
+
if os.path.isfile(order_dir):
|
| 42 |
+
return pd.read_pickle(order_dir)
|
| 43 |
+
else:
|
| 44 |
+
orders = []
|
| 45 |
+
for file in order_dir.iterdir():
|
| 46 |
+
order_data = pd.read_pickle(file)
|
| 47 |
+
orders.append(order_data)
|
| 48 |
+
return pd.concat(orders)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class LazyLoadDataset(Dataset):
|
| 52 |
+
def __init__(
|
| 53 |
+
self,
|
| 54 |
+
data_dir: str,
|
| 55 |
+
order_file_path: Path,
|
| 56 |
+
default_start_time_index: int,
|
| 57 |
+
default_end_time_index: int,
|
| 58 |
+
) -> None:
|
| 59 |
+
self._default_start_time_index = default_start_time_index
|
| 60 |
+
self._default_end_time_index = default_end_time_index
|
| 61 |
+
|
| 62 |
+
self._order_df = _read_orders(order_file_path).reset_index()
|
| 63 |
+
self._ticks_index: Optional[pd.DatetimeIndex] = None
|
| 64 |
+
self._data_dir = Path(data_dir)
|
| 65 |
+
|
| 66 |
+
def __len__(self) -> int:
|
| 67 |
+
return len(self._order_df)
|
| 68 |
+
|
| 69 |
+
def __getitem__(self, index: int) -> Order:
|
| 70 |
+
row = self._order_df.iloc[index]
|
| 71 |
+
date = pd.Timestamp(str(row["date"]))
|
| 72 |
+
|
| 73 |
+
if self._ticks_index is None:
|
| 74 |
+
# TODO: We only load ticks index once based on the assumption that ticks index of different dates
|
| 75 |
+
# TODO: in one experiment are all the same. If that assumption is not hold, we need to load ticks index
|
| 76 |
+
# TODO: of all dates.
|
| 77 |
+
|
| 78 |
+
data = load_handler_intraday_processed_data(
|
| 79 |
+
data_dir=self._data_dir,
|
| 80 |
+
stock_id=row["instrument"],
|
| 81 |
+
date=date,
|
| 82 |
+
feature_columns_today=[],
|
| 83 |
+
feature_columns_yesterday=[],
|
| 84 |
+
backtest=True,
|
| 85 |
+
index_only=True,
|
| 86 |
+
)
|
| 87 |
+
self._ticks_index = [t - date for t in data.today.index]
|
| 88 |
+
|
| 89 |
+
order = Order(
|
| 90 |
+
stock_id=row["instrument"],
|
| 91 |
+
amount=row["amount"],
|
| 92 |
+
direction=OrderDir(int(row["order_type"])),
|
| 93 |
+
start_time=date + self._ticks_index[self._default_start_time_index],
|
| 94 |
+
end_time=date + self._ticks_index[self._default_end_time_index - 1] + ONE_MIN,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
return order
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def train_and_test(
|
| 101 |
+
env_config: dict,
|
| 102 |
+
simulator_config: dict,
|
| 103 |
+
trainer_config: dict,
|
| 104 |
+
data_config: dict,
|
| 105 |
+
state_interpreter: StateInterpreter,
|
| 106 |
+
action_interpreter: ActionInterpreter,
|
| 107 |
+
policy: BasePolicy,
|
| 108 |
+
reward: Reward,
|
| 109 |
+
run_training: bool,
|
| 110 |
+
run_backtest: bool,
|
| 111 |
+
) -> None:
|
| 112 |
+
order_root_path = Path(data_config["source"]["order_dir"])
|
| 113 |
+
|
| 114 |
+
data_granularity = simulator_config.get("data_granularity", 1)
|
| 115 |
+
|
| 116 |
+
def _simulator_factory_simple(order: Order) -> SingleAssetOrderExecutionSimple:
|
| 117 |
+
return SingleAssetOrderExecutionSimple(
|
| 118 |
+
order=order,
|
| 119 |
+
data_dir=data_config["source"]["feature_root_dir"],
|
| 120 |
+
feature_columns_today=data_config["source"]["feature_columns_today"],
|
| 121 |
+
feature_columns_yesterday=data_config["source"]["feature_columns_yesterday"],
|
| 122 |
+
data_granularity=data_granularity,
|
| 123 |
+
ticks_per_step=simulator_config["time_per_step"],
|
| 124 |
+
vol_threshold=simulator_config["vol_limit"],
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
assert data_config["source"]["default_start_time_index"] % data_granularity == 0
|
| 128 |
+
assert data_config["source"]["default_end_time_index"] % data_granularity == 0
|
| 129 |
+
|
| 130 |
+
if run_training:
|
| 131 |
+
train_dataset, valid_dataset = [
|
| 132 |
+
LazyLoadDataset(
|
| 133 |
+
data_dir=data_config["source"]["feature_root_dir"],
|
| 134 |
+
order_file_path=order_root_path / tag,
|
| 135 |
+
default_start_time_index=data_config["source"]["default_start_time_index"] // data_granularity,
|
| 136 |
+
default_end_time_index=data_config["source"]["default_end_time_index"] // data_granularity,
|
| 137 |
+
)
|
| 138 |
+
for tag in ("train", "valid")
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
callbacks: List[Callback] = []
|
| 142 |
+
if "checkpoint_path" in trainer_config:
|
| 143 |
+
callbacks.append(MetricsWriter(dirpath=Path(trainer_config["checkpoint_path"])))
|
| 144 |
+
callbacks.append(
|
| 145 |
+
Checkpoint(
|
| 146 |
+
dirpath=Path(trainer_config["checkpoint_path"]) / "checkpoints",
|
| 147 |
+
every_n_iters=trainer_config.get("checkpoint_every_n_iters", 1),
|
| 148 |
+
save_latest="copy",
|
| 149 |
+
),
|
| 150 |
+
)
|
| 151 |
+
if "earlystop_patience" in trainer_config:
|
| 152 |
+
callbacks.append(
|
| 153 |
+
EarlyStopping(
|
| 154 |
+
patience=trainer_config["earlystop_patience"],
|
| 155 |
+
monitor="val/pa",
|
| 156 |
+
)
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
train(
|
| 160 |
+
simulator_fn=_simulator_factory_simple,
|
| 161 |
+
state_interpreter=state_interpreter,
|
| 162 |
+
action_interpreter=action_interpreter,
|
| 163 |
+
policy=policy,
|
| 164 |
+
reward=reward,
|
| 165 |
+
initial_states=cast(List[Order], train_dataset),
|
| 166 |
+
trainer_kwargs={
|
| 167 |
+
"max_iters": trainer_config["max_epoch"],
|
| 168 |
+
"finite_env_type": env_config["parallel_mode"],
|
| 169 |
+
"concurrency": env_config["concurrency"],
|
| 170 |
+
"val_every_n_iters": trainer_config.get("val_every_n_epoch", None),
|
| 171 |
+
"callbacks": callbacks,
|
| 172 |
+
},
|
| 173 |
+
vessel_kwargs={
|
| 174 |
+
"episode_per_iter": trainer_config["episode_per_collect"],
|
| 175 |
+
"update_kwargs": {
|
| 176 |
+
"batch_size": trainer_config["batch_size"],
|
| 177 |
+
"repeat": trainer_config["repeat_per_collect"],
|
| 178 |
+
},
|
| 179 |
+
"val_initial_states": valid_dataset,
|
| 180 |
+
},
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
if run_backtest:
|
| 184 |
+
test_dataset = LazyLoadDataset(
|
| 185 |
+
data_dir=data_config["source"]["feature_root_dir"],
|
| 186 |
+
order_file_path=order_root_path / "test",
|
| 187 |
+
default_start_time_index=data_config["source"]["default_start_time_index"] // data_granularity,
|
| 188 |
+
default_end_time_index=data_config["source"]["default_end_time_index"] // data_granularity,
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
backtest(
|
| 192 |
+
simulator_fn=_simulator_factory_simple,
|
| 193 |
+
state_interpreter=state_interpreter,
|
| 194 |
+
action_interpreter=action_interpreter,
|
| 195 |
+
initial_states=test_dataset,
|
| 196 |
+
policy=policy,
|
| 197 |
+
logger=CsvWriter(Path(trainer_config["checkpoint_path"])),
|
| 198 |
+
reward=reward,
|
| 199 |
+
finite_env_type=env_config["parallel_mode"],
|
| 200 |
+
concurrency=env_config["concurrency"],
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def main(config: dict, run_training: bool, run_backtest: bool) -> None:
|
| 205 |
+
if not run_training and not run_backtest:
|
| 206 |
+
warnings.warn("Skip the entire job since training and backtest are both skipped.")
|
| 207 |
+
return
|
| 208 |
+
|
| 209 |
+
if "seed" in config["runtime"]:
|
| 210 |
+
seed_everything(config["runtime"]["seed"])
|
| 211 |
+
|
| 212 |
+
for extra_module_path in config["env"].get("extra_module_paths", []):
|
| 213 |
+
sys.path.append(extra_module_path)
|
| 214 |
+
|
| 215 |
+
state_interpreter: StateInterpreter = init_instance_by_config(config["state_interpreter"])
|
| 216 |
+
action_interpreter: ActionInterpreter = init_instance_by_config(config["action_interpreter"])
|
| 217 |
+
reward: Reward = init_instance_by_config(config["reward"])
|
| 218 |
+
|
| 219 |
+
additional_policy_kwargs = {
|
| 220 |
+
"obs_space": state_interpreter.observation_space,
|
| 221 |
+
"action_space": action_interpreter.action_space,
|
| 222 |
+
}
|
| 223 |
+
|
| 224 |
+
# Create torch network
|
| 225 |
+
if "network" in config:
|
| 226 |
+
if "kwargs" not in config["network"]:
|
| 227 |
+
config["network"]["kwargs"] = {}
|
| 228 |
+
config["network"]["kwargs"].update({"obs_space": state_interpreter.observation_space})
|
| 229 |
+
additional_policy_kwargs["network"] = init_instance_by_config(config["network"])
|
| 230 |
+
|
| 231 |
+
# Create policy
|
| 232 |
+
if "kwargs" not in config["policy"]:
|
| 233 |
+
config["policy"]["kwargs"] = {}
|
| 234 |
+
config["policy"]["kwargs"].update(additional_policy_kwargs)
|
| 235 |
+
policy: BasePolicy = init_instance_by_config(config["policy"])
|
| 236 |
+
|
| 237 |
+
use_cuda = config["runtime"].get("use_cuda", False)
|
| 238 |
+
if use_cuda:
|
| 239 |
+
policy.cuda()
|
| 240 |
+
|
| 241 |
+
train_and_test(
|
| 242 |
+
env_config=config["env"],
|
| 243 |
+
simulator_config=config["simulator"],
|
| 244 |
+
data_config=config["data"],
|
| 245 |
+
trainer_config=config["trainer"],
|
| 246 |
+
action_interpreter=action_interpreter,
|
| 247 |
+
state_interpreter=state_interpreter,
|
| 248 |
+
policy=policy,
|
| 249 |
+
reward=reward,
|
| 250 |
+
run_training=run_training,
|
| 251 |
+
run_backtest=run_backtest,
|
| 252 |
+
)
|
| 253 |
+
|
| 254 |
+
|
| 255 |
+
if __name__ == "__main__":
|
| 256 |
+
warnings.filterwarnings("ignore", category=DeprecationWarning)
|
| 257 |
+
warnings.filterwarnings("ignore", category=RuntimeWarning)
|
| 258 |
+
|
| 259 |
+
parser = argparse.ArgumentParser()
|
| 260 |
+
parser.add_argument("--config_path", type=str, required=True, help="Path to the config file")
|
| 261 |
+
parser.add_argument("--no_training", action="store_true", help="Skip training workflow.")
|
| 262 |
+
parser.add_argument("--run_backtest", action="store_true", help="Run backtest workflow.")
|
| 263 |
+
args = parser.parse_args()
|
| 264 |
+
|
| 265 |
+
with open(args.config_path, "r") as input_stream:
|
| 266 |
+
yaml = YAML(typ="safe", pure=True)
|
| 267 |
+
config = yaml.load(input_stream)
|
| 268 |
+
|
| 269 |
+
main(config, run_training=not args.no_training, run_backtest=args.run_backtest)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/utils.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def read_order_file(order_file: Path | pd.DataFrame) -> pd.DataFrame:
|
| 12 |
+
if isinstance(order_file, pd.DataFrame):
|
| 13 |
+
return order_file
|
| 14 |
+
|
| 15 |
+
order_file = Path(order_file)
|
| 16 |
+
|
| 17 |
+
if order_file.suffix == ".pkl":
|
| 18 |
+
order_df = pd.read_pickle(order_file).reset_index()
|
| 19 |
+
elif order_file.suffix == ".csv":
|
| 20 |
+
order_df = pd.read_csv(order_file)
|
| 21 |
+
else:
|
| 22 |
+
raise TypeError(f"Unsupported order file type: {order_file}")
|
| 23 |
+
|
| 24 |
+
if "date" in order_df.columns:
|
| 25 |
+
# legacy dataframe columns
|
| 26 |
+
order_df = order_df.rename(columns={"date": "datetime", "order_type": "direction"})
|
| 27 |
+
order_df["datetime"] = order_df["datetime"].astype(str)
|
| 28 |
+
|
| 29 |
+
return order_df
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""Common utilities to handle ad-hoc-styled data.
|
| 5 |
+
|
| 6 |
+
Most of these snippets comes from research project (paper code).
|
| 7 |
+
Please take caution when using them in production.
|
| 8 |
+
"""
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/base.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from abc import abstractmethod
|
| 6 |
+
|
| 7 |
+
import pandas as pd
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class BaseIntradayBacktestData:
|
| 11 |
+
"""
|
| 12 |
+
Raw market data that is often used in backtesting (thus called BacktestData).
|
| 13 |
+
|
| 14 |
+
Base class for all types of backtest data. Currently, each type of simulator has its corresponding backtest
|
| 15 |
+
data type.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
@abstractmethod
|
| 19 |
+
def __repr__(self) -> str:
|
| 20 |
+
raise NotImplementedError
|
| 21 |
+
|
| 22 |
+
@abstractmethod
|
| 23 |
+
def __len__(self) -> int:
|
| 24 |
+
raise NotImplementedError
|
| 25 |
+
|
| 26 |
+
@abstractmethod
|
| 27 |
+
def get_deal_price(self) -> pd.Series:
|
| 28 |
+
raise NotImplementedError
|
| 29 |
+
|
| 30 |
+
@abstractmethod
|
| 31 |
+
def get_volume(self) -> pd.Series:
|
| 32 |
+
raise NotImplementedError
|
| 33 |
+
|
| 34 |
+
@abstractmethod
|
| 35 |
+
def get_time_index(self) -> pd.DatetimeIndex:
|
| 36 |
+
raise NotImplementedError
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class BaseIntradayProcessedData:
|
| 40 |
+
"""Processed market data after data cleanup and feature engineering.
|
| 41 |
+
|
| 42 |
+
It contains both processed data for "today" and "yesterday", as some algorithms
|
| 43 |
+
might use the market information of the previous day to assist decision making.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
today: pd.DataFrame
|
| 47 |
+
"""Processed data for "today".
|
| 48 |
+
Number of records must be ``time_length``, and columns must be ``feature_dim``."""
|
| 49 |
+
|
| 50 |
+
yesterday: pd.DataFrame
|
| 51 |
+
"""Processed data for "yesterday".
|
| 52 |
+
Number of records must be ``time_length``, and columns must be ``feature_dim``."""
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ProcessedDataProvider:
|
| 56 |
+
"""Provider of processed data"""
|
| 57 |
+
|
| 58 |
+
def get_data(
|
| 59 |
+
self,
|
| 60 |
+
stock_id: str,
|
| 61 |
+
date: pd.Timestamp,
|
| 62 |
+
feature_dim: int,
|
| 63 |
+
time_index: pd.Index,
|
| 64 |
+
) -> BaseIntradayProcessedData:
|
| 65 |
+
raise NotImplementedError
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/integration.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
TODO: This file is used to integrate NeuTrader with Qlib to run the existing projects.
|
| 6 |
+
TODO: The implementation here is kind of adhoc. It is better to design a more uniformed & general implementation.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
import qlib
|
| 14 |
+
from qlib.constant import REG_CN
|
| 15 |
+
from qlib.contrib.ops.high_freq import BFillNan, Cut, Date, DayCumsum, DayLast, FFillNan, IsInf, IsNull, Select
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def init_qlib(qlib_config: dict) -> None:
|
| 19 |
+
"""Initialize necessary resource to launch the workflow, including data direction, feature columns, etc..
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
qlib_config:
|
| 24 |
+
Qlib configuration.
|
| 25 |
+
|
| 26 |
+
Example::
|
| 27 |
+
|
| 28 |
+
{
|
| 29 |
+
"provider_uri_day": DATA_ROOT_DIR / "qlib_1d",
|
| 30 |
+
"provider_uri_1min": DATA_ROOT_DIR / "qlib_1min",
|
| 31 |
+
"feature_root_dir": DATA_ROOT_DIR / "qlib_handler_stock",
|
| 32 |
+
"feature_columns_today": [
|
| 33 |
+
"$open", "$high", "$low", "$close", "$vwap", "$bid", "$ask", "$volume",
|
| 34 |
+
"$bidV", "$bidV1", "$bidV3", "$bidV5", "$askV", "$askV1", "$askV3", "$askV5",
|
| 35 |
+
],
|
| 36 |
+
"feature_columns_yesterday": [
|
| 37 |
+
"$open_1", "$high_1", "$low_1", "$close_1", "$vwap_1", "$bid_1", "$ask_1", "$volume_1",
|
| 38 |
+
"$bidV_1", "$bidV1_1", "$bidV3_1", "$bidV5_1", "$askV_1", "$askV1_1", "$askV3_1", "$askV5_1",
|
| 39 |
+
],
|
| 40 |
+
}
|
| 41 |
+
"""
|
| 42 |
+
|
| 43 |
+
def _convert_to_path(path: str | Path) -> Path:
|
| 44 |
+
return path if isinstance(path, Path) else Path(path)
|
| 45 |
+
|
| 46 |
+
provider_uri_map = {}
|
| 47 |
+
for granularity in ["1min", "5min", "day"]:
|
| 48 |
+
if f"provider_uri_{granularity}" in qlib_config:
|
| 49 |
+
provider_uri_map[f"{granularity}"] = _convert_to_path(qlib_config[f"provider_uri_{granularity}"]).as_posix()
|
| 50 |
+
|
| 51 |
+
qlib.init(
|
| 52 |
+
region=REG_CN,
|
| 53 |
+
auto_mount=False,
|
| 54 |
+
custom_ops=[DayLast, FFillNan, BFillNan, Date, Select, IsNull, IsInf, Cut, DayCumsum],
|
| 55 |
+
expression_cache=None,
|
| 56 |
+
calendar_provider={
|
| 57 |
+
"class": "LocalCalendarProvider",
|
| 58 |
+
"module_path": "qlib.data.data",
|
| 59 |
+
"kwargs": {
|
| 60 |
+
"backend": {
|
| 61 |
+
"class": "FileCalendarStorage",
|
| 62 |
+
"module_path": "qlib.data.storage.file_storage",
|
| 63 |
+
"kwargs": {"provider_uri_map": provider_uri_map},
|
| 64 |
+
},
|
| 65 |
+
},
|
| 66 |
+
},
|
| 67 |
+
feature_provider={
|
| 68 |
+
"class": "LocalFeatureProvider",
|
| 69 |
+
"module_path": "qlib.data.data",
|
| 70 |
+
"kwargs": {
|
| 71 |
+
"backend": {
|
| 72 |
+
"class": "FileFeatureStorage",
|
| 73 |
+
"module_path": "qlib.data.storage.file_storage",
|
| 74 |
+
"kwargs": {"provider_uri_map": provider_uri_map},
|
| 75 |
+
},
|
| 76 |
+
},
|
| 77 |
+
},
|
| 78 |
+
provider_uri=provider_uri_map,
|
| 79 |
+
kernels=1,
|
| 80 |
+
redis_port=-1,
|
| 81 |
+
clear_mem_cache=False, # init_qlib will be called for multiple times. Keep the cache for improving performance
|
| 82 |
+
)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/native.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import List, cast
|
| 8 |
+
|
| 9 |
+
import cachetools
|
| 10 |
+
import pandas as pd
|
| 11 |
+
|
| 12 |
+
from qlib.backtest import Exchange, Order
|
| 13 |
+
from qlib.backtest.decision import TradeRange, TradeRangeByTime
|
| 14 |
+
from qlib.constant import EPS_T
|
| 15 |
+
from qlib.utils.pickle_utils import restricted_pickle_load
|
| 16 |
+
|
| 17 |
+
from .base import BaseIntradayBacktestData, BaseIntradayProcessedData, ProcessedDataProvider
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def get_ticks_slice(
|
| 21 |
+
ticks_index: pd.DatetimeIndex,
|
| 22 |
+
start: pd.Timestamp,
|
| 23 |
+
end: pd.Timestamp,
|
| 24 |
+
include_end: bool = False,
|
| 25 |
+
) -> pd.DatetimeIndex:
|
| 26 |
+
if not include_end:
|
| 27 |
+
end = end - EPS_T
|
| 28 |
+
return ticks_index[ticks_index.slice_indexer(start, end)]
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class IntradayBacktestData(BaseIntradayBacktestData):
|
| 32 |
+
"""Backtest data for Qlib simulator"""
|
| 33 |
+
|
| 34 |
+
def __init__(
|
| 35 |
+
self,
|
| 36 |
+
order: Order,
|
| 37 |
+
exchange: Exchange,
|
| 38 |
+
ticks_index: pd.DatetimeIndex,
|
| 39 |
+
ticks_for_order: pd.DatetimeIndex,
|
| 40 |
+
) -> None:
|
| 41 |
+
self._order = order
|
| 42 |
+
self._exchange = exchange
|
| 43 |
+
self._start_time = ticks_for_order[0]
|
| 44 |
+
self._end_time = ticks_for_order[-1]
|
| 45 |
+
self.ticks_index = ticks_index
|
| 46 |
+
self.ticks_for_order = ticks_for_order
|
| 47 |
+
|
| 48 |
+
self._deal_price = cast(
|
| 49 |
+
pd.Series,
|
| 50 |
+
self._exchange.get_deal_price(
|
| 51 |
+
self._order.stock_id,
|
| 52 |
+
self._start_time,
|
| 53 |
+
self._end_time,
|
| 54 |
+
direction=self._order.direction,
|
| 55 |
+
method=None,
|
| 56 |
+
),
|
| 57 |
+
)
|
| 58 |
+
self._volume = cast(
|
| 59 |
+
pd.Series,
|
| 60 |
+
self._exchange.get_volume(
|
| 61 |
+
self._order.stock_id,
|
| 62 |
+
self._start_time,
|
| 63 |
+
self._end_time,
|
| 64 |
+
method=None,
|
| 65 |
+
),
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
def __repr__(self) -> str:
|
| 69 |
+
return (
|
| 70 |
+
f"Order: {self._order}, Exchange: {self._exchange}, "
|
| 71 |
+
f"Start time: {self._start_time}, End time: {self._end_time}"
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
def __len__(self) -> int:
|
| 75 |
+
return len(self._deal_price)
|
| 76 |
+
|
| 77 |
+
def get_deal_price(self) -> pd.Series:
|
| 78 |
+
return self._deal_price
|
| 79 |
+
|
| 80 |
+
def get_volume(self) -> pd.Series:
|
| 81 |
+
return self._volume
|
| 82 |
+
|
| 83 |
+
def get_time_index(self) -> pd.DatetimeIndex:
|
| 84 |
+
return pd.DatetimeIndex([e[1] for e in list(self._exchange.quote_df.index)])
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
class DataframeIntradayBacktestData(BaseIntradayBacktestData):
|
| 88 |
+
"""Backtest data from dataframe"""
|
| 89 |
+
|
| 90 |
+
def __init__(self, df: pd.DataFrame, price_column: str = "$close0", volume_column: str = "$volume0") -> None:
|
| 91 |
+
self.df = df
|
| 92 |
+
self.price_column = price_column
|
| 93 |
+
self.volume_column = volume_column
|
| 94 |
+
|
| 95 |
+
def __repr__(self) -> str:
|
| 96 |
+
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
| 97 |
+
return f"{self.__class__.__name__}({self.df})"
|
| 98 |
+
|
| 99 |
+
def __len__(self) -> int:
|
| 100 |
+
return len(self.df)
|
| 101 |
+
|
| 102 |
+
def get_deal_price(self) -> pd.Series:
|
| 103 |
+
return self.df[self.price_column]
|
| 104 |
+
|
| 105 |
+
def get_volume(self) -> pd.Series:
|
| 106 |
+
return self.df[self.volume_column]
|
| 107 |
+
|
| 108 |
+
def get_time_index(self) -> pd.DatetimeIndex:
|
| 109 |
+
return cast(pd.DatetimeIndex, self.df.index)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@cachetools.cached( # type: ignore
|
| 113 |
+
cache=cachetools.LRUCache(100),
|
| 114 |
+
key=lambda order, _, __: order.key_by_day,
|
| 115 |
+
)
|
| 116 |
+
def load_backtest_data(
|
| 117 |
+
order: Order,
|
| 118 |
+
trade_exchange: Exchange,
|
| 119 |
+
trade_range: TradeRange,
|
| 120 |
+
) -> IntradayBacktestData:
|
| 121 |
+
ticks_index = pd.DatetimeIndex(trade_exchange.quote_df.reset_index()["datetime"])
|
| 122 |
+
ticks_index = ticks_index[order.start_time <= ticks_index]
|
| 123 |
+
ticks_index = ticks_index[ticks_index <= order.end_time]
|
| 124 |
+
|
| 125 |
+
if isinstance(trade_range, TradeRangeByTime):
|
| 126 |
+
ticks_for_order = get_ticks_slice(
|
| 127 |
+
ticks_index,
|
| 128 |
+
trade_range.start_time,
|
| 129 |
+
trade_range.end_time,
|
| 130 |
+
include_end=True,
|
| 131 |
+
)
|
| 132 |
+
else:
|
| 133 |
+
ticks_for_order = None # FIXME: implement this logic
|
| 134 |
+
|
| 135 |
+
backtest_data = IntradayBacktestData(
|
| 136 |
+
order=order,
|
| 137 |
+
exchange=trade_exchange,
|
| 138 |
+
ticks_index=ticks_index,
|
| 139 |
+
ticks_for_order=ticks_for_order,
|
| 140 |
+
)
|
| 141 |
+
return backtest_data
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class HandlerIntradayProcessedData(BaseIntradayProcessedData):
|
| 145 |
+
"""Subclass of IntradayProcessedData. Used to handle handler (bin format) style data."""
|
| 146 |
+
|
| 147 |
+
def __init__(
|
| 148 |
+
self,
|
| 149 |
+
data_dir: Path,
|
| 150 |
+
stock_id: str,
|
| 151 |
+
date: pd.Timestamp,
|
| 152 |
+
feature_columns_today: List[str],
|
| 153 |
+
feature_columns_yesterday: List[str],
|
| 154 |
+
backtest: bool = False,
|
| 155 |
+
index_only: bool = False,
|
| 156 |
+
) -> None:
|
| 157 |
+
def _drop_stock_id(df: pd.DataFrame) -> pd.DataFrame:
|
| 158 |
+
df = df.reset_index()
|
| 159 |
+
if "instrument" in df.columns:
|
| 160 |
+
df = df.drop(columns=["instrument"])
|
| 161 |
+
return df.set_index(["datetime"])
|
| 162 |
+
|
| 163 |
+
path = os.path.join(data_dir, "backtest" if backtest else "feature", f"{stock_id}.pkl")
|
| 164 |
+
start_time, end_time = date.replace(hour=0, minute=0, second=0), date.replace(hour=23, minute=59, second=59)
|
| 165 |
+
with open(path, "rb") as fstream:
|
| 166 |
+
dataset = restricted_pickle_load(fstream)
|
| 167 |
+
data = dataset.handler.fetch(pd.IndexSlice[stock_id, start_time:end_time], level=None)
|
| 168 |
+
|
| 169 |
+
if index_only:
|
| 170 |
+
self.today = _drop_stock_id(data[[]])
|
| 171 |
+
self.yesterday = _drop_stock_id(data[[]])
|
| 172 |
+
else:
|
| 173 |
+
self.today = _drop_stock_id(data[feature_columns_today])
|
| 174 |
+
self.yesterday = _drop_stock_id(data[feature_columns_yesterday])
|
| 175 |
+
|
| 176 |
+
def __repr__(self) -> str:
|
| 177 |
+
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
| 178 |
+
return f"{self.__class__.__name__}({self.today}, {self.yesterday})"
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
@cachetools.cached( # type: ignore
|
| 182 |
+
cache=cachetools.LRUCache(100), # 100 * 50K = 5MB
|
| 183 |
+
key=lambda data_dir, stock_id, date, feature_columns_today, feature_columns_yesterday, backtest, index_only: (
|
| 184 |
+
stock_id,
|
| 185 |
+
date,
|
| 186 |
+
backtest,
|
| 187 |
+
index_only,
|
| 188 |
+
),
|
| 189 |
+
)
|
| 190 |
+
def load_handler_intraday_processed_data(
|
| 191 |
+
data_dir: Path,
|
| 192 |
+
stock_id: str,
|
| 193 |
+
date: pd.Timestamp,
|
| 194 |
+
feature_columns_today: List[str],
|
| 195 |
+
feature_columns_yesterday: List[str],
|
| 196 |
+
backtest: bool = False,
|
| 197 |
+
index_only: bool = False,
|
| 198 |
+
) -> HandlerIntradayProcessedData:
|
| 199 |
+
return HandlerIntradayProcessedData(
|
| 200 |
+
data_dir, stock_id, date, feature_columns_today, feature_columns_yesterday, backtest, index_only
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class HandlerProcessedDataProvider(ProcessedDataProvider):
|
| 205 |
+
def __init__(
|
| 206 |
+
self,
|
| 207 |
+
data_dir: str,
|
| 208 |
+
feature_columns_today: List[str],
|
| 209 |
+
feature_columns_yesterday: List[str],
|
| 210 |
+
backtest: bool = False,
|
| 211 |
+
) -> None:
|
| 212 |
+
super().__init__()
|
| 213 |
+
|
| 214 |
+
self.data_dir = Path(data_dir)
|
| 215 |
+
self.feature_columns_today = feature_columns_today
|
| 216 |
+
self.feature_columns_yesterday = feature_columns_yesterday
|
| 217 |
+
self.backtest = backtest
|
| 218 |
+
|
| 219 |
+
def get_data(
|
| 220 |
+
self,
|
| 221 |
+
stock_id: str,
|
| 222 |
+
date: pd.Timestamp,
|
| 223 |
+
feature_dim: int,
|
| 224 |
+
time_index: pd.Index,
|
| 225 |
+
) -> BaseIntradayProcessedData:
|
| 226 |
+
return load_handler_intraday_processed_data(
|
| 227 |
+
self.data_dir,
|
| 228 |
+
stock_id,
|
| 229 |
+
date,
|
| 230 |
+
self.feature_columns_today,
|
| 231 |
+
self.feature_columns_yesterday,
|
| 232 |
+
backtest=self.backtest,
|
| 233 |
+
index_only=False,
|
| 234 |
+
)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/pickle_styled.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""This module contains utilities to read financial data from pickle-styled files.
|
| 5 |
+
|
| 6 |
+
This is the format used in `OPD paper <https://seqml.github.io/opd/>`__. NOT the standard data format in qlib.
|
| 7 |
+
|
| 8 |
+
The data here are all wrapped with ``@lru_cache``, which saves the expensive IO cost to repetitively read the data.
|
| 9 |
+
We also encourage users to use ``get_xxx_yyy`` rather than ``XxxYyy`` (although they are the same thing),
|
| 10 |
+
because ``get_xxx_yyy`` is cache-optimized.
|
| 11 |
+
|
| 12 |
+
Note that these pickle files are dumped with Python 3.8. Python lower than 3.7 might not be able to load them.
|
| 13 |
+
See `PEP 574 <https://peps.python.org/pep-0574/>`__ for details.
|
| 14 |
+
|
| 15 |
+
This file shows resemblence to qlib.backtest.high_performance_ds. We might merge those two in future.
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
# TODO: merge with qlib/backtest/high_performance_ds.py
|
| 19 |
+
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
from functools import lru_cache
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
from typing import List, Sequence, cast
|
| 25 |
+
|
| 26 |
+
import cachetools
|
| 27 |
+
import numpy as np
|
| 28 |
+
import pandas as pd
|
| 29 |
+
from cachetools.keys import hashkey
|
| 30 |
+
|
| 31 |
+
from qlib.backtest.decision import Order, OrderDir
|
| 32 |
+
from qlib.rl.data.base import BaseIntradayBacktestData, BaseIntradayProcessedData, ProcessedDataProvider
|
| 33 |
+
from qlib.typehint import Literal
|
| 34 |
+
|
| 35 |
+
DealPriceType = Literal["bid_or_ask", "bid_or_ask_fill", "close"]
|
| 36 |
+
"""Several ad-hoc deal price.
|
| 37 |
+
``bid_or_ask``: If sell, use column ``$bid0``; if buy, use column ``$ask0``.
|
| 38 |
+
``bid_or_ask_fill``: Based on ``bid_or_ask``. If price is 0, use another price (``$ask0`` / ``$bid0``) instead.
|
| 39 |
+
``close``: Use close price (``$close0``) as deal price.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _infer_processed_data_column_names(shape: int) -> List[str]:
|
| 44 |
+
if shape == 16:
|
| 45 |
+
return [
|
| 46 |
+
"$open",
|
| 47 |
+
"$high",
|
| 48 |
+
"$low",
|
| 49 |
+
"$close",
|
| 50 |
+
"$vwap",
|
| 51 |
+
"$bid",
|
| 52 |
+
"$ask",
|
| 53 |
+
"$volume",
|
| 54 |
+
"$bidV",
|
| 55 |
+
"$bidV1",
|
| 56 |
+
"$bidV3",
|
| 57 |
+
"$bidV5",
|
| 58 |
+
"$askV",
|
| 59 |
+
"$askV1",
|
| 60 |
+
"$askV3",
|
| 61 |
+
"$askV5",
|
| 62 |
+
]
|
| 63 |
+
if shape == 6:
|
| 64 |
+
return ["$high", "$low", "$open", "$close", "$vwap", "$volume"]
|
| 65 |
+
elif shape == 5:
|
| 66 |
+
return ["$high", "$low", "$open", "$close", "$volume"]
|
| 67 |
+
raise ValueError(f"Unrecognized data shape: {shape}")
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _find_pickle(filename_without_suffix: Path) -> Path:
|
| 71 |
+
suffix_list = [".pkl", ".pkl.backtest"]
|
| 72 |
+
paths: List[Path] = []
|
| 73 |
+
for suffix in suffix_list:
|
| 74 |
+
path = filename_without_suffix.parent / (filename_without_suffix.name + suffix)
|
| 75 |
+
if path.exists():
|
| 76 |
+
paths.append(path)
|
| 77 |
+
if not paths:
|
| 78 |
+
raise FileNotFoundError(f"No file starting with '{filename_without_suffix}' found")
|
| 79 |
+
if len(paths) > 1:
|
| 80 |
+
raise ValueError(f"Multiple paths are found with prefix '{filename_without_suffix}': {paths}")
|
| 81 |
+
return paths[0]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
@lru_cache(maxsize=10) # 10 * 40M = 400MB
|
| 85 |
+
def _read_pickle(filename_without_suffix: Path) -> pd.DataFrame:
|
| 86 |
+
df = pd.read_pickle(_find_pickle(filename_without_suffix))
|
| 87 |
+
index_cols = df.index.names
|
| 88 |
+
|
| 89 |
+
df = df.reset_index()
|
| 90 |
+
for date_col_name in ["date", "datetime"]:
|
| 91 |
+
if date_col_name in df:
|
| 92 |
+
df[date_col_name] = pd.to_datetime(df[date_col_name])
|
| 93 |
+
df = df.set_index(index_cols)
|
| 94 |
+
|
| 95 |
+
return df
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class SimpleIntradayBacktestData(BaseIntradayBacktestData):
|
| 99 |
+
"""Backtest data for simple simulator"""
|
| 100 |
+
|
| 101 |
+
def __init__(
|
| 102 |
+
self,
|
| 103 |
+
data_dir: Path | str,
|
| 104 |
+
stock_id: str,
|
| 105 |
+
date: pd.Timestamp,
|
| 106 |
+
deal_price: DealPriceType = "close",
|
| 107 |
+
order_dir: int | None = None,
|
| 108 |
+
) -> None:
|
| 109 |
+
super(SimpleIntradayBacktestData, self).__init__()
|
| 110 |
+
|
| 111 |
+
backtest = _read_pickle((data_dir if isinstance(data_dir, Path) else Path(data_dir)) / stock_id)
|
| 112 |
+
backtest = backtest.loc[pd.IndexSlice[stock_id, :, date]]
|
| 113 |
+
|
| 114 |
+
# No longer need for pandas >= 1.4
|
| 115 |
+
# backtest = backtest.droplevel([0, 2])
|
| 116 |
+
|
| 117 |
+
self.data: pd.DataFrame = backtest
|
| 118 |
+
self.deal_price_type: DealPriceType = deal_price
|
| 119 |
+
self.order_dir = order_dir
|
| 120 |
+
|
| 121 |
+
def __repr__(self) -> str:
|
| 122 |
+
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
| 123 |
+
return f"{self.__class__.__name__}({self.data})"
|
| 124 |
+
|
| 125 |
+
def __len__(self) -> int:
|
| 126 |
+
return len(self.data)
|
| 127 |
+
|
| 128 |
+
def get_deal_price(self) -> pd.Series:
|
| 129 |
+
"""Return a pandas series that can be indexed with time.
|
| 130 |
+
See :attribute:`DealPriceType` for details."""
|
| 131 |
+
if self.deal_price_type in ("bid_or_ask", "bid_or_ask_fill"):
|
| 132 |
+
if self.order_dir is None:
|
| 133 |
+
raise ValueError("Order direction cannot be none when deal_price_type is not close.")
|
| 134 |
+
if self.order_dir == OrderDir.SELL:
|
| 135 |
+
col = "$bid0"
|
| 136 |
+
else: # BUY
|
| 137 |
+
col = "$ask0"
|
| 138 |
+
elif self.deal_price_type == "close":
|
| 139 |
+
col = "$close0"
|
| 140 |
+
else:
|
| 141 |
+
raise ValueError(f"Unsupported deal_price_type: {self.deal_price_type}")
|
| 142 |
+
price = self.data[col]
|
| 143 |
+
|
| 144 |
+
if self.deal_price_type == "bid_or_ask_fill":
|
| 145 |
+
if self.order_dir == OrderDir.SELL:
|
| 146 |
+
fill_col = "$ask0"
|
| 147 |
+
else:
|
| 148 |
+
fill_col = "$bid0"
|
| 149 |
+
price = price.replace(0, np.nan).fillna(self.data[fill_col])
|
| 150 |
+
|
| 151 |
+
return price
|
| 152 |
+
|
| 153 |
+
def get_volume(self) -> pd.Series:
|
| 154 |
+
"""Return a volume series that can be indexed with time."""
|
| 155 |
+
return self.data["$volume0"]
|
| 156 |
+
|
| 157 |
+
def get_time_index(self) -> pd.DatetimeIndex:
|
| 158 |
+
return cast(pd.DatetimeIndex, self.data.index)
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class PickleIntradayProcessedData(BaseIntradayProcessedData):
|
| 162 |
+
"""Subclass of IntradayProcessedData. Used to handle pickle-styled data."""
|
| 163 |
+
|
| 164 |
+
def __init__(
|
| 165 |
+
self,
|
| 166 |
+
data_dir: Path | str,
|
| 167 |
+
stock_id: str,
|
| 168 |
+
date: pd.Timestamp,
|
| 169 |
+
feature_dim: int,
|
| 170 |
+
time_index: pd.Index,
|
| 171 |
+
) -> None:
|
| 172 |
+
proc = _read_pickle((data_dir if isinstance(data_dir, Path) else Path(data_dir)) / stock_id)
|
| 173 |
+
|
| 174 |
+
# We have to infer the names here because,
|
| 175 |
+
# unfortunately they are not included in the original data.
|
| 176 |
+
cnames = _infer_processed_data_column_names(feature_dim)
|
| 177 |
+
|
| 178 |
+
time_length: int = len(time_index)
|
| 179 |
+
|
| 180 |
+
try:
|
| 181 |
+
# new data format
|
| 182 |
+
proc = proc.loc[pd.IndexSlice[stock_id, :, date]]
|
| 183 |
+
assert len(proc) == time_length and len(proc.columns) == feature_dim * 2
|
| 184 |
+
proc_today = proc[cnames]
|
| 185 |
+
proc_yesterday = proc[[f"{c}_1" for c in cnames]].rename(columns=lambda c: c[:-2])
|
| 186 |
+
except (IndexError, KeyError):
|
| 187 |
+
# legacy data
|
| 188 |
+
proc = proc.loc[pd.IndexSlice[stock_id, date]]
|
| 189 |
+
assert time_length * feature_dim * 2 == len(proc)
|
| 190 |
+
proc_today = proc.to_numpy()[: time_length * feature_dim].reshape((time_length, feature_dim))
|
| 191 |
+
proc_yesterday = proc.to_numpy()[time_length * feature_dim :].reshape((time_length, feature_dim))
|
| 192 |
+
proc_today = pd.DataFrame(proc_today, index=time_index, columns=cnames)
|
| 193 |
+
proc_yesterday = pd.DataFrame(proc_yesterday, index=time_index, columns=cnames)
|
| 194 |
+
|
| 195 |
+
self.today: pd.DataFrame = proc_today
|
| 196 |
+
self.yesterday: pd.DataFrame = proc_yesterday
|
| 197 |
+
assert len(self.today.columns) == len(self.yesterday.columns) == feature_dim
|
| 198 |
+
assert len(self.today) == len(self.yesterday) == time_length
|
| 199 |
+
|
| 200 |
+
def __repr__(self) -> str:
|
| 201 |
+
with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"):
|
| 202 |
+
return f"{self.__class__.__name__}({self.today}, {self.yesterday})"
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
@lru_cache(maxsize=100) # 100 * 50K = 5MB
|
| 206 |
+
def load_simple_intraday_backtest_data(
|
| 207 |
+
data_dir: Path,
|
| 208 |
+
stock_id: str,
|
| 209 |
+
date: pd.Timestamp,
|
| 210 |
+
deal_price: DealPriceType = "close",
|
| 211 |
+
order_dir: int | None = None,
|
| 212 |
+
) -> SimpleIntradayBacktestData:
|
| 213 |
+
return SimpleIntradayBacktestData(data_dir, stock_id, date, deal_price, order_dir)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
@cachetools.cached( # type: ignore
|
| 217 |
+
cache=cachetools.LRUCache(100), # 100 * 50K = 5MB
|
| 218 |
+
key=lambda data_dir, stock_id, date, feature_dim, time_index: hashkey(data_dir, stock_id, date),
|
| 219 |
+
)
|
| 220 |
+
def load_pickle_intraday_processed_data(
|
| 221 |
+
data_dir: Path,
|
| 222 |
+
stock_id: str,
|
| 223 |
+
date: pd.Timestamp,
|
| 224 |
+
feature_dim: int,
|
| 225 |
+
time_index: pd.Index,
|
| 226 |
+
) -> BaseIntradayProcessedData:
|
| 227 |
+
return PickleIntradayProcessedData(data_dir, stock_id, date, feature_dim, time_index)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class PickleProcessedDataProvider(ProcessedDataProvider):
|
| 231 |
+
def __init__(self, data_dir: Path) -> None:
|
| 232 |
+
super().__init__()
|
| 233 |
+
|
| 234 |
+
self._data_dir = data_dir
|
| 235 |
+
|
| 236 |
+
def get_data(
|
| 237 |
+
self,
|
| 238 |
+
stock_id: str,
|
| 239 |
+
date: pd.Timestamp,
|
| 240 |
+
feature_dim: int,
|
| 241 |
+
time_index: pd.Index,
|
| 242 |
+
) -> BaseIntradayProcessedData:
|
| 243 |
+
return load_pickle_intraday_processed_data(
|
| 244 |
+
data_dir=self._data_dir,
|
| 245 |
+
stock_id=stock_id,
|
| 246 |
+
date=date,
|
| 247 |
+
feature_dim=feature_dim,
|
| 248 |
+
time_index=time_index,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def load_orders(
|
| 253 |
+
order_path: Path,
|
| 254 |
+
start_time: pd.Timestamp = None,
|
| 255 |
+
end_time: pd.Timestamp = None,
|
| 256 |
+
) -> Sequence[Order]:
|
| 257 |
+
"""Load orders, and set start time and end time for the orders."""
|
| 258 |
+
|
| 259 |
+
start_time = start_time or pd.Timestamp("0:00:00")
|
| 260 |
+
end_time = end_time or pd.Timestamp("23:59:59")
|
| 261 |
+
|
| 262 |
+
if order_path.is_file():
|
| 263 |
+
order_df = pd.read_pickle(order_path)
|
| 264 |
+
else:
|
| 265 |
+
order_df = []
|
| 266 |
+
for file in order_path.iterdir():
|
| 267 |
+
order_data = pd.read_pickle(file)
|
| 268 |
+
order_df.append(order_data)
|
| 269 |
+
order_df = pd.concat(order_df)
|
| 270 |
+
|
| 271 |
+
order_df = order_df.reset_index()
|
| 272 |
+
|
| 273 |
+
# Legacy-style orders have "date" instead of "datetime"
|
| 274 |
+
if "date" in order_df.columns:
|
| 275 |
+
order_df = order_df.rename(columns={"date": "datetime"})
|
| 276 |
+
|
| 277 |
+
# Sometimes "date" are str rather than Timestamp
|
| 278 |
+
order_df["datetime"] = pd.to_datetime(order_df["datetime"])
|
| 279 |
+
|
| 280 |
+
orders: List[Order] = []
|
| 281 |
+
|
| 282 |
+
for _, row in order_df.iterrows():
|
| 283 |
+
# filter out orders with amount == 0
|
| 284 |
+
if row["amount"] <= 0:
|
| 285 |
+
continue
|
| 286 |
+
orders.append(
|
| 287 |
+
Order(
|
| 288 |
+
row["instrument"],
|
| 289 |
+
row["amount"],
|
| 290 |
+
OrderDir(int(row["order_type"])),
|
| 291 |
+
row["datetime"].replace(hour=start_time.hour, minute=start_time.minute, second=start_time.second),
|
| 292 |
+
row["datetime"].replace(hour=end_time.hour, minute=end_time.minute, second=end_time.second),
|
| 293 |
+
),
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
return orders
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/interpreter.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import Any, Generic, TypeVar
|
| 7 |
+
|
| 8 |
+
import gym
|
| 9 |
+
import numpy as np
|
| 10 |
+
from gym import spaces
|
| 11 |
+
|
| 12 |
+
from qlib.typehint import final
|
| 13 |
+
from .simulator import ActType, StateType
|
| 14 |
+
|
| 15 |
+
ObsType = TypeVar("ObsType")
|
| 16 |
+
PolicyActType = TypeVar("PolicyActType")
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Interpreter:
|
| 20 |
+
"""Interpreter is a media between states produced by simulators and states needed by RL policies.
|
| 21 |
+
Interpreters are two-way:
|
| 22 |
+
|
| 23 |
+
1. From simulator state to policy state (aka observation), see :class:`StateInterpreter`.
|
| 24 |
+
2. From policy action to action accepted by simulator, see :class:`ActionInterpreter`.
|
| 25 |
+
|
| 26 |
+
Inherit one of the two sub-classes to define your own interpreter.
|
| 27 |
+
This super-class is only used for isinstance check.
|
| 28 |
+
|
| 29 |
+
Interpreters are recommended to be stateless, meaning that storing temporary information with ``self.xxx``
|
| 30 |
+
in interpreter is anti-pattern. In future, we might support register some interpreter-related
|
| 31 |
+
states by calling ``self.env.register_state()``, but it's not planned for first iteration.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class StateInterpreter(Generic[StateType, ObsType], Interpreter):
|
| 36 |
+
"""State Interpreter that interpret execution result of qlib executor into rl env state"""
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def observation_space(self) -> gym.Space:
|
| 40 |
+
raise NotImplementedError()
|
| 41 |
+
|
| 42 |
+
@final # no overridden
|
| 43 |
+
def __call__(self, simulator_state: StateType) -> ObsType:
|
| 44 |
+
obs = self.interpret(simulator_state)
|
| 45 |
+
self.validate(obs)
|
| 46 |
+
return obs
|
| 47 |
+
|
| 48 |
+
def validate(self, obs: ObsType) -> None:
|
| 49 |
+
"""Validate whether an observation belongs to the pre-defined observation space."""
|
| 50 |
+
_gym_space_contains(self.observation_space, obs)
|
| 51 |
+
|
| 52 |
+
def interpret(self, simulator_state: StateType) -> ObsType:
|
| 53 |
+
"""Interpret the state of simulator.
|
| 54 |
+
|
| 55 |
+
Parameters
|
| 56 |
+
----------
|
| 57 |
+
simulator_state
|
| 58 |
+
Retrieved with ``simulator.get_state()``.
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
State needed by policy. Should conform with the state space defined in ``observation_space``.
|
| 63 |
+
"""
|
| 64 |
+
raise NotImplementedError("interpret is not implemented!")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class ActionInterpreter(Generic[StateType, PolicyActType, ActType], Interpreter):
|
| 68 |
+
"""Action Interpreter that interpret rl agent action into qlib orders"""
|
| 69 |
+
|
| 70 |
+
@property
|
| 71 |
+
def action_space(self) -> gym.Space:
|
| 72 |
+
raise NotImplementedError()
|
| 73 |
+
|
| 74 |
+
@final # no overridden
|
| 75 |
+
def __call__(self, simulator_state: StateType, action: PolicyActType) -> ActType:
|
| 76 |
+
self.validate(action)
|
| 77 |
+
obs = self.interpret(simulator_state, action)
|
| 78 |
+
return obs
|
| 79 |
+
|
| 80 |
+
def validate(self, action: PolicyActType) -> None:
|
| 81 |
+
"""Validate whether an action belongs to the pre-defined action space."""
|
| 82 |
+
_gym_space_contains(self.action_space, action)
|
| 83 |
+
|
| 84 |
+
def interpret(self, simulator_state: StateType, action: PolicyActType) -> ActType:
|
| 85 |
+
"""Convert the policy action to simulator action.
|
| 86 |
+
|
| 87 |
+
Parameters
|
| 88 |
+
----------
|
| 89 |
+
simulator_state
|
| 90 |
+
Retrieved with ``simulator.get_state()``.
|
| 91 |
+
action
|
| 92 |
+
Raw action given by policy.
|
| 93 |
+
|
| 94 |
+
Returns
|
| 95 |
+
-------
|
| 96 |
+
The action needed by simulator,
|
| 97 |
+
"""
|
| 98 |
+
raise NotImplementedError("interpret is not implemented!")
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _gym_space_contains(space: gym.Space, x: Any) -> None:
|
| 102 |
+
"""Strengthened version of gym.Space.contains.
|
| 103 |
+
Giving more diagnostic information on why validation fails.
|
| 104 |
+
|
| 105 |
+
Throw exception rather than returning true or false.
|
| 106 |
+
"""
|
| 107 |
+
if isinstance(space, spaces.Dict):
|
| 108 |
+
if not isinstance(x, dict) or len(x) != len(space):
|
| 109 |
+
raise GymSpaceValidationError("Sample must be a dict with same length as space.", space, x)
|
| 110 |
+
for k, subspace in space.spaces.items():
|
| 111 |
+
if k not in x:
|
| 112 |
+
raise GymSpaceValidationError(f"Key {k} not found in sample.", space, x)
|
| 113 |
+
try:
|
| 114 |
+
_gym_space_contains(subspace, x[k])
|
| 115 |
+
except GymSpaceValidationError as e:
|
| 116 |
+
raise GymSpaceValidationError(f"Subspace of key {k} validation error.", space, x) from e
|
| 117 |
+
|
| 118 |
+
elif isinstance(space, spaces.Tuple):
|
| 119 |
+
if isinstance(x, (list, np.ndarray)):
|
| 120 |
+
x = tuple(x) # Promote list and ndarray to tuple for contains check
|
| 121 |
+
if not isinstance(x, tuple) or len(x) != len(space):
|
| 122 |
+
raise GymSpaceValidationError("Sample must be a tuple with same length as space.", space, x)
|
| 123 |
+
for i, (subspace, part) in enumerate(zip(space, x)):
|
| 124 |
+
try:
|
| 125 |
+
_gym_space_contains(subspace, part)
|
| 126 |
+
except GymSpaceValidationError as e:
|
| 127 |
+
raise GymSpaceValidationError(f"Subspace of index {i} validation error.", space, x) from e
|
| 128 |
+
|
| 129 |
+
else:
|
| 130 |
+
if not space.contains(x):
|
| 131 |
+
raise GymSpaceValidationError("Validation error reported by gym.", space, x)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
class GymSpaceValidationError(Exception):
|
| 135 |
+
def __init__(self, message: str, space: gym.Space, x: Any) -> None:
|
| 136 |
+
self.message = message
|
| 137 |
+
self.space = space
|
| 138 |
+
self.x = x
|
| 139 |
+
|
| 140 |
+
def __str__(self) -> str:
|
| 141 |
+
return f"{self.message}\n Space: {self.space}\n Sample: {self.x}"
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/__init__.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
Currently it supports single-asset order execution.
|
| 6 |
+
Multi-asset is on the way.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from .interpreter import (
|
| 10 |
+
FullHistoryStateInterpreter,
|
| 11 |
+
CurrentStepStateInterpreter,
|
| 12 |
+
CategoricalActionInterpreter,
|
| 13 |
+
TwapRelativeActionInterpreter,
|
| 14 |
+
)
|
| 15 |
+
from .network import Recurrent
|
| 16 |
+
from .policy import AllOne, PPO
|
| 17 |
+
from .reward import PAPenaltyReward
|
| 18 |
+
from .simulator_simple import SingleAssetOrderExecutionSimple
|
| 19 |
+
from .state import SAOEMetrics, SAOEState
|
| 20 |
+
from .strategy import SAOEStateAdapter, SAOEStrategy, ProxySAOEStrategy, SAOEIntStrategy
|
| 21 |
+
|
| 22 |
+
__all__ = [
|
| 23 |
+
"FullHistoryStateInterpreter",
|
| 24 |
+
"CurrentStepStateInterpreter",
|
| 25 |
+
"CategoricalActionInterpreter",
|
| 26 |
+
"TwapRelativeActionInterpreter",
|
| 27 |
+
"Recurrent",
|
| 28 |
+
"AllOne",
|
| 29 |
+
"PPO",
|
| 30 |
+
"PAPenaltyReward",
|
| 31 |
+
"SingleAssetOrderExecutionSimple",
|
| 32 |
+
"SAOEStateAdapter",
|
| 33 |
+
"SAOEMetrics",
|
| 34 |
+
"SAOEState",
|
| 35 |
+
"SAOEStrategy",
|
| 36 |
+
"ProxySAOEStrategy",
|
| 37 |
+
"SAOEIntStrategy",
|
| 38 |
+
]
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/interpreter.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import math
|
| 7 |
+
from typing import Any, List, Optional, cast
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from gym import spaces
|
| 12 |
+
|
| 13 |
+
from qlib.constant import EPS
|
| 14 |
+
from qlib.rl.data.base import ProcessedDataProvider
|
| 15 |
+
from qlib.rl.interpreter import ActionInterpreter, StateInterpreter
|
| 16 |
+
from qlib.rl.order_execution.state import SAOEState
|
| 17 |
+
from qlib.typehint import TypedDict
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
"FullHistoryStateInterpreter",
|
| 21 |
+
"CurrentStepStateInterpreter",
|
| 22 |
+
"CategoricalActionInterpreter",
|
| 23 |
+
"TwapRelativeActionInterpreter",
|
| 24 |
+
"FullHistoryObs",
|
| 25 |
+
]
|
| 26 |
+
|
| 27 |
+
from qlib.utils import init_instance_by_config
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def canonicalize(value: int | float | np.ndarray | pd.DataFrame | dict) -> np.ndarray | dict:
|
| 31 |
+
"""To 32-bit numeric types. Recursively."""
|
| 32 |
+
if isinstance(value, pd.DataFrame):
|
| 33 |
+
return value.to_numpy()
|
| 34 |
+
if isinstance(value, (float, np.floating)) or (isinstance(value, np.ndarray) and value.dtype.kind == "f"):
|
| 35 |
+
return np.array(value, dtype=np.float32)
|
| 36 |
+
elif isinstance(value, (int, bool, np.integer)) or (isinstance(value, np.ndarray) and value.dtype.kind == "i"):
|
| 37 |
+
return np.array(value, dtype=np.int32)
|
| 38 |
+
elif isinstance(value, dict):
|
| 39 |
+
return {k: canonicalize(v) for k, v in value.items()}
|
| 40 |
+
else:
|
| 41 |
+
return value
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class FullHistoryObs(TypedDict):
|
| 45 |
+
data_processed: Any
|
| 46 |
+
data_processed_prev: Any
|
| 47 |
+
acquiring: Any
|
| 48 |
+
cur_tick: Any
|
| 49 |
+
cur_step: Any
|
| 50 |
+
num_step: Any
|
| 51 |
+
target: Any
|
| 52 |
+
position: Any
|
| 53 |
+
position_history: Any
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class DummyStateInterpreter(StateInterpreter[SAOEState, dict]):
|
| 57 |
+
"""Dummy interpreter for policies that do not need inputs (for example, AllOne)."""
|
| 58 |
+
|
| 59 |
+
def interpret(self, state: SAOEState) -> dict:
|
| 60 |
+
# TODO: A fake state, used to pass `check_nan_observation`. Find a better way in the future.
|
| 61 |
+
return {"DUMMY": _to_int32(1)}
|
| 62 |
+
|
| 63 |
+
@property
|
| 64 |
+
def observation_space(self) -> spaces.Dict:
|
| 65 |
+
return spaces.Dict({"DUMMY": spaces.Box(-np.inf, np.inf, shape=(), dtype=np.int32)})
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class FullHistoryStateInterpreter(StateInterpreter[SAOEState, FullHistoryObs]):
|
| 69 |
+
"""The observation of all the history, including today (until this moment), and yesterday.
|
| 70 |
+
|
| 71 |
+
Parameters
|
| 72 |
+
----------
|
| 73 |
+
max_step
|
| 74 |
+
Total number of steps (an upper-bound estimation). For example, 390min / 30min-per-step = 13 steps.
|
| 75 |
+
data_ticks
|
| 76 |
+
Equal to the total number of records. For example, in SAOE per minute,
|
| 77 |
+
the total ticks is the length of day in minutes.
|
| 78 |
+
data_dim
|
| 79 |
+
Number of dimensions in data.
|
| 80 |
+
processed_data_provider
|
| 81 |
+
Provider of the processed data.
|
| 82 |
+
"""
|
| 83 |
+
|
| 84 |
+
def __init__(
|
| 85 |
+
self,
|
| 86 |
+
max_step: int,
|
| 87 |
+
data_ticks: int,
|
| 88 |
+
data_dim: int,
|
| 89 |
+
processed_data_provider: dict | ProcessedDataProvider,
|
| 90 |
+
) -> None:
|
| 91 |
+
super().__init__()
|
| 92 |
+
|
| 93 |
+
self.max_step = max_step
|
| 94 |
+
self.data_ticks = data_ticks
|
| 95 |
+
self.data_dim = data_dim
|
| 96 |
+
self.processed_data_provider: ProcessedDataProvider = init_instance_by_config(
|
| 97 |
+
processed_data_provider,
|
| 98 |
+
accept_types=ProcessedDataProvider,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
def interpret(self, state: SAOEState) -> FullHistoryObs:
|
| 102 |
+
processed = self.processed_data_provider.get_data(
|
| 103 |
+
stock_id=state.order.stock_id,
|
| 104 |
+
date=pd.Timestamp(state.order.start_time.date()),
|
| 105 |
+
feature_dim=self.data_dim,
|
| 106 |
+
time_index=state.ticks_index,
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
position_history = np.full(self.max_step + 1, 0.0, dtype=np.float32)
|
| 110 |
+
position_history[0] = state.order.amount
|
| 111 |
+
position_history[1 : len(state.history_steps) + 1] = state.history_steps["position"].to_numpy()
|
| 112 |
+
|
| 113 |
+
# The min, slice here are to make sure that indices fit into the range,
|
| 114 |
+
# even after the final step of the simulator (in the done step),
|
| 115 |
+
# to make network in policy happy.
|
| 116 |
+
return cast(
|
| 117 |
+
FullHistoryObs,
|
| 118 |
+
canonicalize(
|
| 119 |
+
{
|
| 120 |
+
"data_processed": np.array(self._mask_future_info(processed.today, state.cur_time)),
|
| 121 |
+
"data_processed_prev": np.array(processed.yesterday),
|
| 122 |
+
"acquiring": _to_int32(state.order.direction == state.order.BUY),
|
| 123 |
+
"cur_tick": _to_int32(min(int(np.sum(state.ticks_index < state.cur_time)), self.data_ticks - 1)),
|
| 124 |
+
"cur_step": _to_int32(min(state.cur_step, self.max_step - 1)),
|
| 125 |
+
"num_step": _to_int32(self.max_step),
|
| 126 |
+
"target": _to_float32(state.order.amount),
|
| 127 |
+
"position": _to_float32(state.position),
|
| 128 |
+
"position_history": _to_float32(position_history[: self.max_step]),
|
| 129 |
+
},
|
| 130 |
+
),
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
@property
|
| 134 |
+
def observation_space(self) -> spaces.Dict:
|
| 135 |
+
space = {
|
| 136 |
+
"data_processed": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)),
|
| 137 |
+
"data_processed_prev": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)),
|
| 138 |
+
"acquiring": spaces.Discrete(2),
|
| 139 |
+
"cur_tick": spaces.Box(0, self.data_ticks - 1, shape=(), dtype=np.int32),
|
| 140 |
+
"cur_step": spaces.Box(0, self.max_step - 1, shape=(), dtype=np.int32),
|
| 141 |
+
# TODO: support arbitrary length index
|
| 142 |
+
"num_step": spaces.Box(self.max_step, self.max_step, shape=(), dtype=np.int32),
|
| 143 |
+
"target": spaces.Box(-EPS, np.inf, shape=()),
|
| 144 |
+
"position": spaces.Box(-EPS, np.inf, shape=()),
|
| 145 |
+
"position_history": spaces.Box(-EPS, np.inf, shape=(self.max_step,)),
|
| 146 |
+
}
|
| 147 |
+
return spaces.Dict(space)
|
| 148 |
+
|
| 149 |
+
@staticmethod
|
| 150 |
+
def _mask_future_info(arr: pd.DataFrame, current: pd.Timestamp) -> pd.DataFrame:
|
| 151 |
+
arr = arr.copy(deep=True)
|
| 152 |
+
arr.loc[current:] = 0.0 # mask out data after this moment (inclusive)
|
| 153 |
+
return arr
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
class CurrentStateObs(TypedDict):
|
| 157 |
+
acquiring: bool
|
| 158 |
+
cur_step: int
|
| 159 |
+
num_step: int
|
| 160 |
+
target: float
|
| 161 |
+
position: float
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class CurrentStepStateInterpreter(StateInterpreter[SAOEState, CurrentStateObs]):
|
| 165 |
+
"""The observation of current step.
|
| 166 |
+
|
| 167 |
+
Used when policy only depends on the latest state, but not history.
|
| 168 |
+
The key list is not full. You can add more if more information is needed by your policy.
|
| 169 |
+
"""
|
| 170 |
+
|
| 171 |
+
def __init__(self, max_step: int) -> None:
|
| 172 |
+
super().__init__()
|
| 173 |
+
|
| 174 |
+
self.max_step = max_step
|
| 175 |
+
|
| 176 |
+
@property
|
| 177 |
+
def observation_space(self) -> spaces.Dict:
|
| 178 |
+
space = {
|
| 179 |
+
"acquiring": spaces.Discrete(2),
|
| 180 |
+
"cur_step": spaces.Box(0, self.max_step - 1, shape=(), dtype=np.int32),
|
| 181 |
+
"num_step": spaces.Box(self.max_step, self.max_step, shape=(), dtype=np.int32),
|
| 182 |
+
"target": spaces.Box(-EPS, np.inf, shape=()),
|
| 183 |
+
"position": spaces.Box(-EPS, np.inf, shape=()),
|
| 184 |
+
}
|
| 185 |
+
return spaces.Dict(space)
|
| 186 |
+
|
| 187 |
+
def interpret(self, state: SAOEState) -> CurrentStateObs:
|
| 188 |
+
assert state.cur_step <= self.max_step
|
| 189 |
+
obs = CurrentStateObs(
|
| 190 |
+
acquiring=state.order.direction == state.order.BUY,
|
| 191 |
+
cur_step=state.cur_step,
|
| 192 |
+
num_step=self.max_step,
|
| 193 |
+
target=state.order.amount,
|
| 194 |
+
position=state.position,
|
| 195 |
+
)
|
| 196 |
+
return obs
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class CategoricalActionInterpreter(ActionInterpreter[SAOEState, int, float]):
|
| 200 |
+
"""Convert a discrete policy action to a continuous action, then multiplied by ``order.amount``.
|
| 201 |
+
|
| 202 |
+
Parameters
|
| 203 |
+
----------
|
| 204 |
+
values
|
| 205 |
+
It can be a list of length $L$: $[a_1, a_2, \\ldots, a_L]$.
|
| 206 |
+
Then when policy givens decision $x$, $a_x$ times order amount is the output.
|
| 207 |
+
It can also be an integer $n$, in which case the list of length $n+1$ is auto-generated,
|
| 208 |
+
i.e., $[0, 1/n, 2/n, \\ldots, n/n]$.
|
| 209 |
+
max_step
|
| 210 |
+
Total number of steps (an upper-bound estimation). For example, 390min / 30min-per-step = 13 steps.
|
| 211 |
+
"""
|
| 212 |
+
|
| 213 |
+
def __init__(self, values: int | List[float], max_step: Optional[int] = None) -> None:
|
| 214 |
+
super().__init__()
|
| 215 |
+
|
| 216 |
+
if isinstance(values, int):
|
| 217 |
+
values = [i / values for i in range(0, values + 1)]
|
| 218 |
+
self.action_values = values
|
| 219 |
+
self.max_step = max_step
|
| 220 |
+
|
| 221 |
+
@property
|
| 222 |
+
def action_space(self) -> spaces.Discrete:
|
| 223 |
+
return spaces.Discrete(len(self.action_values))
|
| 224 |
+
|
| 225 |
+
def interpret(self, state: SAOEState, action: int) -> float:
|
| 226 |
+
assert 0 <= action < len(self.action_values)
|
| 227 |
+
if self.max_step is not None and state.cur_step >= self.max_step - 1:
|
| 228 |
+
return state.position
|
| 229 |
+
else:
|
| 230 |
+
return min(state.position, state.order.amount * self.action_values[action])
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
class TwapRelativeActionInterpreter(ActionInterpreter[SAOEState, float, float]):
|
| 234 |
+
"""Convert a continuous ratio to deal amount.
|
| 235 |
+
|
| 236 |
+
The ratio is relative to TWAP on the remainder of the day.
|
| 237 |
+
For example, there are 5 steps left, and the left position is 300.
|
| 238 |
+
With TWAP strategy, in each position, 60 should be traded.
|
| 239 |
+
When this interpreter receives action $a$, its output is $60 \\cdot a$.
|
| 240 |
+
"""
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def action_space(self) -> spaces.Box:
|
| 244 |
+
return spaces.Box(0, np.inf, shape=(), dtype=np.float32)
|
| 245 |
+
|
| 246 |
+
def interpret(self, state: SAOEState, action: float) -> float:
|
| 247 |
+
estimated_total_steps = math.ceil(len(state.ticks_for_order) / state.ticks_per_step)
|
| 248 |
+
twap_volume = state.position / (estimated_total_steps - state.cur_step)
|
| 249 |
+
return min(state.position, twap_volume * action)
|
| 250 |
+
|
| 251 |
+
|
| 252 |
+
def _to_int32(val):
|
| 253 |
+
return np.array(int(val), dtype=np.int32)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
def _to_float32(val):
|
| 257 |
+
return np.array(val, dtype=np.float32)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/network.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import List, Tuple, cast
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
import torch.nn as nn
|
| 10 |
+
from tianshou.data import Batch
|
| 11 |
+
|
| 12 |
+
from qlib.typehint import Literal
|
| 13 |
+
|
| 14 |
+
from .interpreter import FullHistoryObs
|
| 15 |
+
|
| 16 |
+
__all__ = ["Recurrent"]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Recurrent(nn.Module):
|
| 20 |
+
"""The network architecture proposed in `OPD <https://seqml.github.io/opd/opd_aaai21_supplement.pdf>`_.
|
| 21 |
+
|
| 22 |
+
At every time step the input of policy network is divided into two parts,
|
| 23 |
+
the public variables and the private variables. which are handled by ``raw_rnn``
|
| 24 |
+
and ``pri_rnn`` in this network, respectively.
|
| 25 |
+
|
| 26 |
+
One minor difference is that, in this implementation, we don't assume the direction to be fixed.
|
| 27 |
+
Thus, another ``dire_fc`` is added to produce an extra direction-related feature.
|
| 28 |
+
"""
|
| 29 |
+
|
| 30 |
+
def __init__(
|
| 31 |
+
self,
|
| 32 |
+
obs_space: FullHistoryObs,
|
| 33 |
+
hidden_dim: int = 64,
|
| 34 |
+
output_dim: int = 32,
|
| 35 |
+
rnn_type: Literal["rnn", "lstm", "gru"] = "gru",
|
| 36 |
+
rnn_num_layers: int = 1,
|
| 37 |
+
) -> None:
|
| 38 |
+
super().__init__()
|
| 39 |
+
|
| 40 |
+
self.hidden_dim = hidden_dim
|
| 41 |
+
self.output_dim = output_dim
|
| 42 |
+
self.num_sources = 3
|
| 43 |
+
|
| 44 |
+
rnn_classes = {"rnn": nn.RNN, "lstm": nn.LSTM, "gru": nn.GRU}
|
| 45 |
+
|
| 46 |
+
self.rnn_class = rnn_classes[rnn_type]
|
| 47 |
+
self.rnn_layers = rnn_num_layers
|
| 48 |
+
|
| 49 |
+
self.raw_rnn = self.rnn_class(hidden_dim, hidden_dim, batch_first=True, num_layers=self.rnn_layers)
|
| 50 |
+
self.prev_rnn = self.rnn_class(hidden_dim, hidden_dim, batch_first=True, num_layers=self.rnn_layers)
|
| 51 |
+
self.pri_rnn = self.rnn_class(hidden_dim, hidden_dim, batch_first=True, num_layers=self.rnn_layers)
|
| 52 |
+
|
| 53 |
+
self.raw_fc = nn.Sequential(nn.Linear(obs_space["data_processed"].shape[-1], hidden_dim), nn.ReLU())
|
| 54 |
+
self.pri_fc = nn.Sequential(nn.Linear(2, hidden_dim), nn.ReLU())
|
| 55 |
+
self.dire_fc = nn.Sequential(nn.Linear(2, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU())
|
| 56 |
+
|
| 57 |
+
self._init_extra_branches()
|
| 58 |
+
|
| 59 |
+
self.fc = nn.Sequential(
|
| 60 |
+
nn.Linear(hidden_dim * self.num_sources, hidden_dim),
|
| 61 |
+
nn.ReLU(),
|
| 62 |
+
nn.Linear(hidden_dim, output_dim),
|
| 63 |
+
nn.ReLU(),
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
def _init_extra_branches(self) -> None:
|
| 67 |
+
pass
|
| 68 |
+
|
| 69 |
+
def _source_features(self, obs: FullHistoryObs, device: torch.device) -> Tuple[List[torch.Tensor], torch.Tensor]:
|
| 70 |
+
bs, _, data_dim = obs["data_processed"].size()
|
| 71 |
+
data = torch.cat((torch.zeros(bs, 1, data_dim, device=device), obs["data_processed"]), 1)
|
| 72 |
+
cur_step = obs["cur_step"].long()
|
| 73 |
+
cur_tick = obs["cur_tick"].long()
|
| 74 |
+
bs_indices = torch.arange(bs, device=device)
|
| 75 |
+
|
| 76 |
+
position = obs["position_history"] / obs["target"].unsqueeze(-1) # [bs, num_step]
|
| 77 |
+
steps = (
|
| 78 |
+
torch.arange(position.size(-1), device=device).unsqueeze(0).repeat(bs, 1).float()
|
| 79 |
+
/ obs["num_step"].unsqueeze(-1).float()
|
| 80 |
+
) # [bs, num_step]
|
| 81 |
+
priv = torch.stack((position.float(), steps), -1)
|
| 82 |
+
|
| 83 |
+
data_in = self.raw_fc(data)
|
| 84 |
+
data_out, _ = self.raw_rnn(data_in)
|
| 85 |
+
# as it is padded with zero in front, this should be last minute
|
| 86 |
+
data_out_slice = data_out[bs_indices, cur_tick]
|
| 87 |
+
|
| 88 |
+
priv_in = self.pri_fc(priv)
|
| 89 |
+
priv_out = self.pri_rnn(priv_in)[0]
|
| 90 |
+
priv_out = priv_out[bs_indices, cur_step]
|
| 91 |
+
|
| 92 |
+
sources = [data_out_slice, priv_out]
|
| 93 |
+
|
| 94 |
+
dir_out = self.dire_fc(torch.stack((obs["acquiring"], 1 - obs["acquiring"]), -1).float())
|
| 95 |
+
sources.append(dir_out)
|
| 96 |
+
|
| 97 |
+
return sources, data_out
|
| 98 |
+
|
| 99 |
+
def forward(self, batch: Batch) -> torch.Tensor:
|
| 100 |
+
"""
|
| 101 |
+
Input should be a dict (at least) containing:
|
| 102 |
+
|
| 103 |
+
- data_processed: [N, T, C]
|
| 104 |
+
- cur_step: [N] (int)
|
| 105 |
+
- cur_time: [N] (int)
|
| 106 |
+
- position_history: [N, S] (S is number of steps)
|
| 107 |
+
- target: [N]
|
| 108 |
+
- num_step: [N] (int)
|
| 109 |
+
- acquiring: [N] (0 or 1)
|
| 110 |
+
"""
|
| 111 |
+
|
| 112 |
+
inp = cast(FullHistoryObs, batch)
|
| 113 |
+
device = inp["data_processed"].device
|
| 114 |
+
|
| 115 |
+
sources, _ = self._source_features(inp, device)
|
| 116 |
+
assert len(sources) == self.num_sources
|
| 117 |
+
|
| 118 |
+
out = torch.cat(sources, -1)
|
| 119 |
+
return self.fc(out)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class Attention(nn.Module):
|
| 123 |
+
def __init__(self, in_dim, out_dim):
|
| 124 |
+
super().__init__()
|
| 125 |
+
self.q_net = nn.Linear(in_dim, out_dim)
|
| 126 |
+
self.k_net = nn.Linear(in_dim, out_dim)
|
| 127 |
+
self.v_net = nn.Linear(in_dim, out_dim)
|
| 128 |
+
|
| 129 |
+
def forward(self, Q, K, V):
|
| 130 |
+
q = self.q_net(Q)
|
| 131 |
+
k = self.k_net(K)
|
| 132 |
+
v = self.v_net(V)
|
| 133 |
+
|
| 134 |
+
attn = torch.einsum("ijk,ilk->ijl", q, k)
|
| 135 |
+
attn = attn.to(Q.device)
|
| 136 |
+
attn_prob = torch.softmax(attn, dim=-1)
|
| 137 |
+
|
| 138 |
+
attn_vec = torch.einsum("ijk,ikl->ijl", attn_prob, v)
|
| 139 |
+
|
| 140 |
+
return attn_vec
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/policy.py
ADDED
|
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
from typing import Any, Dict, Generator, Iterable, Optional, OrderedDict, Tuple, cast
|
| 8 |
+
|
| 9 |
+
import gym
|
| 10 |
+
import numpy as np
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
from gym.spaces import Discrete
|
| 14 |
+
from tianshou.data import Batch, ReplayBuffer, to_torch
|
| 15 |
+
from tianshou.policy import BasePolicy, PPOPolicy, DQNPolicy
|
| 16 |
+
|
| 17 |
+
from qlib.rl.trainer.trainer import Trainer
|
| 18 |
+
|
| 19 |
+
__all__ = ["AllOne", "PPO", "DQN"]
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
# baselines #
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class NonLearnablePolicy(BasePolicy):
|
| 26 |
+
"""Tianshou's BasePolicy with empty ``learn`` and ``process_fn``.
|
| 27 |
+
|
| 28 |
+
This could be moved outside in future.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
def __init__(self, obs_space: gym.Space, action_space: gym.Space) -> None:
|
| 32 |
+
super().__init__()
|
| 33 |
+
|
| 34 |
+
def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, Any]:
|
| 35 |
+
return {}
|
| 36 |
+
|
| 37 |
+
def process_fn(
|
| 38 |
+
self,
|
| 39 |
+
batch: Batch,
|
| 40 |
+
buffer: ReplayBuffer,
|
| 41 |
+
indices: np.ndarray,
|
| 42 |
+
) -> Batch:
|
| 43 |
+
return Batch({})
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class AllOne(NonLearnablePolicy):
|
| 47 |
+
"""Forward returns a batch full of 1.
|
| 48 |
+
|
| 49 |
+
Useful when implementing some baselines (e.g., TWAP).
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
def __init__(self, obs_space: gym.Space, action_space: gym.Space, fill_value: float | int = 1.0) -> None:
|
| 53 |
+
super().__init__(obs_space, action_space)
|
| 54 |
+
|
| 55 |
+
self.fill_value = fill_value
|
| 56 |
+
|
| 57 |
+
def forward(
|
| 58 |
+
self,
|
| 59 |
+
batch: Batch,
|
| 60 |
+
state: dict | Batch | np.ndarray = None,
|
| 61 |
+
**kwargs: Any,
|
| 62 |
+
) -> Batch:
|
| 63 |
+
return Batch(act=np.full(len(batch), self.fill_value), state=state)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ppo #
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class PPOActor(nn.Module):
|
| 70 |
+
def __init__(self, extractor: nn.Module, action_dim: int) -> None:
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.extractor = extractor
|
| 73 |
+
self.layer_out = nn.Sequential(nn.Linear(cast(int, extractor.output_dim), action_dim), nn.Softmax(dim=-1))
|
| 74 |
+
|
| 75 |
+
def forward(
|
| 76 |
+
self,
|
| 77 |
+
obs: torch.Tensor,
|
| 78 |
+
state: torch.Tensor = None,
|
| 79 |
+
info: dict = {},
|
| 80 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 81 |
+
feature = self.extractor(to_torch(obs, device=auto_device(self)))
|
| 82 |
+
out = self.layer_out(feature)
|
| 83 |
+
return out, state
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class PPOCritic(nn.Module):
|
| 87 |
+
def __init__(self, extractor: nn.Module) -> None:
|
| 88 |
+
super().__init__()
|
| 89 |
+
self.extractor = extractor
|
| 90 |
+
self.value_out = nn.Linear(cast(int, extractor.output_dim), 1)
|
| 91 |
+
|
| 92 |
+
def forward(
|
| 93 |
+
self,
|
| 94 |
+
obs: torch.Tensor,
|
| 95 |
+
state: torch.Tensor = None,
|
| 96 |
+
info: dict = {},
|
| 97 |
+
) -> torch.Tensor:
|
| 98 |
+
feature = self.extractor(to_torch(obs, device=auto_device(self)))
|
| 99 |
+
return self.value_out(feature).squeeze(dim=-1)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class PPO(PPOPolicy):
|
| 103 |
+
"""A wrapper of tianshou PPOPolicy.
|
| 104 |
+
|
| 105 |
+
Differences:
|
| 106 |
+
|
| 107 |
+
- Auto-create actor and critic network. Supports discrete action space only.
|
| 108 |
+
- Dedup common parameters between actor network and critic network
|
| 109 |
+
(not sure whether this is included in latest tianshou or not).
|
| 110 |
+
- Support a ``weight_file`` that supports loading checkpoint.
|
| 111 |
+
- Some parameters' default values are different from original.
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
def __init__(
|
| 115 |
+
self,
|
| 116 |
+
network: nn.Module,
|
| 117 |
+
obs_space: gym.Space,
|
| 118 |
+
action_space: gym.Space,
|
| 119 |
+
lr: float,
|
| 120 |
+
weight_decay: float = 0.0,
|
| 121 |
+
discount_factor: float = 1.0,
|
| 122 |
+
max_grad_norm: float = 100.0,
|
| 123 |
+
reward_normalization: bool = True,
|
| 124 |
+
eps_clip: float = 0.3,
|
| 125 |
+
value_clip: bool = True,
|
| 126 |
+
vf_coef: float = 1.0,
|
| 127 |
+
gae_lambda: float = 1.0,
|
| 128 |
+
max_batch_size: int = 256,
|
| 129 |
+
deterministic_eval: bool = True,
|
| 130 |
+
weight_file: Optional[Path] = None,
|
| 131 |
+
) -> None:
|
| 132 |
+
assert isinstance(action_space, Discrete)
|
| 133 |
+
actor = PPOActor(network, action_space.n)
|
| 134 |
+
critic = PPOCritic(network)
|
| 135 |
+
optimizer = torch.optim.Adam(
|
| 136 |
+
chain_dedup(actor.parameters(), critic.parameters()),
|
| 137 |
+
lr=lr,
|
| 138 |
+
weight_decay=weight_decay,
|
| 139 |
+
)
|
| 140 |
+
super().__init__(
|
| 141 |
+
actor,
|
| 142 |
+
critic,
|
| 143 |
+
optimizer,
|
| 144 |
+
torch.distributions.Categorical,
|
| 145 |
+
discount_factor=discount_factor,
|
| 146 |
+
max_grad_norm=max_grad_norm,
|
| 147 |
+
reward_normalization=reward_normalization,
|
| 148 |
+
eps_clip=eps_clip,
|
| 149 |
+
value_clip=value_clip,
|
| 150 |
+
vf_coef=vf_coef,
|
| 151 |
+
gae_lambda=gae_lambda,
|
| 152 |
+
max_batchsize=max_batch_size,
|
| 153 |
+
deterministic_eval=deterministic_eval,
|
| 154 |
+
observation_space=obs_space,
|
| 155 |
+
action_space=action_space,
|
| 156 |
+
)
|
| 157 |
+
if weight_file is not None:
|
| 158 |
+
set_weight(self, Trainer.get_policy_state_dict(weight_file))
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
DQNModel = PPOActor # Reuse PPOActor.
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class DQN(DQNPolicy):
|
| 165 |
+
"""A wrapper of tianshou DQNPolicy.
|
| 166 |
+
|
| 167 |
+
Differences:
|
| 168 |
+
|
| 169 |
+
- Auto-create model network. Supports discrete action space only.
|
| 170 |
+
- Support a ``weight_file`` that supports loading checkpoint.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
def __init__(
|
| 174 |
+
self,
|
| 175 |
+
network: nn.Module,
|
| 176 |
+
obs_space: gym.Space,
|
| 177 |
+
action_space: gym.Space,
|
| 178 |
+
lr: float,
|
| 179 |
+
weight_decay: float = 0.0,
|
| 180 |
+
discount_factor: float = 0.99,
|
| 181 |
+
estimation_step: int = 1,
|
| 182 |
+
target_update_freq: int = 0,
|
| 183 |
+
reward_normalization: bool = False,
|
| 184 |
+
is_double: bool = True,
|
| 185 |
+
clip_loss_grad: bool = False,
|
| 186 |
+
weight_file: Optional[Path] = None,
|
| 187 |
+
) -> None:
|
| 188 |
+
assert isinstance(action_space, Discrete)
|
| 189 |
+
|
| 190 |
+
model = DQNModel(network, action_space.n)
|
| 191 |
+
optimizer = torch.optim.Adam(
|
| 192 |
+
model.parameters(),
|
| 193 |
+
lr=lr,
|
| 194 |
+
weight_decay=weight_decay,
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
super().__init__(
|
| 198 |
+
model,
|
| 199 |
+
optimizer,
|
| 200 |
+
discount_factor=discount_factor,
|
| 201 |
+
estimation_step=estimation_step,
|
| 202 |
+
target_update_freq=target_update_freq,
|
| 203 |
+
reward_normalization=reward_normalization,
|
| 204 |
+
is_double=is_double,
|
| 205 |
+
clip_loss_grad=clip_loss_grad,
|
| 206 |
+
)
|
| 207 |
+
if weight_file is not None:
|
| 208 |
+
set_weight(self, Trainer.get_policy_state_dict(weight_file))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# utilities: these should be put in a separate (common) file. #
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def auto_device(module: nn.Module) -> torch.device:
|
| 215 |
+
for param in module.parameters():
|
| 216 |
+
return param.device
|
| 217 |
+
return torch.device("cpu") # fallback to cpu
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def set_weight(policy: nn.Module, loaded_weight: OrderedDict) -> None:
|
| 221 |
+
try:
|
| 222 |
+
policy.load_state_dict(loaded_weight)
|
| 223 |
+
except RuntimeError:
|
| 224 |
+
# try again by loading the converted weight
|
| 225 |
+
# https://github.com/thu-ml/tianshou/issues/468
|
| 226 |
+
for k in list(loaded_weight):
|
| 227 |
+
loaded_weight["_actor_critic." + k] = loaded_weight[k]
|
| 228 |
+
policy.load_state_dict(loaded_weight)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def chain_dedup(*iterables: Iterable) -> Generator[Any, None, None]:
|
| 232 |
+
seen = set()
|
| 233 |
+
for iterable in iterables:
|
| 234 |
+
for i in iterable:
|
| 235 |
+
if i not in seen:
|
| 236 |
+
seen.add(i)
|
| 237 |
+
yield i
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/reward.py
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import cast
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
from qlib.backtest.decision import OrderDir
|
| 11 |
+
from qlib.rl.order_execution.state import SAOEMetrics, SAOEState
|
| 12 |
+
from qlib.rl.reward import Reward
|
| 13 |
+
|
| 14 |
+
__all__ = ["PAPenaltyReward"]
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class PAPenaltyReward(Reward[SAOEState]):
|
| 18 |
+
"""Encourage higher PAs, but penalize stacking all the amounts within a very short time.
|
| 19 |
+
Formally, for each time step, the reward is :math:`(PA_t * vol_t / target - vol_t^2 * penalty)`.
|
| 20 |
+
|
| 21 |
+
Parameters
|
| 22 |
+
----------
|
| 23 |
+
penalty
|
| 24 |
+
The penalty for large volume in a short time.
|
| 25 |
+
scale
|
| 26 |
+
The weight used to scale up or down the reward.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
def __init__(self, penalty: float = 100.0, scale: float = 1.0) -> None:
|
| 30 |
+
self.penalty = penalty
|
| 31 |
+
self.scale = scale
|
| 32 |
+
|
| 33 |
+
def reward(self, simulator_state: SAOEState) -> float:
|
| 34 |
+
whole_order = simulator_state.order.amount
|
| 35 |
+
assert whole_order > 0
|
| 36 |
+
last_step = cast(SAOEMetrics, simulator_state.history_steps.reset_index().iloc[-1].to_dict())
|
| 37 |
+
pa = last_step["pa"] * last_step["amount"] / whole_order
|
| 38 |
+
|
| 39 |
+
# Inspect the "break-down" of the latest step: trading amount at every tick
|
| 40 |
+
last_step_breakdown = simulator_state.history_exec.loc[last_step["datetime"] :]
|
| 41 |
+
penalty = -self.penalty * ((last_step_breakdown["amount"] / whole_order) ** 2).sum()
|
| 42 |
+
|
| 43 |
+
reward = pa + penalty
|
| 44 |
+
|
| 45 |
+
# Throw error in case of NaN
|
| 46 |
+
assert not (np.isnan(reward) or np.isinf(reward)), f"Invalid reward for simulator state: {simulator_state}"
|
| 47 |
+
|
| 48 |
+
self.log("reward/pa", pa)
|
| 49 |
+
self.log("reward/penalty", penalty)
|
| 50 |
+
return reward * self.scale
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class PPOReward(Reward[SAOEState]):
|
| 54 |
+
"""Reward proposed by paper "An End-to-End Optimal Trade Execution Framework based on Proximal Policy Optimization".
|
| 55 |
+
|
| 56 |
+
Parameters
|
| 57 |
+
----------
|
| 58 |
+
max_step
|
| 59 |
+
Maximum number of steps.
|
| 60 |
+
start_time_index
|
| 61 |
+
First time index that allowed to trade.
|
| 62 |
+
end_time_index
|
| 63 |
+
Last time index that allowed to trade.
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
def __init__(self, max_step: int, start_time_index: int = 0, end_time_index: int = 239) -> None:
|
| 67 |
+
self.max_step = max_step
|
| 68 |
+
self.start_time_index = start_time_index
|
| 69 |
+
self.end_time_index = end_time_index
|
| 70 |
+
|
| 71 |
+
def reward(self, simulator_state: SAOEState) -> float:
|
| 72 |
+
if simulator_state.cur_step == self.max_step - 1 or simulator_state.position < 1e-6:
|
| 73 |
+
if simulator_state.history_exec["deal_amount"].sum() == 0.0:
|
| 74 |
+
vwap_price = cast(
|
| 75 |
+
float,
|
| 76 |
+
np.average(simulator_state.history_exec["market_price"]),
|
| 77 |
+
)
|
| 78 |
+
else:
|
| 79 |
+
vwap_price = cast(
|
| 80 |
+
float,
|
| 81 |
+
np.average(
|
| 82 |
+
simulator_state.history_exec["market_price"],
|
| 83 |
+
weights=simulator_state.history_exec["deal_amount"],
|
| 84 |
+
),
|
| 85 |
+
)
|
| 86 |
+
twap_price = simulator_state.backtest_data.get_deal_price().mean()
|
| 87 |
+
|
| 88 |
+
if simulator_state.order.direction == OrderDir.SELL:
|
| 89 |
+
ratio = vwap_price / twap_price if twap_price != 0 else 1.0
|
| 90 |
+
else:
|
| 91 |
+
ratio = twap_price / vwap_price if vwap_price != 0 else 1.0
|
| 92 |
+
if ratio < 1.0:
|
| 93 |
+
return -1.0
|
| 94 |
+
elif ratio < 1.1:
|
| 95 |
+
return 0.0
|
| 96 |
+
else:
|
| 97 |
+
return 1.0
|
| 98 |
+
else:
|
| 99 |
+
return 0.0
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/simulator_qlib.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import Generator, List, Optional
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from qlib.backtest import collect_data_loop, get_strategy_executor
|
| 11 |
+
from qlib.backtest.decision import BaseTradeDecision, Order, TradeRangeByTime
|
| 12 |
+
from qlib.backtest.executor import NestedExecutor
|
| 13 |
+
from qlib.rl.data.integration import init_qlib
|
| 14 |
+
from qlib.rl.simulator import Simulator
|
| 15 |
+
from .state import SAOEState
|
| 16 |
+
from .strategy import SAOEStateAdapter, SAOEStrategy
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]):
|
| 20 |
+
"""Single-asset order execution (SAOE) simulator which is implemented based on Qlib backtest tools.
|
| 21 |
+
|
| 22 |
+
Parameters
|
| 23 |
+
----------
|
| 24 |
+
order
|
| 25 |
+
The seed to start an SAOE simulator is an order.
|
| 26 |
+
executor_config
|
| 27 |
+
Executor configuration
|
| 28 |
+
exchange_config
|
| 29 |
+
Exchange configuration
|
| 30 |
+
qlib_config
|
| 31 |
+
Configuration used to initialize Qlib. If it is None, Qlib will not be initialized.
|
| 32 |
+
cash_limit:
|
| 33 |
+
Cash limit.
|
| 34 |
+
"""
|
| 35 |
+
|
| 36 |
+
def __init__(
|
| 37 |
+
self,
|
| 38 |
+
order: Order,
|
| 39 |
+
executor_config: dict,
|
| 40 |
+
exchange_config: dict,
|
| 41 |
+
qlib_config: dict | None = None,
|
| 42 |
+
cash_limit: float | None = None,
|
| 43 |
+
) -> None:
|
| 44 |
+
super().__init__(initial=order)
|
| 45 |
+
|
| 46 |
+
assert order.start_time.date() == order.end_time.date(), "Start date and end date must be the same."
|
| 47 |
+
|
| 48 |
+
strategy_config = {
|
| 49 |
+
"class": "SingleOrderStrategy",
|
| 50 |
+
"module_path": "qlib.rl.strategy.single_order",
|
| 51 |
+
"kwargs": {
|
| 52 |
+
"order": order,
|
| 53 |
+
"trade_range": TradeRangeByTime(order.start_time.time(), order.end_time.time()),
|
| 54 |
+
},
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
self._collect_data_loop: Optional[Generator] = None
|
| 58 |
+
self.reset(order, strategy_config, executor_config, exchange_config, qlib_config, cash_limit)
|
| 59 |
+
|
| 60 |
+
def reset(
|
| 61 |
+
self,
|
| 62 |
+
order: Order,
|
| 63 |
+
strategy_config: dict,
|
| 64 |
+
executor_config: dict,
|
| 65 |
+
exchange_config: dict,
|
| 66 |
+
qlib_config: dict | None = None,
|
| 67 |
+
cash_limit: Optional[float] = None,
|
| 68 |
+
) -> None:
|
| 69 |
+
if qlib_config is not None:
|
| 70 |
+
init_qlib(qlib_config)
|
| 71 |
+
|
| 72 |
+
strategy, self._executor = get_strategy_executor(
|
| 73 |
+
start_time=order.date,
|
| 74 |
+
end_time=order.date + pd.DateOffset(1),
|
| 75 |
+
strategy=strategy_config,
|
| 76 |
+
executor=executor_config,
|
| 77 |
+
benchmark=order.stock_id,
|
| 78 |
+
account=cash_limit if cash_limit is not None else int(1e12),
|
| 79 |
+
exchange_kwargs=exchange_config,
|
| 80 |
+
pos_type="Position" if cash_limit is not None else "InfPosition",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
assert isinstance(self._executor, NestedExecutor)
|
| 84 |
+
|
| 85 |
+
self.report_dict: dict = {}
|
| 86 |
+
self.decisions: List[BaseTradeDecision] = []
|
| 87 |
+
self._collect_data_loop = collect_data_loop(
|
| 88 |
+
start_time=order.date,
|
| 89 |
+
end_time=order.date,
|
| 90 |
+
trade_strategy=strategy,
|
| 91 |
+
trade_executor=self._executor,
|
| 92 |
+
return_value=self.report_dict,
|
| 93 |
+
)
|
| 94 |
+
assert isinstance(self._collect_data_loop, Generator)
|
| 95 |
+
|
| 96 |
+
self.step(action=None)
|
| 97 |
+
|
| 98 |
+
self._order = order
|
| 99 |
+
|
| 100 |
+
def _get_adapter(self) -> SAOEStateAdapter:
|
| 101 |
+
return self._last_yielded_saoe_strategy.adapter_dict[self._order.key_by_day]
|
| 102 |
+
|
| 103 |
+
@property
|
| 104 |
+
def twap_price(self) -> float:
|
| 105 |
+
return self._get_adapter().twap_price
|
| 106 |
+
|
| 107 |
+
def _iter_strategy(self, action: Optional[float] = None) -> SAOEStrategy:
|
| 108 |
+
"""Iterate the _collect_data_loop until we get the next yield SAOEStrategy."""
|
| 109 |
+
assert self._collect_data_loop is not None
|
| 110 |
+
|
| 111 |
+
obj = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action)
|
| 112 |
+
while not isinstance(obj, SAOEStrategy):
|
| 113 |
+
if isinstance(obj, BaseTradeDecision):
|
| 114 |
+
self.decisions.append(obj)
|
| 115 |
+
obj = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action)
|
| 116 |
+
assert isinstance(obj, SAOEStrategy)
|
| 117 |
+
return obj
|
| 118 |
+
|
| 119 |
+
def step(self, action: Optional[float]) -> None:
|
| 120 |
+
"""Execute one step or SAOE.
|
| 121 |
+
|
| 122 |
+
Parameters
|
| 123 |
+
----------
|
| 124 |
+
action (float):
|
| 125 |
+
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
assert not self.done(), "Simulator has already done!"
|
| 129 |
+
|
| 130 |
+
try:
|
| 131 |
+
self._last_yielded_saoe_strategy = self._iter_strategy(action=action)
|
| 132 |
+
except StopIteration:
|
| 133 |
+
pass
|
| 134 |
+
|
| 135 |
+
assert self._executor is not None
|
| 136 |
+
|
| 137 |
+
def get_state(self) -> SAOEState:
|
| 138 |
+
return self._get_adapter().saoe_state
|
| 139 |
+
|
| 140 |
+
def done(self) -> bool:
|
| 141 |
+
return self._executor.finished()
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/simulator_simple.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
from typing import Any, cast, List, Optional
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from qlib.backtest.decision import Order, OrderDir
|
| 13 |
+
from qlib.constant import EPS, EPS_T, float_or_ndarray
|
| 14 |
+
from qlib.rl.data.base import BaseIntradayBacktestData
|
| 15 |
+
from qlib.rl.data.native import DataframeIntradayBacktestData, load_handler_intraday_processed_data
|
| 16 |
+
from qlib.rl.data.pickle_styled import load_simple_intraday_backtest_data
|
| 17 |
+
from qlib.rl.simulator import Simulator
|
| 18 |
+
from qlib.rl.utils import LogLevel
|
| 19 |
+
from .state import SAOEMetrics, SAOEState
|
| 20 |
+
|
| 21 |
+
__all__ = ["SingleAssetOrderExecutionSimple"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class SingleAssetOrderExecutionSimple(Simulator[Order, SAOEState, float]):
|
| 25 |
+
"""Single-asset order execution (SAOE) simulator.
|
| 26 |
+
|
| 27 |
+
As there's no "calendar" in the simple simulator, ticks are used to trade.
|
| 28 |
+
A tick is a record (a line) in the pickle-styled data file.
|
| 29 |
+
Each tick is considered as a individual trading opportunity.
|
| 30 |
+
If such fine granularity is not needed, use ``ticks_per_step`` to
|
| 31 |
+
lengthen the ticks for each step.
|
| 32 |
+
|
| 33 |
+
In each step, the traded amount are "equally" separated to each tick,
|
| 34 |
+
then bounded by volume maximum execution volume (i.e., ``vol_threshold``),
|
| 35 |
+
and if it's the last step, try to ensure all the amount to be executed.
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
----------
|
| 39 |
+
order
|
| 40 |
+
The seed to start an SAOE simulator is an order.
|
| 41 |
+
data_dir
|
| 42 |
+
Path to load backtest data.
|
| 43 |
+
feature_columns_today
|
| 44 |
+
Columns of today's feature.
|
| 45 |
+
feature_columns_yesterday
|
| 46 |
+
Columns of yesterday's feature.
|
| 47 |
+
data_granularity
|
| 48 |
+
Number of ticks between consecutive data entries.
|
| 49 |
+
ticks_per_step
|
| 50 |
+
How many ticks per step.
|
| 51 |
+
vol_threshold
|
| 52 |
+
Maximum execution volume (divided by market execution volume).
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
history_exec: pd.DataFrame
|
| 56 |
+
"""All execution history at every possible time ticks. See :class:`SAOEMetrics` for available columns.
|
| 57 |
+
Index is ``datetime``.
|
| 58 |
+
"""
|
| 59 |
+
|
| 60 |
+
history_steps: pd.DataFrame
|
| 61 |
+
"""Positions at each step. The position before first step is also recorded.
|
| 62 |
+
See :class:`SAOEMetrics` for available columns.
|
| 63 |
+
Index is ``datetime``, which is the **starting** time of each step."""
|
| 64 |
+
|
| 65 |
+
metrics: Optional[SAOEMetrics]
|
| 66 |
+
"""Metrics. Only available when done."""
|
| 67 |
+
|
| 68 |
+
twap_price: float
|
| 69 |
+
"""This price is used to compute price advantage.
|
| 70 |
+
It"s defined as the average price in the period from order"s start time to end time."""
|
| 71 |
+
|
| 72 |
+
ticks_index: pd.DatetimeIndex
|
| 73 |
+
"""All available ticks for the day (not restricted to order)."""
|
| 74 |
+
|
| 75 |
+
ticks_for_order: pd.DatetimeIndex
|
| 76 |
+
"""Ticks that is available for trading (sliced by order)."""
|
| 77 |
+
|
| 78 |
+
def __init__(
|
| 79 |
+
self,
|
| 80 |
+
order: Order,
|
| 81 |
+
data_dir: Path,
|
| 82 |
+
feature_columns_today: List[str] = [],
|
| 83 |
+
feature_columns_yesterday: List[str] = [],
|
| 84 |
+
data_granularity: int = 1,
|
| 85 |
+
ticks_per_step: int = 30,
|
| 86 |
+
vol_threshold: Optional[float] = None,
|
| 87 |
+
) -> None:
|
| 88 |
+
super().__init__(initial=order)
|
| 89 |
+
|
| 90 |
+
assert ticks_per_step % data_granularity == 0
|
| 91 |
+
|
| 92 |
+
self.order = order
|
| 93 |
+
self.data_dir = data_dir
|
| 94 |
+
self.feature_columns_today = feature_columns_today
|
| 95 |
+
self.feature_columns_yesterday = feature_columns_yesterday
|
| 96 |
+
self.ticks_per_step: int = ticks_per_step // data_granularity
|
| 97 |
+
self.vol_threshold = vol_threshold
|
| 98 |
+
|
| 99 |
+
self.backtest_data = self.get_backtest_data()
|
| 100 |
+
self.ticks_index = self.backtest_data.get_time_index()
|
| 101 |
+
|
| 102 |
+
# Get time index available for trading
|
| 103 |
+
self.ticks_for_order = self._get_ticks_slice(self.order.start_time, self.order.end_time)
|
| 104 |
+
|
| 105 |
+
self.cur_time = self.ticks_for_order[0]
|
| 106 |
+
self.cur_step = 0
|
| 107 |
+
# NOTE: astype(float) is necessary in some systems.
|
| 108 |
+
# this will align the precision with `.to_numpy()` in `_split_exec_vol`
|
| 109 |
+
self.twap_price = float(self.backtest_data.get_deal_price().loc[self.ticks_for_order].astype(float).mean())
|
| 110 |
+
|
| 111 |
+
self.position = order.amount
|
| 112 |
+
|
| 113 |
+
metric_keys = list(SAOEMetrics.__annotations__.keys()) # pylint: disable=no-member
|
| 114 |
+
# NOTE: can empty dataframe contain index?
|
| 115 |
+
self.history_exec = pd.DataFrame(columns=metric_keys).set_index("datetime")
|
| 116 |
+
self.history_steps = pd.DataFrame(columns=metric_keys).set_index("datetime")
|
| 117 |
+
self.metrics = None
|
| 118 |
+
|
| 119 |
+
self.market_price: Optional[np.ndarray] = None
|
| 120 |
+
self.market_vol: Optional[np.ndarray] = None
|
| 121 |
+
self.market_vol_limit: Optional[np.ndarray] = None
|
| 122 |
+
|
| 123 |
+
def get_backtest_data(self) -> BaseIntradayBacktestData:
|
| 124 |
+
try:
|
| 125 |
+
data = load_handler_intraday_processed_data(
|
| 126 |
+
data_dir=self.data_dir,
|
| 127 |
+
stock_id=self.order.stock_id,
|
| 128 |
+
date=pd.Timestamp(self.order.start_time.date()),
|
| 129 |
+
feature_columns_today=self.feature_columns_today,
|
| 130 |
+
feature_columns_yesterday=self.feature_columns_yesterday,
|
| 131 |
+
backtest=True,
|
| 132 |
+
index_only=False,
|
| 133 |
+
)
|
| 134 |
+
return DataframeIntradayBacktestData(data.today)
|
| 135 |
+
except (AttributeError, FileNotFoundError):
|
| 136 |
+
# TODO: For compatibility with older versions of test scripts (tests/rl/test_saoe_simple.py)
|
| 137 |
+
# TODO: In the future, we should modify the data format used by the test script,
|
| 138 |
+
# TODO: and then delete this branch.
|
| 139 |
+
return load_simple_intraday_backtest_data(
|
| 140 |
+
self.data_dir / "backtest",
|
| 141 |
+
self.order.stock_id,
|
| 142 |
+
pd.Timestamp(self.order.start_time.date()),
|
| 143 |
+
"close",
|
| 144 |
+
self.order.direction,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
def step(self, amount: float) -> None:
|
| 148 |
+
"""Execute one step or SAOE.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
amount
|
| 153 |
+
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
assert not self.done()
|
| 157 |
+
|
| 158 |
+
self.market_price = self.market_vol = None # avoid misuse
|
| 159 |
+
exec_vol = self._split_exec_vol(amount)
|
| 160 |
+
assert self.market_price is not None
|
| 161 |
+
assert self.market_vol is not None
|
| 162 |
+
|
| 163 |
+
ticks_position = self.position - np.cumsum(exec_vol)
|
| 164 |
+
|
| 165 |
+
self.position -= exec_vol.sum()
|
| 166 |
+
if abs(self.position) < 1e-6:
|
| 167 |
+
self.position = 0.0
|
| 168 |
+
if self.position < -EPS or (exec_vol < -EPS).any():
|
| 169 |
+
raise ValueError(f"Execution volume is invalid: {exec_vol} (position = {self.position})")
|
| 170 |
+
|
| 171 |
+
# Get time index available for this step
|
| 172 |
+
time_index = self._get_ticks_slice(self.cur_time, self._next_time())
|
| 173 |
+
|
| 174 |
+
self.history_exec = self._dataframe_append(
|
| 175 |
+
self.history_exec,
|
| 176 |
+
SAOEMetrics(
|
| 177 |
+
# It should have the same keys with SAOEMetrics,
|
| 178 |
+
# but the values do not necessarily have the annotated type.
|
| 179 |
+
# Some values could be vectorized (e.g., exec_vol).
|
| 180 |
+
stock_id=self.order.stock_id,
|
| 181 |
+
datetime=time_index,
|
| 182 |
+
direction=self.order.direction,
|
| 183 |
+
market_volume=self.market_vol,
|
| 184 |
+
market_price=self.market_price,
|
| 185 |
+
amount=exec_vol,
|
| 186 |
+
inner_amount=exec_vol,
|
| 187 |
+
deal_amount=exec_vol,
|
| 188 |
+
trade_price=self.market_price,
|
| 189 |
+
trade_value=self.market_price * exec_vol,
|
| 190 |
+
position=ticks_position,
|
| 191 |
+
ffr=exec_vol / self.order.amount,
|
| 192 |
+
pa=price_advantage(self.market_price, self.twap_price, self.order.direction),
|
| 193 |
+
),
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
self.history_steps = self._dataframe_append(
|
| 197 |
+
self.history_steps,
|
| 198 |
+
[self._metrics_collect(self.cur_time, self.market_vol, self.market_price, amount, exec_vol)],
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
if self.done():
|
| 202 |
+
if self.env is not None:
|
| 203 |
+
self.env.logger.add_any("history_steps", self.history_steps, loglevel=LogLevel.DEBUG)
|
| 204 |
+
self.env.logger.add_any("history_exec", self.history_exec, loglevel=LogLevel.DEBUG)
|
| 205 |
+
|
| 206 |
+
self.metrics = self._metrics_collect(
|
| 207 |
+
self.ticks_index[0], # start time
|
| 208 |
+
self.history_exec["market_volume"],
|
| 209 |
+
self.history_exec["market_price"],
|
| 210 |
+
self.history_steps["amount"].sum(),
|
| 211 |
+
self.history_exec["deal_amount"],
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
# NOTE (yuge): It looks to me that it's the "correct" decision to
|
| 215 |
+
# put all the logs here, because only components like simulators themselves
|
| 216 |
+
# have the knowledge about what could appear in the logs, and what's the format.
|
| 217 |
+
# But I admit it's not necessarily the most convenient way.
|
| 218 |
+
# I'll rethink about it when we have the second environment
|
| 219 |
+
# Maybe some APIs like self.logger.enable_auto_log() ?
|
| 220 |
+
|
| 221 |
+
if self.env is not None:
|
| 222 |
+
for key, value in self.metrics.items():
|
| 223 |
+
if isinstance(value, float):
|
| 224 |
+
self.env.logger.add_scalar(key, value)
|
| 225 |
+
else:
|
| 226 |
+
self.env.logger.add_any(key, value)
|
| 227 |
+
|
| 228 |
+
self.cur_time = self._next_time()
|
| 229 |
+
self.cur_step += 1
|
| 230 |
+
|
| 231 |
+
def get_state(self) -> SAOEState:
|
| 232 |
+
return SAOEState(
|
| 233 |
+
order=self.order,
|
| 234 |
+
cur_time=self.cur_time,
|
| 235 |
+
cur_step=self.cur_step,
|
| 236 |
+
position=self.position,
|
| 237 |
+
history_exec=self.history_exec,
|
| 238 |
+
history_steps=self.history_steps,
|
| 239 |
+
metrics=self.metrics,
|
| 240 |
+
backtest_data=self.backtest_data,
|
| 241 |
+
ticks_per_step=self.ticks_per_step,
|
| 242 |
+
ticks_index=self.ticks_index,
|
| 243 |
+
ticks_for_order=self.ticks_for_order,
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
def done(self) -> bool:
|
| 247 |
+
return self.position < EPS or self.cur_time >= self.order.end_time
|
| 248 |
+
|
| 249 |
+
def _next_time(self) -> pd.Timestamp:
|
| 250 |
+
"""The "current time" (``cur_time``) for next step."""
|
| 251 |
+
# Look for next time on time index
|
| 252 |
+
current_loc = self.ticks_index.get_loc(self.cur_time)
|
| 253 |
+
next_loc = current_loc + self.ticks_per_step
|
| 254 |
+
|
| 255 |
+
# Calibrate the next location to multiple of ticks_per_step.
|
| 256 |
+
# This is to make sure that:
|
| 257 |
+
# as long as ticks_per_step is a multiple of something, each step won't cross morning and afternoon.
|
| 258 |
+
next_loc = next_loc - next_loc % self.ticks_per_step
|
| 259 |
+
|
| 260 |
+
if next_loc < len(self.ticks_index) and self.ticks_index[next_loc] < self.order.end_time:
|
| 261 |
+
return self.ticks_index[next_loc]
|
| 262 |
+
else:
|
| 263 |
+
return self.order.end_time
|
| 264 |
+
|
| 265 |
+
def _cur_duration(self) -> pd.Timedelta:
|
| 266 |
+
"""The "duration" of this step (step that is about to happen)."""
|
| 267 |
+
return self._next_time() - self.cur_time
|
| 268 |
+
|
| 269 |
+
def _split_exec_vol(self, exec_vol_sum: float) -> np.ndarray:
|
| 270 |
+
"""
|
| 271 |
+
Split the volume in each step into minutes, considering possible constraints.
|
| 272 |
+
This follows TWAP strategy.
|
| 273 |
+
"""
|
| 274 |
+
next_time = self._next_time()
|
| 275 |
+
|
| 276 |
+
# get the backtest data for next interval
|
| 277 |
+
self.market_vol = self.backtest_data.get_volume().loc[self.cur_time : next_time - EPS_T].to_numpy()
|
| 278 |
+
self.market_price = self.backtest_data.get_deal_price().loc[self.cur_time : next_time - EPS_T].to_numpy()
|
| 279 |
+
|
| 280 |
+
assert self.market_vol is not None and self.market_price is not None
|
| 281 |
+
|
| 282 |
+
# split the volume equally into each minute
|
| 283 |
+
exec_vol = np.repeat(exec_vol_sum / len(self.market_price), len(self.market_price))
|
| 284 |
+
|
| 285 |
+
# apply the volume threshold
|
| 286 |
+
market_vol_limit = self.vol_threshold * self.market_vol if self.vol_threshold is not None else np.inf
|
| 287 |
+
exec_vol = np.minimum(exec_vol, market_vol_limit) # type: ignore
|
| 288 |
+
|
| 289 |
+
# Complete all the order amount at the last moment.
|
| 290 |
+
if next_time >= self.order.end_time:
|
| 291 |
+
exec_vol[-1] += self.position - exec_vol.sum()
|
| 292 |
+
exec_vol = np.minimum(exec_vol, market_vol_limit) # type: ignore
|
| 293 |
+
|
| 294 |
+
return exec_vol
|
| 295 |
+
|
| 296 |
+
def _metrics_collect(
|
| 297 |
+
self,
|
| 298 |
+
datetime: pd.Timestamp,
|
| 299 |
+
market_vol: np.ndarray,
|
| 300 |
+
market_price: np.ndarray,
|
| 301 |
+
amount: float, # intended to trade such amount
|
| 302 |
+
exec_vol: np.ndarray,
|
| 303 |
+
) -> SAOEMetrics:
|
| 304 |
+
assert len(market_vol) == len(market_price) == len(exec_vol)
|
| 305 |
+
|
| 306 |
+
if np.abs(np.sum(exec_vol)) < EPS:
|
| 307 |
+
exec_avg_price = 0.0
|
| 308 |
+
else:
|
| 309 |
+
exec_avg_price = cast(float, np.average(market_price, weights=exec_vol)) # could be nan
|
| 310 |
+
if hasattr(exec_avg_price, "item"): # could be numpy scalar
|
| 311 |
+
exec_avg_price = exec_avg_price.item() # type: ignore
|
| 312 |
+
|
| 313 |
+
return SAOEMetrics(
|
| 314 |
+
stock_id=self.order.stock_id,
|
| 315 |
+
datetime=datetime,
|
| 316 |
+
direction=self.order.direction,
|
| 317 |
+
market_volume=market_vol.sum(),
|
| 318 |
+
market_price=market_price.mean(),
|
| 319 |
+
amount=amount,
|
| 320 |
+
inner_amount=exec_vol.sum(),
|
| 321 |
+
deal_amount=exec_vol.sum(), # in this simulator, there's no other restrictions
|
| 322 |
+
trade_price=exec_avg_price,
|
| 323 |
+
trade_value=float(np.sum(market_price * exec_vol)),
|
| 324 |
+
position=self.position,
|
| 325 |
+
ffr=float(exec_vol.sum() / self.order.amount),
|
| 326 |
+
pa=price_advantage(exec_avg_price, self.twap_price, self.order.direction),
|
| 327 |
+
)
|
| 328 |
+
|
| 329 |
+
def _get_ticks_slice(self, start: pd.Timestamp, end: pd.Timestamp, include_end: bool = False) -> pd.DatetimeIndex:
|
| 330 |
+
if not include_end:
|
| 331 |
+
end = end - EPS_T
|
| 332 |
+
return self.ticks_index[self.ticks_index.slice_indexer(start, end)]
|
| 333 |
+
|
| 334 |
+
@staticmethod
|
| 335 |
+
def _dataframe_append(df: pd.DataFrame, other: Any) -> pd.DataFrame:
|
| 336 |
+
# dataframe.append is deprecated
|
| 337 |
+
other_df = pd.DataFrame(other).set_index("datetime")
|
| 338 |
+
other_df.index.name = "datetime"
|
| 339 |
+
return pd.concat([df, other_df], axis=0)
|
| 340 |
+
|
| 341 |
+
|
| 342 |
+
def price_advantage(
|
| 343 |
+
exec_price: float_or_ndarray,
|
| 344 |
+
baseline_price: float,
|
| 345 |
+
direction: OrderDir | int,
|
| 346 |
+
) -> float_or_ndarray:
|
| 347 |
+
if baseline_price == 0: # something is wrong with data. Should be nan here
|
| 348 |
+
if isinstance(exec_price, float):
|
| 349 |
+
return 0.0
|
| 350 |
+
else:
|
| 351 |
+
return np.zeros_like(exec_price)
|
| 352 |
+
if direction == OrderDir.BUY:
|
| 353 |
+
res = (1 - exec_price / baseline_price) * 10000
|
| 354 |
+
elif direction == OrderDir.SELL:
|
| 355 |
+
res = (exec_price / baseline_price - 1) * 10000
|
| 356 |
+
else:
|
| 357 |
+
raise ValueError(f"Unexpected order direction: {direction}")
|
| 358 |
+
res_wo_nan: np.ndarray = np.nan_to_num(res, nan=0.0)
|
| 359 |
+
if res_wo_nan.size == 1:
|
| 360 |
+
return res_wo_nan.item()
|
| 361 |
+
else:
|
| 362 |
+
return cast(float_or_ndarray, res_wo_nan)
|
Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/state.py
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) Microsoft Corporation.
|
| 2 |
+
# Licensed under the MIT License.
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import typing
|
| 7 |
+
from typing import NamedTuple, Optional
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
import pandas as pd
|
| 11 |
+
from qlib.backtest import Order
|
| 12 |
+
from qlib.typehint import TypedDict
|
| 13 |
+
|
| 14 |
+
if typing.TYPE_CHECKING:
|
| 15 |
+
from qlib.rl.data.base import BaseIntradayBacktestData
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class SAOEMetrics(TypedDict):
|
| 19 |
+
"""Metrics for SAOE accumulated for a "period".
|
| 20 |
+
It could be accumulated for a day, or a period of time (e.g., 30min), or calculated separately for every minute.
|
| 21 |
+
|
| 22 |
+
Warnings
|
| 23 |
+
--------
|
| 24 |
+
The type hints are for single elements. In lots of times, they can be vectorized.
|
| 25 |
+
For example, ``market_volume`` could be a list of float (or ndarray) rather tahn a single float.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
stock_id: str
|
| 29 |
+
"""Stock ID of this record."""
|
| 30 |
+
datetime: pd.Timestamp | pd.DatetimeIndex
|
| 31 |
+
"""Datetime of this record (this is index in the dataframe)."""
|
| 32 |
+
direction: int
|
| 33 |
+
"""Direction of the order. 0 for sell, 1 for buy."""
|
| 34 |
+
|
| 35 |
+
# Market information.
|
| 36 |
+
market_volume: np.ndarray | float
|
| 37 |
+
"""(total) market volume traded in the period."""
|
| 38 |
+
market_price: np.ndarray | float
|
| 39 |
+
"""Deal price. If it's a period of time, this is the average market deal price."""
|
| 40 |
+
|
| 41 |
+
# Strategy records.
|
| 42 |
+
|
| 43 |
+
amount: np.ndarray | float
|
| 44 |
+
"""Total amount (volume) strategy intends to trade."""
|
| 45 |
+
inner_amount: np.ndarray | float
|
| 46 |
+
"""Total amount that the lower-level strategy intends to trade
|
| 47 |
+
(might be larger than amount, e.g., to ensure ffr)."""
|
| 48 |
+
|
| 49 |
+
deal_amount: np.ndarray | float
|
| 50 |
+
"""Amount that successfully takes effect (must be less than inner_amount)."""
|
| 51 |
+
trade_price: np.ndarray | float
|
| 52 |
+
"""The average deal price for this strategy."""
|
| 53 |
+
trade_value: np.ndarray | float
|
| 54 |
+
"""Total worth of trading. In the simple simulation, trade_value = deal_amount * price."""
|
| 55 |
+
position: np.ndarray | float
|
| 56 |
+
"""Position left after this "period"."""
|
| 57 |
+
|
| 58 |
+
# Accumulated metrics
|
| 59 |
+
|
| 60 |
+
ffr: np.ndarray | float
|
| 61 |
+
"""Completed how much percent of the daily order."""
|
| 62 |
+
|
| 63 |
+
pa: np.ndarray | float
|
| 64 |
+
"""Price advantage compared to baseline (i.e., trade with baseline market price).
|
| 65 |
+
The baseline is trade price when using TWAP strategy to execute this order.
|
| 66 |
+
Please note that there could be data leak here).
|
| 67 |
+
Unit is BP (basis point, 1/10000)."""
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
class SAOEState(NamedTuple):
|
| 71 |
+
"""Data structure holding a state for SAOE simulator."""
|
| 72 |
+
|
| 73 |
+
order: Order
|
| 74 |
+
"""The order we are dealing with."""
|
| 75 |
+
cur_time: pd.Timestamp
|
| 76 |
+
"""Current time, e.g., 9:30."""
|
| 77 |
+
cur_step: int
|
| 78 |
+
"""Current step, e.g., 0."""
|
| 79 |
+
position: float
|
| 80 |
+
"""Current remaining volume to execute."""
|
| 81 |
+
history_exec: pd.DataFrame
|
| 82 |
+
"""See :attr:`SingleAssetOrderExecution.history_exec`."""
|
| 83 |
+
history_steps: pd.DataFrame
|
| 84 |
+
"""See :attr:`SingleAssetOrderExecution.history_steps`."""
|
| 85 |
+
|
| 86 |
+
metrics: Optional[SAOEMetrics]
|
| 87 |
+
"""Daily metric, only available when the trading is in "done" state."""
|
| 88 |
+
|
| 89 |
+
backtest_data: BaseIntradayBacktestData
|
| 90 |
+
"""Backtest data is included in the state.
|
| 91 |
+
Actually, only the time index of this data is needed, at this moment.
|
| 92 |
+
I include the full data so that algorithms (e.g., VWAP) that relies on the raw data can be implemented.
|
| 93 |
+
Interpreter can use this as they wish, but they should be careful not to leak future data.
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
ticks_per_step: int
|
| 97 |
+
"""How many ticks for each step."""
|
| 98 |
+
ticks_index: pd.DatetimeIndex
|
| 99 |
+
"""Trading ticks in all day, NOT sliced by order (defined in data). e.g., [9:30, 9:31, ..., 14:59]."""
|
| 100 |
+
ticks_for_order: pd.DatetimeIndex
|
| 101 |
+
"""Trading ticks sliced by order, e.g., [9:45, 9:46, ..., 14:44]."""
|