humblman commited on
Commit
3bb0598
·
verified ·
1 Parent(s): 29ea226

Upload folder using huggingface_hub (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. Kronos/qlib/CHANGELOG.md +0 -0
  3. Kronos/qlib/CHANGES.rst +179 -0
  4. Kronos/qlib/CODE_OF_CONDUCT.md +9 -0
  5. Kronos/qlib/Dockerfile +31 -0
  6. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.pyx +207 -0
  7. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/base.py +281 -0
  8. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/cache.py +1199 -0
  9. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/client.py +103 -0
  10. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/data.py +1332 -0
  11. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/__init__.py +722 -0
  12. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/handler.py +785 -0
  13. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/loader.py +414 -0
  14. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/processor.py +419 -0
  15. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/storage.py +191 -0
  16. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/utils.py +142 -0
  17. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/weight.py +27 -0
  18. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/filter.py +375 -0
  19. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/inst_processor.py +22 -0
  20. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/ops.py +1681 -0
  21. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/pit.py +72 -0
  22. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/__init__.py +6 -0
  23. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/file_storage.py +379 -0
  24. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/storage.py +494 -0
  25. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/log.py +262 -0
  26. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/__init__.py +8 -0
  27. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/base.py +110 -0
  28. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/__init__.py +0 -0
  29. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/ensemble.py +132 -0
  30. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/group.py +115 -0
  31. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/__init__.py +0 -0
  32. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/base.py +45 -0
  33. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/__init__.py +7 -0
  34. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/dataset.py +77 -0
  35. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/model.py +75 -0
  36. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/task.py +56 -0
  37. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/__init__.py +14 -0
  38. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/base.py +147 -0
  39. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/poet.py +83 -0
  40. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/shrink.py +259 -0
  41. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/structured.py +94 -0
  42. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/trainer.py +619 -0
  43. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/utils.py +26 -0
  44. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/__init__.py +8 -0
  45. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/aux_info.py +43 -0
  46. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/__init__.py +0 -0
  47. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/backtest.py +384 -0
  48. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/naive_config_parser.py +106 -0
  49. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/train_onpolicy.py +269 -0
  50. Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/utils.py +29 -0
.gitattributes CHANGED
@@ -62,3 +62,7 @@ Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/expanding.cpython
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
64
  Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.cpython-39-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
64
  Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.cpython-39-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
65
+ Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/expanding.o filter=lfs diff=lfs merge=lfs -text
66
+ Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/rolling.o filter=lfs diff=lfs merge=lfs -text
67
+ Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/expanding.o filter=lfs diff=lfs merge=lfs -text
68
+ Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/rolling.o filter=lfs diff=lfs merge=lfs -text
Kronos/qlib/CHANGELOG.md ADDED
File without changes
Kronos/qlib/CHANGES.rst ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Changelog
2
+ =========
3
+ Here you can see the full list of changes between each QLib release.
4
+
5
+ Version 0.1.0
6
+ -------------
7
+ This is the initial release of QLib library.
8
+
9
+ Version 0.1.1
10
+ -------------
11
+ Performance optimize. Add more features and operators.
12
+
13
+ Version 0.1.2
14
+ -------------
15
+ - Support operator syntax. Now ``High() - Low()`` is equivalent to ``Sub(High(), Low())``.
16
+ - Add more technical indicators.
17
+
18
+ Version 0.1.3
19
+ -------------
20
+ Bug fix and add instruments filtering mechanism.
21
+
22
+ Version 0.2.0
23
+ -------------
24
+ - Redesign ``LocalProvider`` database format for performance improvement.
25
+ - Support load features as string fields.
26
+ - Add scripts for database construction.
27
+ - More operators and technical indicators.
28
+
29
+ Version 0.2.1
30
+ -------------
31
+ - Support registering user-defined ``Provider``.
32
+ - Support use operators in string format, e.g. ``['Ref($close, 1)']`` is valid field format.
33
+ - Support dynamic fields in ``$some_field`` format. And existing fields like ``Close()`` may be deprecated in the future.
34
+
35
+ Version 0.2.2
36
+ -------------
37
+ - Add ``disk_cache`` for reusing features (enabled by default).
38
+ - Add ``qlib.contrib`` for experimental model construction and evaluation.
39
+
40
+
41
+ Version 0.2.3
42
+ -------------
43
+ - Add ``backtest`` module
44
+ - Decoupling the Strategy, Account, Position, Exchange from the backtest module
45
+
46
+ Version 0.2.4
47
+ -------------
48
+ - Add ``profit attribution`` module
49
+ - Add ``rick_control`` and ``cost_control`` strategies
50
+
51
+ Version 0.3.0
52
+ -------------
53
+ - Add ``estimator`` module
54
+
55
+ Version 0.3.1
56
+ -------------
57
+ - Add ``filter`` module
58
+
59
+ Version 0.3.2
60
+ -------------
61
+ - Add real price trading, if the ``factor`` field in the data set is incomplete, use ``adj_price`` trading
62
+ - Refactor ``handler`` ``launcher`` ``trainer`` code
63
+ - Support ``backtest`` configuration parameters in the configuration file
64
+ - Fix bug in position ``amount`` is 0
65
+ - Fix bug of ``filter`` module
66
+
67
+ Version 0.3.3
68
+ -------------
69
+ - Fix bug of ``filter`` module
70
+
71
+ Version 0.3.4
72
+ -------------
73
+ - Support for ``finetune model``
74
+ - Refactor ``fetcher`` code
75
+
76
+ Version 0.3.5
77
+ -------------
78
+ - Support multi-label training, you can provide multiple label in ``handler``. (But LightGBM doesn't support due to the algorithm itself)
79
+ - Refactor ``handler`` code, dataset.py is no longer used, and you can deploy your own labels and features in ``feature_label_config``
80
+ - Handler only offer DataFrame. Also, ``trainer`` and model.py only receive DataFrame
81
+ - Change ``split_rolling_data``, we roll the data on market calendar now, not on normal date
82
+ - Move some date config from ``handler`` to ``trainer``
83
+
84
+ Version 0.4.0
85
+ -------------
86
+ - Add `data` package that holds all data-related codes
87
+ - Reform the data provider structure
88
+ - Create a server for data centralized management `qlib-server <https://amc-msra.visualstudio.com/trading-algo/_git/qlib-server>`_
89
+ - Add a `ClientProvider` to work with server
90
+ - Add a pluggable cache mechanism
91
+ - Add a recursive backtracking algorithm to inspect the furthest reference date for an expression
92
+
93
+ .. note::
94
+ The ``D.instruments`` function does not support ``start_time``, ``end_time``, and ``as_list`` parameters, if you want to get the results of previous versions of ``D.instruments``, you can do this:
95
+
96
+
97
+ >>> from qlib.data import D
98
+ >>> instruments = D.instruments(market='csi500')
99
+ >>> D.list_instruments(instruments=instruments, start_time='2015-01-01', end_time='2016-02-15', as_list=True)
100
+
101
+
102
+ Version 0.4.1
103
+ -------------
104
+ - Add support Windows
105
+ - Fix ``instruments`` type bug
106
+ - Fix ``features`` is empty bug(It will cause failure in updating)
107
+ - Fix ``cache`` lock and update bug
108
+ - Fix use the same cache for the same field (the original space will add a new cache)
109
+ - Change "logger handler" from config
110
+ - Change model load support 0.4.0 later
111
+ - The default value of the ``method`` parameter of ``risk_analysis`` function is changed from **ci** to **si**
112
+
113
+
114
+ Version 0.4.2
115
+ -------------
116
+ - Refactor DataHandler
117
+ - Add ``Alpha360`` DataHandler
118
+
119
+
120
+ Version 0.4.3
121
+ -------------
122
+ - Implementing Online Inference and Trading Framework
123
+ - Refactoring The interfaces of backtest and strategy module.
124
+
125
+
126
+ Version 0.4.4
127
+ -------------
128
+ - Optimize cache generation performance
129
+ - Add report module
130
+ - Fix bug when using ``ServerDatasetCache`` offline.
131
+ - In the previous version of ``long_short_backtest``, there is a case of ``np.nan`` in long_short. The current version ``0.4.4`` has been fixed, so ``long_short_backtest`` will be different from the previous version.
132
+ - In the ``0.4.2`` version of ``risk_analysis`` function, ``N`` is ``250``, and ``N`` is ``252`` from ``0.4.3``, so ``0.4.2`` is ``0.002122`` smaller than the ``0.4.3`` the backtest result is slightly different between ``0.4.2`` and ``0.4.3``.
133
+ - refactor the argument of backtest function.
134
+ - **NOTE**:
135
+ - The default arguments of topk margin strategy is changed. Please pass the arguments explicitly if you want to get the same backtest result as previous version.
136
+ - The TopkWeightStrategy is changed slightly. It will try to sell the stocks more than ``topk``. (The backtest result of TopkAmountStrategy remains the same)
137
+ - The margin ratio mechanism is supported in the Topk Margin strategies.
138
+
139
+
140
+ Version 0.4.5
141
+ -------------
142
+ - Add multi-kernel implementation for both client and server.
143
+ - Support a new way to load data from client which skips dataset cache.
144
+ - Change the default dataset method from single kernel implementation to multi kernel implementation.
145
+ - Accelerate the high frequency data reading by optimizing the relative modules.
146
+ - Support a new method to write config file by using dict.
147
+
148
+ Version 0.4.6
149
+ -------------
150
+ - Some bugs are fixed
151
+ - The default config in `Version 0.4.5` is not friendly to daily frequency data.
152
+ - Backtest error in TopkWeightStrategy when `WithInteract=True`.
153
+
154
+
155
+ Version 0.5.0
156
+ -------------
157
+ - First opensource version
158
+ - Refine the docs, code
159
+ - Add baselines
160
+ - public data crawler
161
+
162
+
163
+ Version 0.8.0
164
+ -------------
165
+ - The backtest is greatly refactored.
166
+ - Nested decision execution framework is supported
167
+ - There are lots of changes for daily trading, it is hard to list all of them. But a few important changes could be noticed
168
+ - The trading limitation is more accurate;
169
+ - In `previous version <https://github.com/microsoft/qlib/blob/v0.7.2/qlib/contrib/backtest/exchange.py#L160>`__, longing and shorting actions share the same action.
170
+ - In `current version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/backtest/exchange.py#L304>`__, the trading limitation is different between logging and shorting action.
171
+ - The constant is different when calculating annualized metrics.
172
+ - `Current version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/contrib/evaluate.py#L42>`_ uses more accurate constant than `previous version <https://github.com/microsoft/qlib/blob/v0.7.2/qlib/contrib/evaluate.py#L22>`__
173
+ - `A new version <https://github.com/microsoft/qlib/blob/7c31012b507a3823117bddcc693fc64899460b2a/qlib/tests/data.py#L17>`__ of data is released. Due to the unstability of Yahoo data source, the data may be different after downloading data again.
174
+ - Users could check out the backtesting results between `Current version <https://github.com/microsoft/qlib/tree/7c31012b507a3823117bddcc693fc64899460b2a/examples/benchmarks>`__ and `previous version <https://github.com/microsoft/qlib/tree/v0.7.2/examples/benchmarks>`__
175
+
176
+
177
+ Other Versions
178
+ --------------
179
+ Please refer to `Github release Notes <https://github.com/microsoft/qlib/releases>`_
Kronos/qlib/CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ # Microsoft Open Source Code of Conduct
2
+
3
+ This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/).
4
+
5
+ Resources:
6
+
7
+ - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/)
8
+ - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/)
9
+ - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns
Kronos/qlib/Dockerfile ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM continuumio/miniconda3:latest
2
+
3
+ WORKDIR /qlib
4
+
5
+ COPY . .
6
+
7
+ RUN apt-get update && \
8
+ apt-get install -y build-essential
9
+
10
+ RUN conda create --name qlib_env python=3.8 -y
11
+ RUN echo "conda activate qlib_env" >> ~/.bashrc
12
+ ENV PATH /opt/conda/envs/qlib_env/bin:$PATH
13
+
14
+ RUN python -m pip install --upgrade pip
15
+
16
+ RUN python -m pip install numpy==1.23.5
17
+ RUN python -m pip install pandas==1.5.3
18
+ RUN python -m pip install importlib-metadata==5.2.0
19
+ RUN python -m pip install "cloudpickle<3"
20
+ RUN python -m pip install scikit-learn==1.3.2
21
+
22
+ RUN python -m pip install cython packaging tables matplotlib statsmodels
23
+ RUN python -m pip install pybind11 cvxpy
24
+
25
+ ARG IS_STABLE="yes"
26
+
27
+ RUN if [ "$IS_STABLE" = "yes" ]; then \
28
+ python -m pip install pyqlib; \
29
+ else \
30
+ python setup.py install; \
31
+ fi
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.pyx ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # cython: profile=False
2
+ # cython: boundscheck=False, wraparound=False, cdivision=True
3
+ cimport cython
4
+ cimport numpy as np
5
+ import numpy as np
6
+
7
+ from libc.math cimport sqrt, isnan, NAN
8
+ from libcpp.deque cimport deque
9
+
10
+
11
+ cdef class Rolling:
12
+ """1-D array rolling"""
13
+ cdef int window
14
+ cdef deque[double] barv
15
+ cdef int na_count
16
+ def __init__(self, int window):
17
+ self.window = window
18
+ self.na_count = window
19
+ cdef int i
20
+ for i in range(window):
21
+ self.barv.push_back(NAN)
22
+
23
+ cdef double update(self, double val):
24
+ pass
25
+
26
+
27
+ cdef class Mean(Rolling):
28
+ """1-D array rolling mean"""
29
+ cdef double vsum
30
+ def __init__(self, int window):
31
+ super(Mean, self).__init__(window)
32
+ self.vsum = 0
33
+
34
+ cdef double update(self, double val):
35
+ self.barv.push_back(val)
36
+ if not isnan(self.barv.front()):
37
+ self.vsum -= self.barv.front()
38
+ else:
39
+ self.na_count -= 1
40
+ self.barv.pop_front()
41
+ if isnan(val):
42
+ self.na_count += 1
43
+ # return NAN
44
+ else:
45
+ self.vsum += val
46
+ return self.vsum / (self.window - self.na_count)
47
+
48
+
49
+ cdef class Slope(Rolling):
50
+ """1-D array rolling slope"""
51
+ cdef double i_sum # can be used as i2_sum
52
+ cdef double x_sum
53
+ cdef double x2_sum
54
+ cdef double y_sum
55
+ cdef double xy_sum
56
+ def __init__(self, int window):
57
+ super(Slope, self).__init__(window)
58
+ self.i_sum = 0
59
+ self.x_sum = 0
60
+ self.x2_sum = 0
61
+ self.y_sum = 0
62
+ self.xy_sum = 0
63
+
64
+ cdef double update(self, double val):
65
+ self.barv.push_back(val)
66
+ self.xy_sum = self.xy_sum - self.y_sum
67
+ self.x2_sum = self.x2_sum + self.i_sum - 2*self.x_sum
68
+ self.x_sum = self.x_sum - self.i_sum
69
+ cdef double _val
70
+ _val = self.barv.front()
71
+ if not isnan(_val):
72
+ self.i_sum -= 1
73
+ self.y_sum -= _val
74
+ else:
75
+ self.na_count -= 1
76
+ self.barv.pop_front()
77
+ if isnan(val):
78
+ self.na_count += 1
79
+ # return NAN
80
+ else:
81
+ self.i_sum += 1
82
+ self.x_sum += self.window
83
+ self.x2_sum += self.window * self.window
84
+ self.y_sum += val
85
+ self.xy_sum += self.window * val
86
+ cdef int N = self.window - self.na_count
87
+ return (N*self.xy_sum - self.x_sum*self.y_sum) / \
88
+ (N*self.x2_sum - self.x_sum*self.x_sum)
89
+
90
+
91
+ cdef class Resi(Rolling):
92
+ """1-D array rolling residuals"""
93
+ cdef double i_sum # can be used as i2_sum
94
+ cdef double x_sum
95
+ cdef double x2_sum
96
+ cdef double y_sum
97
+ cdef double xy_sum
98
+ def __init__(self, int window):
99
+ super(Resi, self).__init__(window)
100
+ self.i_sum = 0
101
+ self.x_sum = 0
102
+ self.x2_sum = 0
103
+ self.y_sum = 0
104
+ self.xy_sum = 0
105
+
106
+ cdef double update(self, double val):
107
+ self.barv.push_back(val)
108
+ self.xy_sum = self.xy_sum - self.y_sum
109
+ self.x2_sum = self.x2_sum + self.i_sum - 2*self.x_sum
110
+ self.x_sum = self.x_sum - self.i_sum
111
+ cdef double _val
112
+ _val = self.barv.front()
113
+ if not isnan(_val):
114
+ self.i_sum -= 1
115
+ self.y_sum -= _val
116
+ else:
117
+ self.na_count -= 1
118
+ self.barv.pop_front()
119
+ if isnan(val):
120
+ self.na_count += 1
121
+ # return NAN
122
+ else:
123
+ self.i_sum += 1
124
+ self.x_sum += self.window
125
+ self.x2_sum += self.window * self.window
126
+ self.y_sum += val
127
+ self.xy_sum += self.window * val
128
+ cdef int N = self.window - self.na_count
129
+ slope = (N*self.xy_sum - self.x_sum*self.y_sum) / \
130
+ (N*self.x2_sum - self.x_sum*self.x_sum)
131
+ x_mean = self.x_sum / N
132
+ y_mean = self.y_sum / N
133
+ interp = y_mean - slope*x_mean
134
+ return val - (slope*self.window + interp)
135
+
136
+
137
+ cdef class Rsquare(Rolling):
138
+ """1-D array rolling rsquare"""
139
+ cdef double i_sum
140
+ cdef double x_sum
141
+ cdef double x2_sum
142
+ cdef double y_sum
143
+ cdef double y2_sum
144
+ cdef double xy_sum
145
+ def __init__(self, int window):
146
+ super(Rsquare, self).__init__(window)
147
+ self.i_sum = 0
148
+ self.x_sum = 0
149
+ self.x2_sum = 0
150
+ self.y_sum = 0
151
+ self.y2_sum = 0
152
+ self.xy_sum = 0
153
+
154
+ cdef double update(self, double val):
155
+ self.barv.push_back(val)
156
+ self.xy_sum = self.xy_sum - self.y_sum
157
+ self.x2_sum = self.x2_sum + self.i_sum - 2*self.x_sum
158
+ self.x_sum = self.x_sum - self.i_sum
159
+ cdef double _val
160
+ _val = self.barv.front()
161
+ if not isnan(_val):
162
+ self.i_sum -= 1
163
+ self.y_sum -= _val
164
+ self.y2_sum -= _val * _val
165
+ else:
166
+ self.na_count -= 1
167
+ self.barv.pop_front()
168
+ if isnan(val):
169
+ self.na_count += 1
170
+ # return NAN
171
+ else:
172
+ self.i_sum += 1
173
+ self.x_sum += self.window
174
+ self.x2_sum += self.window * self.window
175
+ self.y_sum += val
176
+ self.y2_sum += val * val
177
+ self.xy_sum += self.window * val
178
+ cdef int N = self.window - self.na_count
179
+ cdef double rvalue
180
+ rvalue = (N*self.xy_sum - self.x_sum*self.y_sum) / \
181
+ sqrt((N*self.x2_sum - self.x_sum*self.x_sum) * (N*self.y2_sum - self.y_sum*self.y_sum))
182
+ return rvalue * rvalue
183
+
184
+
185
+ cdef np.ndarray[double, ndim=1] rolling(Rolling r, np.ndarray a):
186
+ cdef int i
187
+ cdef int N = len(a)
188
+ cdef np.ndarray[double, ndim=1] ret = np.empty(N)
189
+ for i in range(N):
190
+ ret[i] = r.update(a[i])
191
+ return ret
192
+
193
+ def rolling_mean(np.ndarray a, int window):
194
+ cdef Mean r = Mean(window)
195
+ return rolling(r, a)
196
+
197
+ def rolling_slope(np.ndarray a, int window):
198
+ cdef Slope r = Slope(window)
199
+ return rolling(r, a)
200
+
201
+ def rolling_rsquare(np.ndarray a, int window):
202
+ cdef Rsquare r = Rsquare(window)
203
+ return rolling(r, a)
204
+
205
+ def rolling_resi(np.ndarray a, int window):
206
+ cdef Resi r = Resi(window)
207
+ return rolling(r, a)
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/base.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 abc
9
+ import pandas as pd
10
+ from ..log import get_module_logger
11
+
12
+
13
+ class Expression(abc.ABC):
14
+ """
15
+ Expression base class
16
+
17
+ Expression is designed to handle the calculation of data with the format below
18
+ data with two dimension for each instrument,
19
+
20
+ - feature
21
+ - time: it could be observation time or period time.
22
+
23
+ - period time is designed for Point-in-time database. For example, the period time maybe 2014Q4, its value can observed for multiple times(different value may be observed at different time due to amendment).
24
+ """
25
+
26
+ def __str__(self):
27
+ return type(self).__name__
28
+
29
+ def __repr__(self):
30
+ return str(self)
31
+
32
+ def __gt__(self, other):
33
+ from .ops import Gt # pylint: disable=C0415
34
+
35
+ return Gt(self, other)
36
+
37
+ def __ge__(self, other):
38
+ from .ops import Ge # pylint: disable=C0415
39
+
40
+ return Ge(self, other)
41
+
42
+ def __lt__(self, other):
43
+ from .ops import Lt # pylint: disable=C0415
44
+
45
+ return Lt(self, other)
46
+
47
+ def __le__(self, other):
48
+ from .ops import Le # pylint: disable=C0415
49
+
50
+ return Le(self, other)
51
+
52
+ def __eq__(self, other):
53
+ from .ops import Eq # pylint: disable=C0415
54
+
55
+ return Eq(self, other)
56
+
57
+ def __ne__(self, other):
58
+ from .ops import Ne # pylint: disable=C0415
59
+
60
+ return Ne(self, other)
61
+
62
+ def __add__(self, other):
63
+ from .ops import Add # pylint: disable=C0415
64
+
65
+ return Add(self, other)
66
+
67
+ def __radd__(self, other):
68
+ from .ops import Add # pylint: disable=C0415
69
+
70
+ return Add(other, self)
71
+
72
+ def __sub__(self, other):
73
+ from .ops import Sub # pylint: disable=C0415
74
+
75
+ return Sub(self, other)
76
+
77
+ def __rsub__(self, other):
78
+ from .ops import Sub # pylint: disable=C0415
79
+
80
+ return Sub(other, self)
81
+
82
+ def __mul__(self, other):
83
+ from .ops import Mul # pylint: disable=C0415
84
+
85
+ return Mul(self, other)
86
+
87
+ def __rmul__(self, other):
88
+ from .ops import Mul # pylint: disable=C0415
89
+
90
+ return Mul(self, other)
91
+
92
+ def __div__(self, other):
93
+ from .ops import Div # pylint: disable=C0415
94
+
95
+ return Div(self, other)
96
+
97
+ def __rdiv__(self, other):
98
+ from .ops import Div # pylint: disable=C0415
99
+
100
+ return Div(other, self)
101
+
102
+ def __truediv__(self, other):
103
+ from .ops import Div # pylint: disable=C0415
104
+
105
+ return Div(self, other)
106
+
107
+ def __rtruediv__(self, other):
108
+ from .ops import Div # pylint: disable=C0415
109
+
110
+ return Div(other, self)
111
+
112
+ def __pow__(self, other):
113
+ from .ops import Power # pylint: disable=C0415
114
+
115
+ return Power(self, other)
116
+
117
+ def __rpow__(self, other):
118
+ from .ops import Power # pylint: disable=C0415
119
+
120
+ return Power(other, self)
121
+
122
+ def __and__(self, other):
123
+ from .ops import And # pylint: disable=C0415
124
+
125
+ return And(self, other)
126
+
127
+ def __rand__(self, other):
128
+ from .ops import And # pylint: disable=C0415
129
+
130
+ return And(other, self)
131
+
132
+ def __or__(self, other):
133
+ from .ops import Or # pylint: disable=C0415
134
+
135
+ return Or(self, other)
136
+
137
+ def __ror__(self, other):
138
+ from .ops import Or # pylint: disable=C0415
139
+
140
+ return Or(other, self)
141
+
142
+ def load(self, instrument, start_index, end_index, *args):
143
+ """load feature
144
+ This function is responsible for loading feature/expression based on the expression engine.
145
+
146
+ The concrete implementation will be separated into two parts:
147
+
148
+ 1) caching data, handle errors.
149
+
150
+ - This part is shared by all the expressions and implemented in Expression
151
+ 2) processing and calculating data based on the specific expression.
152
+
153
+ - This part is different in each expression and implemented in each expression
154
+
155
+ Expression Engine is shared by different data.
156
+ Different data will have different extra information for `args`.
157
+
158
+ Parameters
159
+ ----------
160
+ instrument : str
161
+ instrument code.
162
+ start_index : str
163
+ feature start index [in calendar].
164
+ end_index : str
165
+ feature end index [in calendar].
166
+
167
+ *args may contain following information:
168
+ 1) if it is used in basic expression engine data, it contains following arguments
169
+ freq: str
170
+ feature frequency.
171
+
172
+ 2) if is used in PIT data, it contains following arguments
173
+ cur_pit:
174
+ it is designed for the point-in-time data.
175
+ period: int
176
+ This is used for query specific period.
177
+ The period is represented with int in Qlib. (e.g. 202001 may represent the first quarter in 2020)
178
+
179
+ Returns
180
+ ----------
181
+ pd.Series
182
+ feature series: The index of the series is the calendar index
183
+ """
184
+ from .cache import H # pylint: disable=C0415
185
+
186
+ # cache
187
+ cache_key = str(self), instrument, start_index, end_index, *args
188
+ if cache_key in H["f"]:
189
+ return H["f"][cache_key]
190
+ if start_index is not None and end_index is not None and start_index > end_index:
191
+ raise ValueError("Invalid index range: {} {}".format(start_index, end_index))
192
+ try:
193
+ series = self._load_internal(instrument, start_index, end_index, *args)
194
+ except Exception as e:
195
+ get_module_logger("data").debug(
196
+ f"Loading data error: instrument={instrument}, expression={str(self)}, "
197
+ f"start_index={start_index}, end_index={end_index}, args={args}. "
198
+ f"error info: {str(e)}"
199
+ )
200
+ raise
201
+ series.name = str(self)
202
+ H["f"][cache_key] = series
203
+ return series
204
+
205
+ @abc.abstractmethod
206
+ def _load_internal(self, instrument, start_index, end_index, *args) -> pd.Series:
207
+ raise NotImplementedError("This function must be implemented in your newly defined feature")
208
+
209
+ @abc.abstractmethod
210
+ def get_longest_back_rolling(self):
211
+ """Get the longest length of historical data the feature has accessed
212
+
213
+ This is designed for getting the needed range of the data to calculate
214
+ the features in specific range at first. However, situations like
215
+ Ref(Ref($close, -1), 1) can not be handled rightly.
216
+
217
+ So this will only used for detecting the length of historical data needed.
218
+ """
219
+ # TODO: forward operator like Ref($close, -1) is not supported yet.
220
+ raise NotImplementedError("This function must be implemented in your newly defined feature")
221
+
222
+ @abc.abstractmethod
223
+ def get_extended_window_size(self):
224
+ """get_extend_window_size
225
+
226
+ For to calculate this Operator in range[start_index, end_index]
227
+ We have to get the *leaf feature* in
228
+ range[start_index - lft_etd, end_index + rght_etd].
229
+
230
+ Returns
231
+ ----------
232
+ (int, int)
233
+ lft_etd, rght_etd
234
+ """
235
+ raise NotImplementedError("This function must be implemented in your newly defined feature")
236
+
237
+
238
+ class Feature(Expression):
239
+ """Static Expression
240
+
241
+ This kind of feature will load data from provider
242
+ """
243
+
244
+ def __init__(self, name=None):
245
+ if name:
246
+ self._name = name
247
+ else:
248
+ self._name = type(self).__name__
249
+
250
+ def __str__(self):
251
+ return "$" + self._name
252
+
253
+ def _load_internal(self, instrument, start_index, end_index, freq):
254
+ # load
255
+ from .data import FeatureD # pylint: disable=C0415
256
+
257
+ return FeatureD.feature(instrument, str(self), start_index, end_index, freq)
258
+
259
+ def get_longest_back_rolling(self):
260
+ return 0
261
+
262
+ def get_extended_window_size(self):
263
+ return 0, 0
264
+
265
+
266
+ class PFeature(Feature):
267
+ def __str__(self):
268
+ return "$$" + self._name
269
+
270
+ def _load_internal(self, instrument, start_index, end_index, cur_time, period=None):
271
+ from .data import PITD # pylint: disable=C0415
272
+
273
+ return PITD.period_feature(instrument, str(self), start_index, end_index, cur_time, period)
274
+
275
+
276
+ class ExpressionOps(Expression):
277
+ """Operator Expression
278
+
279
+ This kind of feature will use operator for feature
280
+ construction on the fly.
281
+ """
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/cache.py ADDED
@@ -0,0 +1,1199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 os
9
+ import sys
10
+ import stat
11
+ import time
12
+ import pickle
13
+ import traceback
14
+ import redis_lock
15
+ import contextlib
16
+ import abc
17
+ from pathlib import Path
18
+ import numpy as np
19
+ import pandas as pd
20
+ from typing import Union, Iterable
21
+ from collections import OrderedDict
22
+
23
+ from ..config import C
24
+ from ..utils import (
25
+ hash_args,
26
+ get_redis_connection,
27
+ read_bin,
28
+ parse_field,
29
+ remove_fields_space,
30
+ normalize_cache_fields,
31
+ normalize_cache_instruments,
32
+ )
33
+ from ..utils.pickle_utils import restricted_pickle_load
34
+
35
+ from ..log import get_module_logger
36
+ from .base import Feature
37
+ from .ops import Operators # pylint: disable=W0611 # noqa: F401
38
+
39
+
40
+ class QlibCacheException(RuntimeError):
41
+ pass
42
+
43
+
44
+ class MemCacheUnit(abc.ABC):
45
+ """Memory Cache Unit."""
46
+
47
+ def __init__(self, *args, **kwargs):
48
+ self.size_limit = kwargs.pop("size_limit", 0)
49
+ self._size = 0
50
+ self.od = OrderedDict()
51
+
52
+ def __setitem__(self, key, value):
53
+ # TODO: thread safe?__setitem__ failure might cause inconsistent size?
54
+
55
+ # precalculate the size after od.__setitem__
56
+ self._adjust_size(key, value)
57
+
58
+ self.od.__setitem__(key, value)
59
+
60
+ # move the key to end,make it latest
61
+ self.od.move_to_end(key)
62
+
63
+ if self.limited:
64
+ # pop the oldest items beyond size limit
65
+ while self._size > self.size_limit:
66
+ self.popitem(last=False)
67
+
68
+ def __getitem__(self, key):
69
+ v = self.od.__getitem__(key)
70
+ self.od.move_to_end(key)
71
+ return v
72
+
73
+ def __contains__(self, key):
74
+ return key in self.od
75
+
76
+ def __len__(self):
77
+ return self.od.__len__()
78
+
79
+ def __repr__(self):
80
+ return f"{self.__class__.__name__}<size_limit:{self.size_limit if self.limited else 'no limit'} total_size:{self._size}>\n{self.od.__repr__()}"
81
+
82
+ def set_limit_size(self, limit):
83
+ self.size_limit = limit
84
+
85
+ @property
86
+ def limited(self):
87
+ """whether memory cache is limited"""
88
+ return self.size_limit > 0
89
+
90
+ @property
91
+ def total_size(self):
92
+ return self._size
93
+
94
+ def clear(self):
95
+ self._size = 0
96
+ self.od.clear()
97
+
98
+ def popitem(self, last=True):
99
+ k, v = self.od.popitem(last=last)
100
+ self._size -= self._get_value_size(v)
101
+
102
+ return k, v
103
+
104
+ def pop(self, key):
105
+ v = self.od.pop(key)
106
+ self._size -= self._get_value_size(v)
107
+
108
+ return v
109
+
110
+ def _adjust_size(self, key, value):
111
+ if key in self.od:
112
+ self._size -= self._get_value_size(self.od[key])
113
+
114
+ self._size += self._get_value_size(value)
115
+
116
+ @abc.abstractmethod
117
+ def _get_value_size(self, value):
118
+ raise NotImplementedError
119
+
120
+
121
+ class MemCacheLengthUnit(MemCacheUnit):
122
+ def __init__(self, size_limit=0):
123
+ super().__init__(size_limit=size_limit)
124
+
125
+ def _get_value_size(self, value):
126
+ return 1
127
+
128
+
129
+ class MemCacheSizeofUnit(MemCacheUnit):
130
+ def __init__(self, size_limit=0):
131
+ super().__init__(size_limit=size_limit)
132
+
133
+ def _get_value_size(self, value):
134
+ return sys.getsizeof(value)
135
+
136
+
137
+ class MemCache:
138
+ """Memory cache."""
139
+
140
+ def __init__(self, mem_cache_size_limit=None, limit_type="length"):
141
+ """
142
+
143
+ Parameters
144
+ ----------
145
+ mem_cache_size_limit:
146
+ cache max size.
147
+ limit_type:
148
+ length or sizeof; length(call fun: len), size(call fun: sys.getsizeof).
149
+ """
150
+
151
+ size_limit = C.mem_cache_size_limit if mem_cache_size_limit is None else mem_cache_size_limit
152
+ limit_type = C.mem_cache_limit_type if limit_type is None else limit_type
153
+
154
+ if limit_type == "length":
155
+ klass = MemCacheLengthUnit
156
+ elif limit_type == "sizeof":
157
+ klass = MemCacheSizeofUnit
158
+ else:
159
+ raise ValueError(f"limit_type must be length or sizeof, your limit_type is {limit_type}")
160
+
161
+ self.__calendar_mem_cache = klass(size_limit)
162
+ self.__instrument_mem_cache = klass(size_limit)
163
+ self.__feature_mem_cache = klass(size_limit)
164
+
165
+ def __getitem__(self, key):
166
+ if key == "c":
167
+ return self.__calendar_mem_cache
168
+ elif key == "i":
169
+ return self.__instrument_mem_cache
170
+ elif key == "f":
171
+ return self.__feature_mem_cache
172
+ else:
173
+ raise KeyError("Unknown memcache unit")
174
+
175
+ def clear(self):
176
+ self.__calendar_mem_cache.clear()
177
+ self.__instrument_mem_cache.clear()
178
+ self.__feature_mem_cache.clear()
179
+
180
+
181
+ class MemCacheExpire:
182
+ CACHE_EXPIRE = C.mem_cache_expire
183
+
184
+ @staticmethod
185
+ def set_cache(mem_cache, key, value):
186
+ """set cache
187
+
188
+ :param mem_cache: MemCache attribute('c'/'i'/'f').
189
+ :param key: cache key.
190
+ :param value: cache value.
191
+ """
192
+ mem_cache[key] = value, time.time()
193
+
194
+ @staticmethod
195
+ def get_cache(mem_cache, key):
196
+ """get mem cache
197
+
198
+ :param mem_cache: MemCache attribute('c'/'i'/'f').
199
+ :param key: cache key.
200
+ :return: cache value; if cache not exist, return None.
201
+ """
202
+ value = None
203
+ expire = False
204
+ if key in mem_cache:
205
+ value, latest_time = mem_cache[key]
206
+ expire = (time.time() - latest_time) > MemCacheExpire.CACHE_EXPIRE
207
+ return value, expire
208
+
209
+
210
+ class CacheUtils:
211
+ LOCK_ID = "QLIB"
212
+
213
+ @staticmethod
214
+ def organize_meta_file():
215
+ pass
216
+
217
+ @staticmethod
218
+ def reset_lock():
219
+ r = get_redis_connection()
220
+ redis_lock.reset_all(r)
221
+
222
+ @staticmethod
223
+ def visit(cache_path: Union[str, Path]):
224
+ # FIXME: Because read_lock was canceled when reading the cache, multiple processes may have read and write exceptions here
225
+ try:
226
+ cache_path = Path(cache_path)
227
+ meta_path = cache_path.with_suffix(".meta")
228
+ with meta_path.open("rb") as f:
229
+ d = restricted_pickle_load(f)
230
+ with meta_path.open("wb") as f:
231
+ try:
232
+ d["meta"]["last_visit"] = str(time.time())
233
+ d["meta"]["visits"] = d["meta"]["visits"] + 1
234
+ except KeyError as key_e:
235
+ raise KeyError("Unknown meta keyword") from key_e
236
+ pickle.dump(d, f, protocol=C.dump_protocol_version)
237
+ except Exception as e:
238
+ get_module_logger("CacheUtils").warning(f"visit {cache_path} cache error: {e}")
239
+
240
+ @staticmethod
241
+ def acquire(lock, lock_name):
242
+ try:
243
+ lock.acquire()
244
+ except redis_lock.AlreadyAcquired as lock_acquired:
245
+ raise QlibCacheException(
246
+ f"""It sees the key(lock:{repr(lock_name)[1:-1]}-wlock) of the redis lock has existed in your redis db now.
247
+ You can use the following command to clear your redis keys and rerun your commands:
248
+ $ redis-cli
249
+ > select {C.redis_task_db}
250
+ > del "lock:{repr(lock_name)[1:-1]}-wlock"
251
+ > quit
252
+ If the issue is not resolved, use "keys *" to find if multiple keys exist. If so, try using "flushall" to clear all the keys.
253
+ """
254
+ ) from lock_acquired
255
+
256
+ @staticmethod
257
+ @contextlib.contextmanager
258
+ def reader_lock(redis_t, lock_name: str):
259
+ current_cache_rlock = redis_lock.Lock(redis_t, f"{lock_name}-rlock")
260
+ current_cache_wlock = redis_lock.Lock(redis_t, f"{lock_name}-wlock")
261
+ lock_reader = f"{lock_name}-reader"
262
+ # make sure only one reader is entering
263
+ current_cache_rlock.acquire(timeout=60)
264
+ try:
265
+ current_cache_readers = redis_t.get(lock_reader)
266
+ if current_cache_readers is None or int(current_cache_readers) == 0:
267
+ CacheUtils.acquire(current_cache_wlock, lock_name)
268
+ redis_t.incr(lock_reader)
269
+ finally:
270
+ current_cache_rlock.release()
271
+ try:
272
+ yield
273
+ finally:
274
+ # make sure only one reader is leaving
275
+ current_cache_rlock.acquire(timeout=60)
276
+ try:
277
+ redis_t.decr(lock_reader)
278
+ if int(redis_t.get(lock_reader)) == 0:
279
+ redis_t.delete(lock_reader)
280
+ current_cache_wlock.reset()
281
+ finally:
282
+ current_cache_rlock.release()
283
+
284
+ @staticmethod
285
+ @contextlib.contextmanager
286
+ def writer_lock(redis_t, lock_name):
287
+ current_cache_wlock = redis_lock.Lock(redis_t, f"{lock_name}-wlock", id=CacheUtils.LOCK_ID)
288
+ CacheUtils.acquire(current_cache_wlock, lock_name)
289
+ try:
290
+ yield
291
+ finally:
292
+ current_cache_wlock.release()
293
+
294
+
295
+ class BaseProviderCache:
296
+ """Provider cache base class"""
297
+
298
+ def __init__(self, provider):
299
+ self.provider = provider
300
+ self.logger = get_module_logger(self.__class__.__name__)
301
+
302
+ def __getattr__(self, attr):
303
+ return getattr(self.provider, attr)
304
+
305
+ @staticmethod
306
+ def check_cache_exists(cache_path: Union[str, Path], suffix_list: Iterable = (".index", ".meta")) -> bool:
307
+ cache_path = Path(cache_path)
308
+ for p in [cache_path] + [cache_path.with_suffix(_s) for _s in suffix_list]:
309
+ if not p.exists():
310
+ return False
311
+ return True
312
+
313
+ @staticmethod
314
+ def clear_cache(cache_path: Union[str, Path]):
315
+ for p in [
316
+ cache_path,
317
+ cache_path.with_suffix(".meta"),
318
+ cache_path.with_suffix(".index"),
319
+ ]:
320
+ if p.exists():
321
+ p.unlink()
322
+
323
+ @staticmethod
324
+ def get_cache_dir(dir_name: str, freq: str = None) -> Path:
325
+ cache_dir = Path(C.dpm.get_data_uri(freq)).joinpath(dir_name)
326
+ cache_dir.mkdir(parents=True, exist_ok=True)
327
+ return cache_dir
328
+
329
+
330
+ class ExpressionCache(BaseProviderCache):
331
+ """Expression cache mechanism base class.
332
+
333
+ This class is used to wrap expression provider with self-defined expression cache mechanism.
334
+
335
+ .. note:: Override the `_uri` and `_expression` method to create your own expression cache mechanism.
336
+ """
337
+
338
+ def expression(self, instrument, field, start_time, end_time, freq):
339
+ """Get expression data.
340
+
341
+ .. note:: Same interface as `expression` method in expression provider
342
+ """
343
+ try:
344
+ return self._expression(instrument, field, start_time, end_time, freq)
345
+ except NotImplementedError:
346
+ return self.provider.expression(instrument, field, start_time, end_time, freq)
347
+
348
+ def _uri(self, instrument, field, start_time, end_time, freq):
349
+ """Get expression cache file uri.
350
+
351
+ Override this method to define how to get expression cache file uri corresponding to users' own cache mechanism.
352
+ """
353
+ raise NotImplementedError("Implement this function to match your own cache mechanism")
354
+
355
+ def _expression(self, instrument, field, start_time, end_time, freq):
356
+ """Get expression data using cache.
357
+
358
+ Override this method to define how to get expression data corresponding to users' own cache mechanism.
359
+ """
360
+ raise NotImplementedError("Implement this method if you want to use expression cache")
361
+
362
+ def update(self, cache_uri: Union[str, Path], freq: str = "day"):
363
+ """Update expression cache to latest calendar.
364
+
365
+ Override this method to define how to update expression cache corresponding to users' own cache mechanism.
366
+
367
+ Parameters
368
+ ----------
369
+ cache_uri : str or Path
370
+ the complete uri of expression cache file (include dir path).
371
+ freq : str
372
+
373
+ Returns
374
+ -------
375
+ int
376
+ 0(successful update)/ 1(no need to update)/ 2(update failure).
377
+ """
378
+ raise NotImplementedError("Implement this method if you want to make expression cache up to date")
379
+
380
+
381
+ class DatasetCache(BaseProviderCache):
382
+ """Dataset cache mechanism base class.
383
+
384
+ This class is used to wrap dataset provider with self-defined dataset cache mechanism.
385
+
386
+ .. note:: Override the `_uri` and `_dataset` method to create your own dataset cache mechanism.
387
+ """
388
+
389
+ HDF_KEY = "df"
390
+
391
+ def dataset(
392
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
393
+ ):
394
+ """Get feature dataset.
395
+
396
+ .. note:: Same interface as `dataset` method in dataset provider
397
+
398
+ .. note:: The server use redis_lock to make sure
399
+ read-write conflicts will not be triggered
400
+ but client readers are not considered.
401
+ """
402
+ if disk_cache == 0:
403
+ # skip cache
404
+ return self.provider.dataset(
405
+ instruments, fields, start_time, end_time, freq, inst_processors=inst_processors
406
+ )
407
+ else:
408
+ # use and replace cache
409
+ try:
410
+ return self._dataset(
411
+ instruments, fields, start_time, end_time, freq, disk_cache, inst_processors=inst_processors
412
+ )
413
+ except NotImplementedError:
414
+ return self.provider.dataset(
415
+ instruments, fields, start_time, end_time, freq, inst_processors=inst_processors
416
+ )
417
+
418
+ def _uri(self, instruments, fields, start_time, end_time, freq, **kwargs):
419
+ """Get dataset cache file uri.
420
+
421
+ Override this method to define how to get dataset cache file uri corresponding to users' own cache mechanism.
422
+ """
423
+ raise NotImplementedError("Implement this function to match your own cache mechanism")
424
+
425
+ def _dataset(
426
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
427
+ ):
428
+ """Get feature dataset using cache.
429
+
430
+ Override this method to define how to get feature dataset corresponding to users' own cache mechanism.
431
+ """
432
+ raise NotImplementedError("Implement this method if you want to use dataset feature cache")
433
+
434
+ def _dataset_uri(
435
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
436
+ ):
437
+ """Get a uri of feature dataset using cache.
438
+ specially:
439
+ disk_cache=1 means using data set cache and return the uri of cache file.
440
+ disk_cache=0 means client knows the path of expression cache,
441
+ server checks if the cache exists(if not, generate it), and client loads data by itself.
442
+ Override this method to define how to get feature dataset uri corresponding to users' own cache mechanism.
443
+ """
444
+ raise NotImplementedError(
445
+ "Implement this method if you want to use dataset feature cache as a cache file for client"
446
+ )
447
+
448
+ def update(self, cache_uri: Union[str, Path], freq: str = "day"):
449
+ """Update dataset cache to latest calendar.
450
+
451
+ Override this method to define how to update dataset cache corresponding to users' own cache mechanism.
452
+
453
+ Parameters
454
+ ----------
455
+ cache_uri : str or Path
456
+ the complete uri of dataset cache file (include dir path).
457
+ freq : str
458
+
459
+ Returns
460
+ -------
461
+ int
462
+ 0(successful update)/ 1(no need to update)/ 2(update failure)
463
+ """
464
+ raise NotImplementedError("Implement this method if you want to make expression cache up to date")
465
+
466
+ @staticmethod
467
+ def cache_to_origin_data(data, fields):
468
+ """cache data to origin data
469
+
470
+ :param data: pd.DataFrame, cache data.
471
+ :param fields: feature fields.
472
+ :return: pd.DataFrame.
473
+ """
474
+ not_space_fields = remove_fields_space(fields)
475
+ data = data.loc[:, not_space_fields]
476
+ # set features fields
477
+ data.columns = [str(i) for i in fields]
478
+ return data
479
+
480
+ @staticmethod
481
+ def normalize_uri_args(instruments, fields, freq):
482
+ """normalize uri args"""
483
+ instruments = normalize_cache_instruments(instruments)
484
+ fields = normalize_cache_fields(fields)
485
+ freq = freq.lower()
486
+
487
+ return instruments, fields, freq
488
+
489
+
490
+ class DiskExpressionCache(ExpressionCache):
491
+ """Prepared cache mechanism for server."""
492
+
493
+ def __init__(self, provider, **kwargs):
494
+ super(DiskExpressionCache, self).__init__(provider)
495
+ self.r = get_redis_connection()
496
+ # remote==True means client is using this module, writing behaviour will not be allowed.
497
+ self.remote = kwargs.get("remote", False)
498
+
499
+ def get_cache_dir(self, freq: str = None) -> Path:
500
+ return super(DiskExpressionCache, self).get_cache_dir(C.features_cache_dir_name, freq)
501
+
502
+ def _uri(self, instrument, field, start_time, end_time, freq):
503
+ field = remove_fields_space(field)
504
+ instrument = str(instrument).lower()
505
+ return hash_args(instrument, field, freq)
506
+
507
+ def _expression(self, instrument, field, start_time=None, end_time=None, freq="day"):
508
+ _cache_uri = self._uri(instrument=instrument, field=field, start_time=None, end_time=None, freq=freq)
509
+ _instrument_dir = self.get_cache_dir(freq).joinpath(instrument.lower())
510
+ cache_path = _instrument_dir.joinpath(_cache_uri)
511
+ # get calendar
512
+ from .data import Cal # pylint: disable=C0415
513
+
514
+ _calendar = Cal.calendar(freq=freq)
515
+
516
+ _, _, start_index, end_index = Cal.locate_index(start_time, end_time, freq, future=False)
517
+
518
+ if self.check_cache_exists(cache_path, suffix_list=[".meta"]):
519
+ """
520
+ In most cases, we do not need reader_lock.
521
+ Because updating data is a small probability event compare to reading data.
522
+
523
+ """
524
+ # FIXME: Removing the reader lock may result in conflicts.
525
+ # with CacheUtils.reader_lock(self.r, 'expression-%s' % _cache_uri):
526
+
527
+ # modify expression cache meta file
528
+ try:
529
+ # FIXME: Multiple readers may result in error visit number
530
+ if not self.remote:
531
+ CacheUtils.visit(cache_path)
532
+ series = read_bin(cache_path, start_index, end_index)
533
+ return series
534
+ except Exception:
535
+ series = None
536
+ self.logger.error("reading %s file error : %s" % (cache_path, traceback.format_exc()))
537
+ return series
538
+ else:
539
+ # normalize field
540
+ field = remove_fields_space(field)
541
+ # cache unavailable, generate the cache
542
+ _instrument_dir.mkdir(parents=True, exist_ok=True)
543
+ if not isinstance(eval(parse_field(field)), Feature):
544
+ # When the expression is not a raw feature
545
+ # generate expression cache if the feature is not a Feature
546
+ # instance
547
+ series = self.provider.expression(instrument, field, _calendar[0], _calendar[-1], freq)
548
+ if not series.empty:
549
+ # This expression is empty, we don't generate any cache for it.
550
+ with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:expression-{_cache_uri}"):
551
+ self.gen_expression_cache(
552
+ expression_data=series,
553
+ cache_path=cache_path,
554
+ instrument=instrument,
555
+ field=field,
556
+ freq=freq,
557
+ last_update=str(_calendar[-1]),
558
+ )
559
+ return series.loc[start_index:end_index]
560
+ else:
561
+ return series
562
+ else:
563
+ # If the expression is a raw feature(such as $close, $open)
564
+ return self.provider.expression(instrument, field, start_time, end_time, freq)
565
+
566
+ def gen_expression_cache(self, expression_data, cache_path, instrument, field, freq, last_update):
567
+ """use bin file to save like feature-data."""
568
+ # Make sure the cache runs right when the directory is deleted
569
+ # while running
570
+ meta = {
571
+ "info": {"instrument": instrument, "field": field, "freq": freq, "last_update": last_update},
572
+ "meta": {"last_visit": time.time(), "visits": 1},
573
+ }
574
+ self.logger.debug(f"generating expression cache: {meta}")
575
+ self.clear_cache(cache_path)
576
+ meta_path = cache_path.with_suffix(".meta")
577
+
578
+ with meta_path.open("wb") as f:
579
+ pickle.dump(meta, f, protocol=C.dump_protocol_version)
580
+ meta_path.chmod(stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
581
+ df = expression_data.to_frame()
582
+
583
+ r = np.hstack([df.index[0], expression_data]).astype("<f")
584
+ r.tofile(str(cache_path))
585
+
586
+ def update(self, sid, cache_uri, freq: str = "day"):
587
+ cp_cache_uri = self.get_cache_dir(freq).joinpath(sid).joinpath(cache_uri)
588
+ meta_path = cp_cache_uri.with_suffix(".meta")
589
+ if not self.check_cache_exists(cp_cache_uri, suffix_list=[".meta"]):
590
+ self.logger.info(f"The cache {cp_cache_uri} has corrupted. It will be removed")
591
+ self.clear_cache(cp_cache_uri)
592
+ return 2
593
+
594
+ with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri())}:expression-{cache_uri}"):
595
+ with meta_path.open("rb") as f:
596
+ d = restricted_pickle_load(f)
597
+ instrument = d["info"]["instrument"]
598
+ field = d["info"]["field"]
599
+ freq = d["info"]["freq"]
600
+ last_update_time = d["info"]["last_update"]
601
+
602
+ # get newest calendar
603
+ from .data import Cal, ExpressionD # pylint: disable=C0415
604
+
605
+ whole_calendar = Cal.calendar(start_time=None, end_time=None, freq=freq)
606
+ # calendar since last updated.
607
+ new_calendar = Cal.calendar(start_time=last_update_time, end_time=None, freq=freq)
608
+
609
+ # get append data
610
+ if len(new_calendar) <= 1:
611
+ # Including last updated calendar, we only get 1 item.
612
+ # No future updating is needed.
613
+ return 1
614
+ else:
615
+ # get the data needed after the historical data are removed.
616
+ # The start index of new data
617
+ current_index = len(whole_calendar) - len(new_calendar) + 1
618
+
619
+ # The existing data length
620
+ size_bytes = os.path.getsize(cp_cache_uri)
621
+ ele_size = np.dtype("<f").itemsize
622
+ assert size_bytes % ele_size == 0
623
+ ele_n = size_bytes // ele_size - 1
624
+
625
+ expr = ExpressionD.get_expression_instance(field)
626
+ lft_etd, rght_etd = expr.get_extended_window_size()
627
+ # The expression used the future data after rght_etd days.
628
+ # So the last rght_etd data should be removed.
629
+ # There are most `ele_n` period of data can be remove
630
+ remove_n = min(rght_etd, ele_n)
631
+ assert new_calendar[1] == whole_calendar[current_index]
632
+ data = self.provider.expression(
633
+ instrument, field, whole_calendar[current_index - remove_n], new_calendar[-1], freq
634
+ )
635
+ with open(cp_cache_uri, "ab") as f:
636
+ data = np.array(data).astype("<f")
637
+ # Remove the last bits
638
+ f.truncate(size_bytes - ele_size * remove_n)
639
+ f.write(data)
640
+ # update meta file
641
+ d["info"]["last_update"] = str(new_calendar[-1])
642
+ with meta_path.open("wb") as f:
643
+ pickle.dump(d, f, protocol=C.dump_protocol_version)
644
+ return 0
645
+
646
+
647
+ class DiskDatasetCache(DatasetCache):
648
+ """Prepared cache mechanism for server."""
649
+
650
+ def __init__(self, provider, **kwargs):
651
+ super(DiskDatasetCache, self).__init__(provider)
652
+ self.r = get_redis_connection()
653
+ self.remote = kwargs.get("remote", False)
654
+
655
+ @staticmethod
656
+ def _uri(instruments, fields, start_time, end_time, freq, disk_cache=1, inst_processors=[], **kwargs):
657
+ return hash_args(*DatasetCache.normalize_uri_args(instruments, fields, freq), disk_cache, inst_processors)
658
+
659
+ def get_cache_dir(self, freq: str = None) -> Path:
660
+ return super(DiskDatasetCache, self).get_cache_dir(C.dataset_cache_dir_name, freq)
661
+
662
+ @classmethod
663
+ def read_data_from_cache(cls, cache_path: Union[str, Path], start_time, end_time, fields):
664
+ """read_cache_from
665
+
666
+ This function can read data from the disk cache dataset
667
+
668
+ :param cache_path:
669
+ :param start_time:
670
+ :param end_time:
671
+ :param fields: The fields order of the dataset cache is sorted. So rearrange the columns to make it consistent.
672
+ :return:
673
+ """
674
+
675
+ im = DiskDatasetCache.IndexManager(cache_path)
676
+ index_data = im.get_index(start_time, end_time)
677
+ if index_data.shape[0] > 0:
678
+ start, stop = (
679
+ index_data["start"].iloc[0].item(),
680
+ index_data["end"].iloc[-1].item(),
681
+ )
682
+ else:
683
+ start = stop = 0
684
+
685
+ with pd.HDFStore(cache_path, mode="r") as store:
686
+ if "/{}".format(im.KEY) in store.keys():
687
+ df = store.select(key=im.KEY, start=start, stop=stop)
688
+ df = df.swaplevel("datetime", "instrument").sort_index()
689
+ # read cache and need to replace not-space fields to field
690
+ df = cls.cache_to_origin_data(df, fields)
691
+
692
+ else:
693
+ df = pd.DataFrame(columns=fields)
694
+ return df
695
+
696
+ def _dataset(
697
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=0, inst_processors=[]
698
+ ):
699
+ if disk_cache == 0:
700
+ # In this case, data_set cache is configured but will not be used.
701
+ return self.provider.dataset(
702
+ instruments, fields, start_time, end_time, freq, inst_processors=inst_processors
703
+ )
704
+ # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date
705
+ if inst_processors:
706
+ raise ValueError(
707
+ f"{self.__class__.__name__} does not support inst_processor. "
708
+ f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`"
709
+ )
710
+ _cache_uri = self._uri(
711
+ instruments=instruments,
712
+ fields=fields,
713
+ start_time=None,
714
+ end_time=None,
715
+ freq=freq,
716
+ disk_cache=disk_cache,
717
+ inst_processors=inst_processors,
718
+ )
719
+
720
+ cache_path = self.get_cache_dir(freq).joinpath(_cache_uri)
721
+
722
+ features = pd.DataFrame()
723
+ gen_flag = False
724
+
725
+ if self.check_cache_exists(cache_path):
726
+ if disk_cache == 1:
727
+ # use cache
728
+ with CacheUtils.reader_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"):
729
+ CacheUtils.visit(cache_path)
730
+ features = self.read_data_from_cache(cache_path, start_time, end_time, fields)
731
+ elif disk_cache == 2:
732
+ gen_flag = True
733
+ else:
734
+ gen_flag = True
735
+
736
+ if gen_flag:
737
+ # cache unavailable, generate the cache
738
+ with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"):
739
+ features = self.gen_dataset_cache(
740
+ cache_path=cache_path,
741
+ instruments=instruments,
742
+ fields=fields,
743
+ freq=freq,
744
+ inst_processors=inst_processors,
745
+ )
746
+ if not features.empty:
747
+ features = features.sort_index().loc(axis=0)[:, start_time:end_time]
748
+ return features
749
+
750
+ def _dataset_uri(
751
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=0, inst_processors=[]
752
+ ):
753
+ if disk_cache == 0:
754
+ # In this case, server only checks the expression cache.
755
+ # The client will load the cache data by itself.
756
+ from .data import LocalDatasetProvider # pylint: disable=C0415
757
+
758
+ LocalDatasetProvider.multi_cache_walker(instruments, fields, start_time, end_time, freq)
759
+ return ""
760
+ # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date
761
+ if inst_processors:
762
+ raise ValueError(
763
+ f"{self.__class__.__name__} does not support inst_processor. "
764
+ f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`"
765
+ )
766
+ _cache_uri = self._uri(
767
+ instruments=instruments,
768
+ fields=fields,
769
+ start_time=None,
770
+ end_time=None,
771
+ freq=freq,
772
+ disk_cache=disk_cache,
773
+ inst_processors=inst_processors,
774
+ )
775
+ cache_path = self.get_cache_dir(freq).joinpath(_cache_uri)
776
+
777
+ if self.check_cache_exists(cache_path):
778
+ self.logger.debug(f"The cache dataset has already existed {cache_path}. Return the uri directly")
779
+ with CacheUtils.reader_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"):
780
+ CacheUtils.visit(cache_path)
781
+ return _cache_uri
782
+ else:
783
+ # cache unavailable, generate the cache
784
+ with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"):
785
+ self.gen_dataset_cache(
786
+ cache_path=cache_path,
787
+ instruments=instruments,
788
+ fields=fields,
789
+ freq=freq,
790
+ inst_processors=inst_processors,
791
+ )
792
+ return _cache_uri
793
+
794
+ class IndexManager:
795
+ """
796
+ The lock is not considered in the class. Please consider the lock outside the code.
797
+ This class is the proxy of the disk data.
798
+ """
799
+
800
+ KEY = "df"
801
+
802
+ def __init__(self, cache_path: Union[str, Path]):
803
+ self.index_path = cache_path.with_suffix(".index")
804
+ self._data = None
805
+ self.logger = get_module_logger(self.__class__.__name__)
806
+
807
+ def get_index(self, start_time=None, end_time=None):
808
+ # TODO: fast read index from the disk.
809
+ if self._data is None:
810
+ self.sync_from_disk()
811
+ return self._data.loc[start_time:end_time].copy()
812
+
813
+ def sync_to_disk(self):
814
+ if self._data is None:
815
+ raise ValueError("No data to sync to disk.")
816
+ self._data.sort_index(inplace=True)
817
+ self._data.to_hdf(self.index_path, key=self.KEY, mode="w", format="table")
818
+ # The index should be readable for all users
819
+ self.index_path.chmod(stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
820
+
821
+ def sync_from_disk(self):
822
+ # The file will not be closed directly if we read_hdf from the disk directly
823
+ with pd.HDFStore(self.index_path, mode="r") as store:
824
+ if "/{}".format(self.KEY) in store.keys():
825
+ self._data = pd.read_hdf(store, key=self.KEY)
826
+ else:
827
+ self._data = pd.DataFrame()
828
+
829
+ def update(self, data, sync=True):
830
+ self._data = data.astype(np.int32).copy()
831
+ if sync:
832
+ self.sync_to_disk()
833
+
834
+ def append_index(self, data, to_disk=True):
835
+ data = data.astype(np.int32).copy()
836
+ data.sort_index(inplace=True)
837
+ self._data = pd.concat([self._data, data])
838
+ if to_disk:
839
+ with pd.HDFStore(self.index_path) as store:
840
+ store.append(self.KEY, data, append=True)
841
+
842
+ @staticmethod
843
+ def build_index_from_data(data, start_index=0):
844
+ if data.empty:
845
+ return pd.DataFrame()
846
+ line_data = data.groupby("datetime", group_keys=False).size()
847
+ line_data.sort_index(inplace=True)
848
+ index_end = line_data.cumsum()
849
+ index_start = index_end.shift(1, fill_value=0)
850
+
851
+ index_data = pd.DataFrame()
852
+ index_data["start"] = index_start
853
+ index_data["end"] = index_end
854
+ index_data += start_index
855
+ return index_data
856
+
857
+ def gen_dataset_cache(self, cache_path: Union[str, Path], instruments, fields, freq, inst_processors=[]):
858
+ """gen_dataset_cache
859
+
860
+ .. note:: This function does not consider the cache read write lock. Please
861
+ acquire the lock outside this function
862
+
863
+ The format the cache contains 3 parts(followed by typical filename).
864
+
865
+ - index : cache/d41366901e25de3ec47297f12e2ba11d.index
866
+
867
+ - The content of the file may be in following format(pandas.Series)
868
+
869
+ .. code-block:: python
870
+
871
+ start end
872
+ 1999-11-10 00:00:00 0 1
873
+ 1999-11-11 00:00:00 1 2
874
+ 1999-11-12 00:00:00 2 3
875
+ ...
876
+
877
+ .. note:: The start is closed. The end is open!!!!!
878
+
879
+ - Each line contains two element <start_index, end_index> with a timestamp as its index.
880
+ - It indicates the `start_index` (included) and `end_index` (excluded) of the data for `timestamp`
881
+
882
+ - meta data: cache/d41366901e25de3ec47297f12e2ba11d.meta
883
+
884
+ - data : cache/d41366901e25de3ec47297f12e2ba11d
885
+
886
+ - This is a hdf file sorted by datetime
887
+
888
+ :param cache_path: The path to store the cache.
889
+ :param instruments: The instruments to store the cache.
890
+ :param fields: The fields to store the cache.
891
+ :param freq: The freq to store the cache.
892
+ :param inst_processors: Instrument processors.
893
+
894
+ :return type pd.DataFrame; The fields of the returned DataFrame are consistent with the parameters of the function.
895
+ """
896
+ # get calendar
897
+ from .data import Cal # pylint: disable=C0415
898
+
899
+ cache_path = Path(cache_path)
900
+ _calendar = Cal.calendar(freq=freq)
901
+ self.logger.debug(f"Generating dataset cache {cache_path}")
902
+ # Make sure the cache runs right when the directory is deleted
903
+ # while running
904
+ self.clear_cache(cache_path)
905
+
906
+ features = self.provider.dataset(
907
+ instruments, fields, _calendar[0], _calendar[-1], freq, inst_processors=inst_processors
908
+ )
909
+
910
+ if features.empty:
911
+ return features
912
+
913
+ # swap index and sorted
914
+ features = features.swaplevel("instrument", "datetime").sort_index()
915
+
916
+ # write cache data
917
+ with pd.HDFStore(str(cache_path.with_suffix(".data"))) as store:
918
+ cache_to_orig_map = dict(zip(remove_fields_space(features.columns), features.columns))
919
+ orig_to_cache_map = dict(zip(features.columns, remove_fields_space(features.columns)))
920
+ cache_features = features[list(cache_to_orig_map.values())].rename(columns=orig_to_cache_map)
921
+ # cache columns
922
+ cache_columns = sorted(cache_features.columns)
923
+ cache_features = cache_features.loc[:, cache_columns]
924
+ cache_features = cache_features.loc[:, ~cache_features.columns.duplicated()]
925
+ store.append(DatasetCache.HDF_KEY, cache_features, append=False)
926
+ # write meta file
927
+ meta = {
928
+ "info": {
929
+ "instruments": instruments,
930
+ "fields": list(cache_features.columns),
931
+ "freq": freq,
932
+ "last_update": str(_calendar[-1]), # The last_update to store the cache
933
+ "inst_processors": inst_processors, # The last_update to store the cache
934
+ },
935
+ "meta": {"last_visit": time.time(), "visits": 1},
936
+ }
937
+ with cache_path.with_suffix(".meta").open("wb") as f:
938
+ pickle.dump(meta, f, protocol=C.dump_protocol_version)
939
+ cache_path.with_suffix(".meta").chmod(stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)
940
+ # write index file
941
+ im = DiskDatasetCache.IndexManager(cache_path)
942
+ index_data = im.build_index_from_data(features)
943
+ im.update(index_data)
944
+
945
+ # rename the file after the cache has been generated
946
+ # this doesn't work well on windows, but our server won't use windows
947
+ # temporarily
948
+ cache_path.with_suffix(".data").rename(cache_path)
949
+ # the fields of the cached features are converted to the original fields
950
+ return features.swaplevel("datetime", "instrument")
951
+
952
+ def update(self, cache_uri, freq: str = "day"):
953
+ cp_cache_uri = self.get_cache_dir(freq).joinpath(cache_uri)
954
+ meta_path = cp_cache_uri.with_suffix(".meta")
955
+ if not self.check_cache_exists(cp_cache_uri):
956
+ self.logger.info(f"The cache {cp_cache_uri} has corrupted. It will be removed")
957
+ self.clear_cache(cp_cache_uri)
958
+ return 2
959
+
960
+ im = DiskDatasetCache.IndexManager(cp_cache_uri)
961
+ with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri())}:dataset-{cache_uri}"):
962
+ with meta_path.open("rb") as f:
963
+ d = restricted_pickle_load(f)
964
+ instruments = d["info"]["instruments"]
965
+ fields = d["info"]["fields"]
966
+ freq = d["info"]["freq"]
967
+ last_update_time = d["info"]["last_update"]
968
+ inst_processors = d["info"].get("inst_processors", [])
969
+ index_data = im.get_index()
970
+
971
+ self.logger.debug("Updating dataset: {}".format(d))
972
+ from .data import Inst # pylint: disable=C0415
973
+
974
+ if Inst.get_inst_type(instruments) == Inst.DICT:
975
+ self.logger.info(f"The file {cache_uri} has dict cache. Skip updating")
976
+ return 1
977
+
978
+ # get newest calendar
979
+ from .data import Cal # pylint: disable=C0415
980
+
981
+ whole_calendar = Cal.calendar(start_time=None, end_time=None, freq=freq)
982
+ # The calendar since last updated
983
+ new_calendar = Cal.calendar(start_time=last_update_time, end_time=None, freq=freq)
984
+
985
+ # get append data
986
+ if len(new_calendar) <= 1:
987
+ # Including last updated calendar, we only get 1 item.
988
+ # No future updating is needed.
989
+ return 1
990
+ else:
991
+ # get the data needed after the historical data are removed.
992
+ # The start index of new data
993
+ current_index = len(whole_calendar) - len(new_calendar) + 1
994
+
995
+ # To avoid recursive import
996
+ from .data import ExpressionD # pylint: disable=C0415
997
+
998
+ # The existing data length
999
+ lft_etd = rght_etd = 0
1000
+ for field in fields:
1001
+ expr = ExpressionD.get_expression_instance(field)
1002
+ l, r = expr.get_extended_window_size()
1003
+ lft_etd = max(lft_etd, l)
1004
+ rght_etd = max(rght_etd, r)
1005
+ # remove the period that should be updated.
1006
+ if index_data.empty:
1007
+ # We don't have any data for such dataset. Nothing to remove
1008
+ rm_n_period = rm_lines = 0
1009
+ else:
1010
+ rm_n_period = min(rght_etd, index_data.shape[0])
1011
+ rm_lines = (
1012
+ (index_data["end"] - index_data["start"])
1013
+ .loc[whole_calendar[current_index - rm_n_period] :]
1014
+ .sum()
1015
+ .item()
1016
+ )
1017
+
1018
+ data = self.provider.dataset(
1019
+ instruments,
1020
+ fields,
1021
+ whole_calendar[current_index - rm_n_period],
1022
+ new_calendar[-1],
1023
+ freq,
1024
+ inst_processors=inst_processors,
1025
+ )
1026
+
1027
+ if not data.empty:
1028
+ data.reset_index(inplace=True)
1029
+ data.set_index(["datetime", "instrument"], inplace=True)
1030
+ data.sort_index(inplace=True)
1031
+ else:
1032
+ return 0 # No data to update cache
1033
+
1034
+ store = pd.HDFStore(cp_cache_uri)
1035
+ # FIXME:
1036
+ # Because the feature cache are stored as .bin file.
1037
+ # So the series read from features are all float32.
1038
+ # However, the first dataset cache is calculated based on the
1039
+ # raw data. So the data type may be float64.
1040
+ # Different data type will result in failure of appending data
1041
+ if "/{}".format(DatasetCache.HDF_KEY) in store.keys():
1042
+ schema = store.select(DatasetCache.HDF_KEY, start=0, stop=0)
1043
+ for col, dtype in schema.dtypes.items():
1044
+ data[col] = data[col].astype(dtype)
1045
+ if rm_lines > 0:
1046
+ store.remove(key=im.KEY, start=-rm_lines)
1047
+ store.append(DatasetCache.HDF_KEY, data)
1048
+ store.close()
1049
+
1050
+ # update index file
1051
+ new_index_data = im.build_index_from_data(
1052
+ data.loc(axis=0)[whole_calendar[current_index] :, :],
1053
+ start_index=0 if index_data.empty else index_data["end"].iloc[-1],
1054
+ )
1055
+ im.append_index(new_index_data)
1056
+
1057
+ # update meta file
1058
+ d["info"]["last_update"] = str(new_calendar[-1])
1059
+ with meta_path.open("wb") as f:
1060
+ pickle.dump(d, f, protocol=C.dump_protocol_version)
1061
+ return 0
1062
+
1063
+
1064
+ class SimpleDatasetCache(DatasetCache):
1065
+ """Simple dataset cache that can be used locally or on client."""
1066
+
1067
+ def __init__(self, provider):
1068
+ super(SimpleDatasetCache, self).__init__(provider)
1069
+ try:
1070
+ self.local_cache_path: Path = Path(C["local_cache_path"]).expanduser().resolve()
1071
+ except (KeyError, TypeError):
1072
+ self.logger.error("Assign a local_cache_path in config if you want to use this cache mechanism")
1073
+ raise
1074
+ self.logger.info(
1075
+ f"DatasetCache directory: {self.local_cache_path}, "
1076
+ f"modify the cache directory via the local_cache_path in the config"
1077
+ )
1078
+
1079
+ def _uri(self, instruments, fields, start_time, end_time, freq, disk_cache=1, inst_processors=[], **kwargs):
1080
+ instruments, fields, freq = self.normalize_uri_args(instruments, fields, freq)
1081
+ return hash_args(
1082
+ instruments, fields, start_time, end_time, freq, disk_cache, str(self.local_cache_path), inst_processors
1083
+ )
1084
+
1085
+ def _dataset(
1086
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
1087
+ ):
1088
+ if disk_cache == 0:
1089
+ # In this case, data_set cache is configured but will not be used.
1090
+ return self.provider.dataset(instruments, fields, start_time, end_time, freq)
1091
+ self.local_cache_path.mkdir(exist_ok=True, parents=True)
1092
+ cache_file = self.local_cache_path.joinpath(
1093
+ self._uri(
1094
+ instruments, fields, start_time, end_time, freq, disk_cache=disk_cache, inst_processors=inst_processors
1095
+ )
1096
+ )
1097
+ gen_flag = False
1098
+
1099
+ if cache_file.exists():
1100
+ if disk_cache == 1:
1101
+ # use cache
1102
+ df = pd.read_pickle(cache_file)
1103
+ return self.cache_to_origin_data(df, fields)
1104
+ elif disk_cache == 2:
1105
+ # replace cache
1106
+ gen_flag = True
1107
+ else:
1108
+ gen_flag = True
1109
+
1110
+ if gen_flag:
1111
+ data = self.provider.dataset(
1112
+ instruments, normalize_cache_fields(fields), start_time, end_time, freq, inst_processors=inst_processors
1113
+ )
1114
+ data.to_pickle(cache_file)
1115
+ return self.cache_to_origin_data(data, fields)
1116
+
1117
+
1118
+ class DatasetURICache(DatasetCache):
1119
+ """Prepared cache mechanism for server."""
1120
+
1121
+ def _uri(self, instruments, fields, start_time, end_time, freq, disk_cache=1, inst_processors=[], **kwargs):
1122
+ return hash_args(*self.normalize_uri_args(instruments, fields, freq), disk_cache, inst_processors)
1123
+
1124
+ def dataset(
1125
+ self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=0, inst_processors=[]
1126
+ ):
1127
+ if "local" in C.dataset_provider.lower():
1128
+ # use LocalDatasetProvider
1129
+ return self.provider.dataset(
1130
+ instruments, fields, start_time, end_time, freq, inst_processors=inst_processors
1131
+ )
1132
+
1133
+ if disk_cache == 0:
1134
+ # do not use data_set cache, load data from remote expression cache directly
1135
+ return self.provider.dataset(
1136
+ instruments,
1137
+ fields,
1138
+ start_time,
1139
+ end_time,
1140
+ freq,
1141
+ disk_cache,
1142
+ return_uri=False,
1143
+ inst_processors=inst_processors,
1144
+ )
1145
+ # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date
1146
+ if inst_processors:
1147
+ raise ValueError(
1148
+ f"{self.__class__.__name__} does not support inst_processor. "
1149
+ f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`"
1150
+ )
1151
+ # use ClientDatasetProvider
1152
+ feature_uri = self._uri(
1153
+ instruments, fields, None, None, freq, disk_cache=disk_cache, inst_processors=inst_processors
1154
+ )
1155
+ value, expire = MemCacheExpire.get_cache(H["f"], feature_uri)
1156
+ mnt_feature_uri = C.dpm.get_data_uri(freq).joinpath(C.dataset_cache_dir_name).joinpath(feature_uri)
1157
+ if value is None or expire or not mnt_feature_uri.exists():
1158
+ df, uri = self.provider.dataset(
1159
+ instruments,
1160
+ fields,
1161
+ start_time,
1162
+ end_time,
1163
+ freq,
1164
+ disk_cache,
1165
+ return_uri=True,
1166
+ inst_processors=inst_processors,
1167
+ )
1168
+ # cache uri
1169
+ MemCacheExpire.set_cache(H["f"], uri, uri)
1170
+ # cache DataFrame
1171
+ # HZ['f'][uri] = df.copy()
1172
+ get_module_logger("cache").debug(f"get feature from {C.dataset_provider}")
1173
+ else:
1174
+ df = DiskDatasetCache.read_data_from_cache(mnt_feature_uri, start_time, end_time, fields)
1175
+ get_module_logger("cache").debug("get feature from uri cache")
1176
+
1177
+ return df
1178
+
1179
+
1180
+ class CalendarCache(BaseProviderCache):
1181
+ pass
1182
+
1183
+
1184
+ class MemoryCalendarCache(CalendarCache):
1185
+ def calendar(self, start_time=None, end_time=None, freq="day", future=False):
1186
+ uri = self._uri(start_time, end_time, freq, future)
1187
+ result, expire = MemCacheExpire.get_cache(H["c"], uri)
1188
+ if result is None or expire:
1189
+ result = self.provider.calendar(start_time, end_time, freq, future)
1190
+ MemCacheExpire.set_cache(H["c"], uri, result)
1191
+
1192
+ get_module_logger("data").debug(f"get calendar from {C.calendar_provider}")
1193
+ else:
1194
+ get_module_logger("data").debug("get calendar from local cache")
1195
+
1196
+ return result
1197
+
1198
+
1199
+ H = MemCache()
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/client.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+
5
+ from __future__ import division, print_function
6
+
7
+ import json
8
+
9
+ import socketio
10
+
11
+ import qlib
12
+
13
+ from ..log import get_module_logger
14
+
15
+
16
+ class Client:
17
+ """A client class
18
+
19
+ Provide the connection tool functions for ClientProvider.
20
+ """
21
+
22
+ def __init__(self, host, port):
23
+ super(Client, self).__init__()
24
+ self.sio = socketio.Client()
25
+ self.server_host = host
26
+ self.server_port = port
27
+ self.logger = get_module_logger(self.__class__.__name__)
28
+ # bind connect/disconnect callbacks
29
+ self.sio.on(
30
+ "connect",
31
+ lambda: self.logger.debug("Connect to server {}".format(self.sio.connection_url)),
32
+ )
33
+ self.sio.on("disconnect", lambda: self.logger.debug("Disconnect from server!"))
34
+
35
+ def connect_server(self):
36
+ """Connect to server."""
37
+ try:
38
+ self.sio.connect(f"ws://{self.server_host}:{self.server_port}")
39
+ except socketio.exceptions.ConnectionError:
40
+ self.logger.error("Cannot connect to server - check your network or server status")
41
+
42
+ def disconnect(self):
43
+ """Disconnect from server."""
44
+ try:
45
+ self.sio.eio.disconnect(True)
46
+ except Exception as e:
47
+ self.logger.error("Cannot disconnect from server : %s" % e)
48
+
49
+ def send_request(self, request_type, request_content, msg_queue, msg_proc_func=None):
50
+ """Send a certain request to server.
51
+
52
+ Parameters
53
+ ----------
54
+ request_type : str
55
+ type of proposed request, 'calendar'/'instrument'/'feature'.
56
+ request_content : dict
57
+ records the information of the request.
58
+ msg_proc_func : func
59
+ the function to process the message when receiving response, should have arg `*args`.
60
+ msg_queue: Queue
61
+ The queue to pass the message after callback.
62
+ """
63
+ head_info = {"version": qlib.__version__}
64
+
65
+ def request_callback(*args):
66
+ """callback_wrapper
67
+
68
+ :param *args: args[0] is the response content
69
+ """
70
+ # args[0] is the response content
71
+ self.logger.debug("receive data and enter queue")
72
+ msg = dict(args[0])
73
+ if msg["detailed_info"] is not None:
74
+ if msg["status"] != 0:
75
+ self.logger.error(msg["detailed_info"])
76
+ else:
77
+ self.logger.info(msg["detailed_info"])
78
+ if msg["status"] != 0:
79
+ ex = ValueError(f"Bad response(status=={msg['status']}), detailed info: {msg['detailed_info']}")
80
+ msg_queue.put(ex)
81
+ else:
82
+ if msg_proc_func is not None:
83
+ try:
84
+ ret = msg_proc_func(msg["result"])
85
+ except Exception as e:
86
+ self.logger.exception("Error when processing message.")
87
+ ret = e
88
+ else:
89
+ ret = msg["result"]
90
+ msg_queue.put(ret)
91
+ self.disconnect()
92
+ self.logger.debug("disconnected")
93
+
94
+ self.logger.debug("try connecting")
95
+ self.connect_server()
96
+ self.logger.debug("connected")
97
+ # The pickle is for passing some parameters with special type(such as
98
+ # pd.Timestamp)
99
+ request_content = {"head": head_info, "body": json.dumps(request_content, default=str)}
100
+ self.sio.on(request_type + "_response", request_callback)
101
+ self.logger.debug("try sending")
102
+ self.sio.emit(request_type + "_request", request_content)
103
+ self.sio.wait()
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/data.py ADDED
@@ -0,0 +1,1332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 re
9
+ import abc
10
+ import copy
11
+ import queue
12
+ import bisect
13
+ import numpy as np
14
+ import pandas as pd
15
+ from typing import List, Union, Optional
16
+
17
+ # For supporting multiprocessing in outer code, joblib is used
18
+ from joblib import delayed
19
+
20
+ from .cache import H
21
+ from ..config import C
22
+ from .inst_processor import InstProcessor
23
+
24
+ from ..log import get_module_logger
25
+ from .cache import DiskDatasetCache
26
+ from ..utils import (
27
+ Wrapper,
28
+ init_instance_by_config,
29
+ register_wrapper,
30
+ get_module_by_module_path,
31
+ parse_field,
32
+ hash_args,
33
+ normalize_cache_fields,
34
+ code_to_fname,
35
+ time_to_slc_point,
36
+ read_period_data,
37
+ get_period_list,
38
+ )
39
+ from ..utils.paral import ParallelExt
40
+ from .ops import Operators # pylint: disable=W0611 # noqa: F401
41
+
42
+
43
+ class ProviderBackendMixin:
44
+ """
45
+ This helper class tries to make the provider based on storage backend more convenient
46
+ It is not necessary to inherent this class if that provider don't rely on the backend storage
47
+ """
48
+
49
+ def get_default_backend(self):
50
+ backend = {}
51
+ provider_name: str = re.findall("[A-Z][^A-Z]*", self.__class__.__name__)[-2]
52
+ # set default storage class
53
+ backend.setdefault("class", f"File{provider_name}Storage")
54
+ # set default storage module
55
+ backend.setdefault("module_path", "qlib.data.storage.file_storage")
56
+ return backend
57
+
58
+ def backend_obj(self, **kwargs):
59
+ backend = self.backend if self.backend else self.get_default_backend()
60
+ backend = copy.deepcopy(backend)
61
+ backend.setdefault("kwargs", {}).update(**kwargs)
62
+ return init_instance_by_config(backend)
63
+
64
+
65
+ class CalendarProvider(abc.ABC):
66
+ """Calendar provider base class
67
+
68
+ Provide calendar data.
69
+ """
70
+
71
+ def calendar(self, start_time=None, end_time=None, freq="day", future=False):
72
+ """Get calendar of certain market in given time range.
73
+
74
+ Parameters
75
+ ----------
76
+ start_time : str
77
+ start of the time range.
78
+ end_time : str
79
+ end of the time range.
80
+ freq : str
81
+ time frequency, available: year/quarter/month/week/day.
82
+ future : bool
83
+ whether including future trading day.
84
+
85
+ Returns
86
+ ----------
87
+ list
88
+ calendar list
89
+ """
90
+ _calendar, _calendar_index = self._get_calendar(freq, future)
91
+ if start_time == "None":
92
+ start_time = None
93
+ if end_time == "None":
94
+ end_time = None
95
+ # strip
96
+ if start_time:
97
+ start_time = pd.Timestamp(start_time)
98
+ if start_time > _calendar[-1]:
99
+ return np.array([])
100
+ else:
101
+ start_time = _calendar[0]
102
+ if end_time:
103
+ end_time = pd.Timestamp(end_time)
104
+ if end_time < _calendar[0]:
105
+ return np.array([])
106
+ else:
107
+ end_time = _calendar[-1]
108
+ _, _, si, ei = self.locate_index(start_time, end_time, freq, future)
109
+ return _calendar[si : ei + 1]
110
+
111
+ def locate_index(
112
+ self, start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], freq: str, future: bool = False
113
+ ):
114
+ """Locate the start time index and end time index in a calendar under certain frequency.
115
+
116
+ Parameters
117
+ ----------
118
+ start_time : pd.Timestamp
119
+ start of the time range.
120
+ end_time : pd.Timestamp
121
+ end of the time range.
122
+ freq : str
123
+ time frequency, available: year/quarter/month/week/day.
124
+ future : bool
125
+ whether including future trading day.
126
+
127
+ Returns
128
+ -------
129
+ pd.Timestamp
130
+ the real start time.
131
+ pd.Timestamp
132
+ the real end time.
133
+ int
134
+ the index of start time.
135
+ int
136
+ the index of end time.
137
+ """
138
+ start_time = pd.Timestamp(start_time)
139
+ end_time = pd.Timestamp(end_time)
140
+ calendar, calendar_index = self._get_calendar(freq=freq, future=future)
141
+ if start_time not in calendar_index:
142
+ try:
143
+ start_time = calendar[bisect.bisect_left(calendar, start_time)]
144
+ except IndexError as index_e:
145
+ raise IndexError(
146
+ "`start_time` uses a future date, if you want to get future trading days, you can use: `future=True`"
147
+ ) from index_e
148
+ start_index = calendar_index[start_time]
149
+ if end_time not in calendar_index:
150
+ end_time = calendar[bisect.bisect_right(calendar, end_time) - 1]
151
+ end_index = calendar_index[end_time]
152
+ return start_time, end_time, start_index, end_index
153
+
154
+ def _get_calendar(self, freq, future):
155
+ """Load calendar using memcache.
156
+
157
+ Parameters
158
+ ----------
159
+ freq : str
160
+ frequency of read calendar file.
161
+ future : bool
162
+ whether including future trading day.
163
+
164
+ Returns
165
+ -------
166
+ list
167
+ list of timestamps.
168
+ dict
169
+ dict composed by timestamp as key and index as value for fast search.
170
+ """
171
+ flag = f"{freq}_future_{future}"
172
+ if flag not in H["c"]:
173
+ _calendar = np.array(self.load_calendar(freq, future))
174
+ _calendar_index = {x: i for i, x in enumerate(_calendar)} # for fast search
175
+ H["c"][flag] = _calendar, _calendar_index
176
+ return H["c"][flag]
177
+
178
+ def _uri(self, start_time, end_time, freq, future=False):
179
+ """Get the uri of calendar generation task."""
180
+ return hash_args(start_time, end_time, freq, future)
181
+
182
+ def load_calendar(self, freq, future):
183
+ """Load original calendar timestamp from file.
184
+
185
+ Parameters
186
+ ----------
187
+ freq : str
188
+ frequency of read calendar file.
189
+ future: bool
190
+
191
+ Returns
192
+ ----------
193
+ list
194
+ list of timestamps
195
+ """
196
+ raise NotImplementedError("Subclass of CalendarProvider must implement `load_calendar` method")
197
+
198
+
199
+ class InstrumentProvider(abc.ABC):
200
+ """Instrument provider base class
201
+
202
+ Provide instrument data.
203
+ """
204
+
205
+ @staticmethod
206
+ def instruments(market: Union[List, str] = "all", filter_pipe: Union[List, None] = None):
207
+ """Get the general config dictionary for a base market adding several dynamic filters.
208
+
209
+ Parameters
210
+ ----------
211
+ market : Union[List, str]
212
+ str:
213
+ market/industry/index shortname, e.g. all/sse/szse/sse50/csi300/csi500.
214
+ list:
215
+ ["ID1", "ID2"]. A list of stocks
216
+ filter_pipe : list
217
+ the list of dynamic filters.
218
+
219
+ Returns
220
+ ----------
221
+ dict: if isinstance(market, str)
222
+ dict of stockpool config.
223
+
224
+ {`market` => base market name, `filter_pipe` => list of filters}
225
+
226
+ example :
227
+
228
+ .. code-block::
229
+
230
+ {'market': 'csi500',
231
+ 'filter_pipe': [{'filter_type': 'ExpressionDFilter',
232
+ 'rule_expression': '$open<40',
233
+ 'filter_start_time': None,
234
+ 'filter_end_time': None,
235
+ 'keep': False},
236
+ {'filter_type': 'NameDFilter',
237
+ 'name_rule_re': 'SH[0-9]{4}55',
238
+ 'filter_start_time': None,
239
+ 'filter_end_time': None}]}
240
+
241
+ list: if isinstance(market, list)
242
+ just return the original list directly.
243
+ NOTE: this will make the instruments compatible with more cases. The user code will be simpler.
244
+ """
245
+ if isinstance(market, list):
246
+ return market
247
+ from .filter import SeriesDFilter # pylint: disable=C0415
248
+
249
+ if filter_pipe is None:
250
+ filter_pipe = []
251
+ config = {"market": market, "filter_pipe": []}
252
+ # the order of the filters will affect the result, so we need to keep
253
+ # the order
254
+ for filter_t in filter_pipe:
255
+ if isinstance(filter_t, dict):
256
+ _config = filter_t
257
+ elif isinstance(filter_t, SeriesDFilter):
258
+ _config = filter_t.to_config()
259
+ else:
260
+ raise TypeError(
261
+ f"Unsupported filter types: {type(filter_t)}! Filter only supports dict or isinstance(filter, SeriesDFilter)"
262
+ )
263
+ config["filter_pipe"].append(_config)
264
+ return config
265
+
266
+ @abc.abstractmethod
267
+ def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False):
268
+ """List the instruments based on a certain stockpool config.
269
+
270
+ Parameters
271
+ ----------
272
+ instruments : dict
273
+ stockpool config.
274
+ start_time : str
275
+ start of the time range.
276
+ end_time : str
277
+ end of the time range.
278
+ as_list : bool
279
+ return instruments as list or dict.
280
+
281
+ Returns
282
+ -------
283
+ dict or list
284
+ instruments list or dictionary with time spans
285
+ """
286
+ raise NotImplementedError("Subclass of InstrumentProvider must implement `list_instruments` method")
287
+
288
+ def _uri(self, instruments, start_time=None, end_time=None, freq="day", as_list=False):
289
+ return hash_args(instruments, start_time, end_time, freq, as_list)
290
+
291
+ # instruments type
292
+ LIST = "LIST"
293
+ DICT = "DICT"
294
+ CONF = "CONF"
295
+
296
+ @classmethod
297
+ def get_inst_type(cls, inst):
298
+ if "market" in inst:
299
+ return cls.CONF
300
+ if isinstance(inst, dict):
301
+ return cls.DICT
302
+ if isinstance(inst, (list, tuple, pd.Index, np.ndarray)):
303
+ return cls.LIST
304
+ raise ValueError(f"Unknown instrument type {inst}")
305
+
306
+
307
+ class FeatureProvider(abc.ABC):
308
+ """Feature provider class
309
+
310
+ Provide feature data.
311
+ """
312
+
313
+ @abc.abstractmethod
314
+ def feature(self, instrument, field, start_time, end_time, freq):
315
+ """Get feature data.
316
+
317
+ Parameters
318
+ ----------
319
+ instrument : str
320
+ a certain instrument.
321
+ field : str
322
+ a certain field of feature.
323
+ start_time : str
324
+ start of the time range.
325
+ end_time : str
326
+ end of the time range.
327
+ freq : str
328
+ time frequency, available: year/quarter/month/week/day.
329
+
330
+ Returns
331
+ -------
332
+ pd.Series
333
+ data of a certain feature
334
+ """
335
+ raise NotImplementedError("Subclass of FeatureProvider must implement `feature` method")
336
+
337
+
338
+ class PITProvider(abc.ABC):
339
+ @abc.abstractmethod
340
+ def period_feature(
341
+ self,
342
+ instrument,
343
+ field,
344
+ start_index: int,
345
+ end_index: int,
346
+ cur_time: pd.Timestamp,
347
+ period: Optional[int] = None,
348
+ ) -> pd.Series:
349
+ """
350
+ get the historical periods data series between `start_index` and `end_index`
351
+
352
+ Parameters
353
+ ----------
354
+ start_index: int
355
+ start_index is a relative index to the latest period to cur_time
356
+
357
+ end_index: int
358
+ end_index is a relative index to the latest period to cur_time
359
+ in most cases, the start_index and end_index will be a non-positive values
360
+ For example, start_index == -3 end_index == 0 and current period index is cur_idx,
361
+ then the data between [start_index + cur_idx, end_index + cur_idx] will be retrieved.
362
+
363
+ period: int
364
+ This is used for query specific period.
365
+ The period is represented with int in Qlib. (e.g. 202001 may represent the first quarter in 2020)
366
+ NOTE: `period` will override `start_index` and `end_index`
367
+
368
+ Returns
369
+ -------
370
+ pd.Series
371
+ The index will be integers to indicate the periods of the data
372
+ An typical examples will be
373
+ TODO
374
+
375
+ Raises
376
+ ------
377
+ FileNotFoundError
378
+ This exception will be raised if the queried data do not exist.
379
+ """
380
+ raise NotImplementedError(f"Please implement the `period_feature` method")
381
+
382
+
383
+ class ExpressionProvider(abc.ABC):
384
+ """Expression provider class
385
+
386
+ Provide Expression data.
387
+ """
388
+
389
+ def __init__(self):
390
+ self.expression_instance_cache = {}
391
+
392
+ def get_expression_instance(self, field):
393
+ try:
394
+ if field in self.expression_instance_cache:
395
+ expression = self.expression_instance_cache[field]
396
+ else:
397
+ expression = eval(parse_field(field))
398
+ self.expression_instance_cache[field] = expression
399
+ except NameError as e:
400
+ get_module_logger("data").exception(
401
+ "ERROR: field [%s] contains invalid operator/variable [%s]" % (str(field), str(e).split()[1])
402
+ )
403
+ raise
404
+ except SyntaxError:
405
+ get_module_logger("data").exception("ERROR: field [%s] contains invalid syntax" % str(field))
406
+ raise
407
+ return expression
408
+
409
+ @abc.abstractmethod
410
+ def expression(self, instrument, field, start_time=None, end_time=None, freq="day") -> pd.Series:
411
+ """Get Expression data.
412
+
413
+ The responsibility of `expression`
414
+ - parse the `field` and `load` the according data.
415
+ - When loading the data, it should handle the time dependency of the data. `get_expression_instance` is commonly used in this method
416
+
417
+ Parameters
418
+ ----------
419
+ instrument : str
420
+ a certain instrument.
421
+ field : str
422
+ a certain field of feature.
423
+ start_time : str
424
+ start of the time range.
425
+ end_time : str
426
+ end of the time range.
427
+ freq : str
428
+ time frequency, available: year/quarter/month/week/day.
429
+
430
+ Returns
431
+ -------
432
+ pd.Series
433
+ data of a certain expression
434
+
435
+ The data has two types of format
436
+
437
+ 1) expression with datetime index
438
+
439
+ 2) expression with integer index
440
+
441
+ - because the datetime is not as good as
442
+ """
443
+ raise NotImplementedError("Subclass of ExpressionProvider must implement `Expression` method")
444
+
445
+
446
+ class DatasetProvider(abc.ABC):
447
+ """Dataset provider class
448
+
449
+ Provide Dataset data.
450
+ """
451
+
452
+ @abc.abstractmethod
453
+ def dataset(self, instruments, fields, start_time=None, end_time=None, freq="day", inst_processors=[]):
454
+ """Get dataset data.
455
+
456
+ Parameters
457
+ ----------
458
+ instruments : list or dict
459
+ list/dict of instruments or dict of stockpool config.
460
+ fields : list
461
+ list of feature instances.
462
+ start_time : str
463
+ start of the time range.
464
+ end_time : str
465
+ end of the time range.
466
+ freq : str
467
+ time frequency.
468
+ inst_processors: Iterable[Union[dict, InstProcessor]]
469
+ the operations performed on each instrument
470
+
471
+ Returns
472
+ ----------
473
+ pd.DataFrame
474
+ a pandas dataframe with <instrument, datetime> index.
475
+ """
476
+ raise NotImplementedError("Subclass of DatasetProvider must implement `Dataset` method")
477
+
478
+ def _uri(
479
+ self,
480
+ instruments,
481
+ fields,
482
+ start_time=None,
483
+ end_time=None,
484
+ freq="day",
485
+ disk_cache=1,
486
+ inst_processors=[],
487
+ **kwargs,
488
+ ):
489
+ """Get task uri, used when generating rabbitmq task in qlib_server
490
+
491
+ Parameters
492
+ ----------
493
+ instruments : list or dict
494
+ list/dict of instruments or dict of stockpool config.
495
+ fields : list
496
+ list of feature instances.
497
+ start_time : str
498
+ start of the time range.
499
+ end_time : str
500
+ end of the time range.
501
+ freq : str
502
+ time frequency.
503
+ disk_cache : int
504
+ whether to skip(0)/use(1)/replace(2) disk_cache.
505
+
506
+ """
507
+ # TODO: qlib-server support inst_processors
508
+ return DiskDatasetCache._uri(instruments, fields, start_time, end_time, freq, disk_cache, inst_processors)
509
+
510
+ @staticmethod
511
+ def get_instruments_d(instruments, freq):
512
+ """
513
+ Parse different types of input instruments to output instruments_d
514
+ Wrong format of input instruments will lead to exception.
515
+
516
+ """
517
+ if isinstance(instruments, dict):
518
+ if "market" in instruments:
519
+ # dict of stockpool config
520
+ instruments_d = Inst.list_instruments(instruments=instruments, freq=freq, as_list=False)
521
+ else:
522
+ # dict of instruments and timestamp
523
+ instruments_d = instruments
524
+ elif isinstance(instruments, (list, tuple, pd.Index, np.ndarray)):
525
+ # list or tuple of a group of instruments
526
+ instruments_d = list(instruments)
527
+ else:
528
+ raise ValueError("Unsupported input type for param `instrument`")
529
+ return instruments_d
530
+
531
+ @staticmethod
532
+ def get_column_names(fields):
533
+ """
534
+ Get column names from input fields
535
+
536
+ """
537
+ if len(fields) == 0:
538
+ raise ValueError("fields cannot be empty")
539
+ column_names = [str(f) for f in fields]
540
+ return column_names
541
+
542
+ @staticmethod
543
+ def parse_fields(fields):
544
+ # parse and check the input fields
545
+ return [ExpressionD.get_expression_instance(f) for f in fields]
546
+
547
+ @staticmethod
548
+ def dataset_processor(instruments_d, column_names, start_time, end_time, freq, inst_processors=[]):
549
+ """
550
+ Load and process the data, return the data set.
551
+ - default using multi-kernel method.
552
+
553
+ """
554
+ normalize_column_names = normalize_cache_fields(column_names)
555
+ # One process for one task, so that the memory will be freed quicker.
556
+ workers = max(min(C.get_kernels(freq), len(instruments_d)), 1)
557
+
558
+ # create iterator
559
+ if isinstance(instruments_d, dict):
560
+ it = instruments_d.items()
561
+ else:
562
+ it = zip(instruments_d, [None] * len(instruments_d))
563
+
564
+ inst_l = []
565
+ task_l = []
566
+ for inst, spans in it:
567
+ inst_l.append(inst)
568
+ task_l.append(
569
+ delayed(DatasetProvider.inst_calculator)(
570
+ inst, start_time, end_time, freq, normalize_column_names, spans, C, inst_processors
571
+ )
572
+ )
573
+
574
+ data = dict(
575
+ zip(
576
+ inst_l,
577
+ ParallelExt(n_jobs=workers, backend=C.joblib_backend, maxtasksperchild=C.maxtasksperchild)(task_l),
578
+ )
579
+ )
580
+
581
+ new_data = dict()
582
+ for inst in sorted(data.keys()):
583
+ if len(data[inst]) > 0:
584
+ # NOTE: Python version >= 3.6; in versions after python3.6, dict will always guarantee the insertion order
585
+ new_data[inst] = data[inst]
586
+
587
+ if len(new_data) > 0:
588
+ data = pd.concat(new_data, names=["instrument"], sort=False)
589
+ data = DiskDatasetCache.cache_to_origin_data(data, column_names)
590
+ else:
591
+ data = pd.DataFrame(
592
+ index=pd.MultiIndex.from_arrays([[], []], names=("instrument", "datetime")),
593
+ columns=column_names,
594
+ dtype=np.float32,
595
+ )
596
+
597
+ return data
598
+
599
+ @staticmethod
600
+ def inst_calculator(inst, start_time, end_time, freq, column_names, spans=None, g_config=None, inst_processors=[]):
601
+ """
602
+ Calculate the expressions for **one** instrument, return a df result.
603
+ If the expression has been calculated before, load from cache.
604
+
605
+ return value: A data frame with index 'datetime' and other data columns.
606
+
607
+ """
608
+ # FIXME: Windows OS or MacOS using spawn: https://docs.python.org/3.8/library/multiprocessing.html?highlight=spawn#contexts-and-start-methods
609
+ # NOTE: This place is compatible with windows, windows multi-process is spawn
610
+ C.register_from_C(g_config)
611
+
612
+ obj = dict()
613
+ for field in column_names:
614
+ # The client does not have expression provider, the data will be loaded from cache using static method.
615
+ obj[field] = ExpressionD.expression(inst, field, start_time, end_time, freq)
616
+
617
+ data = pd.DataFrame(obj)
618
+ if not data.empty and not np.issubdtype(data.index.dtype, np.dtype("M")):
619
+ # If the underlaying provides the data not in datetime format, we'll convert it into datetime format
620
+ _calendar = Cal.calendar(freq=freq)
621
+ data.index = _calendar[data.index.values.astype(int)]
622
+ data.index.names = ["datetime"]
623
+
624
+ if not data.empty and spans is not None:
625
+ mask = np.zeros(len(data), dtype=bool)
626
+ for begin, end in spans:
627
+ mask |= (data.index >= begin) & (data.index <= end)
628
+ data = data[mask]
629
+
630
+ for _processor in inst_processors:
631
+ if _processor:
632
+ _processor_obj = init_instance_by_config(_processor, accept_types=InstProcessor)
633
+ data = _processor_obj(data, instrument=inst)
634
+ return data
635
+
636
+
637
+ class LocalCalendarProvider(CalendarProvider, ProviderBackendMixin):
638
+ """Local calendar data provider class
639
+
640
+ Provide calendar data from local data source.
641
+ """
642
+
643
+ def __init__(self, remote=False, backend={}):
644
+ super().__init__()
645
+ self.remote = remote
646
+ self.backend = backend
647
+
648
+ def load_calendar(self, freq, future):
649
+ """Load original calendar timestamp from file.
650
+
651
+ Parameters
652
+ ----------
653
+ freq : str
654
+ frequency of read calendar file.
655
+ future: bool
656
+ Returns
657
+ ----------
658
+ list
659
+ list of timestamps
660
+ """
661
+ try:
662
+ backend_obj = self.backend_obj(freq=freq, future=future).data
663
+ except ValueError:
664
+ if future:
665
+ get_module_logger("data").warning(
666
+ f"load calendar error: freq={freq}, future={future}; return current calendar!"
667
+ )
668
+ get_module_logger("data").warning(
669
+ "You can get future calendar by referring to the following document: https://github.com/microsoft/qlib/blob/main/scripts/data_collector/contrib/README.md"
670
+ )
671
+ backend_obj = self.backend_obj(freq=freq, future=False).data
672
+ else:
673
+ raise
674
+
675
+ return [pd.Timestamp(x) for x in backend_obj]
676
+
677
+
678
+ class LocalInstrumentProvider(InstrumentProvider, ProviderBackendMixin):
679
+ """Local instrument data provider class
680
+
681
+ Provide instrument data from local data source.
682
+ """
683
+
684
+ def __init__(self, backend={}) -> None:
685
+ super().__init__()
686
+ self.backend = backend
687
+
688
+ def _load_instruments(self, market, freq):
689
+ return self.backend_obj(market=market, freq=freq).data
690
+
691
+ def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False):
692
+ market = instruments["market"]
693
+ if market in H["i"]:
694
+ _instruments = H["i"][market]
695
+ else:
696
+ _instruments = self._load_instruments(market, freq=freq)
697
+ H["i"][market] = _instruments
698
+ # strip
699
+ # use calendar boundary
700
+ cal = Cal.calendar(freq=freq)
701
+ start_time = pd.Timestamp(start_time or cal[0])
702
+ end_time = pd.Timestamp(end_time or cal[-1])
703
+ _instruments_filtered = {
704
+ inst: list(
705
+ filter(
706
+ lambda x: x[0] <= x[1],
707
+ [(max(start_time, pd.Timestamp(x[0])), min(end_time, pd.Timestamp(x[1]))) for x in spans],
708
+ )
709
+ )
710
+ for inst, spans in _instruments.items()
711
+ }
712
+ _instruments_filtered = {key: value for key, value in _instruments_filtered.items() if value}
713
+ # filter
714
+ filter_pipe = instruments["filter_pipe"]
715
+ for filter_config in filter_pipe:
716
+ from . import filter as F # pylint: disable=C0415
717
+
718
+ filter_t = getattr(F, filter_config["filter_type"]).from_config(filter_config)
719
+ _instruments_filtered = filter_t(_instruments_filtered, start_time, end_time, freq)
720
+ # as list
721
+ if as_list:
722
+ return list(_instruments_filtered)
723
+ return _instruments_filtered
724
+
725
+
726
+ class LocalFeatureProvider(FeatureProvider, ProviderBackendMixin):
727
+ """Local feature data provider class
728
+
729
+ Provide feature data from local data source.
730
+ """
731
+
732
+ def __init__(self, remote=False, backend={}):
733
+ super().__init__()
734
+ self.remote = remote
735
+ self.backend = backend
736
+
737
+ def feature(self, instrument, field, start_index, end_index, freq):
738
+ # validate
739
+ field = str(field)[1:]
740
+ instrument = code_to_fname(instrument)
741
+ return self.backend_obj(instrument=instrument, field=field, freq=freq)[start_index : end_index + 1]
742
+
743
+
744
+ class LocalPITProvider(PITProvider):
745
+ # TODO: Add PIT backend file storage
746
+ # NOTE: This class is not multi-threading-safe!!!!
747
+
748
+ def period_feature(self, instrument, field, start_index, end_index, cur_time, period=None):
749
+ if not isinstance(cur_time, pd.Timestamp):
750
+ raise ValueError(
751
+ f"Expected pd.Timestamp for `cur_time`, got '{cur_time}'. Advices: you can't query PIT data directly(e.g. '$$roewa_q'), you must use `P` operator to convert data to each day (e.g. 'P($$roewa_q)')"
752
+ )
753
+
754
+ assert end_index <= 0 # PIT don't support querying future data
755
+
756
+ DATA_RECORDS = [
757
+ ("date", C.pit_record_type["date"]),
758
+ ("period", C.pit_record_type["period"]),
759
+ ("value", C.pit_record_type["value"]),
760
+ ("_next", C.pit_record_type["index"]),
761
+ ]
762
+ VALUE_DTYPE = C.pit_record_type["value"]
763
+
764
+ field = str(field).lower()[2:]
765
+ instrument = code_to_fname(instrument)
766
+
767
+ # {For acceleration
768
+ # start_index, end_index, cur_index = kwargs["info"]
769
+ # if cur_index == start_index:
770
+ # if not hasattr(self, "all_fields"):
771
+ # self.all_fields = []
772
+ # self.all_fields.append(field)
773
+ # if not hasattr(self, "period_index"):
774
+ # self.period_index = {}
775
+ # if field not in self.period_index:
776
+ # self.period_index[field] = {}
777
+ # For acceleration}
778
+
779
+ if not field.endswith("_q") and not field.endswith("_a"):
780
+ raise ValueError("period field must ends with '_q' or '_a'")
781
+ quarterly = field.endswith("_q")
782
+ index_path = C.dpm.get_data_uri() / "financial" / instrument.lower() / f"{field}.index"
783
+ data_path = C.dpm.get_data_uri() / "financial" / instrument.lower() / f"{field}.data"
784
+ if not (index_path.exists() and data_path.exists()):
785
+ raise FileNotFoundError("No file is found.")
786
+ # NOTE: The most significant performance loss is here.
787
+ # Does the acceleration that makes the program complicated really matters?
788
+ # - It makes parameters of the interface complicate
789
+ # - It does not performance in the optimal way (places all the pieces together, we may achieve higher performance)
790
+ # - If we design it carefully, we can go through for only once to get the historical evolution of the data.
791
+ # So I decide to deprecated previous implementation and keep the logic of the program simple
792
+ # Instead, I'll add a cache for the index file.
793
+ data = np.fromfile(data_path, dtype=DATA_RECORDS)
794
+
795
+ # find all revision periods before `cur_time`
796
+ cur_time_int = int(cur_time.year) * 10000 + int(cur_time.month) * 100 + int(cur_time.day)
797
+ loc = np.searchsorted(data["date"], cur_time_int, side="right")
798
+ if loc <= 0:
799
+ return pd.Series(dtype=C.pit_record_type["value"])
800
+ last_period = data["period"][:loc].max() # return the latest quarter
801
+ first_period = data["period"][:loc].min()
802
+ period_list = get_period_list(first_period, last_period, quarterly)
803
+ if period is not None:
804
+ # NOTE: `period` has higher priority than `start_index` & `end_index`
805
+ if period not in period_list:
806
+ return pd.Series(dtype=C.pit_record_type["value"])
807
+ else:
808
+ period_list = [period]
809
+ else:
810
+ period_list = period_list[max(0, len(period_list) + start_index - 1) : len(period_list) + end_index]
811
+ value = np.full((len(period_list),), np.nan, dtype=VALUE_DTYPE)
812
+ for i, p in enumerate(period_list):
813
+ # last_period_index = self.period_index[field].get(period) # For acceleration
814
+ value[i], now_period_index = read_period_data(
815
+ index_path, data_path, p, cur_time_int, quarterly # , last_period_index # For acceleration
816
+ )
817
+ # self.period_index[field].update({period: now_period_index}) # For acceleration
818
+ # NOTE: the index is period_list; So it may result in unexpected values(e.g. nan)
819
+ # when calculation between different features and only part of its financial indicator is published
820
+ series = pd.Series(value, index=period_list, dtype=VALUE_DTYPE)
821
+
822
+ # {For acceleration
823
+ # if cur_index == end_index:
824
+ # self.all_fields.remove(field)
825
+ # if not len(self.all_fields):
826
+ # del self.all_fields
827
+ # del self.period_index
828
+ # For acceleration}
829
+
830
+ return series
831
+
832
+
833
+ class LocalExpressionProvider(ExpressionProvider):
834
+ """Local expression data provider class
835
+
836
+ Provide expression data from local data source.
837
+ """
838
+
839
+ def __init__(self, time2idx=True):
840
+ super().__init__()
841
+ self.time2idx = time2idx
842
+
843
+ def expression(self, instrument, field, start_time=None, end_time=None, freq="day"):
844
+ expression = self.get_expression_instance(field)
845
+ start_time = time_to_slc_point(start_time)
846
+ end_time = time_to_slc_point(end_time)
847
+
848
+ # Two kinds of queries are supported
849
+ # - Index-based expression: this may save a lot of memory because the datetime index is not saved on the disk
850
+ # - Data with datetime index expression: this will make it more convenient to integrating with some existing databases
851
+ if self.time2idx:
852
+ _, _, start_index, end_index = Cal.locate_index(start_time, end_time, freq=freq, future=False)
853
+ lft_etd, rght_etd = expression.get_extended_window_size()
854
+ query_start, query_end = max(0, start_index - lft_etd), end_index + rght_etd
855
+ else:
856
+ start_index, end_index = query_start, query_end = start_time, end_time
857
+
858
+ try:
859
+ series = expression.load(instrument, query_start, query_end, freq)
860
+ except Exception as e:
861
+ get_module_logger("data").debug(
862
+ f"Loading expression error: "
863
+ f"instrument={instrument}, field=({field}), start_time={start_time}, end_time={end_time}, freq={freq}. "
864
+ f"error info: {str(e)}"
865
+ )
866
+ raise
867
+ # Ensure that each column type is consistent
868
+ # FIXME:
869
+ # 1) The stock data is currently float. If there is other types of data, this part needs to be re-implemented.
870
+ # 2) The precision should be configurable
871
+ try:
872
+ series = series.astype(np.float32)
873
+ except ValueError:
874
+ pass
875
+ except TypeError:
876
+ pass
877
+ if not series.empty:
878
+ series = series.loc[start_index:end_index]
879
+ return series
880
+
881
+
882
+ class LocalDatasetProvider(DatasetProvider):
883
+ """Local dataset data provider class
884
+
885
+ Provide dataset data from local data source.
886
+ """
887
+
888
+ def __init__(self, align_time: bool = True):
889
+ """
890
+ Parameters
891
+ ----------
892
+ align_time : bool
893
+ Will we align the time to calendar
894
+ the frequency is flexible in some dataset and can't be aligned.
895
+ For the data with fixed frequency with a shared calendar, the align data to the calendar will provides following benefits
896
+
897
+ - Align queries to the same parameters, so the cache can be shared.
898
+ """
899
+ super().__init__()
900
+ self.align_time = align_time
901
+
902
+ def dataset(
903
+ self,
904
+ instruments,
905
+ fields,
906
+ start_time=None,
907
+ end_time=None,
908
+ freq="day",
909
+ inst_processors=[],
910
+ ):
911
+ instruments_d = self.get_instruments_d(instruments, freq)
912
+ column_names = self.get_column_names(fields)
913
+ if self.align_time:
914
+ # NOTE: if the frequency is a fixed value.
915
+ # align the data to fixed calendar point
916
+ cal = Cal.calendar(start_time, end_time, freq)
917
+ if len(cal) == 0:
918
+ return pd.DataFrame(
919
+ index=pd.MultiIndex.from_arrays([[], []], names=("instrument", "datetime")), columns=column_names
920
+ )
921
+ start_time = cal[0]
922
+ end_time = cal[-1]
923
+ data = self.dataset_processor(
924
+ instruments_d, column_names, start_time, end_time, freq, inst_processors=inst_processors
925
+ )
926
+
927
+ return data
928
+
929
+ @staticmethod
930
+ def multi_cache_walker(instruments, fields, start_time=None, end_time=None, freq="day"):
931
+ """
932
+ This method is used to prepare the expression cache for the client.
933
+ Then the client will load the data from expression cache by itself.
934
+
935
+ """
936
+ instruments_d = DatasetProvider.get_instruments_d(instruments, freq)
937
+ column_names = DatasetProvider.get_column_names(fields)
938
+ cal = Cal.calendar(start_time, end_time, freq)
939
+ if len(cal) == 0:
940
+ return
941
+ start_time = cal[0]
942
+ end_time = cal[-1]
943
+ workers = max(min(C.kernels, len(instruments_d)), 1)
944
+
945
+ ParallelExt(n_jobs=workers, backend=C.joblib_backend, maxtasksperchild=C.maxtasksperchild)(
946
+ delayed(LocalDatasetProvider.cache_walker)(inst, start_time, end_time, freq, column_names)
947
+ for inst in instruments_d
948
+ )
949
+
950
+ @staticmethod
951
+ def cache_walker(inst, start_time, end_time, freq, column_names):
952
+ """
953
+ If the expressions of one instrument haven't been calculated before,
954
+ calculate it and write it into expression cache.
955
+
956
+ """
957
+ for field in column_names:
958
+ ExpressionD.expression(inst, field, start_time, end_time, freq)
959
+
960
+
961
+ class ClientCalendarProvider(CalendarProvider):
962
+ """Client calendar data provider class
963
+
964
+ Provide calendar data by requesting data from server as a client.
965
+ """
966
+
967
+ def __init__(self):
968
+ self.conn = None
969
+ self.queue = queue.Queue()
970
+
971
+ def set_conn(self, conn):
972
+ self.conn = conn
973
+
974
+ def calendar(self, start_time=None, end_time=None, freq="day", future=False):
975
+ self.conn.send_request(
976
+ request_type="calendar",
977
+ request_content={"start_time": str(start_time), "end_time": str(end_time), "freq": freq, "future": future},
978
+ msg_queue=self.queue,
979
+ msg_proc_func=lambda response_content: [pd.Timestamp(c) for c in response_content],
980
+ )
981
+ result = self.queue.get(timeout=C["timeout"])
982
+ return result
983
+
984
+
985
+ class ClientInstrumentProvider(InstrumentProvider):
986
+ """Client instrument data provider class
987
+
988
+ Provide instrument data by requesting data from server as a client.
989
+ """
990
+
991
+ def __init__(self):
992
+ self.conn = None
993
+ self.queue = queue.Queue()
994
+
995
+ def set_conn(self, conn):
996
+ self.conn = conn
997
+
998
+ def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False):
999
+ def inst_msg_proc_func(response_content):
1000
+ if isinstance(response_content, dict):
1001
+ instrument = {
1002
+ i: [(pd.Timestamp(s), pd.Timestamp(e)) for s, e in t] for i, t in response_content.items()
1003
+ }
1004
+ else:
1005
+ instrument = response_content
1006
+ return instrument
1007
+
1008
+ self.conn.send_request(
1009
+ request_type="instrument",
1010
+ request_content={
1011
+ "instruments": instruments,
1012
+ "start_time": str(start_time),
1013
+ "end_time": str(end_time),
1014
+ "freq": freq,
1015
+ "as_list": as_list,
1016
+ },
1017
+ msg_queue=self.queue,
1018
+ msg_proc_func=inst_msg_proc_func,
1019
+ )
1020
+ result = self.queue.get(timeout=C["timeout"])
1021
+ if isinstance(result, Exception):
1022
+ raise result
1023
+ get_module_logger("data").debug("get result")
1024
+ return result
1025
+
1026
+
1027
+ class ClientDatasetProvider(DatasetProvider):
1028
+ """Client dataset data provider class
1029
+
1030
+ Provide dataset data by requesting data from server as a client.
1031
+ """
1032
+
1033
+ def __init__(self):
1034
+ self.conn = None
1035
+
1036
+ def set_conn(self, conn):
1037
+ self.conn = conn
1038
+ self.queue = queue.Queue()
1039
+
1040
+ def dataset(
1041
+ self,
1042
+ instruments,
1043
+ fields,
1044
+ start_time=None,
1045
+ end_time=None,
1046
+ freq="day",
1047
+ disk_cache=0,
1048
+ return_uri=False,
1049
+ inst_processors=[],
1050
+ ):
1051
+ if Inst.get_inst_type(instruments) == Inst.DICT:
1052
+ get_module_logger("data").warning(
1053
+ "Getting features from a dict of instruments is not recommended because the features will not be "
1054
+ "cached! "
1055
+ "The dict of instruments will be cleaned every day."
1056
+ )
1057
+
1058
+ if disk_cache == 0:
1059
+ """
1060
+ Call the server to generate the expression cache.
1061
+ Then load the data from the expression cache directly.
1062
+ - default using multi-kernel method.
1063
+
1064
+ """
1065
+ self.conn.send_request(
1066
+ request_type="feature",
1067
+ request_content={
1068
+ "instruments": instruments,
1069
+ "fields": fields,
1070
+ "start_time": start_time,
1071
+ "end_time": end_time,
1072
+ "freq": freq,
1073
+ "disk_cache": 0,
1074
+ },
1075
+ msg_queue=self.queue,
1076
+ )
1077
+ feature_uri = self.queue.get(timeout=C["timeout"])
1078
+ if isinstance(feature_uri, Exception):
1079
+ raise feature_uri
1080
+ else:
1081
+ instruments_d = self.get_instruments_d(instruments, freq)
1082
+ column_names = self.get_column_names(fields)
1083
+ cal = Cal.calendar(start_time, end_time, freq)
1084
+ if len(cal) == 0:
1085
+ return pd.DataFrame(
1086
+ index=pd.MultiIndex.from_arrays([[], []], names=("instrument", "datetime")),
1087
+ columns=column_names,
1088
+ )
1089
+ start_time = cal[0]
1090
+ end_time = cal[-1]
1091
+
1092
+ data = self.dataset_processor(instruments_d, column_names, start_time, end_time, freq, inst_processors)
1093
+ if return_uri:
1094
+ return data, feature_uri
1095
+ else:
1096
+ return data
1097
+ else:
1098
+ """
1099
+ Call the server to generate the data-set cache, get the uri of the cache file.
1100
+ Then load the data from the file on NFS directly.
1101
+ - using single-process implementation.
1102
+
1103
+ """
1104
+ # TODO: support inst_processors, need to change the code of qlib-server at the same time
1105
+ # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date
1106
+ if inst_processors:
1107
+ raise ValueError(
1108
+ f"{self.__class__.__name__} does not support inst_processor. "
1109
+ f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`"
1110
+ )
1111
+ self.conn.send_request(
1112
+ request_type="feature",
1113
+ request_content={
1114
+ "instruments": instruments,
1115
+ "fields": fields,
1116
+ "start_time": start_time,
1117
+ "end_time": end_time,
1118
+ "freq": freq,
1119
+ "disk_cache": 1,
1120
+ },
1121
+ msg_queue=self.queue,
1122
+ )
1123
+ # - Done in callback
1124
+ feature_uri = self.queue.get(timeout=C["timeout"])
1125
+ if isinstance(feature_uri, Exception):
1126
+ raise feature_uri
1127
+ get_module_logger("data").debug("get result")
1128
+ try:
1129
+ # pre-mound nfs, used for demo
1130
+ mnt_feature_uri = C.dpm.get_data_uri(freq).joinpath(C.dataset_cache_dir_name, feature_uri)
1131
+ df = DiskDatasetCache.read_data_from_cache(mnt_feature_uri, start_time, end_time, fields)
1132
+ get_module_logger("data").debug("finish slicing data")
1133
+ if return_uri:
1134
+ return df, feature_uri
1135
+ return df
1136
+ except AttributeError as attribute_e:
1137
+ raise IOError("Unable to fetch instruments from remote server!") from attribute_e
1138
+
1139
+
1140
+ class BaseProvider:
1141
+ """Local provider class
1142
+ It is a set of interface that allow users to access data.
1143
+ Because PITD is not exposed publicly to users, so it is not included in the interface.
1144
+
1145
+ To keep compatible with old qlib provider.
1146
+ """
1147
+
1148
+ def calendar(self, start_time=None, end_time=None, freq="day", future=False):
1149
+ return Cal.calendar(start_time, end_time, freq, future=future)
1150
+
1151
+ def instruments(self, market="all", filter_pipe=None, start_time=None, end_time=None):
1152
+ if start_time is not None or end_time is not None:
1153
+ get_module_logger("Provider").warning(
1154
+ "The instruments corresponds to a stock pool. "
1155
+ "Parameters `start_time` and `end_time` does not take effect now."
1156
+ )
1157
+ return InstrumentProvider.instruments(market, filter_pipe)
1158
+
1159
+ def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False):
1160
+ return Inst.list_instruments(instruments, start_time, end_time, freq, as_list)
1161
+
1162
+ def features(
1163
+ self,
1164
+ instruments,
1165
+ fields,
1166
+ start_time=None,
1167
+ end_time=None,
1168
+ freq="day",
1169
+ disk_cache=None,
1170
+ inst_processors=[],
1171
+ ):
1172
+ """
1173
+ Parameters
1174
+ ----------
1175
+ disk_cache : int
1176
+ whether to skip(0)/use(1)/replace(2) disk_cache
1177
+
1178
+
1179
+ This function will try to use cache method which has a keyword `disk_cache`,
1180
+ and will use provider method if a type error is raised because the DatasetD instance
1181
+ is a provider class.
1182
+ """
1183
+ disk_cache = C.default_disk_cache if disk_cache is None else disk_cache
1184
+ fields = list(fields) # In case of tuple.
1185
+ try:
1186
+ return DatasetD.dataset(
1187
+ instruments, fields, start_time, end_time, freq, disk_cache, inst_processors=inst_processors
1188
+ )
1189
+ except TypeError:
1190
+ return DatasetD.dataset(instruments, fields, start_time, end_time, freq, inst_processors=inst_processors)
1191
+
1192
+
1193
+ class LocalProvider(BaseProvider):
1194
+ def _uri(self, type, **kwargs):
1195
+ """_uri
1196
+ The server hope to get the uri of the request. The uri will be decided
1197
+ by the dataprovider. For ex, different cache layer has different uri.
1198
+
1199
+ :param type: The type of resource for the uri
1200
+ :param **kwargs:
1201
+ """
1202
+ if type == "calendar":
1203
+ return Cal._uri(**kwargs)
1204
+ elif type == "instrument":
1205
+ return Inst._uri(**kwargs)
1206
+ elif type == "feature":
1207
+ return DatasetD._uri(**kwargs)
1208
+
1209
+ def features_uri(self, instruments, fields, start_time, end_time, freq, disk_cache=1):
1210
+ """features_uri
1211
+
1212
+ Return the uri of the generated cache of features/dataset
1213
+
1214
+ :param disk_cache:
1215
+ :param instruments:
1216
+ :param fields:
1217
+ :param start_time:
1218
+ :param end_time:
1219
+ :param freq:
1220
+ """
1221
+ return DatasetD._dataset_uri(instruments, fields, start_time, end_time, freq, disk_cache)
1222
+
1223
+
1224
+ class ClientProvider(BaseProvider):
1225
+ """Client Provider
1226
+
1227
+ Requesting data from server as a client. Can propose requests:
1228
+
1229
+ - Calendar : Directly respond a list of calendars
1230
+ - Instruments (without filter): Directly respond a list/dict of instruments
1231
+ - Instruments (with filters): Respond a list/dict of instruments
1232
+ - Features : Respond a cache uri
1233
+
1234
+ The general workflow is described as follows:
1235
+ When the user use client provider to propose a request, the client provider will connect the server and send the request. The client will start to wait for the response. The response will be made instantly indicating whether the cache is available. The waiting procedure will terminate only when the client get the response saying `feature_available` is true.
1236
+ `BUG` : Everytime we make request for certain data we need to connect to the server, wait for the response and disconnect from it. We can't make a sequence of requests within one connection. You can refer to https://python-socketio.readthedocs.io/en/latest/client.html for documentation of python-socketIO client.
1237
+ """
1238
+
1239
+ def __init__(self):
1240
+ def is_instance_of_provider(instance: object, cls: type):
1241
+ if isinstance(instance, Wrapper):
1242
+ p = getattr(instance, "_provider", None)
1243
+
1244
+ return False if p is None else isinstance(p, cls)
1245
+
1246
+ return isinstance(instance, cls)
1247
+
1248
+ from .client import Client # pylint: disable=C0415
1249
+
1250
+ self.client = Client(C.flask_server, C.flask_port)
1251
+ self.logger = get_module_logger(self.__class__.__name__)
1252
+ if is_instance_of_provider(Cal, ClientCalendarProvider):
1253
+ Cal.set_conn(self.client)
1254
+ if is_instance_of_provider(Inst, ClientInstrumentProvider):
1255
+ Inst.set_conn(self.client)
1256
+ if hasattr(DatasetD, "provider"):
1257
+ DatasetD.provider.set_conn(self.client)
1258
+ else:
1259
+ DatasetD.set_conn(self.client)
1260
+
1261
+
1262
+ import sys
1263
+
1264
+ if sys.version_info >= (3, 9):
1265
+ from typing import Annotated
1266
+
1267
+ CalendarProviderWrapper = Annotated[CalendarProvider, Wrapper]
1268
+ InstrumentProviderWrapper = Annotated[InstrumentProvider, Wrapper]
1269
+ FeatureProviderWrapper = Annotated[FeatureProvider, Wrapper]
1270
+ PITProviderWrapper = Annotated[PITProvider, Wrapper]
1271
+ ExpressionProviderWrapper = Annotated[ExpressionProvider, Wrapper]
1272
+ DatasetProviderWrapper = Annotated[DatasetProvider, Wrapper]
1273
+ BaseProviderWrapper = Annotated[BaseProvider, Wrapper]
1274
+ else:
1275
+ CalendarProviderWrapper = CalendarProvider
1276
+ InstrumentProviderWrapper = InstrumentProvider
1277
+ FeatureProviderWrapper = FeatureProvider
1278
+ PITProviderWrapper = PITProvider
1279
+ ExpressionProviderWrapper = ExpressionProvider
1280
+ DatasetProviderWrapper = DatasetProvider
1281
+ BaseProviderWrapper = BaseProvider
1282
+
1283
+ Cal: CalendarProviderWrapper = Wrapper()
1284
+ Inst: InstrumentProviderWrapper = Wrapper()
1285
+ FeatureD: FeatureProviderWrapper = Wrapper()
1286
+ PITD: PITProviderWrapper = Wrapper()
1287
+ ExpressionD: ExpressionProviderWrapper = Wrapper()
1288
+ DatasetD: DatasetProviderWrapper = Wrapper()
1289
+ D: BaseProviderWrapper = Wrapper()
1290
+
1291
+
1292
+ def register_all_wrappers(C):
1293
+ """register_all_wrappers"""
1294
+ logger = get_module_logger("data")
1295
+ module = get_module_by_module_path("qlib.data")
1296
+
1297
+ _calendar_provider = init_instance_by_config(C.calendar_provider, module)
1298
+ if getattr(C, "calendar_cache", None) is not None:
1299
+ _calendar_provider = init_instance_by_config(C.calendar_cache, module, provide=_calendar_provider)
1300
+ register_wrapper(Cal, _calendar_provider, "qlib.data")
1301
+ logger.debug(f"registering Cal {C.calendar_provider}-{C.calendar_cache}")
1302
+
1303
+ _instrument_provider = init_instance_by_config(C.instrument_provider, module)
1304
+ register_wrapper(Inst, _instrument_provider, "qlib.data")
1305
+ logger.debug(f"registering Inst {C.instrument_provider}")
1306
+
1307
+ if getattr(C, "feature_provider", None) is not None:
1308
+ feature_provider = init_instance_by_config(C.feature_provider, module)
1309
+ register_wrapper(FeatureD, feature_provider, "qlib.data")
1310
+ logger.debug(f"registering FeatureD {C.feature_provider}")
1311
+
1312
+ if getattr(C, "pit_provider", None) is not None:
1313
+ pit_provider = init_instance_by_config(C.pit_provider, module)
1314
+ register_wrapper(PITD, pit_provider, "qlib.data")
1315
+ logger.debug(f"registering PITD {C.pit_provider}")
1316
+
1317
+ if getattr(C, "expression_provider", None) is not None:
1318
+ # This provider is unnecessary in client provider
1319
+ _eprovider = init_instance_by_config(C.expression_provider, module)
1320
+ if getattr(C, "expression_cache", None) is not None:
1321
+ _eprovider = init_instance_by_config(C.expression_cache, module, provider=_eprovider)
1322
+ register_wrapper(ExpressionD, _eprovider, "qlib.data")
1323
+ logger.debug(f"registering ExpressionD {C.expression_provider}-{C.expression_cache}")
1324
+
1325
+ _dprovider = init_instance_by_config(C.dataset_provider, module)
1326
+ if getattr(C, "dataset_cache", None) is not None:
1327
+ _dprovider = init_instance_by_config(C.dataset_cache, module, provider=_dprovider)
1328
+ register_wrapper(DatasetD, _dprovider, "qlib.data")
1329
+ logger.debug(f"registering DatasetD {C.dataset_provider}-{C.dataset_cache}")
1330
+
1331
+ register_wrapper(D, C.provider, "qlib.data")
1332
+ logger.debug(f"registering D {C.provider}")
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/__init__.py ADDED
@@ -0,0 +1,722 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ...utils.serial import Serializable
2
+ from typing import Callable, Union, List, Tuple, Dict, Text, Optional
3
+ from ...utils import init_instance_by_config, np_ffill, time_to_slc_point
4
+ from ...log import get_module_logger
5
+ from .handler import DataHandler, DataHandlerLP
6
+ from copy import copy, deepcopy
7
+ from inspect import getfullargspec
8
+ import pandas as pd
9
+ import numpy as np
10
+ import bisect
11
+ from ...utils import lazy_sort_index
12
+ from .utils import get_level_index
13
+
14
+
15
+ class Dataset(Serializable):
16
+ """
17
+ Preparing data for model training and inferencing.
18
+ """
19
+
20
+ def __init__(self, **kwargs):
21
+ """
22
+ init is designed to finish following steps:
23
+
24
+ - init the sub instance and the state of the dataset(info to prepare the data)
25
+ - The name of essential state for preparing data should not start with '_' so that it could be serialized on disk when serializing.
26
+
27
+ - setup data
28
+ - The data related attributes' names should start with '_' so that it will not be saved on disk when serializing.
29
+
30
+ The data could specify the info to calculate the essential data for preparation
31
+ """
32
+ self.setup_data(**kwargs)
33
+ super().__init__()
34
+
35
+ def config(self, **kwargs):
36
+ """
37
+ config is designed to configure and parameters that cannot be learned from the data
38
+ """
39
+ super().config(**kwargs)
40
+
41
+ def setup_data(self, **kwargs):
42
+ """
43
+ Setup the data.
44
+
45
+ We split the setup_data function for following situation:
46
+
47
+ - User have a Dataset object with learned status on disk.
48
+
49
+ - User load the Dataset object from the disk.
50
+
51
+ - User call `setup_data` to load new data.
52
+
53
+ - User prepare data for model based on previous status.
54
+ """
55
+
56
+ def prepare(self, **kwargs) -> object:
57
+ """
58
+ The type of dataset depends on the model. (It could be pd.DataFrame, pytorch.DataLoader, etc.)
59
+ The parameters should specify the scope for the prepared data
60
+ The method should:
61
+ - process the data
62
+
63
+ - return the processed data
64
+
65
+ Returns
66
+ -------
67
+ object:
68
+ return the object
69
+ """
70
+
71
+
72
+ class DatasetH(Dataset):
73
+ """
74
+ Dataset with Data(H)andler
75
+
76
+ User should try to put the data preprocessing functions into handler.
77
+ Only following data processing functions should be placed in Dataset:
78
+
79
+ - The processing is related to specific model.
80
+
81
+ - The processing is related to data split.
82
+ """
83
+
84
+ def __init__(
85
+ self,
86
+ handler: Union[Dict, DataHandler],
87
+ segments: Dict[Text, Tuple],
88
+ fetch_kwargs: Dict = {},
89
+ **kwargs,
90
+ ):
91
+ """
92
+ Setup the underlying data.
93
+
94
+ Parameters
95
+ ----------
96
+ handler : Union[dict, DataHandler]
97
+ handler could be:
98
+
99
+ - instance of `DataHandler`
100
+
101
+ - config of `DataHandler`. Please refer to `DataHandler`
102
+
103
+ segments : dict
104
+ Describe the options to segment the data.
105
+ Here are some examples:
106
+
107
+ .. code-block::
108
+
109
+ 1) 'segments': {
110
+ 'train': ("2008-01-01", "2014-12-31"),
111
+ 'valid': ("2017-01-01", "2020-08-01",),
112
+ 'test': ("2015-01-01", "2016-12-31",),
113
+ }
114
+ 2) 'segments': {
115
+ 'insample': ("2008-01-01", "2014-12-31"),
116
+ 'outsample': ("2017-01-01", "2020-08-01",),
117
+ }
118
+ """
119
+ self.handler: DataHandler = init_instance_by_config(handler, accept_types=DataHandler)
120
+ self.segments = segments.copy()
121
+ self.fetch_kwargs = copy(fetch_kwargs)
122
+ super().__init__(**kwargs)
123
+
124
+ def config(self, handler_kwargs: dict = None, **kwargs):
125
+ """
126
+ Initialize the DatasetH
127
+
128
+ Parameters
129
+ ----------
130
+ handler_kwargs : dict
131
+ Config of DataHandler, which could include the following arguments:
132
+
133
+ - arguments of DataHandler.conf_data, such as 'instruments', 'start_time' and 'end_time'.
134
+
135
+ kwargs : dict
136
+ Config of DatasetH, such as
137
+
138
+ - segments : dict
139
+ Config of segments which is same as 'segments' in self.__init__
140
+
141
+ """
142
+ if handler_kwargs is not None:
143
+ self.handler.config(**handler_kwargs)
144
+ if "segments" in kwargs:
145
+ self.segments = deepcopy(kwargs.pop("segments"))
146
+ super().config(**kwargs)
147
+
148
+ def setup_data(self, handler_kwargs: dict = None, **kwargs):
149
+ """
150
+ Setup the Data
151
+
152
+ Parameters
153
+ ----------
154
+ handler_kwargs : dict
155
+ init arguments of DataHandler, which could include the following arguments:
156
+
157
+ - init_type : Init Type of Handler
158
+
159
+ - enable_cache : whether to enable cache
160
+
161
+ """
162
+ super().setup_data(**kwargs)
163
+ if handler_kwargs is not None:
164
+ self.handler.setup_data(**handler_kwargs)
165
+
166
+ def __repr__(self):
167
+ return "{name}(handler={handler}, segments={segments})".format(
168
+ name=self.__class__.__name__, handler=self.handler, segments=self.segments
169
+ )
170
+
171
+ def _prepare_seg(self, slc, **kwargs):
172
+ """
173
+ Give a query, retrieve the according data
174
+
175
+ Parameters
176
+ ----------
177
+ slc : please refer to the docs of `prepare`
178
+ NOTE: it may not be an instance of slice. It may be a segment of `segments` from `def prepare`
179
+ """
180
+ if hasattr(self, "fetch_kwargs"):
181
+ return self.handler.fetch(slc, **kwargs, **self.fetch_kwargs)
182
+ else:
183
+ return self.handler.fetch(slc, **kwargs)
184
+
185
+ def prepare(
186
+ self,
187
+ segments: Union[List[Text], Tuple[Text], Text, slice, pd.Index],
188
+ col_set=DataHandler.CS_ALL,
189
+ data_key=DataHandlerLP.DK_I,
190
+ **kwargs,
191
+ ) -> Union[List[pd.DataFrame], pd.DataFrame]:
192
+ """
193
+ Prepare the data for learning and inference.
194
+
195
+ Parameters
196
+ ----------
197
+ segments : Union[List[Text], Tuple[Text], Text, slice]
198
+ Describe the scope of the data to be prepared
199
+ Here are some examples:
200
+
201
+ - 'train'
202
+
203
+ - ['train', 'valid']
204
+
205
+ col_set : str
206
+ The col_set will be passed to self.handler when fetching data.
207
+ TODO: make it automatic:
208
+
209
+ - select DK_I for test data
210
+ - select DK_L for training data.
211
+ data_key : str
212
+ The data to fetch: DK_*
213
+ Default is DK_I, which indicate fetching data for **inference**.
214
+
215
+ kwargs :
216
+ The parameters that kwargs may contain:
217
+ flt_col : str
218
+ It only exists in TSDatasetH, can be used to add a column of data(True or False) to filter data.
219
+ This parameter is only supported when it is an instance of TSDatasetH.
220
+
221
+ Returns
222
+ -------
223
+ Union[List[pd.DataFrame], pd.DataFrame]:
224
+
225
+ Raises
226
+ ------
227
+ NotImplementedError:
228
+ """
229
+ seg_kwargs = {"col_set": col_set, "data_key": data_key}
230
+ seg_kwargs.update(kwargs)
231
+
232
+ # Conflictions may happen here
233
+ # - The fetched data and the segment key may both be string
234
+ # To resolve the confliction
235
+ # - The segment name will have higher priorities
236
+
237
+ # 1) Use it as segment name first
238
+ # 1.1) directly fetch split like "train" "valid" "test"
239
+ if isinstance(segments, str) and segments in self.segments:
240
+ return self._prepare_seg(self.segments[segments], **seg_kwargs)
241
+
242
+ # 1.2) fetch multiple splits like ["train", "valid"] ["train", "valid", "test"]
243
+ if isinstance(segments, (list, tuple)) and all(seg in self.segments for seg in segments):
244
+ return [self._prepare_seg(self.segments[seg], **seg_kwargs) for seg in segments]
245
+
246
+ # 2) Use pass it directly to prepare a single seg
247
+ return self._prepare_seg(segments, **seg_kwargs)
248
+
249
+ # helper functions
250
+ @staticmethod
251
+ def get_min_time(segments):
252
+ return DatasetH._get_extrema(segments, 0, (lambda a, b: a > b))
253
+
254
+ @staticmethod
255
+ def get_max_time(segments):
256
+ return DatasetH._get_extrema(segments, 1, (lambda a, b: a < b))
257
+
258
+ @staticmethod
259
+ def _get_extrema(segments, idx: int, cmp: Callable, key_func=pd.Timestamp):
260
+ """it will act like sort and return the max value or None"""
261
+ candidate = None
262
+ for _, seg in segments.items():
263
+ point = seg[idx]
264
+ if point is None:
265
+ # None indicates unbounded, return directly
266
+ return None
267
+ elif candidate is None or cmp(key_func(candidate), key_func(point)):
268
+ candidate = point
269
+ return candidate
270
+
271
+
272
+ class TSDataSampler:
273
+ """
274
+ (T)ime-(S)eries DataSampler
275
+ This is the result of TSDatasetH
276
+
277
+ It works like `torch.data.utils.Dataset`, it provides a very convenient interface for constructing time-series
278
+ dataset based on tabular data.
279
+ - On time step dimension, the smaller index indicates the historical data and the larger index indicates the future
280
+ data.
281
+
282
+ If user have further requirements for processing data, user could process them based on `TSDataSampler` or create
283
+ more powerful subclasses.
284
+
285
+ Known Issues:
286
+ - For performance issues, this Sampler will convert dataframe into arrays for better performance. This could result
287
+ in a different data type
288
+
289
+
290
+ Indices design:
291
+ TSDataSampler has a index mechanism to help users query time-series data efficiently.
292
+
293
+ The definition of related variables:
294
+ data_arr: np.ndarray
295
+ The original data. it will contains all the original data.
296
+ The querying are often for time-series of a specific stock.
297
+ By leveraging this data charactoristics to speed up querying, the multi-index of data_arr is rearranged in (instrument, datetime) order
298
+
299
+ data_index: pd.MultiIndex with index order <instrument, datetime>
300
+ it has the same shape with `idx_map`. Each elements of them are expected to be aligned.
301
+
302
+ idx_map: np.ndarray
303
+ It is the indexable data. It originates from data_arr, and then filtered by 1) `start` and `end` 2) `flt_data`
304
+ The extra data in data_arr is useful in following cases
305
+ 1) creating meaningful time series data before `start` instead of padding them with zeros
306
+ 2) some data are excluded by `flt_data` (e.g. no <X, y> sample pair for that index). but they are still used in time-series in X
307
+
308
+ Finnally, it will look like.
309
+
310
+ array([[ 0, 0],
311
+ [ 1, 0],
312
+ [ 2, 0],
313
+ ...,
314
+ [241, 348],
315
+ [242, 348],
316
+ [243, 348]], dtype=int32)
317
+
318
+ It list all indexable data(some data only used in historical time series data may not be indexabla), the values are the corresponding row and col in idx_df
319
+ idx_df: pd.DataFrame
320
+ It aims to map the <datetime, instrument> key to the original position in data_arr
321
+
322
+ For example, it may look like (NOTE: the index for a instrument time-series is continoues in memory)
323
+
324
+ instrument SH600000 SH600008 SH600009 SH600010 SH600011 SH600015 ...
325
+ datetime
326
+ 2017-01-03 0 242 473 717 NaN 974 ...
327
+ 2017-01-04 1 243 474 718 NaN 975 ...
328
+ 2017-01-05 2 244 475 719 NaN 976 ...
329
+ 2017-01-06 3 245 476 720 NaN 977 ...
330
+
331
+ With these two indices(idx_map, idx_df) and original data(data_arr), we can make the following queries fast (implemented in __getitem__)
332
+ (1) Get the i-th indexable sample(time-series): (indexable sample index) -> [idx_map] -> (row col) -> [idx_df] -> (index in data_arr)
333
+ (2) Get the specific sample by <datetime, instrument>: (<datetime, instrument>, i.e. <row, col>) -> [idx_df] -> (index in data_arr)
334
+ (3) Get the index of a time-series data: (get the <row, col>, refer to (1), (2)) -> [idx_df] -> (all indices in data_arr for time-series)
335
+ """
336
+
337
+ # Please refer to the docstring of TSDataSampler for the definition of following attributes
338
+ data_arr: np.ndarray
339
+ data_index: pd.MultiIndex
340
+ idx_map: np.ndarray
341
+ idx_df: pd.DataFrame
342
+
343
+ def __init__(
344
+ self,
345
+ data: pd.DataFrame,
346
+ start,
347
+ end,
348
+ step_len: int,
349
+ fillna_type: str = "none",
350
+ dtype=None,
351
+ flt_data=None,
352
+ ):
353
+ """
354
+ Build a dataset which looks like torch.data.utils.Dataset.
355
+
356
+ Parameters
357
+ ----------
358
+ data : pd.DataFrame
359
+ The raw tabular data whose index order is <"datetime", "instrument">
360
+ start :
361
+ The indexable start time
362
+ end :
363
+ The indexable end time
364
+ step_len : int
365
+ The length of the time-series step
366
+ fillna_type : int
367
+ How will qlib handle the sample if there is on sample in a specific date.
368
+ none:
369
+ fill with np.nan
370
+ ffill:
371
+ ffill with previous sample
372
+ ffill+bfill:
373
+ ffill with previous samples first and fill with later samples second
374
+ flt_data : pd.Series
375
+ a column of data(True or False) to filter data. Its index order is <"datetime", "instrument">
376
+ This feature is essential because:
377
+ - We want some sample not included due to label-based filtering, but we can't filter them at the beginning due to the features is still important in the feature.
378
+ None:
379
+ kepp all data
380
+
381
+ """
382
+ self.start = start
383
+ self.end = end
384
+ self.step_len = step_len
385
+ self.fillna_type = fillna_type
386
+ assert get_level_index(data, "datetime") == 0
387
+ self.data = data.swaplevel().sort_index().copy()
388
+ data.drop(
389
+ data.columns, axis=1, inplace=True
390
+ ) # data is useless since it's passed to a transposed one, hard code to free the memory of this dataframe to avoid three big dataframe in the memory(including: data, self.data, self.data_arr)
391
+
392
+ kwargs = {"object": self.data}
393
+ if dtype is not None:
394
+ kwargs["dtype"] = dtype
395
+
396
+ self.data_arr = np.array(**kwargs) # Get index from numpy.array will much faster than DataFrame.values!
397
+ # NOTE:
398
+ # - append last line with full NaN for better performance in `__getitem__`
399
+ # - Keep the same dtype will result in a better performance
400
+ self.data_arr = np.append(
401
+ self.data_arr,
402
+ np.full((1, self.data_arr.shape[1]), np.nan, dtype=self.data_arr.dtype),
403
+ axis=0,
404
+ )
405
+ self.nan_idx = len(self.data_arr) - 1 # The last line is all NaN; setting it to -1 can cause bug #1716
406
+
407
+ # the data type will be changed
408
+ # The index of usable data is between start_idx and end_idx
409
+ self.idx_df, self.idx_map = self.build_index(self.data)
410
+ self.data_index = deepcopy(self.data.index)
411
+
412
+ if flt_data is not None:
413
+ if isinstance(flt_data, pd.DataFrame):
414
+ assert len(flt_data.columns) == 1
415
+ flt_data = flt_data.iloc[:, 0]
416
+ # NOTE: bool(np.nan) is True !!!!!!!!
417
+ # make sure reindex comes first. Otherwise extra NaN may appear.
418
+ flt_data = flt_data.swaplevel()
419
+ flt_data = flt_data.reindex(self.data_index).fillna(False).astype(bool)
420
+ self.flt_data = flt_data.values
421
+ self.idx_map = self.flt_idx_map(self.flt_data, self.idx_map)
422
+ self.data_index = self.data_index[np.where(self.flt_data)[0]]
423
+ self.idx_map = self.idx_map2arr(self.idx_map)
424
+ self.idx_map, self.data_index = self.slice_idx_map_and_data_index(
425
+ self.idx_map, self.idx_df, self.data_index, start, end
426
+ )
427
+
428
+ self.idx_arr = np.array(self.idx_df.values, dtype=np.float64) # for better performance
429
+ del self.data # save memory
430
+
431
+ @staticmethod
432
+ def slice_idx_map_and_data_index(
433
+ idx_map,
434
+ idx_df,
435
+ data_index,
436
+ start,
437
+ end,
438
+ ):
439
+ assert (
440
+ len(idx_map) == data_index.shape[0]
441
+ ) # make sure idx_map and data_index is same so index of idx_map can be used on data_index
442
+
443
+ start_row_idx, end_row_idx = idx_df.index.slice_locs(start=time_to_slc_point(start), end=time_to_slc_point(end))
444
+
445
+ time_flter_idx = (idx_map[:, 0] < end_row_idx) & (idx_map[:, 0] >= start_row_idx)
446
+ return idx_map[time_flter_idx], data_index[time_flter_idx]
447
+
448
+ @staticmethod
449
+ def idx_map2arr(idx_map):
450
+ # pytorch data sampler will have better memory control without large dict or list
451
+ # - https://github.com/pytorch/pytorch/issues/13243
452
+ # - https://github.com/airctic/icevision/issues/613
453
+ # So we convert the dict into int array.
454
+ # The arr_map is expected to behave the same as idx_map
455
+
456
+ dtype = np.int32
457
+ # set a index out of bound to indicate the none existing
458
+ no_existing_idx = (np.iinfo(dtype).max, np.iinfo(dtype).max)
459
+
460
+ max_idx = max(idx_map.keys())
461
+ arr_map = []
462
+ for i in range(max_idx + 1):
463
+ arr_map.append(idx_map.get(i, no_existing_idx))
464
+ arr_map = np.array(arr_map, dtype=dtype)
465
+ return arr_map
466
+
467
+ @staticmethod
468
+ def flt_idx_map(flt_data, idx_map):
469
+ idx = 0
470
+ new_idx_map = {}
471
+ for i, exist in enumerate(flt_data):
472
+ if exist:
473
+ new_idx_map[idx] = idx_map[i]
474
+ idx += 1
475
+ return new_idx_map
476
+
477
+ def get_index(self):
478
+ """
479
+ Get the pandas index of the data, it will be useful in following scenarios
480
+ - Special sampler will be used (e.g. user want to sample day by day)
481
+ """
482
+ return self.data_index.swaplevel() # to align the order of multiple index of original data received by __init__
483
+
484
+ def config(self, **kwargs):
485
+ # Config the attributes
486
+ for k, v in kwargs.items():
487
+ setattr(self, k, v)
488
+
489
+ @staticmethod
490
+ def build_index(data: pd.DataFrame) -> Tuple[pd.DataFrame, dict]:
491
+ """
492
+ The relation of the data
493
+
494
+ Parameters
495
+ ----------
496
+ data : pd.DataFrame
497
+ A DataFrame with index in order <instrument, datetime>
498
+
499
+ RSQR5 RESI5 WVMA5 LABEL0
500
+ instrument datetime
501
+ SH600000 2017-01-03 0.016389 0.461632 -1.154788 -0.048056
502
+ 2017-01-04 0.884545 -0.110597 -1.059332 -0.030139
503
+ 2017-01-05 0.507540 -0.535493 -1.099665 -0.644983
504
+ 2017-01-06 -1.267771 -0.669685 -1.636733 0.295366
505
+ 2017-01-09 0.339346 0.074317 -0.984989 0.765540
506
+
507
+ Returns
508
+ -------
509
+ Tuple[pd.DataFrame, dict]:
510
+ 1) the first element: reshape the original index into a <datetime(row), instrument(column)> 2D dataframe
511
+ instrument SH600000 SH600008 SH600009 SH600010 SH600011 SH600015 ...
512
+ datetime
513
+ 2017-01-03 0 242 473 717 NaN 974 ...
514
+ 2017-01-04 1 243 474 718 NaN 975 ...
515
+ 2017-01-05 2 244 475 719 NaN 976 ...
516
+ 2017-01-06 3 245 476 720 NaN 977 ...
517
+ 2) the second element: {<original index>: <row, col>}
518
+ """
519
+ # object incase of pandas converting int to float
520
+ idx_df = pd.Series(range(data.shape[0]), index=data.index, dtype=object)
521
+ idx_df = lazy_sort_index(idx_df.unstack())
522
+ # NOTE: the correctness of `__getitem__` depends on columns sorted here
523
+ idx_df = lazy_sort_index(idx_df, axis=1).T
524
+
525
+ idx_map = {}
526
+ for i, (_, row) in enumerate(idx_df.iterrows()):
527
+ for j, real_idx in enumerate(row):
528
+ if not np.isnan(real_idx):
529
+ idx_map[real_idx] = (i, j)
530
+ return idx_df, idx_map
531
+
532
+ @property
533
+ def empty(self):
534
+ return len(self) == 0
535
+
536
+ def _get_indices(self, row: int, col: int) -> np.array:
537
+ """
538
+ get series indices of self.data_arr from the row, col indices of self.idx_df
539
+
540
+ Parameters
541
+ ----------
542
+ row : int
543
+ the row in self.idx_df
544
+ col : int
545
+ the col in self.idx_df
546
+
547
+ Returns
548
+ -------
549
+ np.array:
550
+ The indices of data of the data
551
+ """
552
+ indices = self.idx_arr[max(row - self.step_len + 1, 0) : row + 1, col]
553
+
554
+ if len(indices) < self.step_len:
555
+ indices = np.concatenate([np.full((self.step_len - len(indices),), np.nan), indices])
556
+
557
+ if self.fillna_type == "ffill":
558
+ indices = np_ffill(indices)
559
+ elif self.fillna_type == "ffill+bfill":
560
+ indices = np_ffill(np_ffill(indices)[::-1])[::-1]
561
+ else:
562
+ assert self.fillna_type == "none"
563
+ return indices
564
+
565
+ def _get_row_col(self, idx) -> Tuple[int]:
566
+ """
567
+ get the col index and row index of a given sample index in self.idx_df
568
+
569
+ Parameters
570
+ ----------
571
+ idx :
572
+ the input of `__getitem__`
573
+
574
+ Returns
575
+ -------
576
+ Tuple[int]:
577
+ the row and col index
578
+ """
579
+ # The the right row number `i` and col number `j` in idx_df
580
+ if isinstance(idx, (int, np.integer)):
581
+ real_idx = idx
582
+ if 0 <= real_idx < len(self.idx_map):
583
+ i, j = self.idx_map[real_idx] # TODO: The performance of this line is not good
584
+ else:
585
+ raise KeyError(f"{real_idx} is out of [0, {len(self.idx_map)})")
586
+ elif isinstance(idx, tuple):
587
+ # <TSDataSampler object>["datetime", "instruments"]
588
+ date, inst = idx
589
+ date = pd.Timestamp(date)
590
+ i = bisect.bisect_right(self.idx_df.index, date) - 1
591
+ # NOTE: This relies on the idx_df columns sorted in `__init__`
592
+ j = bisect.bisect_left(self.idx_df.columns, inst)
593
+ else:
594
+ raise NotImplementedError(f"This type of input is not supported")
595
+ return i, j
596
+
597
+ def __getitem__(self, idx: Union[int, Tuple[object, str], List[int]]):
598
+ """
599
+ # We have two method to get the time-series of a sample
600
+ tsds is a instance of TSDataSampler
601
+
602
+ # 1) sample by int index directly
603
+ tsds[len(tsds) - 1]
604
+
605
+ # 2) sample by <datetime,instrument> index
606
+ tsds['2016-12-31', "SZ300315"]
607
+
608
+ # The return value will be similar to the data retrieved by following code
609
+ df.loc(axis=0)['2015-01-01':'2016-12-31', "SZ300315"].iloc[-30:]
610
+
611
+ Parameters
612
+ ----------
613
+ idx : Union[int, Tuple[object, str]]
614
+ """
615
+ # Multi-index type
616
+ mtit = (list, np.ndarray)
617
+ if isinstance(idx, mtit):
618
+ indices = [self._get_indices(*self._get_row_col(i)) for i in idx]
619
+ indices = np.concatenate(indices)
620
+ else:
621
+ indices = self._get_indices(*self._get_row_col(idx))
622
+
623
+ # 1) for better performance, use the last nan line for padding the lost date
624
+ # 2) In case of precision problems. We use np.float64. # TODO: I'm not sure if whether np.float64 will result in
625
+ # precision problems. It will not cause any problems in my tests at least
626
+ indices = np.nan_to_num(indices.astype(np.float64), nan=self.nan_idx).astype(int)
627
+
628
+ if (np.diff(indices) == 1).all(): # slicing instead of indexing for speeding up.
629
+ data = self.data_arr[indices[0] : indices[-1] + 1]
630
+ else:
631
+ data = self.data_arr[indices]
632
+ if isinstance(idx, mtit):
633
+ # if we get multiple indexes, addition dimension should be added.
634
+ # <sample_idx, step_idx, feature_idx>
635
+ data = data.reshape(-1, self.step_len, *data.shape[1:])
636
+ return data
637
+
638
+ def __len__(self):
639
+ return len(self.idx_map)
640
+
641
+
642
+ class TSDatasetH(DatasetH):
643
+ """
644
+ (T)ime-(S)eries Dataset (H)andler
645
+
646
+
647
+ Convert the tabular data to Time-Series data
648
+
649
+ Requirements analysis
650
+
651
+ The typical workflow of a user to get time-series data for an sample
652
+ - process features
653
+ - slice proper data from data handler: dimension of sample <feature, >
654
+ - Build relation of samples by <time, instrument> index
655
+ - Be able to sample times series of data <timestep, feature>
656
+ - It will be better if the interface is like "torch.utils.data.Dataset"
657
+ - User could build customized batch based on the data
658
+ - The dimension of a batch of data <batch_idx, feature, timestep>
659
+ """
660
+
661
+ DEFAULT_STEP_LEN = 30
662
+
663
+ def __init__(self, step_len=DEFAULT_STEP_LEN, flt_col: Optional[str] = None, **kwargs):
664
+ self.step_len = step_len
665
+ self.flt_col = flt_col
666
+ super().__init__(**kwargs)
667
+
668
+ def config(self, **kwargs):
669
+ if "step_len" in kwargs:
670
+ self.step_len = kwargs.pop("step_len")
671
+ super().config(**kwargs)
672
+
673
+ def setup_data(self, **kwargs):
674
+ super().setup_data(**kwargs)
675
+ # make sure the calendar is updated to latest when loading data from new config
676
+ cal = self.handler.fetch(col_set=self.handler.CS_RAW).index.get_level_values("datetime").unique()
677
+ self.cal = sorted(cal)
678
+
679
+ @staticmethod
680
+ def _extend_slice(slc: slice, cal: list, step_len: int) -> slice:
681
+ # Dataset decide how to slice data(Get more data for timeseries).
682
+ start, end = slc.start, slc.stop
683
+ start_idx = bisect.bisect_left(cal, pd.Timestamp(start))
684
+ pad_start_idx = max(0, start_idx - step_len)
685
+ pad_start = cal[pad_start_idx]
686
+ return slice(pad_start, end)
687
+
688
+ def _prepare_seg(self, slc: slice, **kwargs) -> TSDataSampler:
689
+ """
690
+ split the _prepare_raw_seg is to leave a hook for data preprocessing before creating processing data
691
+ NOTE: TSDatasetH only support slc segment on datetime !!!
692
+ """
693
+ dtype = kwargs.pop("dtype", None)
694
+ if not isinstance(slc, slice):
695
+ slc = slice(*slc)
696
+ if (flt_col := kwargs.pop("flt_col", None)) is None:
697
+ flt_col = self.flt_col
698
+
699
+ # TSDatasetH will retrieve more data for complete time-series
700
+ ext_slice = self._extend_slice(slc, self.cal, self.step_len)
701
+ data = super()._prepare_seg(ext_slice, **kwargs)
702
+
703
+ flt_kwargs = deepcopy(kwargs)
704
+ if flt_col is not None:
705
+ flt_kwargs["col_set"] = flt_col
706
+ flt_data = super()._prepare_seg(ext_slice, **flt_kwargs)
707
+ assert len(flt_data.columns) == 1
708
+ else:
709
+ flt_data = None
710
+
711
+ tsds = TSDataSampler(
712
+ data=data,
713
+ start=slc.start,
714
+ end=slc.stop,
715
+ step_len=self.step_len,
716
+ dtype=dtype,
717
+ flt_data=flt_data,
718
+ )
719
+ return tsds
720
+
721
+
722
+ __all__ = ["Optional", "Dataset", "DatasetH"]
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/handler.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ # coding=utf-8
5
+ from abc import abstractmethod
6
+ import warnings
7
+ from typing import Callable, Union, Tuple, List, Iterator, Optional
8
+
9
+ import pandas as pd
10
+
11
+ from qlib.typehint import Literal
12
+ from ...log import get_module_logger, TimeInspector
13
+ from ...utils import init_instance_by_config
14
+ from ...utils.serial import Serializable
15
+ from .utils import fetch_df_by_index, fetch_df_by_col
16
+ from ...utils import lazy_sort_index
17
+ from .loader import DataLoader
18
+
19
+ from . import processor as processor_module
20
+ from . import loader as data_loader_module
21
+
22
+ DATA_KEY_TYPE = Literal["raw", "infer", "learn"]
23
+
24
+
25
+ class DataHandlerABC(Serializable):
26
+ """
27
+ Interface for data handler.
28
+
29
+ This class does not assume the internal data structure of the data handler.
30
+ It only defines the interface for external users (uses DataFrame as the internal data structure).
31
+
32
+ In the future, the data handler's more detailed implementation should be refactored. Here are some guidelines:
33
+
34
+ It covers several components:
35
+
36
+ - [data loader] -> internal representation of the data -> data preprocessing -> interface adaptor for the fetch interface
37
+ - The workflow to combine them all:
38
+ The workflow may be very complicated. DataHandlerLP is one of the practices, but it can't satisfy all the requirements.
39
+ So leaving the flexibility to the user to implement the workflow is a more reasonable choice.
40
+ """
41
+
42
+ def __init__(self, *args, **kwargs): # pylint: disable=W0246
43
+ """
44
+ We should define how to get ready for the fetching.
45
+ """
46
+ super().__init__(*args, **kwargs)
47
+
48
+ CS_ALL = "__all" # return all columns with single-level index column
49
+ CS_RAW = "__raw" # return raw data with multi-level index column
50
+
51
+ # data key
52
+ DK_R: DATA_KEY_TYPE = "raw"
53
+ DK_I: DATA_KEY_TYPE = "infer"
54
+ DK_L: DATA_KEY_TYPE = "learn"
55
+
56
+ @abstractmethod
57
+ def fetch(
58
+ self,
59
+ selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
60
+ level: Union[str, int] = "datetime",
61
+ col_set: Union[str, List[str]] = CS_ALL,
62
+ data_key: DATA_KEY_TYPE = DK_I,
63
+ ) -> pd.DataFrame:
64
+ pass
65
+
66
+
67
+ class DataHandler(DataHandlerABC):
68
+ """
69
+ The motivation of DataHandler:
70
+
71
+ - It provides an implementation of BaseDataHandler that we implement with:
72
+ - Handling responses with an internal loaded DataFrame
73
+ - The DataFrame is loaded by a data loader.
74
+
75
+ The steps to using a handler
76
+ 1. initialized data handler (call by `init`).
77
+ 2. use the data.
78
+
79
+
80
+ The data handler try to maintain a handler with 2 level.
81
+ `datetime` & `instruments`.
82
+
83
+ Any order of the index level can be supported (The order will be implied in the data).
84
+ The order <`datetime`, `instruments`> will be used when the dataframe index name is missed.
85
+
86
+ Example of the data:
87
+ The multi-index of the columns is optional.
88
+
89
+ .. code-block:: text
90
+
91
+ feature label
92
+ $close $volume Ref($close, 1) Mean($close, 3) $high-$low LABEL0
93
+ datetime instrument
94
+ 2010-01-04 SH600000 81.807068 17145150.0 83.737389 83.016739 2.741058 0.0032
95
+ SH600004 13.313329 11800983.0 13.313329 13.317701 0.183632 0.0042
96
+ SH600005 37.796539 12231662.0 38.258602 37.919757 0.970325 0.0289
97
+
98
+
99
+ Tips for improving the performance of datahandler
100
+ - Fetching data with `col_set=CS_RAW` will return the raw data and may avoid pandas from copying the data when calling `loc`
101
+ """
102
+
103
+ _data: pd.DataFrame # underlying data.
104
+
105
+ def __init__(
106
+ self,
107
+ instruments=None,
108
+ start_time=None,
109
+ end_time=None,
110
+ data_loader: Union[dict, str, DataLoader] = None,
111
+ init_data=True,
112
+ fetch_orig=True,
113
+ ):
114
+ """
115
+ Parameters
116
+ ----------
117
+ instruments :
118
+ The stock list to retrieve.
119
+ start_time :
120
+ start_time of the original data.
121
+ end_time :
122
+ end_time of the original data.
123
+ data_loader : Union[dict, str, DataLoader]
124
+ data loader to load the data.
125
+ init_data :
126
+ initialize the original data in the constructor.
127
+ fetch_orig : bool
128
+ Return the original data instead of copy if possible.
129
+ """
130
+
131
+ # Setup data loader
132
+ assert data_loader is not None # to make start_time end_time could have None default value
133
+
134
+ # what data source to load data
135
+ self.data_loader = init_instance_by_config(
136
+ data_loader,
137
+ None if (isinstance(data_loader, dict) and "module_path" in data_loader) else data_loader_module,
138
+ accept_types=DataLoader,
139
+ )
140
+
141
+ # what data to be loaded from data source
142
+ # For IDE auto-completion.
143
+ self.instruments = instruments
144
+ self.start_time = start_time
145
+ self.end_time = end_time
146
+
147
+ self.fetch_orig = fetch_orig
148
+ if init_data:
149
+ with TimeInspector.logt("Init data"):
150
+ self.setup_data()
151
+ super().__init__()
152
+
153
+ def config(self, **kwargs):
154
+ """
155
+ configuration of data.
156
+ # what data to be loaded from data source
157
+
158
+ This method will be used when loading pickled handler from dataset.
159
+ The data will be initialized with different time range.
160
+
161
+ """
162
+ attr_list = {"instruments", "start_time", "end_time"}
163
+ for k, v in kwargs.items():
164
+ if k in attr_list:
165
+ setattr(self, k, v)
166
+
167
+ for attr in attr_list:
168
+ if attr in kwargs:
169
+ kwargs.pop(attr)
170
+
171
+ super().config(**kwargs)
172
+
173
+ def setup_data(self, enable_cache: bool = False):
174
+ """
175
+ Set Up the data in case of running initialization for multiple time
176
+
177
+ It is responsible for maintaining following variable
178
+ 1) self._data
179
+
180
+ Parameters
181
+ ----------
182
+ enable_cache : bool
183
+ default value is false:
184
+
185
+ - if `enable_cache` == True:
186
+
187
+ the processed data will be saved on disk, and handler will load the cached data from the disk directly
188
+ when we call `init` next time
189
+ """
190
+ # Setup data.
191
+ # _data may be with multiple column index level. The outer level indicates the feature set name
192
+ with TimeInspector.logt("Loading data"):
193
+ # make sure the fetch method is based on an index-sorted pd.DataFrame
194
+ self._data = lazy_sort_index(self.data_loader.load(self.instruments, self.start_time, self.end_time))
195
+ # TODO: cache
196
+
197
+ def fetch(
198
+ self,
199
+ selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
200
+ level: Union[str, int] = "datetime",
201
+ col_set: Union[str, List[str]] = DataHandlerABC.CS_ALL,
202
+ data_key: DATA_KEY_TYPE = DataHandlerABC.DK_I,
203
+ squeeze: bool = False,
204
+ proc_func: Optional[Callable] = None,
205
+ ) -> pd.DataFrame:
206
+ """
207
+ fetch data from underlying data source
208
+
209
+ Design motivation:
210
+ - providing a unified interface for underlying data.
211
+ - Potential to make the interface more friendly.
212
+ - User can improve performance when fetching data in this extra layer
213
+
214
+ Parameters
215
+ ----------
216
+ selector : Union[pd.Timestamp, slice, str]
217
+ describe how to select data by index
218
+ It can be categories as following
219
+
220
+ - fetch single index
221
+ - fetch a range of index
222
+
223
+ - a slice range
224
+ - pd.Index for specific indexes
225
+
226
+ Following conflicts may occur
227
+
228
+ - Does ["20200101", "20210101"] mean selecting this slice or these two days?
229
+
230
+ - slice have higher priorities
231
+
232
+ level : Union[str, int]
233
+ which index level to select the data
234
+
235
+ col_set : Union[str, List[str]]
236
+
237
+ - if isinstance(col_set, str):
238
+
239
+ select a set of meaningful, pd.Index columns.(e.g. features, columns)
240
+
241
+ - if col_set == CS_RAW:
242
+
243
+ the raw dataset will be returned.
244
+
245
+ - if isinstance(col_set, List[str]):
246
+
247
+ select several sets of meaningful columns, the returned data has multiple levels
248
+
249
+ proc_func: Callable
250
+
251
+ - Give a hook for processing data before fetching
252
+ - An example to explain the necessity of the hook:
253
+
254
+ - A Dataset learned some processors to process data which is related to data segmentation
255
+ - It will apply them every time when preparing data.
256
+ - The learned processor require the dataframe remains the same format when fitting and applying
257
+ - However the data format will change according to the parameters.
258
+ - So the processors should be applied to the underlayer data.
259
+
260
+ squeeze : bool
261
+ whether squeeze columns and index
262
+
263
+ Returns
264
+ -------
265
+ pd.DataFrame.
266
+ """
267
+ # DataHandler is an example with only one dataframe, so data_key is not used.
268
+ _ = data_key # avoid linting errors (e.g., unused-argument)
269
+ return self._fetch_data(
270
+ data_storage=self._data,
271
+ selector=selector,
272
+ level=level,
273
+ col_set=col_set,
274
+ squeeze=squeeze,
275
+ proc_func=proc_func,
276
+ )
277
+
278
+ def _fetch_data(
279
+ self,
280
+ data_storage,
281
+ selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
282
+ level: Union[str, int] = "datetime",
283
+ col_set: Union[str, List[str]] = DataHandlerABC.CS_ALL,
284
+ squeeze: bool = False,
285
+ proc_func: Callable = None,
286
+ ):
287
+ # This method is extracted for sharing in subclasses
288
+ from .storage import BaseHandlerStorage # pylint: disable=C0415
289
+
290
+ # Following conflicts may occur
291
+ # - Does [20200101", "20210101"] mean selecting this slice or these two days?
292
+ # To solve this issue
293
+ # - slice have higher priorities (except when level is none)
294
+ if isinstance(selector, (tuple, list)) and level is not None:
295
+ # when level is None, the argument will be passed in directly
296
+ # we don't have to convert it into slice
297
+ try:
298
+ selector = slice(*selector)
299
+ except ValueError:
300
+ get_module_logger("DataHandlerLP").info(f"Fail to converting to query to slice. It will used directly")
301
+
302
+ if isinstance(data_storage, pd.DataFrame):
303
+ data_df = data_storage
304
+ if proc_func is not None:
305
+ # FIXME: fetching by time first will be more friendly to `proc_func`
306
+ # Copy in case of `proc_func` changing the data inplace....
307
+ data_df = proc_func(fetch_df_by_index(data_df, selector, level, fetch_orig=self.fetch_orig).copy())
308
+ data_df = fetch_df_by_col(data_df, col_set)
309
+ else:
310
+ # Fetch column first will be more friendly to SepDataFrame
311
+ data_df = fetch_df_by_col(data_df, col_set)
312
+ data_df = fetch_df_by_index(data_df, selector, level, fetch_orig=self.fetch_orig)
313
+ elif isinstance(data_storage, BaseHandlerStorage):
314
+ if proc_func is not None:
315
+ raise ValueError(f"proc_func is not supported by the storage {type(data_storage)}")
316
+ data_df = data_storage.fetch(selector=selector, level=level, col_set=col_set, fetch_orig=self.fetch_orig)
317
+ else:
318
+ raise TypeError(f"data_storage should be pd.DataFrame|HashingStockStorage, not {type(data_storage)}")
319
+
320
+ if squeeze:
321
+ # squeeze columns
322
+ data_df = data_df.squeeze()
323
+ # squeeze index
324
+ if isinstance(selector, (str, pd.Timestamp)):
325
+ data_df = data_df.reset_index(level=level, drop=True)
326
+ return data_df
327
+
328
+ def get_cols(self, col_set=DataHandlerABC.CS_ALL) -> list:
329
+ """
330
+ get the column names
331
+
332
+ Parameters
333
+ ----------
334
+ col_set : str
335
+ select a set of meaningful columns.(e.g. features, columns)
336
+
337
+ Returns
338
+ -------
339
+ list:
340
+ list of column names
341
+ """
342
+ df = self._data.head()
343
+ df = fetch_df_by_col(df, col_set)
344
+ return df.columns.to_list()
345
+
346
+ def get_range_selector(self, cur_date: Union[pd.Timestamp, str], periods: int) -> slice:
347
+ """
348
+ get range selector by number of periods
349
+
350
+ Args:
351
+ cur_date (pd.Timestamp or str): current date
352
+ periods (int): number of periods
353
+ """
354
+ trading_dates = self._data.index.unique(level="datetime")
355
+ cur_loc = trading_dates.get_loc(cur_date)
356
+ pre_loc = cur_loc - periods + 1
357
+ if pre_loc < 0:
358
+ warnings.warn("`periods` is too large. the first date will be returned.")
359
+ pre_loc = 0
360
+ ref_date = trading_dates[pre_loc]
361
+ return slice(ref_date, cur_date)
362
+
363
+ def get_range_iterator(
364
+ self, periods: int, min_periods: Optional[int] = None, **kwargs
365
+ ) -> Iterator[Tuple[pd.Timestamp, pd.DataFrame]]:
366
+ """
367
+ get an iterator of sliced data with given periods
368
+
369
+ Args:
370
+ periods (int): number of periods.
371
+ min_periods (int): minimum periods for sliced dataframe.
372
+ kwargs (dict): will be passed to `self.fetch`.
373
+ """
374
+ trading_dates = self._data.index.unique(level="datetime")
375
+ if min_periods is None:
376
+ min_periods = periods
377
+ for cur_date in trading_dates[min_periods:]:
378
+ selector = self.get_range_selector(cur_date, periods)
379
+ yield cur_date, self.fetch(selector, **kwargs)
380
+
381
+
382
+ class DataHandlerLP(DataHandler):
383
+ """
384
+ Motivation:
385
+ - For the case that we hope using different processor workflows for learning and inference;
386
+
387
+
388
+ DataHandler with **(L)earnable (P)rocessor**
389
+
390
+ This handler will produce three pieces of data in pd.DataFrame format.
391
+
392
+ - DK_R / self._data: the raw data loaded from the loader
393
+ - DK_I / self._infer: the data processed for inference
394
+ - DK_L / self._learn: the data processed for learning model.
395
+
396
+ The motivation of using different processor workflows for learning and inference
397
+ Here are some examples.
398
+
399
+ - The instrument universe for learning and inference may be different.
400
+ - The processing of some samples may rely on label (for example, some samples hit the limit may need extra processing or be dropped).
401
+
402
+ - These processors only apply to the learning phase.
403
+
404
+ Tips for data handler
405
+
406
+ - To reduce the memory cost
407
+
408
+ - `drop_raw=True`: this will modify the data inplace on raw data;
409
+
410
+ - Please note processed data like `self._infer` or `self._learn` are concepts different from `segments` in Qlib's `Dataset` like "train" and "test"
411
+
412
+ - Processed data like `self._infer` or `self._learn` are underlying data processed with different processors
413
+ - `segments` in Qlib's `Dataset` like "train" and "test" are simply the time segmentations when querying data("train" are often before "test" in time-series).
414
+ - For example, you can query `data._infer` processed by `infer_processors` in the "train" time segmentation.
415
+ """
416
+
417
+ # based on `self._data`, _infer and _learn are genrated after processors
418
+ _infer: pd.DataFrame # data for inference
419
+ _learn: pd.DataFrame # data for learning models
420
+
421
+ # map data_key to attribute name
422
+ ATTR_MAP = {DataHandler.DK_R: "_data", DataHandler.DK_I: "_infer", DataHandler.DK_L: "_learn"}
423
+
424
+ # process type
425
+ PTYPE_I = "independent"
426
+ # - self._infer will be processed by shared_processors + infer_processors
427
+ # - self._learn will be processed by shared_processors + learn_processors
428
+
429
+ # NOTE:
430
+ PTYPE_A = "append"
431
+
432
+ # - self._infer will be processed by shared_processors + infer_processors
433
+ # - self._learn will be processed by shared_processors + infer_processors + learn_processors
434
+ # - (e.g. self._infer processed by learn_processors )
435
+
436
+ def __init__(
437
+ self,
438
+ instruments=None,
439
+ start_time=None,
440
+ end_time=None,
441
+ data_loader: Union[dict, str, DataLoader] = None,
442
+ infer_processors: List = [],
443
+ learn_processors: List = [],
444
+ shared_processors: List = [],
445
+ process_type=PTYPE_A,
446
+ drop_raw=False,
447
+ **kwargs,
448
+ ):
449
+ """
450
+ Parameters
451
+ ----------
452
+ infer_processors : list
453
+ - list of <description info> of processors to generate data for inference
454
+
455
+ - example of <description info>:
456
+
457
+ .. code-block::
458
+
459
+ 1) classname & kwargs:
460
+ {
461
+ "class": "MinMaxNorm",
462
+ "kwargs": {
463
+ "fit_start_time": "20080101",
464
+ "fit_end_time": "20121231"
465
+ }
466
+ }
467
+ 2) Only classname:
468
+ "DropnaFeature"
469
+ 3) object instance of Processor
470
+
471
+ learn_processors : list
472
+ similar to infer_processors, but for generating data for learning models
473
+
474
+ process_type: str
475
+ PTYPE_I = 'independent'
476
+
477
+ - self._infer will be processed by infer_processors
478
+
479
+ - self._learn will be processed by learn_processors
480
+
481
+ PTYPE_A = 'append'
482
+
483
+ - self._infer will be processed by infer_processors
484
+
485
+ - self._learn will be processed by infer_processors + learn_processors
486
+
487
+ - (e.g. self._infer processed by learn_processors )
488
+ drop_raw: bool
489
+ Whether to drop the raw data
490
+ """
491
+
492
+ # Setup preprocessor
493
+ self.infer_processors = [] # for lint
494
+ self.learn_processors = [] # for lint
495
+ self.shared_processors = [] # for lint
496
+ for pname in "infer_processors", "learn_processors", "shared_processors":
497
+ for proc in locals()[pname]:
498
+ getattr(self, pname).append(
499
+ init_instance_by_config(
500
+ proc,
501
+ None if (isinstance(proc, dict) and "module_path" in proc) else processor_module,
502
+ accept_types=processor_module.Processor,
503
+ )
504
+ )
505
+
506
+ self.process_type = process_type
507
+ self.drop_raw = drop_raw
508
+ super().__init__(instruments, start_time, end_time, data_loader, **kwargs)
509
+
510
+ def get_all_processors(self):
511
+ return self.shared_processors + self.infer_processors + self.learn_processors
512
+
513
+ def fit(self):
514
+ """
515
+ fit data without processing the data
516
+ """
517
+ for proc in self.get_all_processors():
518
+ with TimeInspector.logt(f"{proc.__class__.__name__}"):
519
+ proc.fit(self._data)
520
+
521
+ def fit_process_data(self):
522
+ """
523
+ fit and process data
524
+
525
+ The input of the `fit` will be the output of the previous processor
526
+ """
527
+ self.process_data(with_fit=True)
528
+
529
+ @staticmethod
530
+ def _run_proc_l(
531
+ df: pd.DataFrame, proc_l: List[processor_module.Processor], with_fit: bool, check_for_infer: bool
532
+ ) -> pd.DataFrame:
533
+ for proc in proc_l:
534
+ if check_for_infer and not proc.is_for_infer():
535
+ raise TypeError("Only processors usable for inference can be used in `infer_processors` ")
536
+ with TimeInspector.logt(f"{proc.__class__.__name__}"):
537
+ if with_fit:
538
+ proc.fit(df)
539
+ df = proc(df)
540
+ return df
541
+
542
+ @staticmethod
543
+ def _is_proc_readonly(proc_l: List[processor_module.Processor]):
544
+ """
545
+ NOTE: it will return True if `len(proc_l) == 0`
546
+ """
547
+ for p in proc_l:
548
+ if not p.readonly():
549
+ return False
550
+ return True
551
+
552
+ def process_data(self, with_fit: bool = False):
553
+ """
554
+ process_data data. Fun `processor.fit` if necessary
555
+
556
+ Notation: (data) [processor]
557
+
558
+ # data processing flow of self.process_type == DataHandlerLP.PTYPE_I
559
+
560
+ .. code-block:: text
561
+
562
+ (self._data)-[shared_processors]-(_shared_df)-[learn_processors]-(_learn_df)
563
+ \\
564
+ -[infer_processors]-(_infer_df)
565
+
566
+ # data processing flow of self.process_type == DataHandlerLP.PTYPE_A
567
+
568
+ .. code-block:: text
569
+
570
+ (self._data)-[shared_processors]-(_shared_df)-[infer_processors]-(_infer_df)-[learn_processors]-(_learn_df)
571
+
572
+ Parameters
573
+ ----------
574
+ with_fit : bool
575
+ The input of the `fit` will be the output of the previous processor
576
+ """
577
+ # shared data processors
578
+ # 1) assign
579
+ _shared_df = self._data
580
+ if not self._is_proc_readonly(self.shared_processors): # avoid modifying the original data
581
+ _shared_df = _shared_df.copy()
582
+ # 2) process
583
+ _shared_df = self._run_proc_l(_shared_df, self.shared_processors, with_fit=with_fit, check_for_infer=True)
584
+
585
+ # data for inference
586
+ # 1) assign
587
+ _infer_df = _shared_df
588
+ if not self._is_proc_readonly(self.infer_processors): # avoid modifying the original data
589
+ _infer_df = _infer_df.copy()
590
+ # 2) process
591
+ _infer_df = self._run_proc_l(_infer_df, self.infer_processors, with_fit=with_fit, check_for_infer=True)
592
+
593
+ self._infer = _infer_df
594
+
595
+ # data for learning
596
+ # 1) assign
597
+ if self.process_type == DataHandlerLP.PTYPE_I:
598
+ _learn_df = _shared_df
599
+ elif self.process_type == DataHandlerLP.PTYPE_A:
600
+ # based on `infer_df` and append the processor
601
+ _learn_df = _infer_df
602
+ else:
603
+ raise NotImplementedError(f"This type of input is not supported")
604
+ if not self._is_proc_readonly(self.learn_processors): # avoid modifying the original data
605
+ _learn_df = _learn_df.copy()
606
+ # 2) process
607
+ _learn_df = self._run_proc_l(_learn_df, self.learn_processors, with_fit=with_fit, check_for_infer=False)
608
+
609
+ self._learn = _learn_df
610
+
611
+ if self.drop_raw:
612
+ del self._data
613
+
614
+ def config(self, processor_kwargs: dict = None, **kwargs):
615
+ """
616
+ configuration of data.
617
+ # what data to be loaded from data source
618
+
619
+ This method will be used when loading pickled handler from dataset.
620
+ The data will be initialized with different time range.
621
+
622
+ """
623
+ super().config(**kwargs)
624
+ if processor_kwargs is not None:
625
+ for processor in self.get_all_processors():
626
+ processor.config(**processor_kwargs)
627
+
628
+ # init type
629
+ IT_FIT_SEQ = "fit_seq" # the input of `fit` will be the output of the previous processor
630
+ IT_FIT_IND = "fit_ind" # the input of `fit` will be the original df
631
+ IT_LS = "load_state" # The state of the object has been load by pickle
632
+
633
+ def setup_data(self, init_type: str = IT_FIT_SEQ, **kwargs):
634
+ """
635
+ Set up the data in case of running initialization for multiple time
636
+
637
+ Parameters
638
+ ----------
639
+ init_type : str
640
+ The type `IT_*` listed above.
641
+ enable_cache : bool
642
+ default value is false:
643
+
644
+ - if `enable_cache` == True:
645
+
646
+ the processed data will be saved on disk, and handler will load the cached data from the disk directly
647
+ when we call `init` next time
648
+ """
649
+ # init raw data
650
+ super().setup_data(**kwargs)
651
+
652
+ with TimeInspector.logt("fit & process data"):
653
+ if init_type == DataHandlerLP.IT_FIT_IND:
654
+ self.fit()
655
+ self.process_data()
656
+ elif init_type == DataHandlerLP.IT_LS:
657
+ self.process_data()
658
+ elif init_type == DataHandlerLP.IT_FIT_SEQ:
659
+ self.fit_process_data()
660
+ else:
661
+ raise NotImplementedError(f"This type of input is not supported")
662
+
663
+ # TODO: Be able to cache handler data. Save the memory for data processing
664
+
665
+ def _get_df_by_key(self, data_key: DATA_KEY_TYPE = DataHandlerABC.DK_I) -> pd.DataFrame:
666
+ if data_key == self.DK_R and self.drop_raw:
667
+ raise AttributeError(
668
+ "DataHandlerLP has not attribute _data, please set drop_raw = False if you want to use raw data"
669
+ )
670
+ df = getattr(self, self.ATTR_MAP[data_key])
671
+ return df
672
+
673
+ def fetch(
674
+ self,
675
+ selector: Union[pd.Timestamp, slice, str] = slice(None, None),
676
+ level: Union[str, int] = "datetime",
677
+ col_set=DataHandler.CS_ALL,
678
+ data_key: DATA_KEY_TYPE = DataHandler.DK_I,
679
+ squeeze: bool = False,
680
+ proc_func: Callable = None,
681
+ ) -> pd.DataFrame:
682
+ """
683
+ fetch data from underlying data source
684
+
685
+ Parameters
686
+ ----------
687
+ selector : Union[pd.Timestamp, slice, str]
688
+ describe how to select data by index.
689
+ level : Union[str, int]
690
+ which index level to select the data.
691
+ col_set : str
692
+ select a set of meaningful columns.(e.g. features, columns).
693
+ data_key : str
694
+ the data to fetch: DK_*.
695
+ proc_func: Callable
696
+ please refer to the doc of DataHandler.fetch
697
+
698
+ Returns
699
+ -------
700
+ pd.DataFrame:
701
+ """
702
+
703
+ return self._fetch_data(
704
+ data_storage=self._get_df_by_key(data_key),
705
+ selector=selector,
706
+ level=level,
707
+ col_set=col_set,
708
+ squeeze=squeeze,
709
+ proc_func=proc_func,
710
+ )
711
+
712
+ def get_cols(self, col_set=DataHandler.CS_ALL, data_key: DATA_KEY_TYPE = DataHandlerABC.DK_I) -> list:
713
+ """
714
+ get the column names
715
+
716
+ Parameters
717
+ ----------
718
+ col_set : str
719
+ select a set of meaningful columns.(e.g. features, columns).
720
+ data_key : DATA_KEY_TYPE
721
+ the data to fetch: DK_*.
722
+
723
+ Returns
724
+ -------
725
+ list:
726
+ list of column names
727
+ """
728
+ df = self._get_df_by_key(data_key).head()
729
+ df = fetch_df_by_col(df, col_set)
730
+ return df.columns.to_list()
731
+
732
+ @classmethod
733
+ def cast(cls, handler: "DataHandlerLP") -> "DataHandlerLP":
734
+ """
735
+ Motivation
736
+
737
+ - A user creates a datahandler in his customized package. Then he wants to share the processed handler to
738
+ other users without introduce the package dependency and complicated data processing logic.
739
+ - This class make it possible by casting the class to DataHandlerLP and only keep the processed data
740
+
741
+ Parameters
742
+ ----------
743
+ handler : DataHandlerLP
744
+ A subclass of DataHandlerLP
745
+
746
+ Returns
747
+ -------
748
+ DataHandlerLP:
749
+ the converted processed data
750
+ """
751
+ new_hd: DataHandlerLP = object.__new__(DataHandlerLP)
752
+ new_hd.from_cast = True # add a mark for the cast instance
753
+
754
+ for key in list(DataHandlerLP.ATTR_MAP.values()) + [
755
+ "instruments",
756
+ "start_time",
757
+ "end_time",
758
+ "fetch_orig",
759
+ "drop_raw",
760
+ ]:
761
+ setattr(new_hd, key, getattr(handler, key, None))
762
+ return new_hd
763
+
764
+ @classmethod
765
+ def from_df(cls, df: pd.DataFrame) -> "DataHandlerLP":
766
+ """
767
+ Motivation:
768
+ - When user want to get a quick data handler.
769
+
770
+ The created data handler will have only one shared Dataframe without processors.
771
+ After creating the handler, user may often want to dump the handler for reuse
772
+ Here is a typical use case
773
+
774
+ .. code-block:: python
775
+
776
+ from qlib.data.dataset import DataHandlerLP
777
+ dh = DataHandlerLP.from_df(df)
778
+ dh.to_pickle(fname, dump_all=True)
779
+
780
+ TODO:
781
+ - The StaticDataLoader is quite slow. It don't have to copy the data again...
782
+
783
+ """
784
+ loader = data_loader_module.StaticDataLoader(df)
785
+ return cls(data_loader=loader)
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/loader.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ import abc
5
+ from pathlib import Path
6
+ import warnings
7
+ import pandas as pd
8
+
9
+ from typing import Tuple, Union, List, Dict
10
+
11
+ from qlib.data import D
12
+ from qlib.utils import load_dataset, init_instance_by_config, time_to_slc_point
13
+ from qlib.utils.pickle_utils import restricted_pickle_load
14
+ from qlib.log import get_module_logger
15
+ from qlib.utils.serial import Serializable
16
+
17
+
18
+ class DataLoader(abc.ABC):
19
+ """
20
+ DataLoader is designed for loading raw data from original data source.
21
+ """
22
+
23
+ @abc.abstractmethod
24
+ def load(self, instruments, start_time=None, end_time=None) -> pd.DataFrame:
25
+ """
26
+ load the data as pd.DataFrame.
27
+
28
+ Example of the data (The multi-index of the columns is optional.):
29
+
30
+ .. code-block:: text
31
+
32
+ feature label
33
+ $close $volume Ref($close, 1) Mean($close, 3) $high-$low LABEL0
34
+ datetime instrument
35
+ 2010-01-04 SH600000 81.807068 17145150.0 83.737389 83.016739 2.741058 0.0032
36
+ SH600004 13.313329 11800983.0 13.313329 13.317701 0.183632 0.0042
37
+ SH600005 37.796539 12231662.0 38.258602 37.919757 0.970325 0.0289
38
+
39
+
40
+ Parameters
41
+ ----------
42
+ instruments : str or dict
43
+ it can either be the market name or the config file of instruments generated by InstrumentProvider.
44
+ If the value of instruments is None, it means that no filtering is done.
45
+ start_time : str
46
+ start of the time range.
47
+ end_time : str
48
+ end of the time range.
49
+
50
+ Returns
51
+ -------
52
+ pd.DataFrame:
53
+ data load from the under layer source
54
+
55
+ Raise
56
+ -----
57
+ KeyError:
58
+ if the instruments filter is not supported, raise KeyError
59
+ """
60
+
61
+
62
+ class DLWParser(DataLoader):
63
+ """
64
+ (D)ata(L)oader (W)ith (P)arser for features and names
65
+
66
+ Extracting this class so that QlibDataLoader and other dataloaders(such as QdbDataLoader) can share the fields.
67
+ """
68
+
69
+ def __init__(self, config: Union[list, tuple, dict]):
70
+ """
71
+ Parameters
72
+ ----------
73
+ config : Union[list, tuple, dict]
74
+ Config will be used to describe the fields and column names
75
+
76
+ .. code-block::
77
+
78
+ <config> := {
79
+ "group_name1": <fields_info1>
80
+ "group_name2": <fields_info2>
81
+ }
82
+ or
83
+ <config> := <fields_info>
84
+
85
+ <fields_info> := ["expr", ...] | (["expr", ...], ["col_name", ...])
86
+ # NOTE: list or tuple will be treated as the things when parsing
87
+ """
88
+ self.is_group = isinstance(config, dict)
89
+
90
+ if self.is_group:
91
+ self.fields = {grp: self._parse_fields_info(fields_info) for grp, fields_info in config.items()}
92
+ else:
93
+ self.fields = self._parse_fields_info(config)
94
+
95
+ def _parse_fields_info(self, fields_info: Union[list, tuple]) -> Tuple[list, list]:
96
+ if len(fields_info) == 0:
97
+ raise ValueError("The size of fields must be greater than 0")
98
+
99
+ if not isinstance(fields_info, (list, tuple)):
100
+ raise TypeError("Unsupported type")
101
+
102
+ if isinstance(fields_info[0], str):
103
+ exprs = names = fields_info
104
+ elif isinstance(fields_info[0], (list, tuple)):
105
+ exprs, names = fields_info
106
+ else:
107
+ raise NotImplementedError(f"This type of input is not supported")
108
+ return exprs, names
109
+
110
+ @abc.abstractmethod
111
+ def load_group_df(
112
+ self,
113
+ instruments,
114
+ exprs: list,
115
+ names: list,
116
+ start_time: Union[str, pd.Timestamp] = None,
117
+ end_time: Union[str, pd.Timestamp] = None,
118
+ gp_name: str = None,
119
+ ) -> pd.DataFrame:
120
+ """
121
+ load the dataframe for specific group
122
+
123
+ Parameters
124
+ ----------
125
+ instruments :
126
+ the instruments.
127
+ exprs : list
128
+ the expressions to describe the content of the data.
129
+ names : list
130
+ the name of the data.
131
+
132
+ Returns
133
+ -------
134
+ pd.DataFrame:
135
+ the queried dataframe.
136
+ """
137
+
138
+ def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame:
139
+ if self.is_group:
140
+ df = pd.concat(
141
+ {
142
+ grp: self.load_group_df(instruments, exprs, names, start_time, end_time, grp)
143
+ for grp, (exprs, names) in self.fields.items()
144
+ },
145
+ axis=1,
146
+ )
147
+ else:
148
+ exprs, names = self.fields
149
+ df = self.load_group_df(instruments, exprs, names, start_time, end_time)
150
+ return df
151
+
152
+
153
+ class QlibDataLoader(DLWParser):
154
+ """Same as QlibDataLoader. The fields can be define by config"""
155
+
156
+ def __init__(
157
+ self,
158
+ config: Tuple[list, tuple, dict],
159
+ filter_pipe: List = None,
160
+ swap_level: bool = True,
161
+ freq: Union[str, dict] = "day",
162
+ inst_processors: Union[dict, list] = None,
163
+ ):
164
+ """
165
+ Parameters
166
+ ----------
167
+ config : Tuple[list, tuple, dict]
168
+ Please refer to the doc of DLWParser
169
+ filter_pipe :
170
+ Filter pipe for the instruments
171
+ swap_level :
172
+ Whether to swap level of MultiIndex
173
+ freq: dict or str
174
+ If type(config) == dict and type(freq) == str, load config data using freq.
175
+ If type(config) == dict and type(freq) == dict, load config[<group_name>] data using freq[<group_name>]
176
+ inst_processors: dict | list
177
+ If inst_processors is not None and type(config) == dict; load config[<group_name>] data using inst_processors[<group_name>]
178
+ If inst_processors is a list, then it will be applied to all groups.
179
+ """
180
+ self.filter_pipe = filter_pipe
181
+ self.swap_level = swap_level
182
+ self.freq = freq
183
+
184
+ # sample
185
+ self.inst_processors = inst_processors if inst_processors is not None else {}
186
+ assert isinstance(
187
+ self.inst_processors, (dict, list)
188
+ ), f"inst_processors(={self.inst_processors}) must be dict or list"
189
+
190
+ super().__init__(config)
191
+
192
+ if self.is_group:
193
+ # check sample config
194
+ if isinstance(freq, dict):
195
+ for _gp in config.keys():
196
+ if _gp not in freq:
197
+ raise ValueError(f"freq(={freq}) missing group(={_gp})")
198
+ assert (
199
+ self.inst_processors
200
+ ), f"freq(={self.freq}), inst_processors(={self.inst_processors}) cannot be None/empty"
201
+
202
+ def load_group_df(
203
+ self,
204
+ instruments,
205
+ exprs: list,
206
+ names: list,
207
+ start_time: Union[str, pd.Timestamp] = None,
208
+ end_time: Union[str, pd.Timestamp] = None,
209
+ gp_name: str = None,
210
+ ) -> pd.DataFrame:
211
+ if instruments is None:
212
+ warnings.warn("`instruments` is not set, will load all stocks")
213
+ instruments = "all"
214
+ if isinstance(instruments, str):
215
+ instruments = D.instruments(instruments, filter_pipe=self.filter_pipe)
216
+ elif self.filter_pipe is not None:
217
+ warnings.warn("`filter_pipe` is not None, but it will not be used with `instruments` as list")
218
+
219
+ freq = self.freq[gp_name] if isinstance(self.freq, dict) else self.freq
220
+ inst_processors = (
221
+ self.inst_processors if isinstance(self.inst_processors, list) else self.inst_processors.get(gp_name, [])
222
+ )
223
+ df = D.features(instruments, exprs, start_time, end_time, freq=freq, inst_processors=inst_processors)
224
+ df.columns = names
225
+ if self.swap_level:
226
+ df = df.swaplevel().sort_index() # NOTE: if swaplevel, return <datetime, instrument>
227
+ return df
228
+
229
+
230
+ class StaticDataLoader(DataLoader, Serializable):
231
+ """
232
+ DataLoader that supports loading data from file or as provided.
233
+ """
234
+
235
+ include_attr = ["_config"]
236
+
237
+ def __init__(self, config: Union[dict, str, pd.DataFrame], join="outer"):
238
+ """
239
+ Parameters
240
+ ----------
241
+ config : dict
242
+ {fields_group: <path or object>}
243
+ join : str
244
+ How to align different dataframes
245
+ """
246
+ self._config = config # using "_" to avoid confliction with the method `config` of Serializable
247
+ self.join = join
248
+ self._data = None
249
+
250
+ def __getstate__(self) -> dict:
251
+ # avoid pickling `self._data`
252
+ return {k: v for k, v in self.__dict__.items() if not k.startswith("_")}
253
+
254
+ def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame:
255
+ self._maybe_load_raw_data()
256
+
257
+ # 1) Filter by instruments
258
+ if instruments is None:
259
+ df = self._data
260
+ else:
261
+ df = self._data.loc(axis=0)[:, instruments]
262
+
263
+ # 2) Filter by Datetime
264
+ if start_time is None and end_time is None:
265
+ return df # NOTE: avoid copy by loc
266
+ # pd.Timestamp(None) == NaT, use NaT as index can not fetch correct thing, so do not change None.
267
+ start_time = time_to_slc_point(start_time)
268
+ end_time = time_to_slc_point(end_time)
269
+ return df.loc[start_time:end_time]
270
+
271
+ def _maybe_load_raw_data(self):
272
+ if self._data is not None:
273
+ return
274
+ if isinstance(self._config, dict):
275
+ self._data = pd.concat(
276
+ {fields_group: load_dataset(path_or_obj) for fields_group, path_or_obj in self._config.items()},
277
+ axis=1,
278
+ join=self.join,
279
+ )
280
+ self._data.sort_index(inplace=True)
281
+ elif isinstance(self._config, (str, Path)):
282
+ if str(self._config).strip().endswith(".parquet"):
283
+ self._data = pd.read_parquet(self._config, engine="pyarrow")
284
+ else:
285
+ with Path(self._config).open("rb") as f:
286
+ self._data = restricted_pickle_load(f)
287
+ elif isinstance(self._config, pd.DataFrame):
288
+ self._data = self._config
289
+
290
+
291
+ class NestedDataLoader(DataLoader):
292
+ """
293
+ We have multiple DataLoader, we can use this class to combine them.
294
+ """
295
+
296
+ def __init__(self, dataloader_l: List[Dict], join="left") -> None:
297
+ """
298
+
299
+ Parameters
300
+ ----------
301
+ dataloader_l : list[dict]
302
+ A list of dataloader, for exmaple
303
+
304
+ .. code-block:: python
305
+
306
+ nd = NestedDataLoader(
307
+ dataloader_l=[
308
+ {
309
+ "class": "qlib.contrib.data.loader.Alpha158DL",
310
+ }, {
311
+ "class": "qlib.contrib.data.loader.Alpha360DL",
312
+ "kwargs": {
313
+ "config": {
314
+ "label": ( ["Ref($close, -2)/Ref($close, -1) - 1"], ["LABEL0"])
315
+ }
316
+ }
317
+ }
318
+ ]
319
+ )
320
+ join :
321
+ it will pass to pd.concat when merging it.
322
+ """
323
+ super().__init__()
324
+ self.data_loader_l = [
325
+ (dl if isinstance(dl, DataLoader) else init_instance_by_config(dl)) for dl in dataloader_l
326
+ ]
327
+ self.join = join
328
+
329
+ def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame:
330
+ df_full = None
331
+ for dl in self.data_loader_l:
332
+ try:
333
+ df_current = dl.load(instruments, start_time, end_time)
334
+ except KeyError:
335
+ warnings.warn(
336
+ "If the value of `instruments` cannot be processed, it will set instruments to None to get all the data."
337
+ )
338
+ df_current = dl.load(instruments=None, start_time=start_time, end_time=end_time)
339
+ if df_full is None:
340
+ df_full = df_current
341
+ else:
342
+ current_columns = df_current.columns.tolist()
343
+ full_columns = df_full.columns.tolist()
344
+ columns_to_drop = [col for col in current_columns if col in full_columns]
345
+ df_full.drop(columns=columns_to_drop, inplace=True)
346
+ df_full = pd.merge(df_full, df_current, left_index=True, right_index=True, how=self.join)
347
+ return df_full.sort_index(axis=1)
348
+
349
+
350
+ class DataLoaderDH(DataLoader):
351
+ """DataLoaderDH
352
+ DataLoader based on (D)ata (H)andler
353
+ It is designed to load multiple data from data handler
354
+ - If you just want to load data from single datahandler, you can write them in single data handler
355
+
356
+ TODO: What make this module not that easy to use.
357
+
358
+ - For online scenario
359
+
360
+ - The underlayer data handler should be configured. But data loader doesn't provide such interface & hook.
361
+ """
362
+
363
+ def __init__(self, handler_config: dict, fetch_kwargs: dict = {}, is_group=False):
364
+ """
365
+ Parameters
366
+ ----------
367
+ handler_config : dict
368
+ handler_config will be used to describe the handlers
369
+
370
+ .. code-block::
371
+
372
+ <handler_config> := {
373
+ "group_name1": <handler>
374
+ "group_name2": <handler>
375
+ }
376
+ or
377
+ <handler_config> := <handler>
378
+ <handler> := DataHandler Instance | DataHandler Config
379
+
380
+ fetch_kwargs : dict
381
+ fetch_kwargs will be used to describe the different arguments of fetch method, such as col_set, squeeze, data_key, etc.
382
+
383
+ is_group: bool
384
+ is_group will be used to describe whether the key of handler_config is group
385
+
386
+ """
387
+ from qlib.data.dataset.handler import DataHandler # pylint: disable=C0415
388
+
389
+ if is_group:
390
+ self.handlers = {
391
+ grp: init_instance_by_config(config, accept_types=DataHandler) for grp, config in handler_config.items()
392
+ }
393
+ else:
394
+ self.handlers = init_instance_by_config(handler_config, accept_types=DataHandler)
395
+
396
+ self.is_group = is_group
397
+ self.fetch_kwargs = {"col_set": DataHandler.CS_RAW}
398
+ self.fetch_kwargs.update(fetch_kwargs)
399
+
400
+ def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame:
401
+ if instruments is not None:
402
+ get_module_logger(self.__class__.__name__).warning(f"instruments[{instruments}] is ignored")
403
+
404
+ if self.is_group:
405
+ df = pd.concat(
406
+ {
407
+ grp: dh.fetch(selector=slice(start_time, end_time), level="datetime", **self.fetch_kwargs)
408
+ for grp, dh in self.handlers.items()
409
+ },
410
+ axis=1,
411
+ )
412
+ else:
413
+ df = self.handlers.fetch(selector=slice(start_time, end_time), level="datetime", **self.fetch_kwargs)
414
+ return df
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/processor.py ADDED
@@ -0,0 +1,419 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+
4
+ import abc
5
+ from typing import Union, Text, Optional
6
+ import numpy as np
7
+ import pandas as pd
8
+
9
+ from qlib.utils.data import robust_zscore, zscore
10
+ from ...constant import EPS
11
+ from .utils import fetch_df_by_index
12
+ from ...utils.serial import Serializable
13
+ from ...utils.paral import datetime_groupby_apply
14
+ from qlib.data.inst_processor import InstProcessor
15
+ from qlib.data import D
16
+
17
+
18
+ def get_group_columns(df: pd.DataFrame, group: Union[Text, None]):
19
+ """
20
+ get a group of columns from multi-index columns DataFrame
21
+
22
+ Parameters
23
+ ----------
24
+ df : pd.DataFrame
25
+ with multi of columns.
26
+ group : str
27
+ the name of the feature group, i.e. the first level value of the group index.
28
+ """
29
+ if group is None:
30
+ return df.columns
31
+ else:
32
+ return df.columns[df.columns.get_loc(group)]
33
+
34
+
35
+ class Processor(Serializable):
36
+ def fit(self, df: pd.DataFrame = None):
37
+ """
38
+ learn data processing parameters
39
+
40
+ Parameters
41
+ ----------
42
+ df : pd.DataFrame
43
+ When we fit and process data with processor one by one. The fit function reiles on the output of previous
44
+ processor, i.e. `df`.
45
+
46
+ """
47
+
48
+ @abc.abstractmethod
49
+ def __call__(self, df: pd.DataFrame):
50
+ """
51
+ process the data
52
+
53
+ NOTE: **The processor could change the content of `df` inplace !!!!! **
54
+ User should keep a copy of data outside
55
+
56
+ Parameters
57
+ ----------
58
+ df : pd.DataFrame
59
+ The raw_df of handler or result from previous processor.
60
+ """
61
+
62
+ def is_for_infer(self) -> bool:
63
+ """
64
+ Is this processor usable for inference
65
+ Some processors are not usable for inference.
66
+
67
+ Returns
68
+ -------
69
+ bool:
70
+ if it is usable for infenrece.
71
+ """
72
+ return True
73
+
74
+ def readonly(self) -> bool:
75
+ """
76
+ Does the processor treat the input data readonly (i.e. does not write the input data) when processing
77
+
78
+ Knowning the readonly information is helpful to the Handler to avoid uncessary copy
79
+ """
80
+ return False
81
+
82
+ def config(self, **kwargs):
83
+ attr_list = {"fit_start_time", "fit_end_time"}
84
+ for k, v in kwargs.items():
85
+ if k in attr_list and hasattr(self, k):
86
+ setattr(self, k, v)
87
+
88
+ for attr in attr_list:
89
+ if attr in kwargs:
90
+ kwargs.pop(attr)
91
+ super().config(**kwargs)
92
+
93
+
94
+ class DropnaProcessor(Processor):
95
+ def __init__(self, fields_group=None):
96
+ self.fields_group = fields_group
97
+
98
+ def __call__(self, df):
99
+ return df.dropna(subset=get_group_columns(df, self.fields_group))
100
+
101
+ def readonly(self):
102
+ return True
103
+
104
+
105
+ class DropnaLabel(DropnaProcessor):
106
+ def __init__(self, fields_group="label"):
107
+ super().__init__(fields_group=fields_group)
108
+
109
+ def is_for_infer(self) -> bool:
110
+ """The samples are dropped according to label. So it is not usable for inference"""
111
+ return False
112
+
113
+
114
+ class DropCol(Processor):
115
+ def __init__(self, col_list=[]):
116
+ self.col_list = col_list
117
+
118
+ def __call__(self, df):
119
+ if isinstance(df.columns, pd.MultiIndex):
120
+ mask = df.columns.get_level_values(-1).isin(self.col_list)
121
+ else:
122
+ mask = df.columns.isin(self.col_list)
123
+ return df.loc[:, ~mask]
124
+
125
+ def readonly(self):
126
+ return True
127
+
128
+
129
+ class FilterCol(Processor):
130
+ def __init__(self, fields_group="feature", col_list=[]):
131
+ self.fields_group = fields_group
132
+ self.col_list = col_list
133
+
134
+ def __call__(self, df):
135
+ cols = get_group_columns(df, self.fields_group)
136
+ all_cols = df.columns
137
+ diff_cols = np.setdiff1d(all_cols.get_level_values(-1), cols.get_level_values(-1))
138
+ self.col_list = np.union1d(diff_cols, self.col_list)
139
+ mask = df.columns.get_level_values(-1).isin(self.col_list)
140
+ return df.loc[:, mask]
141
+
142
+ def readonly(self):
143
+ return True
144
+
145
+
146
+ class TanhProcess(Processor):
147
+ """Use tanh to process noise data"""
148
+
149
+ def __call__(self, df):
150
+ def tanh_denoise(data):
151
+ mask = data.columns.get_level_values(1).str.contains("LABEL")
152
+ col = df.columns[~mask]
153
+ data[col] = data[col] - 1
154
+ data[col] = np.tanh(data[col])
155
+
156
+ return data
157
+
158
+ return tanh_denoise(df)
159
+
160
+
161
+ class ProcessInf(Processor):
162
+ """Process infinity"""
163
+
164
+ def __call__(self, df):
165
+ def replace_inf(data):
166
+ def process_inf(df):
167
+ for col in df.columns:
168
+ # FIXME: Such behavior is very weird
169
+ df[col] = df[col].replace([np.inf, -np.inf], df[col][~np.isinf(df[col])].mean())
170
+ return df
171
+
172
+ data = datetime_groupby_apply(data, process_inf)
173
+ data.sort_index(inplace=True)
174
+ return data
175
+
176
+ return replace_inf(df)
177
+
178
+
179
+ class Fillna(Processor):
180
+ """Process NaN"""
181
+
182
+ def __init__(self, fields_group=None, fill_value=0):
183
+ self.fields_group = fields_group
184
+ self.fill_value = fill_value
185
+
186
+ def __call__(self, df):
187
+ if self.fields_group is None:
188
+ df.fillna(self.fill_value, inplace=True)
189
+ else:
190
+ # this implementation is extremely slow
191
+ # df.fillna({col: self.fill_value for col in cols}, inplace=True)
192
+ df[self.fields_group] = df[self.fields_group].fillna(self.fill_value)
193
+ return df
194
+
195
+
196
+ class MinMaxNorm(Processor):
197
+ def __init__(self, fit_start_time, fit_end_time, fields_group=None):
198
+ # NOTE: correctly set the `fit_start_time` and `fit_end_time` is very important !!!
199
+ # `fit_end_time` **must not** include any information from the test data!!!
200
+ self.fit_start_time = fit_start_time
201
+ self.fit_end_time = fit_end_time
202
+ self.fields_group = fields_group
203
+
204
+ def fit(self, df: pd.DataFrame = None):
205
+ df = fetch_df_by_index(df, slice(self.fit_start_time, self.fit_end_time), level="datetime")
206
+ cols = get_group_columns(df, self.fields_group)
207
+ self.min_val = np.nanmin(df[cols].values, axis=0)
208
+ self.max_val = np.nanmax(df[cols].values, axis=0)
209
+ self.ignore = self.min_val == self.max_val
210
+ # To improve the speed, we set the value of `min_val` to `0` for the columns that do not need to be processed,
211
+ # and the value of `max_val` to `1`, when using `(x - min_val) / (max_val - min_val)` for uniform calculation,
212
+ # the columns that do not need to be processed will be calculated by `(x - 0) / (1 - 0)`,
213
+ # as you can see, the columns that do not need to be processed, will not be affected.
214
+ for _i, _con in enumerate(self.ignore):
215
+ if _con:
216
+ self.min_val[_i] = 0
217
+ self.max_val[_i] = 1
218
+ self.cols = cols
219
+
220
+ def __call__(self, df):
221
+ def normalize(x, min_val=self.min_val, max_val=self.max_val):
222
+ return (x - min_val) / (max_val - min_val)
223
+
224
+ df.loc(axis=1)[self.cols] = normalize(df[self.cols].values)
225
+ return df
226
+
227
+
228
+ class ZScoreNorm(Processor):
229
+ """ZScore Normalization"""
230
+
231
+ def __init__(self, fit_start_time, fit_end_time, fields_group=None):
232
+ # NOTE: correctly set the `fit_start_time` and `fit_end_time` is very important !!!
233
+ # `fit_end_time` **must not** include any information from the test data!!!
234
+ self.fit_start_time = fit_start_time
235
+ self.fit_end_time = fit_end_time
236
+ self.fields_group = fields_group
237
+
238
+ def fit(self, df: pd.DataFrame = None):
239
+ df = fetch_df_by_index(df, slice(self.fit_start_time, self.fit_end_time), level="datetime")
240
+ cols = get_group_columns(df, self.fields_group)
241
+ self.mean_train = np.nanmean(df[cols].values, axis=0)
242
+ self.std_train = np.nanstd(df[cols].values, axis=0)
243
+ self.ignore = self.std_train == 0
244
+ # To improve the speed, we set the value of `std_train` to `1` for the columns that do not need to be processed,
245
+ # and the value of `mean_train` to `0`, when using `(x - mean_train) / std_train` for uniform calculation,
246
+ # the columns that do not need to be processed will be calculated by `(x - 0) / 1`,
247
+ # as you can see, the columns that do not need to be processed, will not be affected.
248
+ for _i, _con in enumerate(self.ignore):
249
+ if _con:
250
+ self.std_train[_i] = 1
251
+ self.mean_train[_i] = 0
252
+ self.cols = cols
253
+
254
+ def __call__(self, df):
255
+ def normalize(x, mean_train=self.mean_train, std_train=self.std_train):
256
+ return (x - mean_train) / std_train
257
+
258
+ df.loc(axis=1)[self.cols] = normalize(df[self.cols].values)
259
+ return df
260
+
261
+
262
+ class RobustZScoreNorm(Processor):
263
+ """Robust ZScore Normalization
264
+
265
+ Use robust statistics for Z-Score normalization:
266
+ mean(x) = median(x)
267
+ std(x) = MAD(x) * 1.4826
268
+
269
+ Reference:
270
+ https://en.wikipedia.org/wiki/Median_absolute_deviation.
271
+ """
272
+
273
+ def __init__(self, fit_start_time, fit_end_time, fields_group=None, clip_outlier=True):
274
+ # NOTE: correctly set the `fit_start_time` and `fit_end_time` is very important !!!
275
+ # `fit_end_time` **must not** include any information from the test data!!!
276
+ self.fit_start_time = fit_start_time
277
+ self.fit_end_time = fit_end_time
278
+ self.fields_group = fields_group
279
+ self.clip_outlier = clip_outlier
280
+
281
+ def fit(self, df: pd.DataFrame = None):
282
+ df = fetch_df_by_index(df, slice(self.fit_start_time, self.fit_end_time), level="datetime")
283
+ self.cols = get_group_columns(df, self.fields_group)
284
+ X = df[self.cols].values
285
+ self.mean_train = np.nanmedian(X, axis=0)
286
+ self.std_train = np.nanmedian(np.abs(X - self.mean_train), axis=0)
287
+ self.std_train += EPS
288
+ self.std_train *= 1.4826
289
+
290
+ def __call__(self, df):
291
+ X = df[self.cols]
292
+ X -= self.mean_train
293
+ X /= self.std_train
294
+ if self.clip_outlier:
295
+ X = np.clip(X, -3, 3)
296
+ df[self.cols] = X
297
+ return df
298
+
299
+
300
+ class CSZScoreNorm(Processor):
301
+ """Cross Sectional ZScore Normalization"""
302
+
303
+ def __init__(self, fields_group=None, method="zscore"):
304
+ self.fields_group = fields_group
305
+ if method == "zscore":
306
+ self.zscore_func = zscore
307
+ elif method == "robust":
308
+ self.zscore_func = robust_zscore
309
+ else:
310
+ raise NotImplementedError(f"This type of input is not supported")
311
+
312
+ def __call__(self, df):
313
+ # try not modify original dataframe
314
+ if not isinstance(self.fields_group, list):
315
+ self.fields_group = [self.fields_group]
316
+ # depress warning by references:
317
+ # https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas
318
+ # https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#getting-and-setting-options
319
+ with pd.option_context("mode.chained_assignment", None):
320
+ for g in self.fields_group:
321
+ cols = get_group_columns(df, g)
322
+ df[cols] = df[cols].groupby("datetime", group_keys=False).apply(self.zscore_func)
323
+ return df
324
+
325
+
326
+ class CSRankNorm(Processor):
327
+ """
328
+ Cross Sectional Rank Normalization.
329
+ "Cross Sectional" is often used to describe data operations.
330
+ The operations across different stocks are often called Cross Sectional Operation.
331
+
332
+ For example, CSRankNorm is an operation that grouping the data by each day and rank `across` all the stocks in each day.
333
+
334
+ Explanation about 3.46 & 0.5
335
+
336
+ .. code-block:: python
337
+
338
+ import numpy as np
339
+ import pandas as pd
340
+ x = np.random.random(10000) # for any variable
341
+ x_rank = pd.Series(x).rank(pct=True) # if it is converted to rank, it will be a uniform distributed
342
+ x_rank_norm = (x_rank - x_rank.mean()) / x_rank.std() # Normally, we will normalize it to make it like normal distribution
343
+
344
+ x_rank.mean() # accounts for 0.5
345
+ 1 / x_rank.std() # accounts for 3.46
346
+
347
+ """
348
+
349
+ def __init__(self, fields_group=None):
350
+ self.fields_group = fields_group
351
+
352
+ def __call__(self, df):
353
+ # try not modify original dataframe
354
+ cols = get_group_columns(df, self.fields_group)
355
+ t = df[cols].groupby("datetime", group_keys=False).rank(pct=True)
356
+ t -= 0.5
357
+ t *= 3.46 # NOTE: towards unit std
358
+ df[cols] = t
359
+ return df
360
+
361
+
362
+ class CSZFillna(Processor):
363
+ """Cross Sectional Fill Nan"""
364
+
365
+ def __init__(self, fields_group=None):
366
+ self.fields_group = fields_group
367
+
368
+ def __call__(self, df):
369
+ cols = get_group_columns(df, self.fields_group)
370
+ df[cols] = df[cols].groupby("datetime", group_keys=False).apply(lambda x: x.fillna(x.mean()))
371
+ return df
372
+
373
+
374
+ class HashStockFormat(Processor):
375
+ """Process the storage of from df into hasing stock format"""
376
+
377
+ def __call__(self, df: pd.DataFrame):
378
+ from .storage import HashingStockStorage # pylint: disable=C0415
379
+
380
+ return HashingStockStorage.from_df(df)
381
+
382
+
383
+ class TimeRangeFlt(InstProcessor):
384
+ """
385
+ This is a filter to filter stock.
386
+ Only keep the data that exist from start_time to end_time (the existence in the middle is not checked.)
387
+ WARNING: It may induce leakage!!!
388
+ """
389
+
390
+ def __init__(
391
+ self,
392
+ start_time: Optional[Union[pd.Timestamp, str]] = None,
393
+ end_time: Optional[Union[pd.Timestamp, str]] = None,
394
+ freq: str = "day",
395
+ ):
396
+ """
397
+ Parameters
398
+ ----------
399
+ start_time : Optional[Union[pd.Timestamp, str]]
400
+ The data must start earlier (or equal) than `start_time`
401
+ None indicates data will not be filtered based on `start_time`
402
+ end_time : Optional[Union[pd.Timestamp, str]]
403
+ similar to start_time
404
+ freq : str
405
+ The frequency of the calendar
406
+ """
407
+ # Align to calendar before filtering
408
+ cal = D.calendar(start_time=start_time, end_time=end_time, freq=freq)
409
+ self.start_time = None if start_time is None else cal[0]
410
+ self.end_time = None if end_time is None else cal[-1]
411
+
412
+ def __call__(self, df: pd.DataFrame, instrument, *args, **kwargs):
413
+ if (
414
+ df.empty
415
+ or (self.start_time is None or df.index.min() <= self.start_time)
416
+ and (self.end_time is None or df.index.max() >= self.end_time)
417
+ ):
418
+ return df
419
+ return df.head(0)
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/storage.py ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import abstractmethod
2
+ import pandas as pd
3
+ import numpy as np
4
+
5
+ from .handler import DataHandler
6
+ from typing import Union, List
7
+ from qlib.log import get_module_logger
8
+
9
+ from .utils import get_level_index, fetch_df_by_index, fetch_df_by_col
10
+
11
+
12
+ class BaseHandlerStorage:
13
+ """
14
+ Base data storage for datahandler
15
+ - pd.DataFrame is the default data storage format in Qlib datahandler
16
+ - If users want to use custom data storage, they should define subclass inherited BaseHandlerStorage, and implement the following method
17
+ """
18
+
19
+ @abstractmethod
20
+ def fetch(
21
+ self,
22
+ selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
23
+ level: Union[str, int] = "datetime",
24
+ col_set: Union[str, List[str]] = DataHandler.CS_ALL,
25
+ fetch_orig: bool = True,
26
+ ) -> pd.DataFrame:
27
+ """fetch data from the data storage
28
+
29
+ Parameters
30
+ ----------
31
+ selector : Union[pd.Timestamp, slice, str]
32
+ describe how to select data by index
33
+ level : Union[str, int]
34
+ which index level to select the data
35
+ - if level is None, apply selector to df directly
36
+ col_set : Union[str, List[str]]
37
+ - if isinstance(col_set, str):
38
+ select a set of meaningful columns.(e.g. features, columns)
39
+ if col_set == DataHandler.CS_RAW:
40
+ the raw dataset will be returned.
41
+ - if isinstance(col_set, List[str]):
42
+ select several sets of meaningful columns, the returned data has multiple level
43
+ fetch_orig : bool
44
+ Return the original data instead of copy if possible.
45
+
46
+ Returns
47
+ -------
48
+ pd.DataFrame
49
+ the dataframe fetched
50
+ """
51
+ raise NotImplementedError("fetch is method not implemented!")
52
+
53
+
54
+ class NaiveDFStorage(BaseHandlerStorage):
55
+ """Naive data storage for datahandler
56
+ - NaiveDFStorage is a naive data storage for datahandler
57
+ - NaiveDFStorage will input a pandas.DataFrame as and provide interface support for fetching data
58
+ """
59
+
60
+ def __init__(self, df: pd.DataFrame):
61
+ self.df = df
62
+
63
+ def fetch(
64
+ self,
65
+ selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
66
+ level: Union[str, int] = "datetime",
67
+ col_set: Union[str, List[str]] = DataHandler.CS_ALL,
68
+ fetch_orig: bool = True,
69
+ ) -> pd.DataFrame:
70
+ # Following conflicts may occur
71
+ # - Does [20200101", "20210101"] mean selecting this slice or these two days?
72
+ # To solve this issue
73
+ # - slice have higher priorities (except when level is none)
74
+ if isinstance(selector, (tuple, list)) and level is not None:
75
+ # when level is None, the argument will be passed in directly
76
+ # we don't have to convert it into slice
77
+ try:
78
+ selector = slice(*selector)
79
+ except ValueError:
80
+ get_module_logger("DataHandlerLP").info(f"Fail to converting to query to slice. It will used directly")
81
+
82
+ data_df = self.df
83
+ data_df = fetch_df_by_col(data_df, col_set)
84
+ data_df = fetch_df_by_index(data_df, selector, level, fetch_orig=fetch_orig)
85
+ return data_df
86
+
87
+
88
+ class HashingStockStorage(BaseHandlerStorage):
89
+ """Hashing data storage for datahanlder
90
+ - The default data storage pandas.DataFrame is too slow when randomly accessing one stock's data
91
+ - HashingStockStorage hashes the multiple stocks' data(pandas.DataFrame) by the key `stock_id`.
92
+ - HashingStockStorage hashes the pandas.DataFrame into a dict, whose key is the stock_id(str) and value this stock data(panda.DataFrame), it has the following format:
93
+ {
94
+ stock1_id: stock1_data,
95
+ stock2_id: stock2_data,
96
+ ...
97
+ stockn_id: stockn_data,
98
+ }
99
+ - By the `fetch` method, users can access any stock data with much lower time cost than default data storage
100
+ """
101
+
102
+ def __init__(self, df):
103
+ self.hash_df = dict()
104
+ self.stock_level = get_level_index(df, "instrument")
105
+ for k, v in df.groupby(level="instrument", group_keys=False):
106
+ self.hash_df[k] = v
107
+ self.columns = df.columns
108
+
109
+ @staticmethod
110
+ def from_df(df):
111
+ return HashingStockStorage(df)
112
+
113
+ def _fetch_hash_df_by_stock(self, selector, level):
114
+ """fetch the data with stock selector
115
+
116
+ Parameters
117
+ ----------
118
+ selector : Union[pd.Timestamp, slice, str]
119
+ describe how to select data by index
120
+ level : Union[str, int]
121
+ which index level to select the data
122
+ - if level is None, apply selector to df directly
123
+ - the `_fetch_hash_df_by_stock` will parse the stock selector in arg `selector`
124
+
125
+ Returns
126
+ -------
127
+ Dict
128
+ The dict whose key is stock_id, value is the stock's data
129
+ """
130
+
131
+ stock_selector = slice(None)
132
+ time_selector = slice(None) # by default not filter by time.
133
+
134
+ if level is None:
135
+ # For directly applying.
136
+ if isinstance(selector, tuple) and self.stock_level < len(selector):
137
+ # full selector format
138
+ stock_selector = selector[self.stock_level]
139
+ time_selector = selector[1 - self.stock_level]
140
+ elif isinstance(selector, (list, str)) and self.stock_level == 0:
141
+ # only stock selector
142
+ stock_selector = selector
143
+ elif level in ("instrument", self.stock_level):
144
+ if isinstance(selector, tuple):
145
+ # NOTE: How could the stock level selector be a tuple?
146
+ stock_selector = selector[0]
147
+ raise TypeError(
148
+ "I forget why would this case appear. But I think it does not make sense. So we raise a error for that case."
149
+ )
150
+ elif isinstance(selector, (list, str)):
151
+ stock_selector = selector
152
+
153
+ if not isinstance(stock_selector, (list, str)) and stock_selector != slice(None):
154
+ raise TypeError(f"stock selector must be type str|list, or slice(None), rather than {stock_selector}")
155
+
156
+ if stock_selector == slice(None):
157
+ return self.hash_df, time_selector
158
+
159
+ if isinstance(stock_selector, str):
160
+ stock_selector = [stock_selector]
161
+
162
+ select_dict = dict()
163
+ for each_stock in sorted(stock_selector):
164
+ if each_stock in self.hash_df:
165
+ select_dict[each_stock] = self.hash_df[each_stock]
166
+ return select_dict, time_selector
167
+
168
+ def fetch(
169
+ self,
170
+ selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
171
+ level: Union[str, int] = "datetime",
172
+ col_set: Union[str, List[str]] = DataHandler.CS_ALL,
173
+ fetch_orig: bool = True,
174
+ ) -> pd.DataFrame:
175
+ fetch_stock_df_list, time_selector = self._fetch_hash_df_by_stock(selector=selector, level=level)
176
+ fetch_stock_df_list = list(fetch_stock_df_list.values())
177
+ for _index, stock_df in enumerate(fetch_stock_df_list):
178
+ fetch_col_df = fetch_df_by_col(df=stock_df, col_set=col_set)
179
+ fetch_index_df = fetch_df_by_index(
180
+ df=fetch_col_df, selector=time_selector, level="datetime", fetch_orig=fetch_orig
181
+ )
182
+ fetch_stock_df_list[_index] = fetch_index_df
183
+ if len(fetch_stock_df_list) == 0:
184
+ index_names = ("instrument", "datetime") if self.stock_level == 0 else ("datetime", "instrument")
185
+ return pd.DataFrame(
186
+ index=pd.MultiIndex.from_arrays([[], []], names=index_names), columns=self.columns, dtype=np.float32
187
+ )
188
+ elif len(fetch_stock_df_list) == 1:
189
+ return fetch_stock_df_list[0]
190
+ else:
191
+ return pd.concat(fetch_stock_df_list, sort=False, copy=~fetch_orig)
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/utils.py ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 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-39/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-39/qlib/data/filter.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/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-39/qlib/data/ops.py ADDED
@@ -0,0 +1,1681 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/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-39/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-39/qlib/data/storage/file_storage.py ADDED
@@ -0,0 +1,379 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/qlib/data/storage/storage.py ADDED
@@ -0,0 +1,494 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/qlib/log.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/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-39/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-39/qlib/model/ens/__init__.py ADDED
File without changes
Kronos/qlib/build/lib.linux-x86_64-cpython-39/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-39/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-39/qlib/model/interpret/__init__.py ADDED
File without changes
Kronos/qlib/build/lib.linux-x86_64-cpython-39/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-39/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-39/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-39/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-39/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-39/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-39/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-39/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
76
+ M3 = (np.abs(R) >= 3.7 * lamb) * R
77
+ M = M1 + M2 + M3
78
+
79
+ Rthresh = M - np.diag(np.diag(M)) + np.eye(p)
80
+ SigmaU = (SuDiag**0.5).dot(Rthresh).dot(SuDiag**0.5)
81
+ SigmaY = SigmaU + Lowrank
82
+
83
+ return SigmaY
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/shrink.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/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-39/qlib/model/trainer.py ADDED
@@ -0,0 +1,619 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-39/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-39/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-39/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-39/qlib/rl/contrib/__init__.py ADDED
File without changes
Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/backtest.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
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-39/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-39/qlib/rl/contrib/train_onpolicy.py ADDED
@@ -0,0 +1,269 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright (c) Microsoft Corporation.
2
+ # Licensed under the MIT License.
3
+ from __future__ import annotations
4
+
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-39/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