diff --git a/.gitattributes b/.gitattributes index 0e9c01e9dabaca1494b9361eb7ebea67a7a579be..b6397c1d27de2cb13502a955b29275532ea7b224 100644 --- a/.gitattributes +++ b/.gitattributes @@ -62,3 +62,7 @@ Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/expanding.cpython 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 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 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 +Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/expanding.o filter=lfs diff=lfs merge=lfs -text +Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/rolling.o filter=lfs diff=lfs merge=lfs -text +Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/expanding.o filter=lfs diff=lfs merge=lfs -text +Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/rolling.o filter=lfs diff=lfs merge=lfs -text diff --git a/Kronos/qlib/CHANGELOG.md b/Kronos/qlib/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/CHANGES.rst b/Kronos/qlib/CHANGES.rst new file mode 100644 index 0000000000000000000000000000000000000000..76aa4829304b901b852db66880699a996799ae9d --- /dev/null +++ b/Kronos/qlib/CHANGES.rst @@ -0,0 +1,179 @@ +Changelog +========= +Here you can see the full list of changes between each QLib release. + +Version 0.1.0 +------------- +This is the initial release of QLib library. + +Version 0.1.1 +------------- +Performance optimize. Add more features and operators. + +Version 0.1.2 +------------- +- Support operator syntax. Now ``High() - Low()`` is equivalent to ``Sub(High(), Low())``. +- Add more technical indicators. + +Version 0.1.3 +------------- +Bug fix and add instruments filtering mechanism. + +Version 0.2.0 +------------- +- Redesign ``LocalProvider`` database format for performance improvement. +- Support load features as string fields. +- Add scripts for database construction. +- More operators and technical indicators. + +Version 0.2.1 +------------- +- Support registering user-defined ``Provider``. +- Support use operators in string format, e.g. ``['Ref($close, 1)']`` is valid field format. +- Support dynamic fields in ``$some_field`` format. And existing fields like ``Close()`` may be deprecated in the future. + +Version 0.2.2 +------------- +- Add ``disk_cache`` for reusing features (enabled by default). +- Add ``qlib.contrib`` for experimental model construction and evaluation. + + +Version 0.2.3 +------------- +- Add ``backtest`` module +- Decoupling the Strategy, Account, Position, Exchange from the backtest module + +Version 0.2.4 +------------- +- Add ``profit attribution`` module +- Add ``rick_control`` and ``cost_control`` strategies + +Version 0.3.0 +------------- +- Add ``estimator`` module + +Version 0.3.1 +------------- +- Add ``filter`` module + +Version 0.3.2 +------------- +- Add real price trading, if the ``factor`` field in the data set is incomplete, use ``adj_price`` trading +- Refactor ``handler`` ``launcher`` ``trainer`` code +- Support ``backtest`` configuration parameters in the configuration file +- Fix bug in position ``amount`` is 0 +- Fix bug of ``filter`` module + +Version 0.3.3 +------------- +- Fix bug of ``filter`` module + +Version 0.3.4 +------------- +- Support for ``finetune model`` +- Refactor ``fetcher`` code + +Version 0.3.5 +------------- +- Support multi-label training, you can provide multiple label in ``handler``. (But LightGBM doesn't support due to the algorithm itself) +- Refactor ``handler`` code, dataset.py is no longer used, and you can deploy your own labels and features in ``feature_label_config`` +- Handler only offer DataFrame. Also, ``trainer`` and model.py only receive DataFrame +- Change ``split_rolling_data``, we roll the data on market calendar now, not on normal date +- Move some date config from ``handler`` to ``trainer`` + +Version 0.4.0 +------------- +- Add `data` package that holds all data-related codes +- Reform the data provider structure +- Create a server for data centralized management `qlib-server `_ +- Add a `ClientProvider` to work with server +- Add a pluggable cache mechanism +- Add a recursive backtracking algorithm to inspect the furthest reference date for an expression + +.. note:: + 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: + + + >>> from qlib.data import D + >>> instruments = D.instruments(market='csi500') + >>> D.list_instruments(instruments=instruments, start_time='2015-01-01', end_time='2016-02-15', as_list=True) + + +Version 0.4.1 +------------- +- Add support Windows +- Fix ``instruments`` type bug +- Fix ``features`` is empty bug(It will cause failure in updating) +- Fix ``cache`` lock and update bug +- Fix use the same cache for the same field (the original space will add a new cache) +- Change "logger handler" from config +- Change model load support 0.4.0 later +- The default value of the ``method`` parameter of ``risk_analysis`` function is changed from **ci** to **si** + + +Version 0.4.2 +------------- +- Refactor DataHandler +- Add ``Alpha360`` DataHandler + + +Version 0.4.3 +------------- +- Implementing Online Inference and Trading Framework +- Refactoring The interfaces of backtest and strategy module. + + +Version 0.4.4 +------------- +- Optimize cache generation performance +- Add report module +- Fix bug when using ``ServerDatasetCache`` offline. +- 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. +- 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``. +- refactor the argument of backtest function. + - **NOTE**: + - 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. + - The TopkWeightStrategy is changed slightly. It will try to sell the stocks more than ``topk``. (The backtest result of TopkAmountStrategy remains the same) +- The margin ratio mechanism is supported in the Topk Margin strategies. + + +Version 0.4.5 +------------- +- Add multi-kernel implementation for both client and server. + - Support a new way to load data from client which skips dataset cache. + - Change the default dataset method from single kernel implementation to multi kernel implementation. +- Accelerate the high frequency data reading by optimizing the relative modules. +- Support a new method to write config file by using dict. + +Version 0.4.6 +------------- +- Some bugs are fixed + - The default config in `Version 0.4.5` is not friendly to daily frequency data. + - Backtest error in TopkWeightStrategy when `WithInteract=True`. + + +Version 0.5.0 +------------- +- First opensource version + - Refine the docs, code + - Add baselines + - public data crawler + + +Version 0.8.0 +------------- +- The backtest is greatly refactored. + - Nested decision execution framework is supported + - There are lots of changes for daily trading, it is hard to list all of them. But a few important changes could be noticed + - The trading limitation is more accurate; + - In `previous version `__, longing and shorting actions share the same action. + - In `current version `__, the trading limitation is different between logging and shorting action. + - The constant is different when calculating annualized metrics. + - `Current version `_ uses more accurate constant than `previous version `__ + - `A new version `__ of data is released. Due to the unstability of Yahoo data source, the data may be different after downloading data again. + - Users could check out the backtesting results between `Current version `__ and `previous version `__ + + +Other Versions +-------------- +Please refer to `Github release Notes `_ diff --git a/Kronos/qlib/CODE_OF_CONDUCT.md b/Kronos/qlib/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..f9ba8cf65f3e3104dd061c178066ec8247811f33 --- /dev/null +++ b/Kronos/qlib/CODE_OF_CONDUCT.md @@ -0,0 +1,9 @@ +# Microsoft Open Source Code of Conduct + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). + +Resources: + +- [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) +- [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) +- Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns diff --git a/Kronos/qlib/Dockerfile b/Kronos/qlib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7eb8c315ccc3bd3db5f7c1584abb89ab1af2ab31 --- /dev/null +++ b/Kronos/qlib/Dockerfile @@ -0,0 +1,31 @@ +FROM continuumio/miniconda3:latest + +WORKDIR /qlib + +COPY . . + +RUN apt-get update && \ + apt-get install -y build-essential + +RUN conda create --name qlib_env python=3.8 -y +RUN echo "conda activate qlib_env" >> ~/.bashrc +ENV PATH /opt/conda/envs/qlib_env/bin:$PATH + +RUN python -m pip install --upgrade pip + +RUN python -m pip install numpy==1.23.5 +RUN python -m pip install pandas==1.5.3 +RUN python -m pip install importlib-metadata==5.2.0 +RUN python -m pip install "cloudpickle<3" +RUN python -m pip install scikit-learn==1.3.2 + +RUN python -m pip install cython packaging tables matplotlib statsmodels +RUN python -m pip install pybind11 cvxpy + +ARG IS_STABLE="yes" + +RUN if [ "$IS_STABLE" = "yes" ]; then \ + python -m pip install pyqlib; \ + else \ + python setup.py install; \ + fi diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.pyx b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.pyx new file mode 100644 index 0000000000000000000000000000000000000000..a18679a991331737776916e95db1c468ff39db47 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/_libs/rolling.pyx @@ -0,0 +1,207 @@ +# cython: profile=False +# cython: boundscheck=False, wraparound=False, cdivision=True +cimport cython +cimport numpy as np +import numpy as np + +from libc.math cimport sqrt, isnan, NAN +from libcpp.deque cimport deque + + +cdef class Rolling: + """1-D array rolling""" + cdef int window + cdef deque[double] barv + cdef int na_count + def __init__(self, int window): + self.window = window + self.na_count = window + cdef int i + for i in range(window): + self.barv.push_back(NAN) + + cdef double update(self, double val): + pass + + +cdef class Mean(Rolling): + """1-D array rolling mean""" + cdef double vsum + def __init__(self, int window): + super(Mean, self).__init__(window) + self.vsum = 0 + + cdef double update(self, double val): + self.barv.push_back(val) + if not isnan(self.barv.front()): + self.vsum -= self.barv.front() + else: + self.na_count -= 1 + self.barv.pop_front() + if isnan(val): + self.na_count += 1 + # return NAN + else: + self.vsum += val + return self.vsum / (self.window - self.na_count) + + +cdef class Slope(Rolling): + """1-D array rolling slope""" + cdef double i_sum # can be used as i2_sum + cdef double x_sum + cdef double x2_sum + cdef double y_sum + cdef double xy_sum + def __init__(self, int window): + super(Slope, self).__init__(window) + self.i_sum = 0 + self.x_sum = 0 + self.x2_sum = 0 + self.y_sum = 0 + self.xy_sum = 0 + + cdef double update(self, double val): + self.barv.push_back(val) + self.xy_sum = self.xy_sum - self.y_sum + self.x2_sum = self.x2_sum + self.i_sum - 2*self.x_sum + self.x_sum = self.x_sum - self.i_sum + cdef double _val + _val = self.barv.front() + if not isnan(_val): + self.i_sum -= 1 + self.y_sum -= _val + else: + self.na_count -= 1 + self.barv.pop_front() + if isnan(val): + self.na_count += 1 + # return NAN + else: + self.i_sum += 1 + self.x_sum += self.window + self.x2_sum += self.window * self.window + self.y_sum += val + self.xy_sum += self.window * val + cdef int N = self.window - self.na_count + return (N*self.xy_sum - self.x_sum*self.y_sum) / \ + (N*self.x2_sum - self.x_sum*self.x_sum) + + +cdef class Resi(Rolling): + """1-D array rolling residuals""" + cdef double i_sum # can be used as i2_sum + cdef double x_sum + cdef double x2_sum + cdef double y_sum + cdef double xy_sum + def __init__(self, int window): + super(Resi, self).__init__(window) + self.i_sum = 0 + self.x_sum = 0 + self.x2_sum = 0 + self.y_sum = 0 + self.xy_sum = 0 + + cdef double update(self, double val): + self.barv.push_back(val) + self.xy_sum = self.xy_sum - self.y_sum + self.x2_sum = self.x2_sum + self.i_sum - 2*self.x_sum + self.x_sum = self.x_sum - self.i_sum + cdef double _val + _val = self.barv.front() + if not isnan(_val): + self.i_sum -= 1 + self.y_sum -= _val + else: + self.na_count -= 1 + self.barv.pop_front() + if isnan(val): + self.na_count += 1 + # return NAN + else: + self.i_sum += 1 + self.x_sum += self.window + self.x2_sum += self.window * self.window + self.y_sum += val + self.xy_sum += self.window * val + cdef int N = self.window - self.na_count + slope = (N*self.xy_sum - self.x_sum*self.y_sum) / \ + (N*self.x2_sum - self.x_sum*self.x_sum) + x_mean = self.x_sum / N + y_mean = self.y_sum / N + interp = y_mean - slope*x_mean + return val - (slope*self.window + interp) + + +cdef class Rsquare(Rolling): + """1-D array rolling rsquare""" + cdef double i_sum + cdef double x_sum + cdef double x2_sum + cdef double y_sum + cdef double y2_sum + cdef double xy_sum + def __init__(self, int window): + super(Rsquare, self).__init__(window) + self.i_sum = 0 + self.x_sum = 0 + self.x2_sum = 0 + self.y_sum = 0 + self.y2_sum = 0 + self.xy_sum = 0 + + cdef double update(self, double val): + self.barv.push_back(val) + self.xy_sum = self.xy_sum - self.y_sum + self.x2_sum = self.x2_sum + self.i_sum - 2*self.x_sum + self.x_sum = self.x_sum - self.i_sum + cdef double _val + _val = self.barv.front() + if not isnan(_val): + self.i_sum -= 1 + self.y_sum -= _val + self.y2_sum -= _val * _val + else: + self.na_count -= 1 + self.barv.pop_front() + if isnan(val): + self.na_count += 1 + # return NAN + else: + self.i_sum += 1 + self.x_sum += self.window + self.x2_sum += self.window * self.window + self.y_sum += val + self.y2_sum += val * val + self.xy_sum += self.window * val + cdef int N = self.window - self.na_count + cdef double rvalue + rvalue = (N*self.xy_sum - self.x_sum*self.y_sum) / \ + sqrt((N*self.x2_sum - self.x_sum*self.x_sum) * (N*self.y2_sum - self.y_sum*self.y_sum)) + return rvalue * rvalue + + +cdef np.ndarray[double, ndim=1] rolling(Rolling r, np.ndarray a): + cdef int i + cdef int N = len(a) + cdef np.ndarray[double, ndim=1] ret = np.empty(N) + for i in range(N): + ret[i] = r.update(a[i]) + return ret + +def rolling_mean(np.ndarray a, int window): + cdef Mean r = Mean(window) + return rolling(r, a) + +def rolling_slope(np.ndarray a, int window): + cdef Slope r = Slope(window) + return rolling(r, a) + +def rolling_rsquare(np.ndarray a, int window): + cdef Rsquare r = Rsquare(window) + return rolling(r, a) + +def rolling_resi(np.ndarray a, int window): + cdef Resi r = Resi(window) + return rolling(r, a) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/base.py new file mode 100644 index 0000000000000000000000000000000000000000..496ae38ee2305c40dd729b56118deb9d0be6e2df --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/base.py @@ -0,0 +1,281 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +from __future__ import division +from __future__ import print_function + +import abc +import pandas as pd +from ..log import get_module_logger + + +class Expression(abc.ABC): + """ + Expression base class + + Expression is designed to handle the calculation of data with the format below + data with two dimension for each instrument, + + - feature + - time: it could be observation time or period time. + + - 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). + """ + + def __str__(self): + return type(self).__name__ + + def __repr__(self): + return str(self) + + def __gt__(self, other): + from .ops import Gt # pylint: disable=C0415 + + return Gt(self, other) + + def __ge__(self, other): + from .ops import Ge # pylint: disable=C0415 + + return Ge(self, other) + + def __lt__(self, other): + from .ops import Lt # pylint: disable=C0415 + + return Lt(self, other) + + def __le__(self, other): + from .ops import Le # pylint: disable=C0415 + + return Le(self, other) + + def __eq__(self, other): + from .ops import Eq # pylint: disable=C0415 + + return Eq(self, other) + + def __ne__(self, other): + from .ops import Ne # pylint: disable=C0415 + + return Ne(self, other) + + def __add__(self, other): + from .ops import Add # pylint: disable=C0415 + + return Add(self, other) + + def __radd__(self, other): + from .ops import Add # pylint: disable=C0415 + + return Add(other, self) + + def __sub__(self, other): + from .ops import Sub # pylint: disable=C0415 + + return Sub(self, other) + + def __rsub__(self, other): + from .ops import Sub # pylint: disable=C0415 + + return Sub(other, self) + + def __mul__(self, other): + from .ops import Mul # pylint: disable=C0415 + + return Mul(self, other) + + def __rmul__(self, other): + from .ops import Mul # pylint: disable=C0415 + + return Mul(self, other) + + def __div__(self, other): + from .ops import Div # pylint: disable=C0415 + + return Div(self, other) + + def __rdiv__(self, other): + from .ops import Div # pylint: disable=C0415 + + return Div(other, self) + + def __truediv__(self, other): + from .ops import Div # pylint: disable=C0415 + + return Div(self, other) + + def __rtruediv__(self, other): + from .ops import Div # pylint: disable=C0415 + + return Div(other, self) + + def __pow__(self, other): + from .ops import Power # pylint: disable=C0415 + + return Power(self, other) + + def __rpow__(self, other): + from .ops import Power # pylint: disable=C0415 + + return Power(other, self) + + def __and__(self, other): + from .ops import And # pylint: disable=C0415 + + return And(self, other) + + def __rand__(self, other): + from .ops import And # pylint: disable=C0415 + + return And(other, self) + + def __or__(self, other): + from .ops import Or # pylint: disable=C0415 + + return Or(self, other) + + def __ror__(self, other): + from .ops import Or # pylint: disable=C0415 + + return Or(other, self) + + def load(self, instrument, start_index, end_index, *args): + """load feature + This function is responsible for loading feature/expression based on the expression engine. + + The concrete implementation will be separated into two parts: + + 1) caching data, handle errors. + + - This part is shared by all the expressions and implemented in Expression + 2) processing and calculating data based on the specific expression. + + - This part is different in each expression and implemented in each expression + + Expression Engine is shared by different data. + Different data will have different extra information for `args`. + + Parameters + ---------- + instrument : str + instrument code. + start_index : str + feature start index [in calendar]. + end_index : str + feature end index [in calendar]. + + *args may contain following information: + 1) if it is used in basic expression engine data, it contains following arguments + freq: str + feature frequency. + + 2) if is used in PIT data, it contains following arguments + cur_pit: + it is designed for the point-in-time data. + period: int + This is used for query specific period. + The period is represented with int in Qlib. (e.g. 202001 may represent the first quarter in 2020) + + Returns + ---------- + pd.Series + feature series: The index of the series is the calendar index + """ + from .cache import H # pylint: disable=C0415 + + # cache + cache_key = str(self), instrument, start_index, end_index, *args + if cache_key in H["f"]: + return H["f"][cache_key] + if start_index is not None and end_index is not None and start_index > end_index: + raise ValueError("Invalid index range: {} {}".format(start_index, end_index)) + try: + series = self._load_internal(instrument, start_index, end_index, *args) + except Exception as e: + get_module_logger("data").debug( + f"Loading data error: instrument={instrument}, expression={str(self)}, " + f"start_index={start_index}, end_index={end_index}, args={args}. " + f"error info: {str(e)}" + ) + raise + series.name = str(self) + H["f"][cache_key] = series + return series + + @abc.abstractmethod + def _load_internal(self, instrument, start_index, end_index, *args) -> pd.Series: + raise NotImplementedError("This function must be implemented in your newly defined feature") + + @abc.abstractmethod + def get_longest_back_rolling(self): + """Get the longest length of historical data the feature has accessed + + This is designed for getting the needed range of the data to calculate + the features in specific range at first. However, situations like + Ref(Ref($close, -1), 1) can not be handled rightly. + + So this will only used for detecting the length of historical data needed. + """ + # TODO: forward operator like Ref($close, -1) is not supported yet. + raise NotImplementedError("This function must be implemented in your newly defined feature") + + @abc.abstractmethod + def get_extended_window_size(self): + """get_extend_window_size + + For to calculate this Operator in range[start_index, end_index] + We have to get the *leaf feature* in + range[start_index - lft_etd, end_index + rght_etd]. + + Returns + ---------- + (int, int) + lft_etd, rght_etd + """ + raise NotImplementedError("This function must be implemented in your newly defined feature") + + +class Feature(Expression): + """Static Expression + + This kind of feature will load data from provider + """ + + def __init__(self, name=None): + if name: + self._name = name + else: + self._name = type(self).__name__ + + def __str__(self): + return "$" + self._name + + def _load_internal(self, instrument, start_index, end_index, freq): + # load + from .data import FeatureD # pylint: disable=C0415 + + return FeatureD.feature(instrument, str(self), start_index, end_index, freq) + + def get_longest_back_rolling(self): + return 0 + + def get_extended_window_size(self): + return 0, 0 + + +class PFeature(Feature): + def __str__(self): + return "$$" + self._name + + def _load_internal(self, instrument, start_index, end_index, cur_time, period=None): + from .data import PITD # pylint: disable=C0415 + + return PITD.period_feature(instrument, str(self), start_index, end_index, cur_time, period) + + +class ExpressionOps(Expression): + """Operator Expression + + This kind of feature will use operator for feature + construction on the fly. + """ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/cache.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/cache.py new file mode 100644 index 0000000000000000000000000000000000000000..fbf6e839db1cc06fb0d12b8283de3b98167d5374 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/cache.py @@ -0,0 +1,1199 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +from __future__ import division +from __future__ import print_function + +import os +import sys +import stat +import time +import pickle +import traceback +import redis_lock +import contextlib +import abc +from pathlib import Path +import numpy as np +import pandas as pd +from typing import Union, Iterable +from collections import OrderedDict + +from ..config import C +from ..utils import ( + hash_args, + get_redis_connection, + read_bin, + parse_field, + remove_fields_space, + normalize_cache_fields, + normalize_cache_instruments, +) +from ..utils.pickle_utils import restricted_pickle_load + +from ..log import get_module_logger +from .base import Feature +from .ops import Operators # pylint: disable=W0611 # noqa: F401 + + +class QlibCacheException(RuntimeError): + pass + + +class MemCacheUnit(abc.ABC): + """Memory Cache Unit.""" + + def __init__(self, *args, **kwargs): + self.size_limit = kwargs.pop("size_limit", 0) + self._size = 0 + self.od = OrderedDict() + + def __setitem__(self, key, value): + # TODO: thread safe?__setitem__ failure might cause inconsistent size? + + # precalculate the size after od.__setitem__ + self._adjust_size(key, value) + + self.od.__setitem__(key, value) + + # move the key to end,make it latest + self.od.move_to_end(key) + + if self.limited: + # pop the oldest items beyond size limit + while self._size > self.size_limit: + self.popitem(last=False) + + def __getitem__(self, key): + v = self.od.__getitem__(key) + self.od.move_to_end(key) + return v + + def __contains__(self, key): + return key in self.od + + def __len__(self): + return self.od.__len__() + + def __repr__(self): + return f"{self.__class__.__name__}\n{self.od.__repr__()}" + + def set_limit_size(self, limit): + self.size_limit = limit + + @property + def limited(self): + """whether memory cache is limited""" + return self.size_limit > 0 + + @property + def total_size(self): + return self._size + + def clear(self): + self._size = 0 + self.od.clear() + + def popitem(self, last=True): + k, v = self.od.popitem(last=last) + self._size -= self._get_value_size(v) + + return k, v + + def pop(self, key): + v = self.od.pop(key) + self._size -= self._get_value_size(v) + + return v + + def _adjust_size(self, key, value): + if key in self.od: + self._size -= self._get_value_size(self.od[key]) + + self._size += self._get_value_size(value) + + @abc.abstractmethod + def _get_value_size(self, value): + raise NotImplementedError + + +class MemCacheLengthUnit(MemCacheUnit): + def __init__(self, size_limit=0): + super().__init__(size_limit=size_limit) + + def _get_value_size(self, value): + return 1 + + +class MemCacheSizeofUnit(MemCacheUnit): + def __init__(self, size_limit=0): + super().__init__(size_limit=size_limit) + + def _get_value_size(self, value): + return sys.getsizeof(value) + + +class MemCache: + """Memory cache.""" + + def __init__(self, mem_cache_size_limit=None, limit_type="length"): + """ + + Parameters + ---------- + mem_cache_size_limit: + cache max size. + limit_type: + length or sizeof; length(call fun: len), size(call fun: sys.getsizeof). + """ + + size_limit = C.mem_cache_size_limit if mem_cache_size_limit is None else mem_cache_size_limit + limit_type = C.mem_cache_limit_type if limit_type is None else limit_type + + if limit_type == "length": + klass = MemCacheLengthUnit + elif limit_type == "sizeof": + klass = MemCacheSizeofUnit + else: + raise ValueError(f"limit_type must be length or sizeof, your limit_type is {limit_type}") + + self.__calendar_mem_cache = klass(size_limit) + self.__instrument_mem_cache = klass(size_limit) + self.__feature_mem_cache = klass(size_limit) + + def __getitem__(self, key): + if key == "c": + return self.__calendar_mem_cache + elif key == "i": + return self.__instrument_mem_cache + elif key == "f": + return self.__feature_mem_cache + else: + raise KeyError("Unknown memcache unit") + + def clear(self): + self.__calendar_mem_cache.clear() + self.__instrument_mem_cache.clear() + self.__feature_mem_cache.clear() + + +class MemCacheExpire: + CACHE_EXPIRE = C.mem_cache_expire + + @staticmethod + def set_cache(mem_cache, key, value): + """set cache + + :param mem_cache: MemCache attribute('c'/'i'/'f'). + :param key: cache key. + :param value: cache value. + """ + mem_cache[key] = value, time.time() + + @staticmethod + def get_cache(mem_cache, key): + """get mem cache + + :param mem_cache: MemCache attribute('c'/'i'/'f'). + :param key: cache key. + :return: cache value; if cache not exist, return None. + """ + value = None + expire = False + if key in mem_cache: + value, latest_time = mem_cache[key] + expire = (time.time() - latest_time) > MemCacheExpire.CACHE_EXPIRE + return value, expire + + +class CacheUtils: + LOCK_ID = "QLIB" + + @staticmethod + def organize_meta_file(): + pass + + @staticmethod + def reset_lock(): + r = get_redis_connection() + redis_lock.reset_all(r) + + @staticmethod + def visit(cache_path: Union[str, Path]): + # FIXME: Because read_lock was canceled when reading the cache, multiple processes may have read and write exceptions here + try: + cache_path = Path(cache_path) + meta_path = cache_path.with_suffix(".meta") + with meta_path.open("rb") as f: + d = restricted_pickle_load(f) + with meta_path.open("wb") as f: + try: + d["meta"]["last_visit"] = str(time.time()) + d["meta"]["visits"] = d["meta"]["visits"] + 1 + except KeyError as key_e: + raise KeyError("Unknown meta keyword") from key_e + pickle.dump(d, f, protocol=C.dump_protocol_version) + except Exception as e: + get_module_logger("CacheUtils").warning(f"visit {cache_path} cache error: {e}") + + @staticmethod + def acquire(lock, lock_name): + try: + lock.acquire() + except redis_lock.AlreadyAcquired as lock_acquired: + raise QlibCacheException( + f"""It sees the key(lock:{repr(lock_name)[1:-1]}-wlock) of the redis lock has existed in your redis db now. + You can use the following command to clear your redis keys and rerun your commands: + $ redis-cli + > select {C.redis_task_db} + > del "lock:{repr(lock_name)[1:-1]}-wlock" + > quit + If the issue is not resolved, use "keys *" to find if multiple keys exist. If so, try using "flushall" to clear all the keys. + """ + ) from lock_acquired + + @staticmethod + @contextlib.contextmanager + def reader_lock(redis_t, lock_name: str): + current_cache_rlock = redis_lock.Lock(redis_t, f"{lock_name}-rlock") + current_cache_wlock = redis_lock.Lock(redis_t, f"{lock_name}-wlock") + lock_reader = f"{lock_name}-reader" + # make sure only one reader is entering + current_cache_rlock.acquire(timeout=60) + try: + current_cache_readers = redis_t.get(lock_reader) + if current_cache_readers is None or int(current_cache_readers) == 0: + CacheUtils.acquire(current_cache_wlock, lock_name) + redis_t.incr(lock_reader) + finally: + current_cache_rlock.release() + try: + yield + finally: + # make sure only one reader is leaving + current_cache_rlock.acquire(timeout=60) + try: + redis_t.decr(lock_reader) + if int(redis_t.get(lock_reader)) == 0: + redis_t.delete(lock_reader) + current_cache_wlock.reset() + finally: + current_cache_rlock.release() + + @staticmethod + @contextlib.contextmanager + def writer_lock(redis_t, lock_name): + current_cache_wlock = redis_lock.Lock(redis_t, f"{lock_name}-wlock", id=CacheUtils.LOCK_ID) + CacheUtils.acquire(current_cache_wlock, lock_name) + try: + yield + finally: + current_cache_wlock.release() + + +class BaseProviderCache: + """Provider cache base class""" + + def __init__(self, provider): + self.provider = provider + self.logger = get_module_logger(self.__class__.__name__) + + def __getattr__(self, attr): + return getattr(self.provider, attr) + + @staticmethod + def check_cache_exists(cache_path: Union[str, Path], suffix_list: Iterable = (".index", ".meta")) -> bool: + cache_path = Path(cache_path) + for p in [cache_path] + [cache_path.with_suffix(_s) for _s in suffix_list]: + if not p.exists(): + return False + return True + + @staticmethod + def clear_cache(cache_path: Union[str, Path]): + for p in [ + cache_path, + cache_path.with_suffix(".meta"), + cache_path.with_suffix(".index"), + ]: + if p.exists(): + p.unlink() + + @staticmethod + def get_cache_dir(dir_name: str, freq: str = None) -> Path: + cache_dir = Path(C.dpm.get_data_uri(freq)).joinpath(dir_name) + cache_dir.mkdir(parents=True, exist_ok=True) + return cache_dir + + +class ExpressionCache(BaseProviderCache): + """Expression cache mechanism base class. + + This class is used to wrap expression provider with self-defined expression cache mechanism. + + .. note:: Override the `_uri` and `_expression` method to create your own expression cache mechanism. + """ + + def expression(self, instrument, field, start_time, end_time, freq): + """Get expression data. + + .. note:: Same interface as `expression` method in expression provider + """ + try: + return self._expression(instrument, field, start_time, end_time, freq) + except NotImplementedError: + return self.provider.expression(instrument, field, start_time, end_time, freq) + + def _uri(self, instrument, field, start_time, end_time, freq): + """Get expression cache file uri. + + Override this method to define how to get expression cache file uri corresponding to users' own cache mechanism. + """ + raise NotImplementedError("Implement this function to match your own cache mechanism") + + def _expression(self, instrument, field, start_time, end_time, freq): + """Get expression data using cache. + + Override this method to define how to get expression data corresponding to users' own cache mechanism. + """ + raise NotImplementedError("Implement this method if you want to use expression cache") + + def update(self, cache_uri: Union[str, Path], freq: str = "day"): + """Update expression cache to latest calendar. + + Override this method to define how to update expression cache corresponding to users' own cache mechanism. + + Parameters + ---------- + cache_uri : str or Path + the complete uri of expression cache file (include dir path). + freq : str + + Returns + ------- + int + 0(successful update)/ 1(no need to update)/ 2(update failure). + """ + raise NotImplementedError("Implement this method if you want to make expression cache up to date") + + +class DatasetCache(BaseProviderCache): + """Dataset cache mechanism base class. + + This class is used to wrap dataset provider with self-defined dataset cache mechanism. + + .. note:: Override the `_uri` and `_dataset` method to create your own dataset cache mechanism. + """ + + HDF_KEY = "df" + + def dataset( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[] + ): + """Get feature dataset. + + .. note:: Same interface as `dataset` method in dataset provider + + .. note:: The server use redis_lock to make sure + read-write conflicts will not be triggered + but client readers are not considered. + """ + if disk_cache == 0: + # skip cache + return self.provider.dataset( + instruments, fields, start_time, end_time, freq, inst_processors=inst_processors + ) + else: + # use and replace cache + try: + return self._dataset( + instruments, fields, start_time, end_time, freq, disk_cache, inst_processors=inst_processors + ) + except NotImplementedError: + return self.provider.dataset( + instruments, fields, start_time, end_time, freq, inst_processors=inst_processors + ) + + def _uri(self, instruments, fields, start_time, end_time, freq, **kwargs): + """Get dataset cache file uri. + + Override this method to define how to get dataset cache file uri corresponding to users' own cache mechanism. + """ + raise NotImplementedError("Implement this function to match your own cache mechanism") + + def _dataset( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[] + ): + """Get feature dataset using cache. + + Override this method to define how to get feature dataset corresponding to users' own cache mechanism. + """ + raise NotImplementedError("Implement this method if you want to use dataset feature cache") + + def _dataset_uri( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[] + ): + """Get a uri of feature dataset using cache. + specially: + disk_cache=1 means using data set cache and return the uri of cache file. + disk_cache=0 means client knows the path of expression cache, + server checks if the cache exists(if not, generate it), and client loads data by itself. + Override this method to define how to get feature dataset uri corresponding to users' own cache mechanism. + """ + raise NotImplementedError( + "Implement this method if you want to use dataset feature cache as a cache file for client" + ) + + def update(self, cache_uri: Union[str, Path], freq: str = "day"): + """Update dataset cache to latest calendar. + + Override this method to define how to update dataset cache corresponding to users' own cache mechanism. + + Parameters + ---------- + cache_uri : str or Path + the complete uri of dataset cache file (include dir path). + freq : str + + Returns + ------- + int + 0(successful update)/ 1(no need to update)/ 2(update failure) + """ + raise NotImplementedError("Implement this method if you want to make expression cache up to date") + + @staticmethod + def cache_to_origin_data(data, fields): + """cache data to origin data + + :param data: pd.DataFrame, cache data. + :param fields: feature fields. + :return: pd.DataFrame. + """ + not_space_fields = remove_fields_space(fields) + data = data.loc[:, not_space_fields] + # set features fields + data.columns = [str(i) for i in fields] + return data + + @staticmethod + def normalize_uri_args(instruments, fields, freq): + """normalize uri args""" + instruments = normalize_cache_instruments(instruments) + fields = normalize_cache_fields(fields) + freq = freq.lower() + + return instruments, fields, freq + + +class DiskExpressionCache(ExpressionCache): + """Prepared cache mechanism for server.""" + + def __init__(self, provider, **kwargs): + super(DiskExpressionCache, self).__init__(provider) + self.r = get_redis_connection() + # remote==True means client is using this module, writing behaviour will not be allowed. + self.remote = kwargs.get("remote", False) + + def get_cache_dir(self, freq: str = None) -> Path: + return super(DiskExpressionCache, self).get_cache_dir(C.features_cache_dir_name, freq) + + def _uri(self, instrument, field, start_time, end_time, freq): + field = remove_fields_space(field) + instrument = str(instrument).lower() + return hash_args(instrument, field, freq) + + def _expression(self, instrument, field, start_time=None, end_time=None, freq="day"): + _cache_uri = self._uri(instrument=instrument, field=field, start_time=None, end_time=None, freq=freq) + _instrument_dir = self.get_cache_dir(freq).joinpath(instrument.lower()) + cache_path = _instrument_dir.joinpath(_cache_uri) + # get calendar + from .data import Cal # pylint: disable=C0415 + + _calendar = Cal.calendar(freq=freq) + + _, _, start_index, end_index = Cal.locate_index(start_time, end_time, freq, future=False) + + if self.check_cache_exists(cache_path, suffix_list=[".meta"]): + """ + In most cases, we do not need reader_lock. + Because updating data is a small probability event compare to reading data. + + """ + # FIXME: Removing the reader lock may result in conflicts. + # with CacheUtils.reader_lock(self.r, 'expression-%s' % _cache_uri): + + # modify expression cache meta file + try: + # FIXME: Multiple readers may result in error visit number + if not self.remote: + CacheUtils.visit(cache_path) + series = read_bin(cache_path, start_index, end_index) + return series + except Exception: + series = None + self.logger.error("reading %s file error : %s" % (cache_path, traceback.format_exc())) + return series + else: + # normalize field + field = remove_fields_space(field) + # cache unavailable, generate the cache + _instrument_dir.mkdir(parents=True, exist_ok=True) + if not isinstance(eval(parse_field(field)), Feature): + # When the expression is not a raw feature + # generate expression cache if the feature is not a Feature + # instance + series = self.provider.expression(instrument, field, _calendar[0], _calendar[-1], freq) + if not series.empty: + # This expression is empty, we don't generate any cache for it. + with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:expression-{_cache_uri}"): + self.gen_expression_cache( + expression_data=series, + cache_path=cache_path, + instrument=instrument, + field=field, + freq=freq, + last_update=str(_calendar[-1]), + ) + return series.loc[start_index:end_index] + else: + return series + else: + # If the expression is a raw feature(such as $close, $open) + return self.provider.expression(instrument, field, start_time, end_time, freq) + + def gen_expression_cache(self, expression_data, cache_path, instrument, field, freq, last_update): + """use bin file to save like feature-data.""" + # Make sure the cache runs right when the directory is deleted + # while running + meta = { + "info": {"instrument": instrument, "field": field, "freq": freq, "last_update": last_update}, + "meta": {"last_visit": time.time(), "visits": 1}, + } + self.logger.debug(f"generating expression cache: {meta}") + self.clear_cache(cache_path) + meta_path = cache_path.with_suffix(".meta") + + with meta_path.open("wb") as f: + pickle.dump(meta, f, protocol=C.dump_protocol_version) + meta_path.chmod(stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH) + df = expression_data.to_frame() + + r = np.hstack([df.index[0], expression_data]).astype(" Path: + return super(DiskDatasetCache, self).get_cache_dir(C.dataset_cache_dir_name, freq) + + @classmethod + def read_data_from_cache(cls, cache_path: Union[str, Path], start_time, end_time, fields): + """read_cache_from + + This function can read data from the disk cache dataset + + :param cache_path: + :param start_time: + :param end_time: + :param fields: The fields order of the dataset cache is sorted. So rearrange the columns to make it consistent. + :return: + """ + + im = DiskDatasetCache.IndexManager(cache_path) + index_data = im.get_index(start_time, end_time) + if index_data.shape[0] > 0: + start, stop = ( + index_data["start"].iloc[0].item(), + index_data["end"].iloc[-1].item(), + ) + else: + start = stop = 0 + + with pd.HDFStore(cache_path, mode="r") as store: + if "/{}".format(im.KEY) in store.keys(): + df = store.select(key=im.KEY, start=start, stop=stop) + df = df.swaplevel("datetime", "instrument").sort_index() + # read cache and need to replace not-space fields to field + df = cls.cache_to_origin_data(df, fields) + + else: + df = pd.DataFrame(columns=fields) + return df + + def _dataset( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=0, inst_processors=[] + ): + if disk_cache == 0: + # In this case, data_set cache is configured but will not be used. + return self.provider.dataset( + instruments, fields, start_time, end_time, freq, inst_processors=inst_processors + ) + # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date + if inst_processors: + raise ValueError( + f"{self.__class__.__name__} does not support inst_processor. " + f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`" + ) + _cache_uri = self._uri( + instruments=instruments, + fields=fields, + start_time=None, + end_time=None, + freq=freq, + disk_cache=disk_cache, + inst_processors=inst_processors, + ) + + cache_path = self.get_cache_dir(freq).joinpath(_cache_uri) + + features = pd.DataFrame() + gen_flag = False + + if self.check_cache_exists(cache_path): + if disk_cache == 1: + # use cache + with CacheUtils.reader_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"): + CacheUtils.visit(cache_path) + features = self.read_data_from_cache(cache_path, start_time, end_time, fields) + elif disk_cache == 2: + gen_flag = True + else: + gen_flag = True + + if gen_flag: + # cache unavailable, generate the cache + with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"): + features = self.gen_dataset_cache( + cache_path=cache_path, + instruments=instruments, + fields=fields, + freq=freq, + inst_processors=inst_processors, + ) + if not features.empty: + features = features.sort_index().loc(axis=0)[:, start_time:end_time] + return features + + def _dataset_uri( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=0, inst_processors=[] + ): + if disk_cache == 0: + # In this case, server only checks the expression cache. + # The client will load the cache data by itself. + from .data import LocalDatasetProvider # pylint: disable=C0415 + + LocalDatasetProvider.multi_cache_walker(instruments, fields, start_time, end_time, freq) + return "" + # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date + if inst_processors: + raise ValueError( + f"{self.__class__.__name__} does not support inst_processor. " + f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`" + ) + _cache_uri = self._uri( + instruments=instruments, + fields=fields, + start_time=None, + end_time=None, + freq=freq, + disk_cache=disk_cache, + inst_processors=inst_processors, + ) + cache_path = self.get_cache_dir(freq).joinpath(_cache_uri) + + if self.check_cache_exists(cache_path): + self.logger.debug(f"The cache dataset has already existed {cache_path}. Return the uri directly") + with CacheUtils.reader_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"): + CacheUtils.visit(cache_path) + return _cache_uri + else: + # cache unavailable, generate the cache + with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri(freq))}:dataset-{_cache_uri}"): + self.gen_dataset_cache( + cache_path=cache_path, + instruments=instruments, + fields=fields, + freq=freq, + inst_processors=inst_processors, + ) + return _cache_uri + + class IndexManager: + """ + The lock is not considered in the class. Please consider the lock outside the code. + This class is the proxy of the disk data. + """ + + KEY = "df" + + def __init__(self, cache_path: Union[str, Path]): + self.index_path = cache_path.with_suffix(".index") + self._data = None + self.logger = get_module_logger(self.__class__.__name__) + + def get_index(self, start_time=None, end_time=None): + # TODO: fast read index from the disk. + if self._data is None: + self.sync_from_disk() + return self._data.loc[start_time:end_time].copy() + + def sync_to_disk(self): + if self._data is None: + raise ValueError("No data to sync to disk.") + self._data.sort_index(inplace=True) + self._data.to_hdf(self.index_path, key=self.KEY, mode="w", format="table") + # The index should be readable for all users + self.index_path.chmod(stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH) + + def sync_from_disk(self): + # The file will not be closed directly if we read_hdf from the disk directly + with pd.HDFStore(self.index_path, mode="r") as store: + if "/{}".format(self.KEY) in store.keys(): + self._data = pd.read_hdf(store, key=self.KEY) + else: + self._data = pd.DataFrame() + + def update(self, data, sync=True): + self._data = data.astype(np.int32).copy() + if sync: + self.sync_to_disk() + + def append_index(self, data, to_disk=True): + data = data.astype(np.int32).copy() + data.sort_index(inplace=True) + self._data = pd.concat([self._data, data]) + if to_disk: + with pd.HDFStore(self.index_path) as store: + store.append(self.KEY, data, append=True) + + @staticmethod + def build_index_from_data(data, start_index=0): + if data.empty: + return pd.DataFrame() + line_data = data.groupby("datetime", group_keys=False).size() + line_data.sort_index(inplace=True) + index_end = line_data.cumsum() + index_start = index_end.shift(1, fill_value=0) + + index_data = pd.DataFrame() + index_data["start"] = index_start + index_data["end"] = index_end + index_data += start_index + return index_data + + def gen_dataset_cache(self, cache_path: Union[str, Path], instruments, fields, freq, inst_processors=[]): + """gen_dataset_cache + + .. note:: This function does not consider the cache read write lock. Please + acquire the lock outside this function + + The format the cache contains 3 parts(followed by typical filename). + + - index : cache/d41366901e25de3ec47297f12e2ba11d.index + + - The content of the file may be in following format(pandas.Series) + + .. code-block:: python + + start end + 1999-11-10 00:00:00 0 1 + 1999-11-11 00:00:00 1 2 + 1999-11-12 00:00:00 2 3 + ... + + .. note:: The start is closed. The end is open!!!!! + + - Each line contains two element with a timestamp as its index. + - It indicates the `start_index` (included) and `end_index` (excluded) of the data for `timestamp` + + - meta data: cache/d41366901e25de3ec47297f12e2ba11d.meta + + - data : cache/d41366901e25de3ec47297f12e2ba11d + + - This is a hdf file sorted by datetime + + :param cache_path: The path to store the cache. + :param instruments: The instruments to store the cache. + :param fields: The fields to store the cache. + :param freq: The freq to store the cache. + :param inst_processors: Instrument processors. + + :return type pd.DataFrame; The fields of the returned DataFrame are consistent with the parameters of the function. + """ + # get calendar + from .data import Cal # pylint: disable=C0415 + + cache_path = Path(cache_path) + _calendar = Cal.calendar(freq=freq) + self.logger.debug(f"Generating dataset cache {cache_path}") + # Make sure the cache runs right when the directory is deleted + # while running + self.clear_cache(cache_path) + + features = self.provider.dataset( + instruments, fields, _calendar[0], _calendar[-1], freq, inst_processors=inst_processors + ) + + if features.empty: + return features + + # swap index and sorted + features = features.swaplevel("instrument", "datetime").sort_index() + + # write cache data + with pd.HDFStore(str(cache_path.with_suffix(".data"))) as store: + cache_to_orig_map = dict(zip(remove_fields_space(features.columns), features.columns)) + orig_to_cache_map = dict(zip(features.columns, remove_fields_space(features.columns))) + cache_features = features[list(cache_to_orig_map.values())].rename(columns=orig_to_cache_map) + # cache columns + cache_columns = sorted(cache_features.columns) + cache_features = cache_features.loc[:, cache_columns] + cache_features = cache_features.loc[:, ~cache_features.columns.duplicated()] + store.append(DatasetCache.HDF_KEY, cache_features, append=False) + # write meta file + meta = { + "info": { + "instruments": instruments, + "fields": list(cache_features.columns), + "freq": freq, + "last_update": str(_calendar[-1]), # The last_update to store the cache + "inst_processors": inst_processors, # The last_update to store the cache + }, + "meta": {"last_visit": time.time(), "visits": 1}, + } + with cache_path.with_suffix(".meta").open("wb") as f: + pickle.dump(meta, f, protocol=C.dump_protocol_version) + cache_path.with_suffix(".meta").chmod(stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH) + # write index file + im = DiskDatasetCache.IndexManager(cache_path) + index_data = im.build_index_from_data(features) + im.update(index_data) + + # rename the file after the cache has been generated + # this doesn't work well on windows, but our server won't use windows + # temporarily + cache_path.with_suffix(".data").rename(cache_path) + # the fields of the cached features are converted to the original fields + return features.swaplevel("datetime", "instrument") + + def update(self, cache_uri, freq: str = "day"): + cp_cache_uri = self.get_cache_dir(freq).joinpath(cache_uri) + meta_path = cp_cache_uri.with_suffix(".meta") + if not self.check_cache_exists(cp_cache_uri): + self.logger.info(f"The cache {cp_cache_uri} has corrupted. It will be removed") + self.clear_cache(cp_cache_uri) + return 2 + + im = DiskDatasetCache.IndexManager(cp_cache_uri) + with CacheUtils.writer_lock(self.r, f"{str(C.dpm.get_data_uri())}:dataset-{cache_uri}"): + with meta_path.open("rb") as f: + d = restricted_pickle_load(f) + instruments = d["info"]["instruments"] + fields = d["info"]["fields"] + freq = d["info"]["freq"] + last_update_time = d["info"]["last_update"] + inst_processors = d["info"].get("inst_processors", []) + index_data = im.get_index() + + self.logger.debug("Updating dataset: {}".format(d)) + from .data import Inst # pylint: disable=C0415 + + if Inst.get_inst_type(instruments) == Inst.DICT: + self.logger.info(f"The file {cache_uri} has dict cache. Skip updating") + return 1 + + # get newest calendar + from .data import Cal # pylint: disable=C0415 + + whole_calendar = Cal.calendar(start_time=None, end_time=None, freq=freq) + # The calendar since last updated + new_calendar = Cal.calendar(start_time=last_update_time, end_time=None, freq=freq) + + # get append data + if len(new_calendar) <= 1: + # Including last updated calendar, we only get 1 item. + # No future updating is needed. + return 1 + else: + # get the data needed after the historical data are removed. + # The start index of new data + current_index = len(whole_calendar) - len(new_calendar) + 1 + + # To avoid recursive import + from .data import ExpressionD # pylint: disable=C0415 + + # The existing data length + lft_etd = rght_etd = 0 + for field in fields: + expr = ExpressionD.get_expression_instance(field) + l, r = expr.get_extended_window_size() + lft_etd = max(lft_etd, l) + rght_etd = max(rght_etd, r) + # remove the period that should be updated. + if index_data.empty: + # We don't have any data for such dataset. Nothing to remove + rm_n_period = rm_lines = 0 + else: + rm_n_period = min(rght_etd, index_data.shape[0]) + rm_lines = ( + (index_data["end"] - index_data["start"]) + .loc[whole_calendar[current_index - rm_n_period] :] + .sum() + .item() + ) + + data = self.provider.dataset( + instruments, + fields, + whole_calendar[current_index - rm_n_period], + new_calendar[-1], + freq, + inst_processors=inst_processors, + ) + + if not data.empty: + data.reset_index(inplace=True) + data.set_index(["datetime", "instrument"], inplace=True) + data.sort_index(inplace=True) + else: + return 0 # No data to update cache + + store = pd.HDFStore(cp_cache_uri) + # FIXME: + # Because the feature cache are stored as .bin file. + # So the series read from features are all float32. + # However, the first dataset cache is calculated based on the + # raw data. So the data type may be float64. + # Different data type will result in failure of appending data + if "/{}".format(DatasetCache.HDF_KEY) in store.keys(): + schema = store.select(DatasetCache.HDF_KEY, start=0, stop=0) + for col, dtype in schema.dtypes.items(): + data[col] = data[col].astype(dtype) + if rm_lines > 0: + store.remove(key=im.KEY, start=-rm_lines) + store.append(DatasetCache.HDF_KEY, data) + store.close() + + # update index file + new_index_data = im.build_index_from_data( + data.loc(axis=0)[whole_calendar[current_index] :, :], + start_index=0 if index_data.empty else index_data["end"].iloc[-1], + ) + im.append_index(new_index_data) + + # update meta file + d["info"]["last_update"] = str(new_calendar[-1]) + with meta_path.open("wb") as f: + pickle.dump(d, f, protocol=C.dump_protocol_version) + return 0 + + +class SimpleDatasetCache(DatasetCache): + """Simple dataset cache that can be used locally or on client.""" + + def __init__(self, provider): + super(SimpleDatasetCache, self).__init__(provider) + try: + self.local_cache_path: Path = Path(C["local_cache_path"]).expanduser().resolve() + except (KeyError, TypeError): + self.logger.error("Assign a local_cache_path in config if you want to use this cache mechanism") + raise + self.logger.info( + f"DatasetCache directory: {self.local_cache_path}, " + f"modify the cache directory via the local_cache_path in the config" + ) + + def _uri(self, instruments, fields, start_time, end_time, freq, disk_cache=1, inst_processors=[], **kwargs): + instruments, fields, freq = self.normalize_uri_args(instruments, fields, freq) + return hash_args( + instruments, fields, start_time, end_time, freq, disk_cache, str(self.local_cache_path), inst_processors + ) + + def _dataset( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[] + ): + if disk_cache == 0: + # In this case, data_set cache is configured but will not be used. + return self.provider.dataset(instruments, fields, start_time, end_time, freq) + self.local_cache_path.mkdir(exist_ok=True, parents=True) + cache_file = self.local_cache_path.joinpath( + self._uri( + instruments, fields, start_time, end_time, freq, disk_cache=disk_cache, inst_processors=inst_processors + ) + ) + gen_flag = False + + if cache_file.exists(): + if disk_cache == 1: + # use cache + df = pd.read_pickle(cache_file) + return self.cache_to_origin_data(df, fields) + elif disk_cache == 2: + # replace cache + gen_flag = True + else: + gen_flag = True + + if gen_flag: + data = self.provider.dataset( + instruments, normalize_cache_fields(fields), start_time, end_time, freq, inst_processors=inst_processors + ) + data.to_pickle(cache_file) + return self.cache_to_origin_data(data, fields) + + +class DatasetURICache(DatasetCache): + """Prepared cache mechanism for server.""" + + def _uri(self, instruments, fields, start_time, end_time, freq, disk_cache=1, inst_processors=[], **kwargs): + return hash_args(*self.normalize_uri_args(instruments, fields, freq), disk_cache, inst_processors) + + def dataset( + self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=0, inst_processors=[] + ): + if "local" in C.dataset_provider.lower(): + # use LocalDatasetProvider + return self.provider.dataset( + instruments, fields, start_time, end_time, freq, inst_processors=inst_processors + ) + + if disk_cache == 0: + # do not use data_set cache, load data from remote expression cache directly + return self.provider.dataset( + instruments, + fields, + start_time, + end_time, + freq, + disk_cache, + return_uri=False, + inst_processors=inst_processors, + ) + # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date + if inst_processors: + raise ValueError( + f"{self.__class__.__name__} does not support inst_processor. " + f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`" + ) + # use ClientDatasetProvider + feature_uri = self._uri( + instruments, fields, None, None, freq, disk_cache=disk_cache, inst_processors=inst_processors + ) + value, expire = MemCacheExpire.get_cache(H["f"], feature_uri) + mnt_feature_uri = C.dpm.get_data_uri(freq).joinpath(C.dataset_cache_dir_name).joinpath(feature_uri) + if value is None or expire or not mnt_feature_uri.exists(): + df, uri = self.provider.dataset( + instruments, + fields, + start_time, + end_time, + freq, + disk_cache, + return_uri=True, + inst_processors=inst_processors, + ) + # cache uri + MemCacheExpire.set_cache(H["f"], uri, uri) + # cache DataFrame + # HZ['f'][uri] = df.copy() + get_module_logger("cache").debug(f"get feature from {C.dataset_provider}") + else: + df = DiskDatasetCache.read_data_from_cache(mnt_feature_uri, start_time, end_time, fields) + get_module_logger("cache").debug("get feature from uri cache") + + return df + + +class CalendarCache(BaseProviderCache): + pass + + +class MemoryCalendarCache(CalendarCache): + def calendar(self, start_time=None, end_time=None, freq="day", future=False): + uri = self._uri(start_time, end_time, freq, future) + result, expire = MemCacheExpire.get_cache(H["c"], uri) + if result is None or expire: + result = self.provider.calendar(start_time, end_time, freq, future) + MemCacheExpire.set_cache(H["c"], uri, result) + + get_module_logger("data").debug(f"get calendar from {C.calendar_provider}") + else: + get_module_logger("data").debug("get calendar from local cache") + + return result + + +H = MemCache() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/client.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/client.py new file mode 100644 index 0000000000000000000000000000000000000000..d9af2456d3eb17c40d2810ee0239e2e79540dfae --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/client.py @@ -0,0 +1,103 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +from __future__ import division, print_function + +import json + +import socketio + +import qlib + +from ..log import get_module_logger + + +class Client: + """A client class + + Provide the connection tool functions for ClientProvider. + """ + + def __init__(self, host, port): + super(Client, self).__init__() + self.sio = socketio.Client() + self.server_host = host + self.server_port = port + self.logger = get_module_logger(self.__class__.__name__) + # bind connect/disconnect callbacks + self.sio.on( + "connect", + lambda: self.logger.debug("Connect to server {}".format(self.sio.connection_url)), + ) + self.sio.on("disconnect", lambda: self.logger.debug("Disconnect from server!")) + + def connect_server(self): + """Connect to server.""" + try: + self.sio.connect(f"ws://{self.server_host}:{self.server_port}") + except socketio.exceptions.ConnectionError: + self.logger.error("Cannot connect to server - check your network or server status") + + def disconnect(self): + """Disconnect from server.""" + try: + self.sio.eio.disconnect(True) + except Exception as e: + self.logger.error("Cannot disconnect from server : %s" % e) + + def send_request(self, request_type, request_content, msg_queue, msg_proc_func=None): + """Send a certain request to server. + + Parameters + ---------- + request_type : str + type of proposed request, 'calendar'/'instrument'/'feature'. + request_content : dict + records the information of the request. + msg_proc_func : func + the function to process the message when receiving response, should have arg `*args`. + msg_queue: Queue + The queue to pass the message after callback. + """ + head_info = {"version": qlib.__version__} + + def request_callback(*args): + """callback_wrapper + + :param *args: args[0] is the response content + """ + # args[0] is the response content + self.logger.debug("receive data and enter queue") + msg = dict(args[0]) + if msg["detailed_info"] is not None: + if msg["status"] != 0: + self.logger.error(msg["detailed_info"]) + else: + self.logger.info(msg["detailed_info"]) + if msg["status"] != 0: + ex = ValueError(f"Bad response(status=={msg['status']}), detailed info: {msg['detailed_info']}") + msg_queue.put(ex) + else: + if msg_proc_func is not None: + try: + ret = msg_proc_func(msg["result"]) + except Exception as e: + self.logger.exception("Error when processing message.") + ret = e + else: + ret = msg["result"] + msg_queue.put(ret) + self.disconnect() + self.logger.debug("disconnected") + + self.logger.debug("try connecting") + self.connect_server() + self.logger.debug("connected") + # The pickle is for passing some parameters with special type(such as + # pd.Timestamp) + request_content = {"head": head_info, "body": json.dumps(request_content, default=str)} + self.sio.on(request_type + "_response", request_callback) + self.logger.debug("try sending") + self.sio.emit(request_type + "_request", request_content) + self.sio.wait() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/data.py new file mode 100644 index 0000000000000000000000000000000000000000..aba75c0b1ab1bbe16e65961ca32fe27eef9e82f4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/data.py @@ -0,0 +1,1332 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +from __future__ import division +from __future__ import print_function + +import re +import abc +import copy +import queue +import bisect +import numpy as np +import pandas as pd +from typing import List, Union, Optional + +# For supporting multiprocessing in outer code, joblib is used +from joblib import delayed + +from .cache import H +from ..config import C +from .inst_processor import InstProcessor + +from ..log import get_module_logger +from .cache import DiskDatasetCache +from ..utils import ( + Wrapper, + init_instance_by_config, + register_wrapper, + get_module_by_module_path, + parse_field, + hash_args, + normalize_cache_fields, + code_to_fname, + time_to_slc_point, + read_period_data, + get_period_list, +) +from ..utils.paral import ParallelExt +from .ops import Operators # pylint: disable=W0611 # noqa: F401 + + +class ProviderBackendMixin: + """ + This helper class tries to make the provider based on storage backend more convenient + It is not necessary to inherent this class if that provider don't rely on the backend storage + """ + + def get_default_backend(self): + backend = {} + provider_name: str = re.findall("[A-Z][^A-Z]*", self.__class__.__name__)[-2] + # set default storage class + backend.setdefault("class", f"File{provider_name}Storage") + # set default storage module + backend.setdefault("module_path", "qlib.data.storage.file_storage") + return backend + + def backend_obj(self, **kwargs): + backend = self.backend if self.backend else self.get_default_backend() + backend = copy.deepcopy(backend) + backend.setdefault("kwargs", {}).update(**kwargs) + return init_instance_by_config(backend) + + +class CalendarProvider(abc.ABC): + """Calendar provider base class + + Provide calendar data. + """ + + def calendar(self, start_time=None, end_time=None, freq="day", future=False): + """Get calendar of certain market in given time range. + + Parameters + ---------- + start_time : str + start of the time range. + end_time : str + end of the time range. + freq : str + time frequency, available: year/quarter/month/week/day. + future : bool + whether including future trading day. + + Returns + ---------- + list + calendar list + """ + _calendar, _calendar_index = self._get_calendar(freq, future) + if start_time == "None": + start_time = None + if end_time == "None": + end_time = None + # strip + if start_time: + start_time = pd.Timestamp(start_time) + if start_time > _calendar[-1]: + return np.array([]) + else: + start_time = _calendar[0] + if end_time: + end_time = pd.Timestamp(end_time) + if end_time < _calendar[0]: + return np.array([]) + else: + end_time = _calendar[-1] + _, _, si, ei = self.locate_index(start_time, end_time, freq, future) + return _calendar[si : ei + 1] + + def locate_index( + self, start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], freq: str, future: bool = False + ): + """Locate the start time index and end time index in a calendar under certain frequency. + + Parameters + ---------- + start_time : pd.Timestamp + start of the time range. + end_time : pd.Timestamp + end of the time range. + freq : str + time frequency, available: year/quarter/month/week/day. + future : bool + whether including future trading day. + + Returns + ------- + pd.Timestamp + the real start time. + pd.Timestamp + the real end time. + int + the index of start time. + int + the index of end time. + """ + start_time = pd.Timestamp(start_time) + end_time = pd.Timestamp(end_time) + calendar, calendar_index = self._get_calendar(freq=freq, future=future) + if start_time not in calendar_index: + try: + start_time = calendar[bisect.bisect_left(calendar, start_time)] + except IndexError as index_e: + raise IndexError( + "`start_time` uses a future date, if you want to get future trading days, you can use: `future=True`" + ) from index_e + start_index = calendar_index[start_time] + if end_time not in calendar_index: + end_time = calendar[bisect.bisect_right(calendar, end_time) - 1] + end_index = calendar_index[end_time] + return start_time, end_time, start_index, end_index + + def _get_calendar(self, freq, future): + """Load calendar using memcache. + + Parameters + ---------- + freq : str + frequency of read calendar file. + future : bool + whether including future trading day. + + Returns + ------- + list + list of timestamps. + dict + dict composed by timestamp as key and index as value for fast search. + """ + flag = f"{freq}_future_{future}" + if flag not in H["c"]: + _calendar = np.array(self.load_calendar(freq, future)) + _calendar_index = {x: i for i, x in enumerate(_calendar)} # for fast search + H["c"][flag] = _calendar, _calendar_index + return H["c"][flag] + + def _uri(self, start_time, end_time, freq, future=False): + """Get the uri of calendar generation task.""" + return hash_args(start_time, end_time, freq, future) + + def load_calendar(self, freq, future): + """Load original calendar timestamp from file. + + Parameters + ---------- + freq : str + frequency of read calendar file. + future: bool + + Returns + ---------- + list + list of timestamps + """ + raise NotImplementedError("Subclass of CalendarProvider must implement `load_calendar` method") + + +class InstrumentProvider(abc.ABC): + """Instrument provider base class + + Provide instrument data. + """ + + @staticmethod + def instruments(market: Union[List, str] = "all", filter_pipe: Union[List, None] = None): + """Get the general config dictionary for a base market adding several dynamic filters. + + Parameters + ---------- + market : Union[List, str] + str: + market/industry/index shortname, e.g. all/sse/szse/sse50/csi300/csi500. + list: + ["ID1", "ID2"]. A list of stocks + filter_pipe : list + the list of dynamic filters. + + Returns + ---------- + dict: if isinstance(market, str) + dict of stockpool config. + + {`market` => base market name, `filter_pipe` => list of filters} + + example : + + .. code-block:: + + {'market': 'csi500', + 'filter_pipe': [{'filter_type': 'ExpressionDFilter', + 'rule_expression': '$open<40', + 'filter_start_time': None, + 'filter_end_time': None, + 'keep': False}, + {'filter_type': 'NameDFilter', + 'name_rule_re': 'SH[0-9]{4}55', + 'filter_start_time': None, + 'filter_end_time': None}]} + + list: if isinstance(market, list) + just return the original list directly. + NOTE: this will make the instruments compatible with more cases. The user code will be simpler. + """ + if isinstance(market, list): + return market + from .filter import SeriesDFilter # pylint: disable=C0415 + + if filter_pipe is None: + filter_pipe = [] + config = {"market": market, "filter_pipe": []} + # the order of the filters will affect the result, so we need to keep + # the order + for filter_t in filter_pipe: + if isinstance(filter_t, dict): + _config = filter_t + elif isinstance(filter_t, SeriesDFilter): + _config = filter_t.to_config() + else: + raise TypeError( + f"Unsupported filter types: {type(filter_t)}! Filter only supports dict or isinstance(filter, SeriesDFilter)" + ) + config["filter_pipe"].append(_config) + return config + + @abc.abstractmethod + def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False): + """List the instruments based on a certain stockpool config. + + Parameters + ---------- + instruments : dict + stockpool config. + start_time : str + start of the time range. + end_time : str + end of the time range. + as_list : bool + return instruments as list or dict. + + Returns + ------- + dict or list + instruments list or dictionary with time spans + """ + raise NotImplementedError("Subclass of InstrumentProvider must implement `list_instruments` method") + + def _uri(self, instruments, start_time=None, end_time=None, freq="day", as_list=False): + return hash_args(instruments, start_time, end_time, freq, as_list) + + # instruments type + LIST = "LIST" + DICT = "DICT" + CONF = "CONF" + + @classmethod + def get_inst_type(cls, inst): + if "market" in inst: + return cls.CONF + if isinstance(inst, dict): + return cls.DICT + if isinstance(inst, (list, tuple, pd.Index, np.ndarray)): + return cls.LIST + raise ValueError(f"Unknown instrument type {inst}") + + +class FeatureProvider(abc.ABC): + """Feature provider class + + Provide feature data. + """ + + @abc.abstractmethod + def feature(self, instrument, field, start_time, end_time, freq): + """Get feature data. + + Parameters + ---------- + instrument : str + a certain instrument. + field : str + a certain field of feature. + start_time : str + start of the time range. + end_time : str + end of the time range. + freq : str + time frequency, available: year/quarter/month/week/day. + + Returns + ------- + pd.Series + data of a certain feature + """ + raise NotImplementedError("Subclass of FeatureProvider must implement `feature` method") + + +class PITProvider(abc.ABC): + @abc.abstractmethod + def period_feature( + self, + instrument, + field, + start_index: int, + end_index: int, + cur_time: pd.Timestamp, + period: Optional[int] = None, + ) -> pd.Series: + """ + get the historical periods data series between `start_index` and `end_index` + + Parameters + ---------- + start_index: int + start_index is a relative index to the latest period to cur_time + + end_index: int + end_index is a relative index to the latest period to cur_time + in most cases, the start_index and end_index will be a non-positive values + For example, start_index == -3 end_index == 0 and current period index is cur_idx, + then the data between [start_index + cur_idx, end_index + cur_idx] will be retrieved. + + period: int + This is used for query specific period. + The period is represented with int in Qlib. (e.g. 202001 may represent the first quarter in 2020) + NOTE: `period` will override `start_index` and `end_index` + + Returns + ------- + pd.Series + The index will be integers to indicate the periods of the data + An typical examples will be + TODO + + Raises + ------ + FileNotFoundError + This exception will be raised if the queried data do not exist. + """ + raise NotImplementedError(f"Please implement the `period_feature` method") + + +class ExpressionProvider(abc.ABC): + """Expression provider class + + Provide Expression data. + """ + + def __init__(self): + self.expression_instance_cache = {} + + def get_expression_instance(self, field): + try: + if field in self.expression_instance_cache: + expression = self.expression_instance_cache[field] + else: + expression = eval(parse_field(field)) + self.expression_instance_cache[field] = expression + except NameError as e: + get_module_logger("data").exception( + "ERROR: field [%s] contains invalid operator/variable [%s]" % (str(field), str(e).split()[1]) + ) + raise + except SyntaxError: + get_module_logger("data").exception("ERROR: field [%s] contains invalid syntax" % str(field)) + raise + return expression + + @abc.abstractmethod + def expression(self, instrument, field, start_time=None, end_time=None, freq="day") -> pd.Series: + """Get Expression data. + + The responsibility of `expression` + - parse the `field` and `load` the according data. + - When loading the data, it should handle the time dependency of the data. `get_expression_instance` is commonly used in this method + + Parameters + ---------- + instrument : str + a certain instrument. + field : str + a certain field of feature. + start_time : str + start of the time range. + end_time : str + end of the time range. + freq : str + time frequency, available: year/quarter/month/week/day. + + Returns + ------- + pd.Series + data of a certain expression + + The data has two types of format + + 1) expression with datetime index + + 2) expression with integer index + + - because the datetime is not as good as + """ + raise NotImplementedError("Subclass of ExpressionProvider must implement `Expression` method") + + +class DatasetProvider(abc.ABC): + """Dataset provider class + + Provide Dataset data. + """ + + @abc.abstractmethod + def dataset(self, instruments, fields, start_time=None, end_time=None, freq="day", inst_processors=[]): + """Get dataset data. + + Parameters + ---------- + instruments : list or dict + list/dict of instruments or dict of stockpool config. + fields : list + list of feature instances. + start_time : str + start of the time range. + end_time : str + end of the time range. + freq : str + time frequency. + inst_processors: Iterable[Union[dict, InstProcessor]] + the operations performed on each instrument + + Returns + ---------- + pd.DataFrame + a pandas dataframe with index. + """ + raise NotImplementedError("Subclass of DatasetProvider must implement `Dataset` method") + + def _uri( + self, + instruments, + fields, + start_time=None, + end_time=None, + freq="day", + disk_cache=1, + inst_processors=[], + **kwargs, + ): + """Get task uri, used when generating rabbitmq task in qlib_server + + Parameters + ---------- + instruments : list or dict + list/dict of instruments or dict of stockpool config. + fields : list + list of feature instances. + start_time : str + start of the time range. + end_time : str + end of the time range. + freq : str + time frequency. + disk_cache : int + whether to skip(0)/use(1)/replace(2) disk_cache. + + """ + # TODO: qlib-server support inst_processors + return DiskDatasetCache._uri(instruments, fields, start_time, end_time, freq, disk_cache, inst_processors) + + @staticmethod + def get_instruments_d(instruments, freq): + """ + Parse different types of input instruments to output instruments_d + Wrong format of input instruments will lead to exception. + + """ + if isinstance(instruments, dict): + if "market" in instruments: + # dict of stockpool config + instruments_d = Inst.list_instruments(instruments=instruments, freq=freq, as_list=False) + else: + # dict of instruments and timestamp + instruments_d = instruments + elif isinstance(instruments, (list, tuple, pd.Index, np.ndarray)): + # list or tuple of a group of instruments + instruments_d = list(instruments) + else: + raise ValueError("Unsupported input type for param `instrument`") + return instruments_d + + @staticmethod + def get_column_names(fields): + """ + Get column names from input fields + + """ + if len(fields) == 0: + raise ValueError("fields cannot be empty") + column_names = [str(f) for f in fields] + return column_names + + @staticmethod + def parse_fields(fields): + # parse and check the input fields + return [ExpressionD.get_expression_instance(f) for f in fields] + + @staticmethod + def dataset_processor(instruments_d, column_names, start_time, end_time, freq, inst_processors=[]): + """ + Load and process the data, return the data set. + - default using multi-kernel method. + + """ + normalize_column_names = normalize_cache_fields(column_names) + # One process for one task, so that the memory will be freed quicker. + workers = max(min(C.get_kernels(freq), len(instruments_d)), 1) + + # create iterator + if isinstance(instruments_d, dict): + it = instruments_d.items() + else: + it = zip(instruments_d, [None] * len(instruments_d)) + + inst_l = [] + task_l = [] + for inst, spans in it: + inst_l.append(inst) + task_l.append( + delayed(DatasetProvider.inst_calculator)( + inst, start_time, end_time, freq, normalize_column_names, spans, C, inst_processors + ) + ) + + data = dict( + zip( + inst_l, + ParallelExt(n_jobs=workers, backend=C.joblib_backend, maxtasksperchild=C.maxtasksperchild)(task_l), + ) + ) + + new_data = dict() + for inst in sorted(data.keys()): + if len(data[inst]) > 0: + # NOTE: Python version >= 3.6; in versions after python3.6, dict will always guarantee the insertion order + new_data[inst] = data[inst] + + if len(new_data) > 0: + data = pd.concat(new_data, names=["instrument"], sort=False) + data = DiskDatasetCache.cache_to_origin_data(data, column_names) + else: + data = pd.DataFrame( + index=pd.MultiIndex.from_arrays([[], []], names=("instrument", "datetime")), + columns=column_names, + dtype=np.float32, + ) + + return data + + @staticmethod + def inst_calculator(inst, start_time, end_time, freq, column_names, spans=None, g_config=None, inst_processors=[]): + """ + Calculate the expressions for **one** instrument, return a df result. + If the expression has been calculated before, load from cache. + + return value: A data frame with index 'datetime' and other data columns. + + """ + # FIXME: Windows OS or MacOS using spawn: https://docs.python.org/3.8/library/multiprocessing.html?highlight=spawn#contexts-and-start-methods + # NOTE: This place is compatible with windows, windows multi-process is spawn + C.register_from_C(g_config) + + obj = dict() + for field in column_names: + # The client does not have expression provider, the data will be loaded from cache using static method. + obj[field] = ExpressionD.expression(inst, field, start_time, end_time, freq) + + data = pd.DataFrame(obj) + if not data.empty and not np.issubdtype(data.index.dtype, np.dtype("M")): + # If the underlaying provides the data not in datetime format, we'll convert it into datetime format + _calendar = Cal.calendar(freq=freq) + data.index = _calendar[data.index.values.astype(int)] + data.index.names = ["datetime"] + + if not data.empty and spans is not None: + mask = np.zeros(len(data), dtype=bool) + for begin, end in spans: + mask |= (data.index >= begin) & (data.index <= end) + data = data[mask] + + for _processor in inst_processors: + if _processor: + _processor_obj = init_instance_by_config(_processor, accept_types=InstProcessor) + data = _processor_obj(data, instrument=inst) + return data + + +class LocalCalendarProvider(CalendarProvider, ProviderBackendMixin): + """Local calendar data provider class + + Provide calendar data from local data source. + """ + + def __init__(self, remote=False, backend={}): + super().__init__() + self.remote = remote + self.backend = backend + + def load_calendar(self, freq, future): + """Load original calendar timestamp from file. + + Parameters + ---------- + freq : str + frequency of read calendar file. + future: bool + Returns + ---------- + list + list of timestamps + """ + try: + backend_obj = self.backend_obj(freq=freq, future=future).data + except ValueError: + if future: + get_module_logger("data").warning( + f"load calendar error: freq={freq}, future={future}; return current calendar!" + ) + get_module_logger("data").warning( + "You can get future calendar by referring to the following document: https://github.com/microsoft/qlib/blob/main/scripts/data_collector/contrib/README.md" + ) + backend_obj = self.backend_obj(freq=freq, future=False).data + else: + raise + + return [pd.Timestamp(x) for x in backend_obj] + + +class LocalInstrumentProvider(InstrumentProvider, ProviderBackendMixin): + """Local instrument data provider class + + Provide instrument data from local data source. + """ + + def __init__(self, backend={}) -> None: + super().__init__() + self.backend = backend + + def _load_instruments(self, market, freq): + return self.backend_obj(market=market, freq=freq).data + + def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False): + market = instruments["market"] + if market in H["i"]: + _instruments = H["i"][market] + else: + _instruments = self._load_instruments(market, freq=freq) + H["i"][market] = _instruments + # strip + # use calendar boundary + cal = Cal.calendar(freq=freq) + start_time = pd.Timestamp(start_time or cal[0]) + end_time = pd.Timestamp(end_time or cal[-1]) + _instruments_filtered = { + inst: list( + filter( + lambda x: x[0] <= x[1], + [(max(start_time, pd.Timestamp(x[0])), min(end_time, pd.Timestamp(x[1]))) for x in spans], + ) + ) + for inst, spans in _instruments.items() + } + _instruments_filtered = {key: value for key, value in _instruments_filtered.items() if value} + # filter + filter_pipe = instruments["filter_pipe"] + for filter_config in filter_pipe: + from . import filter as F # pylint: disable=C0415 + + filter_t = getattr(F, filter_config["filter_type"]).from_config(filter_config) + _instruments_filtered = filter_t(_instruments_filtered, start_time, end_time, freq) + # as list + if as_list: + return list(_instruments_filtered) + return _instruments_filtered + + +class LocalFeatureProvider(FeatureProvider, ProviderBackendMixin): + """Local feature data provider class + + Provide feature data from local data source. + """ + + def __init__(self, remote=False, backend={}): + super().__init__() + self.remote = remote + self.backend = backend + + def feature(self, instrument, field, start_index, end_index, freq): + # validate + field = str(field)[1:] + instrument = code_to_fname(instrument) + return self.backend_obj(instrument=instrument, field=field, freq=freq)[start_index : end_index + 1] + + +class LocalPITProvider(PITProvider): + # TODO: Add PIT backend file storage + # NOTE: This class is not multi-threading-safe!!!! + + def period_feature(self, instrument, field, start_index, end_index, cur_time, period=None): + if not isinstance(cur_time, pd.Timestamp): + raise ValueError( + 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)')" + ) + + assert end_index <= 0 # PIT don't support querying future data + + DATA_RECORDS = [ + ("date", C.pit_record_type["date"]), + ("period", C.pit_record_type["period"]), + ("value", C.pit_record_type["value"]), + ("_next", C.pit_record_type["index"]), + ] + VALUE_DTYPE = C.pit_record_type["value"] + + field = str(field).lower()[2:] + instrument = code_to_fname(instrument) + + # {For acceleration + # start_index, end_index, cur_index = kwargs["info"] + # if cur_index == start_index: + # if not hasattr(self, "all_fields"): + # self.all_fields = [] + # self.all_fields.append(field) + # if not hasattr(self, "period_index"): + # self.period_index = {} + # if field not in self.period_index: + # self.period_index[field] = {} + # For acceleration} + + if not field.endswith("_q") and not field.endswith("_a"): + raise ValueError("period field must ends with '_q' or '_a'") + quarterly = field.endswith("_q") + index_path = C.dpm.get_data_uri() / "financial" / instrument.lower() / f"{field}.index" + data_path = C.dpm.get_data_uri() / "financial" / instrument.lower() / f"{field}.data" + if not (index_path.exists() and data_path.exists()): + raise FileNotFoundError("No file is found.") + # NOTE: The most significant performance loss is here. + # Does the acceleration that makes the program complicated really matters? + # - It makes parameters of the interface complicate + # - It does not performance in the optimal way (places all the pieces together, we may achieve higher performance) + # - If we design it carefully, we can go through for only once to get the historical evolution of the data. + # So I decide to deprecated previous implementation and keep the logic of the program simple + # Instead, I'll add a cache for the index file. + data = np.fromfile(data_path, dtype=DATA_RECORDS) + + # find all revision periods before `cur_time` + cur_time_int = int(cur_time.year) * 10000 + int(cur_time.month) * 100 + int(cur_time.day) + loc = np.searchsorted(data["date"], cur_time_int, side="right") + if loc <= 0: + return pd.Series(dtype=C.pit_record_type["value"]) + last_period = data["period"][:loc].max() # return the latest quarter + first_period = data["period"][:loc].min() + period_list = get_period_list(first_period, last_period, quarterly) + if period is not None: + # NOTE: `period` has higher priority than `start_index` & `end_index` + if period not in period_list: + return pd.Series(dtype=C.pit_record_type["value"]) + else: + period_list = [period] + else: + period_list = period_list[max(0, len(period_list) + start_index - 1) : len(period_list) + end_index] + value = np.full((len(period_list),), np.nan, dtype=VALUE_DTYPE) + for i, p in enumerate(period_list): + # last_period_index = self.period_index[field].get(period) # For acceleration + value[i], now_period_index = read_period_data( + index_path, data_path, p, cur_time_int, quarterly # , last_period_index # For acceleration + ) + # self.period_index[field].update({period: now_period_index}) # For acceleration + # NOTE: the index is period_list; So it may result in unexpected values(e.g. nan) + # when calculation between different features and only part of its financial indicator is published + series = pd.Series(value, index=period_list, dtype=VALUE_DTYPE) + + # {For acceleration + # if cur_index == end_index: + # self.all_fields.remove(field) + # if not len(self.all_fields): + # del self.all_fields + # del self.period_index + # For acceleration} + + return series + + +class LocalExpressionProvider(ExpressionProvider): + """Local expression data provider class + + Provide expression data from local data source. + """ + + def __init__(self, time2idx=True): + super().__init__() + self.time2idx = time2idx + + def expression(self, instrument, field, start_time=None, end_time=None, freq="day"): + expression = self.get_expression_instance(field) + start_time = time_to_slc_point(start_time) + end_time = time_to_slc_point(end_time) + + # Two kinds of queries are supported + # - Index-based expression: this may save a lot of memory because the datetime index is not saved on the disk + # - Data with datetime index expression: this will make it more convenient to integrating with some existing databases + if self.time2idx: + _, _, start_index, end_index = Cal.locate_index(start_time, end_time, freq=freq, future=False) + lft_etd, rght_etd = expression.get_extended_window_size() + query_start, query_end = max(0, start_index - lft_etd), end_index + rght_etd + else: + start_index, end_index = query_start, query_end = start_time, end_time + + try: + series = expression.load(instrument, query_start, query_end, freq) + except Exception as e: + get_module_logger("data").debug( + f"Loading expression error: " + f"instrument={instrument}, field=({field}), start_time={start_time}, end_time={end_time}, freq={freq}. " + f"error info: {str(e)}" + ) + raise + # Ensure that each column type is consistent + # FIXME: + # 1) The stock data is currently float. If there is other types of data, this part needs to be re-implemented. + # 2) The precision should be configurable + try: + series = series.astype(np.float32) + except ValueError: + pass + except TypeError: + pass + if not series.empty: + series = series.loc[start_index:end_index] + return series + + +class LocalDatasetProvider(DatasetProvider): + """Local dataset data provider class + + Provide dataset data from local data source. + """ + + def __init__(self, align_time: bool = True): + """ + Parameters + ---------- + align_time : bool + Will we align the time to calendar + the frequency is flexible in some dataset and can't be aligned. + For the data with fixed frequency with a shared calendar, the align data to the calendar will provides following benefits + + - Align queries to the same parameters, so the cache can be shared. + """ + super().__init__() + self.align_time = align_time + + def dataset( + self, + instruments, + fields, + start_time=None, + end_time=None, + freq="day", + inst_processors=[], + ): + instruments_d = self.get_instruments_d(instruments, freq) + column_names = self.get_column_names(fields) + if self.align_time: + # NOTE: if the frequency is a fixed value. + # align the data to fixed calendar point + cal = Cal.calendar(start_time, end_time, freq) + if len(cal) == 0: + return pd.DataFrame( + index=pd.MultiIndex.from_arrays([[], []], names=("instrument", "datetime")), columns=column_names + ) + start_time = cal[0] + end_time = cal[-1] + data = self.dataset_processor( + instruments_d, column_names, start_time, end_time, freq, inst_processors=inst_processors + ) + + return data + + @staticmethod + def multi_cache_walker(instruments, fields, start_time=None, end_time=None, freq="day"): + """ + This method is used to prepare the expression cache for the client. + Then the client will load the data from expression cache by itself. + + """ + instruments_d = DatasetProvider.get_instruments_d(instruments, freq) + column_names = DatasetProvider.get_column_names(fields) + cal = Cal.calendar(start_time, end_time, freq) + if len(cal) == 0: + return + start_time = cal[0] + end_time = cal[-1] + workers = max(min(C.kernels, len(instruments_d)), 1) + + ParallelExt(n_jobs=workers, backend=C.joblib_backend, maxtasksperchild=C.maxtasksperchild)( + delayed(LocalDatasetProvider.cache_walker)(inst, start_time, end_time, freq, column_names) + for inst in instruments_d + ) + + @staticmethod + def cache_walker(inst, start_time, end_time, freq, column_names): + """ + If the expressions of one instrument haven't been calculated before, + calculate it and write it into expression cache. + + """ + for field in column_names: + ExpressionD.expression(inst, field, start_time, end_time, freq) + + +class ClientCalendarProvider(CalendarProvider): + """Client calendar data provider class + + Provide calendar data by requesting data from server as a client. + """ + + def __init__(self): + self.conn = None + self.queue = queue.Queue() + + def set_conn(self, conn): + self.conn = conn + + def calendar(self, start_time=None, end_time=None, freq="day", future=False): + self.conn.send_request( + request_type="calendar", + request_content={"start_time": str(start_time), "end_time": str(end_time), "freq": freq, "future": future}, + msg_queue=self.queue, + msg_proc_func=lambda response_content: [pd.Timestamp(c) for c in response_content], + ) + result = self.queue.get(timeout=C["timeout"]) + return result + + +class ClientInstrumentProvider(InstrumentProvider): + """Client instrument data provider class + + Provide instrument data by requesting data from server as a client. + """ + + def __init__(self): + self.conn = None + self.queue = queue.Queue() + + def set_conn(self, conn): + self.conn = conn + + def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False): + def inst_msg_proc_func(response_content): + if isinstance(response_content, dict): + instrument = { + i: [(pd.Timestamp(s), pd.Timestamp(e)) for s, e in t] for i, t in response_content.items() + } + else: + instrument = response_content + return instrument + + self.conn.send_request( + request_type="instrument", + request_content={ + "instruments": instruments, + "start_time": str(start_time), + "end_time": str(end_time), + "freq": freq, + "as_list": as_list, + }, + msg_queue=self.queue, + msg_proc_func=inst_msg_proc_func, + ) + result = self.queue.get(timeout=C["timeout"]) + if isinstance(result, Exception): + raise result + get_module_logger("data").debug("get result") + return result + + +class ClientDatasetProvider(DatasetProvider): + """Client dataset data provider class + + Provide dataset data by requesting data from server as a client. + """ + + def __init__(self): + self.conn = None + + def set_conn(self, conn): + self.conn = conn + self.queue = queue.Queue() + + def dataset( + self, + instruments, + fields, + start_time=None, + end_time=None, + freq="day", + disk_cache=0, + return_uri=False, + inst_processors=[], + ): + if Inst.get_inst_type(instruments) == Inst.DICT: + get_module_logger("data").warning( + "Getting features from a dict of instruments is not recommended because the features will not be " + "cached! " + "The dict of instruments will be cleaned every day." + ) + + if disk_cache == 0: + """ + Call the server to generate the expression cache. + Then load the data from the expression cache directly. + - default using multi-kernel method. + + """ + self.conn.send_request( + request_type="feature", + request_content={ + "instruments": instruments, + "fields": fields, + "start_time": start_time, + "end_time": end_time, + "freq": freq, + "disk_cache": 0, + }, + msg_queue=self.queue, + ) + feature_uri = self.queue.get(timeout=C["timeout"]) + if isinstance(feature_uri, Exception): + raise feature_uri + else: + instruments_d = self.get_instruments_d(instruments, freq) + column_names = self.get_column_names(fields) + cal = Cal.calendar(start_time, end_time, freq) + if len(cal) == 0: + return pd.DataFrame( + index=pd.MultiIndex.from_arrays([[], []], names=("instrument", "datetime")), + columns=column_names, + ) + start_time = cal[0] + end_time = cal[-1] + + data = self.dataset_processor(instruments_d, column_names, start_time, end_time, freq, inst_processors) + if return_uri: + return data, feature_uri + else: + return data + else: + """ + Call the server to generate the data-set cache, get the uri of the cache file. + Then load the data from the file on NFS directly. + - using single-process implementation. + + """ + # TODO: support inst_processors, need to change the code of qlib-server at the same time + # FIXME: The cache after resample, when read again and intercepted with end_time, results in incomplete data date + if inst_processors: + raise ValueError( + f"{self.__class__.__name__} does not support inst_processor. " + f"Please use `D.features(disk_cache=0)` or `qlib.init(dataset_cache=None)`" + ) + self.conn.send_request( + request_type="feature", + request_content={ + "instruments": instruments, + "fields": fields, + "start_time": start_time, + "end_time": end_time, + "freq": freq, + "disk_cache": 1, + }, + msg_queue=self.queue, + ) + # - Done in callback + feature_uri = self.queue.get(timeout=C["timeout"]) + if isinstance(feature_uri, Exception): + raise feature_uri + get_module_logger("data").debug("get result") + try: + # pre-mound nfs, used for demo + mnt_feature_uri = C.dpm.get_data_uri(freq).joinpath(C.dataset_cache_dir_name, feature_uri) + df = DiskDatasetCache.read_data_from_cache(mnt_feature_uri, start_time, end_time, fields) + get_module_logger("data").debug("finish slicing data") + if return_uri: + return df, feature_uri + return df + except AttributeError as attribute_e: + raise IOError("Unable to fetch instruments from remote server!") from attribute_e + + +class BaseProvider: + """Local provider class + It is a set of interface that allow users to access data. + Because PITD is not exposed publicly to users, so it is not included in the interface. + + To keep compatible with old qlib provider. + """ + + def calendar(self, start_time=None, end_time=None, freq="day", future=False): + return Cal.calendar(start_time, end_time, freq, future=future) + + def instruments(self, market="all", filter_pipe=None, start_time=None, end_time=None): + if start_time is not None or end_time is not None: + get_module_logger("Provider").warning( + "The instruments corresponds to a stock pool. " + "Parameters `start_time` and `end_time` does not take effect now." + ) + return InstrumentProvider.instruments(market, filter_pipe) + + def list_instruments(self, instruments, start_time=None, end_time=None, freq="day", as_list=False): + return Inst.list_instruments(instruments, start_time, end_time, freq, as_list) + + def features( + self, + instruments, + fields, + start_time=None, + end_time=None, + freq="day", + disk_cache=None, + inst_processors=[], + ): + """ + Parameters + ---------- + disk_cache : int + whether to skip(0)/use(1)/replace(2) disk_cache + + + This function will try to use cache method which has a keyword `disk_cache`, + and will use provider method if a type error is raised because the DatasetD instance + is a provider class. + """ + disk_cache = C.default_disk_cache if disk_cache is None else disk_cache + fields = list(fields) # In case of tuple. + try: + return DatasetD.dataset( + instruments, fields, start_time, end_time, freq, disk_cache, inst_processors=inst_processors + ) + except TypeError: + return DatasetD.dataset(instruments, fields, start_time, end_time, freq, inst_processors=inst_processors) + + +class LocalProvider(BaseProvider): + def _uri(self, type, **kwargs): + """_uri + The server hope to get the uri of the request. The uri will be decided + by the dataprovider. For ex, different cache layer has different uri. + + :param type: The type of resource for the uri + :param **kwargs: + """ + if type == "calendar": + return Cal._uri(**kwargs) + elif type == "instrument": + return Inst._uri(**kwargs) + elif type == "feature": + return DatasetD._uri(**kwargs) + + def features_uri(self, instruments, fields, start_time, end_time, freq, disk_cache=1): + """features_uri + + Return the uri of the generated cache of features/dataset + + :param disk_cache: + :param instruments: + :param fields: + :param start_time: + :param end_time: + :param freq: + """ + return DatasetD._dataset_uri(instruments, fields, start_time, end_time, freq, disk_cache) + + +class ClientProvider(BaseProvider): + """Client Provider + + Requesting data from server as a client. Can propose requests: + + - Calendar : Directly respond a list of calendars + - Instruments (without filter): Directly respond a list/dict of instruments + - Instruments (with filters): Respond a list/dict of instruments + - Features : Respond a cache uri + + The general workflow is described as follows: + 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. + `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. + """ + + def __init__(self): + def is_instance_of_provider(instance: object, cls: type): + if isinstance(instance, Wrapper): + p = getattr(instance, "_provider", None) + + return False if p is None else isinstance(p, cls) + + return isinstance(instance, cls) + + from .client import Client # pylint: disable=C0415 + + self.client = Client(C.flask_server, C.flask_port) + self.logger = get_module_logger(self.__class__.__name__) + if is_instance_of_provider(Cal, ClientCalendarProvider): + Cal.set_conn(self.client) + if is_instance_of_provider(Inst, ClientInstrumentProvider): + Inst.set_conn(self.client) + if hasattr(DatasetD, "provider"): + DatasetD.provider.set_conn(self.client) + else: + DatasetD.set_conn(self.client) + + +import sys + +if sys.version_info >= (3, 9): + from typing import Annotated + + CalendarProviderWrapper = Annotated[CalendarProvider, Wrapper] + InstrumentProviderWrapper = Annotated[InstrumentProvider, Wrapper] + FeatureProviderWrapper = Annotated[FeatureProvider, Wrapper] + PITProviderWrapper = Annotated[PITProvider, Wrapper] + ExpressionProviderWrapper = Annotated[ExpressionProvider, Wrapper] + DatasetProviderWrapper = Annotated[DatasetProvider, Wrapper] + BaseProviderWrapper = Annotated[BaseProvider, Wrapper] +else: + CalendarProviderWrapper = CalendarProvider + InstrumentProviderWrapper = InstrumentProvider + FeatureProviderWrapper = FeatureProvider + PITProviderWrapper = PITProvider + ExpressionProviderWrapper = ExpressionProvider + DatasetProviderWrapper = DatasetProvider + BaseProviderWrapper = BaseProvider + +Cal: CalendarProviderWrapper = Wrapper() +Inst: InstrumentProviderWrapper = Wrapper() +FeatureD: FeatureProviderWrapper = Wrapper() +PITD: PITProviderWrapper = Wrapper() +ExpressionD: ExpressionProviderWrapper = Wrapper() +DatasetD: DatasetProviderWrapper = Wrapper() +D: BaseProviderWrapper = Wrapper() + + +def register_all_wrappers(C): + """register_all_wrappers""" + logger = get_module_logger("data") + module = get_module_by_module_path("qlib.data") + + _calendar_provider = init_instance_by_config(C.calendar_provider, module) + if getattr(C, "calendar_cache", None) is not None: + _calendar_provider = init_instance_by_config(C.calendar_cache, module, provide=_calendar_provider) + register_wrapper(Cal, _calendar_provider, "qlib.data") + logger.debug(f"registering Cal {C.calendar_provider}-{C.calendar_cache}") + + _instrument_provider = init_instance_by_config(C.instrument_provider, module) + register_wrapper(Inst, _instrument_provider, "qlib.data") + logger.debug(f"registering Inst {C.instrument_provider}") + + if getattr(C, "feature_provider", None) is not None: + feature_provider = init_instance_by_config(C.feature_provider, module) + register_wrapper(FeatureD, feature_provider, "qlib.data") + logger.debug(f"registering FeatureD {C.feature_provider}") + + if getattr(C, "pit_provider", None) is not None: + pit_provider = init_instance_by_config(C.pit_provider, module) + register_wrapper(PITD, pit_provider, "qlib.data") + logger.debug(f"registering PITD {C.pit_provider}") + + if getattr(C, "expression_provider", None) is not None: + # This provider is unnecessary in client provider + _eprovider = init_instance_by_config(C.expression_provider, module) + if getattr(C, "expression_cache", None) is not None: + _eprovider = init_instance_by_config(C.expression_cache, module, provider=_eprovider) + register_wrapper(ExpressionD, _eprovider, "qlib.data") + logger.debug(f"registering ExpressionD {C.expression_provider}-{C.expression_cache}") + + _dprovider = init_instance_by_config(C.dataset_provider, module) + if getattr(C, "dataset_cache", None) is not None: + _dprovider = init_instance_by_config(C.dataset_cache, module, provider=_dprovider) + register_wrapper(DatasetD, _dprovider, "qlib.data") + logger.debug(f"registering DatasetD {C.dataset_provider}-{C.dataset_cache}") + + register_wrapper(D, C.provider, "qlib.data") + logger.debug(f"registering D {C.provider}") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a6cace3730fcf531ea98784e7427655bf442acdf --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/__init__.py @@ -0,0 +1,722 @@ +from ...utils.serial import Serializable +from typing import Callable, Union, List, Tuple, Dict, Text, Optional +from ...utils import init_instance_by_config, np_ffill, time_to_slc_point +from ...log import get_module_logger +from .handler import DataHandler, DataHandlerLP +from copy import copy, deepcopy +from inspect import getfullargspec +import pandas as pd +import numpy as np +import bisect +from ...utils import lazy_sort_index +from .utils import get_level_index + + +class Dataset(Serializable): + """ + Preparing data for model training and inferencing. + """ + + def __init__(self, **kwargs): + """ + init is designed to finish following steps: + + - init the sub instance and the state of the dataset(info to prepare the data) + - The name of essential state for preparing data should not start with '_' so that it could be serialized on disk when serializing. + + - setup data + - The data related attributes' names should start with '_' so that it will not be saved on disk when serializing. + + The data could specify the info to calculate the essential data for preparation + """ + self.setup_data(**kwargs) + super().__init__() + + def config(self, **kwargs): + """ + config is designed to configure and parameters that cannot be learned from the data + """ + super().config(**kwargs) + + def setup_data(self, **kwargs): + """ + Setup the data. + + We split the setup_data function for following situation: + + - User have a Dataset object with learned status on disk. + + - User load the Dataset object from the disk. + + - User call `setup_data` to load new data. + + - User prepare data for model based on previous status. + """ + + def prepare(self, **kwargs) -> object: + """ + The type of dataset depends on the model. (It could be pd.DataFrame, pytorch.DataLoader, etc.) + The parameters should specify the scope for the prepared data + The method should: + - process the data + + - return the processed data + + Returns + ------- + object: + return the object + """ + + +class DatasetH(Dataset): + """ + Dataset with Data(H)andler + + User should try to put the data preprocessing functions into handler. + Only following data processing functions should be placed in Dataset: + + - The processing is related to specific model. + + - The processing is related to data split. + """ + + def __init__( + self, + handler: Union[Dict, DataHandler], + segments: Dict[Text, Tuple], + fetch_kwargs: Dict = {}, + **kwargs, + ): + """ + Setup the underlying data. + + Parameters + ---------- + handler : Union[dict, DataHandler] + handler could be: + + - instance of `DataHandler` + + - config of `DataHandler`. Please refer to `DataHandler` + + segments : dict + Describe the options to segment the data. + Here are some examples: + + .. code-block:: + + 1) 'segments': { + 'train': ("2008-01-01", "2014-12-31"), + 'valid': ("2017-01-01", "2020-08-01",), + 'test': ("2015-01-01", "2016-12-31",), + } + 2) 'segments': { + 'insample': ("2008-01-01", "2014-12-31"), + 'outsample': ("2017-01-01", "2020-08-01",), + } + """ + self.handler: DataHandler = init_instance_by_config(handler, accept_types=DataHandler) + self.segments = segments.copy() + self.fetch_kwargs = copy(fetch_kwargs) + super().__init__(**kwargs) + + def config(self, handler_kwargs: dict = None, **kwargs): + """ + Initialize the DatasetH + + Parameters + ---------- + handler_kwargs : dict + Config of DataHandler, which could include the following arguments: + + - arguments of DataHandler.conf_data, such as 'instruments', 'start_time' and 'end_time'. + + kwargs : dict + Config of DatasetH, such as + + - segments : dict + Config of segments which is same as 'segments' in self.__init__ + + """ + if handler_kwargs is not None: + self.handler.config(**handler_kwargs) + if "segments" in kwargs: + self.segments = deepcopy(kwargs.pop("segments")) + super().config(**kwargs) + + def setup_data(self, handler_kwargs: dict = None, **kwargs): + """ + Setup the Data + + Parameters + ---------- + handler_kwargs : dict + init arguments of DataHandler, which could include the following arguments: + + - init_type : Init Type of Handler + + - enable_cache : whether to enable cache + + """ + super().setup_data(**kwargs) + if handler_kwargs is not None: + self.handler.setup_data(**handler_kwargs) + + def __repr__(self): + return "{name}(handler={handler}, segments={segments})".format( + name=self.__class__.__name__, handler=self.handler, segments=self.segments + ) + + def _prepare_seg(self, slc, **kwargs): + """ + Give a query, retrieve the according data + + Parameters + ---------- + slc : please refer to the docs of `prepare` + NOTE: it may not be an instance of slice. It may be a segment of `segments` from `def prepare` + """ + if hasattr(self, "fetch_kwargs"): + return self.handler.fetch(slc, **kwargs, **self.fetch_kwargs) + else: + return self.handler.fetch(slc, **kwargs) + + def prepare( + self, + segments: Union[List[Text], Tuple[Text], Text, slice, pd.Index], + col_set=DataHandler.CS_ALL, + data_key=DataHandlerLP.DK_I, + **kwargs, + ) -> Union[List[pd.DataFrame], pd.DataFrame]: + """ + Prepare the data for learning and inference. + + Parameters + ---------- + segments : Union[List[Text], Tuple[Text], Text, slice] + Describe the scope of the data to be prepared + Here are some examples: + + - 'train' + + - ['train', 'valid'] + + col_set : str + The col_set will be passed to self.handler when fetching data. + TODO: make it automatic: + + - select DK_I for test data + - select DK_L for training data. + data_key : str + The data to fetch: DK_* + Default is DK_I, which indicate fetching data for **inference**. + + kwargs : + The parameters that kwargs may contain: + flt_col : str + It only exists in TSDatasetH, can be used to add a column of data(True or False) to filter data. + This parameter is only supported when it is an instance of TSDatasetH. + + Returns + ------- + Union[List[pd.DataFrame], pd.DataFrame]: + + Raises + ------ + NotImplementedError: + """ + seg_kwargs = {"col_set": col_set, "data_key": data_key} + seg_kwargs.update(kwargs) + + # Conflictions may happen here + # - The fetched data and the segment key may both be string + # To resolve the confliction + # - The segment name will have higher priorities + + # 1) Use it as segment name first + # 1.1) directly fetch split like "train" "valid" "test" + if isinstance(segments, str) and segments in self.segments: + return self._prepare_seg(self.segments[segments], **seg_kwargs) + + # 1.2) fetch multiple splits like ["train", "valid"] ["train", "valid", "test"] + if isinstance(segments, (list, tuple)) and all(seg in self.segments for seg in segments): + return [self._prepare_seg(self.segments[seg], **seg_kwargs) for seg in segments] + + # 2) Use pass it directly to prepare a single seg + return self._prepare_seg(segments, **seg_kwargs) + + # helper functions + @staticmethod + def get_min_time(segments): + return DatasetH._get_extrema(segments, 0, (lambda a, b: a > b)) + + @staticmethod + def get_max_time(segments): + return DatasetH._get_extrema(segments, 1, (lambda a, b: a < b)) + + @staticmethod + def _get_extrema(segments, idx: int, cmp: Callable, key_func=pd.Timestamp): + """it will act like sort and return the max value or None""" + candidate = None + for _, seg in segments.items(): + point = seg[idx] + if point is None: + # None indicates unbounded, return directly + return None + elif candidate is None or cmp(key_func(candidate), key_func(point)): + candidate = point + return candidate + + +class TSDataSampler: + """ + (T)ime-(S)eries DataSampler + This is the result of TSDatasetH + + It works like `torch.data.utils.Dataset`, it provides a very convenient interface for constructing time-series + dataset based on tabular data. + - On time step dimension, the smaller index indicates the historical data and the larger index indicates the future + data. + + If user have further requirements for processing data, user could process them based on `TSDataSampler` or create + more powerful subclasses. + + Known Issues: + - For performance issues, this Sampler will convert dataframe into arrays for better performance. This could result + in a different data type + + + Indices design: + TSDataSampler has a index mechanism to help users query time-series data efficiently. + + The definition of related variables: + data_arr: np.ndarray + The original data. it will contains all the original data. + The querying are often for time-series of a specific stock. + By leveraging this data charactoristics to speed up querying, the multi-index of data_arr is rearranged in (instrument, datetime) order + + data_index: pd.MultiIndex with index order + it has the same shape with `idx_map`. Each elements of them are expected to be aligned. + + idx_map: np.ndarray + It is the indexable data. It originates from data_arr, and then filtered by 1) `start` and `end` 2) `flt_data` + The extra data in data_arr is useful in following cases + 1) creating meaningful time series data before `start` instead of padding them with zeros + 2) some data are excluded by `flt_data` (e.g. no sample pair for that index). but they are still used in time-series in X + + Finnally, it will look like. + + array([[ 0, 0], + [ 1, 0], + [ 2, 0], + ..., + [241, 348], + [242, 348], + [243, 348]], dtype=int32) + + 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 + idx_df: pd.DataFrame + It aims to map the key to the original position in data_arr + + For example, it may look like (NOTE: the index for a instrument time-series is continoues in memory) + + instrument SH600000 SH600008 SH600009 SH600010 SH600011 SH600015 ... + datetime + 2017-01-03 0 242 473 717 NaN 974 ... + 2017-01-04 1 243 474 718 NaN 975 ... + 2017-01-05 2 244 475 719 NaN 976 ... + 2017-01-06 3 245 476 720 NaN 977 ... + + With these two indices(idx_map, idx_df) and original data(data_arr), we can make the following queries fast (implemented in __getitem__) + (1) Get the i-th indexable sample(time-series): (indexable sample index) -> [idx_map] -> (row col) -> [idx_df] -> (index in data_arr) + (2) Get the specific sample by : (, i.e. ) -> [idx_df] -> (index in data_arr) + (3) Get the index of a time-series data: (get the , refer to (1), (2)) -> [idx_df] -> (all indices in data_arr for time-series) + """ + + # Please refer to the docstring of TSDataSampler for the definition of following attributes + data_arr: np.ndarray + data_index: pd.MultiIndex + idx_map: np.ndarray + idx_df: pd.DataFrame + + def __init__( + self, + data: pd.DataFrame, + start, + end, + step_len: int, + fillna_type: str = "none", + dtype=None, + flt_data=None, + ): + """ + Build a dataset which looks like torch.data.utils.Dataset. + + Parameters + ---------- + data : pd.DataFrame + The raw tabular data whose index order is <"datetime", "instrument"> + start : + The indexable start time + end : + The indexable end time + step_len : int + The length of the time-series step + fillna_type : int + How will qlib handle the sample if there is on sample in a specific date. + none: + fill with np.nan + ffill: + ffill with previous sample + ffill+bfill: + ffill with previous samples first and fill with later samples second + flt_data : pd.Series + a column of data(True or False) to filter data. Its index order is <"datetime", "instrument"> + This feature is essential because: + - 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. + None: + kepp all data + + """ + self.start = start + self.end = end + self.step_len = step_len + self.fillna_type = fillna_type + assert get_level_index(data, "datetime") == 0 + self.data = data.swaplevel().sort_index().copy() + data.drop( + data.columns, axis=1, inplace=True + ) # 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) + + kwargs = {"object": self.data} + if dtype is not None: + kwargs["dtype"] = dtype + + self.data_arr = np.array(**kwargs) # Get index from numpy.array will much faster than DataFrame.values! + # NOTE: + # - append last line with full NaN for better performance in `__getitem__` + # - Keep the same dtype will result in a better performance + self.data_arr = np.append( + self.data_arr, + np.full((1, self.data_arr.shape[1]), np.nan, dtype=self.data_arr.dtype), + axis=0, + ) + self.nan_idx = len(self.data_arr) - 1 # The last line is all NaN; setting it to -1 can cause bug #1716 + + # the data type will be changed + # The index of usable data is between start_idx and end_idx + self.idx_df, self.idx_map = self.build_index(self.data) + self.data_index = deepcopy(self.data.index) + + if flt_data is not None: + if isinstance(flt_data, pd.DataFrame): + assert len(flt_data.columns) == 1 + flt_data = flt_data.iloc[:, 0] + # NOTE: bool(np.nan) is True !!!!!!!! + # make sure reindex comes first. Otherwise extra NaN may appear. + flt_data = flt_data.swaplevel() + flt_data = flt_data.reindex(self.data_index).fillna(False).astype(bool) + self.flt_data = flt_data.values + self.idx_map = self.flt_idx_map(self.flt_data, self.idx_map) + self.data_index = self.data_index[np.where(self.flt_data)[0]] + self.idx_map = self.idx_map2arr(self.idx_map) + self.idx_map, self.data_index = self.slice_idx_map_and_data_index( + self.idx_map, self.idx_df, self.data_index, start, end + ) + + self.idx_arr = np.array(self.idx_df.values, dtype=np.float64) # for better performance + del self.data # save memory + + @staticmethod + def slice_idx_map_and_data_index( + idx_map, + idx_df, + data_index, + start, + end, + ): + assert ( + len(idx_map) == data_index.shape[0] + ) # make sure idx_map and data_index is same so index of idx_map can be used on data_index + + start_row_idx, end_row_idx = idx_df.index.slice_locs(start=time_to_slc_point(start), end=time_to_slc_point(end)) + + time_flter_idx = (idx_map[:, 0] < end_row_idx) & (idx_map[:, 0] >= start_row_idx) + return idx_map[time_flter_idx], data_index[time_flter_idx] + + @staticmethod + def idx_map2arr(idx_map): + # pytorch data sampler will have better memory control without large dict or list + # - https://github.com/pytorch/pytorch/issues/13243 + # - https://github.com/airctic/icevision/issues/613 + # So we convert the dict into int array. + # The arr_map is expected to behave the same as idx_map + + dtype = np.int32 + # set a index out of bound to indicate the none existing + no_existing_idx = (np.iinfo(dtype).max, np.iinfo(dtype).max) + + max_idx = max(idx_map.keys()) + arr_map = [] + for i in range(max_idx + 1): + arr_map.append(idx_map.get(i, no_existing_idx)) + arr_map = np.array(arr_map, dtype=dtype) + return arr_map + + @staticmethod + def flt_idx_map(flt_data, idx_map): + idx = 0 + new_idx_map = {} + for i, exist in enumerate(flt_data): + if exist: + new_idx_map[idx] = idx_map[i] + idx += 1 + return new_idx_map + + def get_index(self): + """ + Get the pandas index of the data, it will be useful in following scenarios + - Special sampler will be used (e.g. user want to sample day by day) + """ + return self.data_index.swaplevel() # to align the order of multiple index of original data received by __init__ + + def config(self, **kwargs): + # Config the attributes + for k, v in kwargs.items(): + setattr(self, k, v) + + @staticmethod + def build_index(data: pd.DataFrame) -> Tuple[pd.DataFrame, dict]: + """ + The relation of the data + + Parameters + ---------- + data : pd.DataFrame + A DataFrame with index in order + + RSQR5 RESI5 WVMA5 LABEL0 + instrument datetime + SH600000 2017-01-03 0.016389 0.461632 -1.154788 -0.048056 + 2017-01-04 0.884545 -0.110597 -1.059332 -0.030139 + 2017-01-05 0.507540 -0.535493 -1.099665 -0.644983 + 2017-01-06 -1.267771 -0.669685 -1.636733 0.295366 + 2017-01-09 0.339346 0.074317 -0.984989 0.765540 + + Returns + ------- + Tuple[pd.DataFrame, dict]: + 1) the first element: reshape the original index into a 2D dataframe + instrument SH600000 SH600008 SH600009 SH600010 SH600011 SH600015 ... + datetime + 2017-01-03 0 242 473 717 NaN 974 ... + 2017-01-04 1 243 474 718 NaN 975 ... + 2017-01-05 2 244 475 719 NaN 976 ... + 2017-01-06 3 245 476 720 NaN 977 ... + 2) the second element: {: } + """ + # object incase of pandas converting int to float + idx_df = pd.Series(range(data.shape[0]), index=data.index, dtype=object) + idx_df = lazy_sort_index(idx_df.unstack()) + # NOTE: the correctness of `__getitem__` depends on columns sorted here + idx_df = lazy_sort_index(idx_df, axis=1).T + + idx_map = {} + for i, (_, row) in enumerate(idx_df.iterrows()): + for j, real_idx in enumerate(row): + if not np.isnan(real_idx): + idx_map[real_idx] = (i, j) + return idx_df, idx_map + + @property + def empty(self): + return len(self) == 0 + + def _get_indices(self, row: int, col: int) -> np.array: + """ + get series indices of self.data_arr from the row, col indices of self.idx_df + + Parameters + ---------- + row : int + the row in self.idx_df + col : int + the col in self.idx_df + + Returns + ------- + np.array: + The indices of data of the data + """ + indices = self.idx_arr[max(row - self.step_len + 1, 0) : row + 1, col] + + if len(indices) < self.step_len: + indices = np.concatenate([np.full((self.step_len - len(indices),), np.nan), indices]) + + if self.fillna_type == "ffill": + indices = np_ffill(indices) + elif self.fillna_type == "ffill+bfill": + indices = np_ffill(np_ffill(indices)[::-1])[::-1] + else: + assert self.fillna_type == "none" + return indices + + def _get_row_col(self, idx) -> Tuple[int]: + """ + get the col index and row index of a given sample index in self.idx_df + + Parameters + ---------- + idx : + the input of `__getitem__` + + Returns + ------- + Tuple[int]: + the row and col index + """ + # The the right row number `i` and col number `j` in idx_df + if isinstance(idx, (int, np.integer)): + real_idx = idx + if 0 <= real_idx < len(self.idx_map): + i, j = self.idx_map[real_idx] # TODO: The performance of this line is not good + else: + raise KeyError(f"{real_idx} is out of [0, {len(self.idx_map)})") + elif isinstance(idx, tuple): + # ["datetime", "instruments"] + date, inst = idx + date = pd.Timestamp(date) + i = bisect.bisect_right(self.idx_df.index, date) - 1 + # NOTE: This relies on the idx_df columns sorted in `__init__` + j = bisect.bisect_left(self.idx_df.columns, inst) + else: + raise NotImplementedError(f"This type of input is not supported") + return i, j + + def __getitem__(self, idx: Union[int, Tuple[object, str], List[int]]): + """ + # We have two method to get the time-series of a sample + tsds is a instance of TSDataSampler + + # 1) sample by int index directly + tsds[len(tsds) - 1] + + # 2) sample by index + tsds['2016-12-31', "SZ300315"] + + # The return value will be similar to the data retrieved by following code + df.loc(axis=0)['2015-01-01':'2016-12-31', "SZ300315"].iloc[-30:] + + Parameters + ---------- + idx : Union[int, Tuple[object, str]] + """ + # Multi-index type + mtit = (list, np.ndarray) + if isinstance(idx, mtit): + indices = [self._get_indices(*self._get_row_col(i)) for i in idx] + indices = np.concatenate(indices) + else: + indices = self._get_indices(*self._get_row_col(idx)) + + # 1) for better performance, use the last nan line for padding the lost date + # 2) In case of precision problems. We use np.float64. # TODO: I'm not sure if whether np.float64 will result in + # precision problems. It will not cause any problems in my tests at least + indices = np.nan_to_num(indices.astype(np.float64), nan=self.nan_idx).astype(int) + + if (np.diff(indices) == 1).all(): # slicing instead of indexing for speeding up. + data = self.data_arr[indices[0] : indices[-1] + 1] + else: + data = self.data_arr[indices] + if isinstance(idx, mtit): + # if we get multiple indexes, addition dimension should be added. + # + data = data.reshape(-1, self.step_len, *data.shape[1:]) + return data + + def __len__(self): + return len(self.idx_map) + + +class TSDatasetH(DatasetH): + """ + (T)ime-(S)eries Dataset (H)andler + + + Convert the tabular data to Time-Series data + + Requirements analysis + + The typical workflow of a user to get time-series data for an sample + - process features + - slice proper data from data handler: dimension of sample + - Build relation of samples by index + - Be able to sample times series of data + - It will be better if the interface is like "torch.utils.data.Dataset" + - User could build customized batch based on the data + - The dimension of a batch of data + """ + + DEFAULT_STEP_LEN = 30 + + def __init__(self, step_len=DEFAULT_STEP_LEN, flt_col: Optional[str] = None, **kwargs): + self.step_len = step_len + self.flt_col = flt_col + super().__init__(**kwargs) + + def config(self, **kwargs): + if "step_len" in kwargs: + self.step_len = kwargs.pop("step_len") + super().config(**kwargs) + + def setup_data(self, **kwargs): + super().setup_data(**kwargs) + # make sure the calendar is updated to latest when loading data from new config + cal = self.handler.fetch(col_set=self.handler.CS_RAW).index.get_level_values("datetime").unique() + self.cal = sorted(cal) + + @staticmethod + def _extend_slice(slc: slice, cal: list, step_len: int) -> slice: + # Dataset decide how to slice data(Get more data for timeseries). + start, end = slc.start, slc.stop + start_idx = bisect.bisect_left(cal, pd.Timestamp(start)) + pad_start_idx = max(0, start_idx - step_len) + pad_start = cal[pad_start_idx] + return slice(pad_start, end) + + def _prepare_seg(self, slc: slice, **kwargs) -> TSDataSampler: + """ + split the _prepare_raw_seg is to leave a hook for data preprocessing before creating processing data + NOTE: TSDatasetH only support slc segment on datetime !!! + """ + dtype = kwargs.pop("dtype", None) + if not isinstance(slc, slice): + slc = slice(*slc) + if (flt_col := kwargs.pop("flt_col", None)) is None: + flt_col = self.flt_col + + # TSDatasetH will retrieve more data for complete time-series + ext_slice = self._extend_slice(slc, self.cal, self.step_len) + data = super()._prepare_seg(ext_slice, **kwargs) + + flt_kwargs = deepcopy(kwargs) + if flt_col is not None: + flt_kwargs["col_set"] = flt_col + flt_data = super()._prepare_seg(ext_slice, **flt_kwargs) + assert len(flt_data.columns) == 1 + else: + flt_data = None + + tsds = TSDataSampler( + data=data, + start=slc.start, + end=slc.stop, + step_len=self.step_len, + dtype=dtype, + flt_data=flt_data, + ) + return tsds + + +__all__ = ["Optional", "Dataset", "DatasetH"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/handler.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/handler.py new file mode 100644 index 0000000000000000000000000000000000000000..2c45aec687f02dd31132c64a0797c31458dde5cd --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/handler.py @@ -0,0 +1,785 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# coding=utf-8 +from abc import abstractmethod +import warnings +from typing import Callable, Union, Tuple, List, Iterator, Optional + +import pandas as pd + +from qlib.typehint import Literal +from ...log import get_module_logger, TimeInspector +from ...utils import init_instance_by_config +from ...utils.serial import Serializable +from .utils import fetch_df_by_index, fetch_df_by_col +from ...utils import lazy_sort_index +from .loader import DataLoader + +from . import processor as processor_module +from . import loader as data_loader_module + +DATA_KEY_TYPE = Literal["raw", "infer", "learn"] + + +class DataHandlerABC(Serializable): + """ + Interface for data handler. + + This class does not assume the internal data structure of the data handler. + It only defines the interface for external users (uses DataFrame as the internal data structure). + + In the future, the data handler's more detailed implementation should be refactored. Here are some guidelines: + + It covers several components: + + - [data loader] -> internal representation of the data -> data preprocessing -> interface adaptor for the fetch interface + - The workflow to combine them all: + The workflow may be very complicated. DataHandlerLP is one of the practices, but it can't satisfy all the requirements. + So leaving the flexibility to the user to implement the workflow is a more reasonable choice. + """ + + def __init__(self, *args, **kwargs): # pylint: disable=W0246 + """ + We should define how to get ready for the fetching. + """ + super().__init__(*args, **kwargs) + + CS_ALL = "__all" # return all columns with single-level index column + CS_RAW = "__raw" # return raw data with multi-level index column + + # data key + DK_R: DATA_KEY_TYPE = "raw" + DK_I: DATA_KEY_TYPE = "infer" + DK_L: DATA_KEY_TYPE = "learn" + + @abstractmethod + def fetch( + self, + selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None), + level: Union[str, int] = "datetime", + col_set: Union[str, List[str]] = CS_ALL, + data_key: DATA_KEY_TYPE = DK_I, + ) -> pd.DataFrame: + pass + + +class DataHandler(DataHandlerABC): + """ + The motivation of DataHandler: + + - It provides an implementation of BaseDataHandler that we implement with: + - Handling responses with an internal loaded DataFrame + - The DataFrame is loaded by a data loader. + + The steps to using a handler + 1. initialized data handler (call by `init`). + 2. use the data. + + + The data handler try to maintain a handler with 2 level. + `datetime` & `instruments`. + + Any order of the index level can be supported (The order will be implied in the data). + The order <`datetime`, `instruments`> will be used when the dataframe index name is missed. + + Example of the data: + The multi-index of the columns is optional. + + .. code-block:: text + + feature label + $close $volume Ref($close, 1) Mean($close, 3) $high-$low LABEL0 + datetime instrument + 2010-01-04 SH600000 81.807068 17145150.0 83.737389 83.016739 2.741058 0.0032 + SH600004 13.313329 11800983.0 13.313329 13.317701 0.183632 0.0042 + SH600005 37.796539 12231662.0 38.258602 37.919757 0.970325 0.0289 + + + Tips for improving the performance of datahandler + - Fetching data with `col_set=CS_RAW` will return the raw data and may avoid pandas from copying the data when calling `loc` + """ + + _data: pd.DataFrame # underlying data. + + def __init__( + self, + instruments=None, + start_time=None, + end_time=None, + data_loader: Union[dict, str, DataLoader] = None, + init_data=True, + fetch_orig=True, + ): + """ + Parameters + ---------- + instruments : + The stock list to retrieve. + start_time : + start_time of the original data. + end_time : + end_time of the original data. + data_loader : Union[dict, str, DataLoader] + data loader to load the data. + init_data : + initialize the original data in the constructor. + fetch_orig : bool + Return the original data instead of copy if possible. + """ + + # Setup data loader + assert data_loader is not None # to make start_time end_time could have None default value + + # what data source to load data + self.data_loader = init_instance_by_config( + data_loader, + None if (isinstance(data_loader, dict) and "module_path" in data_loader) else data_loader_module, + accept_types=DataLoader, + ) + + # what data to be loaded from data source + # For IDE auto-completion. + self.instruments = instruments + self.start_time = start_time + self.end_time = end_time + + self.fetch_orig = fetch_orig + if init_data: + with TimeInspector.logt("Init data"): + self.setup_data() + super().__init__() + + def config(self, **kwargs): + """ + configuration of data. + # what data to be loaded from data source + + This method will be used when loading pickled handler from dataset. + The data will be initialized with different time range. + + """ + attr_list = {"instruments", "start_time", "end_time"} + for k, v in kwargs.items(): + if k in attr_list: + setattr(self, k, v) + + for attr in attr_list: + if attr in kwargs: + kwargs.pop(attr) + + super().config(**kwargs) + + def setup_data(self, enable_cache: bool = False): + """ + Set Up the data in case of running initialization for multiple time + + It is responsible for maintaining following variable + 1) self._data + + Parameters + ---------- + enable_cache : bool + default value is false: + + - if `enable_cache` == True: + + the processed data will be saved on disk, and handler will load the cached data from the disk directly + when we call `init` next time + """ + # Setup data. + # _data may be with multiple column index level. The outer level indicates the feature set name + with TimeInspector.logt("Loading data"): + # make sure the fetch method is based on an index-sorted pd.DataFrame + self._data = lazy_sort_index(self.data_loader.load(self.instruments, self.start_time, self.end_time)) + # TODO: cache + + def fetch( + self, + selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None), + level: Union[str, int] = "datetime", + col_set: Union[str, List[str]] = DataHandlerABC.CS_ALL, + data_key: DATA_KEY_TYPE = DataHandlerABC.DK_I, + squeeze: bool = False, + proc_func: Optional[Callable] = None, + ) -> pd.DataFrame: + """ + fetch data from underlying data source + + Design motivation: + - providing a unified interface for underlying data. + - Potential to make the interface more friendly. + - User can improve performance when fetching data in this extra layer + + Parameters + ---------- + selector : Union[pd.Timestamp, slice, str] + describe how to select data by index + It can be categories as following + + - fetch single index + - fetch a range of index + + - a slice range + - pd.Index for specific indexes + + Following conflicts may occur + + - Does ["20200101", "20210101"] mean selecting this slice or these two days? + + - slice have higher priorities + + level : Union[str, int] + which index level to select the data + + col_set : Union[str, List[str]] + + - if isinstance(col_set, str): + + select a set of meaningful, pd.Index columns.(e.g. features, columns) + + - if col_set == CS_RAW: + + the raw dataset will be returned. + + - if isinstance(col_set, List[str]): + + select several sets of meaningful columns, the returned data has multiple levels + + proc_func: Callable + + - Give a hook for processing data before fetching + - An example to explain the necessity of the hook: + + - A Dataset learned some processors to process data which is related to data segmentation + - It will apply them every time when preparing data. + - The learned processor require the dataframe remains the same format when fitting and applying + - However the data format will change according to the parameters. + - So the processors should be applied to the underlayer data. + + squeeze : bool + whether squeeze columns and index + + Returns + ------- + pd.DataFrame. + """ + # DataHandler is an example with only one dataframe, so data_key is not used. + _ = data_key # avoid linting errors (e.g., unused-argument) + return self._fetch_data( + data_storage=self._data, + selector=selector, + level=level, + col_set=col_set, + squeeze=squeeze, + proc_func=proc_func, + ) + + def _fetch_data( + self, + data_storage, + selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None), + level: Union[str, int] = "datetime", + col_set: Union[str, List[str]] = DataHandlerABC.CS_ALL, + squeeze: bool = False, + proc_func: Callable = None, + ): + # This method is extracted for sharing in subclasses + from .storage import BaseHandlerStorage # pylint: disable=C0415 + + # Following conflicts may occur + # - Does [20200101", "20210101"] mean selecting this slice or these two days? + # To solve this issue + # - slice have higher priorities (except when level is none) + if isinstance(selector, (tuple, list)) and level is not None: + # when level is None, the argument will be passed in directly + # we don't have to convert it into slice + try: + selector = slice(*selector) + except ValueError: + get_module_logger("DataHandlerLP").info(f"Fail to converting to query to slice. It will used directly") + + if isinstance(data_storage, pd.DataFrame): + data_df = data_storage + if proc_func is not None: + # FIXME: fetching by time first will be more friendly to `proc_func` + # Copy in case of `proc_func` changing the data inplace.... + data_df = proc_func(fetch_df_by_index(data_df, selector, level, fetch_orig=self.fetch_orig).copy()) + data_df = fetch_df_by_col(data_df, col_set) + else: + # Fetch column first will be more friendly to SepDataFrame + data_df = fetch_df_by_col(data_df, col_set) + data_df = fetch_df_by_index(data_df, selector, level, fetch_orig=self.fetch_orig) + elif isinstance(data_storage, BaseHandlerStorage): + if proc_func is not None: + raise ValueError(f"proc_func is not supported by the storage {type(data_storage)}") + data_df = data_storage.fetch(selector=selector, level=level, col_set=col_set, fetch_orig=self.fetch_orig) + else: + raise TypeError(f"data_storage should be pd.DataFrame|HashingStockStorage, not {type(data_storage)}") + + if squeeze: + # squeeze columns + data_df = data_df.squeeze() + # squeeze index + if isinstance(selector, (str, pd.Timestamp)): + data_df = data_df.reset_index(level=level, drop=True) + return data_df + + def get_cols(self, col_set=DataHandlerABC.CS_ALL) -> list: + """ + get the column names + + Parameters + ---------- + col_set : str + select a set of meaningful columns.(e.g. features, columns) + + Returns + ------- + list: + list of column names + """ + df = self._data.head() + df = fetch_df_by_col(df, col_set) + return df.columns.to_list() + + def get_range_selector(self, cur_date: Union[pd.Timestamp, str], periods: int) -> slice: + """ + get range selector by number of periods + + Args: + cur_date (pd.Timestamp or str): current date + periods (int): number of periods + """ + trading_dates = self._data.index.unique(level="datetime") + cur_loc = trading_dates.get_loc(cur_date) + pre_loc = cur_loc - periods + 1 + if pre_loc < 0: + warnings.warn("`periods` is too large. the first date will be returned.") + pre_loc = 0 + ref_date = trading_dates[pre_loc] + return slice(ref_date, cur_date) + + def get_range_iterator( + self, periods: int, min_periods: Optional[int] = None, **kwargs + ) -> Iterator[Tuple[pd.Timestamp, pd.DataFrame]]: + """ + get an iterator of sliced data with given periods + + Args: + periods (int): number of periods. + min_periods (int): minimum periods for sliced dataframe. + kwargs (dict): will be passed to `self.fetch`. + """ + trading_dates = self._data.index.unique(level="datetime") + if min_periods is None: + min_periods = periods + for cur_date in trading_dates[min_periods:]: + selector = self.get_range_selector(cur_date, periods) + yield cur_date, self.fetch(selector, **kwargs) + + +class DataHandlerLP(DataHandler): + """ + Motivation: + - For the case that we hope using different processor workflows for learning and inference; + + + DataHandler with **(L)earnable (P)rocessor** + + This handler will produce three pieces of data in pd.DataFrame format. + + - DK_R / self._data: the raw data loaded from the loader + - DK_I / self._infer: the data processed for inference + - DK_L / self._learn: the data processed for learning model. + + The motivation of using different processor workflows for learning and inference + Here are some examples. + + - The instrument universe for learning and inference may be different. + - The processing of some samples may rely on label (for example, some samples hit the limit may need extra processing or be dropped). + + - These processors only apply to the learning phase. + + Tips for data handler + + - To reduce the memory cost + + - `drop_raw=True`: this will modify the data inplace on raw data; + + - Please note processed data like `self._infer` or `self._learn` are concepts different from `segments` in Qlib's `Dataset` like "train" and "test" + + - Processed data like `self._infer` or `self._learn` are underlying data processed with different processors + - `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). + - For example, you can query `data._infer` processed by `infer_processors` in the "train" time segmentation. + """ + + # based on `self._data`, _infer and _learn are genrated after processors + _infer: pd.DataFrame # data for inference + _learn: pd.DataFrame # data for learning models + + # map data_key to attribute name + ATTR_MAP = {DataHandler.DK_R: "_data", DataHandler.DK_I: "_infer", DataHandler.DK_L: "_learn"} + + # process type + PTYPE_I = "independent" + # - self._infer will be processed by shared_processors + infer_processors + # - self._learn will be processed by shared_processors + learn_processors + + # NOTE: + PTYPE_A = "append" + + # - self._infer will be processed by shared_processors + infer_processors + # - self._learn will be processed by shared_processors + infer_processors + learn_processors + # - (e.g. self._infer processed by learn_processors ) + + def __init__( + self, + instruments=None, + start_time=None, + end_time=None, + data_loader: Union[dict, str, DataLoader] = None, + infer_processors: List = [], + learn_processors: List = [], + shared_processors: List = [], + process_type=PTYPE_A, + drop_raw=False, + **kwargs, + ): + """ + Parameters + ---------- + infer_processors : list + - list of of processors to generate data for inference + + - example of : + + .. code-block:: + + 1) classname & kwargs: + { + "class": "MinMaxNorm", + "kwargs": { + "fit_start_time": "20080101", + "fit_end_time": "20121231" + } + } + 2) Only classname: + "DropnaFeature" + 3) object instance of Processor + + learn_processors : list + similar to infer_processors, but for generating data for learning models + + process_type: str + PTYPE_I = 'independent' + + - self._infer will be processed by infer_processors + + - self._learn will be processed by learn_processors + + PTYPE_A = 'append' + + - self._infer will be processed by infer_processors + + - self._learn will be processed by infer_processors + learn_processors + + - (e.g. self._infer processed by learn_processors ) + drop_raw: bool + Whether to drop the raw data + """ + + # Setup preprocessor + self.infer_processors = [] # for lint + self.learn_processors = [] # for lint + self.shared_processors = [] # for lint + for pname in "infer_processors", "learn_processors", "shared_processors": + for proc in locals()[pname]: + getattr(self, pname).append( + init_instance_by_config( + proc, + None if (isinstance(proc, dict) and "module_path" in proc) else processor_module, + accept_types=processor_module.Processor, + ) + ) + + self.process_type = process_type + self.drop_raw = drop_raw + super().__init__(instruments, start_time, end_time, data_loader, **kwargs) + + def get_all_processors(self): + return self.shared_processors + self.infer_processors + self.learn_processors + + def fit(self): + """ + fit data without processing the data + """ + for proc in self.get_all_processors(): + with TimeInspector.logt(f"{proc.__class__.__name__}"): + proc.fit(self._data) + + def fit_process_data(self): + """ + fit and process data + + The input of the `fit` will be the output of the previous processor + """ + self.process_data(with_fit=True) + + @staticmethod + def _run_proc_l( + df: pd.DataFrame, proc_l: List[processor_module.Processor], with_fit: bool, check_for_infer: bool + ) -> pd.DataFrame: + for proc in proc_l: + if check_for_infer and not proc.is_for_infer(): + raise TypeError("Only processors usable for inference can be used in `infer_processors` ") + with TimeInspector.logt(f"{proc.__class__.__name__}"): + if with_fit: + proc.fit(df) + df = proc(df) + return df + + @staticmethod + def _is_proc_readonly(proc_l: List[processor_module.Processor]): + """ + NOTE: it will return True if `len(proc_l) == 0` + """ + for p in proc_l: + if not p.readonly(): + return False + return True + + def process_data(self, with_fit: bool = False): + """ + process_data data. Fun `processor.fit` if necessary + + Notation: (data) [processor] + + # data processing flow of self.process_type == DataHandlerLP.PTYPE_I + + .. code-block:: text + + (self._data)-[shared_processors]-(_shared_df)-[learn_processors]-(_learn_df) + \\ + -[infer_processors]-(_infer_df) + + # data processing flow of self.process_type == DataHandlerLP.PTYPE_A + + .. code-block:: text + + (self._data)-[shared_processors]-(_shared_df)-[infer_processors]-(_infer_df)-[learn_processors]-(_learn_df) + + Parameters + ---------- + with_fit : bool + The input of the `fit` will be the output of the previous processor + """ + # shared data processors + # 1) assign + _shared_df = self._data + if not self._is_proc_readonly(self.shared_processors): # avoid modifying the original data + _shared_df = _shared_df.copy() + # 2) process + _shared_df = self._run_proc_l(_shared_df, self.shared_processors, with_fit=with_fit, check_for_infer=True) + + # data for inference + # 1) assign + _infer_df = _shared_df + if not self._is_proc_readonly(self.infer_processors): # avoid modifying the original data + _infer_df = _infer_df.copy() + # 2) process + _infer_df = self._run_proc_l(_infer_df, self.infer_processors, with_fit=with_fit, check_for_infer=True) + + self._infer = _infer_df + + # data for learning + # 1) assign + if self.process_type == DataHandlerLP.PTYPE_I: + _learn_df = _shared_df + elif self.process_type == DataHandlerLP.PTYPE_A: + # based on `infer_df` and append the processor + _learn_df = _infer_df + else: + raise NotImplementedError(f"This type of input is not supported") + if not self._is_proc_readonly(self.learn_processors): # avoid modifying the original data + _learn_df = _learn_df.copy() + # 2) process + _learn_df = self._run_proc_l(_learn_df, self.learn_processors, with_fit=with_fit, check_for_infer=False) + + self._learn = _learn_df + + if self.drop_raw: + del self._data + + def config(self, processor_kwargs: dict = None, **kwargs): + """ + configuration of data. + # what data to be loaded from data source + + This method will be used when loading pickled handler from dataset. + The data will be initialized with different time range. + + """ + super().config(**kwargs) + if processor_kwargs is not None: + for processor in self.get_all_processors(): + processor.config(**processor_kwargs) + + # init type + IT_FIT_SEQ = "fit_seq" # the input of `fit` will be the output of the previous processor + IT_FIT_IND = "fit_ind" # the input of `fit` will be the original df + IT_LS = "load_state" # The state of the object has been load by pickle + + def setup_data(self, init_type: str = IT_FIT_SEQ, **kwargs): + """ + Set up the data in case of running initialization for multiple time + + Parameters + ---------- + init_type : str + The type `IT_*` listed above. + enable_cache : bool + default value is false: + + - if `enable_cache` == True: + + the processed data will be saved on disk, and handler will load the cached data from the disk directly + when we call `init` next time + """ + # init raw data + super().setup_data(**kwargs) + + with TimeInspector.logt("fit & process data"): + if init_type == DataHandlerLP.IT_FIT_IND: + self.fit() + self.process_data() + elif init_type == DataHandlerLP.IT_LS: + self.process_data() + elif init_type == DataHandlerLP.IT_FIT_SEQ: + self.fit_process_data() + else: + raise NotImplementedError(f"This type of input is not supported") + + # TODO: Be able to cache handler data. Save the memory for data processing + + def _get_df_by_key(self, data_key: DATA_KEY_TYPE = DataHandlerABC.DK_I) -> pd.DataFrame: + if data_key == self.DK_R and self.drop_raw: + raise AttributeError( + "DataHandlerLP has not attribute _data, please set drop_raw = False if you want to use raw data" + ) + df = getattr(self, self.ATTR_MAP[data_key]) + return df + + def fetch( + self, + selector: Union[pd.Timestamp, slice, str] = slice(None, None), + level: Union[str, int] = "datetime", + col_set=DataHandler.CS_ALL, + data_key: DATA_KEY_TYPE = DataHandler.DK_I, + squeeze: bool = False, + proc_func: Callable = None, + ) -> pd.DataFrame: + """ + fetch data from underlying data source + + Parameters + ---------- + selector : Union[pd.Timestamp, slice, str] + describe how to select data by index. + level : Union[str, int] + which index level to select the data. + col_set : str + select a set of meaningful columns.(e.g. features, columns). + data_key : str + the data to fetch: DK_*. + proc_func: Callable + please refer to the doc of DataHandler.fetch + + Returns + ------- + pd.DataFrame: + """ + + return self._fetch_data( + data_storage=self._get_df_by_key(data_key), + selector=selector, + level=level, + col_set=col_set, + squeeze=squeeze, + proc_func=proc_func, + ) + + def get_cols(self, col_set=DataHandler.CS_ALL, data_key: DATA_KEY_TYPE = DataHandlerABC.DK_I) -> list: + """ + get the column names + + Parameters + ---------- + col_set : str + select a set of meaningful columns.(e.g. features, columns). + data_key : DATA_KEY_TYPE + the data to fetch: DK_*. + + Returns + ------- + list: + list of column names + """ + df = self._get_df_by_key(data_key).head() + df = fetch_df_by_col(df, col_set) + return df.columns.to_list() + + @classmethod + def cast(cls, handler: "DataHandlerLP") -> "DataHandlerLP": + """ + Motivation + + - A user creates a datahandler in his customized package. Then he wants to share the processed handler to + other users without introduce the package dependency and complicated data processing logic. + - This class make it possible by casting the class to DataHandlerLP and only keep the processed data + + Parameters + ---------- + handler : DataHandlerLP + A subclass of DataHandlerLP + + Returns + ------- + DataHandlerLP: + the converted processed data + """ + new_hd: DataHandlerLP = object.__new__(DataHandlerLP) + new_hd.from_cast = True # add a mark for the cast instance + + for key in list(DataHandlerLP.ATTR_MAP.values()) + [ + "instruments", + "start_time", + "end_time", + "fetch_orig", + "drop_raw", + ]: + setattr(new_hd, key, getattr(handler, key, None)) + return new_hd + + @classmethod + def from_df(cls, df: pd.DataFrame) -> "DataHandlerLP": + """ + Motivation: + - When user want to get a quick data handler. + + The created data handler will have only one shared Dataframe without processors. + After creating the handler, user may often want to dump the handler for reuse + Here is a typical use case + + .. code-block:: python + + from qlib.data.dataset import DataHandlerLP + dh = DataHandlerLP.from_df(df) + dh.to_pickle(fname, dump_all=True) + + TODO: + - The StaticDataLoader is quite slow. It don't have to copy the data again... + + """ + loader = data_loader_module.StaticDataLoader(df) + return cls(data_loader=loader) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/loader.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/loader.py new file mode 100644 index 0000000000000000000000000000000000000000..2f3615a635776bc4effb4fdbbd8163a3f646deec --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/loader.py @@ -0,0 +1,414 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import abc +from pathlib import Path +import warnings +import pandas as pd + +from typing import Tuple, Union, List, Dict + +from qlib.data import D +from qlib.utils import load_dataset, init_instance_by_config, time_to_slc_point +from qlib.utils.pickle_utils import restricted_pickle_load +from qlib.log import get_module_logger +from qlib.utils.serial import Serializable + + +class DataLoader(abc.ABC): + """ + DataLoader is designed for loading raw data from original data source. + """ + + @abc.abstractmethod + def load(self, instruments, start_time=None, end_time=None) -> pd.DataFrame: + """ + load the data as pd.DataFrame. + + Example of the data (The multi-index of the columns is optional.): + + .. code-block:: text + + feature label + $close $volume Ref($close, 1) Mean($close, 3) $high-$low LABEL0 + datetime instrument + 2010-01-04 SH600000 81.807068 17145150.0 83.737389 83.016739 2.741058 0.0032 + SH600004 13.313329 11800983.0 13.313329 13.317701 0.183632 0.0042 + SH600005 37.796539 12231662.0 38.258602 37.919757 0.970325 0.0289 + + + Parameters + ---------- + instruments : str or dict + it can either be the market name or the config file of instruments generated by InstrumentProvider. + If the value of instruments is None, it means that no filtering is done. + start_time : str + start of the time range. + end_time : str + end of the time range. + + Returns + ------- + pd.DataFrame: + data load from the under layer source + + Raise + ----- + KeyError: + if the instruments filter is not supported, raise KeyError + """ + + +class DLWParser(DataLoader): + """ + (D)ata(L)oader (W)ith (P)arser for features and names + + Extracting this class so that QlibDataLoader and other dataloaders(such as QdbDataLoader) can share the fields. + """ + + def __init__(self, config: Union[list, tuple, dict]): + """ + Parameters + ---------- + config : Union[list, tuple, dict] + Config will be used to describe the fields and column names + + .. code-block:: + + := { + "group_name1": + "group_name2": + } + or + := + + := ["expr", ...] | (["expr", ...], ["col_name", ...]) + # NOTE: list or tuple will be treated as the things when parsing + """ + self.is_group = isinstance(config, dict) + + if self.is_group: + self.fields = {grp: self._parse_fields_info(fields_info) for grp, fields_info in config.items()} + else: + self.fields = self._parse_fields_info(config) + + def _parse_fields_info(self, fields_info: Union[list, tuple]) -> Tuple[list, list]: + if len(fields_info) == 0: + raise ValueError("The size of fields must be greater than 0") + + if not isinstance(fields_info, (list, tuple)): + raise TypeError("Unsupported type") + + if isinstance(fields_info[0], str): + exprs = names = fields_info + elif isinstance(fields_info[0], (list, tuple)): + exprs, names = fields_info + else: + raise NotImplementedError(f"This type of input is not supported") + return exprs, names + + @abc.abstractmethod + def load_group_df( + self, + instruments, + exprs: list, + names: list, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + gp_name: str = None, + ) -> pd.DataFrame: + """ + load the dataframe for specific group + + Parameters + ---------- + instruments : + the instruments. + exprs : list + the expressions to describe the content of the data. + names : list + the name of the data. + + Returns + ------- + pd.DataFrame: + the queried dataframe. + """ + + def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame: + if self.is_group: + df = pd.concat( + { + grp: self.load_group_df(instruments, exprs, names, start_time, end_time, grp) + for grp, (exprs, names) in self.fields.items() + }, + axis=1, + ) + else: + exprs, names = self.fields + df = self.load_group_df(instruments, exprs, names, start_time, end_time) + return df + + +class QlibDataLoader(DLWParser): + """Same as QlibDataLoader. The fields can be define by config""" + + def __init__( + self, + config: Tuple[list, tuple, dict], + filter_pipe: List = None, + swap_level: bool = True, + freq: Union[str, dict] = "day", + inst_processors: Union[dict, list] = None, + ): + """ + Parameters + ---------- + config : Tuple[list, tuple, dict] + Please refer to the doc of DLWParser + filter_pipe : + Filter pipe for the instruments + swap_level : + Whether to swap level of MultiIndex + freq: dict or str + If type(config) == dict and type(freq) == str, load config data using freq. + If type(config) == dict and type(freq) == dict, load config[] data using freq[] + inst_processors: dict | list + If inst_processors is not None and type(config) == dict; load config[] data using inst_processors[] + If inst_processors is a list, then it will be applied to all groups. + """ + self.filter_pipe = filter_pipe + self.swap_level = swap_level + self.freq = freq + + # sample + self.inst_processors = inst_processors if inst_processors is not None else {} + assert isinstance( + self.inst_processors, (dict, list) + ), f"inst_processors(={self.inst_processors}) must be dict or list" + + super().__init__(config) + + if self.is_group: + # check sample config + if isinstance(freq, dict): + for _gp in config.keys(): + if _gp not in freq: + raise ValueError(f"freq(={freq}) missing group(={_gp})") + assert ( + self.inst_processors + ), f"freq(={self.freq}), inst_processors(={self.inst_processors}) cannot be None/empty" + + def load_group_df( + self, + instruments, + exprs: list, + names: list, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + gp_name: str = None, + ) -> pd.DataFrame: + if instruments is None: + warnings.warn("`instruments` is not set, will load all stocks") + instruments = "all" + if isinstance(instruments, str): + instruments = D.instruments(instruments, filter_pipe=self.filter_pipe) + elif self.filter_pipe is not None: + warnings.warn("`filter_pipe` is not None, but it will not be used with `instruments` as list") + + freq = self.freq[gp_name] if isinstance(self.freq, dict) else self.freq + inst_processors = ( + self.inst_processors if isinstance(self.inst_processors, list) else self.inst_processors.get(gp_name, []) + ) + df = D.features(instruments, exprs, start_time, end_time, freq=freq, inst_processors=inst_processors) + df.columns = names + if self.swap_level: + df = df.swaplevel().sort_index() # NOTE: if swaplevel, return + return df + + +class StaticDataLoader(DataLoader, Serializable): + """ + DataLoader that supports loading data from file or as provided. + """ + + include_attr = ["_config"] + + def __init__(self, config: Union[dict, str, pd.DataFrame], join="outer"): + """ + Parameters + ---------- + config : dict + {fields_group: } + join : str + How to align different dataframes + """ + self._config = config # using "_" to avoid confliction with the method `config` of Serializable + self.join = join + self._data = None + + def __getstate__(self) -> dict: + # avoid pickling `self._data` + return {k: v for k, v in self.__dict__.items() if not k.startswith("_")} + + def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame: + self._maybe_load_raw_data() + + # 1) Filter by instruments + if instruments is None: + df = self._data + else: + df = self._data.loc(axis=0)[:, instruments] + + # 2) Filter by Datetime + if start_time is None and end_time is None: + return df # NOTE: avoid copy by loc + # pd.Timestamp(None) == NaT, use NaT as index can not fetch correct thing, so do not change None. + start_time = time_to_slc_point(start_time) + end_time = time_to_slc_point(end_time) + return df.loc[start_time:end_time] + + def _maybe_load_raw_data(self): + if self._data is not None: + return + if isinstance(self._config, dict): + self._data = pd.concat( + {fields_group: load_dataset(path_or_obj) for fields_group, path_or_obj in self._config.items()}, + axis=1, + join=self.join, + ) + self._data.sort_index(inplace=True) + elif isinstance(self._config, (str, Path)): + if str(self._config).strip().endswith(".parquet"): + self._data = pd.read_parquet(self._config, engine="pyarrow") + else: + with Path(self._config).open("rb") as f: + self._data = restricted_pickle_load(f) + elif isinstance(self._config, pd.DataFrame): + self._data = self._config + + +class NestedDataLoader(DataLoader): + """ + We have multiple DataLoader, we can use this class to combine them. + """ + + def __init__(self, dataloader_l: List[Dict], join="left") -> None: + """ + + Parameters + ---------- + dataloader_l : list[dict] + A list of dataloader, for exmaple + + .. code-block:: python + + nd = NestedDataLoader( + dataloader_l=[ + { + "class": "qlib.contrib.data.loader.Alpha158DL", + }, { + "class": "qlib.contrib.data.loader.Alpha360DL", + "kwargs": { + "config": { + "label": ( ["Ref($close, -2)/Ref($close, -1) - 1"], ["LABEL0"]) + } + } + } + ] + ) + join : + it will pass to pd.concat when merging it. + """ + super().__init__() + self.data_loader_l = [ + (dl if isinstance(dl, DataLoader) else init_instance_by_config(dl)) for dl in dataloader_l + ] + self.join = join + + def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame: + df_full = None + for dl in self.data_loader_l: + try: + df_current = dl.load(instruments, start_time, end_time) + except KeyError: + warnings.warn( + "If the value of `instruments` cannot be processed, it will set instruments to None to get all the data." + ) + df_current = dl.load(instruments=None, start_time=start_time, end_time=end_time) + if df_full is None: + df_full = df_current + else: + current_columns = df_current.columns.tolist() + full_columns = df_full.columns.tolist() + columns_to_drop = [col for col in current_columns if col in full_columns] + df_full.drop(columns=columns_to_drop, inplace=True) + df_full = pd.merge(df_full, df_current, left_index=True, right_index=True, how=self.join) + return df_full.sort_index(axis=1) + + +class DataLoaderDH(DataLoader): + """DataLoaderDH + DataLoader based on (D)ata (H)andler + It is designed to load multiple data from data handler + - If you just want to load data from single datahandler, you can write them in single data handler + + TODO: What make this module not that easy to use. + + - For online scenario + + - The underlayer data handler should be configured. But data loader doesn't provide such interface & hook. + """ + + def __init__(self, handler_config: dict, fetch_kwargs: dict = {}, is_group=False): + """ + Parameters + ---------- + handler_config : dict + handler_config will be used to describe the handlers + + .. code-block:: + + := { + "group_name1": + "group_name2": + } + or + := + := DataHandler Instance | DataHandler Config + + fetch_kwargs : dict + fetch_kwargs will be used to describe the different arguments of fetch method, such as col_set, squeeze, data_key, etc. + + is_group: bool + is_group will be used to describe whether the key of handler_config is group + + """ + from qlib.data.dataset.handler import DataHandler # pylint: disable=C0415 + + if is_group: + self.handlers = { + grp: init_instance_by_config(config, accept_types=DataHandler) for grp, config in handler_config.items() + } + else: + self.handlers = init_instance_by_config(handler_config, accept_types=DataHandler) + + self.is_group = is_group + self.fetch_kwargs = {"col_set": DataHandler.CS_RAW} + self.fetch_kwargs.update(fetch_kwargs) + + def load(self, instruments=None, start_time=None, end_time=None) -> pd.DataFrame: + if instruments is not None: + get_module_logger(self.__class__.__name__).warning(f"instruments[{instruments}] is ignored") + + if self.is_group: + df = pd.concat( + { + grp: dh.fetch(selector=slice(start_time, end_time), level="datetime", **self.fetch_kwargs) + for grp, dh in self.handlers.items() + }, + axis=1, + ) + else: + df = self.handlers.fetch(selector=slice(start_time, end_time), level="datetime", **self.fetch_kwargs) + return df diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/processor.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/processor.py new file mode 100644 index 0000000000000000000000000000000000000000..d05dbe381c5bcb245c25c8d1ed26128ed5d5dc35 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/processor.py @@ -0,0 +1,419 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import abc +from typing import Union, Text, Optional +import numpy as np +import pandas as pd + +from qlib.utils.data import robust_zscore, zscore +from ...constant import EPS +from .utils import fetch_df_by_index +from ...utils.serial import Serializable +from ...utils.paral import datetime_groupby_apply +from qlib.data.inst_processor import InstProcessor +from qlib.data import D + + +def get_group_columns(df: pd.DataFrame, group: Union[Text, None]): + """ + get a group of columns from multi-index columns DataFrame + + Parameters + ---------- + df : pd.DataFrame + with multi of columns. + group : str + the name of the feature group, i.e. the first level value of the group index. + """ + if group is None: + return df.columns + else: + return df.columns[df.columns.get_loc(group)] + + +class Processor(Serializable): + def fit(self, df: pd.DataFrame = None): + """ + learn data processing parameters + + Parameters + ---------- + df : pd.DataFrame + When we fit and process data with processor one by one. The fit function reiles on the output of previous + processor, i.e. `df`. + + """ + + @abc.abstractmethod + def __call__(self, df: pd.DataFrame): + """ + process the data + + NOTE: **The processor could change the content of `df` inplace !!!!! ** + User should keep a copy of data outside + + Parameters + ---------- + df : pd.DataFrame + The raw_df of handler or result from previous processor. + """ + + def is_for_infer(self) -> bool: + """ + Is this processor usable for inference + Some processors are not usable for inference. + + Returns + ------- + bool: + if it is usable for infenrece. + """ + return True + + def readonly(self) -> bool: + """ + Does the processor treat the input data readonly (i.e. does not write the input data) when processing + + Knowning the readonly information is helpful to the Handler to avoid uncessary copy + """ + return False + + def config(self, **kwargs): + attr_list = {"fit_start_time", "fit_end_time"} + for k, v in kwargs.items(): + if k in attr_list and hasattr(self, k): + setattr(self, k, v) + + for attr in attr_list: + if attr in kwargs: + kwargs.pop(attr) + super().config(**kwargs) + + +class DropnaProcessor(Processor): + def __init__(self, fields_group=None): + self.fields_group = fields_group + + def __call__(self, df): + return df.dropna(subset=get_group_columns(df, self.fields_group)) + + def readonly(self): + return True + + +class DropnaLabel(DropnaProcessor): + def __init__(self, fields_group="label"): + super().__init__(fields_group=fields_group) + + def is_for_infer(self) -> bool: + """The samples are dropped according to label. So it is not usable for inference""" + return False + + +class DropCol(Processor): + def __init__(self, col_list=[]): + self.col_list = col_list + + def __call__(self, df): + if isinstance(df.columns, pd.MultiIndex): + mask = df.columns.get_level_values(-1).isin(self.col_list) + else: + mask = df.columns.isin(self.col_list) + return df.loc[:, ~mask] + + def readonly(self): + return True + + +class FilterCol(Processor): + def __init__(self, fields_group="feature", col_list=[]): + self.fields_group = fields_group + self.col_list = col_list + + def __call__(self, df): + cols = get_group_columns(df, self.fields_group) + all_cols = df.columns + diff_cols = np.setdiff1d(all_cols.get_level_values(-1), cols.get_level_values(-1)) + self.col_list = np.union1d(diff_cols, self.col_list) + mask = df.columns.get_level_values(-1).isin(self.col_list) + return df.loc[:, mask] + + def readonly(self): + return True + + +class TanhProcess(Processor): + """Use tanh to process noise data""" + + def __call__(self, df): + def tanh_denoise(data): + mask = data.columns.get_level_values(1).str.contains("LABEL") + col = df.columns[~mask] + data[col] = data[col] - 1 + data[col] = np.tanh(data[col]) + + return data + + return tanh_denoise(df) + + +class ProcessInf(Processor): + """Process infinity""" + + def __call__(self, df): + def replace_inf(data): + def process_inf(df): + for col in df.columns: + # FIXME: Such behavior is very weird + df[col] = df[col].replace([np.inf, -np.inf], df[col][~np.isinf(df[col])].mean()) + return df + + data = datetime_groupby_apply(data, process_inf) + data.sort_index(inplace=True) + return data + + return replace_inf(df) + + +class Fillna(Processor): + """Process NaN""" + + def __init__(self, fields_group=None, fill_value=0): + self.fields_group = fields_group + self.fill_value = fill_value + + def __call__(self, df): + if self.fields_group is None: + df.fillna(self.fill_value, inplace=True) + else: + # this implementation is extremely slow + # df.fillna({col: self.fill_value for col in cols}, inplace=True) + df[self.fields_group] = df[self.fields_group].fillna(self.fill_value) + return df + + +class MinMaxNorm(Processor): + def __init__(self, fit_start_time, fit_end_time, fields_group=None): + # NOTE: correctly set the `fit_start_time` and `fit_end_time` is very important !!! + # `fit_end_time` **must not** include any information from the test data!!! + self.fit_start_time = fit_start_time + self.fit_end_time = fit_end_time + self.fields_group = fields_group + + def fit(self, df: pd.DataFrame = None): + df = fetch_df_by_index(df, slice(self.fit_start_time, self.fit_end_time), level="datetime") + cols = get_group_columns(df, self.fields_group) + self.min_val = np.nanmin(df[cols].values, axis=0) + self.max_val = np.nanmax(df[cols].values, axis=0) + self.ignore = self.min_val == self.max_val + # To improve the speed, we set the value of `min_val` to `0` for the columns that do not need to be processed, + # and the value of `max_val` to `1`, when using `(x - min_val) / (max_val - min_val)` for uniform calculation, + # the columns that do not need to be processed will be calculated by `(x - 0) / (1 - 0)`, + # as you can see, the columns that do not need to be processed, will not be affected. + for _i, _con in enumerate(self.ignore): + if _con: + self.min_val[_i] = 0 + self.max_val[_i] = 1 + self.cols = cols + + def __call__(self, df): + def normalize(x, min_val=self.min_val, max_val=self.max_val): + return (x - min_val) / (max_val - min_val) + + df.loc(axis=1)[self.cols] = normalize(df[self.cols].values) + return df + + +class ZScoreNorm(Processor): + """ZScore Normalization""" + + def __init__(self, fit_start_time, fit_end_time, fields_group=None): + # NOTE: correctly set the `fit_start_time` and `fit_end_time` is very important !!! + # `fit_end_time` **must not** include any information from the test data!!! + self.fit_start_time = fit_start_time + self.fit_end_time = fit_end_time + self.fields_group = fields_group + + def fit(self, df: pd.DataFrame = None): + df = fetch_df_by_index(df, slice(self.fit_start_time, self.fit_end_time), level="datetime") + cols = get_group_columns(df, self.fields_group) + self.mean_train = np.nanmean(df[cols].values, axis=0) + self.std_train = np.nanstd(df[cols].values, axis=0) + self.ignore = self.std_train == 0 + # To improve the speed, we set the value of `std_train` to `1` for the columns that do not need to be processed, + # and the value of `mean_train` to `0`, when using `(x - mean_train) / std_train` for uniform calculation, + # the columns that do not need to be processed will be calculated by `(x - 0) / 1`, + # as you can see, the columns that do not need to be processed, will not be affected. + for _i, _con in enumerate(self.ignore): + if _con: + self.std_train[_i] = 1 + self.mean_train[_i] = 0 + self.cols = cols + + def __call__(self, df): + def normalize(x, mean_train=self.mean_train, std_train=self.std_train): + return (x - mean_train) / std_train + + df.loc(axis=1)[self.cols] = normalize(df[self.cols].values) + return df + + +class RobustZScoreNorm(Processor): + """Robust ZScore Normalization + + Use robust statistics for Z-Score normalization: + mean(x) = median(x) + std(x) = MAD(x) * 1.4826 + + Reference: + https://en.wikipedia.org/wiki/Median_absolute_deviation. + """ + + def __init__(self, fit_start_time, fit_end_time, fields_group=None, clip_outlier=True): + # NOTE: correctly set the `fit_start_time` and `fit_end_time` is very important !!! + # `fit_end_time` **must not** include any information from the test data!!! + self.fit_start_time = fit_start_time + self.fit_end_time = fit_end_time + self.fields_group = fields_group + self.clip_outlier = clip_outlier + + def fit(self, df: pd.DataFrame = None): + df = fetch_df_by_index(df, slice(self.fit_start_time, self.fit_end_time), level="datetime") + self.cols = get_group_columns(df, self.fields_group) + X = df[self.cols].values + self.mean_train = np.nanmedian(X, axis=0) + self.std_train = np.nanmedian(np.abs(X - self.mean_train), axis=0) + self.std_train += EPS + self.std_train *= 1.4826 + + def __call__(self, df): + X = df[self.cols] + X -= self.mean_train + X /= self.std_train + if self.clip_outlier: + X = np.clip(X, -3, 3) + df[self.cols] = X + return df + + +class CSZScoreNorm(Processor): + """Cross Sectional ZScore Normalization""" + + def __init__(self, fields_group=None, method="zscore"): + self.fields_group = fields_group + if method == "zscore": + self.zscore_func = zscore + elif method == "robust": + self.zscore_func = robust_zscore + else: + raise NotImplementedError(f"This type of input is not supported") + + def __call__(self, df): + # try not modify original dataframe + if not isinstance(self.fields_group, list): + self.fields_group = [self.fields_group] + # depress warning by references: + # https://stackoverflow.com/questions/20625582/how-to-deal-with-settingwithcopywarning-in-pandas + # https://pandas.pydata.org/pandas-docs/stable/user_guide/options.html#getting-and-setting-options + with pd.option_context("mode.chained_assignment", None): + for g in self.fields_group: + cols = get_group_columns(df, g) + df[cols] = df[cols].groupby("datetime", group_keys=False).apply(self.zscore_func) + return df + + +class CSRankNorm(Processor): + """ + Cross Sectional Rank Normalization. + "Cross Sectional" is often used to describe data operations. + The operations across different stocks are often called Cross Sectional Operation. + + For example, CSRankNorm is an operation that grouping the data by each day and rank `across` all the stocks in each day. + + Explanation about 3.46 & 0.5 + + .. code-block:: python + + import numpy as np + import pandas as pd + x = np.random.random(10000) # for any variable + x_rank = pd.Series(x).rank(pct=True) # if it is converted to rank, it will be a uniform distributed + x_rank_norm = (x_rank - x_rank.mean()) / x_rank.std() # Normally, we will normalize it to make it like normal distribution + + x_rank.mean() # accounts for 0.5 + 1 / x_rank.std() # accounts for 3.46 + + """ + + def __init__(self, fields_group=None): + self.fields_group = fields_group + + def __call__(self, df): + # try not modify original dataframe + cols = get_group_columns(df, self.fields_group) + t = df[cols].groupby("datetime", group_keys=False).rank(pct=True) + t -= 0.5 + t *= 3.46 # NOTE: towards unit std + df[cols] = t + return df + + +class CSZFillna(Processor): + """Cross Sectional Fill Nan""" + + def __init__(self, fields_group=None): + self.fields_group = fields_group + + def __call__(self, df): + cols = get_group_columns(df, self.fields_group) + df[cols] = df[cols].groupby("datetime", group_keys=False).apply(lambda x: x.fillna(x.mean())) + return df + + +class HashStockFormat(Processor): + """Process the storage of from df into hasing stock format""" + + def __call__(self, df: pd.DataFrame): + from .storage import HashingStockStorage # pylint: disable=C0415 + + return HashingStockStorage.from_df(df) + + +class TimeRangeFlt(InstProcessor): + """ + This is a filter to filter stock. + Only keep the data that exist from start_time to end_time (the existence in the middle is not checked.) + WARNING: It may induce leakage!!! + """ + + def __init__( + self, + start_time: Optional[Union[pd.Timestamp, str]] = None, + end_time: Optional[Union[pd.Timestamp, str]] = None, + freq: str = "day", + ): + """ + Parameters + ---------- + start_time : Optional[Union[pd.Timestamp, str]] + The data must start earlier (or equal) than `start_time` + None indicates data will not be filtered based on `start_time` + end_time : Optional[Union[pd.Timestamp, str]] + similar to start_time + freq : str + The frequency of the calendar + """ + # Align to calendar before filtering + cal = D.calendar(start_time=start_time, end_time=end_time, freq=freq) + self.start_time = None if start_time is None else cal[0] + self.end_time = None if end_time is None else cal[-1] + + def __call__(self, df: pd.DataFrame, instrument, *args, **kwargs): + if ( + df.empty + or (self.start_time is None or df.index.min() <= self.start_time) + and (self.end_time is None or df.index.max() >= self.end_time) + ): + return df + return df.head(0) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/storage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..ca3325a28cfbef116ca26f9069defa0887aa9ec1 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/storage.py @@ -0,0 +1,191 @@ +from abc import abstractmethod +import pandas as pd +import numpy as np + +from .handler import DataHandler +from typing import Union, List +from qlib.log import get_module_logger + +from .utils import get_level_index, fetch_df_by_index, fetch_df_by_col + + +class BaseHandlerStorage: + """ + Base data storage for datahandler + - pd.DataFrame is the default data storage format in Qlib datahandler + - If users want to use custom data storage, they should define subclass inherited BaseHandlerStorage, and implement the following method + """ + + @abstractmethod + def fetch( + self, + selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None), + level: Union[str, int] = "datetime", + col_set: Union[str, List[str]] = DataHandler.CS_ALL, + fetch_orig: bool = True, + ) -> pd.DataFrame: + """fetch data from the data storage + + Parameters + ---------- + selector : Union[pd.Timestamp, slice, str] + describe how to select data by index + level : Union[str, int] + which index level to select the data + - if level is None, apply selector to df directly + col_set : Union[str, List[str]] + - if isinstance(col_set, str): + select a set of meaningful columns.(e.g. features, columns) + if col_set == DataHandler.CS_RAW: + the raw dataset will be returned. + - if isinstance(col_set, List[str]): + select several sets of meaningful columns, the returned data has multiple level + fetch_orig : bool + Return the original data instead of copy if possible. + + Returns + ------- + pd.DataFrame + the dataframe fetched + """ + raise NotImplementedError("fetch is method not implemented!") + + +class NaiveDFStorage(BaseHandlerStorage): + """Naive data storage for datahandler + - NaiveDFStorage is a naive data storage for datahandler + - NaiveDFStorage will input a pandas.DataFrame as and provide interface support for fetching data + """ + + def __init__(self, df: pd.DataFrame): + self.df = df + + def fetch( + self, + selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None), + level: Union[str, int] = "datetime", + col_set: Union[str, List[str]] = DataHandler.CS_ALL, + fetch_orig: bool = True, + ) -> pd.DataFrame: + # Following conflicts may occur + # - Does [20200101", "20210101"] mean selecting this slice or these two days? + # To solve this issue + # - slice have higher priorities (except when level is none) + if isinstance(selector, (tuple, list)) and level is not None: + # when level is None, the argument will be passed in directly + # we don't have to convert it into slice + try: + selector = slice(*selector) + except ValueError: + get_module_logger("DataHandlerLP").info(f"Fail to converting to query to slice. It will used directly") + + data_df = self.df + data_df = fetch_df_by_col(data_df, col_set) + data_df = fetch_df_by_index(data_df, selector, level, fetch_orig=fetch_orig) + return data_df + + +class HashingStockStorage(BaseHandlerStorage): + """Hashing data storage for datahanlder + - The default data storage pandas.DataFrame is too slow when randomly accessing one stock's data + - HashingStockStorage hashes the multiple stocks' data(pandas.DataFrame) by the key `stock_id`. + - 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: + { + stock1_id: stock1_data, + stock2_id: stock2_data, + ... + stockn_id: stockn_data, + } + - By the `fetch` method, users can access any stock data with much lower time cost than default data storage + """ + + def __init__(self, df): + self.hash_df = dict() + self.stock_level = get_level_index(df, "instrument") + for k, v in df.groupby(level="instrument", group_keys=False): + self.hash_df[k] = v + self.columns = df.columns + + @staticmethod + def from_df(df): + return HashingStockStorage(df) + + def _fetch_hash_df_by_stock(self, selector, level): + """fetch the data with stock selector + + Parameters + ---------- + selector : Union[pd.Timestamp, slice, str] + describe how to select data by index + level : Union[str, int] + which index level to select the data + - if level is None, apply selector to df directly + - the `_fetch_hash_df_by_stock` will parse the stock selector in arg `selector` + + Returns + ------- + Dict + The dict whose key is stock_id, value is the stock's data + """ + + stock_selector = slice(None) + time_selector = slice(None) # by default not filter by time. + + if level is None: + # For directly applying. + if isinstance(selector, tuple) and self.stock_level < len(selector): + # full selector format + stock_selector = selector[self.stock_level] + time_selector = selector[1 - self.stock_level] + elif isinstance(selector, (list, str)) and self.stock_level == 0: + # only stock selector + stock_selector = selector + elif level in ("instrument", self.stock_level): + if isinstance(selector, tuple): + # NOTE: How could the stock level selector be a tuple? + stock_selector = selector[0] + raise TypeError( + "I forget why would this case appear. But I think it does not make sense. So we raise a error for that case." + ) + elif isinstance(selector, (list, str)): + stock_selector = selector + + if not isinstance(stock_selector, (list, str)) and stock_selector != slice(None): + raise TypeError(f"stock selector must be type str|list, or slice(None), rather than {stock_selector}") + + if stock_selector == slice(None): + return self.hash_df, time_selector + + if isinstance(stock_selector, str): + stock_selector = [stock_selector] + + select_dict = dict() + for each_stock in sorted(stock_selector): + if each_stock in self.hash_df: + select_dict[each_stock] = self.hash_df[each_stock] + return select_dict, time_selector + + def fetch( + self, + selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None), + level: Union[str, int] = "datetime", + col_set: Union[str, List[str]] = DataHandler.CS_ALL, + fetch_orig: bool = True, + ) -> pd.DataFrame: + fetch_stock_df_list, time_selector = self._fetch_hash_df_by_stock(selector=selector, level=level) + fetch_stock_df_list = list(fetch_stock_df_list.values()) + for _index, stock_df in enumerate(fetch_stock_df_list): + fetch_col_df = fetch_df_by_col(df=stock_df, col_set=col_set) + fetch_index_df = fetch_df_by_index( + df=fetch_col_df, selector=time_selector, level="datetime", fetch_orig=fetch_orig + ) + fetch_stock_df_list[_index] = fetch_index_df + if len(fetch_stock_df_list) == 0: + index_names = ("instrument", "datetime") if self.stock_level == 0 else ("datetime", "instrument") + return pd.DataFrame( + index=pd.MultiIndex.from_arrays([[], []], names=index_names), columns=self.columns, dtype=np.float32 + ) + elif len(fetch_stock_df_list) == 1: + return fetch_stock_df_list[0] + else: + return pd.concat(fetch_stock_df_list, sort=False, copy=~fetch_orig) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..688cde99af7d9df3cbf50875c5ffe0c848246f63 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/utils.py @@ -0,0 +1,142 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations +import pandas as pd +from typing import Union, List, TYPE_CHECKING +from qlib.utils import init_instance_by_config + +if TYPE_CHECKING: + from qlib.data.dataset import DataHandler + + +def get_level_index(df: pd.DataFrame, level: Union[str, int]) -> int: + """ + + get the level index of `df` given `level` + + Parameters + ---------- + df : pd.DataFrame + data + level : Union[str, int] + index level + + Returns + ------- + int: + The level index in the multiple index + """ + if isinstance(level, str): + try: + return df.index.names.index(level) + except (AttributeError, ValueError): + # NOTE: If level index is not given in the data, the default level index will be ('datetime', 'instrument') + return ("datetime", "instrument").index(level) + elif isinstance(level, int): + return level + else: + raise NotImplementedError(f"This type of input is not supported") + + +def fetch_df_by_index( + df: pd.DataFrame, + selector: Union[pd.Timestamp, slice, str, list, pd.Index], + level: Union[str, int], + fetch_orig=True, +) -> pd.DataFrame: + """ + fetch data from `data` with `selector` and `level` + + selector are assumed to be well processed. + `fetch_df_by_index` is only responsible for get the right level + + Parameters + ---------- + selector : Union[pd.Timestamp, slice, str, list] + selector + level : Union[int, str] + the level to use the selector + + Returns + ------- + Data of the given index. + """ + # level = None -> use selector directly + if level is None or isinstance(selector, pd.MultiIndex): + return df.loc(axis=0)[selector] + # Try to get the right index + idx_slc = (selector, slice(None, None)) + if get_level_index(df, level) == 1: + idx_slc = idx_slc[1], idx_slc[0] + if fetch_orig: + for slc in idx_slc: + if slc != slice(None, None): + return df.loc[pd.IndexSlice[idx_slc],] # noqa: E231 + else: # pylint: disable=W0120 + return df + else: + return df.loc[pd.IndexSlice[idx_slc],] # noqa: E231 + + +def fetch_df_by_col(df: pd.DataFrame, col_set: Union[str, List[str]]) -> pd.DataFrame: + from .handler import DataHandler # pylint: disable=C0415 + + if not isinstance(df.columns, pd.MultiIndex) or col_set == DataHandler.CS_RAW: + return df + elif col_set == DataHandler.CS_ALL: + return df.droplevel(axis=1, level=0) + else: + return df.loc(axis=1)[col_set] + + +def convert_index_format(df: Union[pd.DataFrame, pd.Series], level: str = "datetime") -> Union[pd.DataFrame, pd.Series]: + """ + Convert the format of df.MultiIndex according to the following rules: + - If `level` is the first level of df.MultiIndex, do nothing + - If `level` is the second level of df.MultiIndex, swap the level of index. + + NOTE: + the number of levels of df.MultiIndex should be 2 + + Parameters + ---------- + df : Union[pd.DataFrame, pd.Series] + raw DataFrame/Series + level : str, optional + the level that will be converted to the first one, by default "datetime" + + Returns + ------- + Union[pd.DataFrame, pd.Series] + converted DataFrame/Series + """ + + if get_level_index(df, level=level) == 1: + df = df.swaplevel().sort_index() + return df + + +def init_task_handler(task: dict) -> DataHandler: + """ + initialize the handler part of the task **inplace** + + Parameters + ---------- + task : dict + the task to be handled + + Returns + ------- + Union[DataHandler, None]: + returns + """ + # avoid recursive import + from .handler import DataHandler # pylint: disable=C0415 + + h_conf = task["dataset"]["kwargs"].get("handler") + if h_conf is not None: + handler = init_instance_by_config(h_conf, accept_types=DataHandler) + task["dataset"]["kwargs"]["handler"] = handler + return handler + else: + raise ValueError("The task does not contains a handler part.") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/weight.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/weight.py new file mode 100644 index 0000000000000000000000000000000000000000..ee82080533b7a1f46d898e467463d59e4a2f846f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/dataset/weight.py @@ -0,0 +1,27 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +class Reweighter: + def __init__(self, *args, **kwargs): + """ + To initialize the Reweighter, users should provide specific methods to let reweighter do the reweighting (such as sample-wise, rule-based). + """ + raise NotImplementedError() + + def reweight(self, data: object) -> object: + """ + Get weights for data + + Parameters + ---------- + data : object + The input data. + The first dimension is the index of samples + + Returns + ------- + object: + the weights info for the data + """ + raise NotImplementedError(f"This type of input is not supported") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/filter.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..246d6baf76571991c9e03e277c93983f087a6397 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/filter.py @@ -0,0 +1,375 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import print_function +from abc import abstractmethod + +import re +import pandas as pd +import numpy as np +import abc + +from .data import Cal, DatasetD + + +class BaseDFilter(abc.ABC): + """Dynamic Instruments Filter Abstract class + + Users can override this class to construct their own filter + + Override __init__ to input filter regulations + + Override filter_main to use the regulations to filter instruments + """ + + def __init__(self): + pass + + @staticmethod + def from_config(config): + """Construct an instance from config dict. + + Parameters + ---------- + config : dict + dict of config parameters. + """ + raise NotImplementedError("Subclass of BaseDFilter must reimplement `from_config` method") + + @abstractmethod + def to_config(self): + """Construct an instance from config dict. + + Returns + ---------- + dict + return the dict of config parameters. + """ + raise NotImplementedError("Subclass of BaseDFilter must reimplement `to_config` method") + + +class SeriesDFilter(BaseDFilter): + """Dynamic Instruments Filter Abstract class to filter a series of certain features + + Filters should provide parameters: + + - filter start time + - filter end time + - filter rule + + Override __init__ to assign a certain rule to filter the series. + + 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 + """ + + def __init__(self, fstart_time=None, fend_time=None, keep=False): + """Init function for filter base class. + Filter a set of instruments based on a certain rule within a certain period assigned by fstart_time and fend_time. + + Parameters + ---------- + fstart_time: str + the time for the filter rule to start filter the instruments. + fend_time: str + the time for the filter rule to stop filter the instruments. + keep: bool + whether to keep the instruments of which features don't exist in the filter time span. + """ + super(SeriesDFilter, self).__init__() + self.filter_start_time = pd.Timestamp(fstart_time) if fstart_time else None + self.filter_end_time = pd.Timestamp(fend_time) if fend_time else None + self.keep = keep + + def _getTimeBound(self, instruments): + """Get time bound for all instruments. + + Parameters + ---------- + instruments: dict + the dict of instruments in the form {instrument_name => list of timestamp tuple}. + + Returns + ---------- + pd.Timestamp, pd.Timestamp + the lower time bound and upper time bound of all the instruments. + """ + trange = Cal.calendar(freq=self.filter_freq) + ubound, lbound = trange[0], trange[-1] + for _, timestamp in instruments.items(): + if timestamp: + lbound = timestamp[0][0] if timestamp[0][0] < lbound else lbound + ubound = timestamp[-1][-1] if timestamp[-1][-1] > ubound else ubound + return lbound, ubound + + def _toSeries(self, time_range, target_timestamp): + """Convert the target timestamp to a pandas series of bool value within a time range. + Make the time inside the target_timestamp range TRUE, others FALSE. + + Parameters + ---------- + time_range : D.calendar + the time range of the instruments. + target_timestamp : list + the list of tuple (timestamp, timestamp). + + Returns + ---------- + pd.Series + the series of bool value for an instrument. + """ + # Construct a whole dict of {date => bool} + timestamp_series = {timestamp: False for timestamp in time_range} + # Convert to pd.Series + timestamp_series = pd.Series(timestamp_series) + # Fill the date within target_timestamp with TRUE + for start, end in target_timestamp: + timestamp_series[Cal.calendar(start_time=start, end_time=end, freq=self.filter_freq)] = True + return timestamp_series + + def _filterSeries(self, timestamp_series, filter_series): + """Filter the timestamp series with filter series by using element-wise AND operation of the two series. + + Parameters + ---------- + timestamp_series : pd.Series + the series of bool value indicating existing time. + filter_series : pd.Series + the series of bool value indicating filter feature. + + Returns + ---------- + pd.Series + the series of bool value indicating whether the date satisfies the filter condition and exists in target timestamp. + """ + fstart, fend = list(filter_series.keys())[0], list(filter_series.keys())[-1] + filter_series = filter_series.astype("bool") # Make sure the filter_series is boolean + timestamp_series[fstart:fend] = timestamp_series[fstart:fend] & filter_series + return timestamp_series + + def _toTimestamp(self, timestamp_series): + """Convert the timestamp series to a list of tuple (timestamp, timestamp) indicating a continuous range of TRUE. + + Parameters + ---------- + timestamp_series: pd.Series + the series of bool value after being filtered. + + Returns + ---------- + list + the list of tuple (timestamp, timestamp). + """ + # sort the timestamp_series according to the timestamps + timestamp_series.sort_index() + timestamp = [] + _lbool = None + _ltime = None + _cur_start = None + for _ts, _bool in timestamp_series.items(): + # there is likely to be NAN when the filter series don't have the + # bool value, so we just change the NAN into False + if np.isnan(_bool): + _bool = False + if _lbool is None: + _cur_start = _ts + _lbool = _bool + _ltime = _ts + continue + if (_lbool, _bool) == (True, False): + if _cur_start: + timestamp.append((_cur_start, _ltime)) + elif (_lbool, _bool) == (False, True): + _cur_start = _ts + _lbool = _bool + _ltime = _ts + if _lbool: + timestamp.append((_cur_start, _ltime)) + return timestamp + + def __call__(self, instruments, start_time=None, end_time=None, freq="day"): + """Call this filter to get filtered instruments list""" + self.filter_freq = freq + return self.filter_main(instruments, start_time, end_time) + + @abstractmethod + def _getFilterSeries(self, instruments, fstart, fend): + """Get filter series based on the rules assigned during the initialization and the input time range. + + Parameters + ---------- + instruments : dict + the dict of instruments to be filtered. + fstart : pd.Timestamp + start time of filter. + fend : pd.Timestamp + end time of filter. + + .. note:: fstart/fend indicates the intersection of instruments start/end time and filter start/end time. + + Returns + ---------- + pd.Dataframe + a series of {pd.Timestamp => bool}. + """ + raise NotImplementedError("Subclass of SeriesDFilter must reimplement `getFilterSeries` method") + + def filter_main(self, instruments, start_time=None, end_time=None): + """Implement this method to filter the instruments. + + Parameters + ---------- + instruments: dict + input instruments to be filtered. + start_time: str + start of the time range. + end_time: str + end of the time range. + + Returns + ---------- + dict + filtered instruments, same structure as input instruments. + """ + lbound, ubound = self._getTimeBound(instruments) + start_time = pd.Timestamp(start_time or lbound) + end_time = pd.Timestamp(end_time or ubound) + _instruments_filtered = {} + _all_calendar = Cal.calendar(start_time=start_time, end_time=end_time, freq=self.filter_freq) + _filter_calendar = Cal.calendar( + start_time=self.filter_start_time and max(self.filter_start_time, _all_calendar[0]) or _all_calendar[0], + end_time=self.filter_end_time and min(self.filter_end_time, _all_calendar[-1]) or _all_calendar[-1], + freq=self.filter_freq, + ) + _all_filter_series = self._getFilterSeries(instruments, _filter_calendar[0], _filter_calendar[-1]) + for inst, timestamp in instruments.items(): + # Construct a whole map of date + _timestamp_series = self._toSeries(_all_calendar, timestamp) + # Get filter series + if inst in _all_filter_series: + _filter_series = _all_filter_series[inst] + else: + if self.keep: + _filter_series = pd.Series({timestamp: True for timestamp in _filter_calendar}) + else: + _filter_series = pd.Series({timestamp: False for timestamp in _filter_calendar}) + # Calculate bool value within the range of filter + _timestamp_series = self._filterSeries(_timestamp_series, _filter_series) + # Reform the map to (start_timestamp, end_timestamp) format + _timestamp = self._toTimestamp(_timestamp_series) + # Remove empty timestamp + if _timestamp: + _instruments_filtered[inst] = _timestamp + return _instruments_filtered + + +class NameDFilter(SeriesDFilter): + """Name dynamic instrument filter + + Filter the instruments based on a regulated name format. + + A name rule regular expression is required. + """ + + def __init__(self, name_rule_re, fstart_time=None, fend_time=None): + """Init function for name filter class + + Parameters + ---------- + name_rule_re: str + regular expression for the name rule. + """ + super(NameDFilter, self).__init__(fstart_time, fend_time) + self.name_rule_re = name_rule_re + + def _getFilterSeries(self, instruments, fstart, fend): + all_filter_series = {} + filter_calendar = Cal.calendar(start_time=fstart, end_time=fend, freq=self.filter_freq) + for inst, timestamp in instruments.items(): + if re.match(self.name_rule_re, inst): + _filter_series = pd.Series({timestamp: True for timestamp in filter_calendar}) + else: + _filter_series = pd.Series({timestamp: False for timestamp in filter_calendar}) + all_filter_series[inst] = _filter_series + return all_filter_series + + @staticmethod + def from_config(config): + return NameDFilter( + name_rule_re=config["name_rule_re"], + fstart_time=config["filter_start_time"], + fend_time=config["filter_end_time"], + ) + + def to_config(self): + return { + "filter_type": "NameDFilter", + "name_rule_re": self.name_rule_re, + "filter_start_time": str(self.filter_start_time) if self.filter_start_time else self.filter_start_time, + "filter_end_time": str(self.filter_end_time) if self.filter_end_time else self.filter_end_time, + } + + +class ExpressionDFilter(SeriesDFilter): + """Expression dynamic instrument filter + + Filter the instruments based on a certain expression. + + An expression rule indicating a certain feature field is required. + + Examples + ---------- + - *basic features filter* : rule_expression = '$close/$open>5' + - *cross-sectional features filter* : rule_expression = '$rank($close)<10' + - *time-sequence features filter* : rule_expression = '$Ref($close, 3)>100' + """ + + def __init__(self, rule_expression, fstart_time=None, fend_time=None, keep=False): + """Init function for expression filter class + + Parameters + ---------- + fstart_time: str + filter the feature starting from this time. + fend_time: str + filter the feature ending by this time. + rule_expression: str + an input expression for the rule. + """ + super(ExpressionDFilter, self).__init__(fstart_time, fend_time, keep=keep) + self.rule_expression = rule_expression + + def _getFilterSeries(self, instruments, fstart, fend): + # do not use dataset cache + try: + _features = DatasetD.dataset( + instruments, + [self.rule_expression], + fstart, + fend, + freq=self.filter_freq, + disk_cache=0, + ) + except TypeError: + # use LocalDatasetProvider + _features = DatasetD.dataset(instruments, [self.rule_expression], fstart, fend, freq=self.filter_freq) + rule_expression_field_name = list(_features.keys())[0] + all_filter_series = _features[rule_expression_field_name] + return all_filter_series + + @staticmethod + def from_config(config): + return ExpressionDFilter( + rule_expression=config["rule_expression"], + fstart_time=config["filter_start_time"], + fend_time=config["filter_end_time"], + keep=config["keep"], + ) + + def to_config(self): + return { + "filter_type": "ExpressionDFilter", + "rule_expression": self.rule_expression, + "filter_start_time": str(self.filter_start_time) if self.filter_start_time else self.filter_start_time, + "filter_end_time": str(self.filter_end_time) if self.filter_end_time else self.filter_end_time, + "keep": self.keep, + } diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/inst_processor.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/inst_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..e00132777d5fd81da920f8af8316a1d2aafa2afb --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/inst_processor.py @@ -0,0 +1,22 @@ +import abc +import json +import pandas as pd + + +class InstProcessor: + @abc.abstractmethod + def __call__(self, df: pd.DataFrame, instrument, *args, **kwargs): + """ + process the data + + NOTE: **The processor could change the content of `df` inplace !!!!! ** + User should keep a copy of data outside + + Parameters + ---------- + df : pd.DataFrame + The raw_df of handler or result from previous processor. + """ + + def __str__(self): + return f"{self.__class__.__name__}:{json.dumps(self.__dict__, sort_keys=True, default=str)}" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/ops.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a2ffbb3e31f552e115ba3bdc97a200e3866f46 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/ops.py @@ -0,0 +1,1681 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +from __future__ import division +from __future__ import print_function + +import numpy as np +import pandas as pd + +from typing import Union, List, Type +from scipy.stats import percentileofscore +from .base import Expression, ExpressionOps, Feature, PFeature +from ..log import get_module_logger +from ..utils import get_callable_kwargs + +try: + from ._libs.rolling import rolling_slope, rolling_rsquare, rolling_resi + from ._libs.expanding import expanding_slope, expanding_rsquare, expanding_resi +except ImportError: + print( + "#### Do not import qlib package in the repository directory in case of importing qlib from . without compiling #####" + ) + raise +except ValueError: + print("!!!!!!!! A error occurs when importing operators implemented based on Cython.!!!!!!!!") + print("!!!!!!!! They will be disabled. Please Upgrade your numpy to enable them !!!!!!!!") + # We catch this error because some platform can't upgrade there package (e.g. Kaggle) + # https://www.kaggle.com/general/293387 + # https://www.kaggle.com/product-feedback/98562 + + +np.seterr(invalid="ignore") + + +#################### Element-Wise Operator #################### +class ElemOperator(ExpressionOps): + """Element-wise Operator + + Parameters + ---------- + feature : Expression + feature instance + + Returns + ---------- + Expression + feature operation output + """ + + def __init__(self, feature): + self.feature = feature + + def __str__(self): + return "{}({})".format(type(self).__name__, self.feature) + + def get_longest_back_rolling(self): + return self.feature.get_longest_back_rolling() + + def get_extended_window_size(self): + return self.feature.get_extended_window_size() + + +class ChangeInstrument(ElemOperator): + """Change Instrument Operator + In some case, one may want to change to another instrument when calculating, for example, to + calculate beta of a stock with respect to a market index. + This would require changing the calculation of features from the stock (original instrument) to + the index (reference instrument) + Parameters + ---------- + instrument: new instrument for which the downstream operations should be performed upon. + i.e., SH000300 (CSI300 index), or ^GPSC (SP500 index). + + feature: the feature to be calculated for the new instrument. + Returns + ---------- + Expression + feature operation output + """ + + def __init__(self, instrument, feature): + self.instrument = instrument + self.feature = feature + + def __str__(self): + return "{}('{}',{})".format(type(self).__name__, self.instrument, self.feature) + + def load(self, instrument, start_index, end_index, *args): + # the first `instrument` is ignored + return super().load(self.instrument, start_index, end_index, *args) + + def _load_internal(self, instrument, start_index, end_index, *args): + return self.feature.load(instrument, start_index, end_index, *args) + + +class NpElemOperator(ElemOperator): + """Numpy Element-wise Operator + + Parameters + ---------- + feature : Expression + feature instance + func : str + numpy feature operation method + + Returns + ---------- + Expression + feature operation output + """ + + def __init__(self, feature, func): + self.func = func + super(NpElemOperator, self).__init__(feature) + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + return getattr(np, self.func)(series) + + +class Abs(NpElemOperator): + """Feature Absolute Value + + Parameters + ---------- + feature : Expression + feature instance + + Returns + ---------- + Expression + a feature instance with absolute output + """ + + def __init__(self, feature): + super(Abs, self).__init__(feature, "abs") + + +class Sign(NpElemOperator): + """Feature Sign + + Parameters + ---------- + feature : Expression + feature instance + + Returns + ---------- + Expression + a feature instance with sign + """ + + def __init__(self, feature): + super(Sign, self).__init__(feature, "sign") + + def _load_internal(self, instrument, start_index, end_index, *args): + """ + To avoid error raised by bool type input, we transform the data into float32. + """ + series = self.feature.load(instrument, start_index, end_index, *args) + # TODO: More precision types should be configurable + series = series.astype(np.float32) + return getattr(np, self.func)(series) + + +class Log(NpElemOperator): + """Feature Log + + Parameters + ---------- + feature : Expression + feature instance + + Returns + ---------- + Expression + a feature instance with log + """ + + def __init__(self, feature): + super(Log, self).__init__(feature, "log") + + +class Mask(NpElemOperator): + """Feature Mask + + Parameters + ---------- + feature : Expression + feature instance + instrument : str + instrument mask + + Returns + ---------- + Expression + a feature instance with masked instrument + """ + + def __init__(self, feature, instrument): + super(Mask, self).__init__(feature, "mask") + self.instrument = instrument + + def __str__(self): + return "{}({},{})".format(type(self).__name__, self.feature, self.instrument.lower()) + + def _load_internal(self, instrument, start_index, end_index, *args): + return self.feature.load(self.instrument, start_index, end_index, *args) + + +class Not(NpElemOperator): + """Not Operator + + Parameters + ---------- + feature : Expression + feature instance + + Returns + ---------- + Feature: + feature elementwise not output + """ + + def __init__(self, feature): + super(Not, self).__init__(feature, "bitwise_not") + + +#################### Pair-Wise Operator #################### +class PairOperator(ExpressionOps): + """Pair-wise operator + + Parameters + ---------- + feature_left : Expression + feature instance or numeric value + feature_right : Expression + feature instance or numeric value + + Returns + ---------- + Feature: + two features' operation output + """ + + def __init__(self, feature_left, feature_right): + self.feature_left = feature_left + self.feature_right = feature_right + + def __str__(self): + return "{}({},{})".format(type(self).__name__, self.feature_left, self.feature_right) + + def get_longest_back_rolling(self): + if isinstance(self.feature_left, (Expression,)): + left_br = self.feature_left.get_longest_back_rolling() + else: + left_br = 0 + + if isinstance(self.feature_right, (Expression,)): + right_br = self.feature_right.get_longest_back_rolling() + else: + right_br = 0 + return max(left_br, right_br) + + def get_extended_window_size(self): + if isinstance(self.feature_left, (Expression,)): + ll, lr = self.feature_left.get_extended_window_size() + else: + ll, lr = 0, 0 + + if isinstance(self.feature_right, (Expression,)): + rl, rr = self.feature_right.get_extended_window_size() + else: + rl, rr = 0, 0 + return max(ll, rl), max(lr, rr) + + +class NpPairOperator(PairOperator): + """Numpy Pair-wise operator + + Parameters + ---------- + feature_left : Expression + feature instance or numeric value + feature_right : Expression + feature instance or numeric value + func : str + operator function + + Returns + ---------- + Feature: + two features' operation output + """ + + def __init__(self, feature_left, feature_right, func): + self.func = func + super(NpPairOperator, self).__init__(feature_left, feature_right) + + def _load_internal(self, instrument, start_index, end_index, *args): + assert any( + [isinstance(self.feature_left, (Expression,)), self.feature_right, Expression] + ), "at least one of two inputs is Expression instance" + if isinstance(self.feature_left, (Expression,)): + series_left = self.feature_left.load(instrument, start_index, end_index, *args) + else: + series_left = self.feature_left # numeric value + if isinstance(self.feature_right, (Expression,)): + series_right = self.feature_right.load(instrument, start_index, end_index, *args) + else: + series_right = self.feature_right + check_length = isinstance(series_left, (np.ndarray, pd.Series)) and isinstance( + series_right, (np.ndarray, pd.Series) + ) + if check_length: + warning_info = ( + f"Loading {instrument}: {str(self)}; np.{self.func}(series_left, series_right), " + f"The length of series_left and series_right is different: ({len(series_left)}, {len(series_right)}), " + f"series_left is {str(self.feature_left)}, series_right is {str(self.feature_right)}. Please check the data" + ) + else: + warning_info = ( + f"Loading {instrument}: {str(self)}; np.{self.func}(series_left, series_right), " + f"series_left is {str(self.feature_left)}, series_right is {str(self.feature_right)}. Please check the data" + ) + try: + res = getattr(np, self.func)(series_left, series_right) + except ValueError as e: + get_module_logger("ops").debug(warning_info) + raise ValueError(f"{str(e)}. \n\t{warning_info}") from e + else: + if check_length and len(series_left) != len(series_right): + get_module_logger("ops").debug(warning_info) + return res + + +class Power(NpPairOperator): + """Power Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + The bases in feature_left raised to the exponents in feature_right + """ + + def __init__(self, feature_left, feature_right): + super(Power, self).__init__(feature_left, feature_right, "power") + + +class Add(NpPairOperator): + """Add Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + two features' sum + """ + + def __init__(self, feature_left, feature_right): + super(Add, self).__init__(feature_left, feature_right, "add") + + +class Sub(NpPairOperator): + """Subtract Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + two features' subtraction + """ + + def __init__(self, feature_left, feature_right): + super(Sub, self).__init__(feature_left, feature_right, "subtract") + + +class Mul(NpPairOperator): + """Multiply Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + two features' product + """ + + def __init__(self, feature_left, feature_right): + super(Mul, self).__init__(feature_left, feature_right, "multiply") + + +class Div(NpPairOperator): + """Division Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + two features' division + """ + + def __init__(self, feature_left, feature_right): + super(Div, self).__init__(feature_left, feature_right, "divide") + + +class Greater(NpPairOperator): + """Greater Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + greater elements taken from the input two features + """ + + def __init__(self, feature_left, feature_right): + super(Greater, self).__init__(feature_left, feature_right, "maximum") + + +class Less(NpPairOperator): + """Less Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + smaller elements taken from the input two features + """ + + def __init__(self, feature_left, feature_right): + super(Less, self).__init__(feature_left, feature_right, "minimum") + + +class Gt(NpPairOperator): + """Greater Than Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + bool series indicate `left > right` + """ + + def __init__(self, feature_left, feature_right): + super(Gt, self).__init__(feature_left, feature_right, "greater") + + +class Ge(NpPairOperator): + """Greater Equal Than Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + bool series indicate `left >= right` + """ + + def __init__(self, feature_left, feature_right): + super(Ge, self).__init__(feature_left, feature_right, "greater_equal") + + +class Lt(NpPairOperator): + """Less Than Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + bool series indicate `left < right` + """ + + def __init__(self, feature_left, feature_right): + super(Lt, self).__init__(feature_left, feature_right, "less") + + +class Le(NpPairOperator): + """Less Equal Than Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + bool series indicate `left <= right` + """ + + def __init__(self, feature_left, feature_right): + super(Le, self).__init__(feature_left, feature_right, "less_equal") + + +class Eq(NpPairOperator): + """Equal Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + bool series indicate `left == right` + """ + + def __init__(self, feature_left, feature_right): + super(Eq, self).__init__(feature_left, feature_right, "equal") + + +class Ne(NpPairOperator): + """Not Equal Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + bool series indicate `left != right` + """ + + def __init__(self, feature_left, feature_right): + super(Ne, self).__init__(feature_left, feature_right, "not_equal") + + +class And(NpPairOperator): + """And Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + two features' row by row & output + """ + + def __init__(self, feature_left, feature_right): + super(And, self).__init__(feature_left, feature_right, "bitwise_and") + + +class Or(NpPairOperator): + """Or Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + + Returns + ---------- + Feature: + two features' row by row | outputs + """ + + def __init__(self, feature_left, feature_right): + super(Or, self).__init__(feature_left, feature_right, "bitwise_or") + + +#################### Triple-wise Operator #################### +class If(ExpressionOps): + """If Operator + + Parameters + ---------- + condition : Expression + feature instance with bool values as condition + feature_left : Expression + feature instance + feature_right : Expression + feature instance + """ + + def __init__(self, condition, feature_left, feature_right): + self.condition = condition + self.feature_left = feature_left + self.feature_right = feature_right + + def __str__(self): + return "If({},{},{})".format(self.condition, self.feature_left, self.feature_right) + + def _load_internal(self, instrument, start_index, end_index, *args): + series_cond = self.condition.load(instrument, start_index, end_index, *args) + if isinstance(self.feature_left, (Expression,)): + series_left = self.feature_left.load(instrument, start_index, end_index, *args) + else: + series_left = self.feature_left + if isinstance(self.feature_right, (Expression,)): + series_right = self.feature_right.load(instrument, start_index, end_index, *args) + else: + series_right = self.feature_right + series = pd.Series(np.where(series_cond, series_left, series_right), index=series_cond.index) + return series + + def get_longest_back_rolling(self): + if isinstance(self.feature_left, (Expression,)): + left_br = self.feature_left.get_longest_back_rolling() + else: + left_br = 0 + + if isinstance(self.feature_right, (Expression,)): + right_br = self.feature_right.get_longest_back_rolling() + else: + right_br = 0 + + if isinstance(self.condition, (Expression,)): + c_br = self.condition.get_longest_back_rolling() + else: + c_br = 0 + return max(left_br, right_br, c_br) + + def get_extended_window_size(self): + if isinstance(self.feature_left, (Expression,)): + ll, lr = self.feature_left.get_extended_window_size() + else: + ll, lr = 0, 0 + + if isinstance(self.feature_right, (Expression,)): + rl, rr = self.feature_right.get_extended_window_size() + else: + rl, rr = 0, 0 + + if isinstance(self.condition, (Expression,)): + cl, cr = self.condition.get_extended_window_size() + else: + cl, cr = 0, 0 + return max(ll, rl, cl), max(lr, rr, cr) + + +#################### Rolling #################### +# NOTE: methods like `rolling.mean` are optimized with cython, +# and are super faster than `rolling.apply(np.mean)` + + +class Rolling(ExpressionOps): + """Rolling Operator + The meaning of rolling and expanding is the same in pandas. + When the window is set to 0, the behaviour of the operator should follow `expanding` + Otherwise, it follows `rolling` + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + func : str + rolling method + + Returns + ---------- + Expression + rolling outputs + """ + + def __init__(self, feature, N, func): + self.feature = feature + self.N = N + self.func = func + + def __str__(self): + return "{}({},{})".format(type(self).__name__, self.feature, self.N) + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + # NOTE: remove all null check, + # now it's user's responsibility to decide whether use features in null days + # isnull = series.isnull() # NOTE: isnull = NaN, inf is not null + if isinstance(self.N, int) and self.N == 0: + series = getattr(series.expanding(min_periods=1), self.func)() + elif isinstance(self.N, float) and 0 < self.N < 1: + series = series.ewm(alpha=self.N, min_periods=1).mean() + else: + series = getattr(series.rolling(self.N, min_periods=1), self.func)() + # series.iloc[:self.N-1] = np.nan + # series[isnull] = np.nan + return series + + def get_longest_back_rolling(self): + if self.N == 0: + return np.inf + if 0 < self.N < 1: + return int(np.log(1e-6) / np.log(1 - self.N)) # (1 - N)**window == 1e-6 + return self.feature.get_longest_back_rolling() + self.N - 1 + + def get_extended_window_size(self): + if self.N == 0: + # FIXME: How to make this accurate and efficiently? Or should we + # remove such support for N == 0? + get_module_logger(self.__class__.__name__).warning("The Rolling(ATTR, 0) will not be accurately calculated") + return self.feature.get_extended_window_size() + elif 0 < self.N < 1: + lft_etd, rght_etd = self.feature.get_extended_window_size() + size = int(np.log(1e-6) / np.log(1 - self.N)) + lft_etd = max(lft_etd + size - 1, lft_etd) + return lft_etd, rght_etd + else: + lft_etd, rght_etd = self.feature.get_extended_window_size() + lft_etd = max(lft_etd + self.N - 1, lft_etd) + return lft_etd, rght_etd + + +class Ref(Rolling): + """Feature Reference + + Parameters + ---------- + feature : Expression + feature instance + N : int + N = 0, retrieve the first data; N > 0, retrieve data of N periods ago; N < 0, future data + + Returns + ---------- + Expression + a feature instance with target reference + """ + + def __init__(self, feature, N): + super(Ref, self).__init__(feature, N, "ref") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + # N = 0, return first day + if series.empty: + return series # Pandas bug, see: https://github.com/pandas-dev/pandas/issues/21049 + elif self.N == 0: + series = pd.Series(series.iloc[0], index=series.index) + else: + series = series.shift(self.N) # copy + return series + + def get_longest_back_rolling(self): + if self.N == 0: + return np.inf + return self.feature.get_longest_back_rolling() + self.N + + def get_extended_window_size(self): + if self.N == 0: + get_module_logger(self.__class__.__name__).warning("The Ref(ATTR, 0) will not be accurately calculated") + return self.feature.get_extended_window_size() + else: + lft_etd, rght_etd = self.feature.get_extended_window_size() + lft_etd = max(lft_etd + self.N, lft_etd) + rght_etd = max(rght_etd - self.N, rght_etd) + return lft_etd, rght_etd + + +class Mean(Rolling): + """Rolling Mean (MA) + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling average + """ + + def __init__(self, feature, N): + super(Mean, self).__init__(feature, N, "mean") + + +class Sum(Rolling): + """Rolling Sum + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling sum + """ + + def __init__(self, feature, N): + super(Sum, self).__init__(feature, N, "sum") + + +class Std(Rolling): + """Rolling Std + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling std + """ + + def __init__(self, feature, N): + super(Std, self).__init__(feature, N, "std") + + +class Var(Rolling): + """Rolling Variance + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling variance + """ + + def __init__(self, feature, N): + super(Var, self).__init__(feature, N, "var") + + +class Skew(Rolling): + """Rolling Skewness + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling skewness + """ + + def __init__(self, feature, N): + if N != 0 and N < 3: + raise ValueError("The rolling window size of Skewness operation should >= 3") + super(Skew, self).__init__(feature, N, "skew") + + +class Kurt(Rolling): + """Rolling Kurtosis + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling kurtosis + """ + + def __init__(self, feature, N): + if N != 0 and N < 4: + raise ValueError("The rolling window size of Kurtosis operation should >= 5") + super(Kurt, self).__init__(feature, N, "kurt") + + +class Max(Rolling): + """Rolling Max + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling max + """ + + def __init__(self, feature, N): + super(Max, self).__init__(feature, N, "max") + + +class IdxMax(Rolling): + """Rolling Max Index + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling max index + """ + + def __init__(self, feature, N): + super(IdxMax, self).__init__(feature, N, "idxmax") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = series.expanding(min_periods=1).apply(lambda x: x.argmax() + 1, raw=True) + else: + series = series.rolling(self.N, min_periods=1).apply(lambda x: x.argmax() + 1, raw=True) + return series + + +class Min(Rolling): + """Rolling Min + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling min + """ + + def __init__(self, feature, N): + super(Min, self).__init__(feature, N, "min") + + +class IdxMin(Rolling): + """Rolling Min Index + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling min index + """ + + def __init__(self, feature, N): + super(IdxMin, self).__init__(feature, N, "idxmin") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = series.expanding(min_periods=1).apply(lambda x: x.argmin() + 1, raw=True) + else: + series = series.rolling(self.N, min_periods=1).apply(lambda x: x.argmin() + 1, raw=True) + return series + + +class Quantile(Rolling): + """Rolling Quantile + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling quantile + """ + + def __init__(self, feature, N, qscore): + super(Quantile, self).__init__(feature, N, "quantile") + self.qscore = qscore + + def __str__(self): + return "{}({},{},{})".format(type(self).__name__, self.feature, self.N, self.qscore) + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = series.expanding(min_periods=1).quantile(self.qscore) + else: + series = series.rolling(self.N, min_periods=1).quantile(self.qscore) + return series + + +class Med(Rolling): + """Rolling Median + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling median + """ + + def __init__(self, feature, N): + super(Med, self).__init__(feature, N, "median") + + +class Mad(Rolling): + """Rolling Mean Absolute Deviation + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling mean absolute deviation + """ + + def __init__(self, feature, N): + super(Mad, self).__init__(feature, N, "mad") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + # TODO: implement in Cython + + def mad(x): + x1 = x[~np.isnan(x)] + return np.mean(np.abs(x1 - x1.mean())) + + if self.N == 0: + series = series.expanding(min_periods=1).apply(mad, raw=True) + else: + series = series.rolling(self.N, min_periods=1).apply(mad, raw=True) + return series + + +class Rank(Rolling): + """Rolling Rank (Percentile) + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling rank + """ + + def __init__(self, feature, N): + super(Rank, self).__init__(feature, N, "rank") + + # for compatiblity of python 3.7, which doesn't support pandas 1.4.0+ which implements Rolling.rank + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + + rolling_or_expending = series.expanding(min_periods=1) if self.N == 0 else series.rolling(self.N, min_periods=1) + if hasattr(rolling_or_expending, "rank"): + return rolling_or_expending.rank(pct=True) + + def rank(x): + if np.isnan(x[-1]): + return np.nan + x1 = x[~np.isnan(x)] + if x1.shape[0] == 0: + return np.nan + return percentileofscore(x1, x1[-1]) / 100 + + return rolling_or_expending.apply(rank, raw=True) + + +class Count(Rolling): + """Rolling Count + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling count of number of non-NaN elements + """ + + def __init__(self, feature, N): + super(Count, self).__init__(feature, N, "count") + + +class Delta(Rolling): + """Rolling Delta + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with end minus start in rolling window + """ + + def __init__(self, feature, N): + super(Delta, self).__init__(feature, N, "delta") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = series - series.iloc[0] + else: + series = series - series.shift(self.N) + return series + + +# TODO: +# support pair-wise rolling like `Slope(A, B, N)` +class Slope(Rolling): + """Rolling Slope + This operator calculate the slope between `idx` and `feature`. + (e.g. [, , ] and [1, 2, 3]) + + Usage Example: + - "Slope($close, %d)/$close" + + # TODO: + # Some users may want pair-wise rolling like `Slope(A, B, N)` + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with linear regression slope of given window + """ + + def __init__(self, feature, N): + super(Slope, self).__init__(feature, N, "slope") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = pd.Series(expanding_slope(series.values), index=series.index) + else: + series = pd.Series(rolling_slope(series.values, self.N), index=series.index) + return series + + +class Rsquare(Rolling): + """Rolling R-value Square + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with linear regression r-value square of given window + """ + + def __init__(self, feature, N): + super(Rsquare, self).__init__(feature, N, "rsquare") + + def _load_internal(self, instrument, start_index, end_index, *args): + _series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = pd.Series(expanding_rsquare(_series.values), index=_series.index) + else: + series = pd.Series(rolling_rsquare(_series.values, self.N), index=_series.index) + series.loc[np.isclose(_series.rolling(self.N, min_periods=1).std(), 0, atol=2e-05)] = np.nan + return series + + +class Resi(Rolling): + """Rolling Regression Residuals + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with regression residuals of given window + """ + + def __init__(self, feature, N): + super(Resi, self).__init__(feature, N, "resi") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + if self.N == 0: + series = pd.Series(expanding_resi(series.values), index=series.index) + else: + series = pd.Series(rolling_resi(series.values, self.N), index=series.index) + return series + + +class WMA(Rolling): + """Rolling WMA + + Parameters + ---------- + feature : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with weighted moving average output + """ + + def __init__(self, feature, N): + super(WMA, self).__init__(feature, N, "wma") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + # TODO: implement in Cython + + def weighted_mean(x): + w = np.arange(len(x)) + 1 + w = w / w.sum() + return np.nanmean(w * x) + + if self.N == 0: + series = series.expanding(min_periods=1).apply(weighted_mean, raw=True) + else: + series = series.rolling(self.N, min_periods=1).apply(weighted_mean, raw=True) + return series + + +class EMA(Rolling): + """Rolling Exponential Mean (EMA) + + Parameters + ---------- + feature : Expression + feature instance + N : int, float + rolling window size + + Returns + ---------- + Expression + a feature instance with regression r-value square of given window + """ + + def __init__(self, feature, N): + super(EMA, self).__init__(feature, N, "ema") + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + + def exp_weighted_mean(x): + a = 1 - 2 / (1 + len(x)) + w = a ** np.arange(len(x))[::-1] + w /= w.sum() + return np.nansum(w * x) + + if self.N == 0: + series = series.expanding(min_periods=1).apply(exp_weighted_mean, raw=True) + elif 0 < self.N < 1: + series = series.ewm(alpha=self.N, min_periods=1).mean() + else: + series = series.ewm(span=self.N, min_periods=1).mean() + return series + + +#################### Pair-Wise Rolling #################### +class PairRolling(ExpressionOps): + """Pair Rolling Operator + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling output of two input features + """ + + def __init__(self, feature_left, feature_right, N, func): + # TODO: in what case will a const be passed into `__init__` as `feature_left` or `feature_right` + self.feature_left = feature_left + self.feature_right = feature_right + self.N = N + self.func = func + + def __str__(self): + return "{}({},{},{})".format(type(self).__name__, self.feature_left, self.feature_right, self.N) + + def _load_internal(self, instrument, start_index, end_index, *args): + assert any( + [isinstance(self.feature_left, Expression), self.feature_right, Expression] + ), "at least one of two inputs is Expression instance" + + if isinstance(self.feature_left, Expression): + series_left = self.feature_left.load(instrument, start_index, end_index, *args) + else: + series_left = self.feature_left # numeric value + if isinstance(self.feature_right, Expression): + series_right = self.feature_right.load(instrument, start_index, end_index, *args) + else: + series_right = self.feature_right + + if self.N == 0: + series = getattr(series_left.expanding(min_periods=1), self.func)(series_right) + else: + series = getattr(series_left.rolling(self.N, min_periods=1), self.func)(series_right) + return series + + def get_longest_back_rolling(self): + if self.N == 0: + return np.inf + if isinstance(self.feature_left, Expression): + left_br = self.feature_left.get_longest_back_rolling() + else: + left_br = 0 + + if isinstance(self.feature_right, Expression): + right_br = self.feature_right.get_longest_back_rolling() + else: + right_br = 0 + return max(left_br, right_br) + + def get_extended_window_size(self): + if isinstance(self.feature_left, Expression): + ll, lr = self.feature_left.get_extended_window_size() + else: + ll, lr = 0, 0 + if isinstance(self.feature_right, Expression): + rl, rr = self.feature_right.get_extended_window_size() + else: + rl, rr = 0, 0 + if self.N == 0: + get_module_logger(self.__class__.__name__).warning( + "The PairRolling(ATTR, 0) will not be accurately calculated" + ) + return -np.inf, max(lr, rr) + else: + return max(ll, rl) + self.N - 1, max(lr, rr) + + +class Corr(PairRolling): + """Rolling Correlation + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling correlation of two input features + """ + + def __init__(self, feature_left, feature_right, N): + super(Corr, self).__init__(feature_left, feature_right, N, "corr") + + def _load_internal(self, instrument, start_index, end_index, *args): + res: pd.Series = super(Corr, self)._load_internal(instrument, start_index, end_index, *args) + + # NOTE: Load uses MemCache, so calling load again will not cause performance degradation + series_left = self.feature_left.load(instrument, start_index, end_index, *args) + series_right = self.feature_right.load(instrument, start_index, end_index, *args) + res.loc[ + np.isclose(series_left.rolling(self.N, min_periods=1).std(), 0, atol=2e-05) + | np.isclose(series_right.rolling(self.N, min_periods=1).std(), 0, atol=2e-05) + ] = np.nan + return res + + +class Cov(PairRolling): + """Rolling Covariance + + Parameters + ---------- + feature_left : Expression + feature instance + feature_right : Expression + feature instance + N : int + rolling window size + + Returns + ---------- + Expression + a feature instance with rolling max of two input features + """ + + def __init__(self, feature_left, feature_right, N): + super(Cov, self).__init__(feature_left, feature_right, N, "cov") + + +#################### Operator which only support data with time index #################### +# Convention +# - The name of the operators in this section will start with "T" + + +class TResample(ElemOperator): + def __init__(self, feature, freq, func): + """ + Resampling the data to target frequency. + The resample function of pandas is used. + + - the timestamp will be at the start of the time span after resample. + + Parameters + ---------- + feature : Expression + An expression for calculating the feature + freq : str + It will be passed into the resample method for resampling basedn on given frequency + func : method + The method to get the resampled values + Some expression are high frequently used + """ + self.feature = feature + self.freq = freq + self.func = func + + def __str__(self): + return "{}({},{})".format(type(self).__name__, self.feature, self.freq) + + def _load_internal(self, instrument, start_index, end_index, *args): + series = self.feature.load(instrument, start_index, end_index, *args) + + if series.empty: + return series + else: + if self.func == "sum": + return getattr(series.resample(self.freq), self.func)(min_count=1) + else: + return getattr(series.resample(self.freq), self.func)() + + +TOpsList = [TResample] +OpsList = [ + ChangeInstrument, + Rolling, + Ref, + Max, + Min, + Sum, + Mean, + Std, + Var, + Skew, + Kurt, + Med, + Mad, + Slope, + Rsquare, + Resi, + Rank, + Quantile, + Count, + EMA, + WMA, + Corr, + Cov, + Delta, + Abs, + Sign, + Log, + Power, + Add, + Sub, + Mul, + Div, + Greater, + Less, + And, + Or, + Not, + Gt, + Ge, + Lt, + Le, + Eq, + Ne, + Mask, + IdxMax, + IdxMin, + If, + Feature, + PFeature, +] + [TResample] + + +class OpsWrapper: + """Ops Wrapper""" + + def __init__(self): + self._ops = {} + + def reset(self): + self._ops = {} + + def register(self, ops_list: List[Union[Type[ExpressionOps], dict]]): + """register operator + + Parameters + ---------- + ops_list : List[Union[Type[ExpressionOps], dict]] + - if type(ops_list) is List[Type[ExpressionOps]], each element of ops_list represents the operator class, which should be the subclass of `ExpressionOps`. + - if type(ops_list) is List[dict], each element of ops_list represents the config of operator, which has the following format: + + .. code-block:: text + + { + "class": class_name, + "module_path": path, + } + + Note: `class` should be the class name of operator, `module_path` should be a python module or path of file. + """ + for _operator in ops_list: + if isinstance(_operator, dict): + _ops_class, _ = get_callable_kwargs(_operator) + else: + _ops_class = _operator + + if not issubclass(_ops_class, (Expression,)): + raise TypeError("operator must be subclass of ExpressionOps, not {}".format(_ops_class)) + + if _ops_class.__name__ in self._ops: + get_module_logger(self.__class__.__name__).warning( + "The custom operator [{}] will override the qlib default definition".format(_ops_class.__name__) + ) + self._ops[_ops_class.__name__] = _ops_class + + def __getattr__(self, key): + if key not in self._ops: + raise AttributeError("The operator [{0}] is not registered".format(key)) + return self._ops[key] + + +Operators = OpsWrapper() + + +def register_all_ops(C): + """register all operator""" + logger = get_module_logger("ops") + + from qlib.data.pit import P, PRef # pylint: disable=C0415 + + Operators.reset() + Operators.register(OpsList + [P, PRef]) + + if getattr(C, "custom_ops", None) is not None: + Operators.register(C.custom_ops) + logger.debug("register custom operator {}".format(C.custom_ops)) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/pit.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/pit.py new file mode 100644 index 0000000000000000000000000000000000000000..740fd7b19a4a7d16ce34233d730cdace25e812c1 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/pit.py @@ -0,0 +1,72 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Qlib follow the logic below to supporting point-in-time database + +For each stock, the format of its data is . Expression Engine support calculation on such format of data + +To calculate the feature value f_t at a specific observe time t, data with format will be used. +For example, the average earning of last 4 quarters (period_time) on 20190719 (observe_time) + +The calculation of both and data rely on expression engine. It consists of 2 phases. +1) calculation at each observation time t and it will collasped into a point (just like a normal feature) +2) concatenate all th collasped data, we will get data with format . +Qlib will use the operator `P` to perform the collapse. +""" + +import numpy as np +import pandas as pd +from qlib.data.ops import ElemOperator +from qlib.log import get_module_logger +from .data import Cal + + +class P(ElemOperator): + def _load_internal(self, instrument, start_index, end_index, freq): + _calendar = Cal.calendar(freq=freq) + resample_data = np.empty(end_index - start_index + 1, dtype="float32") + + for cur_index in range(start_index, end_index + 1): + cur_time = _calendar[cur_index] + # To load expression accurately, more historical data are required + start_ws, end_ws = self.feature.get_extended_window_size() + if end_ws > 0: + raise ValueError( + "PIT database does not support referring to future period (e.g. expressions like `Ref('$$roewa_q', -1)` are not supported" + ) + + # The calculated value will always the last element, so the end_offset is zero. + try: + s = self._load_feature(instrument, -start_ws, 0, cur_time) + resample_data[cur_index - start_index] = s.iloc[-1] if len(s) > 0 else np.nan + except FileNotFoundError: + get_module_logger("base").warning(f"WARN: period data not found for {str(self)}") + return pd.Series(dtype="float32", name=str(self)) + + resample_series = pd.Series( + resample_data, index=pd.RangeIndex(start_index, end_index + 1), dtype="float32", name=str(self) + ) + return resample_series + + def _load_feature(self, instrument, start_index, end_index, cur_time): + return self.feature.load(instrument, start_index, end_index, cur_time) + + def get_longest_back_rolling(self): + # The period data will collapse as a normal feature. So no extending and looking back + return 0 + + def get_extended_window_size(self): + # The period data will collapse as a normal feature. So no extending and looking back + return 0, 0 + + +class PRef(P): + def __init__(self, feature, period): + super().__init__(feature) + self.period = period + + def __str__(self): + return f"{super().__str__()}[{self.period}]" + + def _load_feature(self, instrument, start_index, end_index, cur_time): + return self.feature.load(instrument, start_index, end_index, cur_time, self.period) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26dd6d624e5852612db7ebc8489b8b66c0f6bc80 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/__init__.py @@ -0,0 +1,6 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from .storage import CalendarStorage, InstrumentStorage, FeatureStorage, CalVT, InstVT, InstKT + +__all__ = ["CalendarStorage", "InstrumentStorage", "FeatureStorage", "CalVT", "InstVT", "InstKT"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/file_storage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/file_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..8a100a2d19e8c1037fc49d636ec75327e374c285 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/file_storage.py @@ -0,0 +1,379 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import struct +from pathlib import Path +from typing import Iterable, Union, Dict, Mapping, Tuple, List + +import numpy as np +import pandas as pd + +from qlib.utils.time import Freq +from qlib.utils.resam import resam_calendar +from qlib.config import C +from qlib.data.cache import H +from qlib.log import get_module_logger +from qlib.data.storage import CalendarStorage, InstrumentStorage, FeatureStorage, CalVT, InstKT, InstVT + +logger = get_module_logger("file_storage") + + +class FileStorageMixin: + """FileStorageMixin, applicable to FileXXXStorage + Subclasses need to have provider_uri, freq, storage_name, file_name attributes + + """ + + # NOTE: provider_uri priority: + # 1. self._provider_uri : if provider_uri is provided. + # 2. provider_uri in qlib.config.C + + @property + def provider_uri(self): + return C["provider_uri"] if getattr(self, "_provider_uri", None) is None else self._provider_uri + + @property + def dpm(self): + return ( + C.dpm + if getattr(self, "_provider_uri", None) is None + else C.DataPathManager(self._provider_uri, C.mount_path) + ) + + @property + def support_freq(self) -> List[str]: + _v = "_support_freq" + if hasattr(self, _v): + return getattr(self, _v) + if len(self.provider_uri) == 1 and C.DEFAULT_FREQ in self.provider_uri: + freq_l = filter( + lambda _freq: not _freq.endswith("_future"), + map(lambda x: x.stem, self.dpm.get_data_uri(C.DEFAULT_FREQ).joinpath("calendars").glob("*.txt")), + ) + else: + freq_l = self.provider_uri.keys() + freq_l = [Freq(freq) for freq in freq_l] + setattr(self, _v, freq_l) + return freq_l + + @property + def uri(self) -> Path: + if self.freq not in self.support_freq: + raise ValueError(f"{self.storage_name}: {self.provider_uri} does not contain data for {self.freq}") + return self.dpm.get_data_uri(self.freq).joinpath(f"{self.storage_name}s", self.file_name) + + def check(self): + """check self.uri + + Raises + ------- + ValueError + """ + if not self.uri.exists(): + raise ValueError(f"{self.storage_name} not exists: {self.uri}") + + +class FileCalendarStorage(FileStorageMixin, CalendarStorage): + def __init__(self, freq: str, future: bool, provider_uri: dict = None, **kwargs): + super(FileCalendarStorage, self).__init__(freq, future, **kwargs) + self.future = future + self._provider_uri = None if provider_uri is None else C.DataPathManager.format_provider_uri(provider_uri) + self.enable_read_cache = True # TODO: make it configurable + self.region = C["region"] + + @property + def file_name(self) -> str: + return f"{self._freq_file}_future.txt" if self.future else f"{self._freq_file}.txt".lower() + + @property + def _freq_file(self) -> str: + """the freq to read from file""" + if not hasattr(self, "_freq_file_cache"): + freq = Freq(self.freq) + if freq not in self.support_freq: + # NOTE: uri + # 1. If `uri` does not exist + # - Get the `min_uri` of the closest `freq` under the same "directory" as the `uri` + # - Read data from `min_uri` and resample to `freq` + + freq = Freq.get_recent_freq(freq, self.support_freq) + if freq is None: + raise ValueError(f"can't find a freq from {self.support_freq} that can resample to {self.freq}!") + self._freq_file_cache = freq + return self._freq_file_cache + + def _read_calendar(self) -> List[CalVT]: + # NOTE: + # if we want to accelerate partial reading calendar + # we can add parameters like `skip_rows: int = 0, n_rows: int = None` to the interface. + # Currently, it is not supported for the txt-based calendar + + if not self.uri.exists(): + self._write_calendar(values=[]) + + with self.uri.open("r") as fp: + res = [] + for line in fp.readlines(): + line = line.strip() + if len(line) > 0: + res.append(line) + return res + + def _write_calendar(self, values: Iterable[CalVT], mode: str = "wb"): + with self.uri.open(mode=mode) as fp: + np.savetxt(fp, values, fmt="%s", encoding="utf-8") + + @property + def uri(self) -> Path: + return self.dpm.get_data_uri(self._freq_file).joinpath(f"{self.storage_name}s", self.file_name) + + @property + def data(self) -> List[CalVT]: + self.check() + # If cache is enabled, then return cache directly + if self.enable_read_cache: + key = "orig_file" + str(self.uri) + if key not in H["c"]: + H["c"][key] = self._read_calendar() + _calendar = H["c"][key] + else: + _calendar = self._read_calendar() + if Freq(self._freq_file) != Freq(self.freq): + _calendar = resam_calendar( + np.array(list(map(pd.Timestamp, _calendar))), self._freq_file, self.freq, self.region + ) + return _calendar + + def _get_storage_freq(self) -> List[str]: + return sorted(set(map(lambda x: x.stem.split("_")[0], self.uri.parent.glob("*.txt")))) + + def extend(self, values: Iterable[CalVT]) -> None: + self._write_calendar(values, mode="ab") + + def clear(self) -> None: + self._write_calendar(values=[]) + + def index(self, value: CalVT) -> int: + self.check() + calendar = self._read_calendar() + return int(np.argwhere(calendar == value)[0]) + + def insert(self, index: int, value: CalVT): + calendar = self._read_calendar() + calendar = np.insert(calendar, index, value) + self._write_calendar(values=calendar) + + def remove(self, value: CalVT) -> None: + self.check() + index = self.index(value) + calendar = self._read_calendar() + calendar = np.delete(calendar, index) + self._write_calendar(values=calendar) + + def __setitem__(self, i: Union[int, slice], values: Union[CalVT, Iterable[CalVT]]) -> None: + calendar = self._read_calendar() + calendar[i] = values + self._write_calendar(values=calendar) + + def __delitem__(self, i: Union[int, slice]) -> None: + self.check() + calendar = self._read_calendar() + calendar = np.delete(calendar, i) + self._write_calendar(values=calendar) + + def __getitem__(self, i: Union[int, slice]) -> Union[CalVT, List[CalVT]]: + self.check() + return self._read_calendar()[i] + + def __len__(self) -> int: + return len(self.data) + + +class FileInstrumentStorage(FileStorageMixin, InstrumentStorage): + INSTRUMENT_SEP = "\t" + INSTRUMENT_START_FIELD = "start_datetime" + INSTRUMENT_END_FIELD = "end_datetime" + SYMBOL_FIELD_NAME = "instrument" + + def __init__(self, market: str, freq: str, provider_uri: dict = None, **kwargs): + super(FileInstrumentStorage, self).__init__(market, freq, **kwargs) + self._provider_uri = None if provider_uri is None else C.DataPathManager.format_provider_uri(provider_uri) + self.file_name = f"{market.lower()}.txt" + + def _read_instrument(self) -> Dict[InstKT, InstVT]: + if not self.uri.exists(): + self._write_instrument() + + _instruments = dict() + df = pd.read_csv( + self.uri, + sep="\t", + usecols=[0, 1, 2], + names=[self.SYMBOL_FIELD_NAME, self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD], + dtype={self.SYMBOL_FIELD_NAME: str}, + parse_dates=[self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD], + ) + for row in df.itertuples(index=False): + _instruments.setdefault(row[0], []).append((row[1], row[2])) + return _instruments + + def _write_instrument(self, data: Dict[InstKT, InstVT] = None) -> None: + if not data: + with self.uri.open("w") as _: + pass + return + + res = [] + for inst, v_list in data.items(): + _df = pd.DataFrame(v_list, columns=[self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD]) + _df[self.SYMBOL_FIELD_NAME] = inst + res.append(_df) + + df = pd.concat(res, sort=False) + df.loc[:, [self.SYMBOL_FIELD_NAME, self.INSTRUMENT_START_FIELD, self.INSTRUMENT_END_FIELD]].to_csv( + self.uri, header=False, sep=self.INSTRUMENT_SEP, index=False + ) + df.to_csv(self.uri, sep="\t", encoding="utf-8", header=False, index=False) + + def clear(self) -> None: + self._write_instrument(data={}) + + @property + def data(self) -> Dict[InstKT, InstVT]: + self.check() + return self._read_instrument() + + def __setitem__(self, k: InstKT, v: InstVT) -> None: + inst = self._read_instrument() + inst[k] = v + self._write_instrument(inst) + + def __delitem__(self, k: InstKT) -> None: + self.check() + inst = self._read_instrument() + del inst[k] + self._write_instrument(inst) + + def __getitem__(self, k: InstKT) -> InstVT: + self.check() + return self._read_instrument()[k] + + def update(self, *args, **kwargs) -> None: + if len(args) > 1: + raise TypeError(f"update expected at most 1 arguments, got {len(args)}") + inst = self._read_instrument() + if args: + other = args[0] # type: dict + if isinstance(other, Mapping): + for key in other: + inst[key] = other[key] + elif hasattr(other, "keys"): + for key in other.keys(): + inst[key] = other[key] + else: + for key, value in other: + inst[key] = value + for key, value in kwargs.items(): + inst[key] = value + + self._write_instrument(inst) + + def __len__(self) -> int: + return len(self.data) + + +class FileFeatureStorage(FileStorageMixin, FeatureStorage): + def __init__(self, instrument: str, field: str, freq: str, provider_uri: dict = None, **kwargs): + super(FileFeatureStorage, self).__init__(instrument, field, freq, **kwargs) + self._provider_uri = None if provider_uri is None else C.DataPathManager.format_provider_uri(provider_uri) + self.file_name = f"{instrument.lower()}/{field.lower()}.{freq.lower()}.bin" + + def clear(self): + with self.uri.open("wb") as _: + pass + + @property + def data(self) -> pd.Series: + return self[:] + + def write(self, data_array: Union[List, np.ndarray], index: int = None) -> None: + if len(data_array) == 0: + logger.info( + "len(data_array) == 0, write" + "if you need to clear the FeatureStorage, please execute: FeatureStorage.clear" + ) + return + if not self.uri.exists(): + # write + index = 0 if index is None else index + with self.uri.open("wb") as fp: + np.hstack([index, data_array]).astype(" self.end_index: + # append + index = 0 if index is None else index + with self.uri.open("ab+") as fp: + np.hstack([[np.nan] * (index - self.end_index - 1), data_array]).astype(" Union[int, None]: + if not self.uri.exists(): + return None + with self.uri.open("rb") as fp: + index = int(np.frombuffer(fp.read(4), dtype=" Union[int, None]: + if not self.uri.exists(): + return None + # The next data appending index point will be `end_index + 1` + return self.start_index + len(self) - 1 + + def __getitem__(self, i: Union[int, slice]) -> Union[Tuple[int, float], pd.Series]: + if not self.uri.exists(): + if isinstance(i, int): + return None, None + elif isinstance(i, slice): + return pd.Series(dtype=np.float32) + else: + raise TypeError(f"type(i) = {type(i)}") + + storage_start_index = self.start_index + storage_end_index = self.end_index + with self.uri.open("rb") as fp: + if isinstance(i, int): + if storage_start_index > i: + raise IndexError(f"{i}: start index is {storage_start_index}") + fp.seek(4 * (i - storage_start_index) + 4) + return i, struct.unpack("f", fp.read(4))[0] + elif isinstance(i, slice): + start_index = storage_start_index if i.start is None else i.start + end_index = storage_end_index if i.stop is None else i.stop - 1 + si = max(start_index, storage_start_index) + if si > end_index: + return pd.Series(dtype=np.float32) + fp.seek(4 * (si - storage_start_index) + 4) + # read n bytes + count = end_index - si + 1 + data = np.frombuffer(fp.read(4 * count), dtype=" int: + self.check() + return self.uri.stat().st_size // 4 - 1 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/storage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb7da1de664d167d223672a4eb0a5c6bf86af3b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/data/storage/storage.py @@ -0,0 +1,494 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import re +from typing import Iterable, overload, Tuple, List, Text, Union, Dict + +import numpy as np +import pandas as pd +from qlib.log import get_module_logger + +# calendar value type +CalVT = str + +# instrument value +InstVT = List[Tuple[CalVT, CalVT]] +# instrument key +InstKT = Text + +logger = get_module_logger("storage") + +""" +If the user is only using it in `qlib`, you can customize Storage to implement only the following methods: + +class UserCalendarStorage(CalendarStorage): + + @property + def data(self) -> Iterable[CalVT]: + '''get all data + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + ''' + raise NotImplementedError("Subclass of CalendarStorage must implement `data` method") + + +class UserInstrumentStorage(InstrumentStorage): + + @property + def data(self) -> Dict[InstKT, InstVT]: + '''get all data + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + ''' + raise NotImplementedError("Subclass of InstrumentStorage must implement `data` method") + + +class UserFeatureStorage(FeatureStorage): + + def __getitem__(self, s: slice) -> pd.Series: + '''x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step] + + Returns + ------- + pd.Series(values, index=pd.RangeIndex(start, len(values)) + + Notes + ------- + if data(storage) does not exist: + if isinstance(i, int): + return (None, None) + if isinstance(i, slice): + # return empty pd.Series + return pd.Series(dtype=np.float32) + ''' + raise NotImplementedError( + "Subclass of FeatureStorage must implement `__getitem__(s: slice)` method" + ) + + +""" + + +class BaseStorage: + @property + def storage_name(self) -> str: + return re.findall("[A-Z][^A-Z]*", self.__class__.__name__)[-2].lower() + + +class CalendarStorage(BaseStorage): + """ + The behavior of CalendarStorage's methods and List's methods of the same name remain consistent + """ + + def __init__(self, freq: str, future: bool, **kwargs): + self.freq = freq + self.future = future + self.kwargs = kwargs + + @property + def data(self) -> Iterable[CalVT]: + """get all data + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + """ + raise NotImplementedError("Subclass of CalendarStorage must implement `data` method") + + def clear(self) -> None: + raise NotImplementedError("Subclass of CalendarStorage must implement `clear` method") + + def extend(self, iterable: Iterable[CalVT]) -> None: + raise NotImplementedError("Subclass of CalendarStorage must implement `extend` method") + + def index(self, value: CalVT) -> int: + """ + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + """ + raise NotImplementedError("Subclass of CalendarStorage must implement `index` method") + + def insert(self, index: int, value: CalVT) -> None: + raise NotImplementedError("Subclass of CalendarStorage must implement `insert` method") + + def remove(self, value: CalVT) -> None: + raise NotImplementedError("Subclass of CalendarStorage must implement `remove` method") + + @overload + def __setitem__(self, i: int, value: CalVT) -> None: + """x.__setitem__(i, o) <==> (x[i] = o)""" + + @overload + def __setitem__(self, s: slice, value: Iterable[CalVT]) -> None: + """x.__setitem__(s, o) <==> (x[s] = o)""" + + def __setitem__(self, i, value) -> None: + raise NotImplementedError( + "Subclass of CalendarStorage must implement `__setitem__(i: int, o: CalVT)`/`__setitem__(s: slice, o: Iterable[CalVT])` method" + ) + + @overload + def __delitem__(self, i: int) -> None: + """x.__delitem__(i) <==> del x[i]""" + + @overload + def __delitem__(self, i: slice) -> None: + """x.__delitem__(slice(start: int, stop: int, step: int)) <==> del x[start:stop:step]""" + + def __delitem__(self, i) -> None: + """ + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + """ + raise NotImplementedError( + "Subclass of CalendarStorage must implement `__delitem__(i: int)`/`__delitem__(s: slice)` method" + ) + + @overload + def __getitem__(self, s: slice) -> Iterable[CalVT]: + """x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step]""" + + @overload + def __getitem__(self, i: int) -> CalVT: + """x.__getitem__(i) <==> x[i]""" + + def __getitem__(self, i) -> CalVT: + """ + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + + """ + raise NotImplementedError( + "Subclass of CalendarStorage must implement `__getitem__(i: int)`/`__getitem__(s: slice)` method" + ) + + def __len__(self) -> int: + """ + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + + """ + raise NotImplementedError("Subclass of CalendarStorage must implement `__len__` method") + + +class InstrumentStorage(BaseStorage): + def __init__(self, market: str, freq: str, **kwargs): + self.market = market + self.freq = freq + self.kwargs = kwargs + + @property + def data(self) -> Dict[InstKT, InstVT]: + """get all data + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + """ + raise NotImplementedError("Subclass of InstrumentStorage must implement `data` method") + + def clear(self) -> None: + raise NotImplementedError("Subclass of InstrumentStorage must implement `clear` method") + + def update(self, *args, **kwargs) -> None: + """D.update([E, ]**F) -> None. Update D from mapping/iterable E and F. + + Notes + ------ + If E present and has a .keys() method, does: for k in E: D[k] = E[k] + + If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v + + In either case, this is followed by: for k, v in F.items(): D[k] = v + + """ + raise NotImplementedError("Subclass of InstrumentStorage must implement `update` method") + + def __setitem__(self, k: InstKT, v: InstVT) -> None: + """Set self[key] to value.""" + raise NotImplementedError("Subclass of InstrumentStorage must implement `__setitem__` method") + + def __delitem__(self, k: InstKT) -> None: + """Delete self[key]. + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + """ + raise NotImplementedError("Subclass of InstrumentStorage must implement `__delitem__` method") + + def __getitem__(self, k: InstKT) -> InstVT: + """x.__getitem__(k) <==> x[k]""" + raise NotImplementedError("Subclass of InstrumentStorage must implement `__getitem__` method") + + def __len__(self) -> int: + """ + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + + """ + raise NotImplementedError("Subclass of InstrumentStorage must implement `__len__` method") + + +class FeatureStorage(BaseStorage): + def __init__(self, instrument: str, field: str, freq: str, **kwargs): + self.instrument = instrument + self.field = field + self.freq = freq + self.kwargs = kwargs + + @property + def data(self) -> pd.Series: + """get all data + + Notes + ------ + if data(storage) does not exist, return empty pd.Series: `return pd.Series(dtype=np.float32)` + """ + raise NotImplementedError("Subclass of FeatureStorage must implement `data` method") + + @property + def start_index(self) -> Union[int, None]: + """get FeatureStorage start index + + Notes + ----- + If the data(storage) does not exist, return None + """ + raise NotImplementedError("Subclass of FeatureStorage must implement `start_index` method") + + @property + def end_index(self) -> Union[int, None]: + """get FeatureStorage end index + + Notes + ----- + The right index of the data range (both sides are closed) + + The next data appending point will be `end_index + 1` + + If the data(storage) does not exist, return None + """ + raise NotImplementedError("Subclass of FeatureStorage must implement `end_index` method") + + def clear(self) -> None: + raise NotImplementedError("Subclass of FeatureStorage must implement `clear` method") + + def write(self, data_array: Union[List, np.ndarray, Tuple], index: int = None): + """Write data_array to FeatureStorage starting from index. + + Notes + ------ + If index is None, append data_array to feature. + + If len(data_array) == 0; return + + If (index - self.end_index) >= 1, self[end_index+1: index] will be filled with np.nan + + Examples + --------- + .. code-block:: + + feature: + 3 4 + 4 5 + 5 6 + + + >>> self.write([6, 7], index=6) + + feature: + 3 4 + 4 5 + 5 6 + 6 6 + 7 7 + + >>> self.write([8], index=9) + + feature: + 3 4 + 4 5 + 5 6 + 6 6 + 7 7 + 8 np.nan + 9 8 + + >>> self.write([1, np.nan], index=3) + + feature: + 3 1 + 4 np.nan + 5 6 + 6 6 + 7 7 + 8 np.nan + 9 8 + + """ + raise NotImplementedError("Subclass of FeatureStorage must implement `write` method") + + def rebase(self, start_index: int = None, end_index: int = None): + """Rebase the start_index and end_index of the FeatureStorage. + + start_index and end_index are closed intervals: [start_index, end_index] + + Examples + --------- + + .. code-block:: + + feature: + 3 4 + 4 5 + 5 6 + + + >>> self.rebase(start_index=4) + + feature: + 4 5 + 5 6 + + >>> self.rebase(start_index=3) + + feature: + 3 np.nan + 4 5 + 5 6 + + >>> self.write([3], index=3) + + feature: + 3 3 + 4 5 + 5 6 + + >>> self.rebase(end_index=4) + + feature: + 3 3 + 4 5 + + >>> self.write([6, 7, 8], index=4) + + feature: + 3 3 + 4 6 + 5 7 + 6 8 + + >>> self.rebase(start_index=4, end_index=5) + + feature: + 4 6 + 5 7 + + """ + storage_si = self.start_index + storage_ei = self.end_index + if storage_si is None or storage_ei is None: + raise ValueError("storage.start_index or storage.end_index is None, storage may not exist") + + start_index = storage_si if start_index is None else start_index + end_index = storage_ei if end_index is None else end_index + + if start_index is None or end_index is None: + logger.warning("both start_index and end_index are None, or storage does not exist; rebase is ignored") + return + + if start_index < 0 or end_index < 0: + logger.warning("start_index or end_index cannot be less than 0") + return + if start_index > end_index: + logger.warning( + f"start_index({start_index}) > end_index({end_index}), rebase is ignored; " + f"if you need to clear the FeatureStorage, please execute: FeatureStorage.clear" + ) + return + + if start_index <= storage_si: + self.write([np.nan] * (storage_si - start_index), start_index) + else: + self.rewrite(self[start_index:].values, start_index) + + if end_index >= self.end_index: + self.write([np.nan] * (end_index - self.end_index)) + else: + self.rewrite(self[: end_index + 1].values, start_index) + + def rewrite(self, data: Union[List, np.ndarray, Tuple], index: int): + """overwrite all data in FeatureStorage with data + + Parameters + ---------- + data: Union[List, np.ndarray, Tuple] + data + index: int + data start index + """ + self.clear() + self.write(data, index) + + @overload + def __getitem__(self, s: slice) -> pd.Series: + """x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step] + + Returns + ------- + pd.Series(values, index=pd.RangeIndex(start, len(values)) + """ + + @overload + def __getitem__(self, i: int) -> Tuple[int, float]: + """x.__getitem__(y) <==> x[y]""" + + def __getitem__(self, i) -> Union[Tuple[int, float], pd.Series]: + """x.__getitem__(y) <==> x[y] + + Notes + ------- + if data(storage) does not exist: + if isinstance(i, int): + return (None, None) + if isinstance(i, slice): + # return empty pd.Series + return pd.Series(dtype=np.float32) + """ + raise NotImplementedError( + "Subclass of FeatureStorage must implement `__getitem__(i: int)`/`__getitem__(s: slice)` method" + ) + + def __len__(self) -> int: + """ + + Raises + ------ + ValueError + If the data(storage) does not exist, raise ValueError + + """ + raise NotImplementedError("Subclass of FeatureStorage must implement `__len__` method") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/log.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/log.py new file mode 100644 index 0000000000000000000000000000000000000000..f7683d51163c625ac2d5514d1ff83aefd52ad913 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/log.py @@ -0,0 +1,262 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +import logging +from typing import Optional, Text, Dict, Any +import re +from logging import config as logging_config +from time import time +from contextlib import contextmanager + +from .config import C + + +class MetaLogger(type): + def __new__(mcs, name, bases, attrs): # pylint: disable=C0204 + wrapper_dict = logging.Logger.__dict__.copy() + for key, val in wrapper_dict.items(): + if key not in attrs and key != "__reduce__": + attrs[key] = val + return type.__new__(mcs, name, bases, attrs) + + +class QlibLogger(metaclass=MetaLogger): + """ + Customized logger for Qlib. + """ + + def __init__(self, module_name): + self.module_name = module_name + # this feature name conflicts with the attribute with Logger + # rename it to avoid some corner cases that result in comparing `str` and `int` + self.__level = 0 + + @property + def logger(self): + logger = logging.getLogger(self.module_name) + logger.setLevel(self.__level) + return logger + + def setLevel(self, level): + self.__level = level + + def __getattr__(self, name): + # During unpickling, python will call __getattr__. Use this line to avoid maximum recursion error. + if name in {"__setstate__"}: + raise AttributeError + return self.logger.__getattribute__(name) + + +class _QLibLoggerManager: + def __init__(self): + self._loggers = {} + + def setLevel(self, level): + for logger in self._loggers.values(): + logger.setLevel(level) + + def __call__(self, module_name, level: Optional[int] = None) -> QlibLogger: + """ + Get a logger for a specific module. + + :param module_name: str + Logic module name. + :param level: int + :return: Logger + Logger object. + """ + if level is None: + level = C.logging_level + + if not module_name.startswith("qlib."): + # Add a prefix of qlib. when the requested ``module_name`` doesn't start with ``qlib.``. + # If the module_name is already qlib.xxx, we do not format here. Otherwise, it will become qlib.qlib.xxx. + module_name = "qlib.{}".format(module_name) + + # Get logger. + module_logger = self._loggers.setdefault(module_name, QlibLogger(module_name)) + module_logger.setLevel(level) + return module_logger + + +get_module_logger = _QLibLoggerManager() + + +class TimeInspector: + timer_logger = get_module_logger("timer") + + time_marks = [] + + @classmethod + def set_time_mark(cls): + """ + Set a time mark with current time, and this time mark will push into a stack. + :return: float + A timestamp for current time. + """ + _time = time() + cls.time_marks.append(_time) + return _time + + @classmethod + def pop_time_mark(cls): + """ + Pop last time mark from stack. + """ + return cls.time_marks.pop() + + @classmethod + def get_cost_time(cls): + """ + Get last time mark from stack, calculate time diff with current time. + :return: float + Time diff calculated by last time mark with current time. + """ + cost_time = time() - cls.time_marks.pop() + return cost_time + + @classmethod + def log_cost_time(cls, info="Done"): + """ + Get last time mark from stack, calculate time diff with current time, and log time diff and info. + :param info: str + Info that will be logged into stdout. + """ + cost_time = time() - cls.time_marks.pop() + cls.timer_logger.info("Time cost: {0:.3f}s | {1}".format(cost_time, info)) + + @classmethod + @contextmanager + def logt(cls, name="", show_start=False): + """logt. + Log the time of the inside code + + Parameters + ---------- + name : + name + show_start : + show_start + """ + if show_start: + cls.timer_logger.info(f"{name} Begin") + cls.set_time_mark() + try: + yield None + finally: + pass + cls.log_cost_time(info=f"{name} Done") + + +def set_log_with_config(log_config: Dict[Text, Any]): + """set log with config + + :param log_config: + :return: + """ + logging_config.dictConfig(log_config) + + +class LogFilter(logging.Filter): + def __init__(self, param=None): + super().__init__() + self.param = param + + @staticmethod + def match_msg(filter_str, msg): + match = False + try: + if re.match(filter_str, msg): + match = True + except Exception: + pass + return match + + def filter(self, record): + allow = True + if isinstance(self.param, str): + allow = not self.match_msg(self.param, record.msg) + elif isinstance(self.param, list): + allow = not any(self.match_msg(p, record.msg) for p in self.param) + return allow + + +def set_global_logger_level(level: int, return_orig_handler_level: bool = False): + """set qlib.xxx logger handlers level + + Parameters + ---------- + level: int + logger level + + return_orig_handler_level: bool + return origin handler level map + + Examples + --------- + + .. code-block:: python + + import qlib + import logging + from qlib.log import get_module_logger, set_global_logger_level + qlib.init() + + tmp_logger_01 = get_module_logger("tmp_logger_01", level=logging.INFO) + tmp_logger_01.info("1. tmp_logger_01 info show") + + global_level = logging.WARNING + 1 + set_global_logger_level(global_level) + tmp_logger_02 = get_module_logger("tmp_logger_02", level=logging.INFO) + tmp_logger_02.log(msg="2. tmp_logger_02 log show", level=global_level) + + tmp_logger_01.info("3. tmp_logger_01 info do not show") + + """ + _handler_level_map = {} + qlib_logger = logging.root.manager.loggerDict.get("qlib", None) # pylint: disable=E1101 + if qlib_logger is not None: + for _handler in qlib_logger.handlers: + _handler_level_map[_handler] = _handler.level + _handler.level = level + return _handler_level_map if return_orig_handler_level else None + + +@contextmanager +def set_global_logger_level_cm(level: int): + """set qlib.xxx logger handlers level to use contextmanager + + Parameters + ---------- + level: int + logger level + + Examples + --------- + + .. code-block:: python + + import qlib + import logging + from qlib.log import get_module_logger, set_global_logger_level_cm + qlib.init() + + tmp_logger_01 = get_module_logger("tmp_logger_01", level=logging.INFO) + tmp_logger_01.info("1. tmp_logger_01 info show") + + global_level = logging.WARNING + 1 + with set_global_logger_level_cm(global_level): + tmp_logger_02 = get_module_logger("tmp_logger_02", level=logging.INFO) + tmp_logger_02.log(msg="2. tmp_logger_02 log show", level=global_level) + tmp_logger_01.info("3. tmp_logger_01 info do not show") + + tmp_logger_01.info("4. tmp_logger_01 info show") + + """ + _handler_level_map = set_global_logger_level(level, return_orig_handler_level=True) + try: + yield + finally: + for _handler, _level in _handler_level_map.items(): + _handler.level = _level diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..490f28860f2750ea19f5161b613965101199f124 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import warnings + +from .base import Model + +__all__ = ["Model", "warnings"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/base.py new file mode 100644 index 0000000000000000000000000000000000000000..009a3bd1441d962b1c9f64259f89484d778db3a3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/base.py @@ -0,0 +1,110 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +import abc +from typing import Text, Union +from ..utils.serial import Serializable +from ..data.dataset import Dataset +from ..data.dataset.weight import Reweighter + + +class BaseModel(Serializable, metaclass=abc.ABCMeta): + """Modeling things""" + + @abc.abstractmethod + def predict(self, *args, **kwargs) -> object: + """Make predictions after modeling things""" + + def __call__(self, *args, **kwargs) -> object: + """leverage Python syntactic sugar to make the models' behaviors like functions""" + return self.predict(*args, **kwargs) + + +class Model(BaseModel): + """Learnable Models""" + + def fit(self, dataset: Dataset, reweighter: Reweighter): + """ + Learn model from the base model + + .. note:: + + The attribute names of learned model should `not` start with '_'. So that the model could be + dumped to disk. + + The following code example shows how to retrieve `x_train`, `y_train` and `w_train` from the `dataset`: + + .. code-block:: Python + + # get features and labels + df_train, df_valid = dataset.prepare( + ["train", "valid"], col_set=["feature", "label"], data_key=DataHandlerLP.DK_L + ) + x_train, y_train = df_train["feature"], df_train["label"] + x_valid, y_valid = df_valid["feature"], df_valid["label"] + + # get weights + try: + wdf_train, wdf_valid = dataset.prepare(["train", "valid"], col_set=["weight"], + data_key=DataHandlerLP.DK_L) + w_train, w_valid = wdf_train["weight"], wdf_valid["weight"] + except KeyError as e: + w_train = pd.DataFrame(np.ones_like(y_train.values), index=y_train.index) + w_valid = pd.DataFrame(np.ones_like(y_valid.values), index=y_valid.index) + + Parameters + ---------- + dataset : Dataset + dataset will generate the processed data from model training. + + """ + raise NotImplementedError() + + @abc.abstractmethod + def predict(self, dataset: Dataset, segment: Union[Text, slice] = "test") -> object: + """give prediction given Dataset + + Parameters + ---------- + dataset : Dataset + dataset will generate the processed dataset from model training. + + segment : Text or slice + dataset will use this segment to prepare data. (default=test) + + Returns + ------- + Prediction results with certain type such as `pandas.Series`. + """ + raise NotImplementedError() + + +class ModelFT(Model): + """Model (F)ine(t)unable""" + + @abc.abstractmethod + def finetune(self, dataset: Dataset): + """finetune model based given dataset + + A typical use case of finetuning model with qlib.workflow.R + + .. code-block:: python + + # start exp to train init model + with R.start(experiment_name="init models"): + model.fit(dataset) + R.save_objects(init_model=model) + rid = R.get_recorder().id + + # Finetune model based on previous trained model + with R.start(experiment_name="finetune model"): + recorder = R.get_recorder(recorder_id=rid, experiment_name="init models") + model = recorder.load_object("init_model") + model.finetune(dataset, num_boost_round=10) + + + Parameters + ---------- + dataset : Dataset + dataset will generate the processed dataset from model training. + """ + raise NotImplementedError() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/ensemble.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/ensemble.py new file mode 100644 index 0000000000000000000000000000000000000000..1670a6538ef5dc249fb278339517eb3d75159955 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/ensemble.py @@ -0,0 +1,132 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +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. +""" + +from typing import Union +import pandas as pd +from qlib.utils import FLATTEN_TUPLE, flatten_dict +from qlib.log import get_module_logger + + +class Ensemble: + """Merge the ensemble_dict into an ensemble object. + + For example: {Rollinga_b: object, Rollingb_c: object} -> object + + When calling this class: + + Args: + ensemble_dict (dict): the ensemble dict like {name: things} waiting for merging + + Returns: + object: the ensemble object + """ + + def __call__(self, ensemble_dict: dict, *args, **kwargs): + raise NotImplementedError(f"Please implement the `__call__` method.") + + +class SingleKeyEnsemble(Ensemble): + """ + Extract the object if there is only one key and value in the dict. Make the result more readable. + {Only key: Only value} -> Only value + + If there is more than 1 key or less than 1 key, then do nothing. + Even you can run this recursively to make dict more readable. + + NOTE: Default runs recursively. + + When calling this class: + + Args: + ensemble_dict (dict): the dict. The key of the dict will be ignored. + + Returns: + dict: the readable dict. + """ + + def __call__(self, ensemble_dict: Union[dict, object], recursion: bool = True) -> object: + if not isinstance(ensemble_dict, dict): + return ensemble_dict + if recursion: + tmp_dict = {} + for k, v in ensemble_dict.items(): + tmp_dict[k] = self(v, recursion) + ensemble_dict = tmp_dict + keys = list(ensemble_dict.keys()) + if len(keys) == 1: + ensemble_dict = ensemble_dict[keys[0]] + return ensemble_dict + + +class RollingEnsemble(Ensemble): + """Merge a dict of rolling dataframe like `prediction` or `IC` into an ensemble. + + NOTE: The values of dict must be pd.DataFrame, and have the index "datetime". + + When calling this class: + + Args: + ensemble_dict (dict): a dict like {"A": pd.DataFrame, "B": pd.DataFrame}. + The key of the dict will be ignored. + + Returns: + pd.DataFrame: the complete result of rolling. + """ + + def __call__(self, ensemble_dict: dict) -> pd.DataFrame: + get_module_logger("RollingEnsemble").info(f"keys in group: {list(ensemble_dict.keys())}") + artifact_list = list(ensemble_dict.values()) + artifact_list.sort(key=lambda x: x.index.get_level_values("datetime").min()) + artifact = pd.concat(artifact_list) + # If there are duplicated predition, use the latest perdiction + artifact = artifact[~artifact.index.duplicated(keep="last")] + artifact = artifact.sort_index() + return artifact + + +class AverageEnsemble(Ensemble): + """ + Average and standardize a dict of same shape dataframe like `prediction` or `IC` into an ensemble. + + NOTE: The values of dict must be pd.DataFrame, and have the index "datetime". If it is a nested dict, then flat it. + + When calling this class: + + Args: + ensemble_dict (dict): a dict like {"A": pd.DataFrame, "B": pd.DataFrame}. + The key of the dict will be ignored. + + Returns: + pd.DataFrame: the complete result of averaging and standardizing. + """ + + def __call__(self, ensemble_dict: dict) -> pd.DataFrame: + """using sample: + from qlib.model.ens.ensemble import AverageEnsemble + pred_res['new_key_name'] = AverageEnsemble()(predict_dict) + + Parameters + ---------- + ensemble_dict : dict + Dictionary you want to ensemble + + Returns + ------- + pd.DataFrame + The dictionary including ensenbling result + """ + # need to flatten the nested dict + ensemble_dict = flatten_dict(ensemble_dict, sep=FLATTEN_TUPLE) + get_module_logger("AverageEnsemble").info(f"keys in group: {list(ensemble_dict.keys())}") + values = list(ensemble_dict.values()) + # NOTE: this may change the style underlying data!!!! + # from pd.DataFrame to pd.Series + results = pd.concat(values, axis=1) + results = results.groupby("datetime", group_keys=False).apply(lambda df: (df - df.mean()) / df.std()) + results = results.mean(axis=1) + results = results.sort_index() + return results diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/group.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/group.py new file mode 100644 index 0000000000000000000000000000000000000000..ba6f9f8071bbf8c859b59cd2e9831f43d8c10d82 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/ens/group.py @@ -0,0 +1,115 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +Group can group a set of objects based on `group_func` and change them to a dict. +After group, we provide a method to reduce them. + +For example: + +group: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}} +reduce: {(A,B): {C1: object, C2: object}} -> {(A,B): object} + +""" + +from qlib.model.ens.ensemble import Ensemble, RollingEnsemble +from typing import Callable +from joblib import Parallel, delayed + + +class Group: + """Group the objects based on dict""" + + def __init__(self, group_func=None, ens: Ensemble = None): + """ + Init Group. + + Args: + group_func (Callable, optional): Given a dict and return the group key and one of the group elements. + + For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}} + + Defaults to None. + + ens (Ensemble, optional): If not None, do ensemble for grouped value after grouping. + """ + self._group_func = group_func + self._ens_func = ens + + def group(self, *args, **kwargs) -> dict: + """ + Group a set of objects and change them to a dict. + + For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}} + + Returns: + dict: grouped dict + """ + if isinstance(getattr(self, "_group_func", None), Callable): + return self._group_func(*args, **kwargs) + else: + raise NotImplementedError(f"Please specify valid `group_func`.") + + def reduce(self, *args, **kwargs) -> dict: + """ + Reduce grouped dict. + + For example: {(A,B): {C1: object, C2: object}} -> {(A,B): object} + + Returns: + dict: reduced dict + """ + if isinstance(getattr(self, "_ens_func", None), Callable): + return self._ens_func(*args, **kwargs) + else: + raise NotImplementedError(f"Please specify valid `_ens_func`.") + + def __call__(self, ungrouped_dict: dict, n_jobs: int = 1, verbose: int = 0, *args, **kwargs) -> dict: + """ + Group the ungrouped_dict into different groups. + + Args: + ungrouped_dict (dict): the ungrouped dict waiting for grouping like {name: things} + + Returns: + dict: grouped_dict like {G1: object, G2: object} + n_jobs: how many progress you need. + verbose: the print mode for Parallel. + """ + + # NOTE: The multiprocessing will raise error if you use `Serializable` + # Because the `Serializable` will affect the behaviors of pickle + grouped_dict = self.group(ungrouped_dict, *args, **kwargs) + + key_l = [] + job_l = [] + for key, value in grouped_dict.items(): + key_l.append(key) + job_l.append(delayed(Group.reduce)(self, value)) + return dict(zip(key_l, Parallel(n_jobs=n_jobs, verbose=verbose)(job_l))) + + +class RollingGroup(Group): + """Group the rolling dict""" + + def group(self, rolling_dict: dict) -> dict: + """Given an rolling dict likes {(A,B,R): things}, return the grouped dict likes {(A,B): {R:things}} + + 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. + + Args: + rolling_dict (dict): an rolling dict. If the key is not a tuple, then do nothing. + + Returns: + dict: grouped dict + """ + grouped_dict = {} + for key, values in rolling_dict.items(): + if isinstance(key, tuple): + grouped_dict.setdefault(key[:-1], {})[key[-1]] = values + else: + raise TypeError(f"Expected `tuple` type, but got a value `{key}`") + return grouped_dict + + def __init__(self, ens=RollingEnsemble()): + super().__init__(ens=ens) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a490d7744248e8f9d49e328a726168eef77fef53 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/interpret/base.py @@ -0,0 +1,45 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +Interfaces to interpret models +""" + +import pandas as pd +from abc import abstractmethod + + +class FeatureInt: + """Feature (Int)erpreter""" + + @abstractmethod + def get_feature_importance(self) -> pd.Series: + """get feature importance + + Returns + ------- + The index is the feature name. + + The greater the value, the higher importance. + """ + + +class LightGBMFInt(FeatureInt): + """LightGBM (F)eature (Int)erpreter""" + + def __init__(self): + self.model = None + + def get_feature_importance(self, *args, **kwargs) -> pd.Series: + """get feature importance + + Notes + ----- + parameters reference: + https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html?highlight=feature_importance#lightgbm.Booster.feature_importance + """ + return pd.Series( + self.model.feature_importance(*args, **kwargs), index=self.model.feature_name() + ).sort_values( # pylint: disable=E1101 + ascending=False + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75b9c38588ba931886950cf238e560598fe06714 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/__init__.py @@ -0,0 +1,7 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from .task import MetaTask +from .dataset import MetaTaskDataset + +__all__ = ["MetaTask", "MetaTaskDataset"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/dataset.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..34a9b949b31cc71f7a3cfa2adb77e93aec14c265 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/dataset.py @@ -0,0 +1,77 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import abc +from qlib.model.meta.task import MetaTask +from typing import Dict, Union, List, Tuple, Text +from ...utils.serial import Serializable + + +class MetaTaskDataset(Serializable, metaclass=abc.ABCMeta): + """ + A dataset fetching the data in a meta-level. + + A Meta Dataset is responsible for + + - input tasks(e.g. Qlib tasks) and prepare meta tasks + + - meta task contains more information than normal tasks (e.g. input data for meta model) + + The learnt pattern could transfer to other meta dataset. The following cases should be supported + + - A meta-model trained on meta-dataset A and then applied to meta-dataset B + + - 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 + """ + + def __init__(self, segments: Union[Dict[Text, Tuple], float], *args, **kwargs): + """ + The meta-dataset maintains a list of meta-tasks when it is initialized. + + The segments indicates the way to divide the data + + The duty of the `__init__` function of MetaTaskDataset + - initialize the tasks + """ + super().__init__(*args, **kwargs) + self.segments = segments + + def prepare_tasks(self, segments: Union[List[Text], Text], *args, **kwargs) -> List[MetaTask]: + """ + Prepare the data in each meta-task and ready for training. + + The following code example shows how to retrieve a list of meta-tasks from the `meta_dataset`: + + .. code-block:: Python + + # get the train segment and the test segment, both of them are lists + train_meta_tasks, test_meta_tasks = meta_dataset.prepare_tasks(["train", "test"]) + + Parameters + ---------- + segments: Union[List[Text], Tuple[Text], Text] + the info to select data + + Returns + ------- + list: + 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]]. + Each task is a meta task + """ + if isinstance(segments, (list, tuple)): + return [self._prepare_seg(seg) for seg in segments] + elif isinstance(segments, str): + return self._prepare_seg(segments) + else: + raise NotImplementedError(f"This type of input is not supported") + + @abc.abstractmethod + def _prepare_seg(self, segment: Text): + """ + prepare a single segment of data for training data + + Parameters + ---------- + seg : Text + the name of the segment + """ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/model.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/model.py new file mode 100644 index 0000000000000000000000000000000000000000..1f13dba34af9fda951ab9ab0a01b668f08dca442 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/model.py @@ -0,0 +1,75 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import abc +from typing import List + +from .dataset import MetaTaskDataset + + +class MetaModel(metaclass=abc.ABCMeta): + """ + The meta-model guiding the model learning. + + The word `Guiding` can be categorized into two types based on the stage of model learning + - The definition of learning tasks: Please refer to docs of `MetaTaskModel` + - Controlling the learning process of models: Please refer to the docs of `MetaGuideModel` + """ + + @abc.abstractmethod + def fit(self, *args, **kwargs): + """ + The training process of the meta-model. + """ + + @abc.abstractmethod + def inference(self, *args, **kwargs) -> object: + """ + The inference process of the meta-model. + + Returns + ------- + object: + Some information to guide the model learning + """ + + +class MetaTaskModel(MetaModel): + """ + 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. + """ + + def fit(self, meta_dataset: MetaTaskDataset): + """ + The MetaTaskModel is expected to get prepared MetaTask from meta_dataset. + And then it will learn knowledge from the meta tasks + """ + raise NotImplementedError(f"Please implement the `fit` method") + + def inference(self, meta_dataset: MetaTaskDataset) -> List[dict]: + """ + MetaTaskModel will make inference on the meta_dataset + The MetaTaskModel is expected to get prepared MetaTask from meta_dataset. + Then it will create modified task with Qlib format which can be executed by Qlib trainer. + + Returns + ------- + List[dict]: + A list of modified task definitions. + + """ + raise NotImplementedError(f"Please implement the `inference` method") + + +class MetaGuideModel(MetaModel): + """ + 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. + """ + + @abc.abstractmethod + def fit(self, *args, **kwargs): + pass + + @abc.abstractmethod + def inference(self, *args, **kwargs): + pass diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/task.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/task.py new file mode 100644 index 0000000000000000000000000000000000000000..a051acf14669c391f83596cc0e3a96e73906dafb --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/meta/task.py @@ -0,0 +1,56 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from qlib.data.dataset import Dataset +from ...utils import init_instance_by_config + + +class MetaTask: + """ + A single meta-task, a meta-dataset contains a list of them. + It serves as a component as in MetaDatasetDS + + The data processing is different + + - the processed input may be different between training and testing + + - When training, the X, y, X_test, y_test in training tasks are necessary (# PROC_MODE_FULL #) + but not necessary in test tasks. (# PROC_MODE_TEST #) + - When the meta model can be transferred into other dataset, only meta_info is necessary (# PROC_MODE_TRANSFER #) + """ + + PROC_MODE_FULL = "full" + PROC_MODE_TEST = "test" + PROC_MODE_TRANSFER = "transfer" + + def __init__(self, task: dict, meta_info: object, mode: str = PROC_MODE_FULL): + """ + The `__init__` func is responsible for + + - store the task + - store the origin input data for + - process the input data for meta data + + Parameters + ---------- + task : dict + the task to be enhanced by meta model + + meta_info : object + the input for meta model + """ + self.task = task + self.meta_info = meta_info # the original meta input information, it will be processed later + self.mode = mode + + def get_dataset(self) -> Dataset: + return init_instance_by_config(self.task["dataset"], accept_types=Dataset) + + def get_meta_input(self) -> object: + """ + Return the **processed** meta_info + """ + return self.meta_info + + def __repr__(self): + return f"MetaTask(task={self.task}, meta_info={self.meta_info})" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..230fdfca0828f7e1a395d9f7bfc0d9dcade3dd48 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/__init__.py @@ -0,0 +1,14 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from .base import RiskModel +from .poet import POETCovEstimator +from .shrink import ShrinkCovEstimator +from .structured import StructuredCovEstimator + +__all__ = [ + "RiskModel", + "POETCovEstimator", + "ShrinkCovEstimator", + "StructuredCovEstimator", +] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/base.py new file mode 100644 index 0000000000000000000000000000000000000000..7afacfe8ff23a8b295d9cd06092ef8e609390a2d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/base.py @@ -0,0 +1,147 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import inspect +import numpy as np +import pandas as pd +from typing import Union + +from qlib.model.base import BaseModel + + +class RiskModel(BaseModel): + """Risk Model + + A risk model is used to estimate the covariance matrix of stock returns. + """ + + MASK_NAN = "mask" + FILL_NAN = "fill" + IGNORE_NAN = "ignore" + + def __init__(self, nan_option: str = "ignore", assume_centered: bool = False, scale_return: bool = True): + """ + Args: + nan_option (str): nan handling option (`ignore`/`mask`/`fill`). + assume_centered (bool): whether the data is assumed to be centered. + scale_return (bool): whether scale returns as percentage. + """ + # nan + assert nan_option in [ + self.MASK_NAN, + self.FILL_NAN, + self.IGNORE_NAN, + ], f"`nan_option={nan_option}` is not supported" + self.nan_option = nan_option + + self.assume_centered = assume_centered + self.scale_return = scale_return + + def predict( + self, + X: Union[pd.Series, pd.DataFrame, np.ndarray], + return_corr: bool = False, + is_price: bool = True, + return_decomposed_components=False, + ) -> Union[pd.DataFrame, np.ndarray, tuple]: + """ + Args: + X (pd.Series, pd.DataFrame or np.ndarray): data from which to estimate the covariance, + with variables as columns and observations as rows. + return_corr (bool): whether return the correlation matrix. + is_price (bool): whether `X` contains price (if not assume stock returns). + return_decomposed_components (bool): whether return decomposed components of the covariance matrix. + + Returns: + pd.DataFrame or np.ndarray: estimated covariance (or correlation). + """ + assert ( + not return_corr or not return_decomposed_components + ), "Can only return either correlation matrix or decomposed components." + + # transform input into 2D array + if not isinstance(X, (pd.Series, pd.DataFrame)): + columns = None + else: + if isinstance(X.index, pd.MultiIndex): + if isinstance(X, pd.DataFrame): + X = X.iloc[:, 0].unstack(level="instrument") # always use the first column + else: + X = X.unstack(level="instrument") + else: + # X is 2D DataFrame + pass + columns = X.columns # will be used to restore dataframe + X = X.values + + # calculate pct_change + if is_price: + X = X[1:] / X[:-1] - 1 # NOTE: resulting `n - 1` rows + + # scale return + if self.scale_return: + X *= 100 + + # handle nan and centered + X = self._preprocess(X) + + # return decomposed components if needed + if return_decomposed_components: + assert ( + "return_decomposed_components" in inspect.getfullargspec(self._predict).args + ), "This risk model does not support return decomposed components of the covariance matrix " + + F, cov_b, var_u = self._predict(X, return_decomposed_components=True) # pylint: disable=E1123 + return F, cov_b, var_u + + # estimate covariance + S = self._predict(X) + + # return correlation if needed + if return_corr: + vola = np.sqrt(np.diag(S)) + corr = S / np.outer(vola, vola) + if columns is None: + return corr + return pd.DataFrame(corr, index=columns, columns=columns) + + # return covariance + if columns is None: + return S + return pd.DataFrame(S, index=columns, columns=columns) + + def _predict(self, X: np.ndarray) -> np.ndarray: + """covariance estimation implementation + + This method should be overridden by child classes. + + By default, this method implements the empirical covariance estimation. + + Args: + X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows). + + Returns: + np.ndarray: covariance matrix. + """ + xTx = np.asarray(X.T.dot(X)) + N = len(X) + if isinstance(X, np.ma.MaskedArray): + M = 1 - X.mask + N = M.T.dot(M) # each pair has distinct number of samples + return xTx / N + + def _preprocess(self, X: np.ndarray) -> Union[np.ndarray, np.ma.MaskedArray]: + """handle nan and centerize data + + Note: + if `nan_option='mask'` then the returned array will be `np.ma.MaskedArray`. + """ + # handle nan + if self.nan_option == self.FILL_NAN: + X = np.nan_to_num(X) + elif self.nan_option == self.MASK_NAN: + X = np.ma.masked_invalid(X) + # centralize + if not self.assume_centered: + X = X - np.nanmean(X, axis=0) + return X diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/poet.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/poet.py new file mode 100644 index 0000000000000000000000000000000000000000..42388d84cb387aa2bffb669fdfd83d5601346eb3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/poet.py @@ -0,0 +1,83 @@ +import numpy as np + +from qlib.model.riskmodel import RiskModel + + +class POETCovEstimator(RiskModel): + """Principal Orthogonal Complement Thresholding Estimator (POET) + + Reference: + [1] Fan, J., Liao, Y., & Mincheva, M. (2013). Large covariance estimation by thresholding principal orthogonal complements. + Journal of the Royal Statistical Society. Series B: Statistical Methodology, 75(4), 603–680. https://doi.org/10.1111/rssb.12016 + [2] http://econweb.rutgers.edu/yl1114/papers/poet/POET.m + """ + + THRESH_SOFT = "soft" + THRESH_HARD = "hard" + THRESH_SCAD = "scad" + + def __init__(self, num_factors: int = 0, thresh: float = 1.0, thresh_method: str = "soft", **kwargs): + """ + Args: + num_factors (int): number of factors (if set to zero, no factor model will be used). + thresh (float): the positive constant for thresholding. + thresh_method (str): thresholding method, which can be + - 'soft': soft thresholding. + - 'hard': hard thresholding. + - 'scad': scad thresholding. + kwargs: see `RiskModel` for more information. + """ + super().__init__(**kwargs) + + assert num_factors >= 0, "`num_factors` requires a positive integer" + self.num_factors = num_factors + + assert thresh >= 0, "`thresh` requires a positive float number" + self.thresh = thresh + + assert thresh_method in [ + self.THRESH_HARD, + self.THRESH_SOFT, + self.THRESH_SCAD, + ], "`thresh_method` should be `soft`/`hard`/`scad`" + self.thresh_method = thresh_method + + def _predict(self, X: np.ndarray) -> np.ndarray: + Y = X.T # NOTE: to match POET's implementation + p, n = Y.shape + + if self.num_factors > 0: + Dd, V = np.linalg.eig(Y.T.dot(Y)) + V = V[:, np.argsort(Dd)] + F = V[:, -self.num_factors :][:, ::-1] * np.sqrt(n) + LamPCA = Y.dot(F) / n + uhat = np.asarray(Y - LamPCA.dot(F.T)) + Lowrank = np.asarray(LamPCA.dot(LamPCA.T)) + rate = 1 / np.sqrt(p) + np.sqrt(np.log(p) / n) + else: + uhat = np.asarray(Y) + rate = np.sqrt(np.log(p) / n) + Lowrank = 0 + + lamb = rate * self.thresh + SuPCA = uhat.dot(uhat.T) / n + SuDiag = np.diag(np.diag(SuPCA)) + R = np.linalg.inv(SuDiag**0.5).dot(SuPCA).dot(np.linalg.inv(SuDiag**0.5)) + + if self.thresh_method == self.THRESH_HARD: + M = R * (np.abs(R) > lamb) + elif self.thresh_method == self.THRESH_SOFT: + res = np.abs(R) - lamb + res = (res + np.abs(res)) / 2 + M = np.sign(R) * res + else: + M1 = (np.abs(R) < 2 * lamb) * np.sign(R) * (np.abs(R) - lamb) * (np.abs(R) > lamb) + M2 = (np.abs(R) < 3.7 * lamb) * (np.abs(R) >= 2 * lamb) * (2.7 * R - 3.7 * np.sign(R) * lamb) / 1.7 + M3 = (np.abs(R) >= 3.7 * lamb) * R + M = M1 + M2 + M3 + + Rthresh = M - np.diag(np.diag(M)) + np.eye(p) + SigmaU = (SuDiag**0.5).dot(Rthresh).dot(SuDiag**0.5) + SigmaY = SigmaU + Lowrank + + return SigmaY diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/shrink.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/shrink.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c0e48ef8ba21ac7bd64c513e0cfe2ef154ec08 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/shrink.py @@ -0,0 +1,259 @@ +import numpy as np +from typing import Union + +from qlib.model.riskmodel import RiskModel + + +class ShrinkCovEstimator(RiskModel): + """Shrinkage Covariance Estimator + + This estimator will shrink the sample covariance matrix towards + an identify matrix: + S_hat = (1 - alpha) * S + alpha * F + where `alpha` is the shrink parameter and `F` is the shrinking target. + + The following shrinking parameters (`alpha`) are supported: + - `lw` [1][2][3]: use Ledoit-Wolf shrinking parameter. + - `oas` [4]: use Oracle Approximating Shrinkage shrinking parameter. + - float: directly specify the shrink parameter, should be between [0, 1]. + + The following shrinking targets (`F`) are supported: + - `const_var` [1][4][5]: assume stocks have the same constant variance and zero correlation. + - `const_corr` [2][6]: assume stocks have different variance but equal correlation. + - `single_factor` [3][7]: assume single factor model as the shrinking target. + - np.ndarray: provide the shrinking targets directly. + + Note: + - The optimal shrinking parameter depends on the selection of the shrinking target. + Currently, `oas` is not supported for `const_corr` and `single_factor`. + - Remember to set `nan_option` to `fill` or `mask` if your data has missing values. + + References: + [1] Ledoit, O., & Wolf, M. (2004). A well-conditioned estimator for large-dimensional covariance matrices. + Journal of Multivariate Analysis, 88(2), 365–411. https://doi.org/10.1016/S0047-259X(03)00096-4 + [2] Ledoit, O., & Wolf, M. (2004). Honey, I shrunk the sample covariance matrix. + Journal of Portfolio Management, 30(4), 1–22. https://doi.org/10.3905/jpm.2004.110 + [3] Ledoit, O., & Wolf, M. (2003). Improved estimation of the covariance matrix of stock returns + with an application to portfolio selection. + Journal of Empirical Finance, 10(5), 603–621. https://doi.org/10.1016/S0927-5398(03)00007-0 + [4] Chen, Y., Wiesel, A., Eldar, Y. C., & Hero, A. O. (2010). Shrinkage algorithms for MMSE covariance + estimation. IEEE Transactions on Signal Processing, 58(10), 5016–5029. + https://doi.org/10.1109/TSP.2010.2053029 + [5] https://www.econ.uzh.ch/dam/jcr:ffffffff-935a-b0d6-0000-00007f64e5b9/cov1para.m.zip + [6] https://www.econ.uzh.ch/dam/jcr:ffffffff-935a-b0d6-ffff-ffffde5e2d4e/covCor.m.zip + [7] https://www.econ.uzh.ch/dam/jcr:ffffffff-935a-b0d6-0000-0000648dfc98/covMarket.m.zip + """ + + SHR_LW = "lw" + SHR_OAS = "oas" + + TGT_CONST_VAR = "const_var" + TGT_CONST_CORR = "const_corr" + TGT_SINGLE_FACTOR = "single_factor" + + def __init__(self, alpha: Union[str, float] = 0.0, target: Union[str, np.ndarray] = "const_var", **kwargs): + """ + Args: + alpha (str or float): shrinking parameter or estimator (`lw`/`oas`) + target (str or np.ndarray): shrinking target (`const_var`/`const_corr`/`single_factor`) + kwargs: see `RiskModel` for more information + """ + super().__init__(**kwargs) + + # alpha + if isinstance(alpha, str): + assert alpha in [self.SHR_LW, self.SHR_OAS], f"shrinking method `{alpha}` is not supported" + elif isinstance(alpha, (float, np.floating)): + assert 0 <= alpha <= 1, "alpha should be between [0, 1]" + else: + raise TypeError("invalid argument type for `alpha`") + self.alpha = alpha + + # target + if isinstance(target, str): + assert target in [ + self.TGT_CONST_VAR, + self.TGT_CONST_CORR, + self.TGT_SINGLE_FACTOR, + ], f"shrinking target `{target} is not supported" + elif isinstance(target, np.ndarray): + pass + else: + raise TypeError("invalid argument type for `target`") + if alpha == self.SHR_OAS and target != self.TGT_CONST_VAR: + raise NotImplementedError("currently `oas` can only support `const_var` as target") + self.target = target + + def _predict(self, X: np.ndarray) -> np.ndarray: + # sample covariance + S = super()._predict(X) + + # shrinking target + F = self._get_shrink_target(X, S) + + # get shrinking parameter + alpha = self._get_shrink_param(X, S, F) + + # shrink covariance + if alpha > 0: + S *= 1 - alpha + F *= alpha + S += F + + return S + + def _get_shrink_target(self, X: np.ndarray, S: np.ndarray) -> np.ndarray: + """get shrinking target `F`""" + if self.target == self.TGT_CONST_VAR: + return self._get_shrink_target_const_var(X, S) + if self.target == self.TGT_CONST_CORR: + return self._get_shrink_target_const_corr(X, S) + if self.target == self.TGT_SINGLE_FACTOR: + return self._get_shrink_target_single_factor(X, S) + return self.target + + def _get_shrink_target_const_var(self, X: np.ndarray, S: np.ndarray) -> np.ndarray: + """get shrinking target with constant variance + + This target assumes zero pair-wise correlation and constant variance. + The constant variance is estimated by averaging all sample's variances. + """ + n = len(S) + F = np.eye(n) + np.fill_diagonal(F, np.mean(np.diag(S))) + return F + + def _get_shrink_target_const_corr(self, X: np.ndarray, S: np.ndarray) -> np.ndarray: + """get shrinking target with constant correlation + + This target assumes constant pair-wise correlation but keep the sample variance. + The constant correlation is estimated by averaging all pairwise correlations. + """ + n = len(S) + var = np.diag(S) + sqrt_var = np.sqrt(var) + covar = np.outer(sqrt_var, sqrt_var) + r_bar = (np.sum(S / covar) - n) / (n * (n - 1)) + F = r_bar * covar + np.fill_diagonal(F, var) + return F + + def _get_shrink_target_single_factor(self, X: np.ndarray, S: np.ndarray) -> np.ndarray: + """get shrinking target with single factor model""" + X_mkt = np.nanmean(X, axis=1) + cov_mkt = np.asarray(X.T.dot(X_mkt) / len(X)) + var_mkt = np.asarray(X_mkt.dot(X_mkt) / len(X)) + F = np.outer(cov_mkt, cov_mkt) / var_mkt + np.fill_diagonal(F, np.diag(S)) + return F + + def _get_shrink_param(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float: + """get shrinking parameter `alpha` + + Note: + The Ledoit-Wolf shrinking parameter estimator consists of three different methods. + """ + if self.alpha == self.SHR_OAS: + return self._get_shrink_param_oas(X, S, F) + elif self.alpha == self.SHR_LW: + if self.target == self.TGT_CONST_VAR: + return self._get_shrink_param_lw_const_var(X, S, F) + if self.target == self.TGT_CONST_CORR: + return self._get_shrink_param_lw_const_corr(X, S, F) + if self.target == self.TGT_SINGLE_FACTOR: + return self._get_shrink_param_lw_single_factor(X, S, F) + return self.alpha + + def _get_shrink_param_oas(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float: + """Oracle Approximating Shrinkage Estimator + + This method uses the following formula to estimate the `alpha` + parameter for the shrink covariance estimator: + A = (1 - 2 / p) * trace(S^2) + trace^2(S) + B = (n + 1 - 2 / p) * (trace(S^2) - trace^2(S) / p) + alpha = A / B + where `n`, `p` are the dim of observations and variables respectively. + """ + trS2 = np.sum(S**2) + tr2S = np.trace(S) ** 2 + + n, p = X.shape + + A = (1 - 2 / p) * (trS2 + tr2S) + B = (n + 1 - 2 / p) * (trS2 + tr2S / p) + alpha = A / B + + return alpha + + def _get_shrink_param_lw_const_var(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float: + """Ledoit-Wolf Shrinkage Estimator (Constant Variance) + + This method shrinks the covariance matrix towards the constand variance target. + """ + t, n = X.shape + + y = X**2 + phi = np.sum(y.T.dot(y) / t - S**2) + + gamma = np.linalg.norm(S - F, "fro") ** 2 + + kappa = phi / gamma + alpha = max(0, min(1, kappa / t)) + + return alpha + + def _get_shrink_param_lw_const_corr(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float: + """Ledoit-Wolf Shrinkage Estimator (Constant Correlation) + + This method shrinks the covariance matrix towards the constand correlation target. + """ + t, n = X.shape + + var = np.diag(S) + sqrt_var = np.sqrt(var) + r_bar = (np.sum(S / np.outer(sqrt_var, sqrt_var)) - n) / (n * (n - 1)) + + y = X**2 + phi_mat = y.T.dot(y) / t - S**2 + phi = np.sum(phi_mat) + + theta_mat = (X**3).T.dot(X) / t - var[:, None] * S + np.fill_diagonal(theta_mat, 0) + rho = np.sum(np.diag(phi_mat)) + r_bar * np.sum(np.outer(1 / sqrt_var, sqrt_var) * theta_mat) + + gamma = np.linalg.norm(S - F, "fro") ** 2 + + kappa = (phi - rho) / gamma + alpha = max(0, min(1, kappa / t)) + + return alpha + + def _get_shrink_param_lw_single_factor(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float: + """Ledoit-Wolf Shrinkage Estimator (Single Factor Model) + + This method shrinks the covariance matrix towards the single factor model target. + """ + t, n = X.shape + + X_mkt = np.nanmean(X, axis=1) + cov_mkt = np.asarray(X.T.dot(X_mkt) / len(X)) + var_mkt = np.asarray(X_mkt.dot(X_mkt) / len(X)) + + y = X**2 + phi = np.sum(y.T.dot(y)) / t - np.sum(S**2) + + rdiag = np.sum(y**2) / t - np.sum(np.diag(S) ** 2) + z = X * X_mkt[:, None] + v1 = y.T.dot(z) / t - cov_mkt[:, None] * S + roff1 = np.sum(v1 * cov_mkt[:, None].T) / var_mkt - np.sum(np.diag(v1) * cov_mkt) / var_mkt + v3 = z.T.dot(z) / t - var_mkt * S + roff3 = np.sum(v3 * np.outer(cov_mkt, cov_mkt)) / var_mkt**2 - np.sum(np.diag(v3) * cov_mkt**2) / var_mkt**2 + roff = 2 * roff1 - roff3 + rho = rdiag + roff + + gamma = np.linalg.norm(S - F, "fro") ** 2 + + kappa = (phi - rho) / gamma + alpha = max(0, min(1, kappa / t)) + + return alpha diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/structured.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/structured.py new file mode 100644 index 0000000000000000000000000000000000000000..71e442536dc00147dc0655ee848d495b3357233a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/riskmodel/structured.py @@ -0,0 +1,94 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import numpy as np +from typing import Union +from sklearn.decomposition import PCA, FactorAnalysis + +from qlib.model.riskmodel import RiskModel + + +class StructuredCovEstimator(RiskModel): + """Structured Covariance Estimator + + This estimator assumes observations can be predicted by multiple factors + X = B @ F.T + U + where `X` contains observations (row) of multiple variables (column), + `F` contains factor exposures (column) for all variables (row), + `B` is the regression coefficients matrix for all observations (row) on + all factors (columns), and `U` is the residual matrix with shape like `X`. + + Therefore, the structured covariance can be estimated by + cov(X.T) = F @ cov(B.T) @ F.T + diag(var(U)) + + In finance domain, there are mainly three methods to design `F` [1][2]: + - Statistical Risk Model (SRM): latent factor models major components + - Fundamental Risk Model (FRM): human designed factors + - Deep Risk Model (DRM): neural network designed factors (like a blend of SRM & DRM) + + In this implementation we use latent factor models to specify `F`. + Specifically, the following two latent factor models are supported: + - `pca`: Principal Component Analysis + - `fa`: Factor Analysis + + Reference: + [1] Fan, J., Liao, Y., & Liu, H. (2016). An overview of the estimation of large covariance and + precision matrices. Econometrics Journal, 19(1), C1–C32. https://doi.org/10.1111/ectj.12061 + [2] Lin, H., Zhou, D., Liu, W., & Bian, J. (2021). Deep Risk Model: A Deep Learning Solution for + Mining Latent Risk Factors to Improve Covariance Matrix Estimation. arXiv preprint arXiv:2107.05201. + """ + + FACTOR_MODEL_PCA = "pca" + FACTOR_MODEL_FA = "fa" + DEFAULT_NAN_OPTION = "fill" + + def __init__(self, factor_model: str = "pca", num_factors: int = 10, **kwargs): + """ + Args: + factor_model (str): the latent factor models used to estimate the structured covariance (`pca`/`fa`). + num_factors (int): number of components to keep. + kwargs: see `RiskModel` for more information + """ + if "nan_option" in kwargs: + assert kwargs["nan_option"] in [self.DEFAULT_NAN_OPTION], "nan_option={} is not supported".format( + kwargs["nan_option"] + ) + else: + kwargs["nan_option"] = self.DEFAULT_NAN_OPTION + + super().__init__(**kwargs) + + assert factor_model in [ + self.FACTOR_MODEL_PCA, + self.FACTOR_MODEL_FA, + ], "factor_model={} is not supported".format(factor_model) + self.solver = PCA if factor_model == self.FACTOR_MODEL_PCA else FactorAnalysis + + self.num_factors = num_factors + + def _predict(self, X: np.ndarray, return_decomposed_components=False) -> Union[np.ndarray, tuple]: + """ + covariance estimation implementation + + Args: + X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows). + return_decomposed_components (bool): whether return decomposed components of the covariance matrix. + + Returns: + tuple or np.ndarray: decomposed covariance matrix or covariance matrix. + """ + + model = self.solver(self.num_factors, random_state=0).fit(X) + + F = model.components_.T # variables x factors + B = model.transform(X) # observations x factors + U = X - B @ F.T + cov_b = np.cov(B.T) # factors x factors + var_u = np.var(U, axis=0) # diagonal + + if return_decomposed_components: + return F, cov_b, var_u + + cov_x = F @ cov_b @ F.T + np.diag(var_u) + + return cov_x diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/trainer.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..ce204420f81a36c50d7b672ecff49522a1a0bb85 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/trainer.py @@ -0,0 +1,619 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +The Trainer will train a list of tasks and return a list of model recorders. +There are two steps in each Trainer including ``train`` (make model recorder) and ``end_train`` (modify model recorder). + +This is a concept called ``DelayTrainer``, which can be used in online simulating for parallel training. +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. + +``Qlib`` offer two kinds of Trainer, ``TrainerR`` is the simplest way and ``TrainerRM`` is based on TaskManager to help manager tasks lifecycle automatically. +""" + +import socket +from typing import Callable, List, Optional + +from tqdm.auto import tqdm + +from qlib.config import C +from qlib.data.dataset import Dataset +from qlib.data.dataset.weight import Reweighter +from qlib.log import get_module_logger +from qlib.model.base import Model +from qlib.utils import ( + auto_filter_kwargs, + fill_placeholder, + flatten_dict, + init_instance_by_config, +) +from qlib.utils.paral import call_in_subproc +from qlib.workflow import R +from qlib.workflow.recorder import Recorder +from qlib.workflow.task.manage import TaskManager, run_task + + +def _log_task_info(task_config: dict): + R.log_params(**flatten_dict(task_config)) + R.save_objects(**{"task": task_config}) # keep the original format and datatype + R.set_tags(**{"hostname": socket.gethostname()}) + + +def _exe_task(task_config: dict): + rec = R.get_recorder() + # model & dataset initialization + model: Model = init_instance_by_config(task_config["model"], accept_types=Model) + dataset: Dataset = init_instance_by_config(task_config["dataset"], accept_types=Dataset) + reweighter: Reweighter = task_config.get("reweighter", None) + # model training + auto_filter_kwargs(model.fit)(dataset, reweighter=reweighter) + R.save_objects(**{"params.pkl": model}) + # this dataset is saved for online inference. So the concrete data should not be dumped + dataset.config(dump_all=False, recursive=True) + R.save_objects(**{"dataset": dataset}) + # fill placehorder + placehorder_value = {"": model, "": dataset} + task_config = fill_placeholder(task_config, placehorder_value) + # generate records: prediction, backtest, and analysis + records = task_config.get("record", []) + if isinstance(records, dict): # prevent only one dict + records = [records] + for record in records: + # Some recorder require the parameter `model` and `dataset`. + # try to automatically pass in them to the initialization function + # to make defining the tasking easier + r = init_instance_by_config( + record, + recorder=rec, + default_module="qlib.workflow.record_temp", + try_kwargs={"model": model, "dataset": dataset}, + ) + r.generate() + + +def begin_task_train(task_config: dict, experiment_name: str, recorder_name: str = None) -> Recorder: + """ + Begin task training to start a recorder and save the task config. + + Args: + task_config (dict): the config of a task + experiment_name (str): the name of experiment + recorder_name (str): the given name will be the recorder name. None for using rid. + + Returns: + Recorder: the model recorder + """ + with R.start(experiment_name=experiment_name, recorder_name=recorder_name): + _log_task_info(task_config) + return R.get_recorder() + + +def end_task_train(rec: Recorder, experiment_name: str) -> Recorder: + """ + Finish task training with real model fitting and saving. + + Args: + rec (Recorder): the recorder will be resumed + experiment_name (str): the name of experiment + + Returns: + Recorder: the model recorder + """ + with R.start(experiment_name=experiment_name, recorder_id=rec.info["id"], resume=True): + task_config = R.load_object("task") + _exe_task(task_config) + return rec + + +def task_train(task_config: dict, experiment_name: str, recorder_name: str = None) -> Recorder: + """ + Task based training, will be divided into two steps. + + Parameters + ---------- + task_config : dict + The config of a task. + experiment_name: str + The name of experiment + recorder_name: str + The name of recorder + + Returns + ---------- + Recorder: The instance of the recorder + """ + with R.start(experiment_name=experiment_name, recorder_name=recorder_name): + _log_task_info(task_config) + _exe_task(task_config) + return R.get_recorder() + + +class Trainer: + """ + The trainer can train a list of models. + There are Trainer and DelayTrainer, which can be distinguished by when it will finish real training. + """ + + def __init__(self): + self.delay = False + + def train(self, tasks: list, *args, **kwargs) -> list: + """ + Given a list of task definitions, begin training, and return the models. + + For Trainer, it finishes real training in this method. + For DelayTrainer, it only does some preparation in this method. + + Args: + tasks: a list of tasks + + Returns: + list: a list of models + """ + raise NotImplementedError(f"Please implement the `train` method.") + + def end_train(self, models: list, *args, **kwargs) -> list: + """ + Given a list of models, finished something at the end of training if you need. + The models may be Recorder, txt file, database, and so on. + + For Trainer, it does some finishing touches in this method. + For DelayTrainer, it finishes real training in this method. + + Args: + models: a list of models + + Returns: + list: a list of models + """ + # do nothing if you finished all work in `train` method + return models + + def is_delay(self) -> bool: + """ + If Trainer will delay finishing `end_train`. + + Returns: + bool: if DelayTrainer + """ + return self.delay + + def __call__(self, *args, **kwargs) -> list: + return self.end_train(self.train(*args, **kwargs)) + + def has_worker(self) -> bool: + """ + Some trainer has backend worker to support parallel training + This method can tell if the worker is enabled. + + Returns + ------- + bool: + if the worker is enabled + + """ + return False + + def worker(self): + """ + start the worker + + Raises + ------ + NotImplementedError: + If the worker is not supported + """ + raise NotImplementedError(f"Please implement the `worker` method") + + +class TrainerR(Trainer): + """ + Trainer based on (R)ecorder. + It will train a list of tasks and return a list of model recorders in a linear way. + + Assumption: models were defined by `task` and the results will be saved to `Recorder`. + """ + + # Those tag will help you distinguish whether the Recorder has finished traning + STATUS_KEY = "train_status" + STATUS_BEGIN = "begin_task_train" + STATUS_END = "end_task_train" + + def __init__( + self, + experiment_name: Optional[str] = None, + train_func: Callable = task_train, + call_in_subproc: bool = False, + default_rec_name: Optional[str] = None, + ): + """ + Init TrainerR. + + Args: + experiment_name (str, optional): the default name of experiment. + train_func (Callable, optional): default training method. Defaults to `task_train`. + call_in_subproc (bool): call the process in subprocess to force memory release + """ + super().__init__() + self.experiment_name = experiment_name + self.default_rec_name = default_rec_name + self.train_func = train_func + self._call_in_subproc = call_in_subproc + + def train( + self, tasks: list, train_func: Optional[Callable] = None, experiment_name: Optional[str] = None, **kwargs + ) -> List[Recorder]: + """ + Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed. + + Args: + tasks (list): a list of definitions based on `task` dict + train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method. + experiment_name (str): the experiment name, None for use default name. + kwargs: the params for train_func. + + Returns: + List[Recorder]: a list of Recorders + """ + if isinstance(tasks, dict): + tasks = [tasks] + if len(tasks) == 0: + return [] + if train_func is None: + train_func = self.train_func + if experiment_name is None: + experiment_name = self.experiment_name + recs = [] + for task in tqdm(tasks, desc="train tasks"): + if self._call_in_subproc: + get_module_logger("TrainerR").info("running models in sub process (for forcing release memroy).") + train_func = call_in_subproc(train_func, C) + rec = train_func(task, experiment_name, recorder_name=self.default_rec_name, **kwargs) + rec.set_tags(**{self.STATUS_KEY: self.STATUS_BEGIN}) + recs.append(rec) + return recs + + def end_train(self, models: list, **kwargs) -> List[Recorder]: + """ + Set STATUS_END tag to the recorders. + + Args: + models (list): a list of trained recorders. + + Returns: + List[Recorder]: the same list as the param. + """ + if isinstance(models, Recorder): + models = [models] + for rec in models: + rec.set_tags(**{self.STATUS_KEY: self.STATUS_END}) + return models + + +class DelayTrainerR(TrainerR): + """ + 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. + """ + + def __init__( + self, experiment_name: str = None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs + ): + """ + Init TrainerRM. + + Args: + experiment_name (str): the default name of experiment. + train_func (Callable, optional): default train method. Defaults to `begin_task_train`. + end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`. + """ + super().__init__(experiment_name, train_func, **kwargs) + self.end_train_func = end_train_func + self.delay = True + + def end_train(self, models, end_train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]: + """ + Given a list of Recorder and return a list of trained Recorder. + This class will finish real data loading and model fitting. + + Args: + models (list): a list of Recorder, the tasks have been saved to them + 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. + experiment_name (str): the experiment name, None for use default name. + kwargs: the params for end_train_func. + + Returns: + List[Recorder]: a list of Recorders + """ + if isinstance(models, Recorder): + models = [models] + if end_train_func is None: + end_train_func = self.end_train_func + if experiment_name is None: + experiment_name = self.experiment_name + for rec in models: + if rec.list_tags()[self.STATUS_KEY] == self.STATUS_END: + continue + end_train_func(rec, experiment_name, **kwargs) + rec.set_tags(**{self.STATUS_KEY: self.STATUS_END}) + return models + + +class TrainerRM(Trainer): + """ + Trainer based on (R)ecorder and Task(M)anager. + It can train a list of tasks and return a list of model recorders in a multiprocessing way. + + Assumption: `task` will be saved to TaskManager and `task` will be fetched and trained from TaskManager + """ + + # Those tag will help you distinguish whether the Recorder has finished traning + STATUS_KEY = "train_status" + STATUS_BEGIN = "begin_task_train" + STATUS_END = "end_task_train" + + # This tag is the _id in TaskManager to distinguish tasks. + TM_ID = "_id in TaskManager" + + def __init__( + self, + experiment_name: str = None, + task_pool: str = None, + train_func=task_train, + skip_run_task: bool = False, + default_rec_name: Optional[str] = None, + ): + """ + Init TrainerR. + + Args: + experiment_name (str): the default name of experiment. + task_pool (str): task pool name in TaskManager. None for use same name as experiment_name. + train_func (Callable, optional): default training method. Defaults to `task_train`. + skip_run_task (bool): + If skip_run_task == True: + Only run_task in the worker. Otherwise skip run_task. + """ + + super().__init__() + self.experiment_name = experiment_name + self.task_pool = task_pool + self.train_func = train_func + self.skip_run_task = skip_run_task + self.default_rec_name = default_rec_name + + def train( + self, + tasks: list, + train_func: Callable = None, + experiment_name: str = None, + before_status: str = TaskManager.STATUS_WAITING, + after_status: str = TaskManager.STATUS_DONE, + default_rec_name: Optional[str] = None, + **kwargs, + ) -> List[Recorder]: + """ + Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed. + + This method defaults to a single process, but TaskManager offered a great way to parallel training. + Users can customize their train_func to realize multiple processes or even multiple machines. + + Args: + tasks (list): a list of definitions based on `task` dict + train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method. + experiment_name (str): the experiment name, None for use default name. + before_status (str): the tasks in before_status will be fetched and trained. Can be STATUS_WAITING, STATUS_PART_DONE. + after_status (str): the tasks after trained will become after_status. Can be STATUS_WAITING, STATUS_PART_DONE. + kwargs: the params for train_func. + + Returns: + List[Recorder]: a list of Recorders + """ + if isinstance(tasks, dict): + tasks = [tasks] + if len(tasks) == 0: + return [] + if train_func is None: + train_func = self.train_func + if experiment_name is None: + experiment_name = self.experiment_name + if default_rec_name is None: + default_rec_name = self.default_rec_name + task_pool = self.task_pool + if task_pool is None: + task_pool = experiment_name + tm = TaskManager(task_pool=task_pool) + _id_list = tm.create_task(tasks) # all tasks will be saved to MongoDB + query = {"_id": {"$in": _id_list}} + if not self.skip_run_task: + run_task( + train_func, + task_pool, + query=query, # only train these tasks + experiment_name=experiment_name, + before_status=before_status, + after_status=after_status, + recorder_name=default_rec_name, + **kwargs, + ) + + if not self.is_delay(): + tm.wait(query=query) + + recs = [] + for _id in _id_list: + rec = tm.re_query(_id)["res"] + rec.set_tags(**{self.STATUS_KEY: self.STATUS_BEGIN}) + rec.set_tags(**{self.TM_ID: _id}) + recs.append(rec) + return recs + + def end_train(self, recs: list, **kwargs) -> List[Recorder]: + """ + Set STATUS_END tag to the recorders. + + Args: + recs (list): a list of trained recorders. + + Returns: + List[Recorder]: the same list as the param. + """ + if isinstance(recs, Recorder): + recs = [recs] + for rec in recs: + rec.set_tags(**{self.STATUS_KEY: self.STATUS_END}) + return recs + + def worker( + self, + train_func: Callable = None, + experiment_name: str = None, + ): + """ + The multiprocessing method for `train`. It can share a same task_pool with `train` and can run in other progress or other machines. + + Args: + train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method. + experiment_name (str): the experiment name, None for use default name. + """ + if train_func is None: + train_func = self.train_func + if experiment_name is None: + experiment_name = self.experiment_name + task_pool = self.task_pool + if task_pool is None: + task_pool = experiment_name + run_task(train_func, task_pool=task_pool, experiment_name=experiment_name) + + def has_worker(self) -> bool: + return True + + +class DelayTrainerRM(TrainerRM): + """ + 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. + + """ + + def __init__( + self, + experiment_name: str = None, + task_pool: str = None, + train_func=begin_task_train, + end_train_func=end_task_train, + skip_run_task: bool = False, + **kwargs, + ): + """ + Init DelayTrainerRM. + + Args: + experiment_name (str): the default name of experiment. + task_pool (str): task pool name in TaskManager. None for use same name as experiment_name. + train_func (Callable, optional): default train method. Defaults to `begin_task_train`. + end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`. + skip_run_task (bool): + If skip_run_task == True: + Only run_task in the worker. Otherwise skip run_task. + E.g. Starting trainer on a CPU VM and then waiting tasks to be finished on GPU VMs. + """ + super().__init__(experiment_name, task_pool, train_func, **kwargs) + self.end_train_func = end_train_func + self.delay = True + self.skip_run_task = skip_run_task + + def train(self, tasks: list, train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]: + """ + Same as `train` of TrainerRM, after_status will be STATUS_PART_DONE. + + Args: + tasks (list): a list of definition based on `task` dict + train_func (Callable): the train method which need at least `tasks` and `experiment_name`. Defaults to None for using self.train_func. + experiment_name (str): the experiment name, None for use default name. + + Returns: + List[Recorder]: a list of Recorders + """ + if isinstance(tasks, dict): + tasks = [tasks] + if len(tasks) == 0: + return [] + _skip_run_task = self.skip_run_task + self.skip_run_task = False # The task preparation can't be skipped + res = super().train( + tasks, + train_func=train_func, + experiment_name=experiment_name, + after_status=TaskManager.STATUS_PART_DONE, + **kwargs, + ) + self.skip_run_task = _skip_run_task + return res + + def end_train(self, recs, end_train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]: + """ + Given a list of Recorder and return a list of trained Recorder. + This class will finish real data loading and model fitting. + + Args: + recs (list): a list of Recorder, the tasks have been saved to them. + 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. + experiment_name (str): the experiment name, None for use default name. + kwargs: the params for end_train_func. + + Returns: + List[Recorder]: a list of Recorders + """ + if isinstance(recs, Recorder): + recs = [recs] + if end_train_func is None: + end_train_func = self.end_train_func + if experiment_name is None: + experiment_name = self.experiment_name + task_pool = self.task_pool + if task_pool is None: + task_pool = experiment_name + _id_list = [] + for rec in recs: + _id_list.append(rec.list_tags()[self.TM_ID]) + + query = {"_id": {"$in": _id_list}} + if not self.skip_run_task: + run_task( + end_train_func, + task_pool, + query=query, # only train these tasks + experiment_name=experiment_name, + before_status=TaskManager.STATUS_PART_DONE, + **kwargs, + ) + + TaskManager(task_pool=task_pool).wait(query=query) + + for rec in recs: + rec.set_tags(**{self.STATUS_KEY: self.STATUS_END}) + return recs + + def worker(self, end_train_func=None, experiment_name: str = None): + """ + 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. + + Args: + 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. + experiment_name (str): the experiment name, None for use default name. + """ + if end_train_func is None: + end_train_func = self.end_train_func + if experiment_name is None: + experiment_name = self.experiment_name + task_pool = self.task_pool + if task_pool is None: + task_pool = experiment_name + run_task( + end_train_func, + task_pool=task_pool, + experiment_name=experiment_name, + before_status=TaskManager.STATUS_PART_DONE, + ) + + def has_worker(self) -> bool: + return True diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..10eeb945e7beb8d577f4b4fd26539910cda99b16 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/model/utils.py @@ -0,0 +1,26 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from torch.utils.data import Dataset + + +class ConcatDataset(Dataset): + def __init__(self, *datasets): + self.datasets = datasets + + def __getitem__(self, i): + return tuple(d[i] for d in self.datasets) + + def __len__(self): + return min(len(d) for d in self.datasets) + + +class IndexSampler: + def __init__(self, sampler): + self.sampler = sampler + + def __getitem__(self, i: int): + return self.sampler[i], i + + def __len__(self): + return len(self.sampler) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a12afc399605270821047b55244bf7eabbb81633 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from .interpreter import Interpreter, StateInterpreter, ActionInterpreter +from .reward import Reward, RewardCombination +from .simulator import Simulator + +__all__ = ["Interpreter", "StateInterpreter", "ActionInterpreter", "Reward", "RewardCombination", "Simulator"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/aux_info.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/aux_info.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd581544e10312128ef1c91cfe837b467fcf443 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/aux_info.py @@ -0,0 +1,43 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Generic, Optional, TypeVar + +from qlib.typehint import final + +from .simulator import StateType + +if TYPE_CHECKING: + from .utils.env_wrapper import EnvWrapper + + +__all__ = ["AuxiliaryInfoCollector"] + +AuxInfoType = TypeVar("AuxInfoType") + + +class AuxiliaryInfoCollector(Generic[StateType, AuxInfoType]): + """Override this class to collect customized auxiliary information from environment.""" + + env: Optional[EnvWrapper] = None + + @final + def __call__(self, simulator_state: StateType) -> AuxInfoType: + return self.collect(simulator_state) + + def collect(self, simulator_state: StateType) -> AuxInfoType: + """Override this for customized auxiliary info. + Usually useful in Multi-agent RL. + + Parameters + ---------- + simulator_state + Retrieved with ``simulator.get_state()``. + + Returns + ------- + Auxiliary information. + """ + raise NotImplementedError("collect is not implemented!") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/backtest.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/backtest.py new file mode 100644 index 0000000000000000000000000000000000000000..60602c10d3cf5ad557a714cea9a127049f28e64e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/backtest.py @@ -0,0 +1,384 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +import argparse +import copy +import os +import pickle +from collections import defaultdict +from pathlib import Path +from typing import Dict, List, Optional, Tuple, Union, cast + +import numpy as np +import pandas as pd +import torch +from joblib import Parallel, delayed + +from qlib.backtest import INDICATOR_METRIC, collect_data_loop, get_strategy_executor +from qlib.backtest.decision import BaseTradeDecision, Order, OrderDir, TradeRangeByTime +from qlib.backtest.executor import SimulatorExecutor +from qlib.backtest.high_performance_ds import BaseOrderIndicator +from qlib.rl.contrib.naive_config_parser import get_backtest_config_fromfile +from qlib.rl.contrib.utils import read_order_file +from qlib.rl.data.integration import init_qlib +from qlib.rl.order_execution.simulator_qlib import SingleAssetOrderExecution +from qlib.typehint import Literal + + +def _get_multi_level_executor_config( + strategy_config: dict, + cash_limit: float | None = None, + generate_report: bool = False, + data_granularity: str = "1min", +) -> dict: + executor_config = { + "class": "SimulatorExecutor", + "module_path": "qlib.backtest.executor", + "kwargs": { + "time_per_step": data_granularity, + "verbose": False, + "trade_type": SimulatorExecutor.TT_PARAL if cash_limit is not None else SimulatorExecutor.TT_SERIAL, + "generate_report": generate_report, + "track_data": True, + }, + } + + freqs = list(strategy_config.keys()) + freqs.sort(key=pd.Timedelta) + for freq in freqs: + executor_config = { + "class": "NestedExecutor", + "module_path": "qlib.backtest.executor", + "kwargs": { + "time_per_step": freq, + "inner_strategy": strategy_config[freq], + "inner_executor": executor_config, + "track_data": True, + }, + } + + return executor_config + + +def _convert_indicator_to_dataframe(indicator: dict) -> Optional[pd.DataFrame]: + record_list = [] + for time, value_dict in indicator.items(): + if isinstance(value_dict, BaseOrderIndicator): + # HACK: for qlib v0.8 + value_dict = value_dict.to_series() + try: + value_dict = copy.deepcopy(value_dict) + if value_dict["ffr"].empty: + continue + except Exception: + value_dict = {k: v for k, v in value_dict.items() if k != "pa"} + value_dict = pd.DataFrame(value_dict) + value_dict["datetime"] = time + record_list.append(value_dict) + + if not record_list: + return None + + records: pd.DataFrame = pd.concat(record_list, 0).reset_index().rename(columns={"index": "instrument"}) + records = records.set_index(["instrument", "datetime"]) + return records + + +def _generate_report( + decisions: List[BaseTradeDecision], + report_indicators: List[INDICATOR_METRIC], +) -> Dict[str, Tuple[pd.DataFrame, pd.DataFrame]]: + """Generate backtest reports + + Parameters + ---------- + decisions: + List of trade decisions. + report_indicators + List of indicator reports. + Returns + ------- + + """ + indicator_dict: Dict[str, List[pd.DataFrame]] = defaultdict(list) + indicator_his: Dict[str, List[dict]] = defaultdict(list) + + for report_indicator in report_indicators: + for key, (indicator_df, indicator_obj) in report_indicator.items(): + indicator_dict[key].append(indicator_df) + indicator_his[key].append(indicator_obj.order_indicator_his) + + report = {} + decision_details = pd.concat([getattr(d, "details") for d in decisions if hasattr(d, "details")]) + for key in indicator_dict: + cur_dict = pd.concat(indicator_dict[key]) + cur_his = pd.concat([_convert_indicator_to_dataframe(his) for his in indicator_his[key]]) + cur_details = decision_details[decision_details.freq == key].set_index(["instrument", "datetime"]) + if len(cur_details) > 0: + cur_details.pop("freq") + cur_his = cur_his.join(cur_details, how="outer") + + report[key] = (cur_dict, cur_his) + + return report + + +def single_with_simulator( + backtest_config: dict, + orders: pd.DataFrame, + split: Literal["stock", "day"] = "stock", + cash_limit: float | None = None, + generate_report: bool = False, +) -> Union[Tuple[pd.DataFrame, dict], pd.DataFrame]: + """Run backtest in a single thread with SingleAssetOrderExecution simulator. The orders will be executed day by day. + A new simulator will be created and used for every single-day order. + + Parameters + ---------- + backtest_config: + Backtest config + orders: + Orders to be executed. Example format: + datetime instrument amount direction + 0 2020-06-01 INST 600.0 0 + 1 2020-06-02 INST 700.0 1 + ... + split + Method to split orders. If it is "stock", split orders by stock. If it is "day", split orders by date. + cash_limit + Limitation of cash. + generate_report + Whether to generate reports. + + Returns + ------- + If generate_report is True, return execution records and the generated report. Otherwise, return only records. + """ + init_qlib(backtest_config["qlib"]) + + stocks = orders.instrument.unique().tolist() + + reports = [] + decisions = [] + for _, row in orders.iterrows(): + date = pd.Timestamp(row["datetime"]) + start_time = pd.Timestamp(backtest_config["start_time"]).replace(year=date.year, month=date.month, day=date.day) + end_time = pd.Timestamp(backtest_config["end_time"]).replace(year=date.year, month=date.month, day=date.day) + order = Order( + stock_id=row["instrument"], + amount=row["amount"], + direction=OrderDir(row["direction"]), + start_time=start_time, + end_time=end_time, + ) + + executor_config = _get_multi_level_executor_config( + strategy_config=backtest_config["strategies"], + cash_limit=cash_limit, + generate_report=generate_report, + data_granularity=backtest_config["data_granularity"], + ) + + exchange_config = copy.deepcopy(backtest_config["exchange"]) + exchange_config.update( + { + "codes": stocks, + "freq": backtest_config["data_granularity"], + } + ) + + simulator = SingleAssetOrderExecution( + order=order, + executor_config=executor_config, + exchange_config=exchange_config, + qlib_config=None, + cash_limit=None, + ) + + reports.append(simulator.report_dict) + decisions += simulator.decisions + + indicator_1day_objs = [report["indicator_dict"]["1day"][1] for report in reports] + indicator_info = {k: v for obj in indicator_1day_objs for k, v in obj.order_indicator_his.items()} + records = _convert_indicator_to_dataframe(indicator_info) + assert records is None or not np.isnan(records["ffr"]).any() + + if generate_report: + _report = _generate_report(decisions, [report["indicator"] for report in reports]) + + if split == "stock": + stock_id = orders.iloc[0].instrument + report = {stock_id: _report} + else: + day = orders.iloc[0].datetime + report = {day: _report} + + return records, report + else: + return records + + +def single_with_collect_data_loop( + backtest_config: dict, + orders: pd.DataFrame, + split: Literal["stock", "day"] = "stock", + cash_limit: float | None = None, + generate_report: bool = False, +) -> Union[Tuple[pd.DataFrame, dict], pd.DataFrame]: + """Run backtest in a single thread with collect_data_loop. + + Parameters + ---------- + backtest_config: + Backtest config + orders: + Orders to be executed. Example format: + datetime instrument amount direction + 0 2020-06-01 INST 600.0 0 + 1 2020-06-02 INST 700.0 1 + ... + split + Method to split orders. If it is "stock", split orders by stock. If it is "day", split orders by date. + cash_limit + Limitation of cash. + generate_report + Whether to generate reports. + + Returns + ------- + If generate_report is True, return execution records and the generated report. Otherwise, return only records. + """ + + init_qlib(backtest_config["qlib"]) + + trade_start_time = orders["datetime"].min() + trade_end_time = orders["datetime"].max() + stocks = orders.instrument.unique().tolist() + + strategy_config = { + "class": "FileOrderStrategy", + "module_path": "qlib.contrib.strategy.rule_strategy", + "kwargs": { + "file": orders, + "trade_range": TradeRangeByTime( + pd.Timestamp(backtest_config["start_time"]).time(), + pd.Timestamp(backtest_config["end_time"]).time(), + ), + }, + } + + executor_config = _get_multi_level_executor_config( + strategy_config=backtest_config["strategies"], + cash_limit=cash_limit, + generate_report=generate_report, + data_granularity=backtest_config["data_granularity"], + ) + + exchange_config = copy.deepcopy(backtest_config["exchange"]) + exchange_config.update( + { + "codes": stocks, + "freq": backtest_config["data_granularity"], + } + ) + + strategy, executor = get_strategy_executor( + start_time=pd.Timestamp(trade_start_time), + end_time=pd.Timestamp(trade_end_time) + pd.DateOffset(1), + strategy=strategy_config, + executor=executor_config, + benchmark=None, + account=cash_limit if cash_limit is not None else int(1e12), + exchange_kwargs=exchange_config, + pos_type="Position" if cash_limit is not None else "InfPosition", + ) + + report_dict: dict = {} + decisions = list(collect_data_loop(trade_start_time, trade_end_time, strategy, executor, report_dict)) + + indicator_dict = cast(INDICATOR_METRIC, report_dict.get("indicator_dict")) + records = _convert_indicator_to_dataframe(indicator_dict["1day"][1].order_indicator_his) + assert records is None or not np.isnan(records["ffr"]).any() + + if generate_report: + _report = _generate_report(decisions, [indicator_dict]) + if split == "stock": + stock_id = orders.iloc[0].instrument + report = {stock_id: _report} + else: + day = orders.iloc[0].datetime + report = {day: _report} + return records, report + else: + return records + + +def backtest(backtest_config: dict, with_simulator: bool = False) -> pd.DataFrame: + order_df = read_order_file(backtest_config["order_file"]) + + cash_limit = backtest_config["exchange"].pop("cash_limit") + generate_report = backtest_config.pop("generate_report") + + stock_pool = order_df["instrument"].unique().tolist() + stock_pool.sort() + + single = single_with_simulator if with_simulator else single_with_collect_data_loop + mp_config = {"n_jobs": backtest_config["concurrency"], "verbose": 10, "backend": "multiprocessing"} + torch.set_num_threads(1) # https://github.com/pytorch/pytorch/issues/17199 + res = Parallel(**mp_config)( + delayed(single)( + backtest_config=backtest_config, + orders=order_df[order_df["instrument"] == stock].copy(), + split="stock", + cash_limit=cash_limit, + generate_report=generate_report, + ) + for stock in stock_pool + ) + + output_path = Path(backtest_config["output_dir"]) + if generate_report: + with (output_path / "report.pkl").open("wb") as f: + report = {} + for r in res: + report.update(r[1]) + pickle.dump(report, f) + res = pd.concat([r[0] for r in res], 0) + else: + res = pd.concat(res) + + if not output_path.exists(): + os.makedirs(output_path) + + if "pa" in res.columns: + res["pa"] = res["pa"] * 10000.0 # align with training metrics + res.to_csv(output_path / "backtest_result.csv") + return res + + +if __name__ == "__main__": + import warnings + + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=RuntimeWarning) + + parser = argparse.ArgumentParser() + parser.add_argument("--config_path", type=str, required=True, help="Path to the config file") + parser.add_argument("--use_simulator", action="store_true", help="Whether to use simulator as the backend") + parser.add_argument( + "--n_jobs", + type=int, + required=False, + help="The number of jobs for running backtest parallely(1 for single process)", + ) + args = parser.parse_args() + + config = get_backtest_config_fromfile(args.config_path) + if args.n_jobs is not None: + config["concurrency"] = args.n_jobs + + backtest( + backtest_config=config, + with_simulator=args.use_simulator, + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/naive_config_parser.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/naive_config_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..3b8d3912f28dbc26d926e71929a293eec8669251 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/naive_config_parser.py @@ -0,0 +1,106 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import os +import platform +import shutil +import sys +import tempfile +from importlib import import_module +from ruamel.yaml import YAML + +DELETE_KEY = "_delete_" + + +def merge_a_into_b(a: dict, b: dict) -> dict: + b = b.copy() + for k, v in a.items(): + if isinstance(v, dict) and k in b: + v.pop(DELETE_KEY, False) + b[k] = merge_a_into_b(v, b[k]) + else: + b[k] = v + return b + + +def check_file_exist(filename: str, msg_tmpl: str = 'file "{}" does not exist') -> None: + if not os.path.isfile(filename): + raise FileNotFoundError(msg_tmpl.format(filename)) + + +def parse_backtest_config(path: str) -> dict: + abs_path = os.path.abspath(path) + check_file_exist(abs_path) + + file_ext_name = os.path.splitext(abs_path)[1] + if file_ext_name not in (".py", ".json", ".yaml", ".yml"): + raise IOError("Only py/yml/yaml/json type are supported now!") + + with tempfile.TemporaryDirectory() as tmp_config_dir: + with tempfile.NamedTemporaryFile(dir=tmp_config_dir, suffix=file_ext_name) as tmp_config_file: + if platform.system() == "Windows": + tmp_config_file.close() + + tmp_config_name = os.path.basename(tmp_config_file.name) + shutil.copyfile(abs_path, tmp_config_file.name) + + if abs_path.endswith(".py"): + tmp_module_name = os.path.splitext(tmp_config_name)[0] + sys.path.insert(0, tmp_config_dir) + module = import_module(tmp_module_name) + sys.path.pop(0) + + config = {k: v for k, v in module.__dict__.items() if not k.startswith("__")} + + del sys.modules[tmp_module_name] + else: + with open(tmp_config_file.name) as input_stream: + yaml = YAML(typ="safe", pure=True) + config = yaml.load(input_stream) + + if "_base_" in config: + base_file_name = config.pop("_base_") + if not isinstance(base_file_name, list): + base_file_name = [base_file_name] + + for f in base_file_name: + base_config = parse_backtest_config(os.path.join(os.path.dirname(abs_path), f)) + config = merge_a_into_b(a=config, b=base_config) + + return config + + +def _convert_all_list_to_tuple(config: dict) -> dict: + for k, v in config.items(): + if isinstance(v, list): + config[k] = tuple(v) + elif isinstance(v, dict): + config[k] = _convert_all_list_to_tuple(v) + return config + + +def get_backtest_config_fromfile(path: str) -> dict: + backtest_config = parse_backtest_config(path) + + exchange_config_default = { + "open_cost": 0.0005, + "close_cost": 0.0015, + "min_cost": 5.0, + "trade_unit": 100.0, + "cash_limit": None, + } + backtest_config["exchange"] = merge_a_into_b(a=backtest_config["exchange"], b=exchange_config_default) + backtest_config["exchange"] = _convert_all_list_to_tuple(backtest_config["exchange"]) + + backtest_config_default = { + "debug_single_stock": None, + "debug_single_day": None, + "concurrency": -1, + "multiplier": 1.0, + "output_dir": "outputs_backtest/", + "generate_report": False, + "data_granularity": "1min", + } + backtest_config = merge_a_into_b(a=backtest_config, b=backtest_config_default) + + return backtest_config diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/train_onpolicy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/train_onpolicy.py new file mode 100644 index 0000000000000000000000000000000000000000..83dd924103fcabc2e0bf8319442e7b40e3432d0a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/train_onpolicy.py @@ -0,0 +1,269 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +import argparse +import os +import random +import sys +import warnings +from pathlib import Path +from ruamel.yaml import YAML +from typing import cast, List, Optional + +import numpy as np +import pandas as pd +import torch +from qlib.backtest import Order +from qlib.backtest.decision import OrderDir +from qlib.constant import ONE_MIN +from qlib.rl.data.native import load_handler_intraday_processed_data +from qlib.rl.interpreter import ActionInterpreter, StateInterpreter +from qlib.rl.order_execution import SingleAssetOrderExecutionSimple +from qlib.rl.reward import Reward +from qlib.rl.trainer import Checkpoint, backtest, train +from qlib.rl.trainer.callbacks import Callback, EarlyStopping, MetricsWriter +from qlib.rl.utils.log import CsvWriter +from qlib.utils import init_instance_by_config +from tianshou.policy import BasePolicy +from torch.utils.data import Dataset + + +def seed_everything(seed: int) -> None: + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + np.random.seed(seed) + random.seed(seed) + torch.backends.cudnn.deterministic = True + + +def _read_orders(order_dir: Path) -> pd.DataFrame: + if os.path.isfile(order_dir): + return pd.read_pickle(order_dir) + else: + orders = [] + for file in order_dir.iterdir(): + order_data = pd.read_pickle(file) + orders.append(order_data) + return pd.concat(orders) + + +class LazyLoadDataset(Dataset): + def __init__( + self, + data_dir: str, + order_file_path: Path, + default_start_time_index: int, + default_end_time_index: int, + ) -> None: + self._default_start_time_index = default_start_time_index + self._default_end_time_index = default_end_time_index + + self._order_df = _read_orders(order_file_path).reset_index() + self._ticks_index: Optional[pd.DatetimeIndex] = None + self._data_dir = Path(data_dir) + + def __len__(self) -> int: + return len(self._order_df) + + def __getitem__(self, index: int) -> Order: + row = self._order_df.iloc[index] + date = pd.Timestamp(str(row["date"])) + + if self._ticks_index is None: + # TODO: We only load ticks index once based on the assumption that ticks index of different dates + # TODO: in one experiment are all the same. If that assumption is not hold, we need to load ticks index + # TODO: of all dates. + + data = load_handler_intraday_processed_data( + data_dir=self._data_dir, + stock_id=row["instrument"], + date=date, + feature_columns_today=[], + feature_columns_yesterday=[], + backtest=True, + index_only=True, + ) + self._ticks_index = [t - date for t in data.today.index] + + order = Order( + stock_id=row["instrument"], + amount=row["amount"], + direction=OrderDir(int(row["order_type"])), + start_time=date + self._ticks_index[self._default_start_time_index], + end_time=date + self._ticks_index[self._default_end_time_index - 1] + ONE_MIN, + ) + + return order + + +def train_and_test( + env_config: dict, + simulator_config: dict, + trainer_config: dict, + data_config: dict, + state_interpreter: StateInterpreter, + action_interpreter: ActionInterpreter, + policy: BasePolicy, + reward: Reward, + run_training: bool, + run_backtest: bool, +) -> None: + order_root_path = Path(data_config["source"]["order_dir"]) + + data_granularity = simulator_config.get("data_granularity", 1) + + def _simulator_factory_simple(order: Order) -> SingleAssetOrderExecutionSimple: + return SingleAssetOrderExecutionSimple( + order=order, + data_dir=data_config["source"]["feature_root_dir"], + feature_columns_today=data_config["source"]["feature_columns_today"], + feature_columns_yesterday=data_config["source"]["feature_columns_yesterday"], + data_granularity=data_granularity, + ticks_per_step=simulator_config["time_per_step"], + vol_threshold=simulator_config["vol_limit"], + ) + + assert data_config["source"]["default_start_time_index"] % data_granularity == 0 + assert data_config["source"]["default_end_time_index"] % data_granularity == 0 + + if run_training: + train_dataset, valid_dataset = [ + LazyLoadDataset( + data_dir=data_config["source"]["feature_root_dir"], + order_file_path=order_root_path / tag, + default_start_time_index=data_config["source"]["default_start_time_index"] // data_granularity, + default_end_time_index=data_config["source"]["default_end_time_index"] // data_granularity, + ) + for tag in ("train", "valid") + ] + + callbacks: List[Callback] = [] + if "checkpoint_path" in trainer_config: + callbacks.append(MetricsWriter(dirpath=Path(trainer_config["checkpoint_path"]))) + callbacks.append( + Checkpoint( + dirpath=Path(trainer_config["checkpoint_path"]) / "checkpoints", + every_n_iters=trainer_config.get("checkpoint_every_n_iters", 1), + save_latest="copy", + ), + ) + if "earlystop_patience" in trainer_config: + callbacks.append( + EarlyStopping( + patience=trainer_config["earlystop_patience"], + monitor="val/pa", + ) + ) + + train( + simulator_fn=_simulator_factory_simple, + state_interpreter=state_interpreter, + action_interpreter=action_interpreter, + policy=policy, + reward=reward, + initial_states=cast(List[Order], train_dataset), + trainer_kwargs={ + "max_iters": trainer_config["max_epoch"], + "finite_env_type": env_config["parallel_mode"], + "concurrency": env_config["concurrency"], + "val_every_n_iters": trainer_config.get("val_every_n_epoch", None), + "callbacks": callbacks, + }, + vessel_kwargs={ + "episode_per_iter": trainer_config["episode_per_collect"], + "update_kwargs": { + "batch_size": trainer_config["batch_size"], + "repeat": trainer_config["repeat_per_collect"], + }, + "val_initial_states": valid_dataset, + }, + ) + + if run_backtest: + test_dataset = LazyLoadDataset( + data_dir=data_config["source"]["feature_root_dir"], + order_file_path=order_root_path / "test", + default_start_time_index=data_config["source"]["default_start_time_index"] // data_granularity, + default_end_time_index=data_config["source"]["default_end_time_index"] // data_granularity, + ) + + backtest( + simulator_fn=_simulator_factory_simple, + state_interpreter=state_interpreter, + action_interpreter=action_interpreter, + initial_states=test_dataset, + policy=policy, + logger=CsvWriter(Path(trainer_config["checkpoint_path"])), + reward=reward, + finite_env_type=env_config["parallel_mode"], + concurrency=env_config["concurrency"], + ) + + +def main(config: dict, run_training: bool, run_backtest: bool) -> None: + if not run_training and not run_backtest: + warnings.warn("Skip the entire job since training and backtest are both skipped.") + return + + if "seed" in config["runtime"]: + seed_everything(config["runtime"]["seed"]) + + for extra_module_path in config["env"].get("extra_module_paths", []): + sys.path.append(extra_module_path) + + state_interpreter: StateInterpreter = init_instance_by_config(config["state_interpreter"]) + action_interpreter: ActionInterpreter = init_instance_by_config(config["action_interpreter"]) + reward: Reward = init_instance_by_config(config["reward"]) + + additional_policy_kwargs = { + "obs_space": state_interpreter.observation_space, + "action_space": action_interpreter.action_space, + } + + # Create torch network + if "network" in config: + if "kwargs" not in config["network"]: + config["network"]["kwargs"] = {} + config["network"]["kwargs"].update({"obs_space": state_interpreter.observation_space}) + additional_policy_kwargs["network"] = init_instance_by_config(config["network"]) + + # Create policy + if "kwargs" not in config["policy"]: + config["policy"]["kwargs"] = {} + config["policy"]["kwargs"].update(additional_policy_kwargs) + policy: BasePolicy = init_instance_by_config(config["policy"]) + + use_cuda = config["runtime"].get("use_cuda", False) + if use_cuda: + policy.cuda() + + train_and_test( + env_config=config["env"], + simulator_config=config["simulator"], + data_config=config["data"], + trainer_config=config["trainer"], + action_interpreter=action_interpreter, + state_interpreter=state_interpreter, + policy=policy, + reward=reward, + run_training=run_training, + run_backtest=run_backtest, + ) + + +if __name__ == "__main__": + warnings.filterwarnings("ignore", category=DeprecationWarning) + warnings.filterwarnings("ignore", category=RuntimeWarning) + + parser = argparse.ArgumentParser() + parser.add_argument("--config_path", type=str, required=True, help="Path to the config file") + parser.add_argument("--no_training", action="store_true", help="Skip training workflow.") + parser.add_argument("--run_backtest", action="store_true", help="Run backtest workflow.") + args = parser.parse_args() + + with open(args.config_path, "r") as input_stream: + yaml = YAML(typ="safe", pure=True) + config = yaml.load(input_stream) + + main(config, run_training=not args.no_training, run_backtest=args.run_backtest) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cad25e0dba611627657d1789b027f0e174067c3f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/contrib/utils.py @@ -0,0 +1,29 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from pathlib import Path + +import pandas as pd + + +def read_order_file(order_file: Path | pd.DataFrame) -> pd.DataFrame: + if isinstance(order_file, pd.DataFrame): + return order_file + + order_file = Path(order_file) + + if order_file.suffix == ".pkl": + order_df = pd.read_pickle(order_file).reset_index() + elif order_file.suffix == ".csv": + order_df = pd.read_csv(order_file) + else: + raise TypeError(f"Unsupported order file type: {order_file}") + + if "date" in order_df.columns: + # legacy dataframe columns + order_df = order_df.rename(columns={"date": "datetime", "order_type": "direction"}) + order_df["datetime"] = order_df["datetime"].astype(str) + + return order_df diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d73517534c83a27e6370796a0669dffca36fa769 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/__init__.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Common utilities to handle ad-hoc-styled data. + +Most of these snippets comes from research project (paper code). +Please take caution when using them in production. +""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e258abe869d74f26f6df7278665f8a7fb85ff09d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/base.py @@ -0,0 +1,65 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +from abc import abstractmethod + +import pandas as pd + + +class BaseIntradayBacktestData: + """ + Raw market data that is often used in backtesting (thus called BacktestData). + + Base class for all types of backtest data. Currently, each type of simulator has its corresponding backtest + data type. + """ + + @abstractmethod + def __repr__(self) -> str: + raise NotImplementedError + + @abstractmethod + def __len__(self) -> int: + raise NotImplementedError + + @abstractmethod + def get_deal_price(self) -> pd.Series: + raise NotImplementedError + + @abstractmethod + def get_volume(self) -> pd.Series: + raise NotImplementedError + + @abstractmethod + def get_time_index(self) -> pd.DatetimeIndex: + raise NotImplementedError + + +class BaseIntradayProcessedData: + """Processed market data after data cleanup and feature engineering. + + It contains both processed data for "today" and "yesterday", as some algorithms + might use the market information of the previous day to assist decision making. + """ + + today: pd.DataFrame + """Processed data for "today". + Number of records must be ``time_length``, and columns must be ``feature_dim``.""" + + yesterday: pd.DataFrame + """Processed data for "yesterday". + Number of records must be ``time_length``, and columns must be ``feature_dim``.""" + + +class ProcessedDataProvider: + """Provider of processed data""" + + def get_data( + self, + stock_id: str, + date: pd.Timestamp, + feature_dim: int, + time_index: pd.Index, + ) -> BaseIntradayProcessedData: + raise NotImplementedError diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/integration.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..e123b6c8cfa5d7aef89235b969ffe1a92c60fc34 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/integration.py @@ -0,0 +1,82 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +TODO: This file is used to integrate NeuTrader with Qlib to run the existing projects. +TODO: The implementation here is kind of adhoc. It is better to design a more uniformed & general implementation. +""" + +from __future__ import annotations + +from pathlib import Path + +import qlib +from qlib.constant import REG_CN +from qlib.contrib.ops.high_freq import BFillNan, Cut, Date, DayCumsum, DayLast, FFillNan, IsInf, IsNull, Select + + +def init_qlib(qlib_config: dict) -> None: + """Initialize necessary resource to launch the workflow, including data direction, feature columns, etc.. + + Parameters + ---------- + qlib_config: + Qlib configuration. + + Example:: + + { + "provider_uri_day": DATA_ROOT_DIR / "qlib_1d", + "provider_uri_1min": DATA_ROOT_DIR / "qlib_1min", + "feature_root_dir": DATA_ROOT_DIR / "qlib_handler_stock", + "feature_columns_today": [ + "$open", "$high", "$low", "$close", "$vwap", "$bid", "$ask", "$volume", + "$bidV", "$bidV1", "$bidV3", "$bidV5", "$askV", "$askV1", "$askV3", "$askV5", + ], + "feature_columns_yesterday": [ + "$open_1", "$high_1", "$low_1", "$close_1", "$vwap_1", "$bid_1", "$ask_1", "$volume_1", + "$bidV_1", "$bidV1_1", "$bidV3_1", "$bidV5_1", "$askV_1", "$askV1_1", "$askV3_1", "$askV5_1", + ], + } + """ + + def _convert_to_path(path: str | Path) -> Path: + return path if isinstance(path, Path) else Path(path) + + provider_uri_map = {} + for granularity in ["1min", "5min", "day"]: + if f"provider_uri_{granularity}" in qlib_config: + provider_uri_map[f"{granularity}"] = _convert_to_path(qlib_config[f"provider_uri_{granularity}"]).as_posix() + + qlib.init( + region=REG_CN, + auto_mount=False, + custom_ops=[DayLast, FFillNan, BFillNan, Date, Select, IsNull, IsInf, Cut, DayCumsum], + expression_cache=None, + calendar_provider={ + "class": "LocalCalendarProvider", + "module_path": "qlib.data.data", + "kwargs": { + "backend": { + "class": "FileCalendarStorage", + "module_path": "qlib.data.storage.file_storage", + "kwargs": {"provider_uri_map": provider_uri_map}, + }, + }, + }, + feature_provider={ + "class": "LocalFeatureProvider", + "module_path": "qlib.data.data", + "kwargs": { + "backend": { + "class": "FileFeatureStorage", + "module_path": "qlib.data.storage.file_storage", + "kwargs": {"provider_uri_map": provider_uri_map}, + }, + }, + }, + provider_uri=provider_uri_map, + kernels=1, + redis_port=-1, + clear_mem_cache=False, # init_qlib will be called for multiple times. Keep the cache for improving performance + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/native.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/native.py new file mode 100644 index 0000000000000000000000000000000000000000..3fdf852ef0b21e7c142dcc5071801afe922a51e2 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/native.py @@ -0,0 +1,234 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +import os +from pathlib import Path +from typing import List, cast + +import cachetools +import pandas as pd + +from qlib.backtest import Exchange, Order +from qlib.backtest.decision import TradeRange, TradeRangeByTime +from qlib.constant import EPS_T +from qlib.utils.pickle_utils import restricted_pickle_load + +from .base import BaseIntradayBacktestData, BaseIntradayProcessedData, ProcessedDataProvider + + +def get_ticks_slice( + ticks_index: pd.DatetimeIndex, + start: pd.Timestamp, + end: pd.Timestamp, + include_end: bool = False, +) -> pd.DatetimeIndex: + if not include_end: + end = end - EPS_T + return ticks_index[ticks_index.slice_indexer(start, end)] + + +class IntradayBacktestData(BaseIntradayBacktestData): + """Backtest data for Qlib simulator""" + + def __init__( + self, + order: Order, + exchange: Exchange, + ticks_index: pd.DatetimeIndex, + ticks_for_order: pd.DatetimeIndex, + ) -> None: + self._order = order + self._exchange = exchange + self._start_time = ticks_for_order[0] + self._end_time = ticks_for_order[-1] + self.ticks_index = ticks_index + self.ticks_for_order = ticks_for_order + + self._deal_price = cast( + pd.Series, + self._exchange.get_deal_price( + self._order.stock_id, + self._start_time, + self._end_time, + direction=self._order.direction, + method=None, + ), + ) + self._volume = cast( + pd.Series, + self._exchange.get_volume( + self._order.stock_id, + self._start_time, + self._end_time, + method=None, + ), + ) + + def __repr__(self) -> str: + return ( + f"Order: {self._order}, Exchange: {self._exchange}, " + f"Start time: {self._start_time}, End time: {self._end_time}" + ) + + def __len__(self) -> int: + return len(self._deal_price) + + def get_deal_price(self) -> pd.Series: + return self._deal_price + + def get_volume(self) -> pd.Series: + return self._volume + + def get_time_index(self) -> pd.DatetimeIndex: + return pd.DatetimeIndex([e[1] for e in list(self._exchange.quote_df.index)]) + + +class DataframeIntradayBacktestData(BaseIntradayBacktestData): + """Backtest data from dataframe""" + + def __init__(self, df: pd.DataFrame, price_column: str = "$close0", volume_column: str = "$volume0") -> None: + self.df = df + self.price_column = price_column + self.volume_column = volume_column + + def __repr__(self) -> str: + with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"): + return f"{self.__class__.__name__}({self.df})" + + def __len__(self) -> int: + return len(self.df) + + def get_deal_price(self) -> pd.Series: + return self.df[self.price_column] + + def get_volume(self) -> pd.Series: + return self.df[self.volume_column] + + def get_time_index(self) -> pd.DatetimeIndex: + return cast(pd.DatetimeIndex, self.df.index) + + +@cachetools.cached( # type: ignore + cache=cachetools.LRUCache(100), + key=lambda order, _, __: order.key_by_day, +) +def load_backtest_data( + order: Order, + trade_exchange: Exchange, + trade_range: TradeRange, +) -> IntradayBacktestData: + ticks_index = pd.DatetimeIndex(trade_exchange.quote_df.reset_index()["datetime"]) + ticks_index = ticks_index[order.start_time <= ticks_index] + ticks_index = ticks_index[ticks_index <= order.end_time] + + if isinstance(trade_range, TradeRangeByTime): + ticks_for_order = get_ticks_slice( + ticks_index, + trade_range.start_time, + trade_range.end_time, + include_end=True, + ) + else: + ticks_for_order = None # FIXME: implement this logic + + backtest_data = IntradayBacktestData( + order=order, + exchange=trade_exchange, + ticks_index=ticks_index, + ticks_for_order=ticks_for_order, + ) + return backtest_data + + +class HandlerIntradayProcessedData(BaseIntradayProcessedData): + """Subclass of IntradayProcessedData. Used to handle handler (bin format) style data.""" + + def __init__( + self, + data_dir: Path, + stock_id: str, + date: pd.Timestamp, + feature_columns_today: List[str], + feature_columns_yesterday: List[str], + backtest: bool = False, + index_only: bool = False, + ) -> None: + def _drop_stock_id(df: pd.DataFrame) -> pd.DataFrame: + df = df.reset_index() + if "instrument" in df.columns: + df = df.drop(columns=["instrument"]) + return df.set_index(["datetime"]) + + path = os.path.join(data_dir, "backtest" if backtest else "feature", f"{stock_id}.pkl") + start_time, end_time = date.replace(hour=0, minute=0, second=0), date.replace(hour=23, minute=59, second=59) + with open(path, "rb") as fstream: + dataset = restricted_pickle_load(fstream) + data = dataset.handler.fetch(pd.IndexSlice[stock_id, start_time:end_time], level=None) + + if index_only: + self.today = _drop_stock_id(data[[]]) + self.yesterday = _drop_stock_id(data[[]]) + else: + self.today = _drop_stock_id(data[feature_columns_today]) + self.yesterday = _drop_stock_id(data[feature_columns_yesterday]) + + def __repr__(self) -> str: + with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"): + return f"{self.__class__.__name__}({self.today}, {self.yesterday})" + + +@cachetools.cached( # type: ignore + cache=cachetools.LRUCache(100), # 100 * 50K = 5MB + key=lambda data_dir, stock_id, date, feature_columns_today, feature_columns_yesterday, backtest, index_only: ( + stock_id, + date, + backtest, + index_only, + ), +) +def load_handler_intraday_processed_data( + data_dir: Path, + stock_id: str, + date: pd.Timestamp, + feature_columns_today: List[str], + feature_columns_yesterday: List[str], + backtest: bool = False, + index_only: bool = False, +) -> HandlerIntradayProcessedData: + return HandlerIntradayProcessedData( + data_dir, stock_id, date, feature_columns_today, feature_columns_yesterday, backtest, index_only + ) + + +class HandlerProcessedDataProvider(ProcessedDataProvider): + def __init__( + self, + data_dir: str, + feature_columns_today: List[str], + feature_columns_yesterday: List[str], + backtest: bool = False, + ) -> None: + super().__init__() + + self.data_dir = Path(data_dir) + self.feature_columns_today = feature_columns_today + self.feature_columns_yesterday = feature_columns_yesterday + self.backtest = backtest + + def get_data( + self, + stock_id: str, + date: pd.Timestamp, + feature_dim: int, + time_index: pd.Index, + ) -> BaseIntradayProcessedData: + return load_handler_intraday_processed_data( + self.data_dir, + stock_id, + date, + self.feature_columns_today, + self.feature_columns_yesterday, + backtest=self.backtest, + index_only=False, + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/pickle_styled.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/pickle_styled.py new file mode 100644 index 0000000000000000000000000000000000000000..4905b026a27c000a508ab30508e8726b562e4bbd --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/data/pickle_styled.py @@ -0,0 +1,296 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""This module contains utilities to read financial data from pickle-styled files. + +This is the format used in `OPD paper `__. NOT the standard data format in qlib. + +The data here are all wrapped with ``@lru_cache``, which saves the expensive IO cost to repetitively read the data. +We also encourage users to use ``get_xxx_yyy`` rather than ``XxxYyy`` (although they are the same thing), +because ``get_xxx_yyy`` is cache-optimized. + +Note that these pickle files are dumped with Python 3.8. Python lower than 3.7 might not be able to load them. +See `PEP 574 `__ for details. + +This file shows resemblence to qlib.backtest.high_performance_ds. We might merge those two in future. +""" + +# TODO: merge with qlib/backtest/high_performance_ds.py + +from __future__ import annotations + +from functools import lru_cache +from pathlib import Path +from typing import List, Sequence, cast + +import cachetools +import numpy as np +import pandas as pd +from cachetools.keys import hashkey + +from qlib.backtest.decision import Order, OrderDir +from qlib.rl.data.base import BaseIntradayBacktestData, BaseIntradayProcessedData, ProcessedDataProvider +from qlib.typehint import Literal + +DealPriceType = Literal["bid_or_ask", "bid_or_ask_fill", "close"] +"""Several ad-hoc deal price. +``bid_or_ask``: If sell, use column ``$bid0``; if buy, use column ``$ask0``. +``bid_or_ask_fill``: Based on ``bid_or_ask``. If price is 0, use another price (``$ask0`` / ``$bid0``) instead. +``close``: Use close price (``$close0``) as deal price. +""" + + +def _infer_processed_data_column_names(shape: int) -> List[str]: + if shape == 16: + return [ + "$open", + "$high", + "$low", + "$close", + "$vwap", + "$bid", + "$ask", + "$volume", + "$bidV", + "$bidV1", + "$bidV3", + "$bidV5", + "$askV", + "$askV1", + "$askV3", + "$askV5", + ] + if shape == 6: + return ["$high", "$low", "$open", "$close", "$vwap", "$volume"] + elif shape == 5: + return ["$high", "$low", "$open", "$close", "$volume"] + raise ValueError(f"Unrecognized data shape: {shape}") + + +def _find_pickle(filename_without_suffix: Path) -> Path: + suffix_list = [".pkl", ".pkl.backtest"] + paths: List[Path] = [] + for suffix in suffix_list: + path = filename_without_suffix.parent / (filename_without_suffix.name + suffix) + if path.exists(): + paths.append(path) + if not paths: + raise FileNotFoundError(f"No file starting with '{filename_without_suffix}' found") + if len(paths) > 1: + raise ValueError(f"Multiple paths are found with prefix '{filename_without_suffix}': {paths}") + return paths[0] + + +@lru_cache(maxsize=10) # 10 * 40M = 400MB +def _read_pickle(filename_without_suffix: Path) -> pd.DataFrame: + df = pd.read_pickle(_find_pickle(filename_without_suffix)) + index_cols = df.index.names + + df = df.reset_index() + for date_col_name in ["date", "datetime"]: + if date_col_name in df: + df[date_col_name] = pd.to_datetime(df[date_col_name]) + df = df.set_index(index_cols) + + return df + + +class SimpleIntradayBacktestData(BaseIntradayBacktestData): + """Backtest data for simple simulator""" + + def __init__( + self, + data_dir: Path | str, + stock_id: str, + date: pd.Timestamp, + deal_price: DealPriceType = "close", + order_dir: int | None = None, + ) -> None: + super(SimpleIntradayBacktestData, self).__init__() + + backtest = _read_pickle((data_dir if isinstance(data_dir, Path) else Path(data_dir)) / stock_id) + backtest = backtest.loc[pd.IndexSlice[stock_id, :, date]] + + # No longer need for pandas >= 1.4 + # backtest = backtest.droplevel([0, 2]) + + self.data: pd.DataFrame = backtest + self.deal_price_type: DealPriceType = deal_price + self.order_dir = order_dir + + def __repr__(self) -> str: + with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"): + return f"{self.__class__.__name__}({self.data})" + + def __len__(self) -> int: + return len(self.data) + + def get_deal_price(self) -> pd.Series: + """Return a pandas series that can be indexed with time. + See :attribute:`DealPriceType` for details.""" + if self.deal_price_type in ("bid_or_ask", "bid_or_ask_fill"): + if self.order_dir is None: + raise ValueError("Order direction cannot be none when deal_price_type is not close.") + if self.order_dir == OrderDir.SELL: + col = "$bid0" + else: # BUY + col = "$ask0" + elif self.deal_price_type == "close": + col = "$close0" + else: + raise ValueError(f"Unsupported deal_price_type: {self.deal_price_type}") + price = self.data[col] + + if self.deal_price_type == "bid_or_ask_fill": + if self.order_dir == OrderDir.SELL: + fill_col = "$ask0" + else: + fill_col = "$bid0" + price = price.replace(0, np.nan).fillna(self.data[fill_col]) + + return price + + def get_volume(self) -> pd.Series: + """Return a volume series that can be indexed with time.""" + return self.data["$volume0"] + + def get_time_index(self) -> pd.DatetimeIndex: + return cast(pd.DatetimeIndex, self.data.index) + + +class PickleIntradayProcessedData(BaseIntradayProcessedData): + """Subclass of IntradayProcessedData. Used to handle pickle-styled data.""" + + def __init__( + self, + data_dir: Path | str, + stock_id: str, + date: pd.Timestamp, + feature_dim: int, + time_index: pd.Index, + ) -> None: + proc = _read_pickle((data_dir if isinstance(data_dir, Path) else Path(data_dir)) / stock_id) + + # We have to infer the names here because, + # unfortunately they are not included in the original data. + cnames = _infer_processed_data_column_names(feature_dim) + + time_length: int = len(time_index) + + try: + # new data format + proc = proc.loc[pd.IndexSlice[stock_id, :, date]] + assert len(proc) == time_length and len(proc.columns) == feature_dim * 2 + proc_today = proc[cnames] + proc_yesterday = proc[[f"{c}_1" for c in cnames]].rename(columns=lambda c: c[:-2]) + except (IndexError, KeyError): + # legacy data + proc = proc.loc[pd.IndexSlice[stock_id, date]] + assert time_length * feature_dim * 2 == len(proc) + proc_today = proc.to_numpy()[: time_length * feature_dim].reshape((time_length, feature_dim)) + proc_yesterday = proc.to_numpy()[time_length * feature_dim :].reshape((time_length, feature_dim)) + proc_today = pd.DataFrame(proc_today, index=time_index, columns=cnames) + proc_yesterday = pd.DataFrame(proc_yesterday, index=time_index, columns=cnames) + + self.today: pd.DataFrame = proc_today + self.yesterday: pd.DataFrame = proc_yesterday + assert len(self.today.columns) == len(self.yesterday.columns) == feature_dim + assert len(self.today) == len(self.yesterday) == time_length + + def __repr__(self) -> str: + with pd.option_context("memory_usage", False, "display.max_info_columns", 1, "display.large_repr", "info"): + return f"{self.__class__.__name__}({self.today}, {self.yesterday})" + + +@lru_cache(maxsize=100) # 100 * 50K = 5MB +def load_simple_intraday_backtest_data( + data_dir: Path, + stock_id: str, + date: pd.Timestamp, + deal_price: DealPriceType = "close", + order_dir: int | None = None, +) -> SimpleIntradayBacktestData: + return SimpleIntradayBacktestData(data_dir, stock_id, date, deal_price, order_dir) + + +@cachetools.cached( # type: ignore + cache=cachetools.LRUCache(100), # 100 * 50K = 5MB + key=lambda data_dir, stock_id, date, feature_dim, time_index: hashkey(data_dir, stock_id, date), +) +def load_pickle_intraday_processed_data( + data_dir: Path, + stock_id: str, + date: pd.Timestamp, + feature_dim: int, + time_index: pd.Index, +) -> BaseIntradayProcessedData: + return PickleIntradayProcessedData(data_dir, stock_id, date, feature_dim, time_index) + + +class PickleProcessedDataProvider(ProcessedDataProvider): + def __init__(self, data_dir: Path) -> None: + super().__init__() + + self._data_dir = data_dir + + def get_data( + self, + stock_id: str, + date: pd.Timestamp, + feature_dim: int, + time_index: pd.Index, + ) -> BaseIntradayProcessedData: + return load_pickle_intraday_processed_data( + data_dir=self._data_dir, + stock_id=stock_id, + date=date, + feature_dim=feature_dim, + time_index=time_index, + ) + + +def load_orders( + order_path: Path, + start_time: pd.Timestamp = None, + end_time: pd.Timestamp = None, +) -> Sequence[Order]: + """Load orders, and set start time and end time for the orders.""" + + start_time = start_time or pd.Timestamp("0:00:00") + end_time = end_time or pd.Timestamp("23:59:59") + + if order_path.is_file(): + order_df = pd.read_pickle(order_path) + else: + order_df = [] + for file in order_path.iterdir(): + order_data = pd.read_pickle(file) + order_df.append(order_data) + order_df = pd.concat(order_df) + + order_df = order_df.reset_index() + + # Legacy-style orders have "date" instead of "datetime" + if "date" in order_df.columns: + order_df = order_df.rename(columns={"date": "datetime"}) + + # Sometimes "date" are str rather than Timestamp + order_df["datetime"] = pd.to_datetime(order_df["datetime"]) + + orders: List[Order] = [] + + for _, row in order_df.iterrows(): + # filter out orders with amount == 0 + if row["amount"] <= 0: + continue + orders.append( + Order( + row["instrument"], + row["amount"], + OrderDir(int(row["order_type"])), + row["datetime"].replace(hour=start_time.hour, minute=start_time.minute, second=start_time.second), + row["datetime"].replace(hour=end_time.hour, minute=end_time.minute, second=end_time.second), + ), + ) + + return orders diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/interpreter.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..5c9cc26c4e628eb35d99d1ff9521fac223a621d5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/interpreter.py @@ -0,0 +1,141 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import Any, Generic, TypeVar + +import gym +import numpy as np +from gym import spaces + +from qlib.typehint import final +from .simulator import ActType, StateType + +ObsType = TypeVar("ObsType") +PolicyActType = TypeVar("PolicyActType") + + +class Interpreter: + """Interpreter is a media between states produced by simulators and states needed by RL policies. + Interpreters are two-way: + + 1. From simulator state to policy state (aka observation), see :class:`StateInterpreter`. + 2. From policy action to action accepted by simulator, see :class:`ActionInterpreter`. + + Inherit one of the two sub-classes to define your own interpreter. + This super-class is only used for isinstance check. + + Interpreters are recommended to be stateless, meaning that storing temporary information with ``self.xxx`` + in interpreter is anti-pattern. In future, we might support register some interpreter-related + states by calling ``self.env.register_state()``, but it's not planned for first iteration. + """ + + +class StateInterpreter(Generic[StateType, ObsType], Interpreter): + """State Interpreter that interpret execution result of qlib executor into rl env state""" + + @property + def observation_space(self) -> gym.Space: + raise NotImplementedError() + + @final # no overridden + def __call__(self, simulator_state: StateType) -> ObsType: + obs = self.interpret(simulator_state) + self.validate(obs) + return obs + + def validate(self, obs: ObsType) -> None: + """Validate whether an observation belongs to the pre-defined observation space.""" + _gym_space_contains(self.observation_space, obs) + + def interpret(self, simulator_state: StateType) -> ObsType: + """Interpret the state of simulator. + + Parameters + ---------- + simulator_state + Retrieved with ``simulator.get_state()``. + + Returns + ------- + State needed by policy. Should conform with the state space defined in ``observation_space``. + """ + raise NotImplementedError("interpret is not implemented!") + + +class ActionInterpreter(Generic[StateType, PolicyActType, ActType], Interpreter): + """Action Interpreter that interpret rl agent action into qlib orders""" + + @property + def action_space(self) -> gym.Space: + raise NotImplementedError() + + @final # no overridden + def __call__(self, simulator_state: StateType, action: PolicyActType) -> ActType: + self.validate(action) + obs = self.interpret(simulator_state, action) + return obs + + def validate(self, action: PolicyActType) -> None: + """Validate whether an action belongs to the pre-defined action space.""" + _gym_space_contains(self.action_space, action) + + def interpret(self, simulator_state: StateType, action: PolicyActType) -> ActType: + """Convert the policy action to simulator action. + + Parameters + ---------- + simulator_state + Retrieved with ``simulator.get_state()``. + action + Raw action given by policy. + + Returns + ------- + The action needed by simulator, + """ + raise NotImplementedError("interpret is not implemented!") + + +def _gym_space_contains(space: gym.Space, x: Any) -> None: + """Strengthened version of gym.Space.contains. + Giving more diagnostic information on why validation fails. + + Throw exception rather than returning true or false. + """ + if isinstance(space, spaces.Dict): + if not isinstance(x, dict) or len(x) != len(space): + raise GymSpaceValidationError("Sample must be a dict with same length as space.", space, x) + for k, subspace in space.spaces.items(): + if k not in x: + raise GymSpaceValidationError(f"Key {k} not found in sample.", space, x) + try: + _gym_space_contains(subspace, x[k]) + except GymSpaceValidationError as e: + raise GymSpaceValidationError(f"Subspace of key {k} validation error.", space, x) from e + + elif isinstance(space, spaces.Tuple): + if isinstance(x, (list, np.ndarray)): + x = tuple(x) # Promote list and ndarray to tuple for contains check + if not isinstance(x, tuple) or len(x) != len(space): + raise GymSpaceValidationError("Sample must be a tuple with same length as space.", space, x) + for i, (subspace, part) in enumerate(zip(space, x)): + try: + _gym_space_contains(subspace, part) + except GymSpaceValidationError as e: + raise GymSpaceValidationError(f"Subspace of index {i} validation error.", space, x) from e + + else: + if not space.contains(x): + raise GymSpaceValidationError("Validation error reported by gym.", space, x) + + +class GymSpaceValidationError(Exception): + def __init__(self, message: str, space: gym.Space, x: Any) -> None: + self.message = message + self.space = space + self.x = x + + def __str__(self) -> str: + return f"{self.message}\n Space: {self.space}\n Sample: {self.x}" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b985c13317bc2ebda7ae471ce4204b72db60e18a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/__init__.py @@ -0,0 +1,38 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +Currently it supports single-asset order execution. +Multi-asset is on the way. +""" + +from .interpreter import ( + FullHistoryStateInterpreter, + CurrentStepStateInterpreter, + CategoricalActionInterpreter, + TwapRelativeActionInterpreter, +) +from .network import Recurrent +from .policy import AllOne, PPO +from .reward import PAPenaltyReward +from .simulator_simple import SingleAssetOrderExecutionSimple +from .state import SAOEMetrics, SAOEState +from .strategy import SAOEStateAdapter, SAOEStrategy, ProxySAOEStrategy, SAOEIntStrategy + +__all__ = [ + "FullHistoryStateInterpreter", + "CurrentStepStateInterpreter", + "CategoricalActionInterpreter", + "TwapRelativeActionInterpreter", + "Recurrent", + "AllOne", + "PPO", + "PAPenaltyReward", + "SingleAssetOrderExecutionSimple", + "SAOEStateAdapter", + "SAOEMetrics", + "SAOEState", + "SAOEStrategy", + "ProxySAOEStrategy", + "SAOEIntStrategy", +] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/interpreter.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..01b08115301bd6285eb40a88be470dc7c8383092 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/interpreter.py @@ -0,0 +1,257 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import math +from typing import Any, List, Optional, cast + +import numpy as np +import pandas as pd +from gym import spaces + +from qlib.constant import EPS +from qlib.rl.data.base import ProcessedDataProvider +from qlib.rl.interpreter import ActionInterpreter, StateInterpreter +from qlib.rl.order_execution.state import SAOEState +from qlib.typehint import TypedDict + +__all__ = [ + "FullHistoryStateInterpreter", + "CurrentStepStateInterpreter", + "CategoricalActionInterpreter", + "TwapRelativeActionInterpreter", + "FullHistoryObs", +] + +from qlib.utils import init_instance_by_config + + +def canonicalize(value: int | float | np.ndarray | pd.DataFrame | dict) -> np.ndarray | dict: + """To 32-bit numeric types. Recursively.""" + if isinstance(value, pd.DataFrame): + return value.to_numpy() + if isinstance(value, (float, np.floating)) or (isinstance(value, np.ndarray) and value.dtype.kind == "f"): + return np.array(value, dtype=np.float32) + elif isinstance(value, (int, bool, np.integer)) or (isinstance(value, np.ndarray) and value.dtype.kind == "i"): + return np.array(value, dtype=np.int32) + elif isinstance(value, dict): + return {k: canonicalize(v) for k, v in value.items()} + else: + return value + + +class FullHistoryObs(TypedDict): + data_processed: Any + data_processed_prev: Any + acquiring: Any + cur_tick: Any + cur_step: Any + num_step: Any + target: Any + position: Any + position_history: Any + + +class DummyStateInterpreter(StateInterpreter[SAOEState, dict]): + """Dummy interpreter for policies that do not need inputs (for example, AllOne).""" + + def interpret(self, state: SAOEState) -> dict: + # TODO: A fake state, used to pass `check_nan_observation`. Find a better way in the future. + return {"DUMMY": _to_int32(1)} + + @property + def observation_space(self) -> spaces.Dict: + return spaces.Dict({"DUMMY": spaces.Box(-np.inf, np.inf, shape=(), dtype=np.int32)}) + + +class FullHistoryStateInterpreter(StateInterpreter[SAOEState, FullHistoryObs]): + """The observation of all the history, including today (until this moment), and yesterday. + + Parameters + ---------- + max_step + Total number of steps (an upper-bound estimation). For example, 390min / 30min-per-step = 13 steps. + data_ticks + Equal to the total number of records. For example, in SAOE per minute, + the total ticks is the length of day in minutes. + data_dim + Number of dimensions in data. + processed_data_provider + Provider of the processed data. + """ + + def __init__( + self, + max_step: int, + data_ticks: int, + data_dim: int, + processed_data_provider: dict | ProcessedDataProvider, + ) -> None: + super().__init__() + + self.max_step = max_step + self.data_ticks = data_ticks + self.data_dim = data_dim + self.processed_data_provider: ProcessedDataProvider = init_instance_by_config( + processed_data_provider, + accept_types=ProcessedDataProvider, + ) + + def interpret(self, state: SAOEState) -> FullHistoryObs: + processed = self.processed_data_provider.get_data( + stock_id=state.order.stock_id, + date=pd.Timestamp(state.order.start_time.date()), + feature_dim=self.data_dim, + time_index=state.ticks_index, + ) + + position_history = np.full(self.max_step + 1, 0.0, dtype=np.float32) + position_history[0] = state.order.amount + position_history[1 : len(state.history_steps) + 1] = state.history_steps["position"].to_numpy() + + # The min, slice here are to make sure that indices fit into the range, + # even after the final step of the simulator (in the done step), + # to make network in policy happy. + return cast( + FullHistoryObs, + canonicalize( + { + "data_processed": np.array(self._mask_future_info(processed.today, state.cur_time)), + "data_processed_prev": np.array(processed.yesterday), + "acquiring": _to_int32(state.order.direction == state.order.BUY), + "cur_tick": _to_int32(min(int(np.sum(state.ticks_index < state.cur_time)), self.data_ticks - 1)), + "cur_step": _to_int32(min(state.cur_step, self.max_step - 1)), + "num_step": _to_int32(self.max_step), + "target": _to_float32(state.order.amount), + "position": _to_float32(state.position), + "position_history": _to_float32(position_history[: self.max_step]), + }, + ), + ) + + @property + def observation_space(self) -> spaces.Dict: + space = { + "data_processed": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)), + "data_processed_prev": spaces.Box(-np.inf, np.inf, shape=(self.data_ticks, self.data_dim)), + "acquiring": spaces.Discrete(2), + "cur_tick": spaces.Box(0, self.data_ticks - 1, shape=(), dtype=np.int32), + "cur_step": spaces.Box(0, self.max_step - 1, shape=(), dtype=np.int32), + # TODO: support arbitrary length index + "num_step": spaces.Box(self.max_step, self.max_step, shape=(), dtype=np.int32), + "target": spaces.Box(-EPS, np.inf, shape=()), + "position": spaces.Box(-EPS, np.inf, shape=()), + "position_history": spaces.Box(-EPS, np.inf, shape=(self.max_step,)), + } + return spaces.Dict(space) + + @staticmethod + def _mask_future_info(arr: pd.DataFrame, current: pd.Timestamp) -> pd.DataFrame: + arr = arr.copy(deep=True) + arr.loc[current:] = 0.0 # mask out data after this moment (inclusive) + return arr + + +class CurrentStateObs(TypedDict): + acquiring: bool + cur_step: int + num_step: int + target: float + position: float + + +class CurrentStepStateInterpreter(StateInterpreter[SAOEState, CurrentStateObs]): + """The observation of current step. + + Used when policy only depends on the latest state, but not history. + The key list is not full. You can add more if more information is needed by your policy. + """ + + def __init__(self, max_step: int) -> None: + super().__init__() + + self.max_step = max_step + + @property + def observation_space(self) -> spaces.Dict: + space = { + "acquiring": spaces.Discrete(2), + "cur_step": spaces.Box(0, self.max_step - 1, shape=(), dtype=np.int32), + "num_step": spaces.Box(self.max_step, self.max_step, shape=(), dtype=np.int32), + "target": spaces.Box(-EPS, np.inf, shape=()), + "position": spaces.Box(-EPS, np.inf, shape=()), + } + return spaces.Dict(space) + + def interpret(self, state: SAOEState) -> CurrentStateObs: + assert state.cur_step <= self.max_step + obs = CurrentStateObs( + acquiring=state.order.direction == state.order.BUY, + cur_step=state.cur_step, + num_step=self.max_step, + target=state.order.amount, + position=state.position, + ) + return obs + + +class CategoricalActionInterpreter(ActionInterpreter[SAOEState, int, float]): + """Convert a discrete policy action to a continuous action, then multiplied by ``order.amount``. + + Parameters + ---------- + values + It can be a list of length $L$: $[a_1, a_2, \\ldots, a_L]$. + Then when policy givens decision $x$, $a_x$ times order amount is the output. + It can also be an integer $n$, in which case the list of length $n+1$ is auto-generated, + i.e., $[0, 1/n, 2/n, \\ldots, n/n]$. + max_step + Total number of steps (an upper-bound estimation). For example, 390min / 30min-per-step = 13 steps. + """ + + def __init__(self, values: int | List[float], max_step: Optional[int] = None) -> None: + super().__init__() + + if isinstance(values, int): + values = [i / values for i in range(0, values + 1)] + self.action_values = values + self.max_step = max_step + + @property + def action_space(self) -> spaces.Discrete: + return spaces.Discrete(len(self.action_values)) + + def interpret(self, state: SAOEState, action: int) -> float: + assert 0 <= action < len(self.action_values) + if self.max_step is not None and state.cur_step >= self.max_step - 1: + return state.position + else: + return min(state.position, state.order.amount * self.action_values[action]) + + +class TwapRelativeActionInterpreter(ActionInterpreter[SAOEState, float, float]): + """Convert a continuous ratio to deal amount. + + The ratio is relative to TWAP on the remainder of the day. + For example, there are 5 steps left, and the left position is 300. + With TWAP strategy, in each position, 60 should be traded. + When this interpreter receives action $a$, its output is $60 \\cdot a$. + """ + + @property + def action_space(self) -> spaces.Box: + return spaces.Box(0, np.inf, shape=(), dtype=np.float32) + + def interpret(self, state: SAOEState, action: float) -> float: + estimated_total_steps = math.ceil(len(state.ticks_for_order) / state.ticks_per_step) + twap_volume = state.position / (estimated_total_steps - state.cur_step) + return min(state.position, twap_volume * action) + + +def _to_int32(val): + return np.array(int(val), dtype=np.int32) + + +def _to_float32(val): + return np.array(val, dtype=np.float32) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/network.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/network.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a11189cff8c3fb35d3ca7f4e5a9450948fa82f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/network.py @@ -0,0 +1,140 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import List, Tuple, cast + +import torch +import torch.nn as nn +from tianshou.data import Batch + +from qlib.typehint import Literal + +from .interpreter import FullHistoryObs + +__all__ = ["Recurrent"] + + +class Recurrent(nn.Module): + """The network architecture proposed in `OPD `_. + + At every time step the input of policy network is divided into two parts, + the public variables and the private variables. which are handled by ``raw_rnn`` + and ``pri_rnn`` in this network, respectively. + + One minor difference is that, in this implementation, we don't assume the direction to be fixed. + Thus, another ``dire_fc`` is added to produce an extra direction-related feature. + """ + + def __init__( + self, + obs_space: FullHistoryObs, + hidden_dim: int = 64, + output_dim: int = 32, + rnn_type: Literal["rnn", "lstm", "gru"] = "gru", + rnn_num_layers: int = 1, + ) -> None: + super().__init__() + + self.hidden_dim = hidden_dim + self.output_dim = output_dim + self.num_sources = 3 + + rnn_classes = {"rnn": nn.RNN, "lstm": nn.LSTM, "gru": nn.GRU} + + self.rnn_class = rnn_classes[rnn_type] + self.rnn_layers = rnn_num_layers + + self.raw_rnn = self.rnn_class(hidden_dim, hidden_dim, batch_first=True, num_layers=self.rnn_layers) + self.prev_rnn = self.rnn_class(hidden_dim, hidden_dim, batch_first=True, num_layers=self.rnn_layers) + self.pri_rnn = self.rnn_class(hidden_dim, hidden_dim, batch_first=True, num_layers=self.rnn_layers) + + self.raw_fc = nn.Sequential(nn.Linear(obs_space["data_processed"].shape[-1], hidden_dim), nn.ReLU()) + self.pri_fc = nn.Sequential(nn.Linear(2, hidden_dim), nn.ReLU()) + self.dire_fc = nn.Sequential(nn.Linear(2, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU()) + + self._init_extra_branches() + + self.fc = nn.Sequential( + nn.Linear(hidden_dim * self.num_sources, hidden_dim), + nn.ReLU(), + nn.Linear(hidden_dim, output_dim), + nn.ReLU(), + ) + + def _init_extra_branches(self) -> None: + pass + + def _source_features(self, obs: FullHistoryObs, device: torch.device) -> Tuple[List[torch.Tensor], torch.Tensor]: + bs, _, data_dim = obs["data_processed"].size() + data = torch.cat((torch.zeros(bs, 1, data_dim, device=device), obs["data_processed"]), 1) + cur_step = obs["cur_step"].long() + cur_tick = obs["cur_tick"].long() + bs_indices = torch.arange(bs, device=device) + + position = obs["position_history"] / obs["target"].unsqueeze(-1) # [bs, num_step] + steps = ( + torch.arange(position.size(-1), device=device).unsqueeze(0).repeat(bs, 1).float() + / obs["num_step"].unsqueeze(-1).float() + ) # [bs, num_step] + priv = torch.stack((position.float(), steps), -1) + + data_in = self.raw_fc(data) + data_out, _ = self.raw_rnn(data_in) + # as it is padded with zero in front, this should be last minute + data_out_slice = data_out[bs_indices, cur_tick] + + priv_in = self.pri_fc(priv) + priv_out = self.pri_rnn(priv_in)[0] + priv_out = priv_out[bs_indices, cur_step] + + sources = [data_out_slice, priv_out] + + dir_out = self.dire_fc(torch.stack((obs["acquiring"], 1 - obs["acquiring"]), -1).float()) + sources.append(dir_out) + + return sources, data_out + + def forward(self, batch: Batch) -> torch.Tensor: + """ + Input should be a dict (at least) containing: + + - data_processed: [N, T, C] + - cur_step: [N] (int) + - cur_time: [N] (int) + - position_history: [N, S] (S is number of steps) + - target: [N] + - num_step: [N] (int) + - acquiring: [N] (0 or 1) + """ + + inp = cast(FullHistoryObs, batch) + device = inp["data_processed"].device + + sources, _ = self._source_features(inp, device) + assert len(sources) == self.num_sources + + out = torch.cat(sources, -1) + return self.fc(out) + + +class Attention(nn.Module): + def __init__(self, in_dim, out_dim): + super().__init__() + self.q_net = nn.Linear(in_dim, out_dim) + self.k_net = nn.Linear(in_dim, out_dim) + self.v_net = nn.Linear(in_dim, out_dim) + + def forward(self, Q, K, V): + q = self.q_net(Q) + k = self.k_net(K) + v = self.v_net(V) + + attn = torch.einsum("ijk,ilk->ijl", q, k) + attn = attn.to(Q.device) + attn_prob = torch.softmax(attn, dim=-1) + + attn_vec = torch.einsum("ijk,ikl->ijl", attn_prob, v) + + return attn_vec diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/policy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a46b587aa1126c92b7e25899a636c0750311dddb --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/policy.py @@ -0,0 +1,237 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from pathlib import Path +from typing import Any, Dict, Generator, Iterable, Optional, OrderedDict, Tuple, cast + +import gym +import numpy as np +import torch +import torch.nn as nn +from gym.spaces import Discrete +from tianshou.data import Batch, ReplayBuffer, to_torch +from tianshou.policy import BasePolicy, PPOPolicy, DQNPolicy + +from qlib.rl.trainer.trainer import Trainer + +__all__ = ["AllOne", "PPO", "DQN"] + + +# baselines # + + +class NonLearnablePolicy(BasePolicy): + """Tianshou's BasePolicy with empty ``learn`` and ``process_fn``. + + This could be moved outside in future. + """ + + def __init__(self, obs_space: gym.Space, action_space: gym.Space) -> None: + super().__init__() + + def learn(self, batch: Batch, **kwargs: Any) -> Dict[str, Any]: + return {} + + def process_fn( + self, + batch: Batch, + buffer: ReplayBuffer, + indices: np.ndarray, + ) -> Batch: + return Batch({}) + + +class AllOne(NonLearnablePolicy): + """Forward returns a batch full of 1. + + Useful when implementing some baselines (e.g., TWAP). + """ + + def __init__(self, obs_space: gym.Space, action_space: gym.Space, fill_value: float | int = 1.0) -> None: + super().__init__(obs_space, action_space) + + self.fill_value = fill_value + + def forward( + self, + batch: Batch, + state: dict | Batch | np.ndarray = None, + **kwargs: Any, + ) -> Batch: + return Batch(act=np.full(len(batch), self.fill_value), state=state) + + +# ppo # + + +class PPOActor(nn.Module): + def __init__(self, extractor: nn.Module, action_dim: int) -> None: + super().__init__() + self.extractor = extractor + self.layer_out = nn.Sequential(nn.Linear(cast(int, extractor.output_dim), action_dim), nn.Softmax(dim=-1)) + + def forward( + self, + obs: torch.Tensor, + state: torch.Tensor = None, + info: dict = {}, + ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]: + feature = self.extractor(to_torch(obs, device=auto_device(self))) + out = self.layer_out(feature) + return out, state + + +class PPOCritic(nn.Module): + def __init__(self, extractor: nn.Module) -> None: + super().__init__() + self.extractor = extractor + self.value_out = nn.Linear(cast(int, extractor.output_dim), 1) + + def forward( + self, + obs: torch.Tensor, + state: torch.Tensor = None, + info: dict = {}, + ) -> torch.Tensor: + feature = self.extractor(to_torch(obs, device=auto_device(self))) + return self.value_out(feature).squeeze(dim=-1) + + +class PPO(PPOPolicy): + """A wrapper of tianshou PPOPolicy. + + Differences: + + - Auto-create actor and critic network. Supports discrete action space only. + - Dedup common parameters between actor network and critic network + (not sure whether this is included in latest tianshou or not). + - Support a ``weight_file`` that supports loading checkpoint. + - Some parameters' default values are different from original. + """ + + def __init__( + self, + network: nn.Module, + obs_space: gym.Space, + action_space: gym.Space, + lr: float, + weight_decay: float = 0.0, + discount_factor: float = 1.0, + max_grad_norm: float = 100.0, + reward_normalization: bool = True, + eps_clip: float = 0.3, + value_clip: bool = True, + vf_coef: float = 1.0, + gae_lambda: float = 1.0, + max_batch_size: int = 256, + deterministic_eval: bool = True, + weight_file: Optional[Path] = None, + ) -> None: + assert isinstance(action_space, Discrete) + actor = PPOActor(network, action_space.n) + critic = PPOCritic(network) + optimizer = torch.optim.Adam( + chain_dedup(actor.parameters(), critic.parameters()), + lr=lr, + weight_decay=weight_decay, + ) + super().__init__( + actor, + critic, + optimizer, + torch.distributions.Categorical, + discount_factor=discount_factor, + max_grad_norm=max_grad_norm, + reward_normalization=reward_normalization, + eps_clip=eps_clip, + value_clip=value_clip, + vf_coef=vf_coef, + gae_lambda=gae_lambda, + max_batchsize=max_batch_size, + deterministic_eval=deterministic_eval, + observation_space=obs_space, + action_space=action_space, + ) + if weight_file is not None: + set_weight(self, Trainer.get_policy_state_dict(weight_file)) + + +DQNModel = PPOActor # Reuse PPOActor. + + +class DQN(DQNPolicy): + """A wrapper of tianshou DQNPolicy. + + Differences: + + - Auto-create model network. Supports discrete action space only. + - Support a ``weight_file`` that supports loading checkpoint. + """ + + def __init__( + self, + network: nn.Module, + obs_space: gym.Space, + action_space: gym.Space, + lr: float, + weight_decay: float = 0.0, + discount_factor: float = 0.99, + estimation_step: int = 1, + target_update_freq: int = 0, + reward_normalization: bool = False, + is_double: bool = True, + clip_loss_grad: bool = False, + weight_file: Optional[Path] = None, + ) -> None: + assert isinstance(action_space, Discrete) + + model = DQNModel(network, action_space.n) + optimizer = torch.optim.Adam( + model.parameters(), + lr=lr, + weight_decay=weight_decay, + ) + + super().__init__( + model, + optimizer, + discount_factor=discount_factor, + estimation_step=estimation_step, + target_update_freq=target_update_freq, + reward_normalization=reward_normalization, + is_double=is_double, + clip_loss_grad=clip_loss_grad, + ) + if weight_file is not None: + set_weight(self, Trainer.get_policy_state_dict(weight_file)) + + +# utilities: these should be put in a separate (common) file. # + + +def auto_device(module: nn.Module) -> torch.device: + for param in module.parameters(): + return param.device + return torch.device("cpu") # fallback to cpu + + +def set_weight(policy: nn.Module, loaded_weight: OrderedDict) -> None: + try: + policy.load_state_dict(loaded_weight) + except RuntimeError: + # try again by loading the converted weight + # https://github.com/thu-ml/tianshou/issues/468 + for k in list(loaded_weight): + loaded_weight["_actor_critic." + k] = loaded_weight[k] + policy.load_state_dict(loaded_weight) + + +def chain_dedup(*iterables: Iterable) -> Generator[Any, None, None]: + seen = set() + for iterable in iterables: + for i in iterable: + if i not in seen: + seen.add(i) + yield i diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/reward.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..0dcfd24bb38e6f494c257253f04c6397f72e64c6 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/reward.py @@ -0,0 +1,99 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import cast + +import numpy as np + +from qlib.backtest.decision import OrderDir +from qlib.rl.order_execution.state import SAOEMetrics, SAOEState +from qlib.rl.reward import Reward + +__all__ = ["PAPenaltyReward"] + + +class PAPenaltyReward(Reward[SAOEState]): + """Encourage higher PAs, but penalize stacking all the amounts within a very short time. + Formally, for each time step, the reward is :math:`(PA_t * vol_t / target - vol_t^2 * penalty)`. + + Parameters + ---------- + penalty + The penalty for large volume in a short time. + scale + The weight used to scale up or down the reward. + """ + + def __init__(self, penalty: float = 100.0, scale: float = 1.0) -> None: + self.penalty = penalty + self.scale = scale + + def reward(self, simulator_state: SAOEState) -> float: + whole_order = simulator_state.order.amount + assert whole_order > 0 + last_step = cast(SAOEMetrics, simulator_state.history_steps.reset_index().iloc[-1].to_dict()) + pa = last_step["pa"] * last_step["amount"] / whole_order + + # Inspect the "break-down" of the latest step: trading amount at every tick + last_step_breakdown = simulator_state.history_exec.loc[last_step["datetime"] :] + penalty = -self.penalty * ((last_step_breakdown["amount"] / whole_order) ** 2).sum() + + reward = pa + penalty + + # Throw error in case of NaN + assert not (np.isnan(reward) or np.isinf(reward)), f"Invalid reward for simulator state: {simulator_state}" + + self.log("reward/pa", pa) + self.log("reward/penalty", penalty) + return reward * self.scale + + +class PPOReward(Reward[SAOEState]): + """Reward proposed by paper "An End-to-End Optimal Trade Execution Framework based on Proximal Policy Optimization". + + Parameters + ---------- + max_step + Maximum number of steps. + start_time_index + First time index that allowed to trade. + end_time_index + Last time index that allowed to trade. + """ + + def __init__(self, max_step: int, start_time_index: int = 0, end_time_index: int = 239) -> None: + self.max_step = max_step + self.start_time_index = start_time_index + self.end_time_index = end_time_index + + def reward(self, simulator_state: SAOEState) -> float: + if simulator_state.cur_step == self.max_step - 1 or simulator_state.position < 1e-6: + if simulator_state.history_exec["deal_amount"].sum() == 0.0: + vwap_price = cast( + float, + np.average(simulator_state.history_exec["market_price"]), + ) + else: + vwap_price = cast( + float, + np.average( + simulator_state.history_exec["market_price"], + weights=simulator_state.history_exec["deal_amount"], + ), + ) + twap_price = simulator_state.backtest_data.get_deal_price().mean() + + if simulator_state.order.direction == OrderDir.SELL: + ratio = vwap_price / twap_price if twap_price != 0 else 1.0 + else: + ratio = twap_price / vwap_price if vwap_price != 0 else 1.0 + if ratio < 1.0: + return -1.0 + elif ratio < 1.1: + return 0.0 + else: + return 1.0 + else: + return 0.0 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/simulator_qlib.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/simulator_qlib.py new file mode 100644 index 0000000000000000000000000000000000000000..1417e2ab4a19f331d5d0d23929ad1f88147a1df6 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/simulator_qlib.py @@ -0,0 +1,141 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import Generator, List, Optional + +import pandas as pd + +from qlib.backtest import collect_data_loop, get_strategy_executor +from qlib.backtest.decision import BaseTradeDecision, Order, TradeRangeByTime +from qlib.backtest.executor import NestedExecutor +from qlib.rl.data.integration import init_qlib +from qlib.rl.simulator import Simulator +from .state import SAOEState +from .strategy import SAOEStateAdapter, SAOEStrategy + + +class SingleAssetOrderExecution(Simulator[Order, SAOEState, float]): + """Single-asset order execution (SAOE) simulator which is implemented based on Qlib backtest tools. + + Parameters + ---------- + order + The seed to start an SAOE simulator is an order. + executor_config + Executor configuration + exchange_config + Exchange configuration + qlib_config + Configuration used to initialize Qlib. If it is None, Qlib will not be initialized. + cash_limit: + Cash limit. + """ + + def __init__( + self, + order: Order, + executor_config: dict, + exchange_config: dict, + qlib_config: dict | None = None, + cash_limit: float | None = None, + ) -> None: + super().__init__(initial=order) + + assert order.start_time.date() == order.end_time.date(), "Start date and end date must be the same." + + strategy_config = { + "class": "SingleOrderStrategy", + "module_path": "qlib.rl.strategy.single_order", + "kwargs": { + "order": order, + "trade_range": TradeRangeByTime(order.start_time.time(), order.end_time.time()), + }, + } + + self._collect_data_loop: Optional[Generator] = None + self.reset(order, strategy_config, executor_config, exchange_config, qlib_config, cash_limit) + + def reset( + self, + order: Order, + strategy_config: dict, + executor_config: dict, + exchange_config: dict, + qlib_config: dict | None = None, + cash_limit: Optional[float] = None, + ) -> None: + if qlib_config is not None: + init_qlib(qlib_config) + + strategy, self._executor = get_strategy_executor( + start_time=order.date, + end_time=order.date + pd.DateOffset(1), + strategy=strategy_config, + executor=executor_config, + benchmark=order.stock_id, + account=cash_limit if cash_limit is not None else int(1e12), + exchange_kwargs=exchange_config, + pos_type="Position" if cash_limit is not None else "InfPosition", + ) + + assert isinstance(self._executor, NestedExecutor) + + self.report_dict: dict = {} + self.decisions: List[BaseTradeDecision] = [] + self._collect_data_loop = collect_data_loop( + start_time=order.date, + end_time=order.date, + trade_strategy=strategy, + trade_executor=self._executor, + return_value=self.report_dict, + ) + assert isinstance(self._collect_data_loop, Generator) + + self.step(action=None) + + self._order = order + + def _get_adapter(self) -> SAOEStateAdapter: + return self._last_yielded_saoe_strategy.adapter_dict[self._order.key_by_day] + + @property + def twap_price(self) -> float: + return self._get_adapter().twap_price + + def _iter_strategy(self, action: Optional[float] = None) -> SAOEStrategy: + """Iterate the _collect_data_loop until we get the next yield SAOEStrategy.""" + assert self._collect_data_loop is not None + + obj = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action) + while not isinstance(obj, SAOEStrategy): + if isinstance(obj, BaseTradeDecision): + self.decisions.append(obj) + obj = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action) + assert isinstance(obj, SAOEStrategy) + return obj + + def step(self, action: Optional[float]) -> None: + """Execute one step or SAOE. + + Parameters + ---------- + action (float): + The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt. + """ + + assert not self.done(), "Simulator has already done!" + + try: + self._last_yielded_saoe_strategy = self._iter_strategy(action=action) + except StopIteration: + pass + + assert self._executor is not None + + def get_state(self) -> SAOEState: + return self._get_adapter().saoe_state + + def done(self) -> bool: + return self._executor.finished() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/simulator_simple.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/simulator_simple.py new file mode 100644 index 0000000000000000000000000000000000000000..48aa03a17072c163884215a2df613c8ca4afc3ea --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/simulator_simple.py @@ -0,0 +1,362 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import Any, cast, List, Optional + +import numpy as np +import pandas as pd + +from pathlib import Path +from qlib.backtest.decision import Order, OrderDir +from qlib.constant import EPS, EPS_T, float_or_ndarray +from qlib.rl.data.base import BaseIntradayBacktestData +from qlib.rl.data.native import DataframeIntradayBacktestData, load_handler_intraday_processed_data +from qlib.rl.data.pickle_styled import load_simple_intraday_backtest_data +from qlib.rl.simulator import Simulator +from qlib.rl.utils import LogLevel +from .state import SAOEMetrics, SAOEState + +__all__ = ["SingleAssetOrderExecutionSimple"] + + +class SingleAssetOrderExecutionSimple(Simulator[Order, SAOEState, float]): + """Single-asset order execution (SAOE) simulator. + + As there's no "calendar" in the simple simulator, ticks are used to trade. + A tick is a record (a line) in the pickle-styled data file. + Each tick is considered as a individual trading opportunity. + If such fine granularity is not needed, use ``ticks_per_step`` to + lengthen the ticks for each step. + + In each step, the traded amount are "equally" separated to each tick, + then bounded by volume maximum execution volume (i.e., ``vol_threshold``), + and if it's the last step, try to ensure all the amount to be executed. + + Parameters + ---------- + order + The seed to start an SAOE simulator is an order. + data_dir + Path to load backtest data. + feature_columns_today + Columns of today's feature. + feature_columns_yesterday + Columns of yesterday's feature. + data_granularity + Number of ticks between consecutive data entries. + ticks_per_step + How many ticks per step. + vol_threshold + Maximum execution volume (divided by market execution volume). + """ + + history_exec: pd.DataFrame + """All execution history at every possible time ticks. See :class:`SAOEMetrics` for available columns. + Index is ``datetime``. + """ + + history_steps: pd.DataFrame + """Positions at each step. The position before first step is also recorded. + See :class:`SAOEMetrics` for available columns. + Index is ``datetime``, which is the **starting** time of each step.""" + + metrics: Optional[SAOEMetrics] + """Metrics. Only available when done.""" + + twap_price: float + """This price is used to compute price advantage. + It"s defined as the average price in the period from order"s start time to end time.""" + + ticks_index: pd.DatetimeIndex + """All available ticks for the day (not restricted to order).""" + + ticks_for_order: pd.DatetimeIndex + """Ticks that is available for trading (sliced by order).""" + + def __init__( + self, + order: Order, + data_dir: Path, + feature_columns_today: List[str] = [], + feature_columns_yesterday: List[str] = [], + data_granularity: int = 1, + ticks_per_step: int = 30, + vol_threshold: Optional[float] = None, + ) -> None: + super().__init__(initial=order) + + assert ticks_per_step % data_granularity == 0 + + self.order = order + self.data_dir = data_dir + self.feature_columns_today = feature_columns_today + self.feature_columns_yesterday = feature_columns_yesterday + self.ticks_per_step: int = ticks_per_step // data_granularity + self.vol_threshold = vol_threshold + + self.backtest_data = self.get_backtest_data() + self.ticks_index = self.backtest_data.get_time_index() + + # Get time index available for trading + self.ticks_for_order = self._get_ticks_slice(self.order.start_time, self.order.end_time) + + self.cur_time = self.ticks_for_order[0] + self.cur_step = 0 + # NOTE: astype(float) is necessary in some systems. + # this will align the precision with `.to_numpy()` in `_split_exec_vol` + self.twap_price = float(self.backtest_data.get_deal_price().loc[self.ticks_for_order].astype(float).mean()) + + self.position = order.amount + + metric_keys = list(SAOEMetrics.__annotations__.keys()) # pylint: disable=no-member + # NOTE: can empty dataframe contain index? + self.history_exec = pd.DataFrame(columns=metric_keys).set_index("datetime") + self.history_steps = pd.DataFrame(columns=metric_keys).set_index("datetime") + self.metrics = None + + self.market_price: Optional[np.ndarray] = None + self.market_vol: Optional[np.ndarray] = None + self.market_vol_limit: Optional[np.ndarray] = None + + def get_backtest_data(self) -> BaseIntradayBacktestData: + try: + data = load_handler_intraday_processed_data( + data_dir=self.data_dir, + stock_id=self.order.stock_id, + date=pd.Timestamp(self.order.start_time.date()), + feature_columns_today=self.feature_columns_today, + feature_columns_yesterday=self.feature_columns_yesterday, + backtest=True, + index_only=False, + ) + return DataframeIntradayBacktestData(data.today) + except (AttributeError, FileNotFoundError): + # TODO: For compatibility with older versions of test scripts (tests/rl/test_saoe_simple.py) + # TODO: In the future, we should modify the data format used by the test script, + # TODO: and then delete this branch. + return load_simple_intraday_backtest_data( + self.data_dir / "backtest", + self.order.stock_id, + pd.Timestamp(self.order.start_time.date()), + "close", + self.order.direction, + ) + + def step(self, amount: float) -> None: + """Execute one step or SAOE. + + Parameters + ---------- + amount + The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt. + """ + + assert not self.done() + + self.market_price = self.market_vol = None # avoid misuse + exec_vol = self._split_exec_vol(amount) + assert self.market_price is not None + assert self.market_vol is not None + + ticks_position = self.position - np.cumsum(exec_vol) + + self.position -= exec_vol.sum() + if abs(self.position) < 1e-6: + self.position = 0.0 + if self.position < -EPS or (exec_vol < -EPS).any(): + raise ValueError(f"Execution volume is invalid: {exec_vol} (position = {self.position})") + + # Get time index available for this step + time_index = self._get_ticks_slice(self.cur_time, self._next_time()) + + self.history_exec = self._dataframe_append( + self.history_exec, + SAOEMetrics( + # It should have the same keys with SAOEMetrics, + # but the values do not necessarily have the annotated type. + # Some values could be vectorized (e.g., exec_vol). + stock_id=self.order.stock_id, + datetime=time_index, + direction=self.order.direction, + market_volume=self.market_vol, + market_price=self.market_price, + amount=exec_vol, + inner_amount=exec_vol, + deal_amount=exec_vol, + trade_price=self.market_price, + trade_value=self.market_price * exec_vol, + position=ticks_position, + ffr=exec_vol / self.order.amount, + pa=price_advantage(self.market_price, self.twap_price, self.order.direction), + ), + ) + + self.history_steps = self._dataframe_append( + self.history_steps, + [self._metrics_collect(self.cur_time, self.market_vol, self.market_price, amount, exec_vol)], + ) + + if self.done(): + if self.env is not None: + self.env.logger.add_any("history_steps", self.history_steps, loglevel=LogLevel.DEBUG) + self.env.logger.add_any("history_exec", self.history_exec, loglevel=LogLevel.DEBUG) + + self.metrics = self._metrics_collect( + self.ticks_index[0], # start time + self.history_exec["market_volume"], + self.history_exec["market_price"], + self.history_steps["amount"].sum(), + self.history_exec["deal_amount"], + ) + + # NOTE (yuge): It looks to me that it's the "correct" decision to + # put all the logs here, because only components like simulators themselves + # have the knowledge about what could appear in the logs, and what's the format. + # But I admit it's not necessarily the most convenient way. + # I'll rethink about it when we have the second environment + # Maybe some APIs like self.logger.enable_auto_log() ? + + if self.env is not None: + for key, value in self.metrics.items(): + if isinstance(value, float): + self.env.logger.add_scalar(key, value) + else: + self.env.logger.add_any(key, value) + + self.cur_time = self._next_time() + self.cur_step += 1 + + def get_state(self) -> SAOEState: + return SAOEState( + order=self.order, + cur_time=self.cur_time, + cur_step=self.cur_step, + position=self.position, + history_exec=self.history_exec, + history_steps=self.history_steps, + metrics=self.metrics, + backtest_data=self.backtest_data, + ticks_per_step=self.ticks_per_step, + ticks_index=self.ticks_index, + ticks_for_order=self.ticks_for_order, + ) + + def done(self) -> bool: + return self.position < EPS or self.cur_time >= self.order.end_time + + def _next_time(self) -> pd.Timestamp: + """The "current time" (``cur_time``) for next step.""" + # Look for next time on time index + current_loc = self.ticks_index.get_loc(self.cur_time) + next_loc = current_loc + self.ticks_per_step + + # Calibrate the next location to multiple of ticks_per_step. + # This is to make sure that: + # as long as ticks_per_step is a multiple of something, each step won't cross morning and afternoon. + next_loc = next_loc - next_loc % self.ticks_per_step + + if next_loc < len(self.ticks_index) and self.ticks_index[next_loc] < self.order.end_time: + return self.ticks_index[next_loc] + else: + return self.order.end_time + + def _cur_duration(self) -> pd.Timedelta: + """The "duration" of this step (step that is about to happen).""" + return self._next_time() - self.cur_time + + def _split_exec_vol(self, exec_vol_sum: float) -> np.ndarray: + """ + Split the volume in each step into minutes, considering possible constraints. + This follows TWAP strategy. + """ + next_time = self._next_time() + + # get the backtest data for next interval + self.market_vol = self.backtest_data.get_volume().loc[self.cur_time : next_time - EPS_T].to_numpy() + self.market_price = self.backtest_data.get_deal_price().loc[self.cur_time : next_time - EPS_T].to_numpy() + + assert self.market_vol is not None and self.market_price is not None + + # split the volume equally into each minute + exec_vol = np.repeat(exec_vol_sum / len(self.market_price), len(self.market_price)) + + # apply the volume threshold + market_vol_limit = self.vol_threshold * self.market_vol if self.vol_threshold is not None else np.inf + exec_vol = np.minimum(exec_vol, market_vol_limit) # type: ignore + + # Complete all the order amount at the last moment. + if next_time >= self.order.end_time: + exec_vol[-1] += self.position - exec_vol.sum() + exec_vol = np.minimum(exec_vol, market_vol_limit) # type: ignore + + return exec_vol + + def _metrics_collect( + self, + datetime: pd.Timestamp, + market_vol: np.ndarray, + market_price: np.ndarray, + amount: float, # intended to trade such amount + exec_vol: np.ndarray, + ) -> SAOEMetrics: + assert len(market_vol) == len(market_price) == len(exec_vol) + + if np.abs(np.sum(exec_vol)) < EPS: + exec_avg_price = 0.0 + else: + exec_avg_price = cast(float, np.average(market_price, weights=exec_vol)) # could be nan + if hasattr(exec_avg_price, "item"): # could be numpy scalar + exec_avg_price = exec_avg_price.item() # type: ignore + + return SAOEMetrics( + stock_id=self.order.stock_id, + datetime=datetime, + direction=self.order.direction, + market_volume=market_vol.sum(), + market_price=market_price.mean(), + amount=amount, + inner_amount=exec_vol.sum(), + deal_amount=exec_vol.sum(), # in this simulator, there's no other restrictions + trade_price=exec_avg_price, + trade_value=float(np.sum(market_price * exec_vol)), + position=self.position, + ffr=float(exec_vol.sum() / self.order.amount), + pa=price_advantage(exec_avg_price, self.twap_price, self.order.direction), + ) + + def _get_ticks_slice(self, start: pd.Timestamp, end: pd.Timestamp, include_end: bool = False) -> pd.DatetimeIndex: + if not include_end: + end = end - EPS_T + return self.ticks_index[self.ticks_index.slice_indexer(start, end)] + + @staticmethod + def _dataframe_append(df: pd.DataFrame, other: Any) -> pd.DataFrame: + # dataframe.append is deprecated + other_df = pd.DataFrame(other).set_index("datetime") + other_df.index.name = "datetime" + return pd.concat([df, other_df], axis=0) + + +def price_advantage( + exec_price: float_or_ndarray, + baseline_price: float, + direction: OrderDir | int, +) -> float_or_ndarray: + if baseline_price == 0: # something is wrong with data. Should be nan here + if isinstance(exec_price, float): + return 0.0 + else: + return np.zeros_like(exec_price) + if direction == OrderDir.BUY: + res = (1 - exec_price / baseline_price) * 10000 + elif direction == OrderDir.SELL: + res = (exec_price / baseline_price - 1) * 10000 + else: + raise ValueError(f"Unexpected order direction: {direction}") + res_wo_nan: np.ndarray = np.nan_to_num(res, nan=0.0) + if res_wo_nan.size == 1: + return res_wo_nan.item() + else: + return cast(float_or_ndarray, res_wo_nan) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/state.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/state.py new file mode 100644 index 0000000000000000000000000000000000000000..315735eaf8431ab262e2249ee26f11ec90bd7dd9 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/state.py @@ -0,0 +1,101 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import typing +from typing import NamedTuple, Optional + +import numpy as np +import pandas as pd +from qlib.backtest import Order +from qlib.typehint import TypedDict + +if typing.TYPE_CHECKING: + from qlib.rl.data.base import BaseIntradayBacktestData + + +class SAOEMetrics(TypedDict): + """Metrics for SAOE accumulated for a "period". + It could be accumulated for a day, or a period of time (e.g., 30min), or calculated separately for every minute. + + Warnings + -------- + The type hints are for single elements. In lots of times, they can be vectorized. + For example, ``market_volume`` could be a list of float (or ndarray) rather tahn a single float. + """ + + stock_id: str + """Stock ID of this record.""" + datetime: pd.Timestamp | pd.DatetimeIndex + """Datetime of this record (this is index in the dataframe).""" + direction: int + """Direction of the order. 0 for sell, 1 for buy.""" + + # Market information. + market_volume: np.ndarray | float + """(total) market volume traded in the period.""" + market_price: np.ndarray | float + """Deal price. If it's a period of time, this is the average market deal price.""" + + # Strategy records. + + amount: np.ndarray | float + """Total amount (volume) strategy intends to trade.""" + inner_amount: np.ndarray | float + """Total amount that the lower-level strategy intends to trade + (might be larger than amount, e.g., to ensure ffr).""" + + deal_amount: np.ndarray | float + """Amount that successfully takes effect (must be less than inner_amount).""" + trade_price: np.ndarray | float + """The average deal price for this strategy.""" + trade_value: np.ndarray | float + """Total worth of trading. In the simple simulation, trade_value = deal_amount * price.""" + position: np.ndarray | float + """Position left after this "period".""" + + # Accumulated metrics + + ffr: np.ndarray | float + """Completed how much percent of the daily order.""" + + pa: np.ndarray | float + """Price advantage compared to baseline (i.e., trade with baseline market price). + The baseline is trade price when using TWAP strategy to execute this order. + Please note that there could be data leak here). + Unit is BP (basis point, 1/10000).""" + + +class SAOEState(NamedTuple): + """Data structure holding a state for SAOE simulator.""" + + order: Order + """The order we are dealing with.""" + cur_time: pd.Timestamp + """Current time, e.g., 9:30.""" + cur_step: int + """Current step, e.g., 0.""" + position: float + """Current remaining volume to execute.""" + history_exec: pd.DataFrame + """See :attr:`SingleAssetOrderExecution.history_exec`.""" + history_steps: pd.DataFrame + """See :attr:`SingleAssetOrderExecution.history_steps`.""" + + metrics: Optional[SAOEMetrics] + """Daily metric, only available when the trading is in "done" state.""" + + backtest_data: BaseIntradayBacktestData + """Backtest data is included in the state. + Actually, only the time index of this data is needed, at this moment. + I include the full data so that algorithms (e.g., VWAP) that relies on the raw data can be implemented. + Interpreter can use this as they wish, but they should be careful not to leak future data. + """ + + ticks_per_step: int + """How many ticks for each step.""" + ticks_index: pd.DatetimeIndex + """Trading ticks in all day, NOT sliced by order (defined in data). e.g., [9:30, 9:31, ..., 14:59].""" + ticks_for_order: pd.DatetimeIndex + """Trading ticks sliced by order, e.g., [9:45, 9:46, ..., 14:44].""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/strategy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..7e66a1f0851ca0ee8cffd8cea306339d9b6f9c9e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/strategy.py @@ -0,0 +1,551 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import collections +from types import GeneratorType +from typing import Any, Callable, cast, Dict, Generator, List, Optional, Tuple, Union + +import warnings +import numpy as np +import pandas as pd +import torch +from tianshou.data import Batch +from tianshou.policy import BasePolicy + +from qlib.backtest import CommonInfrastructure, Order +from qlib.backtest.decision import BaseTradeDecision, TradeDecisionWithDetails, TradeDecisionWO, TradeRange +from qlib.backtest.exchange import Exchange +from qlib.backtest.executor import BaseExecutor +from qlib.backtest.utils import LevelInfrastructure, get_start_end_idx +from qlib.constant import EPS, ONE_MIN, REG_CN +from qlib.rl.data.native import IntradayBacktestData, load_backtest_data +from qlib.rl.interpreter import ActionInterpreter, StateInterpreter +from qlib.rl.order_execution.state import SAOEMetrics, SAOEState +from qlib.rl.order_execution.utils import dataframe_append, price_advantage +from qlib.strategy.base import RLStrategy +from qlib.utils import init_instance_by_config +from qlib.utils.index_data import IndexData +from qlib.utils.time import get_day_min_idx_range + + +def _get_all_timestamps( + start: pd.Timestamp, + end: pd.Timestamp, + granularity: pd.Timedelta = ONE_MIN, + include_end: bool = True, +) -> pd.DatetimeIndex: + ret = [] + while start <= end: + ret.append(start) + start += granularity + + if ret[-1] > end: + ret.pop() + if ret[-1] == end and not include_end: + ret.pop() + return pd.DatetimeIndex(ret) + + +def fill_missing_data( + original_data: np.ndarray, + fill_method: Callable = np.nanmedian, +) -> np.ndarray: + """Fill missing data. + + Parameters + ---------- + original_data + Original data without missing values. + fill_method + Method used to fill the missing data. + + Returns + ------- + The filled data. + """ + return np.nan_to_num(original_data, nan=fill_method(original_data)) + + +class SAOEStateAdapter: + """ + Maintain states of the environment. SAOEStateAdapter accepts execution results and update its internal state + according to the execution results with additional information acquired from executors & exchange. For example, + it gets the dealt order amount from execution results, and get the corresponding market price / volume from + exchange. + + Example usage:: + + adapter = SAOEStateAdapter(...) + adapter.update(...) + state = adapter.saoe_state + """ + + def __init__( + self, + order: Order, + trade_decision: BaseTradeDecision, + executor: BaseExecutor, + exchange: Exchange, + ticks_per_step: int, + backtest_data: IntradayBacktestData, + data_granularity: int = 1, + ) -> None: + self.position = order.amount + self.order = order + self.executor = executor + self.exchange = exchange + self.backtest_data = backtest_data + self.start_idx, _ = get_start_end_idx(self.executor.trade_calendar, trade_decision) + + self.twap_price = self.backtest_data.get_deal_price().mean() + + metric_keys = list(SAOEMetrics.__annotations__.keys()) # pylint: disable=no-member + self.history_exec = pd.DataFrame(columns=metric_keys).set_index("datetime") + self.history_steps = pd.DataFrame(columns=metric_keys).set_index("datetime") + self.metrics: Optional[SAOEMetrics] = None + + self.cur_time = max(backtest_data.ticks_for_order[0], order.start_time) + self.ticks_per_step = ticks_per_step + self.data_granularity = data_granularity + assert self.ticks_per_step % self.data_granularity == 0 + + def _next_time(self) -> pd.Timestamp: + current_loc = self.backtest_data.ticks_index.get_loc(self.cur_time) + next_loc = current_loc + (self.ticks_per_step // self.data_granularity) + next_loc = next_loc - next_loc % (self.ticks_per_step // self.data_granularity) + if ( + next_loc < len(self.backtest_data.ticks_index) + and self.backtest_data.ticks_index[next_loc] < self.order.end_time + ): + return self.backtest_data.ticks_index[next_loc] + else: + return self.order.end_time + + def update( + self, + execute_result: list, + last_step_range: Tuple[int, int], + ) -> None: + last_step_size = last_step_range[1] - last_step_range[0] + 1 + start_time = self.backtest_data.ticks_index[last_step_range[0]] + end_time = self.backtest_data.ticks_index[last_step_range[1]] + + exec_vol = np.zeros(last_step_size) + for order, _, __, ___ in execute_result: + idx, _ = get_day_min_idx_range(order.start_time, order.end_time, f"{self.data_granularity}min", REG_CN) + exec_vol[idx - last_step_range[0]] = order.deal_amount + + if exec_vol.sum() > self.position and exec_vol.sum() > 0.0: + if exec_vol.sum() > self.position + 1.0: + warnings.warn( + f"Sum of execution volume is {exec_vol.sum()} which is larger than " + f"position + 1.0 = {self.position} + 1.0 = {self.position + 1.0}. " + f"All execution volume is scaled down linearly to ensure that their sum does not position." + ) + exec_vol *= self.position / (exec_vol.sum()) + + market_volume = cast( + IndexData, + self.exchange.get_volume( + self.order.stock_id, + pd.Timestamp(start_time), + pd.Timestamp(end_time), + method=None, + ), + ) + market_price = cast( + IndexData, + self.exchange.get_deal_price( + self.order.stock_id, + pd.Timestamp(start_time), + pd.Timestamp(end_time), + method=None, + direction=self.order.direction, + ), + ) + market_price = fill_missing_data(np.array(market_price, dtype=float).reshape(-1)) + market_volume = fill_missing_data(np.array(market_volume, dtype=float).reshape(-1)) + + assert market_price.shape == market_volume.shape == exec_vol.shape + + # Get data from the current level executor's indicator + current_trade_account = self.executor.trade_account + current_df = current_trade_account.get_trade_indicator().generate_trade_indicators_dataframe() + self.history_exec = dataframe_append( + self.history_exec, + self._collect_multi_order_metric( + order=self.order, + datetime=_get_all_timestamps( + start_time, end_time, include_end=True, granularity=ONE_MIN * self.data_granularity + ), + market_vol=market_volume, + market_price=market_price, + exec_vol=exec_vol, + pa=current_df.iloc[-1]["pa"], + ), + ) + + self.history_steps = dataframe_append( + self.history_steps, + [ + self._collect_single_order_metric( + self.order, + self.cur_time, + market_volume, + market_price, + exec_vol.sum(), + exec_vol, + ), + ], + ) + + # Do this at the end + self.position -= exec_vol.sum() + + self.cur_time = self._next_time() + + def generate_metrics_after_done(self) -> None: + """Generate metrics once the upper level execution is done""" + + self.metrics = self._collect_single_order_metric( + self.order, + self.backtest_data.ticks_index[0], # start time + self.history_exec["market_volume"], + self.history_exec["market_price"], + self.history_steps["amount"].sum(), + self.history_exec["deal_amount"], + ) + + def _collect_multi_order_metric( + self, + order: Order, + datetime: pd.DatetimeIndex, + market_vol: np.ndarray, + market_price: np.ndarray, + exec_vol: np.ndarray, + pa: float, + ) -> SAOEMetrics: + return SAOEMetrics( + # It should have the same keys with SAOEMetrics, + # but the values do not necessarily have the annotated type. + # Some values could be vectorized (e.g., exec_vol). + stock_id=order.stock_id, + datetime=datetime, + direction=order.direction, + market_volume=market_vol, + market_price=market_price, + amount=exec_vol, + inner_amount=exec_vol, + deal_amount=exec_vol, + trade_price=market_price, + trade_value=market_price * exec_vol, + position=self.position - np.cumsum(exec_vol), + ffr=exec_vol / order.amount, + pa=pa, + ) + + def _collect_single_order_metric( + self, + order: Order, + datetime: pd.Timestamp, + market_vol: np.ndarray, + market_price: np.ndarray, + amount: float, # intended to trade such amount + exec_vol: np.ndarray, + ) -> SAOEMetrics: + assert len(market_vol) == len(market_price) == len(exec_vol) + + if np.abs(np.sum(exec_vol)) < EPS: + exec_avg_price = 0.0 + else: + exec_avg_price = cast(float, np.average(market_price, weights=exec_vol)) # could be nan + if hasattr(exec_avg_price, "item"): # could be numpy scalar + exec_avg_price = exec_avg_price.item() # type: ignore + + exec_sum = exec_vol.sum() + return SAOEMetrics( + stock_id=order.stock_id, + datetime=datetime, + direction=order.direction, + market_volume=market_vol.sum(), + market_price=market_price.mean() if len(market_price) > 0 else np.nan, + amount=amount, + inner_amount=exec_sum, + deal_amount=exec_sum, # in this simulator, there's no other restrictions + trade_price=exec_avg_price, + trade_value=float(np.sum(market_price * exec_vol)), + position=self.position - exec_sum, + ffr=float(exec_sum / order.amount), + pa=price_advantage(exec_avg_price, self.twap_price, order.direction), + ) + + @property + def saoe_state(self) -> SAOEState: + return SAOEState( + order=self.order, + cur_time=self.cur_time, + cur_step=self.executor.trade_calendar.get_trade_step() - self.start_idx, + position=self.position, + history_exec=self.history_exec, + history_steps=self.history_steps, + metrics=self.metrics, + backtest_data=self.backtest_data, + ticks_per_step=self.ticks_per_step, + ticks_index=self.backtest_data.ticks_index, + ticks_for_order=self.backtest_data.ticks_for_order, + ) + + +class SAOEStrategy(RLStrategy): + """RL-based strategies that use SAOEState as state.""" + + def __init__( + self, + policy: BasePolicy, + outer_trade_decision: BaseTradeDecision | None = None, + level_infra: LevelInfrastructure | None = None, + common_infra: CommonInfrastructure | None = None, + data_granularity: int = 1, + **kwargs: Any, + ) -> None: + super(SAOEStrategy, self).__init__( + policy=policy, + outer_trade_decision=outer_trade_decision, + level_infra=level_infra, + common_infra=common_infra, + **kwargs, + ) + + self._data_granularity = data_granularity + self.adapter_dict: Dict[tuple, SAOEStateAdapter] = {} + self._last_step_range = (0, 0) + + def _create_qlib_backtest_adapter( + self, + order: Order, + trade_decision: BaseTradeDecision, + trade_range: TradeRange, + ) -> SAOEStateAdapter: + backtest_data = load_backtest_data(order, self.trade_exchange, trade_range) + + return SAOEStateAdapter( + order=order, + trade_decision=trade_decision, + executor=self.executor, + exchange=self.trade_exchange, + ticks_per_step=int(pd.Timedelta(self.trade_calendar.get_freq()) / ONE_MIN), + backtest_data=backtest_data, + data_granularity=self._data_granularity, + ) + + def reset(self, outer_trade_decision: BaseTradeDecision | None = None, **kwargs: Any) -> None: + super(SAOEStrategy, self).reset(outer_trade_decision=outer_trade_decision, **kwargs) + + self.adapter_dict = {} + self._last_step_range = (0, 0) + + if outer_trade_decision is not None and not outer_trade_decision.empty(): + trade_range = outer_trade_decision.trade_range + assert trade_range is not None + + self.adapter_dict = {} + for decision in outer_trade_decision.get_decision(): + order = cast(Order, decision) + self.adapter_dict[order.key_by_day] = self._create_qlib_backtest_adapter( + order, outer_trade_decision, trade_range + ) + + def get_saoe_state_by_order(self, order: Order) -> SAOEState: + return self.adapter_dict[order.key_by_day].saoe_state + + def post_upper_level_exe_step(self) -> None: + for adapter in self.adapter_dict.values(): + adapter.generate_metrics_after_done() + + def post_exe_step(self, execute_result: Optional[list]) -> None: + last_step_length = self._last_step_range[1] - self._last_step_range[0] + if last_step_length <= 0: + assert not execute_result + return + + results = collections.defaultdict(list) + if execute_result is not None: + for e in execute_result: + results[e[0].key_by_day].append(e) + + for key, adapter in self.adapter_dict.items(): + adapter.update(results[key], self._last_step_range) + + def generate_trade_decision( + self, + execute_result: list | None = None, + ) -> Union[BaseTradeDecision, Generator[Any, Any, BaseTradeDecision]]: + """ + For SAOEStrategy, we need to update the `self._last_step_range` every time a decision is generated. + This operation should be invisible to developers, so we implement it in `generate_trade_decision()` + The concrete logic to generate decisions should be implemented in `_generate_trade_decision()`. + In other words, all subclass of `SAOEStrategy` should overwrite `_generate_trade_decision()` instead of + `generate_trade_decision()`. + """ + self._last_step_range = self.get_data_cal_avail_range(rtype="step") + + decision = self._generate_trade_decision(execute_result) + if isinstance(decision, GeneratorType): + decision = yield from decision + + return decision + + def _generate_trade_decision( + self, + execute_result: list | None = None, + ) -> Union[BaseTradeDecision, Generator[Any, Any, BaseTradeDecision]]: + raise NotImplementedError + + +class ProxySAOEStrategy(SAOEStrategy): + """Proxy strategy that uses SAOEState. It is called a 'proxy' strategy because it does not make any decisions + by itself. Instead, when the strategy is required to generate a decision, it will yield the environment's + information and let the outside agents to make the decision. Please refer to `_generate_trade_decision` for + more details. + """ + + def __init__( + self, + outer_trade_decision: BaseTradeDecision | None = None, + level_infra: LevelInfrastructure | None = None, + common_infra: CommonInfrastructure | None = None, + **kwargs: Any, + ) -> None: + super().__init__(None, outer_trade_decision, level_infra, common_infra, **kwargs) + + def _generate_trade_decision(self, execute_result: list | None = None) -> Generator[Any, Any, BaseTradeDecision]: + # Once the following line is executed, this ProxySAOEStrategy (self) will be yielded to the outside + # of the entire executor, and the execution will be suspended. When the execution is resumed by `send()`, + # the item will be captured by `exec_vol`. The outside policy could communicate with the inner + # level strategy through this way. + exec_vol = yield self + + oh = self.trade_exchange.get_order_helper() + order = oh.create(self._order.stock_id, exec_vol, self._order.direction) + + return TradeDecisionWO([order], self) + + def reset(self, outer_trade_decision: BaseTradeDecision | None = None, **kwargs: Any) -> None: + super().reset(outer_trade_decision=outer_trade_decision, **kwargs) + + assert isinstance(outer_trade_decision, TradeDecisionWO) + if outer_trade_decision is not None: + order_list = outer_trade_decision.order_list + assert len(order_list) == 1 + self._order = order_list[0] + + +class SAOEIntStrategy(SAOEStrategy): + """(SAOE)state based strategy with (Int)preters.""" + + def __init__( + self, + policy: dict | BasePolicy, + state_interpreter: dict | StateInterpreter, + action_interpreter: dict | ActionInterpreter, + network: dict | torch.nn.Module | None = None, + outer_trade_decision: BaseTradeDecision | None = None, + level_infra: LevelInfrastructure | None = None, + common_infra: CommonInfrastructure | None = None, + **kwargs: Any, + ) -> None: + super(SAOEIntStrategy, self).__init__( + policy=policy, + outer_trade_decision=outer_trade_decision, + level_infra=level_infra, + common_infra=common_infra, + **kwargs, + ) + + self._state_interpreter: StateInterpreter = init_instance_by_config( + state_interpreter, + accept_types=StateInterpreter, + ) + self._action_interpreter: ActionInterpreter = init_instance_by_config( + action_interpreter, + accept_types=ActionInterpreter, + ) + + if isinstance(policy, dict): + assert network is not None + + if isinstance(network, dict): + network["kwargs"].update( + { + "obs_space": self._state_interpreter.observation_space, + } + ) + network_inst = init_instance_by_config(network) + else: + network_inst = network + + policy["kwargs"].update( + { + "obs_space": self._state_interpreter.observation_space, + "action_space": self._action_interpreter.action_space, + "network": network_inst, + } + ) + self._policy = init_instance_by_config(policy) + elif isinstance(policy, BasePolicy): + self._policy = policy + else: + raise ValueError(f"Unsupported policy type: {type(policy)}.") + + if self._policy is not None: + self._policy.eval() + + def reset(self, outer_trade_decision: BaseTradeDecision | None = None, **kwargs: Any) -> None: + super().reset(outer_trade_decision=outer_trade_decision, **kwargs) + + def _generate_trade_details(self, act: np.ndarray, exec_vols: List[float]) -> pd.DataFrame: + assert hasattr(self.outer_trade_decision, "order_list") + + trade_details = [] + for a, v, o in zip(act, exec_vols, getattr(self.outer_trade_decision, "order_list")): + trade_details.append( + { + "instrument": o.stock_id, + "datetime": self.trade_calendar.get_step_time()[0], + "freq": self.trade_calendar.get_freq(), + "rl_exec_vol": v, + } + ) + if a is not None: + trade_details[-1]["rl_action"] = a + return pd.DataFrame.from_records(trade_details) + + def _generate_trade_decision(self, execute_result: list | None = None) -> BaseTradeDecision: + states = [] + obs_batch = [] + for decision in self.outer_trade_decision.get_decision(): + order = cast(Order, decision) + state = self.get_saoe_state_by_order(order) + + states.append(state) + obs_batch.append({"obs": self._state_interpreter.interpret(state)}) + + with torch.no_grad(): + policy_out = self._policy(Batch(obs_batch)) + act = policy_out.act.numpy() if torch.is_tensor(policy_out.act) else policy_out.act + exec_vols = [self._action_interpreter.interpret(s, a) for s, a in zip(states, act)] + + oh = self.trade_exchange.get_order_helper() + order_list = [] + for decision, exec_vol in zip(self.outer_trade_decision.get_decision(), exec_vols): + if exec_vol != 0: + order = cast(Order, decision) + order_list.append(oh.create(order.stock_id, exec_vol, order.direction)) + + return TradeDecisionWithDetails( + order_list=order_list, + strategy=self, + details=self._generate_trade_details(act, exec_vols), + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4fb78ff91d185c4bf3c80b36a791f3fc2e5621 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/order_execution/utils.py @@ -0,0 +1,52 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import Any, cast + +import numpy as np +import pandas as pd + +from qlib.backtest.decision import OrderDir +from qlib.backtest.executor import BaseExecutor, NestedExecutor, SimulatorExecutor +from qlib.constant import float_or_ndarray + + +def dataframe_append(df: pd.DataFrame, other: Any) -> pd.DataFrame: + # dataframe.append is deprecated + other_df = pd.DataFrame(other).set_index("datetime") + other_df.index.name = "datetime" + + res = pd.concat([df, other_df], axis=0) + return res + + +def price_advantage( + exec_price: float_or_ndarray, + baseline_price: float, + direction: OrderDir | int, +) -> float_or_ndarray: + if baseline_price == 0: # something is wrong with data. Should be nan here + if isinstance(exec_price, float): + return 0.0 + else: + return np.zeros_like(exec_price) + if direction == OrderDir.BUY: + res = (1 - exec_price / baseline_price) * 10000 + elif direction == OrderDir.SELL: + res = (exec_price / baseline_price - 1) * 10000 + else: + raise ValueError(f"Unexpected order direction: {direction}") + res_wo_nan: np.ndarray = np.nan_to_num(res, nan=0.0) + if res_wo_nan.size == 1: + return res_wo_nan.item() + else: + return cast(float_or_ndarray, res_wo_nan) + + +def get_simulator_executor(executor: BaseExecutor) -> SimulatorExecutor: + while isinstance(executor, NestedExecutor): + executor = executor.inner_executor + assert isinstance(executor, SimulatorExecutor) + return executor diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/reward.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0dbdc86e82570ce83dcc8ba93a0d0ff3ee23ca --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/reward.py @@ -0,0 +1,85 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Dict, Generic, Optional, Tuple, TypeVar + +from qlib.typehint import final + +if TYPE_CHECKING: + from .utils.env_wrapper import EnvWrapper + +SimulatorState = TypeVar("SimulatorState") + + +class Reward(Generic[SimulatorState]): + """ + Reward calculation component that takes a single argument: state of simulator. Returns a real number: reward. + + Subclass should implement ``reward(simulator_state)`` to implement their own reward calculation recipe. + """ + + env: Optional[EnvWrapper] = None + + @final + def __call__(self, simulator_state: SimulatorState) -> float: + return self.reward(simulator_state) + + def reward(self, simulator_state: SimulatorState) -> float: + """Implement this method for your own reward.""" + raise NotImplementedError("Implement reward calculation recipe in `reward()`.") + + def log(self, name: str, value: Any) -> None: + assert self.env is not None + self.env.logger.add_scalar(name, value) + + +class RewardCombination(Reward): + """Combination of multiple reward.""" + + def __init__(self, rewards: Dict[str, Tuple[Reward, float]]) -> None: + self.rewards = rewards + + def reward(self, simulator_state: Any) -> float: + total_reward = 0.0 + for name, (reward_fn, weight) in self.rewards.items(): + rew = reward_fn(simulator_state) * weight + total_reward += rew + self.log(name, rew) + return total_reward + + +# TODO: +# reward_factory is disabled for now + +# _RegistryConfigReward = RegistryConfig[REWARDS] + + +# @configclass +# class _WeightedRewardConfig: +# weight: float +# reward: _RegistryConfigReward + + +# RewardConfig = Union[_RegistryConfigReward, Dict[str, Union[_RegistryConfigReward, _WeightedRewardConfig]]] + + +# def reward_factory(reward_config: RewardConfig) -> Reward: +# """ +# Use this factory to instantiate the reward from config. +# Simply using ``reward_config.build()`` might not work because reward can have complex combinations. +# """ +# if isinstance(reward_config, dict): +# # as reward combination +# rewards = {} +# for name, rew in reward_config.items(): +# if not isinstance(rew, _WeightedRewardConfig): +# # default weight is 1. +# rew = _WeightedRewardConfig(weight=1., rew=rew) +# # no recursive build in this step +# rewards[name] = (rew.reward.build(), rew.weight) +# return RewardCombination(rewards) +# else: +# # single reward +# return reward_config.build() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/seed.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..93d452a4a2ae5e125b57e322be43b8995b37dd92 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/seed.py @@ -0,0 +1,12 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Defines a set of initial state definitions and state-set definitions. + +With single-asset order execution only, the only seed is order. +""" + +from typing import TypeVar + +InitialStateType = TypeVar("InitialStateType") +"""Type of data that creates the simulator.""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/simulator.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..72e74b64fae38ca83f0ee73372efff17a4764e25 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/simulator.py @@ -0,0 +1,75 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Generic, Optional, TypeVar + +from .seed import InitialStateType + +if TYPE_CHECKING: + from .utils.env_wrapper import EnvWrapper + +StateType = TypeVar("StateType") +"""StateType stores all the useful data in the simulation process +(as well as utilities to generate/retrieve data when needed).""" + +ActType = TypeVar("ActType") +"""This ActType is the type of action at the simulator end.""" + + +class Simulator(Generic[InitialStateType, StateType, ActType]): + """ + Simulator that resets with ``__init__``, and transits with ``step(action)``. + + To make the data-flow clear, we make the following restrictions to Simulator: + + 1. The only way to modify the inner status of a simulator is by using ``step(action)``. + 2. External modules can *read* the status of a simulator by using ``simulator.get_state()``, + and check whether the simulator is in the ending state by calling ``simulator.done()``. + + A simulator is defined to be bounded with three types: + + - *InitialStateType* that is the type of the data used to create the simulator. + - *StateType* that is the type of the **status** (state) of the simulator. + - *ActType* that is the type of the **action**, which is the input received in each step. + + Different simulators might share the same StateType. For example, when they are dealing with the same task, + but with different simulation implementation. With the same type, they can safely share other components in the MDP. + + Simulators are ephemeral. The lifecycle of a simulator starts with an initial state, and ends with the trajectory. + In another word, when the trajectory ends, simulator is recycled. + If simulators want to share context between (e.g., for speed-up purposes), + this could be done by accessing the weak reference of environment wrapper. + + Attributes + ---------- + env + A reference of env-wrapper, which could be useful in some corner cases. + Simulators are discouraged to use this, because it's prone to induce errors. + """ + + env: Optional[EnvWrapper] = None + + def __init__(self, initial: InitialStateType, **kwargs: Any) -> None: + pass + + def step(self, action: ActType) -> None: + """Receives an action of ActType. + + Simulator should update its internal state, and return None. + The updated state can be retrieved with ``simulator.get_state()``. + """ + raise NotImplementedError() + + def get_state(self) -> StateType: + raise NotImplementedError() + + def done(self) -> bool: + """Check whether the simulator is in a "done" state. + When simulator is in a "done" state, + it should no longer receives any ``step`` request. + As simulators are ephemeral, to reset the simulator, + the old one should be destroyed and a new simulator can be created. + """ + raise NotImplementedError() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/strategy/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/strategy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26e12580bace49afc0f2b885802003195537d5df --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/strategy/__init__.py @@ -0,0 +1,5 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from .single_order import SingleOrderStrategy + +__all__ = ["SingleOrderStrategy"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/strategy/single_order.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/strategy/single_order.py new file mode 100644 index 0000000000000000000000000000000000000000..45db0d9c8958d8c28ebaa81a4a26b996f098c6d9 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/strategy/single_order.py @@ -0,0 +1,33 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from qlib.backtest import Order +from qlib.backtest.decision import OrderHelper, TradeDecisionWO, TradeRange +from qlib.strategy.base import BaseStrategy + + +class SingleOrderStrategy(BaseStrategy): + """Strategy used to generate a trade decision with exactly one order.""" + + def __init__( + self, + order: Order, + trade_range: TradeRange | None = None, + ) -> None: + super().__init__() + + self._order = order + self._trade_range = trade_range + + def generate_trade_decision(self, execute_result: list | None = None) -> TradeDecisionWO: + oh: OrderHelper = self.common_infra.get("trade_exchange").get_order_helper() + order_list = [ + oh.create( + code=self._order.stock_id, + amount=self._order.amount, + direction=self._order.direction, + ), + ] + return TradeDecisionWO(order_list, self, self._trade_range) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..828ba7bd3cb9024b45f143308e5c3fb8bd6d55e4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/__init__.py @@ -0,0 +1,20 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Train, test, inference utilities.""" + +from .api import backtest, train +from .callbacks import Checkpoint, EarlyStopping, MetricsWriter +from .trainer import Trainer +from .vessel import TrainingVessel, TrainingVesselBase + +__all__ = [ + "Trainer", + "TrainingVessel", + "TrainingVesselBase", + "Checkpoint", + "EarlyStopping", + "MetricsWriter", + "train", + "backtest", +] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/api.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/api.py new file mode 100644 index 0000000000000000000000000000000000000000..aea99dc3dcc2ab0cf70c90920d131cffce76495d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/api.py @@ -0,0 +1,118 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import Any, Callable, Dict, List, Sequence, cast + +from tianshou.policy import BasePolicy + +from qlib.rl.interpreter import ActionInterpreter, StateInterpreter +from qlib.rl.reward import Reward +from qlib.rl.simulator import InitialStateType, Simulator +from qlib.rl.utils import FiniteEnvType, LogWriter + +from .trainer import Trainer +from .vessel import TrainingVessel + + +def train( + simulator_fn: Callable[[InitialStateType], Simulator], + state_interpreter: StateInterpreter, + action_interpreter: ActionInterpreter, + initial_states: Sequence[InitialStateType], + policy: BasePolicy, + reward: Reward, + vessel_kwargs: Dict[str, Any], + trainer_kwargs: Dict[str, Any], +) -> None: + """Train a policy with the parallelism provided by RL framework. + + Experimental API. Parameters might change shortly. + + Parameters + ---------- + simulator_fn + Callable receiving initial seed, returning a simulator. + state_interpreter + Interprets the state of simulators. + action_interpreter + Interprets the policy actions. + initial_states + Initial states to iterate over. Every state will be run exactly once. + policy + Policy to train against. + reward + Reward function. + vessel_kwargs + Keyword arguments passed to :class:`TrainingVessel`, like ``episode_per_iter``. + trainer_kwargs + Keyword arguments passed to :class:`Trainer`, like ``finite_env_type``, ``concurrency``. + """ + + vessel = TrainingVessel( + simulator_fn=simulator_fn, + state_interpreter=state_interpreter, + action_interpreter=action_interpreter, + policy=policy, + train_initial_states=initial_states, + reward=reward, # ignore none + **vessel_kwargs, + ) + trainer = Trainer(**trainer_kwargs) + trainer.fit(vessel) + + +def backtest( + simulator_fn: Callable[[InitialStateType], Simulator], + state_interpreter: StateInterpreter, + action_interpreter: ActionInterpreter, + initial_states: Sequence[InitialStateType], + policy: BasePolicy, + logger: LogWriter | List[LogWriter], + reward: Reward | None = None, + finite_env_type: FiniteEnvType = "subproc", + concurrency: int = 2, +) -> None: + """Backtest with the parallelism provided by RL framework. + + Experimental API. Parameters might change shortly. + + Parameters + ---------- + simulator_fn + Callable receiving initial seed, returning a simulator. + state_interpreter + Interprets the state of simulators. + action_interpreter + Interprets the policy actions. + initial_states + Initial states to iterate over. Every state will be run exactly once. + policy + Policy to test against. + logger + Logger to record the backtest results. Logger must be present because + without logger, all information will be lost. + reward + Optional reward function. For backtest, this is for testing the rewards + and logging them only. + finite_env_type + Type of finite env implementation. + concurrency + Parallel workers. + """ + + vessel = TrainingVessel( + simulator_fn=simulator_fn, + state_interpreter=state_interpreter, + action_interpreter=action_interpreter, + policy=policy, + test_initial_states=initial_states, + reward=cast(Reward, reward), # ignore none + ) + trainer = Trainer( + finite_env_type=finite_env_type, + concurrency=concurrency, + loggers=logger, + ) + trainer.test(vessel) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/callbacks.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1bf4ba282060c796a1ce07896967642587f51c --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/callbacks.py @@ -0,0 +1,291 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Callbacks to insert customized recipes during the training. +Mimicks the hooks of Keras / PyTorch-Lightning, but tailored for the context of RL. +""" + +from __future__ import annotations + +import copy +import os +import shutil +import time +from datetime import datetime +from pathlib import Path +from typing import Any, List, TYPE_CHECKING + +import numpy as np +import pandas as pd +import torch + +from qlib.log import get_module_logger +from qlib.typehint import Literal + +if TYPE_CHECKING: + from .trainer import Trainer + from .vessel import TrainingVesselBase + +_logger = get_module_logger(__name__) + + +class Callback: + """Base class of all callbacks.""" + + def on_fit_start(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called before the whole fit process begins.""" + + def on_fit_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called after the whole fit process ends.""" + + def on_train_start(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when each collect for training begins.""" + + def on_train_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when the training ends. + To access all outputs produced during training, cache the data in either trainer and vessel, + and post-process them in this hook. + """ + + def on_validate_start(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when every run for validation begins.""" + + def on_validate_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when the validation ends.""" + + def on_test_start(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when every run of testing begins.""" + + def on_test_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when the testing ends.""" + + def on_iter_start(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called when every iteration (i.e., collect) starts.""" + + def on_iter_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + """Called upon every end of iteration. + This is called **after** the bump of ``current_iter``, + when the previous iteration is considered complete. + """ + + def state_dict(self) -> Any: + """Get a state dict of the callback for pause and resume.""" + + def load_state_dict(self, state_dict: Any) -> None: + """Resume the callback from a saved state dict.""" + + +class EarlyStopping(Callback): + """Stop training when a monitored metric has stopped improving. + + The earlystopping callback will be triggered each time validation ends. + It will examine the metrics produced in validation, + and get the metric with name ``monitor` (``monitor`` is ``reward`` by default), + to check whether it's no longer increasing / decreasing. + It takes ``min_delta`` and ``patience`` if applicable. + If it's found to be not increasing / decreasing any more. + ``trainer.should_stop`` will be set to true, + and the training terminates. + + Implementation reference: https://github.com/keras-team/keras/blob/v2.9.0/keras/callbacks.py#L1744-L1893 + """ + + def __init__( + self, + monitor: str = "reward", + min_delta: float = 0.0, + patience: int = 0, + mode: Literal["min", "max"] = "max", + baseline: float | None = None, + restore_best_weights: bool = False, + ): + super().__init__() + + self.monitor = monitor + self.patience = patience + self.baseline = baseline + self.min_delta = abs(min_delta) + self.restore_best_weights = restore_best_weights + self.best_weights: Any | None = None + + if mode not in ["min", "max"]: + raise ValueError("Unsupported earlystopping mode: " + mode) + + if mode == "min": + self.monitor_op = np.less + elif mode == "max": + self.monitor_op = np.greater + + if self.monitor_op == np.greater: + self.min_delta *= 1 + else: + self.min_delta *= -1 + + def state_dict(self) -> dict: + return {"wait": self.wait, "best": self.best, "best_weights": self.best_weights, "best_iter": self.best_iter} + + def load_state_dict(self, state_dict: dict) -> None: + self.wait = state_dict["wait"] + self.best = state_dict["best"] + self.best_weights = state_dict["best_weights"] + self.best_iter = state_dict["best_iter"] + + def on_fit_start(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + # Allow instances to be re-used + self.wait = 0 + self.best = np.inf if self.monitor_op == np.less else -np.inf + self.best_weights = None + self.best_iter = 0 + + def on_validate_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + current = self.get_monitor_value(trainer) + if current is None: + return + if self.restore_best_weights and self.best_weights is None: + # Restore the weights after first iteration if no progress is ever made. + self.best_weights = copy.deepcopy(vessel.state_dict()) + + self.wait += 1 + if self._is_improvement(current, self.best): + self.best = current + self.best_iter = trainer.current_iter + if self.restore_best_weights: + self.best_weights = copy.deepcopy(vessel.state_dict()) + # Only restart wait if we beat both the baseline and our previous best. + if self.baseline is None or self._is_improvement(current, self.baseline): + self.wait = 0 + + msg = ( + f"#{trainer.current_iter} current reward: {current:.4f}, best reward: {self.best:.4f} in #{self.best_iter}" + ) + _logger.info(msg) + + # Only check after the first epoch. + if self.wait >= self.patience and trainer.current_iter > 0: + trainer.should_stop = True + _logger.info(f"On iteration %d: early stopping", trainer.current_iter + 1) + if self.restore_best_weights and self.best_weights is not None: + _logger.info("Restoring model weights from the end of the best iteration: %d", self.best_iter + 1) + vessel.load_state_dict(self.best_weights) + + def get_monitor_value(self, trainer: Trainer) -> Any: + monitor_value = trainer.metrics.get(self.monitor) + if monitor_value is None: + _logger.warning( + "Early stopping conditioned on metric `%s` which is not available. Available metrics are: %s", + self.monitor, + ",".join(list(trainer.metrics.keys())), + ) + return monitor_value + + def _is_improvement(self, monitor_value, reference_value): + return self.monitor_op(monitor_value - self.min_delta, reference_value) + + +class MetricsWriter(Callback): + """Dump training metrics to file.""" + + def __init__(self, dirpath: Path) -> None: + self.dirpath = dirpath + self.dirpath.mkdir(exist_ok=True, parents=True) + self.train_records: List[dict] = [] + self.valid_records: List[dict] = [] + + def on_train_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + self.train_records.append({k: v for k, v in trainer.metrics.items() if not k.startswith("val/")}) + pd.DataFrame.from_records(self.train_records).to_csv(self.dirpath / "train_result.csv", index=True) + + def on_validate_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + self.valid_records.append({k: v for k, v in trainer.metrics.items() if k.startswith("val/")}) + pd.DataFrame.from_records(self.valid_records).to_csv(self.dirpath / "validation_result.csv", index=True) + + +class Checkpoint(Callback): + """Save checkpoints periodically for persistence and recovery. + + Reference: https://github.com/PyTorchLightning/pytorch-lightning/blob/bfa8b7be/pytorch_lightning/callbacks/model_checkpoint.py + + Parameters + ---------- + dirpath + Directory to save the checkpoint file. + filename + Checkpoint filename. Can contain named formatting options to be auto-filled. + For example: ``{iter:03d}-{reward:.2f}.pth``. + Supported argument names are: + + - iter (int) + - metrics in ``trainer.metrics`` + - time string, in the format of ``%Y%m%d%H%M%S`` + save_latest + Save the latest checkpoint in ``latest.pth``. + If ``link``, ``latest.pth`` will be created as a softlink. + If ``copy``, ``latest.pth`` will be stored as an individual copy. + Set to none to disable this. + every_n_iters + Checkpoints are saved at the end of every n iterations of training, + after validation if applicable. + time_interval + Maximum time (seconds) before checkpoints save again. + save_on_fit_end + Save one last checkpoint at the end to fit. + Do nothing if a checkpoint is already saved there. + """ + + def __init__( + self, + dirpath: Path, + filename: str = "{iter:03d}.pth", + save_latest: Literal["link", "copy"] | None = "link", + every_n_iters: int | None = None, + time_interval: int | None = None, + save_on_fit_end: bool = True, + ): + self.dirpath = Path(dirpath) + self.filename = filename + self.save_latest = save_latest + self.every_n_iters = every_n_iters + self.time_interval = time_interval + self.save_on_fit_end = save_on_fit_end + + self._last_checkpoint_name: str | None = None + self._last_checkpoint_iter: int | None = None + self._last_checkpoint_time: float | None = None + + def on_fit_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + if self.save_on_fit_end and (trainer.current_iter != self._last_checkpoint_iter): + self._save_checkpoint(trainer) + + def on_iter_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None: + should_save_ckpt = False + if self.every_n_iters is not None and (trainer.current_iter + 1) % self.every_n_iters == 0: + should_save_ckpt = True + if self.time_interval is not None and ( + self._last_checkpoint_time is None or (time.time() - self._last_checkpoint_time) >= self.time_interval + ): + should_save_ckpt = True + if should_save_ckpt: + self._save_checkpoint(trainer) + + def _save_checkpoint(self, trainer: Trainer) -> None: + self.dirpath.mkdir(exist_ok=True, parents=True) + self._last_checkpoint_name = self._new_checkpoint_name(trainer) + self._last_checkpoint_iter = trainer.current_iter + self._last_checkpoint_time = time.time() + torch.save(trainer.state_dict(), self.dirpath / self._last_checkpoint_name) + + latest_pth = self.dirpath / "latest.pth" + + # Remove first before saving + if self.save_latest and (latest_pth.exists() or os.path.islink(latest_pth)): + latest_pth.unlink() + + if self.save_latest == "link": + latest_pth.symlink_to(self.dirpath / self._last_checkpoint_name) + elif self.save_latest == "copy": + shutil.copyfile(self.dirpath / self._last_checkpoint_name, latest_pth) + + def _new_checkpoint_name(self, trainer: Trainer) -> str: + return self.filename.format( + iter=trainer.current_iter, time=datetime.now().strftime("%Y%m%d%H%M%S"), **trainer.metrics + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/trainer.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a1046e966edbbd8500a51dc22e81e0572f824ff3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/trainer.py @@ -0,0 +1,355 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import collections +import copy +from contextlib import AbstractContextManager, contextmanager +from datetime import datetime +from pathlib import Path +from typing import Any, Dict, Iterable, List, OrderedDict, Sequence, TypeVar, cast + +import torch + +from qlib.log import get_module_logger +from qlib.rl.simulator import InitialStateType +from qlib.rl.utils import EnvWrapper, FiniteEnvType, LogBuffer, LogCollector, LogLevel, LogWriter, vectorize_env +from qlib.rl.utils.finite_env import FiniteVectorEnv +from qlib.typehint import Literal + +from .callbacks import Callback +from .vessel import TrainingVesselBase + +_logger = get_module_logger(__name__) + + +T = TypeVar("T") + + +class Trainer: + """ + Utility to train a policy on a particular task. + + Different from traditional DL trainer, the iteration of this trainer is "collect", + rather than "epoch", or "mini-batch". + In each collect, :class:`Collector` collects a number of policy-env interactions, and accumulates + them into a replay buffer. This buffer is used as the "data" to train the policy. + At the end of each collect, the policy is *updated* several times. + + The API has some resemblence with `PyTorch Lightning `__, + but it's essentially different because this trainer is built for RL applications, and thus + most configurations are under RL context. + We are still looking for ways to incorporate existing trainer libraries, because it looks like + big efforts to build a trainer as powerful as those libraries, and also, that's not our primary goal. + + It's essentially different + `tianshou's built-in trainers `__, + as it's far much more complicated than that. + + Parameters + ---------- + max_iters + Maximum iterations before stopping. + val_every_n_iters + Perform validation every n iterations (i.e., training collects). + logger + Logger to record the backtest results. Logger must be present because + without logger, all information will be lost. + finite_env_type + Type of finite env implementation. + concurrency + Parallel workers. + fast_dev_run + Create a subset for debugging. + How this is implemented depends on the implementation of training vessel. + For :class:`~qlib.rl.vessel.TrainingVessel`, if greater than zero, + a random subset sized ``fast_dev_run`` will be used + instead of ``train_initial_states`` and ``val_initial_states``. + """ + + should_stop: bool + """Set to stop the training.""" + + metrics: dict + """Numeric metrics of produced in train/val/test. + In the middle of training / validation, metrics will be of the latest episode. + When each iteration of training / validation finishes, metrics will be the aggregation + of all episodes encountered in this iteration. + + Cleared on every new iteration of training. + + In fit, validation metrics will be prefixed with ``val/``. + """ + + current_iter: int + """Current iteration (collect) of training.""" + + loggers: List[LogWriter] + """A list of log writers.""" + + def __init__( + self, + *, + max_iters: int | None = None, + val_every_n_iters: int | None = None, + loggers: LogWriter | List[LogWriter] | None = None, + callbacks: List[Callback] | None = None, + finite_env_type: FiniteEnvType = "subproc", + concurrency: int = 2, + fast_dev_run: int | None = None, + ): + self.max_iters = max_iters + self.val_every_n_iters = val_every_n_iters + + if isinstance(loggers, list): + self.loggers = loggers + elif isinstance(loggers, LogWriter): + self.loggers = [loggers] + else: + self.loggers = [] + + self.loggers.append(LogBuffer(self._metrics_callback, loglevel=self._min_loglevel())) + + self.callbacks: List[Callback] = callbacks if callbacks is not None else [] + self.finite_env_type = finite_env_type + self.concurrency = concurrency + self.fast_dev_run = fast_dev_run + + self.current_stage: Literal["train", "val", "test"] = "train" + + self.vessel: TrainingVesselBase = cast(TrainingVesselBase, None) + + def initialize(self): + """Initialize the whole training process. + + The states here should be synchronized with state_dict. + """ + self.should_stop = False + self.current_iter = 0 + self.current_episode = 0 + self.current_stage = "train" + + def initialize_iter(self): + """Initialize one iteration / collect.""" + self.metrics = {} + + def state_dict(self) -> dict: + """Putting every states of current training into a dict, at best effort. + + It doesn't try to handle all the possible kinds of states in the middle of one training collect. + For most cases at the end of each iteration, things should be usually correct. + + Note that it's also intended behavior that replay buffer data in the collector will be lost. + """ + return { + "vessel": self.vessel.state_dict(), + "callbacks": {name: callback.state_dict() for name, callback in self.named_callbacks().items()}, + "loggers": {name: logger.state_dict() for name, logger in self.named_loggers().items()}, + "should_stop": self.should_stop, + "current_iter": self.current_iter, + "current_episode": self.current_episode, + "current_stage": self.current_stage, + "metrics": self.metrics, + } + + @staticmethod + def get_policy_state_dict(ckpt_path: Path) -> OrderedDict: + state_dict = torch.load(ckpt_path, map_location="cpu") + if "vessel" in state_dict: + state_dict = state_dict["vessel"]["policy"] + return state_dict + + def load_state_dict(self, state_dict: dict) -> None: + """Load all states into current trainer.""" + self.vessel.load_state_dict(state_dict["vessel"]) + for name, callback in self.named_callbacks().items(): + callback.load_state_dict(state_dict["callbacks"][name]) + for name, logger in self.named_loggers().items(): + logger.load_state_dict(state_dict["loggers"][name]) + self.should_stop = state_dict["should_stop"] + self.current_iter = state_dict["current_iter"] + self.current_episode = state_dict["current_episode"] + self.current_stage = state_dict["current_stage"] + self.metrics = state_dict["metrics"] + + def named_callbacks(self) -> Dict[str, Callback]: + """Retrieve a collection of callbacks where each one has a name. + Useful when saving checkpoints. + """ + return _named_collection(self.callbacks) + + def named_loggers(self) -> Dict[str, LogWriter]: + """Retrieve a collection of loggers where each one has a name. + Useful when saving checkpoints. + """ + return _named_collection(self.loggers) + + def fit(self, vessel: TrainingVesselBase, ckpt_path: Path | None = None) -> None: + """Train the RL policy upon the defined simulator. + + Parameters + ---------- + vessel + A bundle of all elements used in training. + ckpt_path + Load a pre-trained / paused training checkpoint. + """ + self.vessel = vessel + vessel.assign_trainer(self) + + if ckpt_path is not None: + _logger.info("Resuming states from %s", str(ckpt_path)) + self.load_state_dict(torch.load(ckpt_path, weights_only=False)) + else: + self.initialize() + + self._call_callback_hooks("on_fit_start") + + while not self.should_stop: + msg = f"\n{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\tTrain iteration {self.current_iter + 1}/{self.max_iters}" + _logger.info(msg) + + self.initialize_iter() + + self._call_callback_hooks("on_iter_start") + + self.current_stage = "train" + self._call_callback_hooks("on_train_start") + + # TODO + # Add a feature that supports reloading the training environment every few iterations. + with _wrap_context(vessel.train_seed_iterator()) as iterator: + vector_env = self.venv_from_iterator(iterator) + self.vessel.train(vector_env) + del vector_env # FIXME: Explicitly delete this object to avoid memory leak. + + self._call_callback_hooks("on_train_end") + + if self.val_every_n_iters is not None and (self.current_iter + 1) % self.val_every_n_iters == 0: + # Implementation of validation loop + self.current_stage = "val" + self._call_callback_hooks("on_validate_start") + with _wrap_context(vessel.val_seed_iterator()) as iterator: + vector_env = self.venv_from_iterator(iterator) + self.vessel.validate(vector_env) + del vector_env # FIXME: Explicitly delete this object to avoid memory leak. + + self._call_callback_hooks("on_validate_end") + + # This iteration is considered complete. + # Bumping the current iteration counter. + self.current_iter += 1 + + if self.max_iters is not None and self.current_iter >= self.max_iters: + self.should_stop = True + + self._call_callback_hooks("on_iter_end") + + self._call_callback_hooks("on_fit_end") + + def test(self, vessel: TrainingVesselBase) -> None: + """Test the RL policy against the simulator. + + The simulator will be fed with data generated in ``test_seed_iterator``. + + Parameters + ---------- + vessel + A bundle of all related elements. + """ + self.vessel = vessel + vessel.assign_trainer(self) + + self.initialize_iter() + + self.current_stage = "test" + self._call_callback_hooks("on_test_start") + with _wrap_context(vessel.test_seed_iterator()) as iterator: + vector_env = self.venv_from_iterator(iterator) + self.vessel.test(vector_env) + del vector_env # FIXME: Explicitly delete this object to avoid memory leak. + self._call_callback_hooks("on_test_end") + + def venv_from_iterator(self, iterator: Iterable[InitialStateType]) -> FiniteVectorEnv: + """Create a vectorized environment from iterator and the training vessel.""" + + def env_factory(): + # FIXME: state_interpreter and action_interpreter are stateful (having a weakref of env), + # and could be thread unsafe. + # I'm not sure whether it's a design flaw. + # I'll rethink about this when designing the trainer. + + if self.finite_env_type == "dummy": + # We could only experience the "threading-unsafe" problem in dummy. + state = copy.deepcopy(self.vessel.state_interpreter) + action = copy.deepcopy(self.vessel.action_interpreter) + rew = copy.deepcopy(self.vessel.reward) + else: + state = self.vessel.state_interpreter + action = self.vessel.action_interpreter + rew = self.vessel.reward + + return EnvWrapper( + self.vessel.simulator_fn, + state, + action, + iterator, + rew, + logger=LogCollector(min_loglevel=self._min_loglevel()), + ) + + return vectorize_env( + env_factory, + self.finite_env_type, + self.concurrency, + self.loggers, + ) + + def _metrics_callback(self, on_episode: bool, on_collect: bool, log_buffer: LogBuffer) -> None: + if on_episode: + # Update the global counter. + self.current_episode = log_buffer.global_episode + metrics = log_buffer.episode_metrics() + elif on_collect: + # Update the latest metrics. + metrics = log_buffer.collect_metrics() + if self.current_stage == "val": + metrics = {"val/" + name: value for name, value in metrics.items()} + self.metrics.update(metrics) + + def _call_callback_hooks(self, hook_name: str, *args: Any, **kwargs: Any) -> None: + for callback in self.callbacks: + fn = getattr(callback, hook_name) + fn(self, self.vessel, *args, **kwargs) + + def _min_loglevel(self): + if not self.loggers: + return LogLevel.PERIODIC + else: + # To save bandwidth + return min(lg.loglevel for lg in self.loggers) + + +@contextmanager +def _wrap_context(obj): + """Make any object a (possibly dummy) context manager.""" + + if isinstance(obj, AbstractContextManager): + # obj has __enter__ and __exit__ + with obj as ctx: + yield ctx + else: + yield obj + + +def _named_collection(seq: Sequence[T]) -> Dict[str, T]: + """Convert a list into a dict, where each item is named with its type.""" + res = {} + retry_cnt: collections.Counter = collections.Counter() + for item in seq: + typename = type(item).__name__.lower() + key = typename if retry_cnt[typename] == 0 else f"{typename}{retry_cnt[typename]}" + retry_cnt[typename] += 1 + res[key] = item + return res diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/vessel.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/vessel.py new file mode 100644 index 0000000000000000000000000000000000000000..b7912b488b5beeed188ba32c612b87210518c4ac --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/trainer/vessel.py @@ -0,0 +1,218 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import weakref +from typing import TYPE_CHECKING, Any, Callable, ContextManager, Dict, Generic, Iterable, Sequence, TypeVar, cast + +import numpy as np +from tianshou.data import Collector, VectorReplayBuffer +from tianshou.env import BaseVectorEnv +from tianshou.policy import BasePolicy + +from qlib.constant import INF +from qlib.log import get_module_logger +from qlib.rl.interpreter import ActionInterpreter, ActType, ObsType, PolicyActType, StateInterpreter, StateType +from qlib.rl.reward import Reward +from qlib.rl.simulator import InitialStateType, Simulator +from qlib.rl.utils import DataQueue +from qlib.rl.utils.finite_env import FiniteVectorEnv + +if TYPE_CHECKING: + from .trainer import Trainer + + +T = TypeVar("T") +_logger = get_module_logger(__name__) + + +class SeedIteratorNotAvailable(BaseException): + pass + + +class TrainingVesselBase(Generic[InitialStateType, StateType, ActType, ObsType, PolicyActType]): + """A ship that contains simulator, interpreter, and policy, will be sent to trainer. + This class controls algorithm-related parts of training, while trainer is responsible for runtime part. + + The ship also defines the most important logic of the core training part, + and (optionally) some callbacks to insert customized logics at specific events. + """ + + simulator_fn: Callable[[InitialStateType], Simulator[InitialStateType, StateType, ActType]] + state_interpreter: StateInterpreter[StateType, ObsType] + action_interpreter: ActionInterpreter[StateType, PolicyActType, ActType] + policy: BasePolicy + reward: Reward + trainer: Trainer + + def assign_trainer(self, trainer: Trainer) -> None: + self.trainer = weakref.proxy(trainer) # type: ignore + + def train_seed_iterator(self) -> ContextManager[Iterable[InitialStateType]] | Iterable[InitialStateType]: + """Override this to create a seed iterator for training. + If the iterable is a context manager, the whole training will be invoked in the with-block, + and the iterator will be automatically closed after the training is done.""" + raise SeedIteratorNotAvailable("Seed iterator for training is not available.") + + def val_seed_iterator(self) -> ContextManager[Iterable[InitialStateType]] | Iterable[InitialStateType]: + """Override this to create a seed iterator for validation.""" + raise SeedIteratorNotAvailable("Seed iterator for validation is not available.") + + def test_seed_iterator(self) -> ContextManager[Iterable[InitialStateType]] | Iterable[InitialStateType]: + """Override this to create a seed iterator for testing.""" + raise SeedIteratorNotAvailable("Seed iterator for testing is not available.") + + def train(self, vector_env: BaseVectorEnv) -> Dict[str, Any]: + """Implement this to train one iteration. In RL, one iteration usually refers to one collect.""" + raise NotImplementedError() + + def validate(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]: + """Implement this to validate the policy once.""" + raise NotImplementedError() + + def test(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]: + """Implement this to evaluate the policy on test environment once.""" + raise NotImplementedError() + + def log(self, name: str, value: Any) -> None: + # FIXME: this is a workaround to make the log at least show somewhere. + # Need a refactor in logger to formalize this. + if isinstance(value, (np.ndarray, list)): + value = np.mean(value) + _logger.info(f"[Iter {self.trainer.current_iter + 1}] {name} = {value}") + + def log_dict(self, data: Dict[str, Any]) -> None: + for name, value in data.items(): + self.log(name, value) + + def state_dict(self) -> Dict: + """Return a checkpoint of current vessel state.""" + return {"policy": self.policy.state_dict()} + + def load_state_dict(self, state_dict: Dict) -> None: + """Restore a checkpoint from a previously saved state dict.""" + self.policy.load_state_dict(state_dict["policy"]) + + +class TrainingVessel(TrainingVesselBase): + """The default implementation of training vessel. + + ``__init__`` accepts a sequence of initial states so that iterator can be created. + ``train``, ``validate``, ``test`` each do one collect (and also update in train). + By default, the train initial states will be repeated infinitely during training, + and collector will control the number of episodes for each iteration. + In validation and testing, the val / test initial states will be used exactly once. + + Extra hyper-parameters (only used in train) include: + + - ``buffer_size``: Size of replay buffer. + - ``episode_per_iter``: Episodes per collect at training. Can be overridden by fast dev run. + - ``update_kwargs``: Keyword arguments appearing in ``policy.update``. + For example, ``dict(repeat=10, batch_size=64)``. + """ + + def __init__( + self, + *, + simulator_fn: Callable[[InitialStateType], Simulator[InitialStateType, StateType, ActType]], + state_interpreter: StateInterpreter[StateType, ObsType], + action_interpreter: ActionInterpreter[StateType, PolicyActType, ActType], + policy: BasePolicy, + reward: Reward, + train_initial_states: Sequence[InitialStateType] | None = None, + val_initial_states: Sequence[InitialStateType] | None = None, + test_initial_states: Sequence[InitialStateType] | None = None, + buffer_size: int = 20000, + episode_per_iter: int = 1000, + update_kwargs: Dict[str, Any] = cast(Dict[str, Any], None), + ): + self.simulator_fn = simulator_fn # type: ignore + self.state_interpreter = state_interpreter + self.action_interpreter = action_interpreter + self.policy = policy + self.reward = reward + self.train_initial_states = train_initial_states + self.val_initial_states = val_initial_states + self.test_initial_states = test_initial_states + self.buffer_size = buffer_size + self.episode_per_iter = episode_per_iter + self.update_kwargs = update_kwargs or {} + + def train_seed_iterator(self) -> ContextManager[Iterable[InitialStateType]] | Iterable[InitialStateType]: + if self.train_initial_states is not None: + _logger.info("Training initial states collection size: %d", len(self.train_initial_states)) + # Implement fast_dev_run here. + train_initial_states = self._random_subset("train", self.train_initial_states, self.trainer.fast_dev_run) + return DataQueue(train_initial_states, repeat=-1, shuffle=True) + return super().train_seed_iterator() + + def val_seed_iterator(self) -> ContextManager[Iterable[InitialStateType]] | Iterable[InitialStateType]: + if self.val_initial_states is not None: + _logger.info("Validation initial states collection size: %d", len(self.val_initial_states)) + val_initial_states = self._random_subset("val", self.val_initial_states, self.trainer.fast_dev_run) + return DataQueue(val_initial_states, repeat=1) + return super().val_seed_iterator() + + def test_seed_iterator(self) -> ContextManager[Iterable[InitialStateType]] | Iterable[InitialStateType]: + if self.test_initial_states is not None: + _logger.info("Testing initial states collection size: %d", len(self.test_initial_states)) + test_initial_states = self._random_subset("test", self.test_initial_states, self.trainer.fast_dev_run) + return DataQueue(test_initial_states, repeat=1) + return super().test_seed_iterator() + + def train(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]: + """Create a collector and collects ``episode_per_iter`` episodes. + Update the policy on the collected replay buffer. + """ + self.policy.train() + + with vector_env.collector_guard(): + collector = Collector( + self.policy, vector_env, VectorReplayBuffer(self.buffer_size, len(vector_env)), exploration_noise=True + ) + + # Number of episodes collected in each training iteration can be overridden by fast dev run. + if self.trainer.fast_dev_run is not None: + episodes = self.trainer.fast_dev_run + else: + episodes = self.episode_per_iter + + col_result = collector.collect(n_episode=episodes) + update_result = self.policy.update(sample_size=0, buffer=collector.buffer, **self.update_kwargs) + res = {**col_result, **update_result} + self.log_dict(res) + return res + + def validate(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]: + self.policy.eval() + + with vector_env.collector_guard(): + test_collector = Collector(self.policy, vector_env) + res = test_collector.collect(n_step=INF * len(vector_env)) + self.log_dict(res) + return res + + def test(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]: + self.policy.eval() + + with vector_env.collector_guard(): + test_collector = Collector(self.policy, vector_env) + res = test_collector.collect(n_step=INF * len(vector_env)) + self.log_dict(res) + return res + + @staticmethod + def _random_subset(name: str, collection: Sequence[T], size: int | None) -> Sequence[T]: + if size is None: + # Size = None -> original collection + return collection + order = np.random.permutation(len(collection)) + res = [collection[o] for o in order[:size]] + _logger.info( + "Fast running in development mode. Cut %s initial states from %d to %d.", + name, + len(collection), + len(res), + ) + return res diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c7ba205d87f8d21900273b9149f9bcc944d362b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/__init__.py @@ -0,0 +1,21 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from .data_queue import DataQueue +from .env_wrapper import EnvWrapper, EnvWrapperStatus +from .finite_env import FiniteEnvType, vectorize_env +from .log import ConsoleWriter, CsvWriter, LogBuffer, LogCollector, LogLevel, LogWriter + +__all__ = [ + "LogLevel", + "DataQueue", + "EnvWrapper", + "FiniteEnvType", + "LogCollector", + "LogWriter", + "vectorize_env", + "ConsoleWriter", + "CsvWriter", + "EnvWrapperStatus", + "LogBuffer", +] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/data_queue.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/data_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..71c2dff65b961d413752527847d7b8fc1c7bd84c --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/data_queue.py @@ -0,0 +1,188 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import multiprocessing +from multiprocessing.sharedctypes import Synchronized +import os +import threading +import time +import warnings +from queue import Empty +from typing import Any, Generator, Generic, Sequence, TypeVar, cast + +from qlib.log import get_module_logger + +_logger = get_module_logger(__name__) + +T = TypeVar("T") + +__all__ = ["DataQueue"] + + +class DataQueue(Generic[T]): + """Main process (producer) produces data and stores them in a queue. + Sub-processes (consumers) can retrieve the data-points from the queue. + Data-points are generated via reading items from ``dataset``. + + :class:`DataQueue` is ephemeral. You must create a new DataQueue + when the ``repeat`` is exhausted. + + See the documents of :class:`qlib.rl.utils.FiniteVectorEnv` for more background. + + Parameters + ---------- + dataset + The dataset to read data from. Must implement ``__len__`` and ``__getitem__``. + repeat + Iterate over the data-points for how many times. Use ``-1`` to iterate forever. + shuffle + If ``shuffle`` is true, the items will be read in random order. + producer_num_workers + Concurrent workers for data-loading. + queue_maxsize + Maximum items to put into queue before it jams. + + Examples + -------- + >>> data_queue = DataQueue(my_dataset) + >>> with data_queue: + ... ... + + In worker: + + >>> for data in data_queue: + ... print(data) + """ + + def __init__( + self, + dataset: Sequence[T], + repeat: int = 1, + shuffle: bool = True, + producer_num_workers: int = 0, + queue_maxsize: int = 0, + ) -> None: + if queue_maxsize == 0: + if os.cpu_count() is not None: + queue_maxsize = cast(int, os.cpu_count()) + _logger.info(f"Automatically set data queue maxsize to {queue_maxsize} to avoid overwhelming.") + else: + queue_maxsize = 1 + _logger.warning(f"CPU count not available. Setting queue maxsize to 1.") + + self.dataset: Sequence[T] = dataset + self.repeat: int = repeat + self.shuffle: bool = shuffle + self.producer_num_workers: int = producer_num_workers + + self._activated: bool = False + self._queue: multiprocessing.Queue = multiprocessing.Queue(maxsize=queue_maxsize) + # Mypy 0.981 brought '"SynchronizedBase[Any]" has no attribute "value" [attr-defined]' bug. + # Therefore, add this type casting to pass Mypy checking. + self._done = cast(Synchronized, multiprocessing.Value("i", 0)) + + def __enter__(self) -> DataQueue: + self.activate() + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.cleanup() + + def cleanup(self) -> None: + with self._done.get_lock(): + self._done.value += 1 + for repeat in range(500): + if repeat >= 1: + warnings.warn(f"After {repeat} cleanup, the queue is still not empty.", category=RuntimeWarning) + while not self._queue.empty(): + try: + self._queue.get(block=False) + except Empty: + pass + # Sometimes when the queue gets emptied, more data have already been sent, + # and they are on the way into the queue. + # If these data didn't get consumed, it will jam the queue and make the process hang. + # We wait a second here for potential data arriving, and check again (for ``repeat`` times). + time.sleep(1.0) + if self._queue.empty(): + break + _logger.debug(f"Remaining items in queue collection done. Empty: {self._queue.empty()}") + + def get(self, block: bool = True) -> Any: + if not hasattr(self, "_first_get"): + self._first_get = True + if self._first_get: + timeout = 5.0 + self._first_get = False + else: + timeout = 0.5 + while True: + try: + return self._queue.get(block=block, timeout=timeout) + except Empty: + if self._done.value: + raise StopIteration # pylint: disable=raise-missing-from + + def put(self, obj: Any, block: bool = True, timeout: int | None = None) -> None: + self._queue.put(obj, block=block, timeout=timeout) + + def mark_as_done(self) -> None: + with self._done.get_lock(): + self._done.value = 1 + + def done(self) -> int: + return self._done.value + + def activate(self) -> DataQueue: + if self._activated: + raise ValueError("DataQueue can not activate twice.") + thread = threading.Thread(target=self._producer, daemon=True) + thread.start() + self._activated = True + return self + + def __del__(self) -> None: + _logger.debug(f"__del__ of {__name__}.DataQueue") + self.cleanup() + + def __iter__(self) -> Generator[Any, None, None]: + if not self._activated: + raise ValueError( + "Need to call activate() to launch a daemon worker " + "to produce data into data queue before using it. " + "You probably have forgotten to use the DataQueue in a with block.", + ) + return self._consumer() + + def _consumer(self) -> Generator[Any, None, None]: + while True: + try: + yield self.get() + except StopIteration: + _logger.debug("Data consumer timed-out from get.") + return + + def _producer(self) -> None: + # pytorch dataloader is used here only because we need its sampler and multi-processing + from torch.utils.data import DataLoader, Dataset # pylint: disable=import-outside-toplevel + + try: + dataloader = DataLoader( + cast(Dataset[T], self.dataset), + batch_size=None, + num_workers=self.producer_num_workers, + shuffle=self.shuffle, + collate_fn=lambda t: t, # identity collate fn + ) + repeat = 10**18 if self.repeat == -1 else self.repeat + for _rep in range(repeat): + for data in dataloader: + if self._done.value: + # Already done. + return + self._queue.put(data) + _logger.debug(f"Dataloader loop done. Repeat {_rep}.") + finally: + self.mark_as_done() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/env_wrapper.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/env_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..e863b709a132bff740d252714e509d1b3431238d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/env_wrapper.py @@ -0,0 +1,250 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import weakref +from typing import Any, Callable, cast, Dict, Generic, Iterable, Iterator, Optional, Tuple + +import gym +from gym import Space + +from qlib.rl.aux_info import AuxiliaryInfoCollector +from qlib.rl.interpreter import ActionInterpreter, ObsType, PolicyActType, StateInterpreter +from qlib.rl.reward import Reward +from qlib.rl.simulator import ActType, InitialStateType, Simulator, StateType +from qlib.typehint import TypedDict +from .finite_env import generate_nan_observation +from .log import LogCollector, LogLevel + +__all__ = ["InfoDict", "EnvWrapperStatus", "EnvWrapper"] + +# in this case, there won't be any seed for simulator +SEED_INTERATOR_MISSING = "_missing_" + + +class InfoDict(TypedDict): + """The type of dict that is used in the 4th return value of ``env.step()``.""" + + aux_info: dict + """Any information depends on auxiliary info collector.""" + log: Dict[str, Any] + """Collected by LogCollector.""" + + +class EnvWrapperStatus(TypedDict): + """ + This is the status data structure used in EnvWrapper. + The fields here are in the semantics of RL. + For example, ``obs`` means the observation fed into policy. + ``action`` means the raw action returned by policy. + """ + + cur_step: int + done: bool + initial_state: Optional[Any] + obs_history: list + action_history: list + reward_history: list + + +class EnvWrapper( + gym.Env[ObsType, PolicyActType], + Generic[InitialStateType, StateType, ActType, ObsType, PolicyActType], +): + """Qlib-based RL environment, subclassing ``gym.Env``. + A wrapper of components, including simulator, state-interpreter, action-interpreter, reward. + + This is what the framework of simulator - interpreter - policy looks like in RL training. + All the components other than policy needs to be assembled into a single object called "environment". + The "environment" are replicated into multiple workers, and (at least in tianshou's implementation), + one single policy (agent) plays against a batch of environments. + + Parameters + ---------- + simulator_fn + A callable that is the simulator factory. + When ``seed_iterator`` is present, the factory should take one argument, + that is the seed (aka initial state). + Otherwise, it should take zero argument. + state_interpreter + State-observation converter. + action_interpreter + Policy-simulator action converter. + seed_iterator + An iterable of seed. With the help of :class:`qlib.rl.utils.DataQueue`, + environment workers in different processes can share one ``seed_iterator``. + reward_fn + A callable that accepts the StateType and returns a float (at least in single-agent case). + aux_info_collector + Collect auxiliary information. Could be useful in MARL. + logger + Log collector that collects the logs. The collected logs are sent back to main process, + via the return value of ``env.step()``. + + Attributes + ---------- + status : EnvWrapperStatus + Status indicator. All terms are in *RL language*. + It can be used if users care about data on the RL side. + Can be none when no trajectory is available. + """ + + simulator: Simulator[InitialStateType, StateType, ActType] + seed_iterator: str | Iterator[InitialStateType] | None + + def __init__( + self, + simulator_fn: Callable[..., Simulator[InitialStateType, StateType, ActType]], + state_interpreter: StateInterpreter[StateType, ObsType], + action_interpreter: ActionInterpreter[StateType, PolicyActType, ActType], + seed_iterator: Optional[Iterable[InitialStateType]], + reward_fn: Reward | None = None, + aux_info_collector: AuxiliaryInfoCollector[StateType, Any] | None = None, + logger: LogCollector | None = None, + ) -> None: + # Assign weak reference to wrapper. + # + # Use weak reference here, because: + # 1. Logically, the other components should be able to live without an env_wrapper. + # For example, they might live in a strategy_wrapper in future. + # Therefore injecting a "hard" attribute called "env" is not appropripate. + # 2. When the environment gets destroyed, it gets destoryed. + # We don't want it to silently live inside some interpreters. + # 3. Avoid circular reference. + # 4. When the components get serialized, we can throw away the env without any burden. + # (though this part is not implemented yet) + for obj in [state_interpreter, action_interpreter, reward_fn, aux_info_collector]: + if obj is not None: + obj.env = weakref.proxy(self) # type: ignore + + self.simulator_fn = simulator_fn + self.state_interpreter = state_interpreter + self.action_interpreter = action_interpreter + + if seed_iterator is None: + # In this case, there won't be any seed for simulator + # We can't set it to None because None actually means something else. + # If `seed_iterator` is None, it means that it's exhausted. + self.seed_iterator = SEED_INTERATOR_MISSING + else: + self.seed_iterator = iter(seed_iterator) + self.reward_fn = reward_fn + + self.aux_info_collector = aux_info_collector + self.logger: LogCollector = logger or LogCollector() + self.status: EnvWrapperStatus = cast(EnvWrapperStatus, None) + + @property + def action_space(self) -> Space: + return self.action_interpreter.action_space + + @property + def observation_space(self) -> Space: + return self.state_interpreter.observation_space + + def reset(self, **kwargs: Any) -> ObsType: + """ + Try to get a state from state queue, and init the simulator with this state. + If the queue is exhausted, generate an invalid (nan) observation. + """ + + try: + if self.seed_iterator is None: + raise RuntimeError("You can trying to get a state from a dead environment wrapper.") + + # TODO: simulator/observation might need seed to prefetch something + # as only seed has the ability to do the work beforehands + + # NOTE: though logger is reset here, logs in this function won't work, + # because we can't send them outside. + # See https://github.com/thu-ml/tianshou/issues/605 + self.logger.reset() + + if self.seed_iterator is SEED_INTERATOR_MISSING: + # no initial state + initial_state = None + self.simulator = cast(Callable[[], Simulator], self.simulator_fn)() + else: + initial_state = next(cast(Iterator[InitialStateType], self.seed_iterator)) + self.simulator = self.simulator_fn(initial_state) + + self.status = EnvWrapperStatus( + cur_step=0, + done=False, + initial_state=initial_state, + obs_history=[], + action_history=[], + reward_history=[], + ) + + self.simulator.env = cast(EnvWrapper, weakref.proxy(self)) + + sim_state = self.simulator.get_state() + obs = self.state_interpreter(sim_state) + + self.status["obs_history"].append(obs) + + return obs + + except StopIteration: + # The environment should be recycled because it's in a dead state. + self.seed_iterator = None + return generate_nan_observation(self.observation_space) + + def step(self, policy_action: PolicyActType, **kwargs: Any) -> Tuple[ObsType, float, bool, InfoDict]: + """Environment step. + + See the code along with comments to get a sequence of things happening here. + """ + + if self.seed_iterator is None: + raise RuntimeError("State queue is already exhausted, but the environment is still receiving action.") + + # Clear the logged information from last step + self.logger.reset() + + # Action is what we have got from policy + self.status["action_history"].append(policy_action) + action = self.action_interpreter(self.simulator.get_state(), policy_action) + + # This update must be after action interpreter and before simulator. + self.status["cur_step"] += 1 + + # Use the converted action of update the simulator + self.simulator.step(action) + + # Update "done" first, as this status might be used by reward_fn later + done = self.simulator.done() + self.status["done"] = done + + # Get state and calculate observation + sim_state = self.simulator.get_state() + obs = self.state_interpreter(sim_state) + self.status["obs_history"].append(obs) + + # Reward and extra info + if self.reward_fn is not None: + rew = self.reward_fn(sim_state) + else: + # No reward. Treated as 0. + rew = 0.0 + self.status["reward_history"].append(rew) + + if self.aux_info_collector is not None: + aux_info = self.aux_info_collector(sim_state) + else: + aux_info = {} + + # Final logging stuff: RL-specific logs + if done: + self.logger.add_scalar("steps_per_episode", self.status["cur_step"]) + self.logger.add_scalar("reward", rew) + self.logger.add_any("obs", obs, loglevel=LogLevel.DEBUG) + self.logger.add_any("policy_act", policy_action, loglevel=LogLevel.DEBUG) + + info_dict = InfoDict(log=self.logger.logs(), aux_info=aux_info) + return obs, rew, done, info_dict + + def render(self, mode: str = "human") -> None: + raise NotImplementedError("Render is not implemented in EnvWrapper.") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/finite_env.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/finite_env.py new file mode 100644 index 0000000000000000000000000000000000000000..87f0900e160c80e96fd1682d7ade6f0b14840088 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/finite_env.py @@ -0,0 +1,369 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +This is to support finite env in vector env. +See https://github.com/thu-ml/tianshou/issues/322 for details. +""" + +from __future__ import annotations + +import copy +import warnings +from contextlib import contextmanager +from typing import Any, Callable, Dict, Generator, List, Optional, Set, Tuple, Type, Union, cast + +import gym +import numpy as np +from tianshou.env import BaseVectorEnv, DummyVectorEnv, ShmemVectorEnv, SubprocVectorEnv + +from qlib.typehint import Literal + +from .log import LogWriter + +__all__ = [ + "generate_nan_observation", + "check_nan_observation", + "FiniteVectorEnv", + "FiniteDummyVectorEnv", + "FiniteSubprocVectorEnv", + "FiniteShmemVectorEnv", + "FiniteEnvType", + "vectorize_env", +] + +FiniteEnvType = Literal["dummy", "subproc", "shmem"] +T = Union[dict, list, tuple, np.ndarray] + + +def fill_invalid(obj: int | float | bool | T) -> T: + if isinstance(obj, (int, float, bool)): + return fill_invalid(np.array(obj)) + if hasattr(obj, "dtype"): + if isinstance(obj, np.ndarray): + if np.issubdtype(obj.dtype, np.floating): + return np.full_like(obj, np.nan) + return np.full_like(obj, np.iinfo(obj.dtype).max) + # dealing with corner cases that numpy number is not supported by tianshou's sharray + return fill_invalid(np.array(obj)) + elif isinstance(obj, dict): + return {k: fill_invalid(v) for k, v in obj.items()} + elif isinstance(obj, list): + return [fill_invalid(v) for v in obj] + elif isinstance(obj, tuple): + return tuple(fill_invalid(v) for v in obj) + raise ValueError(f"Unsupported value to fill with invalid: {obj}") + + +def is_invalid(arr: int | float | bool | T) -> bool: + if isinstance(arr, np.ndarray): + if np.issubdtype(arr.dtype, np.floating): + return np.isnan(arr).all() + return cast(bool, cast(np.ndarray, np.iinfo(arr.dtype).max == arr).all()) + if isinstance(arr, dict): + return all(is_invalid(o) for o in arr.values()) + if isinstance(arr, (list, tuple)): + return all(is_invalid(o) for o in arr) + if isinstance(arr, (int, float, bool, np.number)): + return is_invalid(np.array(arr)) + return True + + +def generate_nan_observation(obs_space: gym.Space) -> Any: + """The NaN observation that indicates the environment receives no seed. + + We assume that obs is complex and there must be something like float. + Otherwise this logic doesn't work. + """ + + sample = obs_space.sample() + sample = fill_invalid(sample) + return sample + + +def check_nan_observation(obs: Any) -> bool: + """Check whether obs is generated by :func:`generate_nan_observation`.""" + return is_invalid(obs) + + +class FiniteVectorEnv(BaseVectorEnv): + """To allow the paralleled env workers consume a single DataQueue until it's exhausted. + + See `tianshou issue #322 `_. + + The requirement is to make every possible seed (stored in :class:`qlib.rl.utils.DataQueue` in our case) + consumed by exactly one environment. This is not possible by tianshou's native VectorEnv and Collector, + because tianshou is unaware of this "exactly one" constraint, and might launch extra workers. + + Consider a corner case, where concurrency is 2, but there is only one seed in DataQueue. + The reset of two workers must be both called according to the logic in collect. + The returned results of two workers are collected, regardless of what they are. + The problem is, one of the reset result must be invalid, or repeated, + because there's only one need in queue, and collector isn't aware of such situation. + + Luckily, we can hack the vector env, and make a protocol between single env and vector env. + The single environment (should be :class:`qlib.rl.utils.EnvWrapper` in our case) is responsible for + reading from queue, and generate a special observation when the queue is exhausted. The special obs + is called "nan observation", because simply using none causes problems in shared-memory vector env. + :class:`FiniteVectorEnv` then read the observations from all workers, and select those non-nan + observation. It also maintains an ``_alive_env_ids`` to track which workers should never be + called again. When also the environments are exhausted, it will raise StopIteration exception. + + The usage of this vector env in collector are two parts: + + 1. If the data queue is finite (usually when inference), collector should collect "infinity" number of + episodes, until the vector env exhausts by itself. + 2. If the data queue is infinite (usually in training), collector can set number of episodes / steps. + In this case, data would be randomly ordered, and some repetitions wouldn't matter. + + One extra function of this vector env is that it has a logger that explicitly collects logs + from child workers. See :class:`qlib.rl.utils.LogWriter`. + """ + + _logger: list[LogWriter] + + def __init__( + self, logger: LogWriter | list[LogWriter] | None, env_fns: list[Callable[..., gym.Env]], **kwargs: Any + ) -> None: + super().__init__(env_fns, **kwargs) + + if isinstance(logger, list): + self._logger = logger + elif isinstance(logger, LogWriter): + self._logger = [logger] + else: + self._logger = [] + self._alive_env_ids: Set[int] = set() + self._reset_alive_envs() + self._default_obs = self._default_info = self._default_rew = None + self._zombie = False + + self._collector_guarded: bool = False + + def _reset_alive_envs(self) -> None: + if not self._alive_env_ids: + # starting or running out + self._alive_env_ids = set(range(self.env_num)) + + # to workaround with tianshou's buffer and batch + def _set_default_obs(self, obs: Any) -> None: + if obs is not None and self._default_obs is None: + self._default_obs = copy.deepcopy(obs) + + def _set_default_info(self, info: Any) -> None: + if info is not None and self._default_info is None: + self._default_info = copy.deepcopy(info) + + def _set_default_rew(self, rew: Any) -> None: + if rew is not None and self._default_rew is None: + self._default_rew = copy.deepcopy(rew) + + def _get_default_obs(self) -> Any: + return copy.deepcopy(self._default_obs) + + def _get_default_info(self) -> Any: + return copy.deepcopy(self._default_info) + + def _get_default_rew(self) -> Any: + return copy.deepcopy(self._default_rew) + + # END + + @staticmethod + def _postproc_env_obs(obs: Any) -> Optional[Any]: + # reserved for shmem vector env to restore empty observation + if obs is None or check_nan_observation(obs): + return None + return obs + + @contextmanager + def collector_guard(self) -> Generator[FiniteVectorEnv, None, None]: + """Guard the collector. Recommended to guard every collect. + + This guard is for two purposes. + + 1. Catch and ignore the StopIteration exception, which is the stopping signal + thrown by FiniteEnv to let tianshou know that ``collector.collect()`` should exit. + 2. Notify the loggers that the collect is ready / done what it's ready / done. + + Examples + -------- + >>> with finite_env.collector_guard(): + ... collector.collect(n_episode=INF) + """ + self._collector_guarded = True + + for logger in self._logger: + logger.on_env_all_ready() + + try: + yield self + except StopIteration: + pass + finally: + self._collector_guarded = False + + # At last trigger the loggers + for logger in self._logger: + logger.on_env_all_done() + + def reset( + self, + id: int | List[int] | np.ndarray | None = None, + ) -> np.ndarray: + assert not self._zombie + + # Check whether it's guarded by collector_guard() + if not self._collector_guarded: + warnings.warn( + "Collector is not guarded by FiniteEnv. " + "This may cause unexpected problems, like unexpected StopIteration exception, " + "or missing logs.", + RuntimeWarning, + ) + + wrapped_id = self._wrap_id(id) + self._reset_alive_envs() + + # ask super to reset alive envs and remap to current index + request_id = [i for i in wrapped_id if i in self._alive_env_ids] + obs = [None] * len(wrapped_id) + id2idx = {i: k for k, i in enumerate(wrapped_id)} + if request_id: + for i, o in zip(request_id, super().reset(request_id)): + obs[id2idx[i]] = self._postproc_env_obs(o) + + for i, o in zip(wrapped_id, obs): + if o is None and i in self._alive_env_ids: + self._alive_env_ids.remove(i) + + # logging + for i, o in zip(wrapped_id, obs): + if i in self._alive_env_ids: + for logger in self._logger: + logger.on_env_reset(i, obs) + + # fill empty observation with default(fake) observation + for o in obs: + self._set_default_obs(o) + for i, o in enumerate(obs): + if o is None: + obs[i] = self._get_default_obs() + + if not self._alive_env_ids: + # comment this line so that the env becomes indispensable + # self.reset() + self._zombie = True + raise StopIteration + + return np.stack(obs) + + def step( + self, + action: np.ndarray, + id: int | List[int] | np.ndarray | None = None, + ) -> Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray]: + assert not self._zombie + wrapped_id = self._wrap_id(id) + id2idx = {i: k for k, i in enumerate(wrapped_id)} + request_id = list(filter(lambda i: i in self._alive_env_ids, wrapped_id)) + result = [[None, None, False, None] for _ in range(len(wrapped_id))] + + # ask super to step alive envs and remap to current index + if request_id: + valid_act = np.stack([action[id2idx[i]] for i in request_id]) + for i, r in zip(request_id, zip(*super().step(valid_act, request_id))): + result[id2idx[i]] = list(r) + result[id2idx[i]][0] = self._postproc_env_obs(result[id2idx[i]][0]) + + # logging + for i, r in zip(wrapped_id, result): + if i in self._alive_env_ids: + for logger in self._logger: + logger.on_env_step(i, *r) + + # fill empty observation/info with default(fake) + for _, r, ___, i in result: + self._set_default_info(i) + self._set_default_rew(r) + for i, r in enumerate(result): + if r[0] is None: + result[i][0] = self._get_default_obs() + if r[1] is None: + result[i][1] = self._get_default_rew() + if r[3] is None: + result[i][3] = self._get_default_info() + + ret = list(map(np.stack, zip(*result))) + return cast(Tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray], ret) + + +class FiniteDummyVectorEnv(FiniteVectorEnv, DummyVectorEnv): + pass + + +class FiniteSubprocVectorEnv(FiniteVectorEnv, SubprocVectorEnv): + pass + + +class FiniteShmemVectorEnv(FiniteVectorEnv, ShmemVectorEnv): + pass + + +def vectorize_env( + env_factory: Callable[..., gym.Env], + env_type: FiniteEnvType, + concurrency: int, + logger: LogWriter | List[LogWriter], +) -> FiniteVectorEnv: + """Helper function to create a vector env. Can be used to replace usual VectorEnv. + + For example, once you wrote: :: + + DummyVectorEnv([lambda: gym.make(task) for _ in range(env_num)]) + + Now you can replace it with: :: + + finite_env_factory(lambda: gym.make(task), "dummy", env_num, my_logger) + + By doing such replacement, you have two additional features enabled (compared to normal VectorEnv): + + 1. The vector env will check for NaN observation and kill the worker when its found. + See :class:`FiniteVectorEnv` for why we need this. + 2. A logger to explicit collect logs from environment workers. + + Parameters + ---------- + env_factory + Callable to instantiate one single ``gym.Env``. + All concurrent workers will have the same ``env_factory``. + env_type + dummy or subproc or shmem. Corresponding to + `parallelism in tianshou `_. + concurrency + Concurrent environment workers. + logger + Log writers. + + Warnings + -------- + Please do not use lambda expression here for ``env_factory`` as it may create incorrectly-shared instances. + + Don't do: :: + + vectorize_env(lambda: EnvWrapper(...), ...) + + Please do: :: + + def env_factory(): ... + vectorize_env(env_factory, ...) + """ + env_type_cls_mapping: Dict[str, Type[FiniteVectorEnv]] = { + "dummy": FiniteDummyVectorEnv, + "subproc": FiniteSubprocVectorEnv, + "shmem": FiniteShmemVectorEnv, + } + + finite_env_cls = env_type_cls_mapping[env_type] + + return finite_env_cls(logger, [env_factory for _ in range(concurrency)]) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/log.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/log.py new file mode 100644 index 0000000000000000000000000000000000000000..75aab20688552d35edc3382d016016e2d4eb2754 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/rl/utils/log.py @@ -0,0 +1,523 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Distributed logger for RL. + +:class:`LogCollector` runs in every environment workers. It collects log info from simulator states, +and add them (as a dict) to auxiliary info returned for each step. + +:class:`LogWriter` runs in the central worker. It decodes the dict collected by :class:`LogCollector` +in each worker, and writes them to console, log files, or tensorboard... + +The two modules communicate by the "log" field in "info" returned by ``env.step()``. +""" + +# NOTE: This file contains many hardcoded / ad-hoc rules. +# Refactoring it will be one of the future tasks. + +from __future__ import annotations + +import logging +from collections import defaultdict +from enum import IntEnum +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Dict, Generic, List, Sequence, Set, Tuple, TypeVar + +import numpy as np +import pandas as pd + +from qlib.log import get_module_logger + +if TYPE_CHECKING: + from .env_wrapper import InfoDict + + +__all__ = ["LogCollector", "LogWriter", "LogLevel", "LogBuffer", "ConsoleWriter", "CsvWriter"] + +ObsType = TypeVar("ObsType") +ActType = TypeVar("ActType") + + +class LogLevel(IntEnum): + """Log-levels for RL training. + The behavior of handling each log level depends on the implementation of :class:`LogWriter`. + """ + + DEBUG = 10 + """If you only want to see the metric in debug mode.""" + PERIODIC = 20 + """If you want to see the metric periodically.""" + # FIXME: I haven't given much thought about this. Let's hold it for one iteration. + + INFO = 30 + """Important log messages.""" + CRITICAL = 40 + """LogWriter should always handle CRITICAL messages""" + + +class LogCollector: + """Logs are first collected in each environment worker, + and then aggregated to stream at the central thread in vector env. + + In :class:`LogCollector`, every metric is added to a dict, which needs to be ``reset()`` at each step. + The dict is sent via the ``info`` in ``env.step()``, and decoded by the :class:`LogWriter` at vector env. + + ``min_loglevel`` is for optimization purposes: to avoid too much traffic on networks / in pipe. + """ + + _logged: Dict[str, Tuple[int, Any]] + _min_loglevel: int + + def __init__(self, min_loglevel: int | LogLevel = LogLevel.PERIODIC) -> None: + self._min_loglevel = int(min_loglevel) + + def reset(self) -> None: + """Clear all collected contents.""" + self._logged = {} + + def _add_metric(self, name: str, metric: Any, loglevel: int | LogLevel) -> None: + if name in self._logged: + raise ValueError(f"A metric with {name} is already added. Please change a name or reset the log collector.") + self._logged[name] = (int(loglevel), metric) + + def add_string(self, name: str, string: str, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None: + """Add a string with name into logged contents.""" + if loglevel < self._min_loglevel: + return + if not isinstance(string, str): + raise TypeError(f"{string} is not a string.") + self._add_metric(name, string, loglevel) + + def add_scalar(self, name: str, scalar: Any, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None: + """Add a scalar with name into logged contents. + Scalar will be converted into a float. + """ + if loglevel < self._min_loglevel: + return + + if hasattr(scalar, "item"): + # could be single-item number + scalar = scalar.item() + if not isinstance(scalar, (float, int)): + raise TypeError(f"{scalar} is not and can not be converted into float or integer.") + scalar = float(scalar) + self._add_metric(name, scalar, loglevel) + + def add_array( + self, + name: str, + array: np.ndarray | pd.DataFrame | pd.Series, + loglevel: int | LogLevel = LogLevel.PERIODIC, + ) -> None: + """Add an array with name into logging.""" + if loglevel < self._min_loglevel: + return + + if not isinstance(array, (np.ndarray, pd.DataFrame, pd.Series)): + raise TypeError(f"{array} is not one of ndarray, DataFrame and Series.") + self._add_metric(name, array, loglevel) + + def add_any(self, name: str, obj: Any, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None: + """Log something with any type. + + As it's an "any" object, the only LogWriter accepting it is pickle. + Therefore, pickle must be able to serialize it. + """ + if loglevel < self._min_loglevel: + return + + # FIXME: detect and rescue object that could be scalar or array + + self._add_metric(name, obj, loglevel) + + def logs(self) -> Dict[str, np.ndarray]: + return {key: np.asanyarray(value, dtype="object") for key, value in self._logged.items()} + + +class LogWriter(Generic[ObsType, ActType]): + """Base class for log writers, triggered at every reset and step by finite env. + + What to do with a specific log depends on the implementation of subclassing :class:`LogWriter`. + The general principle is that, it should handle logs above its loglevel (inclusive), + and discard logs that are not acceptable. For instance, console loggers obviously can't handle an image. + """ + + episode_count: int + """Counter of episodes.""" + + step_count: int + """Counter of steps.""" + + global_step: int + """Counter of steps. Won"t be cleared in ``clear``.""" + + global_episode: int + """Counter of episodes. Won"t be cleared in ``clear``.""" + + active_env_ids: Set[int] + """Active environment ids in vector env.""" + + episode_lengths: Dict[int, int] + """Map from environment id to episode length.""" + + episode_rewards: Dict[int, List[float]] + """Map from environment id to episode total reward.""" + + episode_logs: Dict[int, list] + """Map from environment id to episode logs.""" + + def __init__(self, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None: + self.loglevel = loglevel + + self.global_step = 0 + self.global_episode = 0 + + # Information, logs of one episode is stored here. + # This assumes that episode is not too long to fit into the memory. + self.episode_lengths = dict() + self.episode_rewards = dict() + self.episode_logs = dict() + + self.clear() + + def clear(self): + """Clear all the metrics for a fresh start. + To make the logger instance reusable. + """ + self.episode_count = self.step_count = 0 + self.active_env_ids = set() + + def state_dict(self) -> dict: + """Save the states of the logger to a dict.""" + return { + "episode_count": self.episode_count, + "step_count": self.step_count, + "global_step": self.global_step, + "global_episode": self.global_episode, + "active_env_ids": self.active_env_ids, + "episode_lengths": self.episode_lengths, + "episode_rewards": self.episode_rewards, + "episode_logs": self.episode_logs, + } + + def load_state_dict(self, state_dict: dict) -> None: + """Load the states of current logger from a dict.""" + self.episode_count = state_dict["episode_count"] + self.step_count = state_dict["step_count"] + self.global_step = state_dict["global_step"] + self.global_episode = state_dict["global_episode"] + + # These are runtime infos. + # Though they are loaded, I don't think it really helps. + self.active_env_ids = state_dict["active_env_ids"] + self.episode_lengths = state_dict["episode_lengths"] + self.episode_rewards = state_dict["episode_rewards"] + self.episode_logs = state_dict["episode_logs"] + + @staticmethod + def aggregation(array: Sequence[Any], name: str | None = None) -> Any: + """Aggregation function from step-wise to episode-wise. + + If it's a sequence of float, take the mean. + Otherwise, take the first element. + + If a name is specified and, + + - if it's ``reward``, the reduction will be sum. + """ + assert len(array) > 0, "The aggregated array must be not empty." + if all(isinstance(v, float) for v in array): + if name == "reward": + return np.sum(array) + return np.mean(array) + else: + return array[0] + + def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None: + """This is triggered at the end of each trajectory. + + Parameters + ---------- + length + Length of this trajectory. + rewards + A list of rewards at each step of this episode. + contents + Logged contents for every step. + """ + + def log_step(self, reward: float, contents: Dict[str, Any]) -> None: + """This is triggered at each step. + + Parameters + ---------- + reward + Reward for this step. + contents + Logged contents for this step. + """ + + def on_env_step(self, env_id: int, obs: ObsType, rew: float, done: bool, info: InfoDict) -> None: + """Callback for finite env, on each step.""" + + # Update counter + self.global_step += 1 + self.step_count += 1 + + self.active_env_ids.add(env_id) + self.episode_lengths[env_id] += 1 + # TODO: reward can be a list of list for MARL + self.episode_rewards[env_id].append(rew) + + values: Dict[str, Any] = {} + + for key, (loglevel, value) in info["log"].items(): + if loglevel >= self.loglevel: # FIXME: this is actually incorrect (see last FIXME) + values[key] = value + self.episode_logs[env_id].append(values) + + self.log_step(rew, values) + + if done: + # Update counter + self.global_episode += 1 + self.episode_count += 1 + + self.log_episode(self.episode_lengths[env_id], self.episode_rewards[env_id], self.episode_logs[env_id]) + + def on_env_reset(self, env_id: int, _: ObsType) -> None: + """Callback for finite env. + + Reset episode statistics. Nothing task-specific is logged here because of + `a limitation of tianshou `__. + """ + self.episode_lengths[env_id] = 0 + self.episode_rewards[env_id] = [] + self.episode_logs[env_id] = [] + + def on_env_all_ready(self) -> None: + """When all environments are ready to run. + Usually, loggers should be reset here. + """ + self.clear() + + def on_env_all_done(self) -> None: + """All done. Time for cleanup.""" + + +class LogBuffer(LogWriter): + """Keep all numbers in memory. + + Objects that can't be aggregated like strings, tensors, images can't be stored in the buffer. + To persist them, please use :class:`PickleWriter`. + + Every time, Log buffer receives a new metric, the callback is triggered, + which is useful when tracking metrics inside a trainer. + + Parameters + ---------- + callback + A callback receiving three arguments: + + - on_episode: Whether it's called at the end of an episode + - on_collect: Whether it's called at the end of a collect + - log_buffer: the :class:`LogBbuffer` object + + No return value is expected. + """ + + # FIXME: needs a metric count + + def __init__(self, callback: Callable[[bool, bool, LogBuffer], None], loglevel: int | LogLevel = LogLevel.PERIODIC): + super().__init__(loglevel) + self.callback = callback + + def state_dict(self) -> dict: + return { + **super().state_dict(), + "latest_metrics": self._latest_metrics, + "aggregated_metrics": self._aggregated_metrics, + } + + def load_state_dict(self, state_dict: dict) -> None: + self._latest_metrics = state_dict["latest_metrics"] + self._aggregated_metrics = state_dict["aggregated_metrics"] + return super().load_state_dict(state_dict) + + def clear(self): + super().clear() + self._latest_metrics: dict[str, float] | None = None + self._aggregated_metrics: dict[str, float] = defaultdict(float) + + def log_episode(self, length: int, rewards: list[float], contents: list[dict[str, Any]]) -> None: + # FIXME Dup of ConsoleWriter + episode_wise_contents: dict[str, list] = defaultdict(list) + for step_contents in contents: + for name, value in step_contents.items(): + # FIXME This could be false-negative for some numpy types + if isinstance(value, float): + episode_wise_contents[name].append(value) + + logs: dict[str, float] = {} + for name, values in episode_wise_contents.items(): + logs[name] = self.aggregation(values, name) # type: ignore + self._aggregated_metrics[name] += logs[name] + + self._latest_metrics = logs + + self.callback(True, False, self) + + def on_env_all_done(self) -> None: + # This happens when collect exits + self.callback(False, True, self) + + def episode_metrics(self) -> dict[str, float]: + """Retrieve the numeric metrics of the latest episode.""" + if self._latest_metrics is None: + raise ValueError("No episode metrics available yet.") + return self._latest_metrics + + def collect_metrics(self) -> dict[str, float]: + """Retrieve the aggregated metrics of the latest collect.""" + return {name: value / self.episode_count for name, value in self._aggregated_metrics.items()} + + +class ConsoleWriter(LogWriter): + """Write log messages to console periodically. + + It tracks an average meter for each metric, which is the average value since last ``clear()`` till now. + The display format for each metric is `` ()``. + + Non-single-number metrics are auto skipped. + """ + + prefix: str + """Prefix can be set via ``writer.prefix``.""" + + def __init__( + self, + log_every_n_episode: int = 20, + total_episodes: int | None = None, + float_format: str = ":.4f", + counter_format: str = ":4d", + loglevel: int | LogLevel = LogLevel.PERIODIC, + ) -> None: + super().__init__(loglevel) + # TODO: support log_every_n_step + self.log_every_n_episode = log_every_n_episode + self.total_episodes = total_episodes + + self.counter_format = counter_format + self.float_format = float_format + + self.prefix = "" + + self.console_logger = get_module_logger(__name__, level=logging.INFO) + + # FIXME: save & reload + + def clear(self) -> None: + super().clear() + # Clear average meters + self.metric_counts: Dict[str, int] = defaultdict(int) + self.metric_sums: Dict[str, float] = defaultdict(float) + + def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None: + # Aggregate step-wise to episode-wise + episode_wise_contents: Dict[str, list] = defaultdict(list) + + for step_contents in contents: + for name, value in step_contents.items(): + if isinstance(value, float): + episode_wise_contents[name].append(value) + + # Generate log contents and track them in average-meter. + # This should be done at every step, regardless of periodic or not. + logs: Dict[str, float] = {} + for name, values in episode_wise_contents.items(): + logs[name] = self.aggregation(values, name) # type: ignore + + for name, value in logs.items(): + self.metric_counts[name] += 1 + self.metric_sums[name] += value + + if self.episode_count % self.log_every_n_episode == 0 or self.episode_count == self.total_episodes: + # Only log periodically or at the end + self.console_logger.info(self.generate_log_message(logs)) + + def generate_log_message(self, logs: Dict[str, float]) -> str: + if self.prefix: + msg_prefix = self.prefix + " " + else: + msg_prefix = "" + if self.total_episodes is None: + msg_prefix += "[Step {" + self.counter_format + "}]" + else: + msg_prefix += "[{" + self.counter_format + "}/" + str(self.total_episodes) + "]" + msg_prefix = msg_prefix.format(self.episode_count) + + msg = "" + for name, value in logs.items(): + # Double-space as delimiter + format_template = r" {} {" + self.float_format + "} ({" + self.float_format + "})" + msg += format_template.format(name, value, self.metric_sums[name] / self.metric_counts[name]) + + msg = msg_prefix + " " + msg + + return msg + + +class CsvWriter(LogWriter): + """Dump all episode metrics to a ``result.csv``. + + This is not the correct implementation. It's only used for first iteration. + """ + + SUPPORTED_TYPES = (float, str, pd.Timestamp) + + all_records: List[Dict[str, Any]] + + # FIXME: save & reload + + def __init__(self, output_dir: Path, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None: + super().__init__(loglevel) + self.output_dir = output_dir + self.output_dir.mkdir(exist_ok=True) + + def clear(self) -> None: + super().clear() + self.all_records = [] + + def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None: + # FIXME Same as ConsoleLogger, needs a refactor to eliminate code-dup + episode_wise_contents: Dict[str, list] = defaultdict(list) + + for step_contents in contents: + for name, value in step_contents.items(): + if isinstance(value, self.SUPPORTED_TYPES): + episode_wise_contents[name].append(value) + + logs: Dict[str, float] = {} + for name, values in episode_wise_contents.items(): + logs[name] = self.aggregation(values, name) # type: ignore + + self.all_records.append(logs) + + def on_env_all_done(self) -> None: + # FIXME: this is temporary + pd.DataFrame.from_records(self.all_records).to_csv(self.output_dir / "result.csv", index=False) + + +# The following are not implemented yet. + + +class PickleWriter(LogWriter): + """Dump logs to pickle files.""" + + +class TensorboardWriter(LogWriter): + """Write logs to event files that can be visualized with tensorboard.""" + + +class MlflowWriter(LogWriter): + """Add logs to mlflow.""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/strategy/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/strategy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59e481eb93dda48c81e04dd491cd3c9190c8eeb4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/strategy/__init__.py @@ -0,0 +1,2 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/strategy/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/strategy/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e138fdbb7825002cb4a36ff336e5c5f765468f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/strategy/base.py @@ -0,0 +1,296 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +from abc import ABCMeta, abstractmethod +from typing import Any, Generator, Optional, TYPE_CHECKING, Union + +if TYPE_CHECKING: + from qlib.backtest.exchange import Exchange + from qlib.backtest.position import BasePosition + from qlib.backtest.executor import BaseExecutor + +from typing import Tuple + +from ..backtest.decision import BaseTradeDecision +from ..backtest.utils import CommonInfrastructure, LevelInfrastructure, TradeCalendarManager +from ..rl.interpreter import ActionInterpreter, StateInterpreter +from ..utils import init_instance_by_config + +__all__ = ["BaseStrategy", "RLStrategy", "RLIntStrategy"] + + +class BaseStrategy: + """Base strategy for trading""" + + def __init__( + self, + outer_trade_decision: BaseTradeDecision = None, + level_infra: LevelInfrastructure = None, + common_infra: CommonInfrastructure = None, + trade_exchange: Exchange = None, + ) -> None: + """ + Parameters + ---------- + outer_trade_decision : BaseTradeDecision, optional + the trade decision of outer strategy which this strategy relies, and it will be traded in + [start_time, end_time], by default None + + - If the strategy is used to split trade decision, it will be used + - If the strategy is used for portfolio management, it can be ignored + level_infra : LevelInfrastructure, optional + level shared infrastructure for backtesting, including trade calendar + common_infra : CommonInfrastructure, optional + common infrastructure for backtesting, including trade_account, trade_exchange, .etc + + trade_exchange : Exchange + exchange that provides market info, used to deal order and generate report + + - If `trade_exchange` is None, self.trade_exchange will be set with common_infra + - It allows different trade_exchanges is used in different executions. + - For example: + + - In daily execution, both daily exchange and minutely are usable, but the daily exchange is + recommended because it run faster. + - In minutely execution, the daily exchange is not usable, only the minutely exchange is recommended. + """ + + self._reset(level_infra=level_infra, common_infra=common_infra, outer_trade_decision=outer_trade_decision) + self._trade_exchange = trade_exchange + + @property + def executor(self) -> BaseExecutor: + return self.level_infra.get("executor") + + @property + def trade_calendar(self) -> TradeCalendarManager: + return self.level_infra.get("trade_calendar") + + @property + def trade_position(self) -> BasePosition: + return self.common_infra.get("trade_account").current_position + + @property + def trade_exchange(self) -> Exchange: + """get trade exchange in a prioritized order""" + return getattr(self, "_trade_exchange", None) or self.common_infra.get("trade_exchange") + + def reset_level_infra(self, level_infra: LevelInfrastructure) -> None: + if not hasattr(self, "level_infra"): + self.level_infra = level_infra + else: + self.level_infra.update(level_infra) + + def reset_common_infra(self, common_infra: CommonInfrastructure) -> None: + if not hasattr(self, "common_infra"): + self.common_infra: CommonInfrastructure = common_infra + else: + self.common_infra.update(common_infra) + + def reset( + self, + level_infra: LevelInfrastructure = None, + common_infra: CommonInfrastructure = None, + outer_trade_decision: BaseTradeDecision = None, + **kwargs, + ) -> None: + """ + - reset `level_infra`, used to reset trade calendar, .etc + - reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc + - reset `outer_trade_decision`, used to make split decision + + **NOTE**: + split this function into `reset` and `_reset` will make following cases more convenient + 1. Users want to initialize his strategy by overriding `reset`, but they don't want to affect the `_reset` + called when initialization + """ + self._reset( + level_infra=level_infra, + common_infra=common_infra, + outer_trade_decision=outer_trade_decision, + ) + + def _reset( + self, + level_infra: LevelInfrastructure = None, + common_infra: CommonInfrastructure = None, + outer_trade_decision: BaseTradeDecision = None, + ): + """ + Please refer to the docs of `reset` + """ + if level_infra is not None: + self.reset_level_infra(level_infra) + + if common_infra is not None: + self.reset_common_infra(common_infra) + + if outer_trade_decision is not None: + self.outer_trade_decision = outer_trade_decision + + @abstractmethod + def generate_trade_decision( + self, + execute_result: list = None, + ) -> Union[BaseTradeDecision, Generator[Any, Any, BaseTradeDecision]]: + """Generate trade decision in each trading bar + + Parameters + ---------- + execute_result : List[object], optional + the executed result for trade decision, by default None + + - When call the generate_trade_decision firstly, `execute_result` could be None + """ + raise NotImplementedError("generate_trade_decision is not implemented!") + + # helper methods: not necessary but for convenience + def get_data_cal_avail_range(self, rtype: str = "full") -> Tuple[int, int]: + """ + return data calendar's available decision range for `self` strategy + the range consider following factors + - data calendar in the charge of `self` strategy + - trading range limitation from the decision of outer strategy + + + related methods + - TradeCalendarManager.get_data_cal_range + - BaseTradeDecision.get_data_cal_range_limit + + Parameters + ---------- + rtype: str + - "full": return the available data index range of the strategy from `start_time` to `end_time` + - "step": return the available data index range of the strategy of current step + + Returns + ------- + Tuple[int, int]: + the available range both sides are closed + """ + cal_range = self.trade_calendar.get_data_cal_range(rtype=rtype) + if self.outer_trade_decision is None: + raise ValueError(f"There is not limitation for strategy {self}") + range_limit = self.outer_trade_decision.get_data_cal_range_limit(rtype=rtype) + return max(cal_range[0], range_limit[0]), min(cal_range[1], range_limit[1]) + + """ + The following methods are used to do cross-level communications in nested execution. + You do not need to care about them if you are implementing a single-level execution. + """ + + @staticmethod + def update_trade_decision( + trade_decision: BaseTradeDecision, + trade_calendar: TradeCalendarManager, + ) -> Optional[BaseTradeDecision]: + """ + update trade decision in each step of inner execution, this method enable all order + + Parameters + ---------- + trade_decision : BaseTradeDecision + the trade decision that will be updated + trade_calendar : TradeCalendarManager + The calendar of the **inner strategy**!!!!! + + Returns + ------- + BaseTradeDecision: + """ + # default to return None, which indicates that the trade decision is not changed + return None + + def alter_outer_trade_decision(self, outer_trade_decision: BaseTradeDecision) -> BaseTradeDecision: + """ + A method for updating the outer_trade_decision. + The outer strategy may change its decision during updating. + + Parameters + ---------- + outer_trade_decision : BaseTradeDecision + the decision updated by the outer strategy + + Returns + ------- + BaseTradeDecision + """ + # default to reset the decision directly + # NOTE: normally, user should do something to the strategy due to the change of outer decision + return outer_trade_decision + + def post_upper_level_exe_step(self) -> None: + """ + A hook for doing sth after the upper level executor finished its execution (for example, finalize + the metrics collection). + """ + + def post_exe_step(self, execute_result: Optional[list]) -> None: + """ + A hook for doing sth after the corresponding executor finished its execution. + + Parameters + ---------- + execute_result : + the execution result + """ + + +class RLStrategy(BaseStrategy, metaclass=ABCMeta): + """RL-based strategy""" + + def __init__( + self, + policy, + outer_trade_decision: BaseTradeDecision = None, + level_infra: LevelInfrastructure = None, + common_infra: CommonInfrastructure = None, + **kwargs, + ) -> None: + """ + Parameters + ---------- + policy : + RL policy for generate action + """ + super(RLStrategy, self).__init__(outer_trade_decision, level_infra, common_infra, **kwargs) + self.policy = policy + + +class RLIntStrategy(RLStrategy, metaclass=ABCMeta): + """(RL)-based (Strategy) with (Int)erpreter""" + + def __init__( + self, + policy, + state_interpreter: dict | StateInterpreter, + action_interpreter: dict | ActionInterpreter, + outer_trade_decision: BaseTradeDecision = None, + level_infra: LevelInfrastructure = None, + common_infra: CommonInfrastructure = None, + **kwargs, + ) -> None: + """ + Parameters + ---------- + state_interpreter : Union[dict, StateInterpreter] + interpreter that interprets the qlib execute result into rl env state + action_interpreter : Union[dict, ActionInterpreter] + interpreter that interprets the rl agent action into qlib order list + start_time : Union[str, pd.Timestamp], optional + start time of trading, by default None + end_time : Union[str, pd.Timestamp], optional + end time of trading, by default None + """ + super(RLIntStrategy, self).__init__(policy, outer_trade_decision, level_infra, common_infra, **kwargs) + + self.policy = policy + self.state_interpreter = init_instance_by_config(state_interpreter, accept_types=StateInterpreter) + self.action_interpreter = init_instance_by_config(action_interpreter, accept_types=ActionInterpreter) + + def generate_trade_decision(self, execute_result: list = None) -> BaseTradeDecision: + _interpret_state = self.state_interpreter.interpret(execute_result=execute_result) + _action = self.policy.step(_interpret_state) + _trade_decision = self.action_interpreter.interpret(action=_action) + return _trade_decision diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9793cdabde511b64f5bea93e597526b29a2a439 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/__init__.py @@ -0,0 +1,289 @@ +from typing import Union, List, Dict, Tuple +import unittest +import pandas as pd +import numpy as np +import io + +from .data import GetData +from .. import init +from ..constant import REG_CN, REG_TW +from qlib.data.filter import NameDFilter +from qlib.data import D +from qlib.data.data import Cal, DatasetD +from qlib.data.storage import CalendarStorage, InstrumentStorage, FeatureStorage, CalVT, InstKT, InstVT + + +class TestAutoData(unittest.TestCase): + _setup_kwargs = {} + provider_uri = "~/.qlib/qlib_data/cn_data_simple" # target_dir + provider_uri_1day = "~/.qlib/qlib_data/cn_data" # target_dir + provider_uri_1min = "~/.qlib/qlib_data/cn_data_1min" + + @classmethod + def setUpClass(cls, enable_1d_type="simple", enable_1min=False) -> None: + # use default data + + if enable_1d_type == "simple": + provider_uri_day = cls.provider_uri + name_day = "qlib_data_simple" + elif enable_1d_type == "full": + provider_uri_day = cls.provider_uri_1day + name_day = "qlib_data" + else: + raise NotImplementedError(f"This type of input is not supported") + + GetData().qlib_data( + name=name_day, + region=REG_CN, + interval="1d", + target_dir=provider_uri_day, + delete_old=False, + exists_skip=True, + ) + + if enable_1min: + GetData().qlib_data( + name="qlib_data", + region=REG_CN, + interval="1min", + target_dir=cls.provider_uri_1min, + delete_old=False, + exists_skip=True, + ) + + provider_uri_map = {"1min": cls.provider_uri_1min, "day": provider_uri_day} + init( + provider_uri=provider_uri_map, + region=REG_CN, + expression_cache=None, + dataset_cache=None, + **cls._setup_kwargs, + ) + + +class TestOperatorData(TestAutoData): + @classmethod + def setUpClass(cls, enable_1d_type="simple", enable_1min=False) -> None: + # use default data + super().setUpClass(enable_1d_type, enable_1min) + nameDFilter = NameDFilter(name_rule_re="SH600110") + instruments = D.instruments("csi300", filter_pipe=[nameDFilter]) + start_time = "2005-01-04" + end_time = "2005-12-31" + freq = "day" + + instruments_d = DatasetD.get_instruments_d(instruments, freq) + cls.instruments_d = instruments_d + cal = Cal.calendar(start_time, end_time, freq) + cls.cal = cal + cls.start_time = cal[0] + cls.end_time = cal[-1] + cls.inst = list(instruments_d.keys())[0] + cls.spans = list(instruments_d.values())[0] + + +MOCK_DATA = """ +id,symbol,datetime,interval,volume,open,high,low,close +20275,0050,2022-01-03 00:00:00,day,6761.0,146.0,147.35,146.0,146.4 +20276,0050,2022-01-04 00:00:00,day,9608.0,147.7,149.6,147.7,149.6 +20277,0050,2022-01-05 00:00:00,day,11387.0,150.1,150.55,149.1,149.3 +20278,0050,2022-01-06 00:00:00,day,8611.0,148.3,148.75,147.0,147.9 +20279,0050,2022-01-07 00:00:00,day,6954.0,148.3,149.0,146.5,146.6 +20280,0050,2022-01-10 00:00:00,day,15684.0,146.0,147.8,145.4,147.55 +20281,0050,2022-01-11 00:00:00,day,17741.0,147.6,148.5,146.7,148.3 +20282,0050,2022-01-12 00:00:00,day,10134.0,149.35,149.6,148.7,149.55 +20283,0050,2022-01-13 00:00:00,day,7431.0,149.55,150.45,149.55,150.3 +20284,0050,2022-01-14 00:00:00,day,10091.0,150.8,151.2,149.05,150.3 +20285,0050,2022-01-17 00:00:00,day,6899.0,151.1,152.4,151.1,152.0 +20286,0050,2022-01-18 00:00:00,day,14360.0,152.2,152.25,150.15,150.3 +20287,0050,2022-01-19 00:00:00,day,14654.0,149.0,149.65,148.25,148.5 +20288,0050,2022-01-20 00:00:00,day,16201.0,148.5,149.2,147.6,149.1 +20289,0050,2022-01-21 00:00:00,day,29848.0,143.9,143.95,142.3,142.65 +20290,0050,2022-01-24 00:00:00,day,13143.0,142.1,144.0,141.7,144.0 +20291,0050,2022-01-25 00:00:00,day,23982.0,142.55,142.55,141.25,141.65 +20292,0050,2022-01-26 00:00:00,day,17729.0,141.15,142.2,141.05,141.55 +8547,1101,2021-12-01 00:00:00,day,16119.0,46.0,46.85,46.0,46.6 +8548,1101,2021-12-02 00:00:00,day,14521.0,46.6,46.7,46.3,46.3 +8549,1101,2021-12-03 00:00:00,day,14357.0,46.55,46.85,46.4,46.4 +8550,1101,2021-12-06 00:00:00,day,15115.0,46.45,47.35,46.4,47.3 +8551,1101,2021-12-07 00:00:00,day,13117.0,47.35,47.55,46.9,47.55 +8552,1101,2021-12-08 00:00:00,day,10329.0,47.75,47.8,47.5,47.7 +8553,1101,2021-12-09 00:00:00,day,9300.0,47.8,47.85,47.1,47.4 +8554,1101,2021-12-10 00:00:00,day,9919.0,47.4,47.6,47.1,47.3 +8555,1101,2021-12-13 00:00:00,day,7784.0,47.3,47.75,47.1,47.1 +8556,1101,2021-12-14 00:00:00,day,9373.0,47.05,47.2,46.95,47.0 +8557,1101,2021-12-15 00:00:00,day,11189.0,47.0,47.3,46.8,46.95 +8558,1101,2021-12-16 00:00:00,day,7516.0,47.0,47.15,46.8,46.9 +8559,1101,2021-12-17 00:00:00,day,18502.0,46.95,47.6,46.9,47.45 +8560,1101,2021-12-20 00:00:00,day,11309.0,47.45,47.5,47.1,47.4 +8561,1101,2021-12-21 00:00:00,day,5666.0,47.4,47.45,47.1,47.25 +8562,1101,2021-12-22 00:00:00,day,5460.0,47.4,47.45,47.2,47.4 +8563,1101,2021-12-23 00:00:00,day,9371.0,47.3,47.7,47.3,47.7 +8564,1101,2021-12-24 00:00:00,day,5980.0,47.75,47.95,47.75,47.9 +8565,1101,2021-12-27 00:00:00,day,5709.0,47.9,48.1,47.9,48.1 +8566,1101,2021-12-28 00:00:00,day,7777.0,48.1,48.15,47.95,48.15 +8567,1101,2021-12-29 00:00:00,day,5309.0,48.15,48.25,48.05,48.15 +8568,1101,2021-12-30 00:00:00,day,4616.0,48.15,48.2,48.0,48.0 +8569,1101,2022-01-03 00:00:00,day,12350.0,48.05,48.15,47.35,47.45 +8570,1101,2022-01-04 00:00:00,day,11439.0,47.5,47.6,47.0,47.3 +8571,1101,2022-01-05 00:00:00,day,9692.0,47.1,47.3,47.0,47.15 +8572,1101,2022-01-06 00:00:00,day,12361.0,47.3,47.6,47.15,47.6 +8573,1101,2022-01-07 00:00:00,day,10921.0,47.6,47.65,47.2,47.45 +8574,1101,2022-01-10 00:00:00,day,11925.0,47.45,47.5,47.0,47.3 +8575,1101,2022-01-11 00:00:00,day,11047.0,47.1,47.5,47.1,47.5 +8576,1101,2022-01-12 00:00:00,day,10817.0,47.5,47.5,47.1,47.5 +8577,1101,2022-01-13 00:00:00,day,13849.0,47.5,47.95,47.4,47.95 +8578,1101,2022-01-14 00:00:00,day,9460.0,47.85,47.85,47.45,47.6 +8579,1101,2022-01-17 00:00:00,day,9057.0,47.55,47.7,47.35,47.6 +8580,1101,2022-01-18 00:00:00,day,8089.0,47.6,47.75,47.45,47.75 +8581,1101,2022-01-19 00:00:00,day,5110.0,47.6,47.7,47.5,47.6 +8582,1101,2022-01-20 00:00:00,day,6327.0,47.55,47.7,47.45,47.5 +8583,1101,2022-01-21 00:00:00,day,9470.0,47.5,47.65,47.15,47.4 +8584,1101,2022-01-24 00:00:00,day,5475.0,47.1,47.3,47.0,47.15 +8585,1101,2022-01-25 00:00:00,day,16153.0,47.0,47.05,46.6,46.8 +8586,1101,2022-01-26 00:00:00,day,7772.0,46.7,47.0,46.55,46.85 +8587,1101,2022-02-07 00:00:00,day,17031.0,46.55,47.1,46.0,47.1 +8588,1101,2022-02-08 00:00:00,day,9741.0,47.1,47.25,46.9,46.95 +8589,1101,2022-02-09 00:00:00,day,7968.0,46.95,47.3,46.9,47.3 +8590,1101,2022-02-10 00:00:00,day,7479.0,47.15,47.55,47.05,47.55 +8591,1101,2022-02-11 00:00:00,day,6841.0,47.3,47.55,47.15,47.55 +8592,1101,2022-02-14 00:00:00,day,9136.0,47.2,47.3,46.95,47.15 +8593,1101,2022-02-15 00:00:00,day,5444.0,47.05,47.1,46.8,47.0 +8594,1101,2022-02-16 00:00:00,day,8751.0,47.0,47.15,47.0,47.0 +8595,1101,2022-02-17 00:00:00,day,10662.0,47.15,47.55,47.1,47.45 +8596,1101,2022-02-18 00:00:00,day,8781.0,47.25,47.55,47.2,47.45 +8597,1101,2022-02-21 00:00:00,day,8201.0,47.35,47.75,47.15,47.6 +8598,1101,2022-02-22 00:00:00,day,10655.0,47.4,47.7,47.1,47.7 +8599,1101,2022-02-23 00:00:00,day,8040.0,47.7,47.85,47.45,47.65 +8600,1101,2022-02-24 00:00:00,day,13124.0,47.5,47.5,47.1,47.3 +8601,1101,2022-02-25 00:00:00,day,14556.0,47.2,47.5,46.9,47.35 +""" + +MOCK_DF = pd.read_csv(io.StringIO(MOCK_DATA), header=0, dtype={"symbol": str}) + + +class MockStorageBase: + def __init__(self, **kwargs): + self.df = MOCK_DF + + +class MockCalendarStorage(MockStorageBase, CalendarStorage): + def __init__(self, **kwargs): + super().__init__() + self._data = sorted(self.df["datetime"].unique()) + + @property + def data(self) -> List[CalVT]: + return self._data + + def __getitem__(self, i: Union[int, slice]) -> Union[CalVT, List[CalVT]]: + return self.data[i] + + def __len__(self) -> int: + return len(self.data) + + +class MockInstrumentStorage(MockStorageBase, InstrumentStorage): + def __init__(self, **kwargs): + super().__init__() + instruments = {} + for symbol, group in self.df.groupby(by="symbol", group_keys=False): + start = group["datetime"].iloc[0] + end = group["datetime"].iloc[-1] + instruments[symbol] = [(start, end)] + self._data = instruments + + @property + def data(self) -> Dict[InstKT, InstVT]: + return self._data + + def __getitem__(self, k: InstKT) -> InstVT: + return self.data[k] + + def __len__(self) -> int: + return len(self.data) + + +class MockFeatureStorage(MockStorageBase, FeatureStorage): + def __init__(self, instrument: str, field: str, freq: str, db_region: str = None, **kwargs): # type: ignore + super().__init__(instrument=instrument, field=field, freq=freq, db_region=db_region, **kwargs) + self.field = field + calendar = sorted(self.df["datetime"].unique()) + df_calendar = pd.DataFrame(calendar, columns=["datetime"]).set_index("datetime") + df = self.df[self.df["symbol"] == instrument] + data_dt_field = "datetime" + cal_df = df_calendar[ + (df_calendar.index >= df[data_dt_field].min()) & (df_calendar.index <= df[data_dt_field].max()) + ] + df = df.set_index(data_dt_field) + df_data = df.reindex(cal_df.index) + date_index = df_calendar.index.get_loc(df_data.index.min()) # type: ignore + df_data.reset_index(inplace=True) + df_data.index += date_index + self._data = df_data + + @property + def data(self) -> pd.Series: + return self._data[self.field] + + @property + def start_index(self) -> Union[int, None]: + if self._data.empty: + return None + return self._data.index[0] + + @property + def end_index(self) -> Union[int, None]: + if self._data.empty: + return None + # The next data appending index point will be `end_index + 1` + return self._data.index[-1] + + def __getitem__(self, i: Union[int, slice]) -> Union[Tuple[int, float], pd.Series]: + df = self._data + storage_start_index = df.index[0] + storage_end_index = df.index[-1] + if isinstance(i, int): + if storage_start_index > i or i > storage_end_index: + raise IndexError(f"{i}: start index is {storage_start_index}") + data = self.data[i] + return i, data + elif isinstance(i, slice): + start_index = storage_start_index if i.start is None else i.start + end_index = storage_end_index if i.stop is None else i.stop + si = max(start_index, storage_start_index) + if si > end_index or self.field not in df.columns: + return pd.Series(dtype=np.float32) # type: ignore + data = df[self.field].tolist() + result = data[si - storage_start_index : end_index - storage_start_index] + return pd.Series(result, index=pd.RangeIndex(si, si + len(result))) # type: ignore + else: + raise TypeError(f"type(i) = {type(i)}") + + def __len__(self) -> int: + return len(self.data) + + +class TestMockData(unittest.TestCase): + _setup_kwargs = { + "calendar_provider": { + "class": "LocalCalendarProvider", + "module_path": "qlib.data.data", + "kwargs": {"backend": {"class": "MockCalendarStorage", "module_path": "qlib.tests"}}, + }, + "instrument_provider": { + "class": "LocalInstrumentProvider", + "module_path": "qlib.data.data", + "kwargs": {"backend": {"class": "MockInstrumentStorage", "module_path": "qlib.tests"}}, + }, + "feature_provider": { + "class": "LocalFeatureProvider", + "module_path": "qlib.data.data", + "kwargs": {"backend": {"class": "MockFeatureStorage", "module_path": "qlib.tests"}}, + }, + } + + @classmethod + def setUpClass(cls) -> None: + provider_uri = "Not necessary." + init(region=REG_TW, provider_uri=provider_uri, expression_cache=None, dataset_cache=None, **cls._setup_kwargs) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/config.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/config.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1b236594569b65262b7cd0bc5e713aaf35001d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/config.py @@ -0,0 +1,167 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +CSI300_MARKET = "csi300" +CSI100_MARKET = "csi100" + +CSI300_BENCH = "SH000300" + +DATASET_ALPHA158_CLASS = "Alpha158" +DATASET_ALPHA360_CLASS = "Alpha360" + +################################### +# config +################################### + + +GBDT_MODEL = { + "class": "LGBModel", + "module_path": "qlib.contrib.model.gbdt", + "kwargs": { + "loss": "mse", + "colsample_bytree": 0.8879, + "learning_rate": 0.0421, + "subsample": 0.8789, + "lambda_l1": 205.6999, + "lambda_l2": 580.9768, + "max_depth": 8, + "num_leaves": 210, + "num_threads": 20, + }, +} + + +SA_RC = { + "class": "SigAnaRecord", + "module_path": "qlib.workflow.record_temp", +} + + +RECORD_CONFIG = [ + { + "class": "SignalRecord", + "module_path": "qlib.workflow.record_temp", + "kwargs": { + "dataset": "", + "model": "", + }, + }, + SA_RC, +] + + +def get_data_handler_config( + start_time="2008-01-01", + end_time="2020-08-01", + fit_start_time="", + fit_end_time="", + instruments=CSI300_MARKET, +): + return { + "start_time": start_time, + "end_time": end_time, + "fit_start_time": fit_start_time, + "fit_end_time": fit_end_time, + "instruments": instruments, + } + + +def get_dataset_config( + dataset_class=DATASET_ALPHA158_CLASS, + train=("2008-01-01", "2014-12-31"), + valid=("2015-01-01", "2016-12-31"), + test=("2017-01-01", "2020-08-01"), + handler_kwargs={"instruments": CSI300_MARKET}, +): + return { + "class": "DatasetH", + "module_path": "qlib.data.dataset", + "kwargs": { + "handler": { + "class": dataset_class, + "module_path": "qlib.contrib.data.handler", + "kwargs": get_data_handler_config(**handler_kwargs), + }, + "segments": { + "train": train, + "valid": valid, + "test": test, + }, + }, + } + + +def get_gbdt_task(dataset_kwargs={}, handler_kwargs={"instruments": CSI300_MARKET}): + return { + "model": GBDT_MODEL, + "dataset": get_dataset_config(**dataset_kwargs, handler_kwargs=handler_kwargs), + } + + +def get_record_lgb_config(dataset_kwargs={}, handler_kwargs={"instruments": CSI300_MARKET}): + return { + "model": { + "class": "LGBModel", + "module_path": "qlib.contrib.model.gbdt", + }, + "dataset": get_dataset_config(**dataset_kwargs, handler_kwargs=handler_kwargs), + "record": RECORD_CONFIG, + } + + +def get_record_xgboost_config(dataset_kwargs={}, handler_kwargs={"instruments": CSI300_MARKET}): + return { + "model": { + "class": "XGBModel", + "module_path": "qlib.contrib.model.xgboost", + }, + "dataset": get_dataset_config(**dataset_kwargs, handler_kwargs=handler_kwargs), + "record": RECORD_CONFIG, + } + + +CSI300_DATASET_CONFIG = get_dataset_config(handler_kwargs={"instruments": CSI300_MARKET}) +CSI300_GBDT_TASK = get_gbdt_task(handler_kwargs={"instruments": CSI300_MARKET}) + +CSI100_RECORD_XGBOOST_TASK_CONFIG = get_record_xgboost_config(handler_kwargs={"instruments": CSI100_MARKET}) +CSI100_RECORD_LGB_TASK_CONFIG = get_record_lgb_config(handler_kwargs={"instruments": CSI100_MARKET}) + +# use for rolling_online_managment.py +ROLLING_HANDLER_CONFIG = { + "start_time": "2013-01-01", + "end_time": "2020-09-25", + "fit_start_time": "2013-01-01", + "fit_end_time": "2014-12-31", + "instruments": CSI100_MARKET, +} +ROLLING_DATASET_CONFIG = { + "train": ("2013-01-01", "2014-12-31"), + "valid": ("2015-01-01", "2015-12-31"), + "test": ("2016-01-01", "2020-07-10"), +} +CSI100_RECORD_XGBOOST_TASK_CONFIG_ROLLING = get_record_xgboost_config( + dataset_kwargs=ROLLING_DATASET_CONFIG, handler_kwargs=ROLLING_HANDLER_CONFIG +) +CSI100_RECORD_LGB_TASK_CONFIG_ROLLING = get_record_lgb_config( + dataset_kwargs=ROLLING_DATASET_CONFIG, handler_kwargs=ROLLING_HANDLER_CONFIG +) + +# use for online_management_simulate.py +ONLINE_HANDLER_CONFIG = { + "start_time": "2018-01-01", + "end_time": "2018-10-31", + "fit_start_time": "2018-01-01", + "fit_end_time": "2018-03-31", + "instruments": CSI100_MARKET, +} +ONLINE_DATASET_CONFIG = { + "train": ("2018-01-01", "2018-03-31"), + "valid": ("2018-04-01", "2018-05-31"), + "test": ("2018-06-01", "2018-09-10"), +} +CSI100_RECORD_XGBOOST_TASK_CONFIG_ONLINE = get_record_xgboost_config( + dataset_kwargs=ONLINE_DATASET_CONFIG, handler_kwargs=ONLINE_HANDLER_CONFIG +) +CSI100_RECORD_LGB_TASK_CONFIG_ONLINE = get_record_lgb_config( + dataset_kwargs=ONLINE_DATASET_CONFIG, handler_kwargs=ONLINE_HANDLER_CONFIG +) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa76855b58410c40a0912e4617727e0d93e32d5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/tests/data.py @@ -0,0 +1,211 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import os +import re +import sys +import qlib +import shutil +import zipfile +import requests +import datetime +from tqdm import tqdm +from pathlib import Path +from loguru import logger +from qlib.utils import exists_qlib_data + + +class GetData: + REMOTE_URL = "https://github.com/SunsetWolf/qlib_dataset/releases/download" + + def __init__(self, delete_zip_file=False): + """ + + Parameters + ---------- + delete_zip_file : bool, optional + Whether to delete the zip file, value from True or False, by default False + """ + self.delete_zip_file = delete_zip_file + + def merge_remote_url(self, file_name: str): + """ + Generate download links. + + Parameters + ---------- + file_name: str + The name of the file to be downloaded. + The file name can be accompanied by a version number, (e.g.: v2/qlib_data_simple_cn_1d_latest.zip), + if no version number is attached, it will be downloaded from v0 by default. + """ + return f"{self.REMOTE_URL}/{file_name}" if "/" in file_name else f"{self.REMOTE_URL}/v0/{file_name}" + + def download(self, url: str, target_path: [Path, str]): + """ + Download a file from the specified url. + + Parameters + ---------- + url: str + The url of the data. + target_path: str + The location where the data is saved, including the file name. + """ + file_name = str(target_path).rsplit("/", maxsplit=1)[-1] + resp = requests.get(url, stream=True, timeout=60) + resp.raise_for_status() + if resp.status_code != 200: + raise requests.exceptions.HTTPError() + + chunk_size = 1024 + logger.warning( + f"The data for the example is collected from Yahoo Finance. Please be aware that the quality of the data might not be perfect. (You can refer to the original data source: https://finance.yahoo.com/lookup.)" + ) + logger.info(f"{os.path.basename(file_name)} downloading......") + with tqdm(total=int(resp.headers.get("Content-Length", 0))) as p_bar: + with target_path.open("wb") as fp: + for chunk in resp.iter_content(chunk_size=chunk_size): + fp.write(chunk) + p_bar.update(chunk_size) + + def download_data(self, file_name: str, target_dir: [Path, str], delete_old: bool = True): + """ + Download the specified file to the target folder. + + Parameters + ---------- + target_dir: str + data save directory + file_name: str + dataset name, needs to endwith .zip, value from [rl_data.zip, csv_data_cn.zip, ...] + may contain folder names, for example: v2/qlib_data_simple_cn_1d_latest.zip + delete_old: bool + delete an existing directory, by default True + + Examples + --------- + # get rl data + python get_data.py download_data --file_name rl_data.zip --target_dir ~/.qlib/qlib_data/rl_data + When this command is run, the data will be downloaded from this link: https://qlibpublic.blob.core.windows.net/data/default/stock_data/rl_data.zip?{token} + + # get cn csv data + python get_data.py download_data --file_name csv_data_cn.zip --target_dir ~/.qlib/csv_data/cn_data + When this command is run, the data will be downloaded from this link: https://qlibpublic.blob.core.windows.net/data/default/stock_data/csv_data_cn.zip?{token} + ------- + + """ + target_dir = Path(target_dir).expanduser() + target_dir.mkdir(exist_ok=True, parents=True) + # saved file name + _target_file_name = datetime.datetime.now().strftime("%Y%m%d%H%M%S") + "_" + os.path.basename(file_name) + target_path = target_dir.joinpath(_target_file_name) + + url = self.merge_remote_url(file_name) + self.download(url=url, target_path=target_path) + + self._unzip(target_path, target_dir, delete_old) + if self.delete_zip_file: + target_path.unlink() + + def check_dataset(self, file_name: str): + url = self.merge_remote_url(file_name) + resp = requests.get(url, stream=True, timeout=60) + status = True + if resp.status_code == 404: + status = False + return status + + @staticmethod + def _unzip(file_path: [Path, str], target_dir: [Path, str], delete_old: bool = True): + file_path = Path(file_path) + target_dir = Path(target_dir) + if delete_old: + logger.warning( + f"will delete the old qlib data directory(features, instruments, calendars, features_cache, dataset_cache): {target_dir}" + ) + GetData._delete_qlib_data(target_dir) + logger.info(f"{file_path} unzipping......") + with zipfile.ZipFile(str(file_path.resolve()), "r") as zp: + for _file in tqdm(zp.namelist()): + zp.extract(_file, str(target_dir.resolve())) + + @staticmethod + def _delete_qlib_data(file_dir: Path): + rm_dirs = [] + for _name in ["features", "calendars", "instruments", "features_cache", "dataset_cache"]: + _p = file_dir.joinpath(_name) + if _p.exists(): + rm_dirs.append(str(_p.resolve())) + if rm_dirs: + flag = input( + f"Will be deleted: " + f"\n\t{rm_dirs}" + f"\nIf you do not need to delete {file_dir}, please change the <--target_dir>" + f"\nAre you sure you want to delete, yes(Y/y), no (N/n):" + ) + if str(flag) not in ["Y", "y"]: + sys.exit() + for _p in rm_dirs: + logger.warning(f"delete: {_p}") + shutil.rmtree(_p) + + def qlib_data( + self, + name="qlib_data", + target_dir="~/.qlib/qlib_data/cn_data", + version=None, + interval="1d", + region="cn", + delete_old=True, + exists_skip=False, + ): + """download cn qlib data from remote + + Parameters + ---------- + target_dir: str + data save directory + name: str + dataset name, value from [qlib_data, qlib_data_simple], by default qlib_data + version: str + data version, value from [v1, ...], by default None(use script to specify version) + interval: str + data freq, value from [1d], by default 1d + region: str + data region, value from [cn, us], by default cn + delete_old: bool + delete an existing directory, by default True + exists_skip: bool + exists skip, by default False + + Examples + --------- + # get 1d data + python get_data.py qlib_data --name qlib_data --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn + When this command is run, the data will be downloaded from this link: https://qlibpublic.blob.core.windows.net/data/default/stock_data/v2/qlib_data_cn_1d_latest.zip?{token} + + # get 1min data + python get_data.py qlib_data --name qlib_data --target_dir ~/.qlib/qlib_data/cn_data_1min --interval 1min --region cn + When this command is run, the data will be downloaded from this link: https://qlibpublic.blob.core.windows.net/data/default/stock_data/v2/qlib_data_cn_1min_latest.zip?{token} + ------- + + """ + if exists_skip and exists_qlib_data(target_dir): + logger.warning( + f"Data already exists: {target_dir}, the data download will be skipped\n" + f"\tIf downloading is required: `exists_skip=False` or `change target_dir`" + ) + return + + qlib_version = ".".join(re.findall(r"(\d+)\.+", qlib.__version__)) + + def _get_file_name_with_version(qlib_version, dataset_version): + dataset_version = "v2" if dataset_version is None else dataset_version + file_name_with_version = f"{dataset_version}/{name}_{region.lower()}_{interval.lower()}_{qlib_version}.zip" + return file_name_with_version + + file_name = _get_file_name_with_version(qlib_version, dataset_version=version) + if not self.check_dataset(file_name): + file_name = _get_file_name_with_version("latest", dataset_version=version) + self.download_data(file_name.lower(), target_dir, delete_old) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/typehint.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/typehint.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd6e13c1a4071f2757708eb62b8c5ef2566f266 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/typehint.py @@ -0,0 +1,63 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +"""Commonly used types.""" + +import sys +from typing import Union +from pathlib import Path + +__all__ = ["Literal", "TypedDict", "final"] + +if sys.version_info >= (3, 8): + from typing import Literal, TypedDict, final # type: ignore # pylint: disable=no-name-in-module +else: + from typing_extensions import Literal, TypedDict, final + + +class InstDictConf(TypedDict): + """ + InstDictConf is a Dict-based config to describe an instance + + case 1) + { + 'class': 'ClassName', + 'kwargs': dict, # It is optional. {} will be used if not given + 'model_path': path, # It is optional if module is given in the class + } + case 2) + { + 'class': , + 'kwargs': dict, # It is optional. {} will be used if not given + } + """ + + # class: str # because class is a keyword of Python. We have to comment it + kwargs: dict # It is optional. {} will be used if not given + module_path: str # It is optional if module is given in the class + + +InstConf = Union[InstDictConf, str, object, Path] +""" +InstConf is a type to describe an instance; it will be passed into init_instance_by_config for Qlib + + config : Union[str, dict, object, Path] + + InstDictConf example. + please refer to the docs of InstDictConf + + str example. + 1) specify a pickle object + - path like 'file:////obj.pkl' + 2) specify a class name + - "ClassName": getattr(module, "ClassName")() will be used. + 3) specify module path with class name + - "a.b.c.ClassName" getattr(, "ClassName")() will be used. + + object example: + instance of accept_types + + Path example: + specify a pickle object + - it will be treated like 'file:////obj.pkl' +""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a94ebd555b4c12eb76112ddda323c0c797dc7f4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__init__.py @@ -0,0 +1,961 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# TODO: this utils covers too much utilities, please seperat it into sub modules + +from __future__ import division +from __future__ import print_function + +import os +import re +import copy +import json +import redis +import bisect +import struct +import difflib +import inspect +import hashlib +import datetime +import requests +import collections +import numpy as np +import pandas as pd +from pathlib import Path +from typing import List, Union, Optional, Callable +from packaging import version +from ruamel.yaml import YAML +from .file import ( + get_or_create_path, + save_multiple_parts_file, + unpack_archive_with_buffer, + get_tmp_file_with_buffer, +) +from ..config import C +from ..log import get_module_logger, set_log_with_config + +log = get_module_logger("utils") +# MultiIndex.is_lexsorted() is a deprecated method in Pandas 1.3.0. +is_deprecated_lexsorted_pandas = version.parse(pd.__version__) > version.parse("1.3.0") + + +#################### Server #################### +def get_redis_connection(): + """get redis connection instance.""" + return redis.StrictRedis( + host=C.redis_host, + port=C.redis_port, + db=C.redis_task_db, + password=C.redis_password, + ) + + +#################### Data #################### +def read_bin(file_path: Union[str, Path], start_index, end_index): + file_path = Path(file_path.expanduser().resolve()) + with file_path.open("rb") as f: + # read start_index + ref_start_index = int(np.frombuffer(f.read(4), dtype=" end_index: + return pd.Series(dtype=np.float32) + # calculate offset + f.seek(4 * (si - ref_start_index) + 4) + # read nbytes + count = end_index - si + 1 + data = np.frombuffer(f.read(4 * count), dtype=" List[int]: + """ + This method will be used in PIT database. + It return all the possible values between `first` and `end` (first and end is included) + + Parameters + ---------- + quarterly : bool + will it return quarterly index or yearly index. + + Returns + ------- + List[int] + the possible index between [first, last] + """ + + if not quarterly: + assert all(1900 <= x <= 2099 for x in (first, last)), "invalid arguments" + return list(range(first, last + 1)) + else: + assert all(190000 <= x <= 209904 for x in (first, last)), "invalid arguments" + res = [] + for year in range(first // 100, last // 100 + 1): + for q in range(1, 5): + period = year * 100 + q + if first <= period <= last: + res.append(year * 100 + q) + return res + + +def get_period_offset(first_year, period, quarterly): + if quarterly: + offset = (period // 100 - first_year) * 4 + period % 100 - 1 + else: + offset = period - first_year + return offset + + +def read_period_data( + index_path, + data_path, + period, + cur_date_int: int, + quarterly, + last_period_index: int = None, +): + """ + At `cur_date`(e.g. 20190102), read the information at `period`(e.g. 201803). + Only the updating info before cur_date or at cur_date will be used. + + Parameters + ---------- + period: int + date period represented by interger, e.g. 201901 corresponds to the first quarter in 2019 + cur_date_int: int + date which represented by interger, e.g. 20190102 + last_period_index: int + it is a optional parameter; it is designed to avoid repeatedly access the .index data of PIT database when + sequentially observing the data (Because the latest index of a specific period of data certainly appear in after the one in last observation). + + Returns + ------- + the query value and byte index the index value + """ + DATA_DTYPE = "".join( + [ + C.pit_record_type["date"], + C.pit_record_type["period"], + C.pit_record_type["value"], + C.pit_record_type["index"], + ] + ) + + PERIOD_DTYPE = C.pit_record_type["period"] + INDEX_DTYPE = C.pit_record_type["index"] + + NAN_VALUE = C.pit_record_nan["value"] + NAN_INDEX = C.pit_record_nan["index"] + + # find the first index of linked revisions + if last_period_index is None: + with open(index_path, "rb") as fi: + (first_year,) = struct.unpack(PERIOD_DTYPE, fi.read(struct.calcsize(PERIOD_DTYPE))) + all_periods = np.fromfile(fi, dtype=INDEX_DTYPE) + offset = get_period_offset(first_year, period, quarterly) + _next = all_periods[offset] + else: + _next = last_period_index + + # load data following the `_next` link + prev_value = NAN_VALUE + prev_next = _next + + with open(data_path, "rb") as fd: + while _next != NAN_INDEX: + fd.seek(_next) + date, period, value, new_next = struct.unpack(DATA_DTYPE, fd.read(struct.calcsize(DATA_DTYPE))) + if date > cur_date_int: + break + prev_next = _next + _next = new_next + prev_value = value + return prev_value, prev_next + + +def np_ffill(arr: np.array): + """ + forward fill a 1D numpy array + + Parameters + ---------- + arr : np.array + Input numpy 1D array + """ + mask = np.isnan(arr.astype(float)) # np.isnan only works on np.float + # get fill index + idx = np.where(~mask, np.arange(mask.shape[0]), 0) + np.maximum.accumulate(idx, out=idx) + return arr[idx] + + +#################### Search #################### +def lower_bound(data, val, level=0): + """multi fields list lower bound. + + for single field list use `bisect.bisect_left` instead + """ + left = 0 + right = len(data) + while left < right: + mid = (left + right) // 2 + if val <= data[mid][level]: + right = mid + else: + left = mid + 1 + return left + + +def upper_bound(data, val, level=0): + """multi fields list upper bound. + + for single field list use `bisect.bisect_right` instead + """ + left = 0 + right = len(data) + while left < right: + mid = (left + right) // 2 + if val >= data[mid][level]: + left = mid + 1 + else: + right = mid + return left + + +#################### HTTP #################### +def requests_with_retry(url, retry=5, **kwargs): + while retry > 0: + retry -= 1 + try: + res = requests.get(url, timeout=1, **kwargs) + assert res.status_code in {200, 206} + return res + except AssertionError: + continue + except Exception as e: + log.warning("exception encountered {}".format(e)) + continue + raise TimeoutError("ERROR: requests failed!") + + +#################### Parse #################### +def parse_config(config): + # Check whether need parse, all object except str do not need to be parsed + if not isinstance(config, str): + return config + # Check whether config is file + yaml = YAML(typ="safe", pure=True) + if os.path.exists(config): + with open(config, "r") as f: + return yaml.load(f) + # Check whether the str can be parsed + try: + return yaml.load(config) + except BaseException as base_exp: + raise ValueError("cannot parse config!") from base_exp + + +#################### Other #################### +def drop_nan_by_y_index(x, y, weight=None): + # x, y, weight: DataFrame + # Find index of rows which do not contain Nan in all columns from y. + mask = ~y.isna().any(axis=1) + # Get related rows from x, y, weight. + x = x[mask] + y = y[mask] + if weight is not None: + weight = weight[mask] + return x, y, weight + + +def hash_args(*args): + # json.dumps will keep the dict keys always sorted. + string = json.dumps(args, sort_keys=True, default=str) # frozenset + return hashlib.md5(string.encode()).hexdigest() + + +def parse_field(field): + # Following patterns will be matched: + # - $close -> Feature("close") + # - $close5 -> Feature("close5") + # - $open+$close -> Feature("open")+Feature("close") + # TODO: this maybe used in the feature if we want to support the computation of different frequency data + # - $close@5min -> Feature("close", "5min") + + if not isinstance(field, str): + field = str(field) + # Chinese punctuation regex: + # \u3001 -> 、 + # \uff1a -> : + # \uff08 -> ( + # \uff09 -> ) + chinese_punctuation_regex = r"\u3001\uff1a\uff08\uff09" + for pattern, new in [ + ( + rf"\$\$([\w{chinese_punctuation_regex}]+)", + r'PFeature("\1")', + ), # $$ must be before $ + (rf"\$([\w{chinese_punctuation_regex}]+)", r'Feature("\1")'), + (r"(\w+\s*)\(", r"Operators.\1("), + ]: # Features # Operators + field = re.sub(pattern, new, field) + return field + + +def compare_dict_value(src_data: dict, dst_data: dict): + """Compare dict value + + :param src_data: + :param dst_data: + :return: + """ + + class DateEncoder(json.JSONEncoder): + # FIXME: This class can only be accurate to the day. If it is a minute, + # there may be a bug + def default(self, o): + if isinstance(o, (datetime.datetime, datetime.date)): + return o.strftime("%Y-%m-%d %H:%M:%S") + return json.JSONEncoder.default(self, o) + + src_data = json.dumps(src_data, indent=4, sort_keys=True, cls=DateEncoder) + dst_data = json.dumps(dst_data, indent=4, sort_keys=True, cls=DateEncoder) + diff = difflib.ndiff(src_data, dst_data) + changes = [line for line in diff if line.startswith("+ ") or line.startswith("- ")] + return changes + + +def remove_repeat_field(fields): + """remove repeat field + + :param fields: list; features fields + :return: list + """ + fields = copy.deepcopy(fields) + _fields = set(fields) + return sorted(_fields, key=fields.index) + + +def remove_fields_space(fields: [list, str, tuple]): + """remove fields space + + :param fields: features fields + :return: list or str + """ + if isinstance(fields, str): + return fields.replace(" ", "") + return [i.replace(" ", "") if isinstance(i, str) else str(i) for i in fields] + + +def normalize_cache_fields(fields: [list, tuple]): + """normalize cache fields + + :param fields: features fields + :return: list + """ + return sorted(remove_repeat_field(remove_fields_space(fields))) + + +def normalize_cache_instruments(instruments): + """normalize cache instruments + + :return: list or dict + """ + if isinstance(instruments, (list, tuple, pd.Index, np.ndarray)): + instruments = sorted(list(instruments)) + else: + # dict type stockpool + if "market" in instruments: + pass + else: + instruments = {k: sorted(v) for k, v in instruments.items()} + return instruments + + +def is_tradable_date(cur_date): + """judgy whether date is a tradable date + ---------- + date : pandas.Timestamp + current date + """ + from ..data import D # pylint: disable=C0415 + + return str(cur_date.date()) == str(D.calendar(start_time=cur_date, future=True)[0].date()) + + +def get_date_range(trading_date, left_shift=0, right_shift=0, future=False): + """get trading date range by shift + + Parameters + ---------- + trading_date: pd.Timestamp + left_shift: int + right_shift: int + future: bool + + """ + + from ..data import D # pylint: disable=C0415 + + start = get_date_by_shift(trading_date, left_shift, future=future) + end = get_date_by_shift(trading_date, right_shift, future=future) + + calendar = D.calendar(start, end, future=future) + return calendar + + +def get_date_by_shift( + trading_date, + shift, + future=False, + clip_shift=True, + freq="day", + align: Optional[str] = None, +): + """get trading date with shift bias will cur_date + e.g. : shift == 1, return next trading date + shift == -1, return previous trading date + ---------- + trading_date : pandas.Timestamp + current date + shift : int + clip_shift: bool + align : Optional[str] + When align is None, this function will raise ValueError if `trading_date` is not a trading date + when align is "left"/"right", it will try to align to left/right nearest trading date before shifting when `trading_date` is not a trading date + + """ + from qlib.data import D # pylint: disable=C0415 + + cal = D.calendar(future=future, freq=freq) + trading_date = pd.to_datetime(trading_date) + if align is None: + if trading_date not in list(cal): + raise ValueError("{} is not trading day!".format(str(trading_date))) + _index = bisect.bisect_left(cal, trading_date) + elif align == "left": + _index = bisect.bisect_right(cal, trading_date) - 1 + elif align == "right": + _index = bisect.bisect_left(cal, trading_date) + else: + raise ValueError(f"align with value `{align}` is not supported") + shift_index = _index + shift + if shift_index < 0 or shift_index >= len(cal): + if clip_shift: + shift_index = np.clip(shift_index, 0, len(cal) - 1) + else: + raise IndexError(f"The shift_index({shift_index}) of the trading day ({trading_date}) is out of range") + return cal[shift_index] + + +def get_next_trading_date(trading_date, future=False): + """get next trading date + ---------- + cur_date : pandas.Timestamp + current date + """ + return get_date_by_shift(trading_date, 1, future=future) + + +def get_pre_trading_date(trading_date, future=False): + """get previous trading date + ---------- + date : pandas.Timestamp + current date + """ + return get_date_by_shift(trading_date, -1, future=future) + + +def transform_end_date(end_date=None, freq="day"): + """handle the end date with various format + + If end_date is -1, None, or end_date is greater than the maximum trading day, the last trading date is returned. + Otherwise, returns the end_date + + ---------- + end_date: str + end trading date + date : pandas.Timestamp + current date + """ + from ..data import D # pylint: disable=C0415 + + last_date = D.calendar(freq=freq)[-1] + if end_date is None or (str(end_date) == "-1") or (pd.Timestamp(last_date) < pd.Timestamp(end_date)): + log.warning( + "\nInfo: the end_date in the configuration file is {}, " + "so the default last date {} is used.".format(end_date, last_date) + ) + end_date = last_date + return end_date + + +def get_date_in_file_name(file_name): + """Get the date(YYYY-MM-DD) written in file name + Parameter + file_name : str + :return + date : str + 'YYYY-MM-DD' + """ + pattern = "[0-9]{4}-[0-9]{2}-[0-9]{2}" + date = re.search(pattern, str(file_name)).group() + return date + + +def split_pred(pred, number=None, split_date=None): + """split the score file into two part + Parameter + --------- + pred : pd.DataFrame (index:) + A score file of stocks + number: the number of dates for pred_left + split_date: the last date of the pred_left + Return + ------- + pred_left : pd.DataFrame (index:) + The first part of original score file + pred_right : pd.DataFrame (index:) + The second part of original score file + """ + if number is None and split_date is None: + raise ValueError("`number` and `split date` cannot both be None") + dates = sorted(pred.index.get_level_values("datetime").unique()) + dates = list(map(pd.Timestamp, dates)) + if split_date is None: + date_left_end = dates[number - 1] + date_right_begin = dates[number] + date_left_start = None + else: + split_date = pd.Timestamp(split_date) + date_left_end = split_date + date_right_begin = split_date + pd.Timedelta(days=1) + if number is None: + date_left_start = None + else: + end_idx = bisect.bisect_right(dates, split_date) + date_left_start = dates[end_idx - number] + pred_temp = pred.sort_index() + pred_left = pred_temp.loc(axis=0)[:, date_left_start:date_left_end] + pred_right = pred_temp.loc(axis=0)[:, date_right_begin:] + return pred_left, pred_right + + +def time_to_slc_point(t: Union[None, str, pd.Timestamp]) -> Union[None, pd.Timestamp]: + """ + Time slicing in Qlib or Pandas is a frequently-used action. + However, user often input all kinds of data format to represent time. + This function will help user to convert these inputs into a uniform format which is friendly to time slicing. + + Parameters + ---------- + t : Union[None, str, pd.Timestamp] + original time + + Returns + ------- + Union[None, pd.Timestamp]: + """ + if t is None: + # None represents unbounded in Qlib or Pandas(e.g. df.loc[slice(None, "20210303")]). + return t + else: + return pd.Timestamp(t) + + +def can_use_cache(): + res = True + r = get_redis_connection() + try: + r.client() + except redis.exceptions.ConnectionError: + res = False + finally: + r.close() + return res + + +def exists_qlib_data(qlib_dir): + qlib_dir = Path(qlib_dir).expanduser() + if not qlib_dir.exists(): + return False + + calendars_dir = qlib_dir.joinpath("calendars") + instruments_dir = qlib_dir.joinpath("instruments") + features_dir = qlib_dir.joinpath("features") + # check dir + for _dir in [calendars_dir, instruments_dir, features_dir]: + if not (_dir.exists() and list(_dir.iterdir())): + return False + # check calendar bin + for _calendar in calendars_dir.iterdir(): + if ("_future" not in _calendar.name) and ( + not list(features_dir.rglob(f"*.{_calendar.name.split('.')[0]}.bin")) + ): + return False + + # check instruments + code_names = set(map(lambda x: fname_to_code(x.name.lower()), features_dir.iterdir())) + _instrument = instruments_dir.joinpath("all.txt") + # Removed two possible ticker names "NA" and "NULL" from the default na_values list for column 0 + miss_code = set( + pd.read_csv( + _instrument, + sep="\t", + header=None, + keep_default_na=False, + na_values={ + 0: [ + " ", + "#N/A", + "#N/A N/A", + "#NA", + "-1.#IND", + "-1.#QNAN", + "-NaN", + "-nan", + "1.#IND", + "1.#QNAN", + "", + "N/A", + "NaN", + "None", + "n/a", + "nan", + "null ", + ] + }, + ) + .loc[:, 0] + .apply(str.lower) + ) - set(code_names) + if miss_code and any(map(lambda x: "sht" not in x, miss_code)): + return False + + return True + + +def check_qlib_data(qlib_config): + inst_dir = Path(qlib_config["provider_uri"]).joinpath("instruments") + for _p in inst_dir.glob("*.txt"): + assert len(pd.read_csv(_p, sep="\t", nrows=0, header=None).columns) == 3, ( + f"\nThe {str(_p.resolve())} of qlib data is not equal to 3 columns:" + f"\n\tIf you are using the data provided by qlib: " + f"https://qlib.readthedocs.io/en/latest/component/data.html#qlib-format-dataset" + f"\n\tIf you are using your own data, please dump the data again: " + f"https://qlib.readthedocs.io/en/latest/component/data.html#converting-csv-format-into-qlib-format" + ) + + +def lazy_sort_index(df: pd.DataFrame, axis=0) -> pd.DataFrame: + """ + make the df index sorted + + df.sort_index() will take a lot of time even when `df.is_lexsorted() == True` + This function could avoid such case + + Parameters + ---------- + df : pd.DataFrame + + Returns + ------- + pd.DataFrame: + sorted dataframe + """ + idx = df.index if axis == 0 else df.columns + if ( + not idx.is_monotonic_increasing + or not is_deprecated_lexsorted_pandas + and isinstance(idx, pd.MultiIndex) + and not idx.is_lexsorted() + ): # this case is for the old version + return df.sort_index(axis=axis) + else: + return df + + +FLATTEN_TUPLE = "_FLATTEN_TUPLE" + + +def flatten_dict(d, parent_key="", sep=".") -> dict: + """ + Flatten a nested dict. + + >>> flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}) + >>> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'd': [1, 2, 3], 'c.b.y': 10} + + >>> flatten_dict({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}, sep=FLATTEN_TUPLE) + >>> {'a': 1, ('c','a'): 2, ('c','b','x'): 5, 'd': [1, 2, 3], ('c','b','y'): 10} + + Args: + d (dict): the dict waiting for flatting + parent_key (str, optional): the parent key, will be a prefix in new key. Defaults to "". + sep (str, optional): the separator for string connecting. FLATTEN_TUPLE for tuple connecting. + + Returns: + dict: flatten dict + """ + items = [] + for k, v in d.items(): + if sep == FLATTEN_TUPLE: + new_key = (parent_key, k) if parent_key else k + else: + new_key = parent_key + sep + k if parent_key else k + if isinstance(v, collections.abc.MutableMapping): + items.extend(flatten_dict(v, new_key, sep=sep).items()) + else: + items.append((new_key, v)) + return dict(items) + + +def get_item_from_obj(config: dict, name_path: str) -> object: + """ + Follow the name_path to get values from config + For example: + If we follow the example in in the Parameters section, + Timestamp('2008-01-02 00:00:00') will be returned + + Parameters + ---------- + config : dict + e.g. + {'dataset': {'class': 'DatasetH', + 'kwargs': {'handler': {'class': 'Alpha158', + 'kwargs': {'end_time': '2020-08-01', + 'fit_end_time': '', + 'fit_start_time': '', + 'instruments': 'csi100', + 'start_time': '2008-01-01'}, + 'module_path': 'qlib.contrib.data.handler'}, + 'segments': {'test': (Timestamp('2017-01-03 00:00:00'), + Timestamp('2019-04-08 00:00:00')), + 'train': (Timestamp('2008-01-02 00:00:00'), + Timestamp('2014-12-31 00:00:00')), + 'valid': (Timestamp('2015-01-05 00:00:00'), + Timestamp('2016-12-30 00:00:00'))}} + }} + name_path : str + e.g. + "dataset.kwargs.segments.train.1" + + Returns + ------- + object + the retrieved object + """ + cur_cfg = config + for k in name_path.split("."): + if isinstance(cur_cfg, dict): + cur_cfg = cur_cfg[k] # may raise KeyError + elif k.isdigit(): + cur_cfg = cur_cfg[int(k)] # may raise IndexError + else: + raise ValueError(f"Error when getting {k} from cur_cfg") + return cur_cfg + + +def fill_placeholder(config: dict, config_extend: dict): + """ + Detect placeholder in config and fill them with config_extend. + The item of dict must be single item(int, str, etc), dict and list. Tuples are not supported. + There are two type of variables: + - user-defined variables : + e.g. when config_extend is `{"": model, "": dataset}`, "" and "" in `config` will be replaced with `model` `dataset` + - variables extracted from `config` : + e.g. the variables like "" will be replaced with the values from `config` + + Parameters + ---------- + config : dict + the parameter dict will be filled + config_extend : dict + the value of all placeholders + + Returns + ------- + dict + the parameter dict + """ + # check the format of config_extend + for placeholder in config_extend.keys(): + assert re.match(r"<[^<>]+>", placeholder) + + # bfs + top = 0 + tail = 1 + item_queue = [config] + + def try_replace_placeholder(value): + if value in config_extend.keys(): + value = config_extend[value] + else: + m = re.match(r"<(?P[^<>]+)>", value) + if m is not None: + try: + value = get_item_from_obj(config, m.groupdict()["name_path"]) + except (KeyError, ValueError, IndexError): + get_module_logger("fill_placeholder").info( + f"{value} lookes like a placeholder, but it can't match to any given values" + ) + return value + + item_keys = None + while top < tail: + now_item = item_queue[top] + top += 1 + if isinstance(now_item, list): + item_keys = range(len(now_item)) + elif isinstance(now_item, dict): + item_keys = now_item.keys() + for key in item_keys: # noqa + if isinstance(now_item[key], (list, dict)): + item_queue.append(now_item[key]) + tail += 1 + elif isinstance(now_item[key], str): + # If it is a string, try to replace it with placeholder + now_item[key] = try_replace_placeholder(now_item[key]) + return config + + +def auto_filter_kwargs(func: Callable, warning=True) -> Callable: + """ + this will work like a decoration function + + The decrated function will ignore and give warning when the parameter is not acceptable + + For example, if you have a function `f` which may optionally consume the keywards `bar`. + then you can call it by `auto_filter_kwargs(f)(bar=3)`, which will automatically filter out + `bar` when f does not need bar + + Parameters + ---------- + func : Callable + The original function + + Returns + ------- + Callable: + the new callable function + """ + + def _func(*args, **kwargs): + spec = inspect.getfullargspec(func) + new_kwargs = {} + for k, v in kwargs.items(): + # if `func` don't accept variable keyword arguments like `**kwargs` and have not according named arguments + if spec.varkw is None and k not in spec.args: + if warning: + log.warning(f"The parameter `{k}` with value `{v}` is ignored.") + else: + new_kwargs[k] = v + return func(*args, **new_kwargs) + + return _func + + +#################### Wrapper ##################### +class Wrapper: + """Wrapper class for anything that needs to set up during qlib.init""" + + def __init__(self): + self._provider = None + + def register(self, provider): + self._provider = provider + + def __repr__(self): + return "{name}(provider={provider})".format(name=self.__class__.__name__, provider=self._provider) + + def __getattr__(self, key): + if self.__dict__.get("_provider", None) is None: + raise AttributeError("Please run qlib.init() first using qlib") + return getattr(self._provider, key) + + +def register_wrapper(wrapper, cls_or_obj, module_path=None): + """register_wrapper + + :param wrapper: A wrapper. + :param cls_or_obj: A class or class name or object instance. + """ + if isinstance(cls_or_obj, str): + module = get_module_by_module_path(module_path) + cls_or_obj = getattr(module, cls_or_obj) + obj = cls_or_obj() if isinstance(cls_or_obj, type) else cls_or_obj + wrapper.register(obj) + + +def load_dataset(path_or_obj, index_col=[0, 1]): + """load dataset from multiple file formats""" + if isinstance(path_or_obj, pd.DataFrame): + return path_or_obj + if not os.path.exists(path_or_obj): + raise ValueError(f"file {path_or_obj} doesn't exist") + _, extension = os.path.splitext(path_or_obj) + if extension == ".h5": + return pd.read_hdf(path_or_obj) + elif extension == ".pkl": + return pd.read_pickle(path_or_obj) + elif extension == ".csv": + return pd.read_csv(path_or_obj, parse_dates=True, index_col=index_col) + raise ValueError(f"unsupported file type `{extension}`") + + +def code_to_fname(code: str): + """stock code to file name + + Parameters + ---------- + code: str + """ + # NOTE: In windows, the following name is I/O device, and the file with the corresponding name cannot be created + # reference: https://superuser.com/questions/86999/why-cant-i-name-a-folder-or-file-con-in-windows + replace_names = ["CON", "PRN", "AUX", "NUL"] + replace_names += [f"COM{i}" for i in range(10)] + replace_names += [f"LPT{i}" for i in range(10)] + + prefix = "_qlib_" + if str(code).upper() in replace_names: + code = prefix + str(code) + + return code + + +def fname_to_code(fname: str): + """file name to stock code + + Parameters + ---------- + fname: str + """ + + prefix = "_qlib_" + if fname.startswith(prefix): + fname = fname.lstrip(prefix) + return fname + + +from .mod import ( + get_module_by_module_path, + split_module_path, + get_callable_kwargs, + get_cls_kwargs, + init_instance_by_config, + class_casting, +) + +__all__ = [ + "get_or_create_path", + "save_multiple_parts_file", + "unpack_archive_with_buffer", + "get_tmp_file_with_buffer", + "set_log_with_config", + "init_instance_by_config", + "get_module_by_module_path", + "split_module_path", + "get_callable_kwargs", + "get_cls_kwargs", + "init_instance_by_config", + "class_casting", +] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/__init__.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0f0d27bfa842c8f3aba751dcaee952daf20c858 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/__init__.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/file.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/file.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36a65be0c8a190a193d090df4c554c6ca30f5773 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/file.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/mod.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/mod.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db979ccb1329635fe882e8a47fd67be4a4ed1056 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/mod.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/pickle_utils.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/pickle_utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c794b2e50b4ec82d944fccddfd4f36f0f1b8dfb Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/pickle_utils.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/time.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/time.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7314020717c7e2c321a200b39a9b496dd144c549 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/__pycache__/time.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/data.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a9a1027f363cd7c1da9bb51f0b7ce39dbb3e34 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/data.py @@ -0,0 +1,118 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +This module covers some utility functions that operate on data or basic object +""" + +from copy import deepcopy +from typing import List, Union + +import numpy as np +import pandas as pd + +from qlib.data.data import DatasetProvider + + +def robust_zscore(x: pd.Series, zscore=False): + """Robust ZScore Normalization + + Use robust statistics for Z-Score normalization: + mean(x) = median(x) + std(x) = MAD(x) * 1.4826 + + Reference: + https://en.wikipedia.org/wiki/Median_absolute_deviation. + """ + x = x - x.median() + mad = x.abs().median() + x = np.clip(x / mad / 1.4826, -3, 3) + if zscore: + x -= x.mean() + x /= x.std() + return x + + +def zscore(x: Union[pd.Series, pd.DataFrame]): + return (x - x.mean()).div(x.std()) + + +def deepcopy_basic_type(obj: object) -> object: + """ + deepcopy an object without copy the complicated objects. + This is useful when you want to generate Qlib tasks and share the handler + + NOTE: + - This function can't handle recursive objects!!!!! + + Parameters + ---------- + obj : object + the object to be copied + + Returns + ------- + object: + The copied object + """ + if isinstance(obj, tuple): + return tuple(deepcopy_basic_type(i) for i in obj) + elif isinstance(obj, list): + return list(deepcopy_basic_type(i) for i in obj) + elif isinstance(obj, dict): + return {k: deepcopy_basic_type(v) for k, v in obj.items()} + else: + return obj + + +S_DROP = "__DROP__" # this is a symbol which indicates drop the value + + +def update_config(base_config: dict, ext_config: Union[dict, List[dict]]): + """ + supporting adding base config based on the ext_config + + >>> bc = {"a": "xixi"} + >>> ec = {"b": "haha"} + >>> new_bc = update_config(bc, ec) + >>> print(new_bc) + {'a': 'xixi', 'b': 'haha'} + >>> print(bc) # base config should not be changed + {'a': 'xixi'} + >>> print(update_config(bc, {"b": S_DROP})) + {'a': 'xixi'} + >>> print(update_config(new_bc, {"b": S_DROP})) + {'a': 'xixi'} + """ + + base_config = deepcopy(base_config) # in case of modifying base config + + for ec in ext_config if isinstance(ext_config, (list, tuple)) else [ext_config]: + for key in ec: + if key not in base_config: + # if it is not in the default key, then replace it. + # ADD if not drop + if ec[key] != S_DROP: + base_config[key] = ec[key] + + else: + if isinstance(base_config[key], dict) and isinstance(ec[key], dict): + # Recursive + # Both of them are dict, then update it nested + base_config[key] = update_config(base_config[key], ec[key]) + elif ec[key] == S_DROP: + # DROP + del base_config[key] + else: + # REPLACE + # one of then are not dict. Then replace + base_config[key] = ec[key] + return base_config + + +def guess_horizon(label: List): + """ + Try to guess the horizon by parsing label + """ + expr = DatasetProvider.parse_fields(label)[0] + lft_etd, rght_etd = expr.get_extended_window_size() + return rght_etd diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/exceptions.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa5c6dfe738963a4b64e78da5889457c0ae972b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/exceptions.py @@ -0,0 +1,19 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + + +# Base exception class +class QlibException(Exception): + pass + + +class RecorderInitializationError(QlibException): + """Error type for re-initialization when starting an experiment""" + + +class LoadObjectError(QlibException): + """Error type for Recorder when can not load object""" + + +class ExpAlreadyExistError(Exception): + """Experiment already exists""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/file.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/file.py new file mode 100644 index 0000000000000000000000000000000000000000..1e17a574a9de9b0f60cfaab832412219fc2eafd5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/file.py @@ -0,0 +1,190 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import os +import shutil +import tempfile +import contextlib +from typing import Optional, Text, IO, Union +from pathlib import Path + +from qlib.log import get_module_logger + +log = get_module_logger("utils.file") + + +def get_or_create_path(path: Optional[Text] = None, return_dir: bool = False): + """Create or get a file or directory given the path and return_dir. + + Parameters + ---------- + path: a string indicates the path or None indicates creating a temporary path. + return_dir: if True, create and return a directory; otherwise c&r a file. + + """ + if path: + if return_dir and not os.path.exists(path): + os.makedirs(path) + elif not return_dir: # return a file, thus we need to create its parent directory + xpath = os.path.abspath(os.path.join(path, "..")) + if not os.path.exists(xpath): + os.makedirs(xpath) + else: + temp_dir = os.path.expanduser("~/tmp") + if not os.path.exists(temp_dir): + os.makedirs(temp_dir) + if return_dir: + _, path = tempfile.mkdtemp(dir=temp_dir) + else: + _, path = tempfile.mkstemp(dir=temp_dir) + return path + + +@contextlib.contextmanager +def save_multiple_parts_file(filename, format="gztar"): + """Save multiple parts file + + Implementation process: + 1. get the absolute path to 'filename' + 2. create a 'filename' directory + 3. user does something with file_path('filename/') + 4. remove 'filename' directory + 5. make_archive 'filename' directory, and rename 'archive file' to filename + + :param filename: result model path + :param format: archive format: one of "zip", "tar", "gztar", "bztar", or "xztar" + :return: real model path + + Usage:: + + >>> # The following code will create an archive file('~/tmp/test_file') containing 'test_doc_i'(i is 0-10) files. + >>> with save_multiple_parts_file('~/tmp/test_file') as filename_dir: + ... for i in range(10): + ... temp_path = os.path.join(filename_dir, 'test_doc_{}'.format(str(i))) + ... with open(temp_path) as fp: + ... fp.write(str(i)) + ... + + """ + + if filename.startswith("~"): + filename = os.path.expanduser(filename) + + file_path = os.path.abspath(filename) + + # Create model dir + if os.path.exists(file_path): + raise FileExistsError("ERROR: file exists: {}, cannot be create the directory.".format(file_path)) + + os.makedirs(file_path) + + # return model dir + yield file_path + + # filename dir to filename.tar.gz file + tar_file = shutil.make_archive(file_path, format=format, root_dir=file_path) + + # Remove filename dir + if os.path.exists(file_path): + shutil.rmtree(file_path) + + # filename.tar.gz rename to filename + os.rename(tar_file, file_path) + + +@contextlib.contextmanager +def unpack_archive_with_buffer(buffer, format="gztar"): + """Unpack archive with archive buffer + After the call is finished, the archive file and directory will be deleted. + + Implementation process: + 1. create 'tempfile' in '~/tmp/' and directory + 2. 'buffer' write to 'tempfile' + 3. unpack archive file('tempfile') + 4. user does something with file_path('tempfile/') + 5. remove 'tempfile' and 'tempfile directory' + + :param buffer: bytes + :param format: archive format: one of "zip", "tar", "gztar", "bztar", or "xztar" + :return: unpack archive directory path + + Usage:: + + >>> # The following code is to print all the file names in 'test_unpack.tar.gz' + >>> with open('test_unpack.tar.gz') as fp: + ... buffer = fp.read() + ... + >>> with unpack_archive_with_buffer(buffer) as temp_dir: + ... for f_n in os.listdir(temp_dir): + ... print(f_n) + ... + + """ + temp_dir = os.path.expanduser("~/tmp") + if not os.path.exists(temp_dir): + os.makedirs(temp_dir) + with tempfile.NamedTemporaryFile("wb", delete=False, dir=temp_dir) as fp: + fp.write(buffer) + file_path = fp.name + + try: + tar_file = file_path + ".tar.gz" + os.rename(file_path, tar_file) + # Create dir + os.makedirs(file_path) + shutil.unpack_archive(tar_file, format=format, extract_dir=file_path) + + # Return temp dir + yield file_path + + except Exception as e: + log.error(str(e)) + finally: + # Remove temp tar file + if os.path.exists(tar_file): + os.unlink(tar_file) + + # Remove temp model dir + if os.path.exists(file_path): + shutil.rmtree(file_path) + + +@contextlib.contextmanager +def get_tmp_file_with_buffer(buffer): + temp_dir = os.path.expanduser("~/tmp") + if not os.path.exists(temp_dir): + os.makedirs(temp_dir) + with tempfile.NamedTemporaryFile("wb", delete=True, dir=temp_dir) as fp: + fp.write(buffer) + file_path = fp.name + yield file_path + + +@contextlib.contextmanager +def get_io_object(file: Union[IO, str, Path], *args, **kwargs) -> IO: + """ + providing a easy interface to get an IO object + + Parameters + ---------- + file : Union[IO, str, Path] + a object representing the file + + Returns + ------- + IO: + a IO-like object + + Raises + ------ + NotImplementedError: + """ + if isinstance(file, IO): + yield file + else: + if isinstance(file, str): + file = Path(file) + if not isinstance(file, Path): + raise NotImplementedError(f"This type[{type(file)}] of input is not supported") + with file.open(*args, **kwargs) as f: + yield f diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/index_data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/index_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c707240d098986d7d61d5e0b7051453fb77e2405 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/index_data.py @@ -0,0 +1,654 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Motivation of index_data +- Pandas has a lot of user-friendly interfaces. However, integrating too much features in a single tool bring too much overhead and makes it much slower than numpy. + Some users just want a simple numpy dataframe with indices and don't want such a complicated tools. + Such users are the target of `index_data` + +`index_data` try to behave like pandas (some API will be different because we try to be simpler and more intuitive) but don't compromise the performance. It provides the basic numpy data and simple indexing feature. If users call APIs which may compromise the performance, index_data will raise Errors. +""" + +from __future__ import annotations + +from typing import Dict, Tuple, Union, Callable, List +import bisect + +import numpy as np +import pandas as pd + + +def concat(data_list: Union[SingleData], axis=0) -> MultiData: + """concat all SingleData by index. + TODO: now just for SingleData. + + Parameters + ---------- + data_list : List[SingleData] + the list of all SingleData to concat. + + Returns + ------- + MultiData + the MultiData with ndim == 2 + """ + if axis == 0: + raise NotImplementedError(f"please implement this func when axis == 0") + elif axis == 1: + # get all index and row + all_index = set() + for index_data in data_list: + all_index = all_index | set(index_data.index) + all_index = list(all_index) + all_index.sort() + all_index_map = dict(zip(all_index, range(len(all_index)))) + + # concat all + tmp_data = np.full((len(all_index), len(data_list)), np.nan) + for data_id, index_data in enumerate(data_list): + assert isinstance(index_data, SingleData) + now_data_map = [all_index_map[index] for index in index_data.index] + tmp_data[now_data_map, data_id] = index_data.data + return MultiData(tmp_data, all_index) + else: + raise ValueError(f"axis must be 0 or 1") + + +def sum_by_index(data_list: Union[SingleData], new_index: list, fill_value=0) -> SingleData: + """concat all SingleData by new index. + + Parameters + ---------- + data_list : List[SingleData] + the list of all SingleData to sum. + new_index : list + the new_index of new SingleData. + fill_value : float + fill the missing values or replace np.nan. + + Returns + ------- + SingleData + the SingleData with new_index and values after sum. + """ + data_list = [data.to_dict() for data in data_list] + data_sum = {} + for id in new_index: + item_sum = 0 + for data in data_list: + if id in data and not np.isnan(data[id]): + item_sum += data[id] + else: + item_sum += fill_value + data_sum[id] = item_sum + return SingleData(data_sum) + + +class Index: + """ + This is for indexing(rows or columns) + + Read-only operations has higher priorities than others. + So this class is designed in a **read-only** way to shared data for queries. + Modifications will results in new Index. + + NOTE: the indexing has following flaws + - duplicated index value is not well supported (only the first appearance will be considered) + - The order of the index is not considered!!!! So the slicing will not behave like pandas when indexings are ordered + """ + + def __init__(self, idx_list: Union[List, pd.Index, "Index", int]): + self.idx_list: np.ndarray = None # using array type for index list will make things easier + if isinstance(idx_list, Index): + # Fast read-only copy + self.idx_list = idx_list.idx_list + self.index_map = idx_list.index_map + self._is_sorted = idx_list._is_sorted + elif isinstance(idx_list, int): + self.index_map = self.idx_list = np.arange(idx_list) + self._is_sorted = True + else: + # Check if all elements in idx_list are of the same type + if not all(isinstance(x, type(idx_list[0])) for x in idx_list): + raise TypeError("All elements in idx_list must be of the same type") + # Check if all elements in idx_list are of the same datetime64 precision + if isinstance(idx_list[0], np.datetime64) and not all(x.dtype == idx_list[0].dtype for x in idx_list): + raise TypeError("All elements in idx_list must be of the same datetime64 precision") + self.idx_list = np.array(idx_list) + # NOTE: only the first appearance is indexed + self.index_map = dict(zip(self.idx_list, range(len(self)))) + self._is_sorted = False + + def __getitem__(self, i: int): + return self.idx_list[i] + + def _convert_type(self, item): + """ + + After user creates indices with Type A, user may query data with other types with the same info. + This method try to make type conversion and make query sane rather than raising KeyError strictly + + Parameters + ---------- + item : + The item to query index + """ + + if self.idx_list.dtype.type is np.datetime64: + if isinstance(item, pd.Timestamp): + # This happens often when creating index based on pandas.DatetimeIndex and query with pd.Timestamp + return item.to_numpy().astype(self.idx_list.dtype) + elif isinstance(item, np.datetime64): + # This happens often when creating index based on np.datetime64 and query with another precision + return item.astype(self.idx_list.dtype) + # NOTE: It is hard to consider every case at first. + # We just try to cover part of cases to make it more user-friendly + return item + + def index(self, item) -> int: + """ + Given the index value, get the integer index + + Parameters + ---------- + item : + The item to query + + Returns + ------- + int: + The index of the item + + Raises + ------ + KeyError: + If the query item does not exist + """ + try: + return self.index_map[self._convert_type(item)] + except IndexError as index_e: + raise KeyError(f"{item} can't be found in {self}") from index_e + + def __or__(self, other: "Index"): + return Index(idx_list=list(set(self.idx_list) | set(other.idx_list))) + + def __eq__(self, other: "Index"): + # NOTE: np.nan is not supported in the index + if self.idx_list.shape != other.idx_list.shape: + return False + return (self.idx_list == other.idx_list).all() + + def __len__(self): + return len(self.idx_list) + + def is_sorted(self): + return self._is_sorted + + def sort(self) -> Tuple["Index", np.ndarray]: + """ + sort the index + + Returns + ------- + Tuple["Index", np.ndarray]: + the sorted Index and the changed index + """ + sorted_idx = np.argsort(self.idx_list) + idx = Index(self.idx_list[sorted_idx]) + idx._is_sorted = True + return idx, sorted_idx + + def tolist(self): + """return the index with the format of list.""" + return self.idx_list.tolist() + + +class LocIndexer: + """ + `Indexer` will behave like the `LocIndexer` in Pandas + + Read-only operations has higher priorities than others. + So this class is designed in a read-only way to shared data for queries. + Modifications will results in new Index. + """ + + def __init__(self, index_data: "IndexData", indices: List[Index], int_loc: bool = False): + self._indices: List[Index] = indices + self._bind_id = index_data # bind index data + self._int_loc = int_loc + assert self._bind_id.data.ndim == len(self._indices) + + @staticmethod + def proc_idx_l(indices: List[Union[List, pd.Index, Index]], data_shape: Tuple = None) -> List[Index]: + """process the indices from user and output a list of `Index`""" + res = [] + for i, idx in enumerate(indices): + res.append(Index(data_shape[i] if len(idx) == 0 else idx)) + return res + + def _slc_convert(self, index: Index, indexing: slice) -> slice: + """ + convert value-based indexing to integer-based indexing. + + Parameters + ---------- + index : Index + index data. + indexing : slice + value based indexing data with slice type for indexing. + + Returns + ------- + slice: + the integer based slicing + """ + if index.is_sorted(): + int_start = None if indexing.start is None else bisect.bisect_left(index, indexing.start) + int_stop = None if indexing.stop is None else bisect.bisect_right(index, indexing.stop) + else: + int_start = None if indexing.start is None else index.index(indexing.start) + int_stop = None if indexing.stop is None else index.index(indexing.stop) + 1 + return slice(int_start, int_stop) + + def __getitem__(self, indexing): + """ + + Parameters + ---------- + indexing : + query for data + + Raises + ------ + KeyError: + If the non-slice index is queried but does not exist, `KeyError` is raised. + """ + # 1) convert slices to int loc + if not isinstance(indexing, tuple): + # NOTE: tuple is not supported for indexing + indexing = (indexing,) + + # TODO: create a subclass for single value query + assert len(indexing) <= len(self._indices) + + int_indexing = [] + for dim, index in enumerate(self._indices): + if dim < len(indexing): + _indexing = indexing[dim] + if not self._int_loc: # type converting is only necessary when it is not `iloc` + if isinstance(_indexing, slice): + _indexing = self._slc_convert(index, _indexing) + elif isinstance(_indexing, (IndexData, np.ndarray)): + if isinstance(_indexing, IndexData): + _indexing = _indexing.data + assert _indexing.ndim == 1 + if _indexing.dtype != bool: + _indexing = np.array(list(index.index(i) for i in _indexing)) + else: + _indexing = index.index(_indexing) + else: + # Default to select all when user input is not given + _indexing = slice(None) + int_indexing.append(_indexing) + + # 2) select data and index + new_data = self._bind_id.data[tuple(int_indexing)] + # return directly if it is scalar + if new_data.ndim == 0: + return new_data + # otherwise we go on to the index part + new_indices = [idx[indexing] for idx, indexing in zip(self._indices, int_indexing)] + + # 3) squash dimensions + new_indices = [ + idx for idx in new_indices if isinstance(idx, np.ndarray) and idx.ndim > 0 + ] # squash the zero dim indexing + + if new_data.ndim == 1: + cls = SingleData + elif new_data.ndim == 2: + cls = MultiData + else: + raise ValueError("Not supported") + return cls(new_data, *new_indices) + + +class BinaryOps: + def __init__(self, method_name): + self.method_name = method_name + + def __get__(self, obj, *args): + # bind object + self.obj = obj + return self + + def __call__(self, other): + self_data_method = getattr(self.obj.data, self.method_name) + + if isinstance(other, (int, float, np.number)): + return self.obj.__class__(self_data_method(other), *self.obj.indices) + elif isinstance(other, self.obj.__class__): + other_aligned = self.obj._align_indices(other) + return self.obj.__class__(self_data_method(other_aligned.data), *self.obj.indices) + else: + return NotImplemented + + +def index_data_ops_creator(*args, **kwargs): + """ + meta class for auto generating operations for index data. + """ + for method_name in ["__add__", "__sub__", "__rsub__", "__mul__", "__truediv__", "__eq__", "__gt__", "__lt__"]: + args[2][method_name] = BinaryOps(method_name=method_name) + return type(*args) + + +class IndexData(metaclass=index_data_ops_creator): + """ + Base data structure of SingleData and MultiData. + + NOTE: + - For performance issue, only **np.floating** is supported in the underlayer data !!! + - Boolean based on np.floating is also supported. Here are some examples + + .. code-block:: python + + np.array([ np.nan]).any() -> True + np.array([ np.nan]).all() -> True + np.array([1. , 0.]).any() -> True + np.array([1. , 0.]).all() -> False + """ + + loc_idx_cls = LocIndexer + + def __init__(self, data: np.ndarray, *indices: Union[List, pd.Index, Index]): + self.data = data + self.indices = indices + + # get the expected data shape + # - The index has higher priority + self.data = np.array(data) + + expected_dim = max(self.data.ndim, len(indices)) + + data_shape = [] + for i in range(expected_dim): + idx_l = indices[i] if len(indices) > i else [] + if len(idx_l) == 0: + data_shape.append(self.data.shape[i]) + else: + data_shape.append(len(idx_l)) + data_shape = tuple(data_shape) + + # broadcast the data to expected shape + if self.data.shape != data_shape: + self.data = np.broadcast_to(self.data, data_shape) + + self.data = self.data.astype(np.float64) + # Please notice following cases when converting the type + # - np.array([None, 1]).astype(np.float64) -> array([nan, 1.]) + + # create index from user's index data. + self.indices: List[Index] = self.loc_idx_cls.proc_idx_l(indices, data_shape) + + for dim in range(expected_dim): + assert self.data.shape[dim] == len(self.indices[dim]) + + self.ndim = expected_dim + + # indexing related methods + @property + def loc(self): + return self.loc_idx_cls(index_data=self, indices=self.indices) + + @property + def iloc(self): + return self.loc_idx_cls(index_data=self, indices=self.indices, int_loc=True) + + @property + def index(self): + return self.indices[0] + + @property + def columns(self): + return self.indices[1] + + def __getitem__(self, args): + # NOTE: this tries to behave like a numpy array to be compatible with numpy aggregating function like nansum and nanmean + return self.iloc[args] + + def _align_indices(self, other: "IndexData") -> "IndexData": + """ + Align all indices of `other` to `self` before performing the arithmetic operations. + This function will return a new IndexData rather than changing data in `other` inplace + + Parameters + ---------- + other : "IndexData" + the index in `other` is to be changed + + Returns + ------- + IndexData: + the data in `other` with index aligned to `self` + """ + raise NotImplementedError(f"please implement _align_indices func") + + def sort_index(self, axis=0, inplace=True): + assert inplace, "Only support sorting inplace now" + self.indices[axis], sorted_idx = self.indices[axis].sort() + self.data = np.take(self.data, sorted_idx, axis=axis) + + # The code below could be simpler like methods in __getattribute__ + def __invert__(self): + return self.__class__(~self.data.astype(bool), *self.indices) + + def abs(self): + """get the abs of data except np.nan.""" + tmp_data = np.absolute(self.data) + return self.__class__(tmp_data, *self.indices) + + def replace(self, to_replace: Dict[np.number, np.number]): + assert isinstance(to_replace, dict) + tmp_data = self.data.copy() + for num in to_replace: + if num in tmp_data: + tmp_data[self.data == num] = to_replace[num] + return self.__class__(tmp_data, *self.indices) + + def apply(self, func: Callable): + """apply a function to data.""" + tmp_data = func(self.data) + return self.__class__(tmp_data, *self.indices) + + def __len__(self): + """the length of the data. + + Returns + ------- + int + the length of the data. + """ + return len(self.data) + + def sum(self, axis=None, dtype=None, out=None): + assert out is None and dtype is None, "`out` is just for compatible with numpy's aggregating function" + # FIXME: weird logic and not general + if axis is None: + return np.nansum(self.data) + elif axis == 0: + tmp_data = np.nansum(self.data, axis=0) + return SingleData(tmp_data, self.columns) + elif axis == 1: + tmp_data = np.nansum(self.data, axis=1) + return SingleData(tmp_data, self.index) + else: + raise ValueError(f"axis must be None, 0 or 1") + + def mean(self, axis=None, dtype=None, out=None): + assert out is None and dtype is None, "`out` is just for compatible with numpy's aggregating function" + # FIXME: weird logic and not general + if axis is None: + return np.nanmean(self.data) + elif axis == 0: + tmp_data = np.nanmean(self.data, axis=0) + return SingleData(tmp_data, self.columns) + elif axis == 1: + tmp_data = np.nanmean(self.data, axis=1) + return SingleData(tmp_data, self.index) + else: + raise ValueError(f"axis must be None, 0 or 1") + + def isna(self): + return self.__class__(np.isnan(self.data), *self.indices) + + def fillna(self, value=0.0, inplace: bool = False): + if inplace: + self.data = np.nan_to_num(self.data, nan=value) + else: + return self.__class__(np.nan_to_num(self.data, nan=value), *self.indices) + + def count(self): + return len(self.data[~np.isnan(self.data)]) + + def all(self): + if None in self.data: + return self.data[self.data is not None].all() + else: + return self.data.all() + + @property + def empty(self): + return len(self.data) == 0 + + @property + def values(self): + return self.data + + +class SingleData(IndexData): + def __init__( + self, data: Union[int, float, np.number, list, dict, pd.Series] = [], index: Union[List, pd.Index, Index] = [] + ): + """A data structure of index and numpy data. + It's used to replace pd.Series due to high-speed. + + Parameters + ---------- + data : Union[int, float, np.number, list, dict, pd.Series] + the input data + index : Union[list, pd.Index] + the index of data. + empty list indicates that auto filling the index to the length of data + """ + # for special data type + if isinstance(data, dict): + assert len(index) == 0 + if len(data) > 0: + index, data = zip(*data.items()) + else: + index, data = [], [] + elif isinstance(data, pd.Series): + assert len(index) == 0 + index, data = data.index, data.values + elif isinstance(data, (int, float, np.number)): + data = [data] + super().__init__(data, index) + assert self.ndim == 1 + + def _align_indices(self, other): + if self.index == other.index: + return other + elif set(self.index) == set(other.index): + return other.reindex(self.index) + else: + raise ValueError( + f"The indexes of self and other do not meet the requirements of the four arithmetic operations" + ) + + def reindex(self, index: Index, fill_value=np.nan) -> SingleData: + """reindex data and fill the missing value with np.nan. + + Parameters + ---------- + new_index : list + new index + fill_value: + what value to fill if index is missing + + Returns + ------- + SingleData + reindex data + """ + # TODO: This method can be more general + if self.index == index: + return self + tmp_data = np.full(len(index), fill_value, dtype=np.float64) + for index_id, index_item in enumerate(index): + try: + tmp_data[index_id] = self.loc[index_item] + except KeyError: + pass + return SingleData(tmp_data, index) + + def add(self, other: SingleData, fill_value=0): + # TODO: add and __add__ are a little confusing. + # This could be a more general + common_index = self.index | other.index + common_index, _ = common_index.sort() + tmp_data1 = self.reindex(common_index, fill_value) + tmp_data2 = other.reindex(common_index, fill_value) + return tmp_data1.fillna(fill_value) + tmp_data2.fillna(fill_value) + + def to_dict(self): + """convert SingleData to dict. + + Returns + ------- + dict + data with the dict format. + """ + return dict(zip(self.index, self.data.tolist())) + + def to_series(self): + return pd.Series(self.data, index=self.index) + + def __repr__(self) -> str: + return str(pd.Series(self.data, index=self.index.tolist())) + + +class MultiData(IndexData): + def __init__( + self, + data: Union[int, float, np.number, list] = [], + index: Union[List, pd.Index, Index] = [], + columns: Union[List, pd.Index, Index] = [], + ): + """A data structure of index and numpy data. + It's used to replace pd.DataFrame due to high-speed. + + Parameters + ---------- + data : Union[list, np.ndarray] + the dim of data must be 2. + index : Union[List, pd.Index, Index] + the index of data. + columns: Union[List, pd.Index, Index] + the columns of data. + """ + if isinstance(data, pd.DataFrame): + index, columns, data = data.index, data.columns, data.values + super().__init__(data, index, columns) + assert self.ndim == 2 + + def _align_indices(self, other): + if self.indices == other.indices: + return other + else: + raise ValueError( + f"The indexes of self and other do not meet the requirements of the four arithmetic operations" + ) + + def __repr__(self) -> str: + return str(pd.DataFrame(self.data, index=self.index.tolist(), columns=self.columns.tolist())) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/mod.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/mod.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb2ed3f4534c6a4085442539705110092cae16a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/mod.py @@ -0,0 +1,240 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +All module related class, e.g. : +- importing a module, class +- walkiing a module +- operations on class or module... +""" + +import contextlib +import importlib +import os +from pathlib import Path +import pkgutil +import re +import sys +from types import ModuleType +from typing import Any, Dict, List, Tuple, Union +from urllib.parse import urlparse + +from qlib.typehint import InstConf +from qlib.utils.pickle_utils import restricted_pickle_load + + +def get_module_by_module_path(module_path: Union[str, ModuleType]): + """Load module path + + :param module_path: + :return: + :raises: ModuleNotFoundError + """ + if module_path is None: + raise ModuleNotFoundError("None is passed in as parameters as module_path") + + if isinstance(module_path, ModuleType): + module = module_path + else: + if module_path.endswith(".py"): + module_name = re.sub("^[^a-zA-Z_]+", "", re.sub("[^0-9a-zA-Z_]", "", module_path[:-3].replace("/", "_"))) + module_spec = importlib.util.spec_from_file_location(module_name, module_path) + module = importlib.util.module_from_spec(module_spec) + sys.modules[module_name] = module + module_spec.loader.exec_module(module) + else: + module = importlib.import_module(module_path) + return module + + +def split_module_path(module_path: str) -> Tuple[str, str]: + """ + + Parameters + ---------- + module_path : str + e.g. "a.b.c.ClassName" + + Returns + ------- + Tuple[str, str] + e.g. ("a.b.c", "ClassName") + """ + *m_path, cls = module_path.split(".") + m_path = ".".join(m_path) + return m_path, cls + + +def get_callable_kwargs(config: InstConf, default_module: Union[str, ModuleType] = None) -> (type, dict): + """ + extract class/func and kwargs from config info + + Parameters + ---------- + config : [dict, str] + similar to config + please refer to the doc of init_instance_by_config + + default_module : Python module or str + It should be a python module to load the class type + This function will load class from the config['module_path'] first. + If config['module_path'] doesn't exists, it will load the class from default_module. + + Returns + ------- + (type, dict): + the class/func object and it's arguments. + + Raises + ------ + ModuleNotFoundError + """ + if isinstance(config, dict): + key = "class" if "class" in config else "func" + if isinstance(config[key], str): + # 1) get module and class + # - case 1): "a.b.c.ClassName" + # - case 2): {"class": "ClassName", "module_path": "a.b.c"} + m_path, cls = split_module_path(config[key]) + if m_path == "": + m_path = config.get("module_path", default_module) + module = get_module_by_module_path(m_path) + + # 2) get callable + _callable = getattr(module, cls) # may raise AttributeError + else: + _callable = config[key] # the class type itself is passed in + kwargs = config.get("kwargs", {}) + elif isinstance(config, str): + # a.b.c.ClassName + m_path, cls = split_module_path(config) + module = get_module_by_module_path(default_module if m_path == "" else m_path) + + _callable = getattr(module, cls) + kwargs = {} + else: + raise NotImplementedError(f"This type of input is not supported") + return _callable, kwargs + + +get_cls_kwargs = get_callable_kwargs # NOTE: this is for compatibility for the previous version + + +def init_instance_by_config( + config: InstConf, + default_module=None, + accept_types: Union[type, Tuple[type]] = (), + try_kwargs: Dict = {}, + **kwargs, +) -> Any: + """ + get initialized instance with config + + Parameters + ---------- + config : InstConf + + default_module : Python module + Optional. It should be a python module. + NOTE: the "module_path" will be override by `module` arguments + + This function will load class from the config['module_path'] first. + If config['module_path'] doesn't exists, it will load the class from default_module. + + accept_types: Union[type, Tuple[type]] + Optional. If the config is a instance of specific type, return the config directly. + This will be passed into the second parameter of isinstance. + + try_kwargs: Dict + Try to pass in kwargs in `try_kwargs` when initialized the instance + If error occurred, it will fail back to initialization without try_kwargs. + + Returns + ------- + object: + An initialized object based on the config info + """ + if isinstance(config, accept_types): + return config + + if isinstance(config, (str, Path)): + if isinstance(config, str): + # path like 'file:////obj.pkl' + pr = urlparse(config) + if pr.scheme == "file": + # To enable relative path like file://data/a/b/c.pkl. pr.netloc will be data + path = pr.path + if pr.netloc != "": + path = path.lstrip("/") + + pr_path = os.path.join(pr.netloc, path) if bool(pr.path) else pr.netloc + with open(os.path.normpath(pr_path), "rb") as f: + return restricted_pickle_load(f) + else: + with config.open("rb") as f: + return restricted_pickle_load(f) + + klass, cls_kwargs = get_callable_kwargs(config, default_module=default_module) + + try: + return klass(**cls_kwargs, **try_kwargs, **kwargs) + except (TypeError,): + # TypeError for handling errors like + # 1: `XXX() got multiple values for keyword argument 'YYY'` + # 2: `XXX() got an unexpected keyword argument 'YYY' + return klass(**cls_kwargs, **kwargs) + + +@contextlib.contextmanager +def class_casting(obj: object, cls: type): + """ + Python doesn't provide the downcasting mechanism. + We use the trick here to downcast the class + + Parameters + ---------- + obj : object + the object to be cast + cls : type + the target class type + """ + orig_cls = obj.__class__ + obj.__class__ = cls + yield + obj.__class__ = orig_cls + + +def find_all_classes(module_path: Union[str, ModuleType], cls: type) -> List[type]: + """ + Find all the classes recursively that inherit from `cls` in a given module. + - `cls` itself is also included + + >>> from qlib.data.dataset.handler import DataHandler + >>> find_all_classes("qlib.contrib.data.handler", DataHandler) + [, , , , ] + + TODO: + - skip import error + + """ + if isinstance(module_path, ModuleType): + mod = module_path + else: + mod = importlib.import_module(module_path) + + cls_list = [] + + def _append_cls(obj): + # Leverage the closure trick to reuse code + if isinstance(obj, type) and issubclass(obj, cls) and cls not in cls_list: + cls_list.append(obj) + + for attr in dir(mod): + _append_cls(getattr(mod, attr)) + + if hasattr(mod, "__path__"): + # if the model is a package + for _, modname, _ in pkgutil.iter_modules(mod.__path__): + sub_mod = importlib.import_module(f"{mod.__package__}.{modname}") + for m_cls in find_all_classes(sub_mod, cls): + _append_cls(m_cls) + return cls_list diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/objm.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/objm.py new file mode 100644 index 0000000000000000000000000000000000000000..227adc7f3bff3efef6bd7cb9edec7ac489d1b34e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/objm.py @@ -0,0 +1,134 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +import os +import pickle +import tempfile +from pathlib import Path + +from qlib.config import C +from qlib.utils.pickle_utils import restricted_pickle_load + + +class ObjManager: + def save_obj(self, obj: object, name: str): + """ + save obj as name + + Parameters + ---------- + obj : object + object to be saved + name : str + name of the object + """ + raise NotImplementedError(f"Please implement `save_obj`") + + def save_objs(self, obj_name_l): + """ + save objects + + Parameters + ---------- + obj_name_l : list of + """ + raise NotImplementedError(f"Please implement the `save_objs` method") + + def load_obj(self, name: str) -> object: + """ + load object by name + + Parameters + ---------- + name : str + the name of the object + + Returns + ------- + object: + loaded object + """ + raise NotImplementedError(f"Please implement the `load_obj` method") + + def exists(self, name: str) -> bool: + """ + if the object named `name` exists + + Parameters + ---------- + name : str + name of the objecT + + Returns + ------- + bool: + If the object exists + """ + raise NotImplementedError(f"Please implement the `exists` method") + + def list(self) -> list: + """ + list the objects + + Returns + ------- + list: + the list of returned objects + """ + raise NotImplementedError(f"Please implement the `list` method") + + def remove(self, fname=None): + """remove. + + Parameters + ---------- + fname : + if file name is provided. specific file is removed + otherwise, The all the objects will be removed. + """ + raise NotImplementedError(f"Please implement the `remove` method") + + +class FileManager(ObjManager): + """ + Use file system to manage objects + """ + + def __init__(self, path=None): + if path is None: + self.path = Path(self.create_path()) + else: + self.path = Path(path).resolve() + + def create_path(self) -> str: + try: + return tempfile.mkdtemp(prefix=str(C["file_manager_path"]) + os.sep) + except AttributeError as attribute_e: + raise NotImplementedError( + f"If path is not given, the `create_path` function should be implemented" + ) from attribute_e + + def save_obj(self, obj, name): + with (self.path / name).open("wb") as f: + pickle.dump(obj, f, protocol=C.dump_protocol_version) + + def save_objs(self, obj_name_l): + for obj, name in obj_name_l: + self.save_obj(obj, name) + + def load_obj(self, name): + with (self.path / name).open("rb") as f: + return restricted_pickle_load(f) + + def exists(self, name): + return (self.path / name).exists() + + def list(self): + return list(self.path.iterdir()) + + def remove(self, fname=None): + if fname is None: + for fp in self.path.glob("*"): + fp.unlink() + self.path.rmdir() + else: + (self.path / fname).unlink() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/paral.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/paral.py new file mode 100644 index 0000000000000000000000000000000000000000..a61778334136a5e5a107fc5f37b09f199e9e1ead --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/paral.py @@ -0,0 +1,332 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import threading +from functools import partial +from threading import Thread +from typing import Callable, Text, Union + +import joblib +from joblib import Parallel, delayed +from joblib._parallel_backends import MultiprocessingBackend +import pandas as pd + +from queue import Empty, Queue +import concurrent + +from qlib.config import C, QlibConfig + + +class ParallelExt(Parallel): + def __init__(self, *args, **kwargs): + maxtasksperchild = kwargs.pop("maxtasksperchild", None) + super(ParallelExt, self).__init__(*args, **kwargs) + if isinstance(self._backend, MultiprocessingBackend): + # 2025-05-04 joblib released version 1.5.0, in which _backend_args was removed and replaced by _backend_kwargs. + # Ref: https://github.com/joblib/joblib/pull/1525/files#diff-e4dff8042ce45b443faf49605b75a58df35b8c195978d4a57f4afa695b406bdc + if joblib.__version__ < "1.5.0": + self._backend_args["maxtasksperchild"] = maxtasksperchild # pylint: disable=E1101 + else: + self._backend_kwargs["maxtasksperchild"] = maxtasksperchild # pylint: disable=E1101 + + +def datetime_groupby_apply( + df, apply_func: Union[Callable, Text], axis=0, level="datetime", resample_rule="ME", n_jobs=-1 +): + """datetime_groupby_apply + This function will apply the `apply_func` on the datetime level index. + + Parameters + ---------- + df : + DataFrame for processing + apply_func : Union[Callable, Text] + apply_func for processing the data + if a string is given, then it is treated as naive pandas function + axis : + which axis is the datetime level located + level : + which level is the datetime level + resample_rule : + How to resample the data to calculating parallel + n_jobs : + n_jobs for joblib + Returns: + pd.DataFrame + """ + + def _naive_group_apply(df): + if isinstance(apply_func, str): + return getattr(df.groupby(axis=axis, level=level, group_keys=False), apply_func)() + return df.groupby(level=level, group_keys=False).apply(apply_func) + + if n_jobs != 1: + dfs = ParallelExt(n_jobs=n_jobs)( + delayed(_naive_group_apply)(sub_df) for idx, sub_df in df.resample(resample_rule, level=level) + ) + return pd.concat(dfs, axis=axis).sort_index() + else: + return _naive_group_apply(df) + + +class AsyncCaller: + """ + This AsyncCaller tries to make it easier to async call + + Currently, it is used in MLflowRecorder to make functions like `log_params` async + + NOTE: + - This caller didn't consider the return value + """ + + STOP_MARK = "__STOP" + + def __init__(self) -> None: + self._q = Queue() + self._stop = False + self._t = Thread(target=self.run) + self._t.start() + + def close(self): + self._q.put(self.STOP_MARK) + + def run(self): + while True: + # NOTE: + # atexit will only trigger when all the threads ended. So it may results in deadlock. + # So the child-threading should actively watch the status of main threading to stop itself. + main_thread = threading.main_thread() + if not main_thread.is_alive(): + break + try: + data = self._q.get(timeout=1) + except Empty: + # NOTE: avoid deadlock. make checking main thread possible + continue + if data == self.STOP_MARK: + break + data() + + def __call__(self, func, *args, **kwargs): + self._q.put(partial(func, *args, **kwargs)) + + def wait(self, close=True): + if close: + self.close() + self._t.join() + + @staticmethod + def async_dec(ac_attr): + def decorator_func(func): + def wrapper(self, *args, **kwargs): + if isinstance(getattr(self, ac_attr, None), Callable): + return getattr(self, ac_attr)(func, self, *args, **kwargs) + else: + return func(self, *args, **kwargs) + + return wrapper + + return decorator_func + + +# # Outlines: Joblib enhancement +# The code are for implementing following workflow +# - Construct complex data structure nested with delayed joblib tasks +# - For example, {"job": [, {"1": }]} +# - executing all the tasks and replace all the with its return value + +# This will make it easier to convert some existing code to a parallel one + + +class DelayedTask: + def get_delayed_tuple(self): + """get_delayed_tuple. + Return the delayed_tuple created by joblib.delayed + """ + raise NotImplementedError("NotImplemented") + + def set_res(self, res): + """set_res. + + Parameters + ---------- + res : + the executed result of the delayed tuple + """ + self.res = res + + def get_replacement(self): + """return the object to replace the delayed task""" + raise NotImplementedError("NotImplemented") + + +class DelayedTuple(DelayedTask): + def __init__(self, delayed_tpl): + self.delayed_tpl = delayed_tpl + self.res = None + + def get_delayed_tuple(self): + return self.delayed_tpl + + def get_replacement(self): + return self.res + + +class DelayedDict(DelayedTask): + """DelayedDict. + It is designed for following feature: + Converting following existing code to parallel + - constructing a dict + - key can be gotten instantly + - computation of values tasks a lot of time. + - AND ALL the values are calculated in a SINGLE function + """ + + def __init__(self, key_l, delayed_tpl): + self.key_l = key_l + self.delayed_tpl = delayed_tpl + + def get_delayed_tuple(self): + return self.delayed_tpl + + def get_replacement(self): + return dict(zip(self.key_l, self.res)) + + +def is_delayed_tuple(obj) -> bool: + """is_delayed_tuple. + + Parameters + ---------- + obj : object + + Returns + ------- + bool + is `obj` joblib.delayed tuple + """ + return isinstance(obj, tuple) and len(obj) == 3 and callable(obj[0]) + + +def _replace_and_get_dt(complex_iter): + """_replace_and_get_dt. + + FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference + + Parameters + ---------- + complex_iter : + complex_iter + """ + if isinstance(complex_iter, DelayedTask): + dt = complex_iter + return dt, [dt] + elif is_delayed_tuple(complex_iter): + dt = DelayedTuple(complex_iter) + return dt, [dt] + elif isinstance(complex_iter, (list, tuple)): + new_ci = [] + dt_all = [] + for item in complex_iter: + new_item, dt_list = _replace_and_get_dt(item) + new_ci.append(new_item) + dt_all += dt_list + return new_ci, dt_all + elif isinstance(complex_iter, dict): + new_ci = {} + dt_all = [] + for key, item in complex_iter.items(): + new_item, dt_list = _replace_and_get_dt(item) + new_ci[key] = new_item + dt_all += dt_list + return new_ci, dt_all + else: + return complex_iter, [] + + +def _recover_dt(complex_iter): + """_recover_dt. + + replace all the DelayedTask in the `complex_iter` with its `.res` value + + FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference + + Parameters + ---------- + complex_iter : + complex_iter + """ + if isinstance(complex_iter, DelayedTask): + return complex_iter.get_replacement() + elif isinstance(complex_iter, (list, tuple)): + return [_recover_dt(item) for item in complex_iter] + elif isinstance(complex_iter, dict): + return {key: _recover_dt(item) for key, item in complex_iter.items()} + else: + return complex_iter + + +def complex_parallel(paral: Parallel, complex_iter): + """complex_parallel. + Find all the delayed function created by delayed in complex_iter, run them parallelly and then replace it with the result + + >>> from qlib.utils.paral import complex_parallel + >>> from joblib import Parallel, delayed + >>> complex_iter = {"a": delayed(sum)([1,2,3]), "b": [1, 2, delayed(sum)([10, 1])]} + >>> complex_parallel(Parallel(), complex_iter) + {'a': 6, 'b': [1, 2, 11]} + + Parameters + ---------- + paral : Parallel + paral + complex_iter : + NOTE: only list, tuple and dict will be explored!!!! + + Returns + ------- + complex_iter whose delayed joblib tasks are replaced with its execution results. + """ + + complex_iter, dt_all = _replace_and_get_dt(complex_iter) + for res, dt in zip(paral(dt.get_delayed_tuple() for dt in dt_all), dt_all): + dt.set_res(res) + complex_iter = _recover_dt(complex_iter) + return complex_iter + + +class call_in_subproc: + """ + When we repeatedly run functions, it is hard to avoid memory leakage. + So we run it in the subprocess to ensure it is OK. + + NOTE: Because local object can't be pickled. So we can't implement it via closure. + We have to implement it via callable Class + """ + + def __init__(self, func: Callable, qlib_config: QlibConfig = None): + """ + Parameters + ---------- + func : Callable + the function to be wrapped + + qlib_config : QlibConfig + Qlib config for initialization in subprocess + + Returns + ------- + Callable + """ + self.func = func + self.qlib_config = qlib_config + + def _func_mod(self, *args, **kwargs): + """Modify the initial function by adding Qlib initialization""" + if self.qlib_config is not None: + C.register_from_C(self.qlib_config) + return self.func(*args, **kwargs) + + def __call__(self, *args, **kwargs): + with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor: + return executor.submit(self._func_mod, *args, **kwargs).result() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/pickle_utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/pickle_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..920692f3c89f7385db79f6751749756f1ca70eaa --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/pickle_utils.py @@ -0,0 +1,171 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Secure pickle utilities to prevent arbitrary code execution through deserialization. + +This module provides a secure alternative to pickle.load() and pickle.loads() +that restricts deserialization to a whitelist of safe classes. +""" + +import io +import pickle +from typing import Any, BinaryIO, Set, Tuple + +# Whitelist of safe classes that are allowed to be unpickled +# These are common data types used in qlib that should be safe to deserialize +SAFE_PICKLE_CLASSES: Set[Tuple[str, str]] = { + # python builtins + ("builtins", "slice"), + ("builtins", "range"), + ("builtins", "dict"), + ("builtins", "list"), + ("builtins", "tuple"), + ("builtins", "set"), + ("builtins", "frozenset"), + ("builtins", "bytearray"), + ("builtins", "bytes"), + ("builtins", "str"), + ("builtins", "int"), + ("builtins", "float"), + ("builtins", "bool"), + ("builtins", "complex"), + ("builtins", "type"), + ("builtins", "property"), + # common utility classes + ("datetime", "datetime"), + ("datetime", "date"), + ("datetime", "time"), + ("datetime", "timedelta"), + ("datetime", "timezone"), + ("decimal", "Decimal"), + ("collections", "OrderedDict"), + ("collections", "defaultdict"), + ("collections", "Counter"), + ("collections", "namedtuple"), + ("enum", "Enum"), + ("pathlib", "Path"), + ("pathlib", "PosixPath"), + ("pathlib", "WindowsPath"), + ("qlib.data.dataset.handler", "DataHandler"), + ("qlib.data.dataset.handler", "DataHandlerLP"), + ("qlib.data.dataset.loader", "StaticDataLoader"), +} + + +TRUSTED_MODULE_PREFIXES = ( + "pandas", + "numpy", +) + + +class RestrictedUnpickler(pickle.Unpickler): + """Custom unpickler that only allows safe classes to be deserialized. + + This prevents arbitrary code execution through malicious pickle files by + restricting deserialization to a whitelist of safe classes. + + Example: + >>> with open("data.pkl", "rb") as f: + ... data = RestrictedUnpickler(f).load() + """ + + def find_class(self, module: str, name: str): + """Override find_class to restrict allowed classes. + + Args: + module: Module name of the class + name: Class name + + Returns: + The class object if it's in the whitelist + + Raises: + pickle.UnpicklingError: If the class is not in the whitelist + """ + if module.startswith(TRUSTED_MODULE_PREFIXES): + return super().find_class(module, name) + + # 2. explicit whitelist (qlib internal) + if (module, name) in SAFE_PICKLE_CLASSES: + return super().find_class(module, name) + + raise pickle.UnpicklingError( + f"Forbidden class: {module}.{name}. " + f"Only whitelisted classes are allowed for security reasons. " + f"This is to prevent arbitrary code execution through pickle deserialization." + ) + + +def restricted_pickle_load(file: BinaryIO) -> Any: + """Safely load a pickle file with restricted classes. + + This is a drop-in replacement for pickle.load() that prevents + arbitrary code execution by only allowing whitelisted classes. + + Args: + file: An opened file object in binary mode + + Returns: + The unpickled Python object + + Raises: + pickle.UnpicklingError: If the pickle contains forbidden classes + + Example: + >>> with open("data.pkl", "rb") as f: + ... data = restricted_pickle_load(f) + """ + return RestrictedUnpickler(file).load() + + +def restricted_pickle_loads(data: bytes) -> Any: + """Safely load a pickle from bytes with restricted classes. + + This is a drop-in replacement for pickle.loads() that prevents + arbitrary code execution by only allowing whitelisted classes. + + Args: + data: Bytes object containing pickled data + + Returns: + The unpickled Python object + + Raises: + pickle.UnpicklingError: If the pickle contains forbidden classes + + Example: + >>> data = b'\\x80\\x04\\x95...' + >>> obj = restricted_pickle_loads(data) + """ + file_like = io.BytesIO(data) + return RestrictedUnpickler(file_like).load() + + +def add_safe_class(module: str, name: str) -> None: + """Add a class to the whitelist of safe classes for unpickling. + + Use this function to extend the whitelist if your code needs to deserialize + additional classes. However, be very careful when adding classes, as this + could potentially introduce security vulnerabilities. + + Args: + module: Module name of the class (e.g., 'my_package.my_module') + name: Class name (e.g., 'MyClass') + + Warning: + Only add classes that you fully control and trust. Adding arbitrary + classes from external packages could introduce security risks. + + Example: + >>> add_safe_class('my_package.models', 'CustomModel') + """ + SAFE_PICKLE_CLASSES.add((module, name)) + + +def get_safe_classes() -> Set[Tuple[str, str]]: + """Get a copy of the current whitelist of safe classes. + + Returns: + A set of (module, name) tuples representing allowed classes + """ + return SAFE_PICKLE_CLASSES.copy() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/resam.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/resam.py new file mode 100644 index 0000000000000000000000000000000000000000..99aedfcd50c1c89f371c109f01efff03c60c04ac --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/resam.py @@ -0,0 +1,239 @@ +import numpy as np +import pandas as pd + +from functools import partial +from typing import Union, Callable + +from . import lazy_sort_index +from .time import Freq, cal_sam_minute +from ..config import C + + +def resam_calendar( + calendar_raw: np.ndarray, freq_raw: Union[str, Freq], freq_sam: Union[str, Freq], region: str = None +) -> np.ndarray: + """ + Resample the calendar with frequency freq_raw into the calendar with frequency freq_sam + Assumption: + - Fix length (240) of the calendar in each day. + + Parameters + ---------- + calendar_raw : np.ndarray + The calendar with frequency freq_raw + freq_raw : str + Frequency of the raw calendar + freq_sam : str + Sample frequency + region: str + Region, for example, "cn", "us" + Returns + ------- + np.ndarray + The calendar with frequency freq_sam + """ + if region is None: + region = C["region"] + + freq_raw = Freq(freq_raw) + freq_sam = Freq(freq_sam) + if not len(calendar_raw): + return calendar_raw + + # if freq_sam is xminute, divide each trading day into several bars evenly + if freq_sam.base == Freq.NORM_FREQ_MINUTE: + if freq_raw.base != Freq.NORM_FREQ_MINUTE: + raise ValueError("when sampling minute calendar, freq of raw calendar must be minute or min") + else: + if freq_raw.count > freq_sam.count: + raise ValueError("raw freq must be higher than sampling freq") + _calendar_minute = np.unique(list(map(lambda x: cal_sam_minute(x, freq_sam.count, region), calendar_raw))) + return _calendar_minute + + # else, convert the raw calendar into day calendar, and divide the whole calendar into several bars evenly + else: + _calendar_day = np.unique(list(map(lambda x: pd.Timestamp(x.year, x.month, x.day, 0, 0, 0), calendar_raw))) + if freq_sam.base == Freq.NORM_FREQ_DAY: + return _calendar_day[:: freq_sam.count] + + elif freq_sam.base == Freq.NORM_FREQ_WEEK: + _day_in_week = np.array(list(map(lambda x: x.dayofweek, _calendar_day))) + _calendar_week = _calendar_day[np.ediff1d(_day_in_week, to_begin=-1) < 0] + return _calendar_week[:: freq_sam.count] + + elif freq_sam.base == Freq.NORM_FREQ_MONTH: + _day_in_month = np.array(list(map(lambda x: x.day, _calendar_day))) + _calendar_month = _calendar_day[np.ediff1d(_day_in_month, to_begin=-1) < 0] + return _calendar_month[:: freq_sam.count] + else: + raise ValueError("sampling freq must be xmin, xd, xw, xm") + + +def get_higher_eq_freq_feature(instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1): + """get the feature with higher or equal frequency than `freq`. + Returns + ------- + pd.DataFrame + the feature with higher or equal frequency + """ + + from ..data.data import D # pylint: disable=C0415 + + try: + _result = D.features(instruments, fields, start_time, end_time, freq=freq, disk_cache=disk_cache) + _freq = freq + except (ValueError, KeyError) as value_key_e: + _, norm_freq = Freq.parse(freq) + if norm_freq in [Freq.NORM_FREQ_MONTH, Freq.NORM_FREQ_WEEK, Freq.NORM_FREQ_DAY]: + try: + _result = D.features(instruments, fields, start_time, end_time, freq="day", disk_cache=disk_cache) + _freq = "day" + except (ValueError, KeyError): + _result = D.features(instruments, fields, start_time, end_time, freq="1min", disk_cache=disk_cache) + _freq = "1min" + elif norm_freq == Freq.NORM_FREQ_MINUTE: + _result = D.features(instruments, fields, start_time, end_time, freq="1min", disk_cache=disk_cache) + _freq = "1min" + else: + raise ValueError(f"freq {freq} is not supported") from value_key_e + return _result, _freq + + +def resam_ts_data( + ts_feature: Union[pd.DataFrame, pd.Series], + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + method: Union[str, Callable] = "last", + method_kwargs: dict = {}, +): + """ + Resample value from time-series data + + - If `feature` has MultiIndex[instrument, datetime], apply the `method` to each instrument data with datetime in [start_time, end_time] + Example: + + .. code-block:: + + print(feature) + $close $volume + instrument datetime + SH600000 2010-01-04 86.778313 16162960.0 + 2010-01-05 87.433578 28117442.0 + 2010-01-06 85.713585 23632884.0 + 2010-01-07 83.788803 20813402.0 + 2010-01-08 84.730675 16044853.0 + + SH600655 2010-01-04 2699.567383 158193.328125 + 2010-01-08 2612.359619 77501.406250 + 2010-01-11 2712.982422 160852.390625 + 2010-01-12 2788.688232 164587.937500 + 2010-01-13 2790.604004 145460.453125 + + print(resam_ts_data(feature, start_time="2010-01-04", end_time="2010-01-05", fields=["$close", "$volume"], method="last")) + $close $volume + instrument + SH600000 87.433578 28117442.0 + SH600655 2699.567383 158193.328125 + + - Else, the `feature` should have Index[datetime], just apply the `method` to `feature` directly + Example: + + .. code-block:: + print(feature) + $close $volume + datetime + 2010-01-04 86.778313 16162960.0 + 2010-01-05 87.433578 28117442.0 + 2010-01-06 85.713585 23632884.0 + 2010-01-07 83.788803 20813402.0 + 2010-01-08 84.730675 16044853.0 + + print(resam_ts_data(feature, start_time="2010-01-04", end_time="2010-01-05", method="last")) + + $close 87.433578 + $volume 28117442.0 + + print(resam_ts_data(feature['$close'], start_time="2010-01-04", end_time="2010-01-05", method="last")) + + 87.433578 + + Parameters + ---------- + ts_feature : Union[pd.DataFrame, pd.Series] + Raw time-series feature to be resampled + start_time : Union[str, pd.Timestamp], optional + start sampling time, by default None + end_time : Union[str, pd.Timestamp], optional + end sampling time, by default None + method : Union[str, Callable], optional + sample method, apply method function to each stock series data, by default "last" + - If type(method) is str or callable function, it should be an attribute of SeriesGroupBy or DataFrameGroupby, and applies groupy.method for the sliced time-series data + - If method is None, do nothing for the sliced time-series data. + method_kwargs : dict, optional + arguments of method, by default {} + + Returns + ------- + The resampled DataFrame/Series/value, return None when the resampled data is empty. + """ + + selector_datetime = slice(start_time, end_time) + + from ..data.dataset.utils import get_level_index # pylint: disable=C0415 + + feature = lazy_sort_index(ts_feature) + + datetime_level = get_level_index(feature, level="datetime") == 0 + if datetime_level: + feature = feature.loc[selector_datetime] + else: + feature = feature.loc(axis=0)[(slice(None), selector_datetime)] + + if feature.empty: + return None + if isinstance(feature.index, pd.MultiIndex): + if callable(method): + method_func = method + return feature.groupby(level="instrument", group_keys=False).apply(method_func, **method_kwargs) + elif isinstance(method, str): + return getattr(feature.groupby(level="instrument", group_keys=False), method)(**method_kwargs) + else: + if callable(method): + method_func = method + return method_func(feature, **method_kwargs) + elif isinstance(method, str): + return getattr(feature, method)(**method_kwargs) + return feature + + +def get_valid_value(series, last=True): + """get the first/last not nan value of pd.Series with single level index + Parameters + ---------- + series : pd.Series + series should not be empty + last : bool, optional + whether to get the last valid value, by default True + - if last is True, get the last valid value + - else, get the first valid value + + Returns + ------- + Nan | float + the first/last valid value + """ + return series.ffill().iloc[-1] if last else series.bfill().iloc[0] + + +def _ts_data_valid(ts_feature, last=False): + """get the first/last not nan value of pd.Series|DataFrame with single level index""" + if isinstance(ts_feature, pd.DataFrame): + return ts_feature.apply(lambda column: get_valid_value(column, last=last)) + elif isinstance(ts_feature, pd.Series): + return get_valid_value(ts_feature, last=last) + else: + raise TypeError(f"ts_feature should be pd.DataFrame/Series, not {type(ts_feature)}") + + +ts_data_last = partial(_ts_data_valid, last=True) +ts_data_first = partial(_ts_data_valid, last=False) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/serial.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/serial.py new file mode 100644 index 0000000000000000000000000000000000000000..720dbd792889b8a0643712142df367bfa9bd521f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/serial.py @@ -0,0 +1,189 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import pickle +import dill +from pathlib import Path +from typing import Union +from ..config import C + + +class Serializable: + """ + Serializable will change the behaviors of pickle. + + The rule to tell if a attribute will be kept or dropped when dumping. + The rule with higher priorities is on the top + - in the config attribute list -> always dropped + - in the include attribute list -> always kept + - in the exclude attribute list -> always dropped + - name not starts with `_` -> kept + - name starts with `_` -> kept if `dump_all` is true else dropped + + It provides a syntactic sugar for distinguish the attributes which user doesn't want. + - For examples, a learnable Datahandler just wants to save the parameters without data when dumping to disk + """ + + pickle_backend = "pickle" # another optional value is "dill" which can pickle more things of python. + default_dump_all = False # if dump all things + config_attr = ["_include", "_exclude"] + exclude_attr = [] # exclude_attr have lower priorities than `self._exclude` + include_attr = [] # include_attr have lower priorities then `self._include` + FLAG_KEY = "_qlib_serial_flag" + + def __init__(self): + self._dump_all = self.default_dump_all + self._exclude = None # this attribute have higher priorities than `exclude_attr` + + def _is_kept(self, key): + if key in self.config_attr: + return False + if key in self._get_attr_list("include"): + return True + if key in self._get_attr_list("exclude"): + return False + return self.dump_all or not key.startswith("_") + + def __getstate__(self) -> dict: + return {k: v for k, v in self.__dict__.items() if self._is_kept(k)} + + def __setstate__(self, state: dict): + self.__dict__.update(state) + + @property + def dump_all(self): + """ + will the object dump all object + """ + return getattr(self, "_dump_all", False) + + def _get_attr_list(self, attr_type: str) -> list: + """ + What attribute will not be in specific list + + Parameters + ---------- + attr_type : str + "include" or "exclude" + + Returns + ------- + list: + """ + if hasattr(self, f"_{attr_type}"): + res = getattr(self, f"_{attr_type}", []) + else: + res = getattr(self.__class__, f"{attr_type}_attr", []) + if res is None: + return [] + return res + + def config(self, recursive=False, **kwargs): + """ + configure the serializable object + + Parameters + ---------- + kwargs may include following keys + + dump_all : bool + will the object dump all object + exclude : list + What attribute will not be dumped + include : list + What attribute will be dumped + + recursive : bool + will the configuration be recursive + """ + keys = {"dump_all", "exclude", "include"} + for k, v in kwargs.items(): + if k in keys: + attr_name = f"_{k}" + setattr(self, attr_name, v) + else: + raise KeyError(f"Unknown parameter: {k}") + + if recursive: + for obj in self.__dict__.values(): + # set flag to prevent endless loop + self.__dict__[self.FLAG_KEY] = True + if isinstance(obj, Serializable) and self.FLAG_KEY not in obj.__dict__: + obj.config(recursive=True, **kwargs) + del self.__dict__[self.FLAG_KEY] + + def to_pickle(self, path: Union[Path, str], **kwargs): + """ + Dump self to a pickle file. + + path (Union[Path, str]): the path to dump + + kwargs may include following keys + + dump_all : bool + will the object dump all object + exclude : list + What attribute will not be dumped + include : list + What attribute will be dumped + """ + self.config(**kwargs) + with Path(path).open("wb") as f: + # pickle interface like backend; such as dill + self.get_backend().dump(self, f, protocol=C.dump_protocol_version) + + @classmethod + def load(cls, filepath): + """ + Load the serializable class from a filepath. + + Args: + filepath (str): the path of file + + Raises: + TypeError: the pickled file must be `type(cls)` + + Returns: + `type(cls)`: the instance of `type(cls)` + """ + with open(filepath, "rb") as f: + object = cls.get_backend().load(f) + if isinstance(object, cls): + return object + else: + raise TypeError(f"The instance of {type(object)} is not a valid `{type(cls)}`!") + + @classmethod + def get_backend(cls): + """ + Return the real backend of a Serializable class. The pickle_backend value can be "pickle" or "dill". + + Returns: + module: pickle or dill module based on pickle_backend + """ + # NOTE: pickle interface like backend; such as dill + if cls.pickle_backend == "pickle": + return pickle + elif cls.pickle_backend == "dill": + return dill + else: + raise ValueError("Unknown pickle backend, please use 'pickle' or 'dill'.") + + @staticmethod + def general_dump(obj, path: Union[Path, str]): + """ + A general dumping method for object + + Parameters + ---------- + obj : object + the object to be dumped + path : Union[Path, str] + the target path the data will be dumped + """ + path = Path(path) + if isinstance(obj, Serializable): + obj.to_pickle(path) + else: + with path.open("wb") as f: + pickle.dump(obj, f, protocol=C.dump_protocol_version) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/time.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/time.py new file mode 100644 index 0000000000000000000000000000000000000000..b052f6ab9f755216912f356a58e9040f4e33cf51 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/utils/time.py @@ -0,0 +1,377 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Time related utils are compiled in this script +""" + +import bisect +from datetime import datetime, time, date, timedelta +from typing import List, Optional, Tuple, Union +import functools +import re + +import pandas as pd + +from qlib.config import C +from qlib.constant import REG_CN, REG_TW, REG_US + +CN_TIME = [ + datetime.strptime("9:30", "%H:%M"), + datetime.strptime("11:30", "%H:%M"), + datetime.strptime("13:00", "%H:%M"), + datetime.strptime("15:00", "%H:%M"), +] +US_TIME = [datetime.strptime("9:30", "%H:%M"), datetime.strptime("16:00", "%H:%M")] +TW_TIME = [ + datetime.strptime("9:00", "%H:%M"), + datetime.strptime("13:30", "%H:%M"), +] + + +@functools.lru_cache(maxsize=240) +def get_min_cal(shift: int = 0, region: str = REG_CN) -> List[time]: + """ + get the minute level calendar in day period + + Parameters + ---------- + shift : int + the shift direction would be like pandas shift. + series.shift(1) will replace the value at `i`-th with the one at `i-1`-th + region: str + Region, for example, "cn", "us" + + Returns + ------- + List[time]: + + """ + cal = [] + + if region == REG_CN: + for ts in list( + pd.date_range(CN_TIME[0], CN_TIME[1] - timedelta(minutes=1), freq="1min") - pd.Timedelta(minutes=shift) + ) + list( + pd.date_range(CN_TIME[2], CN_TIME[3] - timedelta(minutes=1), freq="1min") - pd.Timedelta(minutes=shift) + ): + cal.append(ts.time()) + elif region == REG_TW: + for ts in list( + pd.date_range(TW_TIME[0], TW_TIME[1] - timedelta(minutes=1), freq="1min") - pd.Timedelta(minutes=shift) + ): + cal.append(ts.time()) + elif region == REG_US: + for ts in list( + pd.date_range(US_TIME[0], US_TIME[1] - timedelta(minutes=1), freq="1min") - pd.Timedelta(minutes=shift) + ): + cal.append(ts.time()) + else: + raise ValueError(f"{region} is not supported") + return cal + + +def is_single_value(start_time, end_time, freq, region: str = REG_CN): + """Is there only one piece of data for stock market. + + Parameters + ---------- + start_time : Union[pd.Timestamp, str] + closed start time for data. + end_time : Union[pd.Timestamp, str] + closed end time for data. + freq : + region: str + Region, for example, "cn", "us" + Returns + ------- + bool + True means one piece of data to obtain. + """ + if region == REG_CN: + if end_time - start_time < freq: + return True + if start_time.hour == 11 and start_time.minute == 29 and start_time.second == 0: + return True + if start_time.hour == 14 and start_time.minute == 59 and start_time.second == 0: + return True + return False + elif region == REG_TW: + if end_time - start_time < freq: + return True + if start_time.hour == 13 and start_time.minute >= 25 and start_time.second == 0: + return True + return False + elif region == REG_US: + if end_time - start_time < freq: + return True + if start_time.hour == 15 and start_time.minute == 59 and start_time.second == 0: + return True + return False + else: + raise NotImplementedError(f"please implement the is_single_value func for {region}") + + +class Freq: + NORM_FREQ_MONTH = "month" + NORM_FREQ_WEEK = "week" + NORM_FREQ_DAY = "day" + NORM_FREQ_MINUTE = "min" # using min instead of minute for align with Qlib's data filename + SUPPORT_CAL_LIST = [NORM_FREQ_MINUTE, NORM_FREQ_DAY] # FIXME: this list should from data + + def __init__(self, freq: Union[str, "Freq"]) -> None: + if isinstance(freq, str): + self.count, self.base = self.parse(freq) + elif isinstance(freq, Freq): + self.count, self.base = freq.count, freq.base + else: + raise NotImplementedError(f"This type of input is not supported") + + def __eq__(self, freq): + freq = Freq(freq) + return freq.count == self.count and freq.base == self.base + + def __str__(self): + # trying to align to the filename of Qlib: day, 30min, 5min, 1min... + return f"{self.count if self.count != 1 or self.base != 'day' else ''}{self.base}" + + def __repr__(self) -> str: + return f"{self.__class__.__name__}({str(self)})" + + @staticmethod + def parse(freq: str) -> Tuple[int, str]: + """ + Parse freq into a unified format + + Parameters + ---------- + freq : str + Raw freq, supported freq should match the re '^([0-9]*)(month|mon|week|w|day|d|minute|min)$' + + Returns + ------- + freq: Tuple[int, str] + Unified freq, including freq count and unified freq unit. The freq unit should be '[month|week|day|minute]'. + Example: + + .. code-block:: + + print(Freq.parse("day")) + (1, "day" ) + print(Freq.parse("2mon")) + (2, "month") + print(Freq.parse("10w")) + (10, "week") + + """ + freq = freq.lower() + match_obj = re.match("^([0-9]*)(month|mon|week|w|day|d|minute|min)$", freq) + if match_obj is None: + raise ValueError( + "freq format is not supported, the freq should be like (n)month/mon, (n)week/w, (n)day/d, (n)minute/min" + ) + _count = int(match_obj.group(1)) if match_obj.group(1) else 1 + _freq = match_obj.group(2) + _freq_format_dict = { + "month": Freq.NORM_FREQ_MONTH, + "mon": Freq.NORM_FREQ_MONTH, + "week": Freq.NORM_FREQ_WEEK, + "w": Freq.NORM_FREQ_WEEK, + "day": Freq.NORM_FREQ_DAY, + "d": Freq.NORM_FREQ_DAY, + "minute": Freq.NORM_FREQ_MINUTE, + "min": Freq.NORM_FREQ_MINUTE, + } + return _count, _freq_format_dict[_freq] + + @staticmethod + def get_timedelta(n: int, freq: str) -> pd.Timedelta: + """ + get pd.Timedeta object + + Parameters + ---------- + n : int + freq : str + Typically, they are the return value of Freq.parse + + Returns + ------- + pd.Timedelta: + """ + return pd.Timedelta(f"{n}{freq}") + + @staticmethod + def get_min_delta(left_frq: str, right_freq: str): + """Calculate freq delta + + Parameters + ---------- + left_frq: str + right_freq: str + + Returns + ------- + + """ + minutes_map = { + Freq.NORM_FREQ_MINUTE: 1, + Freq.NORM_FREQ_DAY: 60 * 24, + Freq.NORM_FREQ_WEEK: 7 * 60 * 24, + Freq.NORM_FREQ_MONTH: 30 * 7 * 60 * 24, + } + left_freq = Freq(left_frq) + left_minutes = left_freq.count * minutes_map[left_freq.base] + right_freq = Freq(right_freq) + right_minutes = right_freq.count * minutes_map[right_freq.base] + return left_minutes - right_minutes + + @staticmethod + def get_recent_freq(base_freq: Union[str, "Freq"], freq_list: List[Union[str, "Freq"]]) -> Optional["Freq"]: + """Get the closest freq to base_freq from freq_list + + Parameters + ---------- + base_freq + freq_list + + Returns + ------- + if the recent frequency is found + Freq + else: + None + """ + base_freq = Freq(base_freq) + # use the nearest freq greater than 0 + min_freq = None + for _freq in freq_list: + _min_delta = Freq.get_min_delta(base_freq, _freq) + if _min_delta < 0: + continue + if min_freq is None: + min_freq = (_min_delta, str(_freq)) + continue + min_freq = min_freq if min_freq[0] <= _min_delta else (_min_delta, _freq) + return min_freq[1] if min_freq else None + + +def time_to_day_index(time_obj: Union[str, datetime], region: str = REG_CN): + if isinstance(time_obj, str): + time_obj = datetime.strptime(time_obj, "%H:%M") + + if region == REG_CN: + if CN_TIME[0] <= time_obj < CN_TIME[1]: + return int((time_obj - CN_TIME[0]).total_seconds() / 60) + elif CN_TIME[2] <= time_obj < CN_TIME[3]: + return int((time_obj - CN_TIME[2]).total_seconds() / 60) + 120 + else: + raise ValueError(f"{time_obj} is not the opening time of the {region} stock market") + elif region == REG_US: + if US_TIME[0] <= time_obj < US_TIME[1]: + return int((time_obj - US_TIME[0]).total_seconds() / 60) + else: + raise ValueError(f"{time_obj} is not the opening time of the {region} stock market") + elif region == REG_TW: + if TW_TIME[0] <= time_obj < TW_TIME[1]: + return int((time_obj - TW_TIME[0]).total_seconds() / 60) + else: + raise ValueError(f"{time_obj} is not the opening time of the {region} stock market") + else: + raise ValueError(f"{region} is not supported") + + +def get_day_min_idx_range(start: str, end: str, freq: str, region: str) -> Tuple[int, int]: + """ + get the min-bar index in a day for a time range (both left and right is closed) given a fixed frequency + Parameters + ---------- + start : str + e.g. "9:30" + end : str + e.g. "14:30" + freq : str + "1min" + + Returns + ------- + Tuple[int, int]: + The index of start and end in the calendar. Both left and right are **closed** + """ + start = pd.Timestamp(start).time() + end = pd.Timestamp(end).time() + freq = Freq(freq) + in_day_cal = get_min_cal(region=region)[:: freq.count] + left_idx = bisect.bisect_left(in_day_cal, start) + right_idx = bisect.bisect_right(in_day_cal, end) - 1 + return left_idx, right_idx + + +def concat_date_time(date_obj: date, time_obj: time) -> pd.Timestamp: + return pd.Timestamp( + datetime( + date_obj.year, + month=date_obj.month, + day=date_obj.day, + hour=time_obj.hour, + minute=time_obj.minute, + second=time_obj.second, + microsecond=time_obj.microsecond, + ) + ) + + +def cal_sam_minute(x: pd.Timestamp, sam_minutes: int, region: str = REG_CN) -> pd.Timestamp: + """ + align the minute-level data to a down sampled calendar + + e.g. align 10:38 to 10:35 in 5 minute-level(10:30 in 10 minute-level) + + Parameters + ---------- + x : pd.Timestamp + datetime to be aligned + sam_minutes : int + align to `sam_minutes` minute-level calendar + region: str + Region, for example, "cn", "us" + + Returns + ------- + pd.Timestamp: + the datetime after aligned + """ + cal = get_min_cal(C.min_data_shift, region)[::sam_minutes] + idx = bisect.bisect_right(cal, x.time()) - 1 + _date, new_time = x.date(), cal[idx] + return concat_date_time(_date, new_time) + + +def epsilon_change(date_time: pd.Timestamp, direction: str = "backward") -> pd.Timestamp: + """ + change the time by infinitely small quantity. + + + Parameters + ---------- + date_time : pd.Timestamp + the original time + direction : str + the direction the time are going to + - "backward" for going to history + - "forward" for going to the future + + Returns + ------- + pd.Timestamp: + the shifted time + """ + if direction == "backward": + return date_time - pd.Timedelta(seconds=1) + elif direction == "forward": + return date_time + pd.Timedelta(seconds=1) + else: + raise ValueError("Wrong input") + + +if __name__ == "__main__": + print(get_day_min_idx_range("8:30", "14:59", "10min", REG_CN)) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a29e471c04b47282cec280ff54784b419bacb4b0 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/__init__.py @@ -0,0 +1,681 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Motivation of this design (instead of using mlflow directly): +- Better design than mlflow native design + - we have record object with a lot of methods(more intuitive), instead of use run_id everytime in mlflow + - So the recorder's interfaces like log, start, will be more intuitive. +- Provide richer and tailerd features than mlflow native + - Logging code diff at the start of run. + - log_object and load_object to for Python object directly instead log_artifact and download_artifact +- (weak) Allow diverse backend support + +To be honest, design always add burdens. For example, +- You need to create an experiment before you can get a recorder. (In MLflow, experiments are more like tags, and you often just use a run_id in many interfaces without first defining an experiment.) +""" + +from contextlib import contextmanager +from typing import Text, Optional, Any, Dict +from .expm import ExpManager +from .exp import Experiment +from .recorder import Recorder +from ..utils import Wrapper +from ..utils.exceptions import RecorderInitializationError + + +class QlibRecorder: + """ + A global system that helps to manage the experiments. + """ + + def __init__(self, exp_manager: ExpManager): + self.exp_manager: ExpManager = exp_manager + + def __repr__(self): + return "{name}(manager={manager})".format(name=self.__class__.__name__, manager=self.exp_manager) + + @contextmanager + def start( + self, + *, + experiment_id: Optional[Text] = None, + experiment_name: Optional[Text] = None, + recorder_id: Optional[Text] = None, + recorder_name: Optional[Text] = None, + uri: Optional[Text] = None, + resume: bool = False, + ): + """ + Method to start an experiment. This method can only be called within a Python's `with` statement. Here is the example code: + + .. code-block:: Python + + # start new experiment and recorder + with R.start(experiment_name='test', recorder_name='recorder_1'): + model.fit(dataset) + R.log... + ... # further operations + + # resume previous experiment and recorder + with R.start(experiment_name='test', recorder_name='recorder_1', resume=True): # if users want to resume recorder, they have to specify the exact same name for experiment and recorder. + ... # further operations + + + Parameters + ---------- + experiment_id : str + id of the experiment one wants to start. + experiment_name : str + name of the experiment one wants to start. + recorder_id : str + id of the recorder under the experiment one wants to start. + recorder_name : str + name of the recorder under the experiment one wants to start. + uri : str + The tracking uri of the experiment, where all the artifacts/metrics etc. will be stored. + The default uri is set in the qlib.config. Note that this uri argument will not change the one defined in the config file. + Therefore, the next time when users call this function in the same experiment, + they have to also specify this argument with the same value. Otherwise, inconsistent uri may occur. + resume : bool + whether to resume the specific recorder with given name under the given experiment. + """ + run = self.start_exp( + experiment_id=experiment_id, + experiment_name=experiment_name, + recorder_id=recorder_id, + recorder_name=recorder_name, + uri=uri, + resume=resume, + ) + try: + yield run + except Exception as e: + self.end_exp(Recorder.STATUS_FA) # end the experiment if something went wrong + raise e + self.end_exp(Recorder.STATUS_FI) + + def start_exp( + self, + *, + experiment_id=None, + experiment_name=None, + recorder_id=None, + recorder_name=None, + uri=None, + resume=False, + ): + """ + Lower level method for starting an experiment. When use this method, one should end the experiment manually + and the status of the recorder may not be handled properly. Here is the example code: + + .. code-block:: Python + + R.start_exp(experiment_name='test', recorder_name='recorder_1') + ... # further operations + R.end_exp('FINISHED') or R.end_exp(Recorder.STATUS_S) + + + Parameters + ---------- + experiment_id : str + id of the experiment one wants to start. + experiment_name : str + the name of the experiment to be started + recorder_id : str + id of the recorder under the experiment one wants to start. + recorder_name : str + name of the recorder under the experiment one wants to start. + uri : str + the tracking uri of the experiment, where all the artifacts/metrics etc. will be stored. + The default uri are set in the qlib.config. + resume : bool + whether to resume the specific recorder with given name under the given experiment. + + Returns + ------- + An experiment instance being started. + """ + return self.exp_manager.start_exp( + experiment_id=experiment_id, + experiment_name=experiment_name, + recorder_id=recorder_id, + recorder_name=recorder_name, + uri=uri, + resume=resume, + ) + + def end_exp(self, recorder_status=Recorder.STATUS_FI): + """ + Method for ending an experiment manually. It will end the current active experiment, as well as its + active recorder with the specified `status` type. Here is the example code of the method: + + .. code-block:: Python + + R.start_exp(experiment_name='test') + ... # further operations + R.end_exp('FINISHED') or R.end_exp(Recorder.STATUS_S) + + Parameters + ---------- + status : str + The status of a recorder, which can be SCHEDULED, RUNNING, FINISHED, FAILED. + """ + self.exp_manager.end_exp(recorder_status) + + def search_records(self, experiment_ids, **kwargs): + """ + Get a pandas DataFrame of records that fit the search criteria. + + The arguments of this function are not set to be rigid, and they will be different with different implementation of + ``ExpManager`` in ``Qlib``. ``Qlib`` now provides an implementation of ``ExpManager`` with mlflow, and here is the + example code of the method with the ``MLflowExpManager``: + + .. code-block:: Python + + R.log_metrics(m=2.50, step=0) + records = R.search_records([experiment_id], order_by=["metrics.m DESC"]) + + Parameters + ---------- + experiment_ids : list + list of experiment IDs. + filter_string : str + filter query string, defaults to searching all runs. + run_view_type : int + one of enum values ACTIVE_ONLY, DELETED_ONLY, or ALL (e.g. in mlflow.entities.ViewType). + max_results : int + the maximum number of runs to put in the dataframe. + order_by : list + list of columns to order by (e.g., “metrics.rmse”). + + Returns + ------- + A pandas.DataFrame of records, where each metric, parameter, and tag + are expanded into their own columns named metrics.*, params.*, and tags.* + respectively. For records that don't have a particular metric, parameter, or tag, their + value will be (NumPy) Nan, None, or None respectively. + """ + return self.exp_manager.search_records(experiment_ids, **kwargs) + + def list_experiments(self): + """ + Method for listing all the existing experiments (except for those being deleted.) + + .. code-block:: Python + + exps = R.list_experiments() + + Returns + ------- + A dictionary (name -> experiment) of experiments information that being stored. + """ + return self.exp_manager.list_experiments() + + def list_recorders(self, experiment_id=None, experiment_name=None): + """ + Method for listing all the recorders of experiment with given id or name. + + If user doesn't provide the id or name of the experiment, this method will try to retrieve the default experiment and + list all the recorders of the default experiment. If the default experiment doesn't exist, the method will first + create the default experiment, and then create a new recorder under it. (More information about the default experiment + can be found `here <../component/recorder.html#qlib.workflow.exp.Experiment>`__). + + Here is the example code: + + .. code-block:: Python + + recorders = R.list_recorders(experiment_name='test') + + Parameters + ---------- + experiment_id : str + id of the experiment. + experiment_name : str + name of the experiment. + + Returns + ------- + A dictionary (id -> recorder) of recorder information that being stored. + """ + return self.get_exp(experiment_id=experiment_id, experiment_name=experiment_name).list_recorders() + + def get_exp( + self, *, experiment_id=None, experiment_name=None, create: bool = True, start: bool = False + ) -> Experiment: + """ + Method for retrieving an experiment with given id or name. Once the `create` argument is set to + True, if no valid experiment is found, this method will create one for you. Otherwise, it will + only retrieve a specific experiment or raise an Error. + + - If '`create`' is True: + + - If `active experiment` exists: + + - no id or name specified, return the active experiment. + + - if id or name is specified, return the specified experiment. If no such exp found, create a new experiment with given id or name. + + - If `active experiment` not exists: + + - no id or name specified, create a default experiment, and the experiment is set to be active. + + - if id or name is specified, return the specified experiment. If no such exp found, create a new experiment with given name or the default experiment. + + - Else If '`create`' is False: + + - If `active experiment` exists: + + - no id or name specified, return the active experiment. + + - if id or name is specified, return the specified experiment. If no such exp found, raise Error. + + - If `active experiment` not exists: + + - no id or name specified. If the default experiment exists, return it, otherwise, raise Error. + + - if id or name is specified, return the specified experiment. If no such exp found, raise Error. + + Here are some use cases: + + .. code-block:: Python + + # Case 1 + with R.start('test'): + exp = R.get_exp() + recorders = exp.list_recorders() + + # Case 2 + with R.start('test'): + exp = R.get_exp(experiment_name='test1') + + # Case 3 + exp = R.get_exp() -> a default experiment. + + # Case 4 + exp = R.get_exp(experiment_name='test') + + # Case 5 + exp = R.get_exp(create=False) -> the default experiment if exists. + + Parameters + ---------- + experiment_id : str + id of the experiment. + experiment_name : str + name of the experiment. + create : boolean + an argument determines whether the method will automatically create a new experiment + according to user's specification if the experiment hasn't been created before. + start : bool + when start is True, + if the experiment has not started(not activated), it will start + It is designed for R.log_params to auto start experiments + + Returns + ------- + An experiment instance with given id or name. + """ + return self.exp_manager.get_exp( + experiment_id=experiment_id, + experiment_name=experiment_name, + create=create, + start=start, + ) + + def delete_exp(self, experiment_id=None, experiment_name=None): + """ + Method for deleting the experiment with given id or name. At least one of id or name must be given, + otherwise, error will occur. + + Here is the example code: + + .. code-block:: Python + + R.delete_exp(experiment_name='test') + + Parameters + ---------- + experiment_id : str + id of the experiment. + experiment_name : str + name of the experiment. + """ + self.exp_manager.delete_exp(experiment_id, experiment_name) + + def get_uri(self): + """ + Method for retrieving the uri of current experiment manager. + + Here is the example code: + + .. code-block:: Python + + uri = R.get_uri() + + Returns + ------- + The uri of current experiment manager. + """ + return self.exp_manager.uri + + def set_uri(self, uri: Optional[Text]): + """ + Method to reset the **default** uri of current experiment manager. + + NOTE: + + - When the uri is refer to a file path, please using the absolute path instead of strings like "~/mlruns/" + The backend don't support strings like this. + """ + self.exp_manager.default_uri = uri + + @contextmanager + def uri_context(self, uri: Text): + """ + Temporarily set the exp_manager's **default_uri** to uri + + NOTE: + - Please refer to the NOTE in the `set_uri` + + Parameters + ---------- + uri : Text + the temporal uri + """ + prev_uri = self.exp_manager.default_uri + self.exp_manager.default_uri = uri + try: + yield + finally: + self.exp_manager.default_uri = prev_uri + + def get_recorder( + self, + *, + recorder_id=None, + recorder_name=None, + experiment_id=None, + experiment_name=None, + ) -> Recorder: + """ + Method for retrieving a recorder. + + - If `active recorder` exists: + + - no id or name specified, return the active recorder. + + - if id or name is specified, return the specified recorder. + + - If `active recorder` not exists: + + - no id or name specified, raise Error. + + - if id or name is specified, and the corresponding experiment_name must be given, return the specified recorder. Otherwise, raise Error. + + The recorder can be used for further process such as `save_object`, `load_object`, `log_params`, + `log_metrics`, etc. + + Here are some use cases: + + .. code-block:: Python + + # Case 1 + with R.start(experiment_name='test'): + recorder = R.get_recorder() + + # Case 2 + with R.start(experiment_name='test'): + recorder = R.get_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d') + + # Case 3 + recorder = R.get_recorder() -> Error + + # Case 4 + recorder = R.get_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d') -> Error + + # Case 5 + recorder = R.get_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d', experiment_name='test') + + + Here are some things users may concern + - Q: What recorder will it return if multiple recorder meets the query (e.g. query with experiment_name) + - A: If mlflow backend is used, then the recorder with the latest `start_time` will be returned. Because MLflow's `search_runs` function guarantee it + + Parameters + ---------- + recorder_id : str + id of the recorder. + recorder_name : str + name of the recorder. + experiment_name : str + name of the experiment. + + Returns + ------- + A recorder instance. + """ + return self.get_exp(experiment_name=experiment_name, experiment_id=experiment_id, create=False).get_recorder( + recorder_id, recorder_name, create=False, start=False + ) + + def delete_recorder(self, recorder_id=None, recorder_name=None): + """ + Method for deleting the recorders with given id or name. At least one of id or name must be given, + otherwise, error will occur. + + Here is the example code: + + .. code-block:: Python + + R.delete_recorder(recorder_id='2e7a4efd66574fa49039e00ffaefa99d') + + Parameters + ---------- + recorder_id : str + id of the experiment. + recorder_name : str + name of the experiment. + """ + self.get_exp().delete_recorder(recorder_id, recorder_name) + + def save_objects(self, local_path=None, artifact_path=None, **kwargs: Dict[Text, Any]): + """ + Method for saving objects as artifacts in the experiment to the uri. It supports either saving + from a local file/directory, or directly saving objects. User can use valid python's keywords arguments + to specify the object to be saved as well as its name (name: value). + + In summary, this API is designs for saving **objects** to **the experiments management backend path**, + 1. Qlib provide two methods to specify **objects** + - Passing in the object directly by passing with `**kwargs` (e.g. R.save_objects(trained_model=model)) + - Passing in the local path to the object, i.e. `local_path` parameter. + 2. `artifact_path` represents the **the experiments management backend path** + + - If `active recorder` exists: it will save the objects through the active recorder. + - If `active recorder` not exists: the system will create a default experiment, and a new recorder and save objects under it. + + .. note:: + + If one wants to save objects with a specific recorder. It is recommended to first get the specific recorder through `get_recorder` API and use the recorder the save objects. The supported arguments are the same as this method. + + Here are some use cases: + + .. code-block:: Python + + # Case 1 + with R.start(experiment_name='test'): + pred = model.predict(dataset) + R.save_objects(**{"pred.pkl": pred}, artifact_path='prediction') + rid = R.get_recorder().id + ... + R.get_recorder(recorder_id=rid).load_object("prediction/pred.pkl") # after saving objects, you can load the previous object with this api + + # Case 2 + with R.start(experiment_name='test'): + R.save_objects(local_path='results/pred.pkl', artifact_path="prediction") + rid = R.get_recorder().id + ... + R.get_recorder(recorder_id=rid).load_object("prediction/pred.pkl") # after saving objects, you can load the previous object with this api + + + Parameters + ---------- + local_path : str + if provided, them save the file or directory to the artifact URI. + artifact_path : str + the relative path for the artifact to be stored in the URI. + **kwargs: Dict[Text, Any] + the object to be saved. + For example, `{"pred.pkl": pred}` + """ + if local_path is not None and len(kwargs) > 0: + raise ValueError( + "You can choose only one of `local_path`(save the files in a path) or `kwargs`(pass in the objects directly)" + ) + self.get_exp().get_recorder(start=True).save_objects(local_path, artifact_path, **kwargs) + + def load_object(self, name: Text): + """ + Method for loading an object from artifacts in the experiment in the uri. + """ + return self.get_exp().get_recorder(start=True).load_object(name) + + def log_params(self, **kwargs): + """ + Method for logging parameters during an experiment. In addition to using ``R``, one can also log to a specific recorder after getting it with `get_recorder` API. + + - If `active recorder` exists: it will log parameters through the active recorder. + - If `active recorder` not exists: the system will create a default experiment as well as a new recorder, and log parameters under it. + + Here are some use cases: + + .. code-block:: Python + + # Case 1 + with R.start('test'): + R.log_params(learning_rate=0.01) + + # Case 2 + R.log_params(learning_rate=0.01) + + Parameters + ---------- + keyword argument: + name1=value1, name2=value2, ... + """ + self.get_exp(start=True).get_recorder(start=True).log_params(**kwargs) + + def log_metrics(self, step=None, **kwargs): + """ + Method for logging metrics during an experiment. In addition to using ``R``, one can also log to a specific recorder after getting it with `get_recorder` API. + + - If `active recorder` exists: it will log metrics through the active recorder. + - If `active recorder` not exists: the system will create a default experiment as well as a new recorder, and log metrics under it. + + Here are some use cases: + + .. code-block:: Python + + # Case 1 + with R.start('test'): + R.log_metrics(train_loss=0.33, step=1) + + # Case 2 + R.log_metrics(train_loss=0.33, step=1) + + Parameters + ---------- + keyword argument: + name1=value1, name2=value2, ... + """ + self.get_exp(start=True).get_recorder(start=True).log_metrics(step, **kwargs) + + def log_artifact(self, local_path: str, artifact_path: Optional[str] = None): + """ + Log a local file or directory as an artifact of the currently active run + + - If `active recorder` exists: it will set tags through the active recorder. + - If `active recorder` not exists: the system will create a default experiment as well as a new recorder, and set the tags under it. + + Parameters + ---------- + local_path : str + Path to the file to write. + artifact_path : Optional[str] + If provided, the directory in ``artifact_uri`` to write to. + """ + self.get_exp(start=True).get_recorder(start=True).log_artifact(local_path, artifact_path) + + def download_artifact(self, path: str, dst_path: Optional[str] = None) -> str: + """ + Download an artifact file or directory from a run to a local directory if applicable, + and return a local path for it. + + Parameters + ---------- + path : str + Relative source path to the desired artifact. + dst_path : Optional[str] + Absolute path of the local filesystem destination directory to which to + download the specified artifacts. This directory must already exist. + If unspecified, the artifacts will either be downloaded to a new + uniquely-named directory on the local filesystem. + + Returns + ------- + str + Local path of desired artifact. + """ + self.get_exp(start=True).get_recorder(start=True).download_artifact(path, dst_path) + + def set_tags(self, **kwargs): + """ + Method for setting tags for a recorder. In addition to using ``R``, one can also set the tag to a specific recorder after getting it with `get_recorder` API. + + - If `active recorder` exists: it will set tags through the active recorder. + - If `active recorder` not exists: the system will create a default experiment as well as a new recorder, and set the tags under it. + + Here are some use cases: + + .. code-block:: Python + + # Case 1 + with R.start('test'): + R.set_tags(release_version="2.2.0") + + # Case 2 + R.set_tags(release_version="2.2.0") + + Parameters + ---------- + keyword argument: + name1=value1, name2=value2, ... + """ + self.get_exp(start=True).get_recorder(start=True).set_tags(**kwargs) + + +class RecorderWrapper(Wrapper): + """ + Wrapper class for QlibRecorder, which detects whether users reinitialize qlib when already starting an experiment. + """ + + def register(self, provider): + if self._provider is not None: + expm = getattr(self._provider, "exp_manager") + if expm.active_experiment is not None: + raise RecorderInitializationError( + "Please don't reinitialize Qlib if QlibRecorder is already activated. Otherwise, the experiment stored location will be modified." + ) + self._provider = provider + + +import sys + +if sys.version_info >= (3, 9): + from typing import Annotated + + QlibRecorderWrapper = Annotated[QlibRecorder, RecorderWrapper] +else: + QlibRecorderWrapper = QlibRecorder + +# global record +R: QlibRecorderWrapper = RecorderWrapper() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/exp.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/exp.py new file mode 100644 index 0000000000000000000000000000000000000000..ae165ef1f87ee547d028e521c6d9299ba3ccc718 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/exp.py @@ -0,0 +1,379 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from typing import Dict, List, Union +from qlib.typehint import Literal +import mlflow +from mlflow.entities import ViewType +from mlflow.exceptions import MlflowException +from .recorder import Recorder, MLflowRecorder +from ..log import get_module_logger + +logger = get_module_logger("workflow") + + +class Experiment: + """ + This is the `Experiment` class for each experiment being run. The API is designed similar to mlflow. + (The link: https://mlflow.org/docs/latest/python_api/mlflow.html) + """ + + def __init__(self, id, name): + self.id = id + self.name = name + self.active_recorder = None # only one recorder can run each time + self._default_rec_name = "abstract_recorder" + + def __repr__(self): + return "{name}(id={id}, info={info})".format(name=self.__class__.__name__, id=self.id, info=self.info) + + def __str__(self): + return str(self.info) + + @property + def info(self): + recorders = self.list_recorders() + output = dict() + output["class"] = "Experiment" + output["id"] = self.id + output["name"] = self.name + output["active_recorder"] = self.active_recorder.id if self.active_recorder is not None else None + output["recorders"] = list(recorders.keys()) + return output + + def start(self, *, recorder_id=None, recorder_name=None, resume=False): + """ + Start the experiment and set it to be active. This method will also start a new recorder. + + Parameters + ---------- + recorder_id : str + the id of the recorder to be created. + recorder_name : str + the name of the recorder to be created. + resume : bool + whether to resume the first recorder + + Returns + ------- + An active recorder. + """ + raise NotImplementedError(f"Please implement the `start` method.") + + def end(self, recorder_status=Recorder.STATUS_S): + """ + End the experiment. + + Parameters + ---------- + recorder_status : str + the status the recorder to be set with when ending (SCHEDULED, RUNNING, FINISHED, FAILED). + """ + raise NotImplementedError(f"Please implement the `end` method.") + + def create_recorder(self, recorder_name=None): + """ + Create a recorder for each experiment. + + Parameters + ---------- + recorder_name : str + the name of the recorder to be created. + + Returns + ------- + A recorder object. + """ + raise NotImplementedError(f"Please implement the `create_recorder` method.") + + def search_records(self, **kwargs): + """ + Get a pandas DataFrame of records that fit the search criteria of the experiment. + Inputs are the search criteria user want to apply. + + Returns + ------- + A pandas.DataFrame of records, where each metric, parameter, and tag + are expanded into their own columns named metrics.*, params.*, and tags.* + respectively. For records that don't have a particular metric, parameter, or tag, their + value will be (NumPy) Nan, None, or None respectively. + """ + raise NotImplementedError(f"Please implement the `search_records` method.") + + def delete_recorder(self, recorder_id): + """ + Create a recorder for each experiment. + + Parameters + ---------- + recorder_id : str + the id of the recorder to be deleted. + """ + raise NotImplementedError(f"Please implement the `delete_recorder` method.") + + def get_recorder(self, recorder_id=None, recorder_name=None, create: bool = True, start: bool = False) -> Recorder: + """ + Retrieve a Recorder for user. When user specify recorder id and name, the method will try to return the + specific recorder. When user does not provide recorder id or name, the method will try to return the current + active recorder. The `create` argument determines whether the method will automatically create a new recorder + according to user's specification if the recorder hasn't been created before. + + * If `create` is True: + + * If `active recorder` exists: + + * no id or name specified, return the active recorder. + * if id or name is specified, return the specified recorder. If no such exp found, create a new recorder with given id or name. If `start` is set to be True, the recorder is set to be active. + + * If `active recorder` not exists: + + * no id or name specified, create a new recorder. + * if id or name is specified, return the specified experiment. If no such exp found, create a new recorder with given id or name. If `start` is set to be True, the recorder is set to be active. + + * Else If `create` is False: + + * If `active recorder` exists: + + * no id or name specified, return the active recorder. + * if id or name is specified, return the specified recorder. If no such exp found, raise Error. + + * If `active recorder` not exists: + + * no id or name specified, raise Error. + * if id or name is specified, return the specified recorder. If no such exp found, raise Error. + + Parameters + ---------- + recorder_id : str + the id of the recorder to be deleted. + recorder_name : str + the name of the recorder to be deleted. + create : boolean + create the recorder if it hasn't been created before. + start : boolean + start the new recorder if one is **created**. + + Returns + ------- + A recorder object. + """ + # special case of getting the recorder + if recorder_id is None and recorder_name is None: + if self.active_recorder is not None: + return self.active_recorder + recorder_name = self._default_rec_name + if create: + recorder, is_new = self._get_or_create_rec(recorder_id=recorder_id, recorder_name=recorder_name) + else: + recorder, is_new = ( + self._get_recorder(recorder_id=recorder_id, recorder_name=recorder_name), + False, + ) + if is_new and start: + self.active_recorder = recorder + # start the recorder + self.active_recorder.start_run() + return recorder + + def _get_or_create_rec(self, recorder_id=None, recorder_name=None) -> (object, bool): + """ + Method for getting or creating a recorder. It will try to first get a valid recorder, if exception occurs, it will + automatically create a new recorder based on the given id and name. + """ + try: + if recorder_id is None and recorder_name is None: + recorder_name = self._default_rec_name + return ( + self._get_recorder(recorder_id=recorder_id, recorder_name=recorder_name), + False, + ) + except ValueError: + if recorder_name is None: + recorder_name = self._default_rec_name + logger.info(f"No valid recorder found. Create a new recorder with name {recorder_name}.") + return self.create_recorder(recorder_name), True + + def _get_recorder(self, recorder_id=None, recorder_name=None): + """ + Get specific recorder by name or id. If it does not exist, raise ValueError + + Parameters + ---------- + recorder_id : + The id of recorder + recorder_name : + The name of recorder + + Returns + ------- + Recorder: + The searched recorder + + Raises + ------ + ValueError + """ + raise NotImplementedError(f"Please implement the `_get_recorder` method") + + RT_D = "dict" # return type dict + RT_L = "list" # return type list + + def list_recorders( + self, rtype: Literal["dict", "list"] = RT_D, **flt_kwargs + ) -> Union[List[Recorder], Dict[str, Recorder]]: + """ + List all the existing recorders of this experiment. Please first get the experiment instance before calling this method. + If user want to use the method `R.list_recorders()`, please refer to the related API document in `QlibRecorder`. + + flt_kwargs : dict + filter recorders by conditions + e.g. list_recorders(status=Recorder.STATUS_FI) + + Returns + ------- + The return type depends on `rtype` + if `rtype` == "dict": + A dictionary (id -> recorder) of recorder information that being stored. + elif `rtype` == "list": + A list of Recorder. + """ + raise NotImplementedError(f"Please implement the `list_recorders` method.") + + +class MLflowExperiment(Experiment): + """ + Use mlflow to implement Experiment. + """ + + def __init__(self, id, name, uri): + super(MLflowExperiment, self).__init__(id, name) + self._uri = uri + self._default_rec_name = "mlflow_recorder" + self._client = mlflow.tracking.MlflowClient(tracking_uri=self._uri) + + def __repr__(self): + return "{name}(id={id}, info={info})".format(name=self.__class__.__name__, id=self.id, info=self.info) + + def start(self, *, recorder_id=None, recorder_name=None, resume=False): + logger.info(f"Experiment {self.id} starts running ...") + # Get or create recorder + if recorder_name is None: + recorder_name = self._default_rec_name + # resume the recorder + if resume: + recorder, _ = self._get_or_create_rec(recorder_id=recorder_id, recorder_name=recorder_name) + # create a new recorder + else: + recorder = self.create_recorder(recorder_name) + # Set up active recorder + self.active_recorder = recorder + # Start the recorder + self.active_recorder.start_run() + + return self.active_recorder + + def end(self, recorder_status=Recorder.STATUS_S): + if self.active_recorder is not None: + self.active_recorder.end_run(recorder_status) + self.active_recorder = None + + def create_recorder(self, recorder_name=None): + if recorder_name is None: + recorder_name = self._default_rec_name + recorder = MLflowRecorder(self.id, self._uri, recorder_name) + + return recorder + + def _get_recorder(self, recorder_id=None, recorder_name=None): + """ + Method for getting or creating a recorder. It will try to first get a valid recorder, if exception occurs, it will + raise errors. + + Quoting docs of search_runs from MLflow + > The default ordering is to sort by start_time DESC, then run_id. + """ + assert ( + recorder_id is not None or recorder_name is not None + ), "Please input at least one of recorder id or name before retrieving recorder." + if recorder_id is not None: + try: + run = self._client.get_run(recorder_id) + recorder = MLflowRecorder(self.id, self._uri, mlflow_run=run) + return recorder + except MlflowException as mlflow_exp: + raise ValueError( + "No valid recorder has been found, please make sure the input recorder id is correct." + ) from mlflow_exp + elif recorder_name is not None: + logger.warning( + f"Please make sure the recorder name {recorder_name} is unique, we will only return the latest recorder if there exist several matched the given name." + ) + recorders = self.list_recorders() + for rid in recorders: + if recorders[rid].name == recorder_name: + return recorders[rid] + raise ValueError("No valid recorder has been found, please make sure the input recorder name is correct.") + + def search_records(self, **kwargs): + filter_string = "" if kwargs.get("filter_string") is None else kwargs.get("filter_string") + run_view_type = 1 if kwargs.get("run_view_type") is None else kwargs.get("run_view_type") + max_results = 100000 if kwargs.get("max_results") is None else kwargs.get("max_results") + order_by = kwargs.get("order_by") + + return self._client.search_runs([self.id], filter_string, run_view_type, max_results, order_by) + + def delete_recorder(self, recorder_id=None, recorder_name=None): + assert ( + recorder_id is not None or recorder_name is not None + ), "Please input a valid recorder id or name before deleting." + try: + if recorder_id is not None: + self._client.delete_run(recorder_id) + else: + recorder = self._get_recorder(recorder_name=recorder_name) + self._client.delete_run(recorder.id) + except MlflowException as e: + raise ValueError( + f"Error: {e}. Something went wrong when deleting recorder. Please check if the name/id of the recorder is correct." + ) from e + + UNLIMITED = 50000 # FIXME: Mlflow can only list 50000 records at most!!!!!!! + + def list_recorders( + self, + rtype: Literal["dict", "list"] = Experiment.RT_D, + max_results: int = UNLIMITED, + status: Union[str, None] = None, + filter_string: str = "", + ): + """ + Quoting docs of search_runs + > The default ordering is to sort by start_time DESC, then run_id. + + Parameters + ---------- + max_results : int + the number limitation of the results' + status : str + the criteria based on status to filter results. + `None` indicates no filtering. + filter_string : str + mlflow supported filter string like 'params."my_param"="a" and tags."my_tag"="b"', use this will help to reduce too much run number. + """ + runs = self._client.search_runs( + self.id, run_view_type=ViewType.ACTIVE_ONLY, max_results=max_results, filter_string=filter_string + ) + rids = [] + recorders = [] + for i, n in enumerate(runs): + recorder = MLflowRecorder(self.id, self._uri, mlflow_run=n) + if status is None or recorder.status == status: + rids.append(n.info.run_id) + recorders.append(recorder) + + if rtype == Experiment.RT_D: + return dict(zip(rids, recorders)) + elif rtype == Experiment.RT_L: + return recorders + else: + raise NotImplementedError(f"This type of input is not supported") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/expm.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/expm.py new file mode 100644 index 0000000000000000000000000000000000000000..cb48d156acf5e5a3c0fd953d351f6afe45805bfc --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/expm.py @@ -0,0 +1,433 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from urllib.parse import urlparse +import mlflow +from filelock import FileLock +from mlflow.exceptions import MlflowException, RESOURCE_ALREADY_EXISTS, ErrorCode +from mlflow.entities import ViewType +import os +from typing import Optional, Text +from pathlib import Path + +from .exp import MLflowExperiment, Experiment +from ..config import C +from .recorder import Recorder +from ..log import get_module_logger +from ..utils.exceptions import ExpAlreadyExistError + +logger = get_module_logger("workflow") + + +class ExpManager: + """ + This is the `ExpManager` class for managing experiments. The API is designed similar to mlflow. + (The link: https://mlflow.org/docs/latest/python_api/mlflow.html) + + The `ExpManager` is expected to be a singleton (btw, we can have multiple `Experiment`s with different uri. user can get different experiments from different uri, and then compare records of them). Global Config (i.e. `C`) is also a singleton. + + So we try to align them together. They share the same variable, which is called **default uri**. Please refer to `ExpManager.default_uri` for details of variable sharing. + + When the user starts an experiment, the user may want to set the uri to a specific uri (it will override **default uri** during this period), and then unset the **specific uri** and fallback to the **default uri**. `ExpManager._active_exp_uri` is that **specific uri**. + """ + + active_experiment: Optional[Experiment] + + def __init__(self, uri: Text, default_exp_name: Optional[Text]): + self.default_uri = uri + self._active_exp_uri = None # No active experiments. So it is set to None + self._default_exp_name = default_exp_name + self.active_experiment = None # only one experiment can be active each time + logger.debug(f"experiment manager uri is at {self.uri}") + + def __repr__(self): + return "{name}(uri={uri})".format(name=self.__class__.__name__, uri=self.uri) + + def start_exp( + self, + *, + experiment_id: Optional[Text] = None, + experiment_name: Optional[Text] = None, + recorder_id: Optional[Text] = None, + recorder_name: Optional[Text] = None, + uri: Optional[Text] = None, + resume: bool = False, + **kwargs, + ) -> Experiment: + """ + Start an experiment. This method includes first get_or_create an experiment, and then + set it to be active. + + Maintaining `_active_exp_uri` is included in start_exp, remaining implementation should be included in _end_exp in subclass + + Parameters + ---------- + experiment_id : str + id of the active experiment. + experiment_name : str + name of the active experiment. + recorder_id : str + id of the recorder to be started. + recorder_name : str + name of the recorder to be started. + uri : str + the current tracking URI. + resume : boolean + whether to resume the experiment and recorder. + + Returns + ------- + An active experiment. + """ + self._active_exp_uri = uri + # The subclass may set the underlying uri back. + # So setting `_active_exp_uri` come before `_start_exp` + return self._start_exp( + experiment_id=experiment_id, + experiment_name=experiment_name, + recorder_id=recorder_id, + recorder_name=recorder_name, + resume=resume, + **kwargs, + ) + + def _start_exp(self, *args, **kwargs) -> Experiment: + """Please refer to the doc of `start_exp`""" + raise NotImplementedError(f"Please implement the `start_exp` method.") + + def end_exp(self, recorder_status: Text = Recorder.STATUS_S, **kwargs): + """ + End an active experiment. + + Maintaining `_active_exp_uri` is included in end_exp, remaining implementation should be included in _end_exp in subclass + + Parameters + ---------- + experiment_name : str + name of the active experiment. + recorder_status : str + the status of the active recorder of the experiment. + """ + self._active_exp_uri = None + # The subclass may set the underlying uri back. + # So setting `_active_exp_uri` come before `_end_exp` + self._end_exp(recorder_status=recorder_status, **kwargs) + + def _end_exp(self, recorder_status: Text = Recorder.STATUS_S, **kwargs): + raise NotImplementedError(f"Please implement the `end_exp` method.") + + def create_exp(self, experiment_name: Optional[Text] = None): + """ + Create an experiment. + + Parameters + ---------- + experiment_name : str + the experiment name, which must be unique. + + Returns + ------- + An experiment object. + + Raise + ----- + ExpAlreadyExistError + """ + raise NotImplementedError(f"Please implement the `create_exp` method.") + + def search_records(self, experiment_ids=None, **kwargs): + """ + Get a pandas DataFrame of records that fit the search criteria of the experiment. + Inputs are the search criteria user want to apply. + + Returns + ------- + A pandas.DataFrame of records, where each metric, parameter, and tag + are expanded into their own columns named metrics.*, params.*, and tags.* + respectively. For records that don't have a particular metric, parameter, or tag, their + value will be (NumPy) Nan, None, or None respectively. + """ + raise NotImplementedError(f"Please implement the `search_records` method.") + + def get_exp(self, *, experiment_id=None, experiment_name=None, create: bool = True, start: bool = False): + """ + Retrieve an experiment. This method includes getting an active experiment, and get_or_create a specific experiment. + + When user specify experiment id and name, the method will try to return the specific experiment. + When user does not provide recorder id or name, the method will try to return the current active experiment. + The `create` argument determines whether the method will automatically create a new experiment according + to user's specification if the experiment hasn't been created before. + + * If `create` is True: + + * If `active experiment` exists: + + * no id or name specified, return the active experiment. + * if id or name is specified, return the specified experiment. If no such exp found, create a new experiment with given id or name. If `start` is set to be True, the experiment is set to be active. + + * If `active experiment` not exists: + + * no id or name specified, create a default experiment. + * if id or name is specified, return the specified experiment. If no such exp found, create a new experiment with given id or name. If `start` is set to be True, the experiment is set to be active. + + * Else If `create` is False: + + * If `active experiment` exists: + + * no id or name specified, return the active experiment. + * if id or name is specified, return the specified experiment. If no such exp found, raise Error. + + * If `active experiment` not exists: + + * no id or name specified. If the default experiment exists, return it, otherwise, raise Error. + * if id or name is specified, return the specified experiment. If no such exp found, raise Error. + + Parameters + ---------- + experiment_id : str + id of the experiment to return. + experiment_name : str + name of the experiment to return. + create : boolean + create the experiment it if hasn't been created before. + start : boolean + start the new experiment if one is created. + + Returns + ------- + An experiment object. + """ + # special case of getting experiment + if experiment_id is None and experiment_name is None: + if self.active_experiment is not None: + return self.active_experiment + # User don't want get active code now. + experiment_name = self._default_exp_name + + if create: + exp, _ = self._get_or_create_exp(experiment_id=experiment_id, experiment_name=experiment_name) + else: + exp = self._get_exp(experiment_id=experiment_id, experiment_name=experiment_name) + if self.active_experiment is None and start: + self.active_experiment = exp + # start the recorder + self.active_experiment.start() + return exp + + def _get_or_create_exp(self, experiment_id=None, experiment_name=None) -> (object, bool): + """ + Method for getting or creating an experiment. It will try to first get a valid experiment, if exception occurs, it will + automatically create a new experiment based on the given id and name. + """ + try: + return ( + self._get_exp(experiment_id=experiment_id, experiment_name=experiment_name), + False, + ) + except ValueError: + if experiment_name is None: + experiment_name = self._default_exp_name + logger.warning(f"No valid experiment found. Create a new experiment with name {experiment_name}.") + + # NOTE: mlflow doesn't consider the lock for recording multiple runs + # So we supported it in the interface wrapper + pr = urlparse(self.uri) + if pr.scheme == "file": + with FileLock(Path(os.path.join(pr.netloc, pr.path.lstrip("/"), "filelock"))): # pylint: disable=E0110 + return self.create_exp(experiment_name), True + # NOTE: for other schemes like http, we double check to avoid create exp conflicts + try: + return self.create_exp(experiment_name), True + except ExpAlreadyExistError: + return ( + self._get_exp(experiment_id=experiment_id, experiment_name=experiment_name), + False, + ) + + def _get_exp(self, experiment_id=None, experiment_name=None) -> Experiment: + """ + Get specific experiment by name or id. If it does not exist, raise ValueError. + + Parameters + ---------- + experiment_id : + The id of experiment + experiment_name : + The name of experiment + + Returns + ------- + Experiment: + The searched experiment + + Raises + ------ + ValueError + """ + raise NotImplementedError(f"Please implement the `_get_exp` method") + + def delete_exp(self, experiment_id=None, experiment_name=None): + """ + Delete an experiment. + + Parameters + ---------- + experiment_id : str + the experiment id. + experiment_name : str + the experiment name. + """ + raise NotImplementedError(f"Please implement the `delete_exp` method.") + + @property + def default_uri(self): + """ + Get the default tracking URI from qlib.config.C + """ + if "kwargs" not in C.exp_manager or "uri" not in C.exp_manager["kwargs"]: + raise ValueError("The default URI is not set in qlib.config.C") + return C.exp_manager["kwargs"]["uri"] + + @default_uri.setter + def default_uri(self, value): + C.exp_manager.setdefault("kwargs", {})["uri"] = value + + @property + def uri(self): + """ + Get the default tracking URI or current URI. + + Returns + ------- + The tracking URI string. + """ + return self._active_exp_uri or self.default_uri + + def list_experiments(self): + """ + List all the existing experiments. + + Returns + ------- + A dictionary (name -> experiment) of experiments information that being stored. + """ + raise NotImplementedError(f"Please implement the `list_experiments` method.") + + +class MLflowExpManager(ExpManager): + """ + Use mlflow to implement ExpManager. + """ + + @property + def client(self): + # Please refer to `tests/dependency_tests/test_mlflow.py::MLflowTest::test_creating_client` + # The test ensure the speed of create a new client + return mlflow.tracking.MlflowClient(tracking_uri=self.uri) + + def _start_exp( + self, + *, + experiment_id: Optional[Text] = None, + experiment_name: Optional[Text] = None, + recorder_id: Optional[Text] = None, + recorder_name: Optional[Text] = None, + resume: bool = False, + ): + # Create experiment + if experiment_name is None: + experiment_name = self._default_exp_name + experiment, _ = self._get_or_create_exp(experiment_id=experiment_id, experiment_name=experiment_name) + # Set up active experiment + self.active_experiment = experiment + # Start the experiment + self.active_experiment.start(recorder_id=recorder_id, recorder_name=recorder_name, resume=resume) + + return self.active_experiment + + def _end_exp(self, recorder_status: Text = Recorder.STATUS_S): + if self.active_experiment is not None: + self.active_experiment.end(recorder_status) + self.active_experiment = None + + def create_exp(self, experiment_name: Optional[Text] = None): + assert experiment_name is not None + # init experiment + try: + experiment_id = self.client.create_experiment(experiment_name) + except MlflowException as e: + if e.error_code == ErrorCode.Name(RESOURCE_ALREADY_EXISTS): + raise ExpAlreadyExistError() from e + raise e + + return MLflowExperiment(experiment_id, experiment_name, self.uri) + + def _get_exp(self, experiment_id=None, experiment_name=None): + """ + Method for getting or creating an experiment. It will try to first get a valid experiment, if exception occurs, it will + raise errors. + """ + assert ( + experiment_id is not None or experiment_name is not None + ), "Please input at least one of experiment/recorder id or name before retrieving experiment/recorder." + if experiment_id is not None: + try: + # NOTE: the mlflow's experiment_id must be str type... + # https://www.mlflow.org/docs/latest/python_api/mlflow.tracking.html#mlflow.tracking.MlflowClient.get_experiment + exp = self.client.get_experiment(experiment_id) + if exp.lifecycle_stage.upper() == "DELETED": + raise MlflowException("No valid experiment has been found.") + experiment = MLflowExperiment(exp.experiment_id, exp.name, self.uri) + return experiment + except MlflowException as e: + raise ValueError( + "No valid experiment has been found, please make sure the input experiment id is correct." + ) from e + elif experiment_name is not None: + try: + exp = self.client.get_experiment_by_name(experiment_name) + if exp is None or exp.lifecycle_stage.upper() == "DELETED": + raise MlflowException("No valid experiment has been found.") + experiment = MLflowExperiment(exp.experiment_id, experiment_name, self.uri) + return experiment + except MlflowException as e: + raise ValueError( + "No valid experiment has been found, please make sure the input experiment name is correct." + ) from e + + def search_records(self, experiment_ids=None, **kwargs): + filter_string = "" if kwargs.get("filter_string") is None else kwargs.get("filter_string") + run_view_type = 1 if kwargs.get("run_view_type") is None else kwargs.get("run_view_type") + max_results = 100000 if kwargs.get("max_results") is None else kwargs.get("max_results") + order_by = kwargs.get("order_by") + return self.client.search_runs(experiment_ids, filter_string, run_view_type, max_results, order_by) + + def delete_exp(self, experiment_id=None, experiment_name=None): + assert ( + experiment_id is not None or experiment_name is not None + ), "Please input a valid experiment id or name before deleting." + try: + if experiment_id is not None: + self.client.delete_experiment(experiment_id) + else: + experiment = self.client.get_experiment_by_name(experiment_name) + if experiment is None: + raise MlflowException("No valid experiment has been found.") + self.client.delete_experiment(experiment.experiment_id) + except MlflowException as e: + raise ValueError( + f"Error: {e}. Something went wrong when deleting experiment. Please check if the name/id of the experiment is correct." + ) from e + + def list_experiments(self): + # retrieve all the existing experiments + mlflow_version = int(mlflow.__version__.split(".", maxsplit=1)[0]) + if mlflow_version >= 2: + exps = self.client.search_experiments(view_type=ViewType.ACTIVE_ONLY) + else: + exps = self.client.list_experiments(view_type=ViewType.ACTIVE_ONLY) # pylint: disable=E1101 + experiments = dict() + for exp in exps: + experiment = MLflowExperiment(exp.experiment_id, exp.name, self.uri) + experiments[exp.name] = experiment + return experiments diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/manager.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..09e96d444f293709a371385482ce76cdf563c646 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/manager.py @@ -0,0 +1,382 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +OnlineManager can manage a set of `Online Strategy <#Online Strategy>`_ and run them dynamically. + +With the change of time, the decisive models will be also changed. In this module, we call those contributing models `online` models. +In every routine(such as every day or every minute), the `online` models may be changed and the prediction of them needs to be updated. +So this module provides a series of methods to control this process. + +This module also provides a method to simulate `Online Strategy <#Online Strategy>`_ in history. +Which means you can verify your strategy or find a better one. + +There are 4 total situations for using different trainers in different situations: + + + +========================= =================================================================================== +Situations Description +========================= =================================================================================== +Online + Trainer When you want to do a REAL routine, the Trainer will help you train the models. It + will train models task by task and strategy by strategy. + +Online + DelayTrainer DelayTrainer will skip concrete training until all tasks have been prepared by + different strategies. It makes users can parallelly train all tasks at the end of + `routine` or `first_train`. Otherwise, these functions will get stuck when each + strategy prepare tasks. + +Simulation + Trainer It will behave in the same way as `Online + Trainer`. The only difference is that it + is for simulation/backtesting instead of online trading + +Simulation + DelayTrainer When your models don't have any temporal dependence, you can use DelayTrainer + for the ability to multitasking. It means all tasks in all routines + can be REAL trained at the end of simulating. The signals will be prepared well at + different time segments (based on whether or not any new model is online). +========================= =================================================================================== + +Here is some pseudo code that demonstrate the workflow of each situation + +For simplicity + - Only one strategy is used in the strategy + - `update_online_pred` is only called in the online mode and is ignored + +1) `Online + Trainer` + +.. code-block:: python + + tasks = first_train() + models = trainer.train(tasks) + trainer.end_train(models) + for day in online_trading_days: + # OnlineManager.routine + models = trainer.train(strategy.prepare_tasks()) # for each strategy + strategy.prepare_online_models(models) # for each strategy + + trainer.end_train(models) + prepare_signals() # prepare trading signals daily + + +`Online + DelayTrainer`: the workflow is the same as `Online + Trainer`. + + +2) `Simulation + DelayTrainer` + +.. code-block:: python + + # simulate + tasks = first_train() + models = trainer.train(tasks) + for day in historical_calendars: + # OnlineManager.routine + models = trainer.train(strategy.prepare_tasks()) # for each strategy + strategy.prepare_online_models(models) # for each strategy + # delay_prepare() + # FIXME: Currently the delay_prepare is not implemented in a proper way. + trainer.end_train() + prepare_signals() + + +# Can we simplify current workflow? + +- Can reduce the number of state of tasks? + + - For each task, we have three phases (i.e. task, partly trained task, final trained task) +""" + +import logging +from typing import Callable, List, Union + +import pandas as pd +from qlib import get_module_logger +from qlib.data.data import D +from qlib.log import set_global_logger_level +from qlib.model.ens.ensemble import AverageEnsemble +from qlib.model.trainer import Trainer, TrainerR +from qlib.utils.serial import Serializable +from qlib.workflow.online.strategy import OnlineStrategy +from qlib.workflow.task.collect import MergeCollector + + +class OnlineManager(Serializable): + """ + OnlineManager can manage online models with `Online Strategy <#Online Strategy>`_. + It also provides a history recording of which models are online at what time. + """ + + STATUS_SIMULATING = "simulating" # when calling `simulate` + STATUS_ONLINE = "online" # the normal status. It is used when online trading + + def __init__( + self, + strategies: Union[OnlineStrategy, List[OnlineStrategy]], + trainer: Trainer = None, + begin_time: Union[str, pd.Timestamp] = None, + freq="day", + ): + """ + Init OnlineManager. + One OnlineManager must have at least one OnlineStrategy. + + Args: + strategies (Union[OnlineStrategy, List[OnlineStrategy]]): an instance of OnlineStrategy or a list of OnlineStrategy + begin_time (Union[str,pd.Timestamp], optional): the OnlineManager will begin at this time. Defaults to None for using the latest date. + trainer (qlib.model.trainer.Trainer): the trainer to train task. None for using TrainerR. + freq (str, optional): data frequency. Defaults to "day". + """ + self.logger = get_module_logger(self.__class__.__name__) + if not isinstance(strategies, list): + strategies = [strategies] + self.strategies = strategies + self.freq = freq + if begin_time is None: + begin_time = D.calendar(freq=self.freq).max() + self.begin_time = pd.Timestamp(begin_time) + self.cur_time = self.begin_time + # OnlineManager will recorder the history of online models, which is a dict like {pd.Timestamp, {strategy, [online_models]}}. + # It records the online servnig models of each strategy for each day. + self.history = {} + if trainer is None: + trainer = TrainerR() + self.trainer = trainer + self.signals = None + self.status = self.STATUS_ONLINE + + def _postpone_action(self): + """ + Should the workflow to postpone the following actions to the end (in delay_prepare) + - trainer.end_train + - prepare_signals + + Postpone these actions is to support simulating/backtest online strategies without time dependencies. + All the actions can be done parallelly at the end. + """ + return self.status == self.STATUS_SIMULATING and self.trainer.is_delay() + + def first_train(self, strategies: List[OnlineStrategy] = None, model_kwargs: dict = {}): + """ + Get tasks from every strategy's first_tasks method and train them. + If using DelayTrainer, it can finish training all together after every strategy's first_tasks. + + Args: + strategies (List[OnlineStrategy]): the strategies list (need this param when adding strategies). None for use default strategies. + model_kwargs (dict): the params for `prepare_online_models` + """ + if strategies is None: + strategies = self.strategies + + models_list = [] + for strategy in strategies: + self.logger.info(f"Strategy `{strategy.name_id}` begins first training...") + tasks = strategy.first_tasks() + models = self.trainer.train(tasks, experiment_name=strategy.name_id) + models_list.append(models) + self.logger.info(f"Finished training {len(models)} models.") + # FIXME: Train multiple online models at `first_train` will result in getting too much online models at the + # start. + online_models = strategy.prepare_online_models(models, **model_kwargs) + self.history.setdefault(self.cur_time, {})[strategy] = online_models + + if not self._postpone_action(): + for strategy, models in zip(strategies, models_list): + models = self.trainer.end_train(models, experiment_name=strategy.name_id) + + def routine( + self, + cur_time: Union[str, pd.Timestamp] = None, + task_kwargs: dict = {}, + model_kwargs: dict = {}, + signal_kwargs: dict = {}, + ): + """ + Typical update process for every strategy and record the online history. + + The typical update process after a routine, such as day by day or month by month. + The process is: Update predictions -> Prepare tasks -> Prepare online models -> Prepare signals. + + If using DelayTrainer, it can finish training all together after every strategy's prepare_tasks. + + Args: + cur_time (Union[str,pd.Timestamp], optional): run routine method in this time. Defaults to None. + task_kwargs (dict): the params for `prepare_tasks` + model_kwargs (dict): the params for `prepare_online_models` + signal_kwargs (dict): the params for `prepare_signals` + """ + if cur_time is None: + cur_time = D.calendar(freq=self.freq).max() + self.cur_time = pd.Timestamp(cur_time) # None for latest date + + models_list = [] + for strategy in self.strategies: + self.logger.info(f"Strategy `{strategy.name_id}` begins routine...") + + tasks = strategy.prepare_tasks(self.cur_time, **task_kwargs) + models = self.trainer.train(tasks, experiment_name=strategy.name_id) + models_list.append(models) + self.logger.info(f"Finished training {len(models)} models.") + online_models = strategy.prepare_online_models(models, **model_kwargs) + self.history.setdefault(self.cur_time, {})[strategy] = online_models + + # The online model may changes in the above processes + # So updating the predictions of online models should be the last step + if self.status == self.STATUS_ONLINE: + strategy.tool.update_online_pred() + + if not self._postpone_action(): + for strategy, models in zip(self.strategies, models_list): + models = self.trainer.end_train(models, experiment_name=strategy.name_id) + self.prepare_signals(**signal_kwargs) + + def get_collector(self, **kwargs) -> MergeCollector: + """ + Get the instance of `Collector <../advanced/task_management.html#Task Collecting>`_ to collect results from every strategy. + This collector can be a basis as the signals preparation. + + Args: + **kwargs: the params for get_collector. + + Returns: + MergeCollector: the collector to merge other collectors. + """ + collector_dict = {} + for strategy in self.strategies: + collector_dict[strategy.name_id] = strategy.get_collector(**kwargs) + return MergeCollector(collector_dict, process_list=[]) + + def add_strategy(self, strategies: Union[OnlineStrategy, List[OnlineStrategy]]): + """ + Add some new strategies to OnlineManager. + + Args: + strategy (Union[OnlineStrategy, List[OnlineStrategy]]): a list of OnlineStrategy + """ + if not isinstance(strategies, list): + strategies = [strategies] + self.first_train(strategies) + self.strategies.extend(strategies) + + def prepare_signals(self, prepare_func: Callable = AverageEnsemble(), over_write=False): + """ + After preparing the data of the last routine (a box in box-plot) which means the end of the routine, we can prepare trading signals for the next routine. + + NOTE: Given a set prediction, all signals before these prediction end times will be prepared well. + + Even if the latest signal already exists, the latest calculation result will be overwritten. + + .. note:: + + Given a prediction of a certain time, all signals before this time will be prepared well. + + Args: + prepare_func (Callable, optional): Get signals from a dict after collecting. Defaults to AverageEnsemble(), the results collected by MergeCollector must be {xxx:pred}. + over_write (bool, optional): If True, the new signals will overwrite. If False, the new signals will append to the end of signals. Defaults to False. + + Returns: + pd.DataFrame: the signals. + """ + signals = prepare_func(self.get_collector()()) + old_signals = self.signals + if old_signals is not None and not over_write: + old_max = old_signals.index.get_level_values("datetime").max() + new_signals = signals.loc[old_max:] + signals = pd.concat([old_signals, new_signals], axis=0) + else: + new_signals = signals + self.logger.info(f"Finished preparing new {len(new_signals)} signals.") + self.signals = signals + return new_signals + + def get_signals(self) -> Union[pd.Series, pd.DataFrame]: + """ + Get prepared online signals. + + Returns: + Union[pd.Series, pd.DataFrame]: pd.Series for only one signals every datetime. + pd.DataFrame for multiple signals, for example, buy and sell operations use different trading signals. + """ + return self.signals + + SIM_LOG_LEVEL = logging.INFO + 1 # when simulating, reduce information + SIM_LOG_NAME = "SIMULATE_INFO" + + def simulate( + self, end_time=None, frequency="day", task_kwargs={}, model_kwargs={}, signal_kwargs={} + ) -> Union[pd.Series, pd.DataFrame]: + """ + Starting from the current time, this method will simulate every routine in OnlineManager until the end time. + + Considering the parallel training, the models and signals can be prepared after all routine simulating. + + The delay training way can be ``DelayTrainer`` and the delay preparing signals way can be ``delay_prepare``. + + Args: + end_time: the time the simulation will end + frequency: the calendar frequency + task_kwargs (dict): the params for `prepare_tasks` + model_kwargs (dict): the params for `prepare_online_models` + signal_kwargs (dict): the params for `prepare_signals` + + Returns: + Union[pd.Series, pd.DataFrame]: pd.Series for only one signals every datetime. + pd.DataFrame for multiple signals, for example, buy and sell operations use different trading signals. + """ + self.status = self.STATUS_SIMULATING + cal = D.calendar(start_time=self.cur_time, end_time=end_time, freq=frequency) + self.first_train() + + simulate_level = self.SIM_LOG_LEVEL + set_global_logger_level(simulate_level) + logging.addLevelName(simulate_level, self.SIM_LOG_NAME) + + for cur_time in cal: + self.logger.log(level=simulate_level, msg=f"Simulating at {str(cur_time)}......") + self.routine( + cur_time, + task_kwargs=task_kwargs, + model_kwargs=model_kwargs, + signal_kwargs=signal_kwargs, + ) + # delay prepare the models and signals + if self._postpone_action(): + self.delay_prepare(model_kwargs=model_kwargs, signal_kwargs=signal_kwargs) + + # FIXME: get logging level firstly and restore it here + set_global_logger_level(logging.DEBUG) + self.logger.info(f"Finished preparing signals") + self.status = self.STATUS_ONLINE + return self.get_signals() + + def delay_prepare(self, model_kwargs={}, signal_kwargs={}): + """ + Prepare all models and signals if something is waiting for preparation. + + Args: + model_kwargs: the params for `end_train` + signal_kwargs: the params for `prepare_signals` + """ + # FIXME: + # This method is not implemented in the proper way!!! + last_models = {} + signals_time = D.calendar()[0] + need_prepare = False + for cur_time, strategy_models in self.history.items(): + self.cur_time = cur_time + + for strategy, models in strategy_models.items(): + # only new online models need to prepare + if last_models.setdefault(strategy, set()) != set(models): + models = self.trainer.end_train(models, experiment_name=strategy.name_id, **model_kwargs) + strategy.tool.reset_online_tag(models) + need_prepare = True + last_models[strategy] = set(models) + + if need_prepare: + # NOTE: Assumption: the predictions of online models need less than next cur_time, or this method will work in a wrong way. + self.prepare_signals(**signal_kwargs) + if signals_time > cur_time: + # FIXME: if use DelayTrainer and worker (and worker is faster than main progress), there are some possibilities of showing this warning. + self.logger.warn( + f"The signals have already parpred to {signals_time} by last preparation, but current time is only {cur_time}. This may be because the online models predict more than they should, which can cause signals to be contaminated by the offline models." + ) + need_prepare = False + signals_time = self.signals.index.get_level_values("datetime").max() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/strategy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..d545e4bc9a6fa46c2e69fad63a30374283002e2a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/strategy.py @@ -0,0 +1,208 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +OnlineStrategy module is an element of online serving. +""" + +from typing import List, Union +from qlib.log import get_module_logger +from qlib.model.ens.group import RollingGroup +from qlib.utils import transform_end_date +from qlib.workflow.online.utils import OnlineTool, OnlineToolR +from qlib.workflow.recorder import Recorder +from qlib.workflow.task.collect import Collector, RecorderCollector +from qlib.workflow.task.gen import RollingGen, task_generator +from qlib.workflow.task.utils import TimeAdjuster + + +class OnlineStrategy: + """ + OnlineStrategy is working with `Online Manager <#Online Manager>`_, responding to how the tasks are generated, the models are updated and signals are prepared. + """ + + def __init__(self, name_id: str): + """ + Init OnlineStrategy. + This module **MUST** use `Trainer <../reference/api.html#qlib.model.trainer.Trainer>`_ to finishing model training. + + Args: + name_id (str): a unique name or id. + trainer (qlib.model.trainer.Trainer, optional): a instance of Trainer. Defaults to None. + """ + self.name_id = name_id + self.logger = get_module_logger(self.__class__.__name__) + self.tool = OnlineTool() + + def prepare_tasks(self, cur_time, **kwargs) -> List[dict]: + """ + After the end of a routine, check whether we need to prepare and train some new tasks based on cur_time (None for latest).. + Return the new tasks waiting for training. + + You can find the last online models by OnlineTool.online_models. + """ + raise NotImplementedError(f"Please implement the `prepare_tasks` method.") + + def prepare_online_models(self, trained_models, cur_time=None) -> List[object]: + """ + Select some models from trained models and set them to online models. + This is a typical implementation to online all trained models, you can override it to implement the complex method. + You can find the last online models by OnlineTool.online_models if you still need them. + + NOTE: Reset all online models to trained models. If there are no trained models, then do nothing. + + **NOTE**: + Current implementation is very naive. Here is a more complex situation which is more closer to the + practical scenarios. + 1. Train new models at the day before `test_start` (at time stamp `T`) + 2. Switch models at the `test_start` (at time timestamp `T + 1` typically) + + Args: + models (list): a list of models. + cur_time (pd.Dataframe): current time from OnlineManger. None for the latest. + + Returns: + List[object]: a list of online models. + """ + if not trained_models: + return self.tool.online_models() + self.tool.reset_online_tag(trained_models) + return trained_models + + def first_tasks(self) -> List[dict]: + """ + Generate a series of tasks firstly and return them. + """ + raise NotImplementedError(f"Please implement the `first_tasks` method.") + + def get_collector(self) -> Collector: + """ + Get the instance of `Collector <../advanced/task_management.html#Task Collecting>`_ to collect different results of this strategy. + + For example: + 1) collect predictions in Recorder + 2) collect signals in a txt file + + Returns: + Collector + """ + raise NotImplementedError(f"Please implement the `get_collector` method.") + + +class RollingStrategy(OnlineStrategy): + """ + This example strategy always uses the latest rolling model sas online models. + """ + + def __init__( + self, + name_id: str, + task_template: Union[dict, List[dict]], + rolling_gen: RollingGen, + ): + """ + Init RollingStrategy. + + Assumption: the str of name_id, the experiment name, and the trainer's experiment name are the same. + + Args: + name_id (str): a unique name or id. Will be also the name of the Experiment. + task_template (Union[dict, List[dict]]): a list of task_template or a single template, which will be used to generate many tasks using rolling_gen. + rolling_gen (RollingGen): an instance of RollingGen + """ + super().__init__(name_id=name_id) + self.exp_name = self.name_id + if not isinstance(task_template, list): + task_template = [task_template] + self.task_template = task_template + self.rg = rolling_gen + assert issubclass(self.rg.__class__, RollingGen), "The rolling strategy relies on the feature if RollingGen" + self.tool = OnlineToolR(self.exp_name) + self.ta = TimeAdjuster() + + def get_collector(self, process_list=[RollingGroup()], rec_key_func=None, rec_filter_func=None, artifacts_key=None): + """ + Get the instance of `Collector <../advanced/task_management.html#Task Collecting>`_ to collect results. The returned collector must distinguish results in different models. + + Assumption: the models can be distinguished based on the model name and rolling test segments. + If you do not want this assumption, please implement your method or use another rec_key_func. + + Args: + rec_key_func (Callable): a function to get the key of a recorder. If None, use recorder id. + rec_filter_func (Callable, optional): filter the recorder by return True or False. Defaults to None. + artifacts_key (List[str], optional): the artifacts key you want to get. If None, get all artifacts. + """ + + def rec_key(recorder): + task_config = recorder.load_object("task") + model_key = task_config["model"]["class"] + rolling_key = task_config["dataset"]["kwargs"]["segments"]["test"] + return model_key, rolling_key + + if rec_key_func is None: + rec_key_func = rec_key + + artifacts_collector = RecorderCollector( + experiment=self.exp_name, + process_list=process_list, + rec_key_func=rec_key_func, + rec_filter_func=rec_filter_func, + artifacts_key=artifacts_key, + ) + + return artifacts_collector + + def first_tasks(self) -> List[dict]: + """ + Use rolling_gen to generate different tasks based on task_template. + + Returns: + List[dict]: a list of tasks + """ + return task_generator( + tasks=self.task_template, + generators=self.rg, # generate different date segment + ) + + def prepare_tasks(self, cur_time) -> List[dict]: + """ + Prepare new tasks based on cur_time (None for the latest). + + You can find the last online models by OnlineToolR.online_models. + + Returns: + List[dict]: a list of new tasks. + """ + # TODO: filter recorders by latest test segments is not a necessary + latest_records, max_test = self._list_latest(self.tool.online_models()) + if max_test is None: + self.logger.warn(f"No latest online recorders, no new tasks.") + return [] + calendar_latest = transform_end_date(cur_time) + self.logger.info( + f"The interval between current time {calendar_latest} and last rolling test begin time {max_test[0]} is {self.ta.cal_interval(calendar_latest, max_test[0])}, the rolling step is {self.rg.step}" + ) + res = [] + for rec in latest_records: + task = rec.load_object("task") + res.extend(self.rg.gen_following_tasks(task, calendar_latest)) + return res + + def _list_latest(self, rec_list: List[Recorder]): + """ + List latest recorder form rec_list + + Args: + rec_list (List[Recorder]): a list of Recorder + + Returns: + List[Recorder], pd.Timestamp: the latest recorders and their test end time + """ + if len(rec_list) == 0: + return rec_list, None + max_test = max(rec.load_object("task")["dataset"]["kwargs"]["segments"]["test"] for rec in rec_list) + latest_rec = [] + for rec in rec_list: + if rec.load_object("task")["dataset"]["kwargs"]["segments"]["test"] == max_test: + latest_rec.append(rec) + return latest_rec, max_test diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/update.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/update.py new file mode 100644 index 0000000000000000000000000000000000000000..5047a1bd25e08fd4fdaf144f60bbf32077f951f3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/update.py @@ -0,0 +1,298 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Updater is a module to update artifacts such as predictions when the stock data is updating. +""" + +from abc import ABCMeta, abstractmethod +from typing import Optional + +import pandas as pd +from qlib import get_module_logger +from qlib.data import D +from qlib.data.dataset import Dataset, DatasetH, TSDatasetH +from qlib.data.dataset.handler import DataHandlerLP +from qlib.model import Model +from qlib.utils import get_date_by_shift +from qlib.workflow.recorder import Recorder +from qlib.workflow.record_temp import SignalRecord + + +class RMDLoader: + """ + Recorder Model Dataset Loader + """ + + def __init__(self, rec: Recorder): + self.rec = rec + + def get_dataset( + self, start_time, end_time, segments=None, unprepared_dataset: Optional[DatasetH] = None + ) -> DatasetH: + """ + Load, config and setup dataset. + + This dataset is for inference. + + Args: + start_time : + the start_time of underlying data + end_time : + the end_time of underlying data + segments : dict + the segments config for dataset + Due to the time series dataset (TSDatasetH), the test segments maybe different from start_time and end_time + unprepared_dataset: Optional[DatasetH] + if user don't want to load dataset from recorder, please specify user's dataset + + Returns: + DatasetH: the instance of DatasetH + + """ + if segments is None: + segments = {"test": (start_time, end_time)} + if unprepared_dataset is None: + dataset: DatasetH = self.rec.load_object("dataset") + else: + dataset = unprepared_dataset + dataset.config(handler_kwargs={"start_time": start_time, "end_time": end_time}, segments=segments) + dataset.setup_data(handler_kwargs={"init_type": DataHandlerLP.IT_LS}) + return dataset + + def get_model(self) -> Model: + return self.rec.load_object("params.pkl") + + +class RecordUpdater(metaclass=ABCMeta): + """ + Update a specific recorders + """ + + def __init__(self, record: Recorder, *args, **kwargs): + self.record = record + self.logger = get_module_logger(self.__class__.__name__) + + @abstractmethod + def update(self, *args, **kwargs): + """ + Update info for specific recorder + """ + + +class DSBasedUpdater(RecordUpdater, metaclass=ABCMeta): + """ + Dataset-Based Updater + + - Providing updating feature for Updating data based on Qlib Dataset + + Assumption + + - Based on Qlib dataset + - The data to be updated is a multi-level index pd.DataFrame. For example label, prediction. + + .. code-block:: + + LABEL0 + datetime instrument + 2021-05-10 SH600000 0.006965 + SH600004 0.003407 + ... ... + 2021-05-28 SZ300498 0.015748 + SZ300676 -0.001321 + """ + + def __init__( + self, + record: Recorder, + to_date=None, + from_date=None, + hist_ref: Optional[int] = None, + freq="day", + fname="pred.pkl", + loader_cls: type = RMDLoader, + ): + """ + Init PredUpdater. + + Expected behavior in following cases: + + - if `to_date` is greater than the max date in the calendar, the data will be updated to the latest date + - if there are data before `from_date` or after `to_date`, only the data between `from_date` and `to_date` are affected. + + Args: + record : Recorder + to_date : + update to prediction to the `to_date` + + if to_date is None: + + data will updated to the latest date. + from_date : + the update will start from `from_date` + + if from_date is None: + + the updating will occur on the next tick after the latest data in historical data + hist_ref : int + Sometimes, the dataset will have historical depends. + Leave the problem to users to set the length of historical dependency + If user doesn't specify this parameter, Updater will try to load dataset to automatically determine the hist_ref + + .. note:: + + the start_time is not included in the `hist_ref`; So the `hist_ref` will be `step_len - 1` in most cases + + loader_cls : type + the class to load the model and dataset + + """ + # TODO: automate this hist_ref in the future. + super().__init__(record=record) + + self.to_date = to_date + self.hist_ref = hist_ref + self.freq = freq + self.fname = fname + self.rmdl = loader_cls(rec=record) + + latest_date = D.calendar(freq=freq)[-1] + if to_date is None: + to_date = latest_date + to_date = pd.Timestamp(to_date) + + if to_date >= latest_date: + self.logger.warning( + f"The given `to_date`({to_date}) is later than `latest_date`({latest_date}). So `to_date` is clipped to `latest_date`." + ) + to_date = latest_date + self.to_date = to_date + + # FIXME: it will raise error when running routine with delay trainer + # should we use another prediction updater for delay trainer? + self.old_data: pd.DataFrame = record.load_object(fname) + if from_date is None: + # dropna is for being compatible to some data with future information(e.g. label) + # The recent label data should be updated together + self.last_end = self.old_data.dropna().index.get_level_values("datetime").max() + else: + self.last_end = get_date_by_shift(from_date, -1, align="right") + + def prepare_data(self, unprepared_dataset: Optional[DatasetH] = None) -> DatasetH: + """ + Load dataset + - if unprepared_dataset is specified, then prepare the dataset directly + - Otherwise, + + Separating this function will make it easier to reuse the dataset + + Returns: + DatasetH: the instance of DatasetH + """ + # automatically getting the historical dependency if not specified + if self.hist_ref is None: + dataset: DatasetH = self.record.load_object("dataset") if unprepared_dataset is None else unprepared_dataset + # Special treatment of historical dependencies + if isinstance(dataset, TSDatasetH): + hist_ref = dataset.step_len - 1 + else: + hist_ref = 0 # if only the lastest data is used, then only current data will be used and no historical data will be used + else: + hist_ref = self.hist_ref + + start_time_buffer = get_date_by_shift( + self.last_end, -hist_ref + 1, clip_shift=False, freq=self.freq # pylint: disable=E1130 + ) + start_time = get_date_by_shift(self.last_end, 1, freq=self.freq) + seg = {"test": (start_time, self.to_date)} + return self.rmdl.get_dataset( + start_time=start_time_buffer, end_time=self.to_date, segments=seg, unprepared_dataset=unprepared_dataset + ) + + def update(self, dataset: DatasetH = None, write: bool = True, ret_new: bool = False) -> Optional[object]: + """ + Parameters + ---------- + dataset : DatasetH + DatasetH: the instance of DatasetH. None for prepare it again. + write : bool + will the the write action be executed + ret_new : bool + will the updated data be returned + + Returns + ------- + Optional[object] + the updated dataset + """ + # FIXME: the problem below is not solved + # The model dumped on GPU instances can not be loaded on CPU instance. Follow exception will raised + # RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU. + # https://github.com/pytorch/pytorch/issues/16797 + + if self.last_end >= self.to_date: + self.logger.info( + f"The data in {self.record.info['id']} are latest ({self.last_end}). No need to update to {self.to_date}." + ) + return + + # load dataset + if dataset is None: + # For reusing the dataset + dataset = self.prepare_data() + + updated_data = self.get_update_data(dataset) + + if write: + self.record.save_objects(**{self.fname: updated_data}) + if ret_new: + return updated_data + + @abstractmethod + def get_update_data(self, dataset: Dataset) -> pd.DataFrame: + """ + return the updated data based on the given dataset + + The difference between `get_update_data` and `update` + - `update_date` only include some data specific feature + - `update` include some general routine steps(e.g. prepare dataset, checking) + """ + + +def _replace_range(data, new_data): + dates = new_data.index.get_level_values("datetime") + data = data.sort_index() + data = data.drop(data.loc[dates.min() : dates.max()].index) + cb_data = pd.concat([data, new_data], axis=0) + cb_data = cb_data[~cb_data.index.duplicated(keep="last")].sort_index() + return cb_data + + +class PredUpdater(DSBasedUpdater): + """ + Update the prediction in the Recorder + """ + + def get_update_data(self, dataset: Dataset) -> pd.DataFrame: + # Load model + model = self.rmdl.get_model() + new_pred: pd.Series = model.predict(dataset) + data = _replace_range(self.old_data, new_pred.to_frame("score")) + self.logger.info(f"Finish updating new {new_pred.shape[0]} predictions in {self.record.info['id']}.") + return data + + +class LabelUpdater(DSBasedUpdater): + """ + Update the label in the recorder + + Assumption + - The label is generated from record_temp.SignalRecord. + """ + + def __init__(self, record: Recorder, to_date=None, **kwargs): + super().__init__(record, to_date=to_date, fname="label.pkl", **kwargs) + + def get_update_data(self, dataset: Dataset) -> pd.DataFrame: + new_label = SignalRecord.generate_label(dataset) + cb_data = _replace_range(self.old_data.sort_index(), new_label) + return cb_data diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c390ca009210da16b0a4386e9fc035558aaa6608 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/online/utils.py @@ -0,0 +1,187 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +OnlineTool is a module to set and unset a series of `online` models. +The `online` models are some decisive models in some time points, which can be changed with the change of time. +This allows us to use efficient submodels as the market-style changing. +""" + +from typing import List, Union + +from qlib.log import get_module_logger +from qlib.utils.exceptions import LoadObjectError +from qlib.workflow.online.update import PredUpdater +from qlib.workflow.recorder import Recorder +from qlib.workflow.task.utils import list_recorders + + +class OnlineTool: + """ + OnlineTool will manage `online` models in an experiment that includes the model recorders. + """ + + ONLINE_KEY = "online_status" # the online status key in recorder + ONLINE_TAG = "online" # the 'online' model + OFFLINE_TAG = "offline" # the 'offline' model, not for online serving + + def __init__(self): + """ + Init OnlineTool. + """ + self.logger = get_module_logger(self.__class__.__name__) + + def set_online_tag(self, tag, recorder: Union[list, object]): + """ + Set `tag` to the model to sign whether online. + + Args: + tag (str): the tags in `ONLINE_TAG`, `OFFLINE_TAG` + recorder (Union[list,object]): the model's recorder + """ + raise NotImplementedError(f"Please implement the `set_online_tag` method.") + + def get_online_tag(self, recorder: object) -> str: + """ + Given a model recorder and return its online tag. + + Args: + recorder (Object): the model's recorder + + Returns: + str: the online tag + """ + raise NotImplementedError(f"Please implement the `get_online_tag` method.") + + def reset_online_tag(self, recorder: Union[list, object]): + """ + Offline all models and set the recorders to 'online'. + + Args: + recorder (Union[list,object]): + the recorder you want to reset to 'online'. + + """ + raise NotImplementedError(f"Please implement the `reset_online_tag` method.") + + def online_models(self) -> list: + """ + Get current `online` models + + Returns: + list: a list of `online` models. + """ + raise NotImplementedError(f"Please implement the `online_models` method.") + + def update_online_pred(self, to_date=None): + """ + Update the predictions of `online` models to to_date. + + Args: + to_date (pd.Timestamp): the pred before this date will be updated. None for updating to the latest. + + """ + raise NotImplementedError(f"Please implement the `update_online_pred` method.") + + +class OnlineToolR(OnlineTool): + """ + The implementation of OnlineTool based on (R)ecorder. + """ + + def __init__(self, default_exp_name: str = None): + """ + Init OnlineToolR. + + Args: + default_exp_name (str): the default experiment name. + """ + super().__init__() + self.default_exp_name = default_exp_name + + def set_online_tag(self, tag, recorder: Union[Recorder, List]): + """ + Set `tag` to the model's recorder to sign whether online. + + Args: + tag (str): the tags in `ONLINE_TAG`, `NEXT_ONLINE_TAG`, `OFFLINE_TAG` + recorder (Union[Recorder, List]): a list of Recorder or an instance of Recorder + """ + if isinstance(recorder, Recorder): + recorder = [recorder] + for rec in recorder: + rec.set_tags(**{self.ONLINE_KEY: tag}) + self.logger.info(f"Set {len(recorder)} models to '{tag}'.") + + def get_online_tag(self, recorder: Recorder) -> str: + """ + Given a model recorder and return its online tag. + + Args: + recorder (Recorder): an instance of recorder + + Returns: + str: the online tag + """ + tags = recorder.list_tags() + return tags.get(self.ONLINE_KEY, self.OFFLINE_TAG) + + def reset_online_tag(self, recorder: Union[Recorder, List], exp_name: str = None): + """ + Offline all models and set the recorders to 'online'. + + Args: + recorder (Union[Recorder, List]): + the recorder you want to reset to 'online'. + exp_name (str): the experiment name. If None, then use default_exp_name. + + """ + exp_name = self._get_exp_name(exp_name) + if isinstance(recorder, Recorder): + recorder = [recorder] + recs = list_recorders(exp_name) + self.set_online_tag(self.OFFLINE_TAG, list(recs.values())) + self.set_online_tag(self.ONLINE_TAG, recorder) + + def online_models(self, exp_name: str = None) -> list: + """ + Get current `online` models + + Args: + exp_name (str): the experiment name. If None, then use default_exp_name. + + Returns: + list: a list of `online` models. + """ + exp_name = self._get_exp_name(exp_name) + return list(list_recorders(exp_name, lambda rec: self.get_online_tag(rec) == self.ONLINE_TAG).values()) + + def update_online_pred(self, to_date=None, from_date=None, exp_name: str = None): + """ + Update the predictions of online models to to_date. + + Args: + to_date (pd.Timestamp): the pred before this date will be updated. None for updating to latest time in Calendar. + exp_name (str): the experiment name. If None, then use default_exp_name. + """ + exp_name = self._get_exp_name(exp_name) + online_models = self.online_models(exp_name=exp_name) + for rec in online_models: + try: + updater = PredUpdater(rec, to_date=to_date, from_date=from_date) + except LoadObjectError as e: + # skip the recorder without pred + self.logger.warn(f"An exception `{str(e)}` happened when load `pred.pkl`, skip it.") + continue + updater.update() + + self.logger.info(f"Finished updating {len(online_models)} online model predictions of {exp_name}.") + + def _get_exp_name(self, exp_name): + if exp_name is None: + if self.default_exp_name is None: + raise ValueError( + "Both default_exp_name and exp_name are None. OnlineToolR needs a specific experiment." + ) + exp_name = self.default_exp_name + return exp_name diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/record_temp.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/record_temp.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd58ec209813197c342e937947e75daa5232c45 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/record_temp.py @@ -0,0 +1,693 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import logging +import warnings +import pandas as pd +import numpy as np +from tqdm import trange +from pprint import pprint +from typing import Union, List, Optional, Dict + +from qlib.utils.exceptions import LoadObjectError +from ..contrib.evaluate import risk_analysis, indicator_analysis + +from ..data.dataset import DatasetH +from ..data.dataset.handler import DataHandlerLP +from ..backtest import backtest as normal_backtest +from ..log import get_module_logger +from ..utils import fill_placeholder, flatten_dict, class_casting, get_date_by_shift +from ..utils.time import Freq +from ..utils.data import deepcopy_basic_type +from ..utils.exceptions import QlibException +from ..contrib.eva.alpha import calc_ic, calc_long_short_return, calc_long_short_prec + +logger = get_module_logger("workflow", logging.INFO) + + +class RecordTemp: + """ + This is the Records Template class that enables user to generate experiment results such as IC and + backtest in a certain format. + """ + + artifact_path = None + depend_cls = None # the dependant class of the record; the record will depend on the results generated by + # `depend_cls` + + @classmethod + def get_path(cls, path=None): + names = [] + if cls.artifact_path is not None: + names.append(cls.artifact_path) + + if path is not None: + names.append(path) + + return "/".join(names) + + def save(self, **kwargs): + """ + It behaves the same as self.recorder.save_objects. + But it is an easier interface because users don't have to care about `get_path` and `artifact_path` + """ + art_path = self.get_path() + if art_path == "": + art_path = None + self.recorder.save_objects(artifact_path=art_path, **kwargs) + + def __init__(self, recorder): + self._recorder = recorder + + @property + def recorder(self): + if self._recorder is None: + raise ValueError("This RecordTemp did not set recorder yet.") + return self._recorder + + def generate(self, **kwargs): + """ + Generate certain records such as IC, backtest etc., and save them. + + Parameters + ---------- + kwargs + + Return + ------ + """ + raise NotImplementedError(f"Please implement the `generate` method.") + + def load(self, name: str, parents: bool = True): + """ + It behaves the same as self.recorder.load_object. + But it is an easier interface because users don't have to care about `get_path` and `artifact_path` + + Parameters + ---------- + name : str + the name for the file to be load. + + parents : bool + Each recorder has different `artifact_path`. + So parents recursively find the path in parents + Sub classes has higher priority + + Return + ------ + The stored records. + """ + try: + return self.recorder.load_object(self.get_path(name)) + except LoadObjectError as e: + if parents: + if self.depend_cls is not None: + with class_casting(self, self.depend_cls): + return self.load(name, parents=True) + raise e + + def list(self): + """ + List the supported artifacts. + Users don't have to consider self.get_path + + Return + ------ + A list of all the supported artifacts. + """ + return [] + + def check(self, include_self: bool = False, parents: bool = True): + """ + Check if the records is properly generated and saved. + It is useful in following examples + + - checking if the dependant files complete before generating new things. + - checking if the final files is completed + + Parameters + ---------- + include_self : bool + is the file generated by self included + parents : bool + will we check parents + + Raise + ------ + FileNotFoundError + whether the records are stored properly. + """ + if include_self: + # Some mlflow backend will not list the directly recursively. + # So we force to the directly + artifacts = {} + + def _get_arts(dirn): + if dirn not in artifacts: + artifacts[dirn] = self.recorder.list_artifacts(dirn) + return artifacts[dirn] + + for item in self.list(): + ps = self.get_path(item).split("/") + dirn = "/".join(ps[:-1]) + if self.get_path(item) not in _get_arts(dirn): + raise FileNotFoundError + if parents: + if self.depend_cls is not None: + with class_casting(self, self.depend_cls): + self.check(include_self=True) + + +class SignalRecord(RecordTemp): + """ + This is the Signal Record class that generates the signal prediction. This class inherits the ``RecordTemp`` class. + """ + + def __init__(self, model=None, dataset=None, recorder=None): + super().__init__(recorder=recorder) + self.model = model + self.dataset = dataset + + @staticmethod + def generate_label(dataset): + with class_casting(dataset, DatasetH): + params = dict(segments="test", col_set="label", data_key=DataHandlerLP.DK_R) + try: + # Assume the backend handler is DataHandlerLP + raw_label = dataset.prepare(**params) + except TypeError: + # The argument number is not right + del params["data_key"] + # The backend handler should be DataHandler + raw_label = dataset.prepare(**params) + except AttributeError as e: + # The data handler is initialized with `drop_raw=True`... + # So raw_label is not available + logger.warning(f"Exception: {e}") + raw_label = None + return raw_label + + def generate(self, **kwargs): + # generate prediction + pred = self.model.predict(self.dataset) + if isinstance(pred, pd.Series): + pred = pred.to_frame("score") + self.save(**{"pred.pkl": pred}) + + logger.info( + f"Signal record 'pred.pkl' has been saved as the artifact of the Experiment {self.recorder.experiment_id}" + ) + # print out results + pprint(f"The following are prediction results of the {type(self.model).__name__} model.") + pprint(pred.head(5)) + + if isinstance(self.dataset, DatasetH): + raw_label = self.generate_label(self.dataset) + self.save(**{"label.pkl": raw_label}) + + def list(self): + return ["pred.pkl", "label.pkl"] + + +class ACRecordTemp(RecordTemp): + """Automatically checking record template""" + + def __init__(self, recorder, skip_existing=False): + self.skip_existing = skip_existing + super().__init__(recorder=recorder) + + def generate(self, *args, **kwargs): + """automatically checking the files and then run the concrete generating task""" + if self.skip_existing: + try: + self.check(include_self=True, parents=False) + except FileNotFoundError: + pass # continue to generating metrics + else: + logger.info("The results has previously generated, Generation skipped.") + return + + try: + self.check() + except FileNotFoundError: + logger.warning("The dependent data does not exists. Generation skipped.") + return + artifact_dict = self._generate(*args, **kwargs) + if isinstance(artifact_dict, dict): + self.save(**artifact_dict) + return artifact_dict + + def _generate(self, *args, **kwargs) -> Dict[str, object]: + """ + Run the concrete generating task, return the dictionary of the generated results. + The caller method will save the results to the recorder. + """ + raise NotImplementedError(f"Please implement the `_generate` method") + + +class HFSignalRecord(SignalRecord): + """ + This is the Signal Analysis Record class that generates the analysis results such as IC and IR. This class inherits the ``RecordTemp`` class. + """ + + artifact_path = "hg_sig_analysis" + depend_cls = SignalRecord + + def __init__(self, recorder, **kwargs): + super().__init__(recorder=recorder) + + def generate(self): + pred = self.load("pred.pkl") + raw_label = self.load("label.pkl") + long_pre, short_pre = calc_long_short_prec(pred.iloc[:, 0], raw_label.iloc[:, 0], is_alpha=True) + ic, ric = calc_ic(pred.iloc[:, 0], raw_label.iloc[:, 0]) + metrics = { + "IC": ic.mean(), + "ICIR": ic.mean() / ic.std(), + "Rank IC": ric.mean(), + "Rank ICIR": ric.mean() / ric.std(), + "Long precision": long_pre.mean(), + "Short precision": short_pre.mean(), + } + objects = {"ic.pkl": ic, "ric.pkl": ric} + objects.update({"long_pre.pkl": long_pre, "short_pre.pkl": short_pre}) + long_short_r, long_avg_r = calc_long_short_return(pred.iloc[:, 0], raw_label.iloc[:, 0]) + metrics.update( + { + "Long-Short Average Return": long_short_r.mean(), + "Long-Short Average Sharpe": long_short_r.mean() / long_short_r.std(), + } + ) + objects.update( + { + "long_short_r.pkl": long_short_r, + "long_avg_r.pkl": long_avg_r, + } + ) + self.recorder.log_metrics(**metrics) + self.save(**objects) + pprint(metrics) + + def list(self): + return ["ic.pkl", "ric.pkl", "long_pre.pkl", "short_pre.pkl", "long_short_r.pkl", "long_avg_r.pkl"] + + +class SigAnaRecord(ACRecordTemp): + """ + This is the Signal Analysis Record class that generates the analysis results such as IC and IR. + This class inherits the ``RecordTemp`` class. + """ + + artifact_path = "sig_analysis" + depend_cls = SignalRecord + + def __init__(self, recorder, ana_long_short=False, ann_scaler=252, label_col=0, skip_existing=False): + super().__init__(recorder=recorder, skip_existing=skip_existing) + self.ana_long_short = ana_long_short + self.ann_scaler = ann_scaler + self.label_col = label_col + + def _generate(self, label: Optional[pd.DataFrame] = None, **kwargs): + """ + Parameters + ---------- + label : Optional[pd.DataFrame] + Label should be a dataframe. + """ + pred = self.load("pred.pkl") + if label is None: + label = self.load("label.pkl") + if label is None or not isinstance(label, pd.DataFrame) or label.empty: + logger.warning(f"Empty label.") + return + ic, ric = calc_ic(pred.iloc[:, 0], label.iloc[:, self.label_col]) + metrics = { + "IC": ic.mean(), + "ICIR": ic.mean() / ic.std(), + "Rank IC": ric.mean(), + "Rank ICIR": ric.mean() / ric.std(), + } + objects = {"ic.pkl": ic, "ric.pkl": ric} + if self.ana_long_short: + long_short_r, long_avg_r = calc_long_short_return(pred.iloc[:, 0], label.iloc[:, self.label_col]) + metrics.update( + { + "Long-Short Ann Return": long_short_r.mean() * self.ann_scaler, + "Long-Short Ann Sharpe": long_short_r.mean() / long_short_r.std() * self.ann_scaler**0.5, + "Long-Avg Ann Return": long_avg_r.mean() * self.ann_scaler, + "Long-Avg Ann Sharpe": long_avg_r.mean() / long_avg_r.std() * self.ann_scaler**0.5, + } + ) + objects.update( + { + "long_short_r.pkl": long_short_r, + "long_avg_r.pkl": long_avg_r, + } + ) + self.recorder.log_metrics(**metrics) + pprint(metrics) + return objects + + def list(self): + paths = ["ic.pkl", "ric.pkl"] + if self.ana_long_short: + paths.extend(["long_short_r.pkl", "long_avg_r.pkl"]) + return paths + + +class PortAnaRecord(ACRecordTemp): + """ + This is the Portfolio Analysis Record class that generates the analysis results such as those of backtest. This class inherits the ``RecordTemp`` class. + + The following files will be stored in recorder + + - report_normal.pkl & positions_normal.pkl: + + - The return report and detailed positions of the backtest, returned by `qlib/contrib/evaluate.py:backtest` + - port_analysis.pkl : The risk analysis of your portfolio, returned by `qlib/contrib/evaluate.py:risk_analysis` + """ + + artifact_path = "portfolio_analysis" + depend_cls = SignalRecord + + def __init__( + self, + recorder, + config=None, + risk_analysis_freq: Union[List, str] = None, + indicator_analysis_freq: Union[List, str] = None, + indicator_analysis_method=None, + skip_existing=False, + **kwargs, + ): + """ + config["strategy"] : dict + define the strategy class as well as the kwargs. + config["executor"] : dict + define the executor class as well as the kwargs. + config["backtest"] : dict + define the backtest kwargs. + risk_analysis_freq : str|List[str] + risk analysis freq of report + indicator_analysis_freq : str|List[str] + indicator analysis freq of report + indicator_analysis_method : str, optional, default by None + the candidate values include 'mean', 'amount_weighted', 'value_weighted' + """ + super().__init__(recorder=recorder, skip_existing=skip_existing, **kwargs) + + if config is None: + config = { # Default config for daily trading + "strategy": { + "class": "TopkDropoutStrategy", + "module_path": "qlib.contrib.strategy", + "kwargs": {"signal": "", "topk": 50, "n_drop": 5}, + }, + "backtest": { + "start_time": None, + "end_time": None, + "account": 100000000, + "benchmark": "SH000300", + "exchange_kwargs": { + "limit_threshold": 0.095, + "deal_price": "close", + "open_cost": 0.0005, + "close_cost": 0.0015, + "min_cost": 5, + }, + }, + } + # We only deepcopy_basic_type because + # - We don't want to affect the config outside. + # - We don't want to deepcopy complex object to avoid overhead + config = deepcopy_basic_type(config) + + self.strategy_config = config["strategy"] + _default_executor_config = { + "class": "SimulatorExecutor", + "module_path": "qlib.backtest.executor", + "kwargs": { + "time_per_step": "day", + "generate_portfolio_metrics": True, + }, + } + self.executor_config = config.get("executor", _default_executor_config) + self.backtest_config = config["backtest"] + + self.all_freq = self._get_report_freq(self.executor_config) + if risk_analysis_freq is None: + risk_analysis_freq = [self.all_freq[0]] + if indicator_analysis_freq is None: + indicator_analysis_freq = [self.all_freq[0]] + + if isinstance(risk_analysis_freq, str): + risk_analysis_freq = [risk_analysis_freq] + if isinstance(indicator_analysis_freq, str): + indicator_analysis_freq = [indicator_analysis_freq] + + self.risk_analysis_freq = [ + "{0}{1}".format(*Freq.parse(_analysis_freq)) for _analysis_freq in risk_analysis_freq + ] + self.indicator_analysis_freq = [ + "{0}{1}".format(*Freq.parse(_analysis_freq)) for _analysis_freq in indicator_analysis_freq + ] + self.indicator_analysis_method = indicator_analysis_method + + def _get_report_freq(self, executor_config): + ret_freq = [] + if executor_config["kwargs"].get("generate_portfolio_metrics", False): + _count, _freq = Freq.parse(executor_config["kwargs"]["time_per_step"]) + ret_freq.append(f"{_count}{_freq}") + if "inner_executor" in executor_config["kwargs"]: + ret_freq.extend(self._get_report_freq(executor_config["kwargs"]["inner_executor"])) + return ret_freq + + def _generate(self, **kwargs): + pred = self.load("pred.pkl") + + # replace the "" with prediction saved before + placeholder_value = {"": pred} + for k in "executor_config", "strategy_config": + setattr(self, k, fill_placeholder(getattr(self, k), placeholder_value)) + + # if the backtesting time range is not set, it will automatically extract time range from the prediction file + dt_values = pred.index.get_level_values("datetime") + if self.backtest_config["start_time"] is None: + self.backtest_config["start_time"] = dt_values.min() + if self.backtest_config["end_time"] is None: + self.backtest_config["end_time"] = get_date_by_shift(dt_values.max(), -1) + warnings.warn( + "No explicit backtest end_time provided. " + "Qlib requires one extra calendar step to determine the right boundary of a bar. " + "Therefore the end_time is shifted backward by one trading day from " + f"{dt_values.max()} -> {self.backtest_config['end_time']}." + ) + + artifact_objects = {} + # custom strategy and get backtest + portfolio_metric_dict, indicator_dict = normal_backtest( + executor=self.executor_config, strategy=self.strategy_config, **self.backtest_config + ) + for _freq, (report_normal, positions_normal) in portfolio_metric_dict.items(): + artifact_objects.update({f"report_normal_{_freq}.pkl": report_normal}) + artifact_objects.update({f"positions_normal_{_freq}.pkl": positions_normal}) + + for _freq, indicators_normal in indicator_dict.items(): + artifact_objects.update({f"indicators_normal_{_freq}.pkl": indicators_normal[0]}) + artifact_objects.update({f"indicators_normal_{_freq}_obj.pkl": indicators_normal[1]}) + + for _analysis_freq in self.risk_analysis_freq: + if _analysis_freq not in portfolio_metric_dict: + warnings.warn( + f"the freq {_analysis_freq} report is not found, please set the corresponding env with `generate_portfolio_metrics=True`" + ) + else: + report_normal, _ = portfolio_metric_dict.get(_analysis_freq) + analysis = dict() + analysis["excess_return_without_cost"] = risk_analysis( + report_normal["return"] - report_normal["bench"], freq=_analysis_freq + ) + analysis["excess_return_with_cost"] = risk_analysis( + report_normal["return"] - report_normal["bench"] - report_normal["cost"], freq=_analysis_freq + ) + + analysis_df = pd.concat(analysis) # type: pd.DataFrame + # log metrics + analysis_dict = flatten_dict(analysis_df["risk"].unstack().T.to_dict()) + self.recorder.log_metrics(**{f"{_analysis_freq}.{k}": v for k, v in analysis_dict.items()}) + # save results + artifact_objects.update({f"port_analysis_{_analysis_freq}.pkl": analysis_df}) + logger.info( + f"Portfolio analysis record 'port_analysis_{_analysis_freq}.pkl' has been saved as the artifact of the Experiment {self.recorder.experiment_id}" + ) + # print out results + pprint(f"The following are analysis results of benchmark return({_analysis_freq}).") + pprint(risk_analysis(report_normal["bench"], freq=_analysis_freq)) + pprint(f"The following are analysis results of the excess return without cost({_analysis_freq}).") + pprint(analysis["excess_return_without_cost"]) + pprint(f"The following are analysis results of the excess return with cost({_analysis_freq}).") + pprint(analysis["excess_return_with_cost"]) + + for _analysis_freq in self.indicator_analysis_freq: + if _analysis_freq not in indicator_dict: + warnings.warn(f"the freq {_analysis_freq} indicator is not found") + else: + indicators_normal = indicator_dict.get(_analysis_freq)[0] + if self.indicator_analysis_method is None: + analysis_df = indicator_analysis(indicators_normal) + else: + analysis_df = indicator_analysis(indicators_normal, method=self.indicator_analysis_method) + # log metrics + analysis_dict = analysis_df["value"].to_dict() + self.recorder.log_metrics(**{f"{_analysis_freq}.{k}": v for k, v in analysis_dict.items()}) + # save results + artifact_objects.update({f"indicator_analysis_{_analysis_freq}.pkl": analysis_df}) + logger.info( + f"Indicator analysis record 'indicator_analysis_{_analysis_freq}.pkl' has been saved as the artifact of the Experiment {self.recorder.experiment_id}" + ) + pprint(f"The following are analysis results of indicators({_analysis_freq}).") + pprint(analysis_df) + return artifact_objects + + def list(self): + list_path = [] + for _freq in self.all_freq: + list_path.extend( + [ + f"report_normal_{_freq}.pkl", + f"positions_normal_{_freq}.pkl", + ] + ) + for _analysis_freq in self.risk_analysis_freq: + if _analysis_freq in self.all_freq: + list_path.append(f"port_analysis_{_analysis_freq}.pkl") + else: + warnings.warn(f"risk_analysis freq {_analysis_freq} is not found") + + for _analysis_freq in self.indicator_analysis_freq: + if _analysis_freq in self.all_freq: + list_path.append(f"indicator_analysis_{_analysis_freq}.pkl") + else: + warnings.warn(f"indicator_analysis freq {_analysis_freq} is not found") + return list_path + + +class MultiPassPortAnaRecord(PortAnaRecord): + """ + This is the Multiple Pass Portfolio Analysis Record class that run backtest multiple times and generates the analysis results such as those of backtest. This class inherits the ``PortAnaRecord`` class. + + If shuffle_init_score enabled, the prediction score of the first backtest date will be shuffled, so that initial position will be random. + The shuffle_init_score will only works when the signal is used as placeholder. The placeholder will be replaced by pred.pkl saved in recorder. + + Parameters + ---------- + recorder : Recorder + The recorder used to save the backtest results. + pass_num : int + The number of backtest passes. + shuffle_init_score : bool + Whether to shuffle the prediction score of the first backtest date. + """ + + depend_cls = SignalRecord + + def __init__(self, recorder, pass_num=10, shuffle_init_score=True, **kwargs): + """ + Parameters + ---------- + recorder : Recorder + The recorder used to save the backtest results. + pass_num : int + The number of backtest passes. + shuffle_init_score : bool + Whether to shuffle the prediction score of the first backtest date. + """ + self.pass_num = pass_num + self.shuffle_init_score = shuffle_init_score + + super().__init__(recorder, **kwargs) + + # Save original strategy so that pred df can be replaced in next generate + self.original_strategy = deepcopy_basic_type(self.strategy_config) + if not isinstance(self.original_strategy, dict): + raise QlibException("MultiPassPortAnaRecord require the passed in strategy to be a dict") + if "signal" not in self.original_strategy.get("kwargs", {}): + raise QlibException("MultiPassPortAnaRecord require the passed in strategy to have signal as a parameter") + + def random_init(self): + pred_df = self.load("pred.pkl") + + all_pred_dates = pred_df.index.get_level_values("datetime") + bt_start_date = pd.to_datetime(self.backtest_config.get("start_time")) + if bt_start_date is None: + first_bt_pred_date = all_pred_dates.min() + else: + first_bt_pred_date = all_pred_dates[all_pred_dates >= bt_start_date].min() + + # Shuffle the first backtest date's pred score + first_date_score = pred_df.loc[first_bt_pred_date]["score"] + np.random.shuffle(first_date_score.values) + + # Use shuffled signal as the strategy signal + self.strategy_config = deepcopy_basic_type(self.original_strategy) + self.strategy_config["kwargs"]["signal"] = pred_df + + def _generate(self, **kwargs): + risk_analysis_df_map = {} + + # Collect each frequency's analysis df as df list + for i in trange(self.pass_num): + if self.shuffle_init_score: + self.random_init() + + # Not check for cache file list + single_run_artifacts = super()._generate(**kwargs) + + for _analysis_freq in self.risk_analysis_freq: + risk_analysis_df_list = risk_analysis_df_map.get(_analysis_freq, []) + risk_analysis_df_map[_analysis_freq] = risk_analysis_df_list + + analysis_df = single_run_artifacts[f"port_analysis_{_analysis_freq}.pkl"] + analysis_df["run_id"] = i + risk_analysis_df_list.append(analysis_df) + + result_artifacts = {} + # Concat df list + for _analysis_freq in self.risk_analysis_freq: + combined_df = pd.concat(risk_analysis_df_map[_analysis_freq]) + + # Calculate return and information ratio's mean, std and mean/std + multi_pass_port_analysis_df = combined_df.groupby(level=[0, 1], group_keys=False).apply( + lambda x: pd.Series( + {"mean": x["risk"].mean(), "std": x["risk"].std(), "mean_std": x["risk"].mean() / x["risk"].std()} + ) + ) + + # Only look at "annualized_return" and "information_ratio" + multi_pass_port_analysis_df = multi_pass_port_analysis_df.loc[ + (slice(None), ["annualized_return", "information_ratio"]), : + ] + pprint(multi_pass_port_analysis_df) + + # Save new df + result_artifacts.update({f"multi_pass_port_analysis_{_analysis_freq}.pkl": multi_pass_port_analysis_df}) + + # Log metrics + metrics = flatten_dict( + { + "mean": multi_pass_port_analysis_df["mean"].unstack().T.to_dict(), + "std": multi_pass_port_analysis_df["std"].unstack().T.to_dict(), + "mean_std": multi_pass_port_analysis_df["mean_std"].unstack().T.to_dict(), + } + ) + self.recorder.log_metrics(**metrics) + return result_artifacts + + def list(self): + list_path = [] + for _analysis_freq in self.risk_analysis_freq: + if _analysis_freq in self.all_freq: + list_path.append(f"multi_pass_port_analysis_{_analysis_freq}.pkl") + else: + warnings.warn(f"risk_analysis freq {_analysis_freq} is not found") + return list_path diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/recorder.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd99c0769fce2d349ac44d918fe2a04de41908e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/recorder.py @@ -0,0 +1,493 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import os +import sys +from typing import Optional +import mlflow +import shutil +import pickle +import tempfile +import subprocess +import platform +from pathlib import Path +from datetime import datetime + +from qlib.utils.serial import Serializable +from qlib.utils.exceptions import LoadObjectError +from qlib.utils.paral import AsyncCaller + +from ..log import TimeInspector, get_module_logger +from mlflow.store.artifact.azure_blob_artifact_repo import AzureBlobArtifactRepository + +logger = get_module_logger("workflow") +# mlflow limits the length of log_param to 500, but this caused errors when using qrun, so we extended the mlflow limit. +mlflow.utils.validation.MAX_PARAM_VAL_LENGTH = 1000 + + +class Recorder: + """ + This is the `Recorder` class for logging the experiments. The API is designed similar to mlflow. + (The link: https://mlflow.org/docs/latest/python_api/mlflow.html) + + The status of the recorder can be SCHEDULED, RUNNING, FINISHED, FAILED. + """ + + # status type + STATUS_S = "SCHEDULED" + STATUS_R = "RUNNING" + STATUS_FI = "FINISHED" + STATUS_FA = "FAILED" + + def __init__(self, experiment_id, name): + self.id = None + self.name = name + self.experiment_id = experiment_id + self.start_time = None + self.end_time = None + self.status = Recorder.STATUS_S + + def __repr__(self): + return "{name}(info={info})".format(name=self.__class__.__name__, info=self.info) + + def __str__(self): + return str(self.info) + + def __hash__(self) -> int: + return hash(self.info["id"]) + + @property + def info(self): + output = dict() + output["class"] = "Recorder" + output["id"] = self.id + output["name"] = self.name + output["experiment_id"] = self.experiment_id + output["start_time"] = self.start_time + output["end_time"] = self.end_time + output["status"] = self.status + return output + + def set_recorder_name(self, rname): + self.recorder_name = rname + + def save_objects(self, local_path=None, artifact_path=None, **kwargs): + """ + Save objects such as prediction file or model checkpoints to the artifact URI. User + can save object through keywords arguments (name:value). + + Please refer to the docs of qlib.workflow:R.save_objects + + Parameters + ---------- + local_path : str + if provided, them save the file or directory to the artifact URI. + artifact_path=None : str + the relative path for the artifact to be stored in the URI. + """ + raise NotImplementedError(f"Please implement the `save_objects` method.") + + def load_object(self, name): + """ + Load objects such as prediction file or model checkpoints. + + Parameters + ---------- + name : str + name of the file to be loaded. + + Returns + ------- + The saved object. + """ + raise NotImplementedError(f"Please implement the `load_object` method.") + + def start_run(self): + """ + Start running or resuming the Recorder. The return value can be used as a context manager within a `with` block; + otherwise, you must call end_run() to terminate the current run. (See `ActiveRun` class in mlflow) + + Returns + ------- + An active running object (e.g. mlflow.ActiveRun object). + """ + raise NotImplementedError(f"Please implement the `start_run` method.") + + def end_run(self): + """ + End an active Recorder. + """ + raise NotImplementedError(f"Please implement the `end_run` method.") + + def log_params(self, **kwargs): + """ + Log a batch of params for the current run. + + Parameters + ---------- + keyword arguments + key, value pair to be logged as parameters. + """ + raise NotImplementedError(f"Please implement the `log_params` method.") + + def log_metrics(self, step=None, **kwargs): + """ + Log multiple metrics for the current run. + + Parameters + ---------- + keyword arguments + key, value pair to be logged as metrics. + """ + raise NotImplementedError(f"Please implement the `log_metrics` method.") + + def log_artifact(self, local_path: str, artifact_path: Optional[str] = None): + """ + Log a local file or directory as an artifact of the currently active run. + + Parameters + ---------- + local_path : str + Path to the file to write. + artifact_path : Optional[str] + If provided, the directory in ``artifact_uri`` to write to. + """ + raise NotImplementedError(f"Please implement the `log_metrics` method.") + + def set_tags(self, **kwargs): + """ + Log a batch of tags for the current run. + + Parameters + ---------- + keyword arguments + key, value pair to be logged as tags. + """ + raise NotImplementedError(f"Please implement the `set_tags` method.") + + def delete_tags(self, *keys): + """ + Delete some tags from a run. + + Parameters + ---------- + keys : series of strs of the keys + all the name of the tag to be deleted. + """ + raise NotImplementedError(f"Please implement the `delete_tags` method.") + + def list_artifacts(self, artifact_path: str = None): + """ + List all the artifacts of a recorder. + + Parameters + ---------- + artifact_path : str + the relative path for the artifact to be stored in the URI. + + Returns + ------- + A list of artifacts information (name, path, etc.) that being stored. + """ + raise NotImplementedError(f"Please implement the `list_artifacts` method.") + + def download_artifact(self, path: str, dst_path: Optional[str] = None) -> str: + """ + Download an artifact file or directory from a run to a local directory if applicable, + and return a local path for it. + + Parameters + ---------- + path : str + Relative source path to the desired artifact. + dst_path : Optional[str] + Absolute path of the local filesystem destination directory to which to + download the specified artifacts. This directory must already exist. + If unspecified, the artifacts will either be downloaded to a new + uniquely-named directory on the local filesystem. + + Returns + ------- + str + Local path of desired artifact. + """ + raise NotImplementedError(f"Please implement the `list_artifacts` method.") + + def list_metrics(self): + """ + List all the metrics of a recorder. + + Returns + ------- + A dictionary of metrics that being stored. + """ + raise NotImplementedError(f"Please implement the `list_metrics` method.") + + def list_params(self): + """ + List all the params of a recorder. + + Returns + ------- + A dictionary of params that being stored. + """ + raise NotImplementedError(f"Please implement the `list_params` method.") + + def list_tags(self): + """ + List all the tags of a recorder. + + Returns + ------- + A dictionary of tags that being stored. + """ + raise NotImplementedError(f"Please implement the `list_tags` method.") + + +class MLflowRecorder(Recorder): + """ + Use mlflow to implement a Recorder. + + Due to the fact that mlflow will only log artifact from a file or directory, we decide to + use file manager to help maintain the objects in the project. + + Instead of using mlflow directly, we use another interface wrapping mlflow to log experiments. + Though it takes extra efforts, but it brings users benefits due to following reasons. + - It will be more convenient to change the experiment logging backend without changing any code in upper level + - We can provide more convenience to automatically do some extra things and make interface easier. For examples: + - Automatically logging the uncommitted code + - Automatically logging part of environment variables + - User can control several different runs by just creating different Recorder (in mlflow, you always have to switch artifact_uri and pass in run ids frequently) + """ + + def __init__(self, experiment_id, uri, name=None, mlflow_run=None): + super(MLflowRecorder, self).__init__(experiment_id, name) + self._uri = uri + self._artifact_uri = None + self.client = mlflow.tracking.MlflowClient(tracking_uri=self._uri) + # construct from mlflow run + if mlflow_run is not None: + assert isinstance(mlflow_run, mlflow.entities.run.Run), "Please input with a MLflow Run object." + self.name = mlflow_run.data.tags["mlflow.runName"] + self.id = mlflow_run.info.run_id + self.status = mlflow_run.info.status + self.start_time = ( + datetime.fromtimestamp(float(mlflow_run.info.start_time) / 1000.0).strftime("%Y-%m-%d %H:%M:%S") + if mlflow_run.info.start_time is not None + else None + ) + self.end_time = ( + datetime.fromtimestamp(float(mlflow_run.info.end_time) / 1000.0).strftime("%Y-%m-%d %H:%M:%S") + if mlflow_run.info.end_time is not None + else None + ) + self._artifact_uri = mlflow_run.info.artifact_uri + self.async_log = None + + def __repr__(self): + name = self.__class__.__name__ + space_length = len(name) + 1 + return "{name}(info={info},\n{space}uri={uri},\n{space}artifact_uri={artifact_uri},\n{space}client={client})".format( + name=name, + space=" " * space_length, + info=self.info, + uri=self.uri, + artifact_uri=self.artifact_uri, + client=self.client, + ) + + def __hash__(self) -> int: + return hash(self.info["id"]) + + def __eq__(self, o: object) -> bool: + if isinstance(o, MLflowRecorder): + return self.info["id"] == o.info["id"] + return False + + @property + def uri(self): + return self._uri + + @property + def artifact_uri(self): + return self._artifact_uri + + def get_local_dir(self): + """ + This function will return the directory path of this recorder. + """ + if self.artifact_uri is not None: + if platform.system() == "Windows": + local_dir_path = Path(self.artifact_uri.lstrip("file:").lstrip("/")).parent + else: + local_dir_path = Path(self.artifact_uri.lstrip("file:")).parent + local_dir_path = str(local_dir_path.resolve()) + if os.path.isdir(local_dir_path): + return local_dir_path + else: + raise RuntimeError("This recorder is not saved in the local file system.") + + else: + raise ValueError( + "Please make sure the recorder has been created and started properly before getting artifact uri." + ) + + def start_run(self): + # set the tracking uri + mlflow.set_tracking_uri(self.uri) + # start the run + run = mlflow.start_run(self.id, self.experiment_id, self.name) + # save the run id and artifact_uri + self.id = run.info.run_id + self._artifact_uri = run.info.artifact_uri + self.start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + self.status = Recorder.STATUS_R + logger.info(f"Recorder {self.id} starts running under Experiment {self.experiment_id} ...") + + # NOTE: making logging async. + # - This may cause delay when uploading results + # - The logging time may not be accurate + self.async_log = AsyncCaller() + + # TODO: currently, this is only supported in MLflowRecorder. + # Maybe we can make this feature more general. + self._log_uncommitted_code() + + self.log_params(**{"cmd-sys.argv": " ".join(sys.argv)}) # log the command to produce current experiment + self.log_params( + **{k: v for k, v in os.environ.items() if k.startswith("_QLIB_")} + ) # Log necessary environment variables + return run + + def _log_uncommitted_code(self): + """ + Mlflow only log the commit id of the current repo. But usually, user will have a lot of uncommitted changes. + So this tries to automatically to log them all. + """ + # TODO: the sub-directories maybe git repos. + # So it will be better if we can walk the sub-directories and log the uncommitted changes. + for cmd, fname in [ + ("git diff", "code_diff.txt"), + ("git status", "code_status.txt"), + ("git diff --cached", "code_cached.txt"), + ]: + try: + out = subprocess.check_output(cmd, shell=True) + self.client.log_text(self.id, out.decode(), fname) # this behaves same as above + except subprocess.CalledProcessError: + logger.info(f"Fail to log the uncommitted code of $CWD({os.getcwd()}) when run {cmd}.") + + def end_run(self, status: str = Recorder.STATUS_S): + assert status in [ + Recorder.STATUS_S, + Recorder.STATUS_R, + Recorder.STATUS_FI, + Recorder.STATUS_FA, + ], f"The status type {status} is not supported." + self.end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + if self.status != Recorder.STATUS_S: + self.status = status + if self.async_log is not None: + # Waiting Queue should go before mlflow.end_run. Otherwise mlflow will raise error + with TimeInspector.logt("waiting `async_log`"): + self.async_log.wait() + self.async_log = None + mlflow.end_run(status) + + def save_objects(self, local_path=None, artifact_path=None, **kwargs): + assert self.uri is not None, "Please start the experiment and recorder first before using recorder directly." + if local_path is not None: + path = Path(local_path) + if path.is_dir(): + self.client.log_artifacts(self.id, local_path, artifact_path) + else: + self.client.log_artifact(self.id, local_path, artifact_path) + else: + temp_dir = Path(tempfile.mkdtemp()).resolve() + for name, data in kwargs.items(): + path = temp_dir / name + Serializable.general_dump(data, path) + self.client.log_artifact(self.id, temp_dir / name, artifact_path) + shutil.rmtree(temp_dir) + + def load_object(self, name, unpickler=pickle.Unpickler): + """ + Load object such as prediction file or model checkpoint in mlflow. + + Args: + name (str): the object name + + unpickler: Supporting using custom unpickler + + Raises: + LoadObjectError: if raise some exceptions when load the object + + Returns: + object: the saved object in mlflow. + """ + assert self.uri is not None, "Please start the experiment and recorder first before using recorder directly." + + path = None + try: + path = self.client.download_artifacts(self.id, name) + with Path(path).open("rb") as f: + data = unpickler(f).load() + return data + except Exception as e: + raise LoadObjectError(str(e)) from e + finally: + ar = self.client._tracking_client._get_artifact_repo(self.id) + if isinstance(ar, AzureBlobArtifactRepository) and path is not None: + # for saving disk space + # For safety, only remove redundant file for specific ArtifactRepository + shutil.rmtree(Path(path).absolute().parent) + + @AsyncCaller.async_dec(ac_attr="async_log") + def log_params(self, **kwargs): + for name, data in kwargs.items(): + self.client.log_param(self.id, name, data) + + @AsyncCaller.async_dec(ac_attr="async_log") + def log_metrics(self, step=None, **kwargs): + for name, data in kwargs.items(): + self.client.log_metric(self.id, name, data, step=step) + + def log_artifact(self, local_path, artifact_path: Optional[str] = None): + self.client.log_artifact(self.id, local_path=local_path, artifact_path=artifact_path) + + @AsyncCaller.async_dec(ac_attr="async_log") + def set_tags(self, **kwargs): + for name, data in kwargs.items(): + self.client.set_tag(self.id, name, data) + + def delete_tags(self, *keys): + for key in keys: + self.client.delete_tag(self.id, key) + + def get_artifact_uri(self): + if self.artifact_uri is not None: + return self.artifact_uri + else: + raise ValueError( + "Please make sure the recorder has been created and started properly before getting artifact uri." + ) + + def list_artifacts(self, artifact_path=None): + assert self.uri is not None, "Please start the experiment and recorder first before using recorder directly." + artifacts = self.client.list_artifacts(self.id, artifact_path) + return [art.path for art in artifacts] + + def download_artifact(self, path: str, dst_path: Optional[str] = None) -> str: + return self.client.download_artifacts(self.id, path, dst_path) + + def list_metrics(self): + run = self.client.get_run(self.id) + return run.data.metrics + + def list_params(self): + run = self.client.get_run(self.id) + return run.data.params + + def list_tags(self): + run = self.client.get_run(self.id) + return run.data.tags diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ea80d9b9a8d82c9b304cc07673f136685ea083 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/__init__.py @@ -0,0 +1,13 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Task related workflow is implemented in this folder + +A typical task workflow + +| Step | Description | +|-----------------------+------------------------------------------------| +| TaskGen | Generating tasks. | +| TaskManager(optional) | Manage generated tasks | +| run task | retrieve tasks from TaskManager and run tasks. | +""" diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/collect.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..bedbd96d2011f014f82391fa3c6f1c36858cc656 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/collect.py @@ -0,0 +1,258 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +Collector module can collect objects from everywhere and process them such as merging, grouping, averaging and so on. +""" + +from collections import defaultdict +from qlib.log import TimeInspector +from typing import Callable, Dict, Iterable, List +from qlib.log import get_module_logger +from qlib.utils.serial import Serializable +from qlib.utils.exceptions import LoadObjectError +from qlib.workflow import R +from qlib.workflow.exp import Experiment +from qlib.workflow.recorder import Recorder + + +class Collector(Serializable): + """The collector to collect different results""" + + pickle_backend = "dill" # use dill to dump user method + + def __init__(self, process_list=[]): + """ + Init Collector. + + Args: + process_list (list or Callable): the list of processors or the instance of a processor to process dict. + """ + if not isinstance(process_list, list): + process_list = [process_list] + self.process_list = process_list + + def collect(self) -> dict: + """ + Collect the results and return a dict like {key: things} + + Returns: + dict: the dict after collecting. + + For example: + + {"prediction": pd.Series} + + {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}} + + ... + """ + raise NotImplementedError(f"Please implement the `collect` method.") + + @staticmethod + def process_collect(collected_dict, process_list=[], *args, **kwargs) -> dict: + """ + Do a series of processing to the dict returned by collect and return a dict like {key: things} + For example, you can group and ensemble. + + Args: + collected_dict (dict): the dict return by `collect` + process_list (list or Callable): the list of processors or the instance of a processor to process dict. + The processor order is the same as the list order. + For example: [Group1(..., Ensemble1()), Group2(..., Ensemble2())] + + Returns: + dict: the dict after processing. + """ + if not isinstance(process_list, list): + process_list = [process_list] + result = {} + for artifact in collected_dict: + value = collected_dict[artifact] + for process in process_list: + if not callable(process): + raise NotImplementedError(f"{type(process)} is not supported in `process_collect`.") + value = process(value, *args, **kwargs) + result[artifact] = value + return result + + def __call__(self, *args, **kwargs) -> dict: + """ + Do the workflow including ``collect`` and ``process_collect`` + + Returns: + dict: the dict after collecting and processing. + """ + collected = self.collect() + return self.process_collect(collected, self.process_list, *args, **kwargs) + + +class MergeCollector(Collector): + """ + A collector to collect the results of other Collectors + + For example: + + We have 2 collector, which named A and B. + A can collect {"prediction": pd.Series} and B can collect {"IC": {"Xgboost": pd.Series, "LSTM": pd.Series}}. + Then after this class's collect, we can collect {"A_prediction": pd.Series, "B_IC": {"Xgboost": pd.Series, "LSTM": pd.Series}} + + ... + + """ + + def __init__(self, collector_dict: Dict[str, Collector], process_list: List[Callable] = [], merge_func=None): + """ + Init MergeCollector. + + Args: + collector_dict (Dict[str,Collector]): the dict like {collector_key, Collector} + process_list (List[Callable]): the list of processors or the instance of processor to process dict. + merge_func (Callable): a method to generate outermost key. The given params are ``collector_key`` from collector_dict and ``key`` from every collector after collecting. + None for using tuple to connect them, such as "ABC"+("a","b") -> ("ABC", ("a","b")). + """ + super().__init__(process_list=process_list) + self.collector_dict = collector_dict + self.merge_func = merge_func + + def collect(self) -> dict: + """ + Collect all results of collector_dict and change the outermost key to a recombination key. + + Returns: + dict: the dict after collecting. + """ + collect_dict = {} + for collector_key, collector in self.collector_dict.items(): + tmp_dict = collector() + for key, value in tmp_dict.items(): + if self.merge_func is not None: + collect_dict[self.merge_func(collector_key, key)] = value + else: + collect_dict[(collector_key, key)] = value + return collect_dict + + +class RecorderCollector(Collector): + ART_KEY_RAW = "__raw" + + def __init__( + self, + experiment, + process_list=[], + rec_key_func=None, + rec_filter_func=None, + artifacts_path={"pred": "pred.pkl"}, + artifacts_key=None, + list_kwargs={}, + status: Iterable = {Recorder.STATUS_FI}, + ): + """ + Init RecorderCollector. + + Args: + experiment: + (Experiment or str): an instance of an Experiment or the name of an Experiment + (Callable): an callable function, which returns a list of experiments + process_list (list or Callable): the list of processors or the instance of a processor to process dict. + rec_key_func (Callable): a function to get the key of a recorder. If None, use recorder id. + rec_filter_func (Callable, optional): filter the recorder by return True or False. Defaults to None. + artifacts_path (dict, optional): The artifacts name and its path in Recorder. Defaults to {"pred": "pred.pkl", "IC": "sig_analysis/ic.pkl"}. + artifacts_key (str or List, optional): the artifacts key you want to get. If None, get all artifacts. + list_kwargs (str): arguments for list_recorders function. + status (Iterable): only collect recorders with specific status. None indicating collecting all the recorders + """ + super().__init__(process_list=process_list) + if isinstance(experiment, str): + experiment = R.get_exp(experiment_name=experiment) + assert isinstance(experiment, (Experiment, Callable)) + self.experiment = experiment + self.artifacts_path = artifacts_path + if rec_key_func is None: + + def rec_key_func(rec): + return rec.info["id"] + + if artifacts_key is None: + artifacts_key = list(self.artifacts_path.keys()) + self.rec_key_func = rec_key_func + self.artifacts_key = artifacts_key + self.rec_filter_func = rec_filter_func + self.list_kwargs = list_kwargs + self.status = status + + def collect(self, artifacts_key=None, rec_filter_func=None, only_exist=True) -> dict: + """ + Collect different artifacts based on recorder after filtering. + + Args: + artifacts_key (str or List, optional): the artifacts key you want to get. If None, use the default. + rec_filter_func (Callable, optional): filter the recorder by return True or False. If None, use the default. + only_exist (bool, optional): if only collect the artifacts when a recorder really has. + If True, the recorder with exception when loading will not be collected. But if False, it will raise the exception. + + Returns: + dict: the dict after collected like {artifact: {rec_key: object}} + """ + if artifacts_key is None: + artifacts_key = self.artifacts_key + if rec_filter_func is None: + rec_filter_func = self.rec_filter_func + + if isinstance(artifacts_key, str): + artifacts_key = [artifacts_key] + + collect_dict = {} + # filter records + + if isinstance(self.experiment, Experiment): + with TimeInspector.logt("Time to `list_recorders` in RecorderCollector"): + recs = list(self.experiment.list_recorders(**self.list_kwargs).values()) + elif isinstance(self.experiment, Callable): + recs = self.experiment() + + recs = [ + rec + for rec in recs + if ( + (self.status is None or rec.status in self.status) and (rec_filter_func is None or rec_filter_func(rec)) + ) + ] + + logger = get_module_logger("RecorderCollector") + status_stat = defaultdict(int) + for r in recs: + status_stat[r.status] += 1 + logger.info(f"Nubmer of recorders after filter: {status_stat}") + for rec in recs: + rec_key = self.rec_key_func(rec) + for key in artifacts_key: + if self.ART_KEY_RAW == key: + artifact = rec + else: + try: + artifact = rec.load_object(self.artifacts_path[key]) + except LoadObjectError as e: + if only_exist: + # only collect existing artifact + logger.warning(f"Fail to load {self.artifacts_path[key]} and it is ignored.") + continue + raise e + # give user some warning if the values are overridden + cdd = collect_dict.setdefault(key, {}) + if rec_key in cdd: + logger.warning( + f"key '{rec_key}' is duplicated. Previous value will be overrides. Please check you `rec_key_func`" + ) + cdd[rec_key] = artifact + + return collect_dict + + def get_exp_name(self) -> str: + """ + Get experiment name + + Returns: + str: experiment name + """ + return self.experiment.name diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/gen.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/gen.py new file mode 100644 index 0000000000000000000000000000000000000000..cf95e60063323137772601a41c3f83cc43e77405 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/gen.py @@ -0,0 +1,350 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +TaskGenerator module can generate many tasks based on TaskGen and some task templates. +""" + +import abc +import copy +import pandas as pd +from typing import Dict, List, Union, Callable + +from qlib.utils import transform_end_date +from .utils import TimeAdjuster + + +def task_generator(tasks, generators) -> list: + """ + Use a list of TaskGen and a list of task templates to generate different tasks. + + For examples: + + There are 3 task templates a,b,c and 2 TaskGen A,B. A will generates 2 tasks from a template and B will generates 3 tasks from a template. + task_generator([a, b, c], [A, B]) will finally generate 3*2*3 = 18 tasks. + + Parameters + ---------- + tasks : List[dict] or dict + a list of task templates or a single task + generators : List[TaskGen] or TaskGen + a list of TaskGen or a single TaskGen + + Returns + ------- + list + a list of tasks + """ + + if isinstance(tasks, dict): + tasks = [tasks] + if isinstance(generators, TaskGen): + generators = [generators] + + # generate gen_task_list + for gen in generators: + new_task_list = [] + for task in tasks: + new_task_list.extend(gen.generate(task)) + tasks = new_task_list + + return tasks + + +class TaskGen(metaclass=abc.ABCMeta): + """ + The base class for generating different tasks + + Example 1: + + input: a specific task template and rolling steps + + output: rolling version of the tasks + + Example 2: + + input: a specific task template and losses list + + output: a set of tasks with different losses + + """ + + @abc.abstractmethod + def generate(self, task: dict) -> List[dict]: + """ + Generate different tasks based on a task template + + Parameters + ---------- + task: dict + a task template + + Returns + ------- + typing.List[dict]: + A list of tasks + """ + + def __call__(self, *args, **kwargs): + """ + This is just a syntactic sugar for generate + """ + return self.generate(*args, **kwargs) + + +def handler_mod(task: dict, rolling_gen): + """ + Help to modify the handler end time when using RollingGen + It try to handle the following case + + - Hander's data end_time is earlier than dataset's test_data's segments. + + - To handle this, handler's data's end_time is extended. + + If the handler's end_time is None, then it is not necessary to change it's end time. + + Args: + task (dict): a task template + rg (RollingGen): an instance of RollingGen + """ + try: + handler_kwargs = task["dataset"]["kwargs"]["handler"]["kwargs"] + handler_end_time = handler_kwargs.get("end_time") + test_seg_end_time = task["dataset"]["kwargs"]["segments"][rolling_gen.test_key][1] + # if the end of test_segments is None (open-ended segment, i.e., "until now") or end_time < the end of test_segments, + # then change end_time to allow load more data + if test_seg_end_time is None or rolling_gen.ta.cal_interval(handler_end_time, test_seg_end_time) < 0: + handler_kwargs["end_time"] = copy.deepcopy(test_seg_end_time) + except KeyError: + # Maybe dataset do not have handler, then do nothing. + pass + except TypeError: + # May be the handler is a string. `"handler.pkl"["kwargs"]` will raise TypeError + # e.g. a dumped file like file://// + pass + + +def trunc_segments(ta: TimeAdjuster, segments: Dict[str, pd.Timestamp], days, test_key="test"): + """ + To avoid the leakage of future information, the segments should be truncated according to the test start_time + + NOTE: + This function will change segments **inplace** + """ + # adjust segment + test_start = min(t for t in segments[test_key] if t is not None) + for k in list(segments.keys()): + if k != test_key: + segments[k] = ta.truncate(segments[k], test_start, days) + + +class RollingGen(TaskGen): + ROLL_EX = TimeAdjuster.SHIFT_EX # fixed start date, expanding end date + ROLL_SD = TimeAdjuster.SHIFT_SD # fixed segments size, slide it from start date + + def __init__( + self, + step: int = 40, + rtype: str = ROLL_EX, + ds_extra_mod_func: Union[None, Callable] = handler_mod, + test_key="test", + train_key="train", + trunc_days: int = None, + task_copy_func: Callable = copy.deepcopy, + ): + """ + Generate tasks for rolling + + Parameters + ---------- + step : int + step to rolling + rtype : str + rolling type (expanding, sliding) + ds_extra_mod_func: Callable + A method like: handler_mod(task: dict, rg: RollingGen) + Do some extra action after generating a task. For example, use ``handler_mod`` to modify the end time of the handler of a dataset. + trunc_days: int + trunc some data to avoid future information leakage + task_copy_func: Callable + the function to copy entire task. This is very useful when user want to share something between tasks + """ + self.step = step + self.rtype = rtype + self.ds_extra_mod_func = ds_extra_mod_func + self.ta = TimeAdjuster(future=True) + + self.test_key = test_key + self.train_key = train_key + self.trunc_days = trunc_days + self.task_copy_func = task_copy_func + + def _update_task_segs(self, task, segs): + # update segments of this task + task["dataset"]["kwargs"]["segments"] = copy.deepcopy(segs) + if self.ds_extra_mod_func is not None: + self.ds_extra_mod_func(task, self) + + def gen_following_tasks(self, task: dict, test_end: pd.Timestamp) -> List[dict]: + """ + generating following rolling tasks for `task` until test_end + + Parameters + ---------- + task : dict + Qlib task format + test_end : pd.Timestamp + the latest rolling task includes `test_end` + + Returns + ------- + List[dict]: + the following tasks of `task`(`task` itself is excluded) + """ + prev_seg = task["dataset"]["kwargs"]["segments"] + while True: + segments = {} + try: + for k, seg in prev_seg.items(): + # decide how to shift + # expanding only for train data, the segments size of test data and valid data won't change + if k == self.train_key and self.rtype == self.ROLL_EX: + rtype = self.ta.SHIFT_EX + else: + rtype = self.ta.SHIFT_SD + # shift the segments data + segments[k] = self.ta.shift(seg, step=self.step, rtype=rtype) + if segments[self.test_key][0] > test_end: + break + except KeyError: + # We reach the end of tasks + # No more rolling + break + + prev_seg = segments + t = self.task_copy_func(task) # deepcopy is necessary to avoid replace task inplace + self._update_task_segs(t, segments) + yield t + + def generate(self, task: dict) -> List[dict]: + """ + Converting the task into a rolling task. + + Parameters + ---------- + task: dict + A dict describing a task. For example. + + .. code-block:: python + + DEFAULT_TASK = { + "model": { + "class": "LGBModel", + "module_path": "qlib.contrib.model.gbdt", + }, + "dataset": { + "class": "DatasetH", + "module_path": "qlib.data.dataset", + "kwargs": { + "handler": { + "class": "Alpha158", + "module_path": "qlib.contrib.data.handler", + "kwargs": { + "start_time": "2008-01-01", + "end_time": "2020-08-01", + "fit_start_time": "2008-01-01", + "fit_end_time": "2014-12-31", + "instruments": "csi100", + }, + }, + "segments": { + "train": ("2008-01-01", "2014-12-31"), + "valid": ("2015-01-01", "2016-12-20"), # Please avoid leaking the future test data into validation + "test": ("2017-01-01", "2020-08-01"), + }, + }, + }, + "record": [ + { + "class": "SignalRecord", + "module_path": "qlib.workflow.record_temp", + }, + ] + } + + Returns + ---------- + List[dict]: a list of tasks + """ + res = [] + + t = self.task_copy_func(task) + + # calculate segments + + # First rolling + # 1) prepare the end point + segments: dict = copy.deepcopy(self.ta.align_seg(t["dataset"]["kwargs"]["segments"])) + test_end = transform_end_date(segments[self.test_key][1]) + # 2) and init test segments + test_start_idx = self.ta.align_idx(segments[self.test_key][0]) + segments[self.test_key] = (self.ta.get(test_start_idx), self.ta.get(test_start_idx + self.step - 1)) + if self.trunc_days is not None: + trunc_segments(self.ta, segments, self.trunc_days, self.test_key) + + # update segments of this task + self._update_task_segs(t, segments) + + res.append(t) + + # Update the following rolling + res.extend(self.gen_following_tasks(t, test_end)) + return res + + +class MultiHorizonGenBase(TaskGen): + def __init__(self, horizon: List[int] = [5], label_leak_n=2): + """ + This task generator tries to generate tasks for different horizons based on an existing task + + Parameters + ---------- + horizon : List[int] + the possible horizons of the tasks + label_leak_n : int + How many future days it will take to get complete label after the day making prediction + For example: + - User make prediction on day `T`(after getting the close price on `T`) + - The label is the return of buying stock on `T + 1` and selling it on `T + 2` + - the `label_leak_n` will be 2 (e.g. two days of information is leaked to leverage this sample) + """ + self.horizon = list(horizon) + self.label_leak_n = label_leak_n + self.ta = TimeAdjuster() + self.test_key = "test" + + @abc.abstractmethod + def set_horizon(self, task: dict, hr: int): + """ + This method is designed to change the task **in place** + + Parameters + ---------- + task : dict + Qlib's task + hr : int + the horizon of task + """ + + def generate(self, task: dict): + res = [] + for hr in self.horizon: + # Add horizon + t = copy.deepcopy(task) + self.set_horizon(t, hr) + + # adjust segment + segments = self.ta.align_seg(t["dataset"]["kwargs"]["segments"]) + trunc_segments(self.ta, segments, days=hr + self.label_leak_n, test_key=self.test_key) + t["dataset"]["kwargs"]["segments"] = segments + res.append(t) + return res diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/manage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/manage.py new file mode 100644 index 0000000000000000000000000000000000000000..df29f3550085148132456b43f92eafaf93d889fd --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/manage.py @@ -0,0 +1,558 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +""" +TaskManager can fetch unused tasks automatically and manage the lifecycle of a set of tasks with error handling. +These features can run tasks concurrently and ensure every task will be used only once. +Task Manager will store all tasks in `MongoDB `_. +Users **MUST** finished the configuration of `MongoDB `_ when using this module. + +A task in TaskManager consists of 3 parts +- tasks description: the desc will define the task +- tasks status: the status of the task +- tasks result: A user can get the task with the task description and task result. +""" + +import concurrent +import pickle +import time +from contextlib import contextmanager +from typing import Callable, List + +import fire +import pymongo +from bson.binary import Binary +from bson.objectid import ObjectId +from pymongo.errors import InvalidDocument +from qlib import auto_init, get_module_logger +from tqdm.cli import tqdm + +from .utils import get_mongodb +from ...config import C +from ...utils.pickle_utils import restricted_pickle_loads + + +class TaskManager: + """ + TaskManager + + Here is what will a task looks like when it created by TaskManager + + .. code-block:: python + + { + 'def': pickle serialized task definition. using pickle will make it easier + 'filter': json-like data. This is for filtering the tasks. + 'status': 'waiting' | 'running' | 'done' + 'res': pickle serialized task result, + } + + The tasks manager assumes that you will only update the tasks you fetched. + The mongo fetch one and update will make it date updating secure. + + This class can be used as a tool from commandline. Here are several examples. + You can view the help of manage module with the following commands: + python -m qlib.workflow.task.manage -h # show manual of manage module CLI + python -m qlib.workflow.task.manage wait -h # show manual of the wait command of manage + + .. code-block:: shell + + python -m qlib.workflow.task.manage -t wait + python -m qlib.workflow.task.manage -t task_stat + + + .. note:: + + Assumption: the data in MongoDB was encoded and the data out of MongoDB was decoded + + Here are four status which are: + + STATUS_WAITING: waiting for training + + STATUS_RUNNING: training + + STATUS_PART_DONE: finished some step and waiting for next step + + STATUS_DONE: all work done + """ + + STATUS_WAITING = "waiting" + STATUS_RUNNING = "running" + STATUS_DONE = "done" + STATUS_PART_DONE = "part_done" + + ENCODE_FIELDS_PREFIX = ["def", "res"] + + def __init__(self, task_pool: str): + """ + Init Task Manager, remember to make the statement of MongoDB url and database name firstly. + A TaskManager instance serves a specific task pool. + The static method of this module serves the whole MongoDB. + + Parameters + ---------- + task_pool: str + the name of Collection in MongoDB + """ + self.task_pool: pymongo.collection.Collection = getattr(get_mongodb(), task_pool) + self.logger = get_module_logger(self.__class__.__name__) + self.logger.info(f"task_pool:{task_pool}") + + @staticmethod + def list() -> list: + """ + List the all collection(task_pool) of the db. + + Returns: + list + """ + return get_mongodb().list_collection_names() + + def _encode_task(self, task): + for prefix in self.ENCODE_FIELDS_PREFIX: + for k in list(task.keys()): + if k.startswith(prefix): + task[k] = Binary(pickle.dumps(task[k], protocol=C.dump_protocol_version)) + return task + + def _decode_task(self, task): + """ + _decode_task is Serialization tool. + Mongodb needs JSON, so it needs to convert Python objects into JSON objects through pickle + + Parameters + ---------- + task : dict + task information + + Returns + ------- + dict + JSON required by mongodb + """ + for prefix in self.ENCODE_FIELDS_PREFIX: + for k in list(task.keys()): + if k.startswith(prefix): + task[k] = restricted_pickle_loads(task[k]) + return task + + def _dict_to_str(self, flt): + return {k: str(v) for k, v in flt.items()} + + def _decode_query(self, query): + """ + If the query includes any `_id`, then it needs `ObjectId` to decode. + For example, when using TrainerRM, it needs query `{"_id": {"$in": _id_list}}`. Then we need to `ObjectId` every `_id` in `_id_list`. + + Args: + query (dict): query dict. Defaults to {}. + + Returns: + dict: the query after decoding. + """ + if "_id" in query: + if isinstance(query["_id"], dict): + for key in query["_id"]: + query["_id"][key] = [ObjectId(i) for i in query["_id"][key]] + else: + query["_id"] = ObjectId(query["_id"]) + return query + + def replace_task(self, task, new_task): + """ + Use a new task to replace a old one + + Args: + task: old task + new_task: new task + """ + new_task = self._encode_task(new_task) + query = {"_id": ObjectId(task["_id"])} + try: + self.task_pool.replace_one(query, new_task) + except InvalidDocument: + task["filter"] = self._dict_to_str(task["filter"]) + self.task_pool.replace_one(query, new_task) + + def insert_task(self, task): + """ + Insert a task. + + Args: + task: the task waiting for insert + + Returns: + pymongo.results.InsertOneResult + """ + try: + insert_result = self.task_pool.insert_one(task) + except InvalidDocument: + task["filter"] = self._dict_to_str(task["filter"]) + insert_result = self.task_pool.insert_one(task) + return insert_result + + def insert_task_def(self, task_def): + """ + Insert a task to task_pool + + Parameters + ---------- + task_def: dict + the task definition + + Returns + ------- + pymongo.results.InsertOneResult + """ + task = self._encode_task( + { + "def": task_def, + "filter": task_def, # FIXME: catch the raised error + "status": self.STATUS_WAITING, + } + ) + insert_result = self.insert_task(task) + return insert_result + + def create_task(self, task_def_l, dry_run=False, print_nt=False) -> List[str]: + """ + If the tasks in task_def_l are new, then insert new tasks into the task_pool, and record inserted_id. + If a task is not new, then just query its _id. + + Parameters + ---------- + task_def_l: list + a list of task + dry_run: bool + if insert those new tasks to task pool + print_nt: bool + if print new task + + Returns + ------- + List[str] + a list of the _id of task_def_l + """ + new_tasks = [] + _id_list = [] + for t in task_def_l: + try: + r = self.task_pool.find_one({"filter": t}) + except InvalidDocument: + r = self.task_pool.find_one({"filter": self._dict_to_str(t)}) + # When r is none, it indicates that r s a new task + if r is None: + new_tasks.append(t) + if not dry_run: + insert_result = self.insert_task_def(t) + _id_list.append(insert_result.inserted_id) + else: + _id_list.append(None) + else: + _id_list.append(self._decode_task(r)["_id"]) + + self.logger.info(f"Total Tasks: {len(task_def_l)}, New Tasks: {len(new_tasks)}") + + if print_nt: # print new task + for t in new_tasks: + print(t) + + if dry_run: + return [] + + return _id_list + + def fetch_task(self, query={}, status=STATUS_WAITING) -> dict: + """ + Use query to fetch tasks. + + Args: + query (dict, optional): query dict. Defaults to {}. + status (str, optional): [description]. Defaults to STATUS_WAITING. + + Returns: + dict: a task(document in collection) after decoding + """ + query = query.copy() + query = self._decode_query(query) + query.update({"status": status}) + task = self.task_pool.find_one_and_update( + query, {"$set": {"status": self.STATUS_RUNNING}}, sort=[("priority", pymongo.DESCENDING)] + ) + # null will be at the top after sorting when using ASCENDING, so the larger the number higher, the higher the priority + if task is None: + return None + task["status"] = self.STATUS_RUNNING + return self._decode_task(task) + + @contextmanager + def safe_fetch_task(self, query={}, status=STATUS_WAITING): + """ + Fetch task from task_pool using query with contextmanager + + Parameters + ---------- + query: dict + the dict of query + + Returns + ------- + dict: a task(document in collection) after decoding + """ + task = self.fetch_task(query=query, status=status) + try: + yield task + except (Exception, KeyboardInterrupt): # KeyboardInterrupt is not a subclass of Exception + if task is not None: + self.logger.info("Returning task before raising error") + self.return_task(task, status=status) # return task as the original status + self.logger.info("Task returned") + raise + + def task_fetcher_iter(self, query={}): + while True: + with self.safe_fetch_task(query=query) as task: + if task is None: + break + yield task + + def query(self, query={}, decode=True): + """ + Query task in collection. + This function may raise exception `pymongo.errors.CursorNotFound: cursor id not found` if it takes too long to iterate the generator + + python -m qlib.workflow.task.manage -t query '{"_id": "615498be837d0053acbc5d58"}' + + Parameters + ---------- + query: dict + the dict of query + decode: bool + + Returns + ------- + dict: a task(document in collection) after decoding + """ + query = query.copy() + query = self._decode_query(query) + for t in self.task_pool.find(query): + yield self._decode_task(t) + + def re_query(self, _id) -> dict: + """ + Use _id to query task. + + Args: + _id (str): _id of a document + + Returns: + dict: a task(document in collection) after decoding + """ + t = self.task_pool.find_one({"_id": ObjectId(_id)}) + return self._decode_task(t) + + def commit_task_res(self, task, res, status=STATUS_DONE): + """ + Commit the result to task['res']. + + Args: + task ([type]): [description] + res (object): the result you want to save + status (str, optional): STATUS_WAITING, STATUS_RUNNING, STATUS_DONE, STATUS_PART_DONE. Defaults to STATUS_DONE. + """ + # A workaround to use the class attribute. + if status is None: + status = TaskManager.STATUS_DONE + self.task_pool.update_one( + {"_id": task["_id"]}, + {"$set": {"status": status, "res": Binary(pickle.dumps(res, protocol=C.dump_protocol_version))}}, + ) + + def return_task(self, task, status=STATUS_WAITING): + """ + Return a task to status. Always using in error handling. + + Args: + task ([type]): [description] + status (str, optional): STATUS_WAITING, STATUS_RUNNING, STATUS_DONE, STATUS_PART_DONE. Defaults to STATUS_WAITING. + """ + if status is None: + status = TaskManager.STATUS_WAITING + update_dict = {"$set": {"status": status}} + self.task_pool.update_one({"_id": task["_id"]}, update_dict) + + def remove(self, query={}): + """ + Remove the task using query + + Parameters + ---------- + query: dict + the dict of query + + """ + query = query.copy() + query = self._decode_query(query) + self.task_pool.delete_many(query) + + def task_stat(self, query={}) -> dict: + """ + Count the tasks in every status. + + Args: + query (dict, optional): the query dict. Defaults to {}. + + Returns: + dict + """ + query = query.copy() + query = self._decode_query(query) + tasks = self.query(query=query, decode=False) + status_stat = {} + for t in tasks: + status_stat[t["status"]] = status_stat.get(t["status"], 0) + 1 + return status_stat + + def reset_waiting(self, query={}): + """ + Reset all running task into waiting status. Can be used when some running task exit unexpected. + + Args: + query (dict, optional): the query dict. Defaults to {}. + """ + query = query.copy() + # default query + if "status" not in query: + query["status"] = self.STATUS_RUNNING + return self.reset_status(query=query, status=self.STATUS_WAITING) + + def reset_status(self, query, status): + query = query.copy() + query = self._decode_query(query) + print(self.task_pool.update_many(query, {"$set": {"status": status}})) + + def prioritize(self, task, priority: int): + """ + Set priority for task + + Parameters + ---------- + task : dict + The task query from the database + priority : int + the target priority + """ + update_dict = {"$set": {"priority": priority}} + self.task_pool.update_one({"_id": task["_id"]}, update_dict) + + def _get_undone_n(self, task_stat): + return ( + task_stat.get(self.STATUS_WAITING, 0) + + task_stat.get(self.STATUS_RUNNING, 0) + + task_stat.get(self.STATUS_PART_DONE, 0) + ) + + def _get_total(self, task_stat): + return sum(task_stat.values()) + + def wait(self, query={}): + """ + When multiprocessing, the main progress may fetch nothing from TaskManager because there are still some running tasks. + So main progress should wait until all tasks are trained well by other progress or machines. + + Args: + query (dict, optional): the query dict. Defaults to {}. + """ + task_stat = self.task_stat(query) + total = self._get_total(task_stat) + last_undone_n = self._get_undone_n(task_stat) + if last_undone_n == 0: + return + self.logger.warning(f"Waiting for {last_undone_n} undone tasks. Please make sure they are running.") + with tqdm(total=total, initial=total - last_undone_n) as pbar: + while True: + time.sleep(10) + undone_n = self._get_undone_n(self.task_stat(query)) + pbar.update(last_undone_n - undone_n) + last_undone_n = undone_n + if undone_n == 0: + break + + def __str__(self): + return f"TaskManager({self.task_pool})" + + +def run_task( + task_func: Callable, + task_pool: str, + query: dict = {}, + force_release: bool = False, + before_status: str = TaskManager.STATUS_WAITING, + after_status: str = TaskManager.STATUS_DONE, + **kwargs, +): + r""" + While the task pool is not empty (has WAITING tasks), use task_func to fetch and run tasks in task_pool + + After running this method, here are 4 situations (before_status -> after_status): + + STATUS_WAITING -> STATUS_DONE: use task["def"] as `task_func` param, it means that the task has not been started + + STATUS_WAITING -> STATUS_PART_DONE: use task["def"] as `task_func` param + + STATUS_PART_DONE -> STATUS_PART_DONE: use task["res"] as `task_func` param, it means that the task has been started but not completed + + STATUS_PART_DONE -> STATUS_DONE: use task["res"] as `task_func` param + + Parameters + ---------- + task_func : Callable + def (task_def, \**kwargs) -> + + the function to run the task + task_pool : str + the name of the task pool (Collection in MongoDB) + query: dict + will use this dict to query task_pool when fetching task + force_release : bool + will the program force to release the resource + before_status : str: + the tasks in before_status will be fetched and trained. Can be STATUS_WAITING, STATUS_PART_DONE. + after_status : str: + the tasks after trained will become after_status. Can be STATUS_WAITING, STATUS_PART_DONE. + kwargs + the params for `task_func` + """ + tm = TaskManager(task_pool) + + ever_run = False + + while True: + with tm.safe_fetch_task(status=before_status, query=query) as task: + if task is None: + break + get_module_logger("run_task").info(task["def"]) + # when fetching `WAITING` task, use task["def"] to train + if before_status == TaskManager.STATUS_WAITING: + param = task["def"] + # when fetching `PART_DONE` task, use task["res"] to train because the middle result has been saved to task["res"] + elif before_status == TaskManager.STATUS_PART_DONE: + param = task["res"] + else: + raise ValueError("The fetched task must be `STATUS_WAITING` or `STATUS_PART_DONE`!") + if force_release: + with concurrent.futures.ProcessPoolExecutor(max_workers=1) as executor: + res = executor.submit(task_func, param, **kwargs).result() + else: + res = task_func(param, **kwargs) + tm.commit_task_res(task, res, status=after_status) + ever_run = True + + return ever_run + + +if __name__ == "__main__": + # This is for using it in cmd + # E.g. : `python -m qlib.workflow.task.manage list` + auto_init() + fire.Fire(TaskManager) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4a7c06b8edbad70b61a756f8efbac27080643e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/task/utils.py @@ -0,0 +1,308 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +Some tools for task management. +""" + +import bisect +from copy import deepcopy +import pandas as pd +from qlib.data import D +from qlib.utils import hash_args +from qlib.utils.mod import init_instance_by_config +from qlib.workflow import R +from qlib.config import C +from qlib.log import get_module_logger +from pymongo import MongoClient +from pymongo.database import Database +from typing import Union +from pathlib import Path + + +def get_mongodb() -> Database: + """ + Get database in MongoDB, which means you need to declare the address and the name of a database at first. + + For example: + + Using qlib.init(): + + .. code-block:: python + + mongo_conf = { + "task_url": task_url, # your MongoDB url + "task_db_name": task_db_name, # database name + } + qlib.init(..., mongo=mongo_conf) + + After qlib.init(): + + .. code-block:: python + + C["mongo"] = { + "task_url" : "mongodb://localhost:27017/", + "task_db_name" : "rolling_db" + } + + Returns: + Database: the Database instance + """ + try: + cfg = C["mongo"] + except KeyError: + get_module_logger("task").error("Please configure `C['mongo']` before using TaskManager") + raise + get_module_logger("task").info(f"mongo config:{cfg}") + client = MongoClient(cfg["task_url"]) + return client.get_database(name=cfg["task_db_name"]) + + +def list_recorders(experiment, rec_filter_func=None): + """ + List all recorders which can pass the filter in an experiment. + + Args: + experiment (str or Experiment): the name of an Experiment or an instance + rec_filter_func (Callable, optional): return True to retain the given recorder. Defaults to None. + + Returns: + dict: a dict {rid: recorder} after filtering. + """ + if isinstance(experiment, str): + experiment = R.get_exp(experiment_name=experiment) + recs = experiment.list_recorders() + recs_flt = {} + for rid, rec in recs.items(): + if rec_filter_func is None or rec_filter_func(rec): + recs_flt[rid] = rec + + return recs_flt + + +class TimeAdjuster: + """ + Find appropriate date and adjust date. + """ + + def __init__(self, future=True, end_time=None): + self._future = future + self.cals = D.calendar(future=future, end_time=end_time) + + def set_end_time(self, end_time=None): + """ + Set end time. None for use calendar's end time. + + Args: + end_time + """ + self.cals = D.calendar(future=self._future, end_time=end_time) + + def get(self, idx: int): + """ + Get datetime by index. + + Parameters + ---------- + idx : int + index of the calendar + """ + if idx is None or idx >= len(self.cals): + return None + return self.cals[idx] + + def max(self) -> pd.Timestamp: + """ + Return the max calendar datetime + """ + return max(self.cals) + + def align_idx(self, time_point, tp_type="start") -> int: + """ + Align the index of time_point in the calendar. + + Parameters + ---------- + time_point + tp_type : str + + Returns + ------- + index : int + """ + if time_point is None: + # `None` indicates unbounded index/boarder + return None + time_point = pd.Timestamp(time_point) + if tp_type == "start": + idx = bisect.bisect_left(self.cals, time_point) + elif tp_type == "end": + idx = bisect.bisect_right(self.cals, time_point) - 1 + else: + raise NotImplementedError(f"This type of input is not supported") + return idx + + def cal_interval(self, time_point_A, time_point_B) -> int: + """ + Calculate the trading day interval (time_point_A - time_point_B) + + Args: + time_point_A : time_point_A + time_point_B : time_point_B (is the past of time_point_A) + + Returns: + int: the interval between A and B + """ + return self.align_idx(time_point_A) - self.align_idx(time_point_B) + + def align_time(self, time_point, tp_type="start") -> pd.Timestamp: + """ + Align time_point to trade date of calendar + + Args: + time_point + Time point + tp_type : str + time point type (`"start"`, `"end"`) + + Returns: + pd.Timestamp + """ + if time_point is None: + return None + return self.cals[self.align_idx(time_point, tp_type=tp_type)] + + def align_seg(self, segment: Union[dict, tuple]) -> Union[dict, tuple]: + """ + Align the given date to the trade date + + for example: + + .. code-block:: python + + input: {'train': ('2008-01-01', '2014-12-31'), 'valid': ('2015-01-01', '2016-12-31'), 'test': ('2017-01-01', '2020-08-01')} + + output: {'train': (Timestamp('2008-01-02 00:00:00'), Timestamp('2014-12-31 00:00:00')), + 'valid': (Timestamp('2015-01-05 00:00:00'), Timestamp('2016-12-30 00:00:00')), + 'test': (Timestamp('2017-01-03 00:00:00'), Timestamp('2020-07-31 00:00:00'))} + + Parameters + ---------- + segment + + Returns + ------- + Union[dict, tuple]: the start and end trade date (pd.Timestamp) between the given start and end date. + """ + if isinstance(segment, dict): + return {k: self.align_seg(seg) for k, seg in segment.items()} + elif isinstance(segment, (tuple, list)): + return self.align_time(segment[0], tp_type="start"), self.align_time(segment[1], tp_type="end") + else: + raise NotImplementedError(f"This type of input is not supported") + + def truncate(self, segment: tuple, test_start, days: int) -> tuple: + """ + Truncate the segment based on the test_start date + + Parameters + ---------- + segment : tuple + time segment + test_start + days : int + The trading days to be truncated + the data in this segment may need 'days' data + `days` are based on the `test_start`. + For example, if the label contains the information of 2 days in the near future, the prediction horizon 1 day. + (e.g. the prediction target is `Ref($close, -2)/Ref($close, -1) - 1`) + the days should be 2 + 1 == 3 days. + + Returns + --------- + tuple: new segment + """ + test_idx = self.align_idx(test_start) + if isinstance(segment, tuple): + new_seg = [] + for time_point in segment: + tp_idx = min(self.align_idx(time_point), test_idx - days) + assert tp_idx > 0 + new_seg.append(self.get(tp_idx)) + return tuple(new_seg) + else: + raise NotImplementedError(f"This type of input is not supported") + + SHIFT_SD = "sliding" + SHIFT_EX = "expanding" + + def _add_step(self, index, step): + if index is None: + return None + return index + step + + def shift(self, seg: tuple, step: int, rtype=SHIFT_SD) -> tuple: + """ + Shift the datetime of segment + + If there are None (which indicates unbounded index) in the segment, this method will return None. + + Parameters + ---------- + seg : + datetime segment + step : int + rolling step + rtype : str + rolling type ("sliding" or "expanding") + + Returns + -------- + tuple: new segment + + Raises + ------ + KeyError: + shift will raise error if the index(both start and end) is out of self.cal + """ + if isinstance(seg, tuple): + start_idx, end_idx = self.align_idx(seg[0], tp_type="start"), self.align_idx(seg[1], tp_type="end") + if rtype == self.SHIFT_SD: + start_idx = self._add_step(start_idx, step) + end_idx = self._add_step(end_idx, step) + elif rtype == self.SHIFT_EX: + end_idx = self._add_step(end_idx, step) + else: + raise NotImplementedError(f"This type of input is not supported") + if start_idx is not None and start_idx > len(self.cals): + raise KeyError("The segment is out of valid calendar") + return self.get(start_idx), self.get(end_idx) + else: + raise NotImplementedError(f"This type of input is not supported") + + +def replace_task_handler_with_cache(task: dict, cache_dir: Union[str, Path] = ".") -> dict: + """ + Replace the handler in task with a cache handler. + It will automatically cache the file and save it in cache_dir. + + >>> import qlib + >>> qlib.auto_init() + >>> import datetime + >>> # it is simplified task + >>> task = {"dataset": {"kwargs":{'handler': {'class': 'Alpha158', 'module_path': 'qlib.contrib.data.handler', 'kwargs': {'start_time': datetime.date(2008, 1, 1), 'end_time': datetime.date(2020, 8, 1), 'fit_start_time': datetime.date(2008, 1, 1), 'fit_end_time': datetime.date(2014, 12, 31), 'instruments': 'CSI300'}}}}} + >>> new_task = replace_task_handler_with_cache(task) + >>> print(new_task) + {'dataset': {'kwargs': {'handler': 'file...Alpha158.3584f5f8b4.pkl'}}} + + """ + cache_dir = Path(cache_dir) + task = deepcopy(task) + handler = task["dataset"]["kwargs"]["handler"] + if isinstance(handler, dict): + hash = hash_args(handler) + h_path = cache_dir / f"{handler['class']}.{hash[:10]}.pkl" + if not h_path.exists(): + h = init_instance_by_config(handler) + h.to_pickle(h_path, dump_all=True) + task["dataset"]["kwargs"]["handler"] = f"file://{h_path}" + return task diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0f48c74f0b24c1e6ac1611ca0a47886aa5099661 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/workflow/utils.py @@ -0,0 +1,47 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import atexit +import logging +import sys +import traceback + +from ..log import get_module_logger +from . import R +from .recorder import Recorder + +logger = get_module_logger("workflow", logging.INFO) + + +# function to handle the experiment when unusual program ending occurs +def experiment_exit_handler(): + """ + Method for handling the experiment when any unusual program ending occurs. + The `atexit` handler should be put in the last, since, as long as the program ends, it will be called. + Thus, if any exception or user interruption occurs beforehand, we should handle them first. Once `R` is + ended, another call of `R.end_exp` will not take effect. + + Limitations: + - If pdb is used in your program, excepthook will not be triggered when it ends. The status will be finished + """ + sys.excepthook = experiment_exception_hook # handle uncaught exception + atexit.register(R.end_exp, recorder_status=Recorder.STATUS_FI) # will not take effect if experiment ends + + +def experiment_exception_hook(exc_type, value, tb): + """ + End an experiment with status to be "FAILED". This exception tries to catch those uncaught exception + and end the experiment automatically. + + Parameters + exc_type: Exception type + value: Exception's value + tb: Exception's traceback + """ + logger.error(f"An exception has been raised[{exc_type.__name__}: {value}].") + + # Same as original format + traceback.print_tb(tb) + print(f"{exc_type.__name__}: {value}") + + R.end_exp(recorder_status=Recorder.STATUS_FA) diff --git a/Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/expanding.o b/Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/expanding.o new file mode 100644 index 0000000000000000000000000000000000000000..0a66aa4093d42ed3c4220917ace612c0c7eab3c2 --- /dev/null +++ b/Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/expanding.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b66ca089c636f6ed23bef0ba93f11d0faf081a95ba49b2c97669ccd2ef9d36ea +size 200880 diff --git a/Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/rolling.o b/Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/rolling.o new file mode 100644 index 0000000000000000000000000000000000000000..e5ca8445293984672a755531da6886d84c3efe0e --- /dev/null +++ b/Kronos/qlib/build/temp.linux-x86_64-cpython-313/qlib/data/_libs/rolling.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1434b69df313db2cc2ae4a43b96872049e746a61a91005fd012c95ae119f676a +size 155576 diff --git a/Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/expanding.o b/Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/expanding.o new file mode 100644 index 0000000000000000000000000000000000000000..bd4d7193fe148338c8ca553c63c18aa87b0c11d3 --- /dev/null +++ b/Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/expanding.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d883c7af15b3195fa62a828ce2257d7b27246f1ebc0231e5784276799ca79fa9 +size 203776 diff --git a/Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/rolling.o b/Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/rolling.o new file mode 100644 index 0000000000000000000000000000000000000000..85029062082d4b55496590379e4687fb794943e5 --- /dev/null +++ b/Kronos/qlib/build/temp.linux-x86_64-cpython-39/qlib/data/_libs/rolling.o @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d8e882f9e74e2150a188fa0e544d88564c7eef14a7e1921ac5d28d5e513463ab +size 156416 diff --git a/Kronos/qlib/build_docker_image.sh b/Kronos/qlib/build_docker_image.sh new file mode 100644 index 0000000000000000000000000000000000000000..4acf963a2c044896cd66c8939a7b71927cb4991f --- /dev/null +++ b/Kronos/qlib/build_docker_image.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +docker_user="your_dockerhub_username" + +read -p "Do you want to build the nightly version of the qlib image? (default is stable) (yes/no): " answer; +answer=$(echo "$answer" | tr '[:upper:]' '[:lower:]') + +if [ "$answer" = "yes" ]; then + # Build the nightly version of the qlib image + docker build --build-arg IS_STABLE=no -t qlib_image -f ./Dockerfile . + image_tag="nightly" +else + # Build the stable version of the qlib image + docker build -t qlib_image -f ./Dockerfile . + image_tag="stable" +fi + +read -p "Is it uploaded to docker hub? (default is no) (yes/no): " answer; +answer=$(echo "$answer" | tr '[:upper:]' '[:lower:]') + +if [ "$answer" = "yes" ]; then + # Log in to Docker Hub + # If you are a new docker hub user, please verify your email address before proceeding with this step. + docker login + # Tag the Docker image + docker tag qlib_image "$docker_user/qlib_image:$image_tag" + # Push the Docker image to Docker Hub + docker push "$docker_user/qlib_image:$image_tag" +else + echo "Not uploaded to docker hub." +fi diff --git a/Kronos/qlib/docs/FAQ/FAQ.rst b/Kronos/qlib/docs/FAQ/FAQ.rst new file mode 100644 index 0000000000000000000000000000000000000000..94c4560b6f30db41db1e9c2cbb81f51069edd595 --- /dev/null +++ b/Kronos/qlib/docs/FAQ/FAQ.rst @@ -0,0 +1,153 @@ + +Qlib FAQ +############ + +Qlib Frequently Asked Questions +=============================== +.. contents:: + :depth: 1 + :local: + :backlinks: none + +------ + + +1. RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase... +----------------------------------------------------------------------------------------------------------------------------------- + +.. code-block:: console + + RuntimeError: + An attempt has been made to start a new process before the + current process has finished its bootstrapping phase. + + This probably means that you are not using fork to start your + child processes and you have forgotten to use the proper idiom + in the main module: + + if __name__ == '__main__': + freeze_support() + ... + + The "freeze_support()" line can be omitted if the program + is not going to be frozen to produce an executable. + +This is caused by the limitation of multiprocessing under windows OS. Please refer to `here `_ for more info. + +**Solution**: To select a start method you use the ``D.features`` in the if __name__ == '__main__' clause of the main module. For example: + +.. code-block:: python + + import qlib + from qlib.data import D + + + if __name__ == "__main__": + qlib.init() + instruments = ["SH600000"] + fields = ["$close", "$change"] + df = D.features(instruments, fields, start_time='2010-01-01', end_time='2012-12-31') + print(df.head()) + + + +2. qlib.data.cache.QlibCacheException: It sees the key(...) of the redis lock has existed in your redis db now. +--------------------------------------------------------------------------------------------------------------- + +It sees the key of the redis lock has existed in your redis db now. You can use the following command to clear your redis keys and rerun your commands + +.. code-block:: console + + $ redis-cli + > select 1 + > flushdb + +If the issue is not resolved, use ``keys *`` to find if multiple keys exist. If so, try using ``flushall`` to clear all the keys. + +.. note:: + + ``qlib.config.redis_task_db`` defaults is ``1``, users can use ``qlib.init(redis_task_db=)`` settings. + + +Also, feel free to post a new issue in our GitHub repository. We always check each issue carefully and try our best to solve them. + +3. ModuleNotFoundError: No module named 'qlib.data._libs.rolling' +----------------------------------------------------------------- + +.. code-block:: python + + #### Do not import qlib package in the repository directory in case of importing qlib from . without compiling ##### + Traceback (most recent call last): + File "", line 1, in + File "qlib/qlib/__init__.py", line 19, in init + from .data.cache import H + File "qlib/qlib/data/__init__.py", line 8, in + from .data import ( + File "qlib/qlib/data/data.py", line 20, in + from .cache import H + File "qlib/qlib/data/cache.py", line 36, in + from .ops import Operators + File "qlib/qlib/data/ops.py", line 19, in + from ._libs.rolling import rolling_slope, rolling_rsquare, rolling_resi + ModuleNotFoundError: No module named 'qlib.data._libs.rolling' + +- If the error occurs when importing ``qlib`` package with ``PyCharm`` IDE, users can execute the following command in the project root folder to compile Cython files and generate executable files: + + .. code-block:: bash + + python setup.py build_ext --inplace + +- If the error occurs when importing ``qlib`` package with command ``python`` , users need to change the running directory to ensure that the script does not run in the project directory. + + +4. BadNamespaceError: / is not a connected namespace +---------------------------------------------------- + +.. code-block:: python + + File "qlib_online.py", line 35, in + cal = D.calendar() + File "e:\code\python\microsoft\qlib_latest\qlib\qlib\data\data.py", line 973, in calendar + return Cal.calendar(start_time, end_time, freq, future=future) + File "e:\code\python\microsoft\qlib_latest\qlib\qlib\data\data.py", line 798, in calendar + self.conn.send_request( + File "e:\code\python\microsoft\qlib_latest\qlib\qlib\data\client.py", line 101, in send_request + self.sio.emit(request_type + "_request", request_content) + File "G:\apps\miniconda\envs\qlib\lib\site-packages\python_socketio-5.3.0-py3.8.egg\socketio\client.py", line 369, in emit + raise exceptions.BadNamespaceError( + BadNamespaceError: / is not a connected namespace. + +- The version of ``python-socketio`` in qlib needs to be the same as the version of ``python-socketio`` in qlib-server: + + .. code-block:: bash + + pip install -U python-socketio== + + +5. TypeError: send() got an unexpected keyword argument 'binary' +---------------------------------------------------------------- + +.. code-block:: python + + File "qlib_online.py", line 35, in + cal = D.calendar() + File "e:\code\python\microsoft\qlib_latest\qlib\qlib\data\data.py", line 973, in calendar + return Cal.calendar(start_time, end_time, freq, future=future) + File "e:\code\python\microsoft\qlib_latest\qlib\qlib\data\data.py", line 798, in calendar + self.conn.send_request( + File "e:\code\python\microsoft\qlib_latest\qlib\qlib\data\client.py", line 101, in send_request + self.sio.emit(request_type + "_request", request_content) + File "G:\apps\miniconda\envs\qlib\lib\site-packages\socketio\client.py", line 263, in emit + self._send_packet(packet.Packet(packet.EVENT, namespace=namespace, + File "G:\apps\miniconda\envs\qlib\lib\site-packages\socketio\client.py", line 339, in _send_packet + self.eio.send(ep, binary=binary) + TypeError: send() got an unexpected keyword argument 'binary' + + +- The ``python-engineio`` version needs to be compatible with the ``python-socketio`` version, reference: https://github.com/miguelgrinberg/python-socketio#version-compatibility + + .. code-block:: bash + + pip install -U python-engineio== + # or + pip install -U python-socketio==3.1.2 python-engineio==3.13.2 diff --git a/Kronos/qlib/docs/Makefile b/Kronos/qlib/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..ad7b944dd2a89e0c592a07ab7bc79b0e7d30c1e7 --- /dev/null +++ b/Kronos/qlib/docs/Makefile @@ -0,0 +1,21 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = python3 -msphinx +SPHINXPROJ = Quantlab +SOURCEDIR = . +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + pip install -r requirements.txt + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) diff --git a/Kronos/qlib/docs/_static/demo.sh b/Kronos/qlib/docs/_static/demo.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd2367a92248564f9b721ec9c558742013d28203 --- /dev/null +++ b/Kronos/qlib/docs/_static/demo.sh @@ -0,0 +1,12 @@ +#!/bin/sh +git clone https://github.com/microsoft/qlib.git +cd qlib +ls +pip install pyqlib +# or +# pip install numpy +# pip install --upgrade cython +# python setup.py install +cd examples +ls +qrun benchmarks/LightGBM/workflow_config_lightgbm_Alpha158.yaml \ No newline at end of file diff --git a/Kronos/qlib/docs/_static/img/QlibRL_framework.png b/Kronos/qlib/docs/_static/img/QlibRL_framework.png new file mode 100644 index 0000000000000000000000000000000000000000..0587e2cfbf312ddb671657eec4e3f7a0aabf73eb --- /dev/null +++ b/Kronos/qlib/docs/_static/img/QlibRL_framework.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:c12f7ce509f5860e64ae6d1136e752552f6af3e54c7d3341241147abe7cbcf86 +size 92968 diff --git a/Kronos/qlib/docs/_static/img/RL_framework.png b/Kronos/qlib/docs/_static/img/RL_framework.png new file mode 100644 index 0000000000000000000000000000000000000000..faaf14c61f21d388c92be09a4c6746f903025e52 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/RL_framework.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f124ef58435fd9d751c9c9096bf7559dc5abe1b3d4a388c5e7387ea89780db82 +size 30494 diff --git a/Kronos/qlib/docs/_static/img/Task-Gen-Recorder-Collector.svg b/Kronos/qlib/docs/_static/img/Task-Gen-Recorder-Collector.svg new file mode 100644 index 0000000000000000000000000000000000000000..51602c12b56a16e65476a47961c179b88aea0598 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/Task-Gen-Recorder-Collector.svg @@ -0,0 +1,4 @@ + + + +
Collector.process_list:
  • qlib.model.ens.ensemble.AverageEnsemble
  • qlib.model.ens.ensemble.RollingEnsemble    
Collector.process_list:...
Combine and Collect Data
Combine and Collect Data
Task Genratation
Task Genratation
Task_{GBDT}
Task_{NN}
Rolling Generator
Rolling Generat...
Genrated Tasks
Genrated Tasks
Task_{GBDT ,t...
Task_{GBDT ,t...
Task_{GBDT ,T...

{"model": { 
       class: "...GBDT"
   },
   "dataset": {
        ....
        "kwargs" {
             segments: {
                test: [....]
                 ....
             }
        }
   }
}

{"model": {...
time
time
Rolling
Generator
Rolling...
Genrated Tasks
Genrated Tasks
Task_{NN,t1}
Task_{NN,t2}
time
time
Task_{NN,T}
Record_{NN,t1}
pred.pkl
pred.pkl
Pred_{avg,t1}
Record_{NN,t2}
pred.pkl
pred.pkl
Record_{NN,T}
pred.pkl
pred.pkl
Record_{GBDT,t1}
pred.pkl
pred.pkl
Record_{GBDT,t2}
pred.pkl
pred.pkl
Record_{GBDT,T}
pred.pkl
pred.pkl
Pred_{avg,t2}
Pred_{avg,T}
qlib.model.ens.ensemble.RollingEnsemble
qlib.model.ens.ensemble.RollingEnsemble
Final Result
Final Result
...
...
...
...
...
...
...
...
...
...
...
...
qlib.model.ens.ensemble.AverageEnsemble
qlib.model.ens.ensemble.AverageEnsemble
qlib.model.ens.group.Group
qlib.model.ens.group.Group
+ Group
It will categorize data into groups
+ Group...
+ Reduce
It calls ensemble to combine the data
+ Reduce...
'score':  {
   {
           : <pd.DataFrame>
   }
}
'score':  {...
t1
Model Training
Model Training
...
...
qlib.model.trainer.Trainer
qlib.model.trainer.Trainer
...
...
...
...
...
...
...
...
Viewer does not support full SVG 1.1
\ No newline at end of file diff --git a/Kronos/qlib/docs/_static/img/analysis/analysis_model_IC.png b/Kronos/qlib/docs/_static/img/analysis/analysis_model_IC.png new file mode 100644 index 0000000000000000000000000000000000000000..7d44fb7ebdb150767837c89edcbd7c5e4765bdf7 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/analysis_model_IC.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dbfcfb72842071d56ff2745fc6480de0f968d6f0aa30b926ed9f437c9f95c12f +size 37744 diff --git a/Kronos/qlib/docs/_static/img/analysis/analysis_model_NDQ.png b/Kronos/qlib/docs/_static/img/analysis/analysis_model_NDQ.png new file mode 100644 index 0000000000000000000000000000000000000000..8b55095b2673045c02954f2062963e74dc067613 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/analysis_model_NDQ.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:269520af31efd406956bf5dac9348de5f98772e838def36940211a9209a9d508 +size 23611 diff --git a/Kronos/qlib/docs/_static/img/analysis/analysis_model_auto_correlation.png b/Kronos/qlib/docs/_static/img/analysis/analysis_model_auto_correlation.png new file mode 100644 index 0000000000000000000000000000000000000000..3b57547201c8a1a8ece5fc0ee9adae82ba816c1e --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/analysis_model_auto_correlation.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:260841199958a57f7f7cb77ca996816a64c1b8e910c9644cf1d9614fe9a0cfc9 +size 45122 diff --git a/Kronos/qlib/docs/_static/img/analysis/analysis_model_cumulative_return.png b/Kronos/qlib/docs/_static/img/analysis/analysis_model_cumulative_return.png new file mode 100644 index 0000000000000000000000000000000000000000..e047b229d7ab13da46eefc2ba60564975ce56f19 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/analysis_model_cumulative_return.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe6c02eeb11e0d75ffed78850f9b97d10ae034d4521b54776e6d151574faeb7a +size 54585 diff --git a/Kronos/qlib/docs/_static/img/analysis/analysis_model_long_short.png b/Kronos/qlib/docs/_static/img/analysis/analysis_model_long_short.png new file mode 100644 index 0000000000000000000000000000000000000000..301cacfd14c74ae1f9c521c1a67584003ffb7102 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/analysis_model_long_short.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:38563fbd6919a608c5a968bfd0c3cd0fa8df74bbabf767899196b1dedb19016f +size 15838 diff --git a/Kronos/qlib/docs/_static/img/analysis/analysis_model_monthly_IC.png b/Kronos/qlib/docs/_static/img/analysis/analysis_model_monthly_IC.png new file mode 100644 index 0000000000000000000000000000000000000000..fc2eb590bef7dd27cfc1d601676ea68e3024ae34 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/analysis_model_monthly_IC.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:abf738d2c4b0380ca078c7403d30732043f8241cac6a66908483ac3ed67131e9 +size 15815 diff --git a/Kronos/qlib/docs/_static/img/analysis/cumulative_return_buy.png b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_buy.png new file mode 100644 index 0000000000000000000000000000000000000000..584c2253a4cdf5b0082f173cc11c40e39b6c8df6 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_buy.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e37abd3e18915ecf7cb50cb3c65a69bdecd881ac42748df5e248146f5eead007 +size 43399 diff --git a/Kronos/qlib/docs/_static/img/analysis/cumulative_return_buy_minus_sell.png b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_buy_minus_sell.png new file mode 100644 index 0000000000000000000000000000000000000000..4ac654796c94772e3d27c4d91d7ad16cd93851c9 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_buy_minus_sell.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:79eb462d4a6e9f75c4bfd9b56ac4c515a21fca0acebf6dbcbaebd0b7bdbe2e90 +size 45341 diff --git a/Kronos/qlib/docs/_static/img/analysis/cumulative_return_hold.png b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_hold.png new file mode 100644 index 0000000000000000000000000000000000000000..52e962c2f6194d8714258a222deff28aed8920a3 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_hold.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ca08269720a69c946309a857297d80feb40a9d054b6838c173f76de34e6ad605 +size 43533 diff --git a/Kronos/qlib/docs/_static/img/analysis/cumulative_return_sell.png b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_sell.png new file mode 100644 index 0000000000000000000000000000000000000000..db83e925efddb1a9fa253ffc59a7b91a808e82db --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/cumulative_return_sell.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:49f29d51461417b7051496f68b6ffd27094e5423ed76015b4fc3c4f9d9f51a04 +size 53526 diff --git a/Kronos/qlib/docs/_static/img/analysis/rank_label_buy.png b/Kronos/qlib/docs/_static/img/analysis/rank_label_buy.png new file mode 100644 index 0000000000000000000000000000000000000000..6beffdf0e1adb9ea64e801c467a18c66381843d8 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/rank_label_buy.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d49096e23eed1040d0033482ca4908793b77b67f18ecb3b3baf0e5a3c64a1b90 +size 83361 diff --git a/Kronos/qlib/docs/_static/img/analysis/rank_label_hold.png b/Kronos/qlib/docs/_static/img/analysis/rank_label_hold.png new file mode 100644 index 0000000000000000000000000000000000000000..45cf87b0bbd3b7dc9abb65d0646c05537aab9229 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/rank_label_hold.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8d9c8a535db79e1e82f90a378476ffe7a823fd4655dadd3f589451edcf75b768 +size 72886 diff --git a/Kronos/qlib/docs/_static/img/analysis/rank_label_sell.png b/Kronos/qlib/docs/_static/img/analysis/rank_label_sell.png new file mode 100644 index 0000000000000000000000000000000000000000..db7450fbe8926988c2df68e6510c2e02e1389859 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/rank_label_sell.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:65ed90d53c96cfa277689666c92b8074d61626cc58f62069086ad0def855afaa +size 83175 diff --git a/Kronos/qlib/docs/_static/img/analysis/report.png b/Kronos/qlib/docs/_static/img/analysis/report.png new file mode 100644 index 0000000000000000000000000000000000000000..90770c71774f69faca79474d1c043f601eeed3c9 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/report.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1f0db397b0029ea9e2ea8ff44819c342918bcdff481d794db75e2cc73afc3768 +size 147442 diff --git a/Kronos/qlib/docs/_static/img/analysis/risk_analysis_annualized_return.png b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_annualized_return.png new file mode 100644 index 0000000000000000000000000000000000000000..0812890020f9e81d9c0ffac0e925bbac504ec877 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_annualized_return.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6ab49a6a8bed1b3b017672a3fb12625f84a344659ca48f0cd97f716180829699 +size 46507 diff --git a/Kronos/qlib/docs/_static/img/analysis/risk_analysis_bar.png b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_bar.png new file mode 100644 index 0000000000000000000000000000000000000000..6ecb9a6414900d112765672f36996f073f1603f9 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_bar.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:350a88336663f947cf148cbbe9f5a6263b46613062c452e76b25f7a237b5cab1 +size 10670 diff --git a/Kronos/qlib/docs/_static/img/analysis/risk_analysis_information_ratio.png b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_information_ratio.png new file mode 100644 index 0000000000000000000000000000000000000000..27506697f910c58ea3ecd52fb6d4e93969a84c5e --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_information_ratio.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dfa2b10e7a640da90dc19fb36cda57db425bbb3ad846f4a27727470e62b61381 +size 53269 diff --git a/Kronos/qlib/docs/_static/img/analysis/risk_analysis_max_drawdown.png b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_max_drawdown.png new file mode 100644 index 0000000000000000000000000000000000000000..691b2feb5931b66fa71f963fc9bfe518388d854f --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_max_drawdown.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6c2b7ce9c15ccee6377fc37b872e0f2fdb2a2a1328ff00af774a719c66b25d67 +size 48861 diff --git a/Kronos/qlib/docs/_static/img/analysis/risk_analysis_std.png b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_std.png new file mode 100644 index 0000000000000000000000000000000000000000..57eca290209d795211960b19e3a530395de8e3b9 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/risk_analysis_std.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5c59a9bc7376aa044a3a8c1a2c0c9dded65bc159365c8641473087f1f43d9282 +size 45382 diff --git a/Kronos/qlib/docs/_static/img/analysis/score_ic.png b/Kronos/qlib/docs/_static/img/analysis/score_ic.png new file mode 100644 index 0000000000000000000000000000000000000000..0092e389fcc54d4d6e19cf7c0b31ad860d0d0303 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/analysis/score_ic.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b5a56bf9ec4a02068b3de069a19655a15dafa6735b146c71f12f16db9d228a4a +size 95451 diff --git a/Kronos/qlib/docs/_static/img/change doc.gif b/Kronos/qlib/docs/_static/img/change doc.gif new file mode 100644 index 0000000000000000000000000000000000000000..b160435d35cce6bed7ae10e15056240f556f771a --- /dev/null +++ b/Kronos/qlib/docs/_static/img/change doc.gif @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3ca880e78c7a9130d37da961b828e13198fc3796be7ff2a98673cd0447c6e80a +size 1355017 diff --git a/Kronos/qlib/docs/_static/img/framework-abstract.jpg b/Kronos/qlib/docs/_static/img/framework-abstract.jpg new file mode 100644 index 0000000000000000000000000000000000000000..5e360ccc16434ec04ffaa5948f12e19c02fb3776 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/framework-abstract.jpg @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:583732782084fcd92a0d54b464f72f37a1dd981e01803c056a7ba32d53c51aa4 +size 66107 diff --git a/Kronos/qlib/docs/_static/img/framework.png b/Kronos/qlib/docs/_static/img/framework.png new file mode 100644 index 0000000000000000000000000000000000000000..aff88f9cb22d832728e8e68ecda601edb49d4ce3 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/framework.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:dd95e3f2ae93e9971a20a4243f256501fb9666b3a81ecf86a2472962c4717f5a +size 213555 diff --git a/Kronos/qlib/docs/_static/img/framework.svg b/Kronos/qlib/docs/_static/img/framework.svg new file mode 100644 index 0000000000000000000000000000000000000000..80671ebe804f2e29fcd14cfd0c400fc4694fee33 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/framework.svg @@ -0,0 +1,4 @@ + + + +
Reinforcement  Learning
Reinforcement  Learning
Environment
Environment
Simulator
Simulator
Strategy
Strategy
Supervised-Learning-based Strategy
Supervised-Learning-based Strategy
Policy
Policy
Supervised Learning
Supervised Learning
Meta Controller
Meta Controller
Analyser
Analyser
Interface
Interface
Multi-level Workflow
Multi-level Workflow
Infrastracture
Infrastracture
Forecasting Analyser
Forecasting...
Portfolio Analyser
Portfolio A...
Execution Analyser
Execution...
Information Extractor
Information Extractor
Online Serving
Online Serving
Graph
Graph
Event
Event
Factor
Factor
Text
Text
Data Server
Data Server
local
local
remote
remote
Trainer
Trainer
Algorithms
Algorithms
Auto-ML
Auto-ML
Model Manager
Model Manager
Model
Model
Model
Model
Models
Models
Model
Model
Model
Model
Decision Generators
Decision Generators
Model Interpreter
Model Interpreter
Executor
Executor
Sub-workflow
(NestedExecutor)
Sub-workflow...
Highly Customizable
Module
Highly Customiz...
Module in development
Module in devel...
Explanation
Explanation
Sub-workflow(1) (E.g. High-frequency order execution nested in portfolio management)
Sub-workflow(1) (E.g. High-fr...
Executor
Executor
...
...
(1)  The sub-workflow will make more fine-grained decisions according to the decision from the upper-level trading agent
(1)  The sub-workflow will make more fine-grained decisions according to the decision from the upper-level trading agent
Supervised signal
Supervised signal
Model Traning
Model Traning
Forecast Model
Forecast Model
Risk
Risk
Alpha
Alpha
Action (Decision)
Action (Decision)
Learning Framework
Learning Framework
Information Extractor
Information Extrac...
Graph
Graph
Event
Event
Factor
Factor
Text
Text
OR
OR
Decision Generator
Decision Generator
Policy
Policy
State Intepreter
State Intepreter
Action Intepreter
Action Intepreter
State/Reward (Execution Results)
State/Reward (Execution Results)
Order Execution
Order Execu...
Portfolio Management
Portfolio M...
Executor
Executor
Portfolio Management
Portfolio Management
Reinforcement-Learning-based Strategy
Reinforcement-Learning-based Strategy
State Intepreter
State Intepreter
Action Intepreter
Action Intepreter
Decision
Decision
Rule-based
Rule-based
Portfolio Optimiaztion
Portfolio Optimiaz...
Decision
Decision
Strategy
Strategy
...
...
Decision
Decision
Portfolio management
Portfolio management
Order execution
Order execution
Asset allocation
Asset allocation
Decision
Decision
Execution Results
Execution Results
Execution
Results

Execution...
Executor
Executor
Order Execution
Order Execution
Forecast Model
Forecast Model
Risk
Risk
Alpha
Alpha
Text is not SVG - cannot display
diff --git a/Kronos/qlib/docs/_static/img/logo/1.png b/Kronos/qlib/docs/_static/img/logo/1.png new file mode 100644 index 0000000000000000000000000000000000000000..44538d1c2c65c9a028a9adc89a5062d33c464157 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/1.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f23e2e35d8f655bf27d3007b5e168617147e2485154456bfaa42e4b5935753d7 +size 18332 diff --git a/Kronos/qlib/docs/_static/img/logo/2.png b/Kronos/qlib/docs/_static/img/logo/2.png new file mode 100644 index 0000000000000000000000000000000000000000..5d1910c616a9288baacab8c08b6c5ee590e03fbb --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/2.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8958a45bd02d3d5f4a9dce7c6b40456e3bf91dace7dc2ac878fde44fa0bcf1af +size 18088 diff --git a/Kronos/qlib/docs/_static/img/logo/3.png b/Kronos/qlib/docs/_static/img/logo/3.png new file mode 100644 index 0000000000000000000000000000000000000000..10581a6c5e460d384e14c1787e56bc1ad3adcb77 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/3.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8397f0e12e919e675c253fd3917b649e6eb96269acce6ecec8e16b322afff3d7 +size 13537 diff --git a/Kronos/qlib/docs/_static/img/logo/white_bg_rec+word.png b/Kronos/qlib/docs/_static/img/logo/white_bg_rec+word.png new file mode 100644 index 0000000000000000000000000000000000000000..eddb4429eaaef236b1ba7ab4561f8f02e038a930 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/white_bg_rec+word.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b37c2aa56f1066d262a09b4fea649143b190b0cf1edb2867655f64d7d4bfdfb +size 15311 diff --git a/Kronos/qlib/docs/_static/img/logo/yel_bg_rec+word.png b/Kronos/qlib/docs/_static/img/logo/yel_bg_rec+word.png new file mode 100644 index 0000000000000000000000000000000000000000..439d378d06c279afacf0cc2b69a975df6b394c6f --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/yel_bg_rec+word.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:6786e95090a4aedbeeff32dee4ba8dc02cb318135f3fddf5333aab3ef5c4d576 +size 9892 diff --git a/Kronos/qlib/docs/_static/img/logo/yellow_bg_rec+word .png b/Kronos/qlib/docs/_static/img/logo/yellow_bg_rec+word .png new file mode 100644 index 0000000000000000000000000000000000000000..5714e49c3ba03336967d4a72c7f6a7a40b4b7829 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/yellow_bg_rec+word .png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:943c0290244369eef62c75233f568f486c0cf4ca14cc5e25eb5a4450a5c6aa6c +size 9410 diff --git a/Kronos/qlib/docs/_static/img/logo/yellow_bg_rec.png b/Kronos/qlib/docs/_static/img/logo/yellow_bg_rec.png new file mode 100644 index 0000000000000000000000000000000000000000..39b978b3cf5f6a19ee6d66f2e53f7ad37bb077c7 --- /dev/null +++ b/Kronos/qlib/docs/_static/img/logo/yellow_bg_rec.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:60c420e61c7c3ab3b8c2eac890f13ff8e3bb9006ed5b58d82d9f950234100606 +size 5136 diff --git a/Kronos/qlib/docs/_static/img/online_serving.png b/Kronos/qlib/docs/_static/img/online_serving.png new file mode 100644 index 0000000000000000000000000000000000000000..fc47bc8e86089f95eef741514b22c6ef61ac420d --- /dev/null +++ b/Kronos/qlib/docs/_static/img/online_serving.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1bcbfbb3518a53486100f0c56adde088be4fa72218582e138113c782598d0948 +size 450088 diff --git a/Kronos/qlib/docs/_static/img/qrcode/gitter_qr.png b/Kronos/qlib/docs/_static/img/qrcode/gitter_qr.png new file mode 100644 index 0000000000000000000000000000000000000000..01476dd105b2f83441c8efcd56e388e8947d333e --- /dev/null +++ b/Kronos/qlib/docs/_static/img/qrcode/gitter_qr.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5b8bc770b01da9940b3691382a8fea9a81abcbe596f02e900dc6026a27dacbd4 +size 7372 diff --git a/Kronos/qlib/docs/_static/img/rdagent_logo.png b/Kronos/qlib/docs/_static/img/rdagent_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..10c4ee1b7f56b6b846471c3b08ad8df559b505cf --- /dev/null +++ b/Kronos/qlib/docs/_static/img/rdagent_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:426c1d8348be4f1056c114136440e7bcbd7a5f3cd7aa4fec37346a9cc10d446b +size 95756 diff --git a/Kronos/qlib/docs/_static/img/topk_drop.png b/Kronos/qlib/docs/_static/img/topk_drop.png new file mode 100644 index 0000000000000000000000000000000000000000..44414989b7b81abfdbfbc9884e9a3fe748b0333b --- /dev/null +++ b/Kronos/qlib/docs/_static/img/topk_drop.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:8ff69926069cdb623269e7494d7cb06dd48ef63d89285bb1c52a9a9fcbb30b68 +size 51648 diff --git a/Kronos/qlib/docs/advanced/PIT.rst b/Kronos/qlib/docs/advanced/PIT.rst new file mode 100644 index 0000000000000000000000000000000000000000..d8eda2097f4b160c402cfa45a27e6bc20968fae9 --- /dev/null +++ b/Kronos/qlib/docs/advanced/PIT.rst @@ -0,0 +1,136 @@ +.. _pit: + +============================ +(P)oint-(I)n-(T)ime Database +============================ +.. currentmodule:: qlib + + +Introduction +------------ +Point-in-time data is a very important consideration when performing any sort of historical market analysis. + +For example, let’s say we are backtesting a trading strategy and we are using the past five years of historical data as our input. +Our model is assumed to trade once a day, at the market close, and we’ll say we are calculating the trading signal for 1 January 2020 in our backtest. At that point, we should only have data for 1 January 2020, 31 December 2019, 30 December 2019 etc. + +In financial data (especially financial reports), the same piece of data may be amended for multiple times overtime. If we only use the latest version for historical backtesting, data leakage will happen. +Point-in-time database is designed for solving this problem to make sure user get the right version of data at any historical timestamp. It will keep the performance of online trading and historical backtesting the same. + + + +Data Preparation +---------------- + +Qlib provides a crawler to help users to download financial data and then a converter to dump the data in Qlib format. +Please follow `scripts/data_collector/pit/README.md `_ to download and convert data. +Besides, you can find some additional usage examples there. + + +File-based design for PIT data +------------------------------ + +Qlib provides a file-based storage for PIT data. + +For each feature, it contains 4 columns, i.e. date, period, value, _next. +Each row corresponds to a statement. + +The meaning of each feature with filename like `XXX_a.data`: + +- `date`: the statement's date of publication. +- `period`: the period of the statement. (e.g. it will be quarterly frequency in most of the markets) + - If it is an annual period, it will be an integer corresponding to the year + - If it is an quarterly periods, it will be an integer like ``. The last two decimal digits represents the index of quarter. Others represent the year. +- `value`: the described value +- `_next`: the byte index of the next occurance of the field. + +Besides the feature data, an index `XXX_a.index` is included to speed up the querying performance + +The statements are soted by the `date` in ascending order from the beginning of the file. + +.. code-block:: python + + # the data format from XXXX.data + array([(20070428, 200701, 0.090219 , 4294967295), + (20070817, 200702, 0.13933 , 4294967295), + (20071023, 200703, 0.24586301, 4294967295), + (20080301, 200704, 0.3479 , 80), + (20080313, 200704, 0.395989 , 4294967295), + (20080422, 200801, 0.100724 , 4294967295), + (20080828, 200802, 0.24996801, 4294967295), + (20081027, 200803, 0.33412001, 4294967295), + (20090325, 200804, 0.39011699, 4294967295), + (20090421, 200901, 0.102675 , 4294967295), + (20090807, 200902, 0.230712 , 4294967295), + (20091024, 200903, 0.30072999, 4294967295), + (20100402, 200904, 0.33546099, 4294967295), + (20100426, 201001, 0.083825 , 4294967295), + (20100812, 201002, 0.200545 , 4294967295), + (20101029, 201003, 0.260986 , 4294967295), + (20110321, 201004, 0.30739301, 4294967295), + (20110423, 201101, 0.097411 , 4294967295), + (20110831, 201102, 0.24825101, 4294967295), + (20111018, 201103, 0.318919 , 4294967295), + (20120323, 201104, 0.4039 , 420), + (20120411, 201104, 0.403925 , 4294967295), + (20120426, 201201, 0.112148 , 4294967295), + (20120810, 201202, 0.26484701, 4294967295), + (20121026, 201203, 0.370487 , 4294967295), + (20130329, 201204, 0.45004699, 4294967295), + (20130418, 201301, 0.099958 , 4294967295), + (20130831, 201302, 0.21044201, 4294967295), + (20131016, 201303, 0.30454299, 4294967295), + (20140325, 201304, 0.394328 , 4294967295), + (20140425, 201401, 0.083217 , 4294967295), + (20140829, 201402, 0.16450299, 4294967295), + (20141030, 201403, 0.23408499, 4294967295), + (20150421, 201404, 0.319612 , 4294967295), + (20150421, 201501, 0.078494 , 4294967295), + (20150828, 201502, 0.137504 , 4294967295), + (20151023, 201503, 0.201709 , 4294967295), + (20160324, 201504, 0.26420501, 4294967295), + (20160421, 201601, 0.073664 , 4294967295), + (20160827, 201602, 0.136576 , 4294967295), + (20161029, 201603, 0.188062 , 4294967295), + (20170415, 201604, 0.244385 , 4294967295), + (20170425, 201701, 0.080614 , 4294967295), + (20170728, 201702, 0.15151 , 4294967295), + (20171026, 201703, 0.25416601, 4294967295), + (20180328, 201704, 0.32954201, 4294967295), + (20180428, 201801, 0.088887 , 4294967295), + (20180802, 201802, 0.170563 , 4294967295), + (20181029, 201803, 0.25522 , 4294967295), + (20190329, 201804, 0.34464401, 4294967295), + (20190425, 201901, 0.094737 , 4294967295), + (20190713, 201902, 0. , 1040), + (20190718, 201902, 0.175322 , 4294967295), + (20191016, 201903, 0.25581899, 4294967295)], + dtype=[('date', '`_. + +.. code-block:: python + + >> from qlib.data.dataset.loader import QlibDataLoader + >> MACD_EXP = '2 * ((EMA($close, 12) - EMA($close, 26))/$close - EMA((EMA($close, 12) - EMA($close, 26))/$close, 9))' + >> fields = [MACD_EXP] # MACD + >> names = ['MACD'] + >> labels = ['Ref($close, -2)/Ref($close, -1) - 1'] # label + >> label_names = ['LABEL'] + >> data_loader_config = { + .. "feature": (fields, names), + .. "label": (labels, label_names) + .. } + >> data_loader = QlibDataLoader(config=data_loader_config) + >> df = data_loader.load(instruments='csi300', start_time='2010-01-01', end_time='2017-12-31') + >> print(df) + feature label + MACD LABEL + datetime instrument + 2010-01-04 SH600000 0.008781 -0.019672 + SH600004 0.006699 -0.014721 + SH600006 0.005714 0.002911 + SH600008 0.000798 0.009818 + SH600009 0.017015 -0.017758 + ... ... ... + 2017-12-29 SZ300124 0.015071 -0.005074 + SZ300136 -0.015466 0.056352 + SZ300144 0.013082 0.011853 + SZ300251 -0.001026 0.021739 + SZ300315 -0.007559 0.012455 + +Reference +========= + +To learn more about ``Data Loader``, please refer to `Data Loader <../component/data.html#data-loader>`_ + +To learn more about ``Data API``, please refer to `Data API <../component/data.html>`_ diff --git a/Kronos/qlib/docs/advanced/serial.rst b/Kronos/qlib/docs/advanced/serial.rst new file mode 100644 index 0000000000000000000000000000000000000000..e50ee91ddaf7e1651c361b5e4336b4353d329681 --- /dev/null +++ b/Kronos/qlib/docs/advanced/serial.rst @@ -0,0 +1,45 @@ +.. _serial: + +============= +Serialization +============= +.. currentmodule:: qlib + +Introduction +============ +``Qlib`` supports dumping the state of ``DataHandler``, ``DataSet``, ``Processor`` and ``Model``, etc. into a disk and reloading them. + +Serializable Class +================== + +``Qlib`` provides a base class ``qlib.utils.serial.Serializable``, whose state can be dumped into or loaded from disk in `pickle` format. +When users dump the state of a ``Serializable`` instance, the attributes of the instance whose name **does not** start with `_` will be saved on the disk. +However, users can use ``config`` method or override ``default_dump_all`` attribute to prevent this feature. + +Users can also override ``pickle_backend`` attribute to choose a pickle backend. The supported value is "pickle" (default and common) and "dill" (dump more things such as function, more information in `here `_). + +Example +======= +``Qlib``'s serializable class includes ``DataHandler``, ``DataSet``, ``Processor`` and ``Model``, etc., which are subclass of ``qlib.utils.serial.Serializable``. +Specifically, ``qlib.data.dataset.DatasetH`` is one of them. Users can serialize ``DatasetH`` as follows. + +.. code-block:: Python + + ##=============dump dataset============= + dataset.to_pickle(path="dataset.pkl") # dataset is an instance of qlib.data.dataset.DatasetH + + ##=============reload dataset============= + with open("dataset.pkl", "rb") as file_dataset: + dataset = pickle.load(file_dataset) + +.. note:: + Only state of ``DatasetH`` should be saved on the disk, such as some `mean` and `variance` used for data normalization, etc. + + After reloading the ``DatasetH``, users need to reinitialize it. It means that users can reset some states of ``DatasetH`` or ``QlibDataHandler`` such as `instruments`, `start_time`, `end_time` and `segments`, etc., and generate new data according to the states (data is not state and should not be saved on the disk). + +A more detailed example is in this `link `_. + + +API +=== +Please refer to `Serializable API <../reference/api.html#module-qlib.utils.serial.Serializable>`_. diff --git a/Kronos/qlib/docs/advanced/server.rst b/Kronos/qlib/docs/advanced/server.rst new file mode 100644 index 0000000000000000000000000000000000000000..2193025b46da6e45cd9d16cf46ca036e6915cb86 --- /dev/null +++ b/Kronos/qlib/docs/advanced/server.rst @@ -0,0 +1,29 @@ +.. _server: + +============================= +``Online`` & ``Offline`` mode +============================= +.. currentmodule:: qlib + + +Introduction +============ + +``Qlib`` supports ``Online`` mode and ``Offline`` mode. Only the ``Offline`` mode is introduced in this document. + +The ``Online`` mode is designed to solve the following problems: + +- Manage the data in a centralized way. Users don't have to manage data of different versions. +- Reduce the amount of cache to be generated. +- Make the data can be accessed in a remote way. + +Qlib-Server +=========== + +``Qlib-Server`` is the assorted server system for ``Qlib``, which utilizes ``Qlib`` for basic calculations and provides extensive server system and cache mechanism. With QLibServer, the data provided for ``Qlib`` can be managed in a centralized manner. With ``Qlib-Server``, users can use ``Qlib`` in ``Online`` mode. + + + +Reference +========= +If users are interested in ``Qlib-Server`` and ``Online`` mode, please refer to `Qlib-Server Project `_ and `Qlib-Server Document `_. diff --git a/Kronos/qlib/docs/advanced/task_management.rst b/Kronos/qlib/docs/advanced/task_management.rst new file mode 100644 index 0000000000000000000000000000000000000000..b1cb6c696a59f86452c2799d409da35ead610bbc --- /dev/null +++ b/Kronos/qlib/docs/advanced/task_management.rst @@ -0,0 +1,100 @@ +.. _task_management: + +=============== +Task Management +=============== +.. currentmodule:: qlib + + +Introduction +============ + +The `Workflow <../component/introduction.html>`_ part introduces how to run research workflow in a loosely-coupled way. But it can only execute one ``task`` when you use ``qrun``. +To automatically generate and execute different tasks, ``Task Management`` provides a whole process including `Task Generating`_, `Task Storing`_, `Task Training`_ and `Task Collecting`_. +With this module, users can run their ``task`` automatically at different periods, in different losses, or even by different models.The processes of task generation, model training and combine and collect data are shown in the following figure. + +.. image:: ../_static/img/Task-Gen-Recorder-Collector.svg + :align: center + +This whole process can be used in `Online Serving <../component/online.html>`_. + +An example of the entire process is shown `here `__. + +Task Generating +=============== +A ``task`` consists of `Model`, `Dataset`, `Record`, or anything added by users. +The specific task template can be viewed in +`Task Section <../component/workflow.html#task-section>`_. +Even though the task template is fixed, users can customize their ``TaskGen`` to generate different ``task`` by task template. + +Here is the base class of ``TaskGen``: + +.. autoclass:: qlib.workflow.task.gen.TaskGen + :members: + :noindex: + +``Qlib`` provides a class `RollingGen `_ to generate a list of ``task`` of the dataset in different date segments. +This class allows users to verify the effect of data from different periods on the model in one experiment. More information is `here <../reference/api.html#TaskGen>`__. + +Task Storing +============ +To achieve higher efficiency and the possibility of cluster operation, ``Task Manager`` will store all tasks in `MongoDB `_. +``TaskManager`` can fetch undone tasks automatically and manage the lifecycle of a set of tasks with error handling. +Users **MUST** finish the configuration of `MongoDB `_ when using this module. + +Users need to provide the MongoDB URL and database name for using ``TaskManager`` in `initialization <../start/initialization.html#Parameters>`_ or make a statement like this. + + .. code-block:: python + + from qlib.config import C + C["mongo"] = { + "task_url" : "mongodb://localhost:27017/", # your MongoDB url + "task_db_name" : "rolling_db" # database name + } + +.. autoclass:: qlib.workflow.task.manage.TaskManager + :members: + :noindex: + +More information of ``Task Manager`` can be found in `here <../reference/api.html#TaskManager>`__. + +Task Training +============= +After generating and storing those ``task``, it's time to run the ``task`` which is in the *WAITING* status. +``Qlib`` provides a method called ``run_task`` to run those ``task`` in task pool, however, users can also customize how tasks are executed. +An easy way to get the ``task_func`` is using ``qlib.model.trainer.task_train`` directly. +It will run the whole workflow defined by ``task``, which includes *Model*, *Dataset*, *Record*. + +.. autofunction:: qlib.workflow.task.manage.run_task + :noindex: + +Meanwhile, ``Qlib`` provides a module called ``Trainer``. + +.. autoclass:: qlib.model.trainer.Trainer + :members: + :noindex: + +``Trainer`` will train a list of tasks and return a list of model recorders. +``Qlib`` offer two kinds of Trainer, TrainerR is the simplest way and TrainerRM is based on TaskManager to help manager tasks lifecycle automatically. +If you do not want to use ``Task Manager`` to manage tasks, then use TrainerR to train a list of tasks generated by ``TaskGen`` is enough. +`Here <../reference/api.html#Trainer>`_ are the details about different ``Trainer``. + +Task Collecting +=============== +Before collecting model training results, you need to use the ``qlib.init`` to specify the path of mlruns. + +To collect the results of ``task`` after training, ``Qlib`` provides `Collector <../reference/api.html#Collector>`_, `Group <../reference/api.html#Group>`_ and `Ensemble <../reference/api.html#Ensemble>`_ to collect the results in a readable, expandable and loosely-coupled way. + +`Collector <../reference/api.html#Collector>`_ can collect objects from everywhere and process them such as merging, grouping, averaging and so on. It has 2 step action including ``collect`` (collect anything in a dict) and ``process_collect`` (process collected dict). + +`Group <../reference/api.html#Group>`_ also has 2 steps including ``group`` (can group a set of object based on `group_func` and change them to a dict) and ``reduce`` (can make a dict become an ensemble based on some rule). +For example: {(A,B,C1): object, (A,B,C2): object} ---``group``---> {(A,B): {C1: object, C2: object}} ---``reduce``---> {(A,B): object} + +`Ensemble <../reference/api.html#Ensemble>`_ can merge the objects in an ensemble. +For example: {C1: object, C2: object} ---``Ensemble``---> object. +You can set the ensembles you want in the ``Collector``'s process_list. +Common ensembles include ``AverageEnsemble`` and ``RollingEnsemble``. Average ensemble is used to ensemble the results of different models in the same time period. Rollingensemble is used to ensemble the results of different models in the same time period + +So the hierarchy is ``Collector``'s second step corresponds to ``Group``. And ``Group``'s second step correspond to ``Ensemble``. + +For more information, please see `Collector <../reference/api.html#Collector>`_, `Group <../reference/api.html#Group>`_ and `Ensemble <../reference/api.html#Ensemble>`_, or the `example `_. diff --git a/Kronos/qlib/docs/changelog/changelog.rst b/Kronos/qlib/docs/changelog/changelog.rst new file mode 100644 index 0000000000000000000000000000000000000000..d76c92b6f8ccc72630aac7f77c44dd1c86a64a82 --- /dev/null +++ b/Kronos/qlib/docs/changelog/changelog.rst @@ -0,0 +1 @@ +.. include:: ../../CHANGES.rst diff --git a/Kronos/qlib/docs/component/data.rst b/Kronos/qlib/docs/component/data.rst new file mode 100644 index 0000000000000000000000000000000000000000..eeddaec60d01f510160c6555e38af0c4fbbba772 --- /dev/null +++ b/Kronos/qlib/docs/component/data.rst @@ -0,0 +1,604 @@ +.. _data: + +================================== +Data Layer: Data Framework & Usage +================================== + +Introduction +============ + +``Data Layer`` provides user-friendly APIs to manage and retrieve data. It provides high-performance data infrastructure. + +It is designed for quantitative investment. For example, users could build formulaic alphas with ``Data Layer`` easily. Please refer to `Building Formulaic Alphas <../advanced/alpha.html>`_ for more details. + +The introduction of ``Data Layer`` includes the following parts. + +- Data Preparation +- Data API +- Data Loader +- Data Handler +- Dataset +- Cache +- Data and Cache File Structure + +Here is a typical example of Qlib data workflow + +- Users download data and converting data into Qlib format(with filename suffix `.bin`). In this step, typically only some basic data are stored on disk(such as OHLCV). +- Creating some basic features based on Qlib's expression Engine(e.g. "Ref($close, 60) / $close", the return of last 60 trading days). Supported operators in the expression engine can be found `here `__. This step is typically implemented in Qlib's `Data Loader `_ which is a component of `Data Handler `_ . +- If users require more complicated data processing (e.g. data normalization), `Data Handler `_ support user-customized processors to process data(some predefined processors can be found `here `__). The processors are different from operators in expression engine. It is designed for some complicated data processing methods which is hard to supported in operators in expression engine. +- At last, `Dataset `_ is responsible to prepare model-specific dataset from the processed data of Data Handler + +Data Preparation +================ + +Qlib Format Data +---------------- + +We've specially designed a data structure to manage financial data, please refer to the `File storage design section in Qlib paper `_ for detailed information. +Such data will be stored with filename suffix `.bin` (We'll call them `.bin` file, `.bin` format, or qlib format). `.bin` file is designed for scientific computing on finance data. + +``Qlib`` provides two different off-the-shelf datasets, which can be accessed through this `link `__: + +======================== ================= ================ +Dataset US Market China Market +======================== ================= ================ +Alpha360 √ √ + +Alpha158 √ √ +======================== ================= ================ + +Also, ``Qlib`` provides a high-frequency dataset. Users can run a high-frequency dataset example through this `link `__. + +Qlib Format Dataset +------------------- +``Qlib`` has provided an off-the-shelf dataset in `.bin` format, users could use the script ``scripts/get_data.py`` to download the China-Stock dataset as follows. User can also use numpy to load `.bin` file to validate data. +The price volume data look different from the actual dealing price because of they are **adjusted** (`adjusted price `_). And then you may find that the adjusted price may be different from different data sources. This is because different data sources may vary in the way of adjusting prices. Qlib normalize the price on first trading day of each stock to 1 when adjusting them. +Users can leverage `$factor` to get the original trading price (e.g. `$close / $factor` to get the original close price). + +Here are some discussions about the price adjusting of Qlib. + +- https://github.com/microsoft/qlib/issues/991#issuecomment-1075252402 + + +.. code-block:: bash + + # download 1d + python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --region cn + + # download 1min + python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/qlib_cn_1min --region cn --interval 1min + +In addition to China-Stock data, ``Qlib`` also includes a US-Stock dataset, which can be downloaded with the following command: + +.. code-block:: bash + + python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/us_data --region us + +After running the above command, users can find china-stock and us-stock data in ``Qlib`` format in the ``~/.qlib/qlib_data/cn_data`` directory and ``~/.qlib/qlib_data/us_data`` directory respectively. + +``Qlib`` also provides the scripts in ``scripts/data_collector`` to help users crawl the latest data on the Internet and convert it to qlib format. + +When ``Qlib`` is initialized with this dataset, users could build and evaluate their own models with it. Please refer to `Initialization <../start/initialization.html>`_ for more details. + +Automatic update of daily frequency data +---------------------------------------- + + **It is recommended that users update the data manually once (\-\-trading_date 2021-05-25) and then set it to update automatically.** + + For more information refer to: `yahoo collector `_ + + - Automatic update of data to the "qlib" directory each trading day(Linux) + - use *crontab*: `crontab -e` + - set up timed tasks: + + .. code-block:: bash + + * * * * 1-5 python