diff --git a/.gitattributes b/.gitattributes index 6a39b2550ba5d8f01bacb3db1a9443b0d547efa8..0e9c01e9dabaca1494b9361eb7ebea67a7a579be 100644 --- a/.gitattributes +++ b/.gitattributes @@ -60,3 +60,5 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.webm filter=lfs diff=lfs merge=lfs -text Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/_libs/expanding.cpython-313-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text 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 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/dataset/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/dataset/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..688cde99af7d9df3cbf50875c5ffe0c848246f63 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/dataset/weight.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/dataset/weight.py new file mode 100644 index 0000000000000000000000000000000000000000..ee82080533b7a1f46d898e467463d59e4a2f846f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/filter.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/filter.py new file mode 100644 index 0000000000000000000000000000000000000000..246d6baf76571991c9e03e277c93983f087a6397 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/inst_processor.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/inst_processor.py new file mode 100644 index 0000000000000000000000000000000000000000..e00132777d5fd81da920f8af8316a1d2aafa2afb --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/ops.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/ops.py new file mode 100644 index 0000000000000000000000000000000000000000..d9a2ffbb3e31f552e115ba3bdc97a200e3866f46 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/pit.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/pit.py new file mode 100644 index 0000000000000000000000000000000000000000..740fd7b19a4a7d16ce34233d730cdace25e812c1 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/storage/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26dd6d624e5852612db7ebc8489b8b66c0f6bc80 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/storage/file_storage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/file_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..8a100a2d19e8c1037fc49d636ec75327e374c285 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/data/storage/storage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/data/storage/storage.py new file mode 100644 index 0000000000000000000000000000000000000000..2eb7da1de664d167d223672a4eb0a5c6bf86af3b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/log.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/log.py new file mode 100644 index 0000000000000000000000000000000000000000..f7683d51163c625ac2d5514d1ff83aefd52ad913 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..490f28860f2750ea19f5161b613965101199f124 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/base.py new file mode 100644 index 0000000000000000000000000000000000000000..009a3bd1441d962b1c9f64259f89484d778db3a3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/ens/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/ensemble.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/ensemble.py new file mode 100644 index 0000000000000000000000000000000000000000..1670a6538ef5dc249fb278339517eb3d75159955 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/ens/group.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/ens/group.py new file mode 100644 index 0000000000000000000000000000000000000000..ba6f9f8071bbf8c859b59cd2e9831f43d8c10d82 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/interpret/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/interpret/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a490d7744248e8f9d49e328a726168eef77fef53 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/meta/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..75b9c38588ba931886950cf238e560598fe06714 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/meta/dataset.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..34a9b949b31cc71f7a3cfa2adb77e93aec14c265 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/meta/model.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/model.py new file mode 100644 index 0000000000000000000000000000000000000000..1f13dba34af9fda951ab9ab0a01b668f08dca442 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/meta/task.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/meta/task.py new file mode 100644 index 0000000000000000000000000000000000000000..a051acf14669c391f83596cc0e3a96e73906dafb --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/riskmodel/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..230fdfca0828f7e1a395d9f7bfc0d9dcade3dd48 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/riskmodel/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/base.py new file mode 100644 index 0000000000000000000000000000000000000000..7afacfe8ff23a8b295d9cd06092ef8e609390a2d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/riskmodel/poet.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/poet.py new file mode 100644 index 0000000000000000000000000000000000000000..42388d84cb387aa2bffb669fdfd83d5601346eb3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/riskmodel/shrink.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/shrink.py new file mode 100644 index 0000000000000000000000000000000000000000..c3c0e48ef8ba21ac7bd64c513e0cfe2ef154ec08 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/riskmodel/structured.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/riskmodel/structured.py new file mode 100644 index 0000000000000000000000000000000000000000..71e442536dc00147dc0655ee848d495b3357233a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/trainer.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..ce204420f81a36c50d7b672ecff49522a1a0bb85 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/model/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/model/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..10eeb945e7beb8d577f4b4fd26539910cda99b16 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a12afc399605270821047b55244bf7eabbb81633 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/aux_info.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/aux_info.py new file mode 100644 index 0000000000000000000000000000000000000000..1fd581544e10312128ef1c91cfe837b467fcf443 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/contrib/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/backtest.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/backtest.py new file mode 100644 index 0000000000000000000000000000000000000000..60602c10d3cf5ad557a714cea9a127049f28e64e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/contrib/naive_config_parser.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/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-313/qlib/rl/contrib/train_onpolicy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/train_onpolicy.py new file mode 100644 index 0000000000000000000000000000000000000000..83dd924103fcabc2e0bf8319442e7b40e3432d0a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/contrib/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/contrib/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cad25e0dba611627657d1789b027f0e174067c3f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/data/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d73517534c83a27e6370796a0669dffca36fa769 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/data/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e258abe869d74f26f6df7278665f8a7fb85ff09d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/data/integration.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/integration.py new file mode 100644 index 0000000000000000000000000000000000000000..e123b6c8cfa5d7aef89235b969ffe1a92c60fc34 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/data/native.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/native.py new file mode 100644 index 0000000000000000000000000000000000000000..3fdf852ef0b21e7c142dcc5071801afe922a51e2 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/data/pickle_styled.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/data/pickle_styled.py new file mode 100644 index 0000000000000000000000000000000000000000..4905b026a27c000a508ab30508e8726b562e4bbd --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/interpreter.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..5c9cc26c4e628eb35d99d1ff9521fac223a621d5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b985c13317bc2ebda7ae471ce4204b72db60e18a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/interpreter.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/interpreter.py new file mode 100644 index 0000000000000000000000000000000000000000..01b08115301bd6285eb40a88be470dc7c8383092 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/network.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/network.py new file mode 100644 index 0000000000000000000000000000000000000000..d6a11189cff8c3fb35d3ca7f4e5a9450948fa82f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/policy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/policy.py new file mode 100644 index 0000000000000000000000000000000000000000..a46b587aa1126c92b7e25899a636c0750311dddb --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/reward.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..0dcfd24bb38e6f494c257253f04c6397f72e64c6 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/simulator_qlib.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/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-313/qlib/rl/order_execution/simulator_simple.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/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-313/qlib/rl/order_execution/state.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/state.py new file mode 100644 index 0000000000000000000000000000000000000000..315735eaf8431ab262e2249ee26f11ec90bd7dd9 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/strategy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..7e66a1f0851ca0ee8cffd8cea306339d9b6f9c9e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/order_execution/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/order_execution/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4fb78ff91d185c4bf3c80b36a791f3fc2e5621 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/reward.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/reward.py new file mode 100644 index 0000000000000000000000000000000000000000..fd0dbdc86e82570ce83dcc8ba93a0d0ff3ee23ca --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/seed.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/seed.py new file mode 100644 index 0000000000000000000000000000000000000000..93d452a4a2ae5e125b57e322be43b8995b37dd92 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/simulator.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..72e74b64fae38ca83f0ee73372efff17a4764e25 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/strategy/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/strategy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26e12580bace49afc0f2b885802003195537d5df --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/strategy/single_order.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/strategy/single_order.py new file mode 100644 index 0000000000000000000000000000000000000000..45db0d9c8958d8c28ebaa81a4a26b996f098c6d9 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/trainer/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..828ba7bd3cb9024b45f143308e5c3fb8bd6d55e4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/trainer/api.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/trainer/api.py new file mode 100644 index 0000000000000000000000000000000000000000..aea99dc3dcc2ab0cf70c90920d131cffce76495d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/trainer/callbacks.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/trainer/callbacks.py new file mode 100644 index 0000000000000000000000000000000000000000..9d1bf4ba282060c796a1ce07896967642587f51c --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/trainer/trainer.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/trainer/trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a1046e966edbbd8500a51dc22e81e0572f824ff3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/trainer/vessel.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/trainer/vessel.py new file mode 100644 index 0000000000000000000000000000000000000000..b7912b488b5beeed188ba32c612b87210518c4ac --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/utils/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7c7ba205d87f8d21900273b9149f9bcc944d362b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/utils/data_queue.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/utils/data_queue.py new file mode 100644 index 0000000000000000000000000000000000000000..71c2dff65b961d413752527847d7b8fc1c7bd84c --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/utils/env_wrapper.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/utils/env_wrapper.py new file mode 100644 index 0000000000000000000000000000000000000000..e863b709a132bff740d252714e509d1b3431238d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/utils/finite_env.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/utils/finite_env.py new file mode 100644 index 0000000000000000000000000000000000000000..87f0900e160c80e96fd1682d7ade6f0b14840088 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/rl/utils/log.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/rl/utils/log.py new file mode 100644 index 0000000000000000000000000000000000000000..75aab20688552d35edc3382d016016e2d4eb2754 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/strategy/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/strategy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..59e481eb93dda48c81e04dd491cd3c9190c8eeb4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/strategy/base.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/strategy/base.py new file mode 100644 index 0000000000000000000000000000000000000000..a9e138fdbb7825002cb4a36ff336e5c5f765468f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/tests/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f9793cdabde511b64f5bea93e597526b29a2a439 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/tests/config.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/tests/config.py new file mode 100644 index 0000000000000000000000000000000000000000..ea1b236594569b65262b7cd0bc5e713aaf35001d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/tests/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/tests/data.py new file mode 100644 index 0000000000000000000000000000000000000000..2fa76855b58410c40a0912e4617727e0d93e32d5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/typehint.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/typehint.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd6e13c1a4071f2757708eb62b8c5ef2566f266 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2a94ebd555b4c12eb76112ddda323c0c797dc7f4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__pycache__/__init__.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__pycache__/__init__.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/__pycache__/file.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__pycache__/file.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/__pycache__/mod.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__pycache__/mod.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/__pycache__/pickle_utils.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__pycache__/pickle_utils.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/__pycache__/time.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/__pycache__/time.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/data.py new file mode 100644 index 0000000000000000000000000000000000000000..e7a9a1027f363cd7c1da9bb51f0b7ce39dbb3e34 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/exceptions.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa5c6dfe738963a4b64e78da5889457c0ae972b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/file.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/file.py new file mode 100644 index 0000000000000000000000000000000000000000..1e17a574a9de9b0f60cfaab832412219fc2eafd5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/index_data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/index_data.py new file mode 100644 index 0000000000000000000000000000000000000000..c707240d098986d7d61d5e0b7051453fb77e2405 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/mod.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/mod.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb2ed3f4534c6a4085442539705110092cae16a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/objm.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/objm.py new file mode 100644 index 0000000000000000000000000000000000000000..227adc7f3bff3efef6bd7cb9edec7ac489d1b34e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/paral.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/paral.py new file mode 100644 index 0000000000000000000000000000000000000000..a61778334136a5e5a107fc5f37b09f199e9e1ead --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/pickle_utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/pickle_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..920692f3c89f7385db79f6751749756f1ca70eaa --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/resam.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/resam.py new file mode 100644 index 0000000000000000000000000000000000000000..99aedfcd50c1c89f371c109f01efff03c60c04ac --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/serial.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/serial.py new file mode 100644 index 0000000000000000000000000000000000000000..720dbd792889b8a0643712142df367bfa9bd521f --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/utils/time.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/utils/time.py new file mode 100644 index 0000000000000000000000000000000000000000..b052f6ab9f755216912f356a58e9040f4e33cf51 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a29e471c04b47282cec280ff54784b419bacb4b0 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/exp.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/exp.py new file mode 100644 index 0000000000000000000000000000000000000000..ae165ef1f87ee547d028e521c6d9299ba3ccc718 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/expm.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/expm.py new file mode 100644 index 0000000000000000000000000000000000000000..cb48d156acf5e5a3c0fd953d351f6afe45805bfc --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/online/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/online/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/online/manager.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/online/manager.py new file mode 100644 index 0000000000000000000000000000000000000000..09e96d444f293709a371385482ce76cdf563c646 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/online/strategy.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/online/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..d545e4bc9a6fa46c2e69fad63a30374283002e2a --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/online/update.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/online/update.py new file mode 100644 index 0000000000000000000000000000000000000000..5047a1bd25e08fd4fdaf144f60bbf32077f951f3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/online/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/online/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c390ca009210da16b0a4386e9fc035558aaa6608 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/record_temp.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/record_temp.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd58ec209813197c342e937947e75daa5232c45 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/recorder.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/recorder.py new file mode 100644 index 0000000000000000000000000000000000000000..5fd99c0769fce2d349ac44d918fe2a04de41908e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/task/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/task/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a7ea80d9b9a8d82c9b304cc07673f136685ea083 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/task/collect.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/task/collect.py new file mode 100644 index 0000000000000000000000000000000000000000..bedbd96d2011f014f82391fa3c6f1c36858cc656 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/task/gen.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/task/gen.py new file mode 100644 index 0000000000000000000000000000000000000000..cf95e60063323137772601a41c3f83cc43e77405 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/task/manage.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/task/manage.py new file mode 100644 index 0000000000000000000000000000000000000000..df29f3550085148132456b43f92eafaf93d889fd --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/task/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/task/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4b4a7c06b8edbad70b61a756f8efbac27080643e --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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-313/qlib/workflow/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/qlib/workflow/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0f48c74f0b24c1e6ac1611ca0a47886aa5099661 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-313/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/lib.linux-x86_64-cpython-39/qlib/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b43dd6fc42aa3b19e9e1aaabbc26d12b6a65d042 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__init__.py @@ -0,0 +1,317 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from pathlib import Path + +from setuptools_scm import get_version + +try: + from ._version import version as __version__ +except ImportError: + __version__ = get_version(root="..", relative_to=__file__) +__version__bak = __version__ # This version is backup for QlibConfig.reset_qlib_version +import logging +import os +import platform +import re +import subprocess +from typing import Union + +from ruamel.yaml import YAML + +from .log import get_module_logger + + +# init qlib +def init(default_conf="client", **kwargs): + """ + + Parameters + ---------- + default_conf: str + the default value is client. Accepted values: client/server. + **kwargs : + clear_mem_cache: str + the default value is True; + Will the memory cache be clear. + It is often used to improve performance when init will be called for multiple times + skip_if_reg: bool: str + the default value is True; + When using the recorder, skip_if_reg can set to True to avoid loss of recorder. + + """ + from .config import C # pylint: disable=C0415 + from .data.cache import H # pylint: disable=C0415 + + logger = get_module_logger("Initialization") + + skip_if_reg = kwargs.pop("skip_if_reg", False) + if skip_if_reg and C.registered: + # if we reinitialize Qlib during running an experiment `R.start`. + # it will result in loss of the recorder + logger.warning("Skip initialization because `skip_if_reg is True`") + return + + clear_mem_cache = kwargs.pop("clear_mem_cache", True) + if clear_mem_cache: + H.clear() + C.set(default_conf, **kwargs) + get_module_logger.setLevel(C.logging_level) + + # mount nfs + for _freq, provider_uri in C.provider_uri.items(): + mount_path = C["mount_path"][_freq] + # check path if server/local + uri_type = C.dpm.get_uri_type(provider_uri) + if uri_type == C.LOCAL_URI: + if not Path(provider_uri).exists(): + if C["auto_mount"]: + logger.error( + f"Invalid provider uri: {provider_uri}, please check if a valid provider uri has been set. This path does not exist." + ) + else: + logger.warning(f"auto_path is False, please make sure {mount_path} is mounted") + elif uri_type == C.NFS_URI: + _mount_nfs_uri(provider_uri, C.dpm.get_data_uri(_freq), C["auto_mount"]) + else: + raise NotImplementedError(f"This type of URI is not supported") + + C.register() + + if "flask_server" in C: + logger.info(f"flask_server={C['flask_server']}, flask_port={C['flask_port']}") + logger.info("qlib successfully initialized based on %s settings." % default_conf) + data_path = {_freq: C.dpm.get_data_uri(_freq) for _freq in C.dpm.provider_uri.keys()} + logger.info(f"data_path={data_path}") + + +def _mount_nfs_uri(provider_uri, mount_path, auto_mount: bool = False): + LOG = get_module_logger("mount nfs", level=logging.INFO) + if mount_path is None: + raise ValueError(f"Invalid mount path: {mount_path}!") + if not re.match(r"^[a-zA-Z0-9.:/\-_]+$", provider_uri): + raise ValueError(f"Invalid provider_uri format: {provider_uri}") + # FIXME: the C["provider_uri"] is modified in this function + # If it is not modified, we can pass only provider_uri or mount_path instead of C + mount_command = ["sudo", "mount.nfs", provider_uri, mount_path] + # If the provider uri looks like this 172.23.233.89//data/csdesign' + # It will be a nfs path. The client provider will be used + if not auto_mount: # pylint: disable=R1702 + if not Path(mount_path).exists(): + raise FileNotFoundError( + f"Invalid mount path: {mount_path}! Please mount manually: {' '.join(mount_command)} or Set init parameter `auto_mount=True`" + ) + else: + # Judging system type + sys_type = platform.system() + if "windows" in sys_type.lower(): + # system: window + try: + subprocess.run( + ["mount", "-o", "anon", provider_uri, mount_path], + capture_output=True, + text=True, + check=True, + ) + LOG.info("Mount finished.") + except subprocess.CalledProcessError as e: + error_output = (e.stdout or "") + (e.stderr or "") + if e.returncode == 85: + LOG.warning(f"{provider_uri} already mounted at {mount_path}") + elif e.returncode == 53: + raise OSError("Network path not found") from e + elif "error" in error_output.lower() or "错误" in error_output: + raise OSError("Invalid mount path") from e + else: + raise OSError(f"Unknown mount error: {error_output.strip()}") from e + else: + # system: linux/Unix/Mac + # check mount + _remote_uri = provider_uri[:-1] if provider_uri.endswith("/") else provider_uri + # `mount a /b/c` is different from `mount a /b/c/`. So we convert it into string to make sure handling it accurately + mount_path = str(mount_path) + _mount_path = mount_path[:-1] if mount_path.endswith("/") else mount_path + _check_level_num = 2 + _is_mount = False + while _check_level_num: + with subprocess.Popen( + ["mount"], + text=True, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + ) as shell_r: + _command_log = shell_r.stdout.readlines() + _command_log = [line for line in _command_log if _remote_uri in line] + if len(_command_log) > 0: + for _c in _command_log: + if isinstance(_c, str): + _temp_mount = _c.split(" ")[2] + else: + _temp_mount = _c.decode("utf-8").split(" ")[2] + _temp_mount = _temp_mount[:-1] if _temp_mount.endswith("/") else _temp_mount + if _temp_mount == _mount_path: + _is_mount = True + break + if _is_mount: + break + _remote_uri = "/".join(_remote_uri.split("/")[:-1]) + _mount_path = "/".join(_mount_path.split("/")[:-1]) + _check_level_num -= 1 + + if not _is_mount: + try: + Path(mount_path).mkdir(parents=True, exist_ok=True) + except Exception as e: + raise OSError( + f"Failed to create directory {mount_path}, please create {mount_path} manually!" + ) from e + + # check nfs-common + command_res = os.popen("dpkg -l | grep nfs-common") + command_res = command_res.readlines() + if not command_res: + raise OSError("nfs-common is not found, please install it by execute: sudo apt install nfs-common") + # manually mount + try: + subprocess.run(mount_command, check=True, capture_output=True, text=True) + LOG.info("Mount finished.") + except subprocess.CalledProcessError as e: + if e.returncode == 256: + raise OSError("Mount failed: requires sudo or permission denied") from e + elif e.returncode == 32512: + raise OSError(f"mount {provider_uri} on {mount_path} error! Command error") from e + else: + raise OSError(f"Mount failed: {e.stderr}") from e + else: + LOG.warning(f"{_remote_uri} on {_mount_path} is already mounted") + + +def init_from_yaml_conf(conf_path, **kwargs): + """init_from_yaml_conf + + :param conf_path: A path to the qlib config in yml format + """ + + if conf_path is None: + config = {} + else: + with open(conf_path) as f: + yaml = YAML(typ="safe", pure=True) + config = yaml.load(f) + config.update(kwargs) + default_conf = config.pop("default_conf", "client") + init(default_conf, **config) + + +def get_project_path(config_name="config.yaml", cur_path: Union[Path, str, None] = None) -> Path: + """ + If users are building a project follow the following pattern. + - Qlib is a sub folder in project path + - There is a file named `config.yaml` in qlib. + + For example: + If your project file system structure follows such a pattern + + / + - config.yaml + - ...some folders... + - qlib/ + + This folder will return + + NOTE: link is not supported here. + + + This method is often used when + - user want to use a relative config path instead of hard-coding qlib config path in code + + Raises + ------ + FileNotFoundError: + If project path is not found + """ + if cur_path is None: + cur_path = Path(__file__).absolute().resolve() + cur_path = Path(cur_path) + while True: + if (cur_path / config_name).exists(): + return cur_path + if cur_path == cur_path.parent: + raise FileNotFoundError("We can't find the project path") + cur_path = cur_path.parent + + +def auto_init(**kwargs): + """ + This function will init qlib automatically with following priority + - Find the project configuration and init qlib + - The parsing process will be affected by the `conf_type` of the configuration file + - Init qlib with default config + - Skip initialization if already initialized + + :**kwargs: it may contain following parameters + cur_path: the start path to find the project path + + Here are two examples of the configuration + + Example 1) + If you want to create a new project-specific config based on a shared configure, you can use `conf_type: ref` + + .. code-block:: yaml + + conf_type: ref + qlib_cfg: '' # this could be null reference no config from other files + # following configs in `qlib_cfg_update` is project=specific + qlib_cfg_update: + exp_manager: + class: "MLflowExpManager" + module_path: "qlib.workflow.expm" + kwargs: + uri: "file://" + default_exp_name: "Experiment" + + Example 2) + If you want to create simple a standalone config, you can use following config(a.k.a. `conf_type: origin`) + + .. code-block:: python + + exp_manager: + class: "MLflowExpManager" + module_path: "qlib.workflow.expm" + kwargs: + uri: "file://" + default_exp_name: "Experiment" + + """ + kwargs["skip_if_reg"] = kwargs.get("skip_if_reg", True) + + try: + pp = get_project_path(cur_path=kwargs.pop("cur_path", None)) + except FileNotFoundError: + init(**kwargs) + else: + logger = get_module_logger("Initialization") + conf_pp = pp / "config.yaml" + with conf_pp.open() as f: + yaml = YAML(typ="safe", pure=True) + conf = yaml.load(f) + + conf_type = conf.get("conf_type", "origin") + if conf_type == "origin": + # The type of config is just like original qlib config + init_from_yaml_conf(conf_pp, **kwargs) + elif conf_type == "ref": + # This config type will be more convenient in following scenario + # - There is a shared configure file, and you don't want to edit it inplace. + # - The shared configure may be updated later, and you don't want to copy it. + # - You have some customized config. + qlib_conf_path = conf.get("qlib_cfg", None) + + # merge the arguments + qlib_conf_update = conf.get("qlib_cfg_update", {}) + for k, v in kwargs.items(): + if k in qlib_conf_update: + logger.warning(f"`qlib_conf_update` from conf_pp is override by `kwargs` on key '{k}'") + qlib_conf_update.update(kwargs) + + init_from_yaml_conf(qlib_conf_path, **qlib_conf_update) + logger.info(f"Auto load project config: {conf_pp}") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/__init__.cpython-313.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a71af1656c03e151830046307d628eb091672dbe Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/__init__.cpython-313.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/__init__.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2e31ba3744849f0a20d946a292a3c97564578256 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/__init__.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/_version.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/_version.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a238fcf8f87dd14403aad488b35866e534e41645 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/_version.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/config.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/config.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1a49ad3fad9f4458eb8c9b48301241335d0daad9 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/config.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/constant.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/constant.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd3b57dd30a665020c7b7d1aa1fff19a1c424245 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/constant.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/log.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/log.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd7bffd975ed0a749238f0c4728b51636566e53e Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/log.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/typehint.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/typehint.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..59109e51ebda1317aa7c61a8da70d7b67eadf155 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/__pycache__/typehint.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/_version.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..b0d4cab91d721e32dc8597957aeac7e4baec9190 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/_version.py @@ -0,0 +1,34 @@ +# file generated by setuptools-scm +# don't change, don't track in version control + +__all__ = [ + "__version__", + "__version_tuple__", + "version", + "version_tuple", + "__commit_id__", + "commit_id", +] + +TYPE_CHECKING = False +if TYPE_CHECKING: + from typing import Tuple + from typing import Union + + VERSION_TUPLE = Tuple[Union[int, str], ...] + COMMIT_ID = Union[str, None] +else: + VERSION_TUPLE = object + COMMIT_ID = object + +version: str +__version__: str +__version_tuple__: VERSION_TUPLE +version_tuple: VERSION_TUPLE +commit_id: COMMIT_ID +__commit_id__: COMMIT_ID + +__version__ = version = '0.9.8.dev27' +__version_tuple__ = version_tuple = (0, 9, 8, 'dev27') + +__commit_id__ = commit_id = 'g3097dcc99' diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9daba9115334142de12e98580151c93b34e59eec --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__init__.py @@ -0,0 +1,349 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import copy +from pathlib import Path +from typing import TYPE_CHECKING, Any, Generator, List, Optional, Tuple, Union + +import pandas as pd + +from .account import Account + +if TYPE_CHECKING: + from ..strategy.base import BaseStrategy + from .executor import BaseExecutor + from .decision import BaseTradeDecision + +from ..config import C +from ..log import get_module_logger +from ..utils import init_instance_by_config +from .backtest import INDICATOR_METRIC, PORT_METRIC, backtest_loop, collect_data_loop +from .decision import Order +from .exchange import Exchange +from .utils import CommonInfrastructure + +# make import more user-friendly by adding `from qlib.backtest import STH` + + +logger = get_module_logger("backtest caller") + + +def get_exchange( + exchange: Union[str, dict, object, Path] = None, + freq: str = "day", + start_time: Union[pd.Timestamp, str] = None, + end_time: Union[pd.Timestamp, str] = None, + codes: Union[list, str] = "all", + subscribe_fields: list = [], + open_cost: float = 0.0015, + close_cost: float = 0.0025, + min_cost: float = 5.0, + limit_threshold: Union[Tuple[str, str], float, None] | None = None, + deal_price: Union[str, Tuple[str, str], List[str]] | None = None, + **kwargs: Any, +) -> Exchange: + """get_exchange + + Parameters + ---------- + + # exchange related arguments + exchange: Exchange + It could be None or any types that are acceptable by `init_instance_by_config`. + freq: str + frequency of data. + start_time: Union[pd.Timestamp, str] + closed start time for backtest. + end_time: Union[pd.Timestamp, str] + closed end time for backtest. + codes: Union[list, str] + list stock_id list or a string of instruments (i.e. all, csi500, sse50) + subscribe_fields: list + subscribe fields. + open_cost : float + open transaction cost. It is a ratio. The cost is proportional to your order's deal amount. + close_cost : float + close transaction cost. It is a ratio. The cost is proportional to your order's deal amount. + min_cost : float + min transaction cost. It is an absolute amount of cost instead of a ratio of your order's deal amount. + e.g. You must pay at least 5 yuan of commission regardless of your order's deal amount. + deal_price: Union[str, Tuple[str, str], List[str]] + The `deal_price` supports following two types of input + - : str + - (, ): Tuple[str, str] or List[str] + + , or := + := str + - for example '$close', '$open', '$vwap' ("close" is OK. `Exchange` will help to prepend + "$" to the expression) + limit_threshold : float + limit move 0.1 (10%) for example, long and short with same limit. + + Returns + ------- + :class: Exchange + an initialized Exchange object + """ + + if limit_threshold is None: + limit_threshold = C.limit_threshold + if exchange is None: + logger.info("Create new exchange") + + exchange = Exchange( + freq=freq, + start_time=start_time, + end_time=end_time, + codes=codes, + deal_price=deal_price, + subscribe_fields=subscribe_fields, + limit_threshold=limit_threshold, + open_cost=open_cost, + close_cost=close_cost, + min_cost=min_cost, + **kwargs, + ) + return exchange + else: + return init_instance_by_config(exchange, accept_types=Exchange) + + +def create_account_instance( + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + benchmark: Optional[str], + account: Union[float, int, dict], + pos_type: str = "Position", +) -> Account: + """ + # TODO: is very strange pass benchmark_config in the account (maybe for report) + # There should be a post-step to process the report. + + Parameters + ---------- + start_time + start time of the benchmark + end_time + end time of the benchmark + benchmark : str + the benchmark for reporting + account : Union[ + float, + { + "cash": float, + "stock1": Union[ + int, # it is equal to {"amount": int} + {"amount": int, "price"(optional): float}, + ] + }, + ] + information for describing how to creating the account + For `float`: + Using Account with only initial cash + For `dict`: + key "cash" means initial cash. + key "stock1" means the information of first stock with amount and price(optional). + ... + pos_type: str + Postion type. + """ + if isinstance(account, (int, float)): + init_cash = account + position_dict = {} + elif isinstance(account, dict): + init_cash = account.pop("cash") + position_dict = account + else: + raise ValueError("account must be in (int, float, dict)") + + return Account( + init_cash=init_cash, + position_dict=position_dict, + pos_type=pos_type, + benchmark_config=( + {} + if benchmark is None + else { + "benchmark": benchmark, + "start_time": start_time, + "end_time": end_time, + } + ), + ) + + +def get_strategy_executor( + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + strategy: Union[str, dict, object, Path], + executor: Union[str, dict, object, Path], + benchmark: Optional[str] = "SH000300", + account: Union[float, int, dict] = 1e9, + exchange_kwargs: dict = {}, + pos_type: str = "Position", +) -> Tuple[BaseStrategy, BaseExecutor]: + # NOTE: + # - for avoiding recursive import + # - typing annotations is not reliable + from ..strategy.base import BaseStrategy # pylint: disable=C0415 + from .executor import BaseExecutor # pylint: disable=C0415 + + trade_account = create_account_instance( + start_time=start_time, + end_time=end_time, + benchmark=benchmark, + account=account, + pos_type=pos_type, + ) + + exchange_kwargs = copy.copy(exchange_kwargs) + if "start_time" not in exchange_kwargs: + exchange_kwargs["start_time"] = start_time + if "end_time" not in exchange_kwargs: + exchange_kwargs["end_time"] = end_time + trade_exchange = get_exchange(**exchange_kwargs) + + common_infra = CommonInfrastructure(trade_account=trade_account, trade_exchange=trade_exchange) + trade_strategy = init_instance_by_config(strategy, accept_types=BaseStrategy) + trade_strategy.reset_common_infra(common_infra) + trade_executor = init_instance_by_config(executor, accept_types=BaseExecutor) + trade_executor.reset_common_infra(common_infra) + + return trade_strategy, trade_executor + + +def backtest( + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + strategy: Union[str, dict, object, Path], + executor: Union[str, dict, object, Path], + benchmark: str = "SH000300", + account: Union[float, int, dict] = 1e9, + exchange_kwargs: dict = {}, + pos_type: str = "Position", +) -> Tuple[PORT_METRIC, INDICATOR_METRIC]: + """initialize the strategy and executor, then backtest function for the interaction of the outermost strategy and + executor in the nested decision execution + + Parameters + ---------- + start_time : Union[pd.Timestamp, str] + closed start time for backtest + **NOTE**: This will be applied to the outmost executor's calendar. + end_time : Union[pd.Timestamp, str] + closed end time for backtest + **NOTE**: This will be applied to the outmost executor's calendar. + E.g. Executor[day](Executor[1min]), setting `end_time == 20XX0301` will include all the minutes on 20XX0301 + strategy : Union[str, dict, object, Path] + for initializing outermost portfolio strategy. Please refer to the docs of init_instance_by_config for more + information. + executor : Union[str, dict, object, Path] + for initializing the outermost executor. + benchmark: str + the benchmark for reporting. + account : Union[float, int, Position] + information for describing how to create the account + For `float` or `int`: + Using Account with only initial cash + For `Position`: + Using Account with a Position + exchange_kwargs : dict + the kwargs for initializing Exchange + pos_type : str + the type of Position. + + Returns + ------- + portfolio_dict: PORT_METRIC + it records the trading portfolio_metrics information + indicator_dict: INDICATOR_METRIC + it computes the trading indicator + It is organized in a dict format + + """ + trade_strategy, trade_executor = get_strategy_executor( + start_time, + end_time, + strategy, + executor, + benchmark, + account, + exchange_kwargs, + pos_type=pos_type, + ) + return backtest_loop(start_time, end_time, trade_strategy, trade_executor) + + +def collect_data( + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + strategy: Union[str, dict, object, Path], + executor: Union[str, dict, object, Path], + benchmark: str = "SH000300", + account: Union[float, int, dict] = 1e9, + exchange_kwargs: dict = {}, + pos_type: str = "Position", + return_value: dict | None = None, +) -> Generator[object, None, None]: + """initialize the strategy and executor, then collect the trade decision data for rl training + + please refer to the docs of the backtest for the explanation of the parameters + + Yields + ------- + object + trade decision + """ + trade_strategy, trade_executor = get_strategy_executor( + start_time, + end_time, + strategy, + executor, + benchmark, + account, + exchange_kwargs, + pos_type=pos_type, + ) + yield from collect_data_loop(start_time, end_time, trade_strategy, trade_executor, return_value=return_value) + + +def format_decisions( + decisions: List[BaseTradeDecision], +) -> Optional[Tuple[str, List[Tuple[BaseTradeDecision, Union[Tuple, None]]]]]: + """ + format the decisions collected by `qlib.backtest.collect_data` + The decisions will be organized into a tree-like structure. + + Parameters + ---------- + decisions : List[BaseTradeDecision] + decisions collected by `qlib.backtest.collect_data` + + Returns + ------- + Tuple[str, List[Tuple[BaseTradeDecision, Union[Tuple, None]]]]: + + reformat the list of decisions into a more user-friendly format + := Tuple[, List[Tuple[, ]]] + - := ` in lower level` | None + - := "day" | "30min" | "1min" | ... + - := + """ + if len(decisions) == 0: + return None + + cur_freq = decisions[0].strategy.trade_calendar.get_freq() + + res: Tuple[str, list] = (cur_freq, []) + last_dec_idx = 0 + for i, dec in enumerate(decisions[1:], 1): + if dec.strategy.trade_calendar.get_freq() == cur_freq: + res[1].append((decisions[last_dec_idx], format_decisions(decisions[last_dec_idx + 1 : i]))) + last_dec_idx = i + res[1].append((decisions[last_dec_idx], format_decisions(decisions[last_dec_idx + 1 :]))) + return res + + +__all__ = ["Order", "backtest", "get_strategy_executor"] diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/__init__.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/__init__.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..478922b71aaa0f69a39d0982873463d280950069 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/__init__.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/account.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/account.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c74a860648680a9d98d09b6c0f95b65dca8e873 Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/account.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/decision.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/decision.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e79b06cee94b533b97d0b1e6d1c71bade8f866e Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/decision.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/utils.cpython-39.pyc b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/utils.cpython-39.pyc new file mode 100644 index 0000000000000000000000000000000000000000..045cf271480af9179fe8007d446dadf312f8942f Binary files /dev/null and b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/__pycache__/utils.cpython-39.pyc differ diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/account.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/account.py new file mode 100644 index 0000000000000000000000000000000000000000..b0e416f8f458d23deba1f8487a184c69cee82f71 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/account.py @@ -0,0 +1,417 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +import copy +from typing import Dict, List, Optional, Tuple, cast + +import pandas as pd + +from qlib.utils import init_instance_by_config + +from .decision import BaseTradeDecision, Order +from .exchange import Exchange +from .high_performance_ds import BaseOrderIndicator +from .position import BasePosition +from .report import Indicator, PortfolioMetrics + +""" +rtn & earning in the Account + rtn: + from order's view + 1.change if any order is executed, sell order or buy order + 2.change at the end of today, (today_close - stock_price) * amount + earning + from value of current position + earning will be updated at the end of trade date + earning = today_value - pre_value + **is consider cost** + while earning is the difference of two position value, so it considers cost, it is the true return rate + in the specific accomplishment for rtn, it does not consider cost, in other words, rtn - cost = earning + +""" + + +class AccumulatedInfo: + """ + accumulated trading info, including accumulated return/cost/turnover + AccumulatedInfo should be shared across different levels + """ + + def __init__(self) -> None: + self.reset() + + def reset(self) -> None: + self.rtn: float = 0.0 # accumulated return, do not consider cost + self.cost: float = 0.0 # accumulated cost + self.to: float = 0.0 # accumulated turnover + + def add_return_value(self, value: float) -> None: + self.rtn += value + + def add_cost(self, value: float) -> None: + self.cost += value + + def add_turnover(self, value: float) -> None: + self.to += value + + @property + def get_return(self) -> float: + return self.rtn + + @property + def get_cost(self) -> float: + return self.cost + + @property + def get_turnover(self) -> float: + return self.to + + +class Account: + """ + The correctness of the metrics of Account in nested execution depends on the shallow copy of `trade_account` in + qlib/backtest/executor.py:NestedExecutor + Different level of executor has different Account object when calculating metrics. But the position object is + shared cross all the Account object. + """ + + def __init__( + self, + init_cash: float = 1e9, + position_dict: dict = {}, + freq: str = "day", + benchmark_config: dict = {}, + pos_type: str = "Position", + port_metr_enabled: bool = True, + ) -> None: + """the trade account of backtest. + + Parameters + ---------- + init_cash : float, optional + initial cash, by default 1e9 + position_dict : Dict[ + stock_id, + Union[ + int, # it is equal to {"amount": int} + {"amount": int, "price"(optional): float}, + ] + ] + initial stocks with parameters amount and price, + if there is no price key in the dict of stocks, it will be filled by _fill_stock_value. + by default {}. + """ + + self._pos_type = pos_type + self._port_metr_enabled = port_metr_enabled + self.benchmark_config: dict = {} # avoid no attribute error + self.init_vars(init_cash, position_dict, freq, benchmark_config) + + def init_vars(self, init_cash: float, position_dict: dict, freq: str, benchmark_config: dict) -> None: + # 1) the following variables are shared by multiple layers + # - you will see a shallow copy instead of deepcopy in the NestedExecutor; + self.init_cash = init_cash + self.current_position: BasePosition = init_instance_by_config( + { + "class": self._pos_type, + "kwargs": { + "cash": init_cash, + "position_dict": position_dict, + }, + "module_path": "qlib.backtest.position", + }, + ) + self.accum_info = AccumulatedInfo() + + # 2) following variables are not shared between layers + self.portfolio_metrics: Optional[PortfolioMetrics] = None + self.hist_positions: Dict[pd.Timestamp, BasePosition] = {} + self.reset(freq=freq, benchmark_config=benchmark_config) + + def is_port_metr_enabled(self) -> bool: + """ + Is portfolio-based metrics enabled. + """ + return self._port_metr_enabled and not self.current_position.skip_update() + + def reset_report(self, freq: str, benchmark_config: dict) -> None: + # portfolio related metrics + if self.is_port_metr_enabled(): + # NOTE: + # `accum_info` and `current_position` are shared here + self.portfolio_metrics = PortfolioMetrics(freq, benchmark_config) + self.hist_positions = {} + + # fill stock value + # The frequency of account may not align with the trading frequency. + # This may result in obscure bugs when data quality is low. + if isinstance(self.benchmark_config, dict) and "start_time" in self.benchmark_config: + self.current_position.fill_stock_value(self.benchmark_config["start_time"], self.freq) + + # trading related metrics(e.g. high-frequency trading) + self.indicator = Indicator() + + def reset( + self, freq: str | None = None, benchmark_config: dict | None = None, port_metr_enabled: bool | None = None + ) -> None: + """reset freq and report of account + + Parameters + ---------- + freq : str, optional + frequency of account & report, by default None + benchmark_config : {}, optional + benchmark config of report, by default None + port_metr_enabled: bool + """ + if freq is not None: + self.freq = freq + if benchmark_config is not None: + self.benchmark_config = benchmark_config + if port_metr_enabled is not None: + self._port_metr_enabled = port_metr_enabled + + self.reset_report(self.freq, self.benchmark_config) + + def get_hist_positions(self) -> Dict[pd.Timestamp, BasePosition]: + return self.hist_positions + + def get_cash(self) -> float: + return self.current_position.get_cash() + + def _update_state_from_order(self, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + if self.is_port_metr_enabled(): + # update turnover + self.accum_info.add_turnover(trade_val) + # update cost + self.accum_info.add_cost(cost) + + # update return from order + trade_amount = trade_val / trade_price + if order.direction == Order.SELL: # 0 for sell + # when sell stock, get profit from price change + profit = trade_val - self.current_position.get_stock_price(order.stock_id) * trade_amount + self.accum_info.add_return_value(profit) # note here do not consider cost + + elif order.direction == Order.BUY: # 1 for buy + # when buy stock, we get return for the rtn computing method + # profit in buy order is to make rtn is consistent with earning at the end of bar + profit = self.current_position.get_stock_price(order.stock_id) * trade_amount - trade_val + self.accum_info.add_return_value(profit) # note here do not consider cost + + def update_order(self, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + if self.current_position.skip_update(): + # TODO: supporting polymorphism for account + # updating order for infinite position is meaningless + return + + # if stock is sold out, no stock price information in Position, then we should update account first, + # then update current position + # if stock is bought, there is no stock in current position, update current, then update account + # The cost will be subtracted from the cash at last. So the trading logic can ignore the cost calculation + if order.direction == Order.SELL: + # sell stock + self._update_state_from_order(order, trade_val, cost, trade_price) + # update current position + # for may sell all of stock_id + self.current_position.update_order(order, trade_val, cost, trade_price) + else: + # buy stock + # deal order, then update state + self.current_position.update_order(order, trade_val, cost, trade_price) + self._update_state_from_order(order, trade_val, cost, trade_price) + + def update_current_position( + self, + trade_start_time: pd.Timestamp, + trade_end_time: pd.Timestamp, + trade_exchange: Exchange, + ) -> None: + """ + Update current to make rtn consistent with earning at the end of bar, and update holding bar count of stock + """ + # update price for stock in the position and the profit from changed_price + # NOTE: updating position does not only serve portfolio metrics, it also serve the strategy + assert self.current_position is not None + + if not self.current_position.skip_update(): + stock_list = self.current_position.get_stock_list() + for code in stock_list: + # if suspended, no new price to be updated, profit is 0 + if trade_exchange.check_stock_suspended(code, trade_start_time, trade_end_time): + continue + bar_close = cast(float, trade_exchange.get_close(code, trade_start_time, trade_end_time)) + self.current_position.update_stock_price(stock_id=code, price=bar_close) + # update holding day count + # NOTE: updating bar_count does not only serve portfolio metrics, it also serve the strategy + self.current_position.add_count_all(bar=self.freq) + + def update_portfolio_metrics(self, trade_start_time: pd.Timestamp, trade_end_time: pd.Timestamp) -> None: + """update portfolio_metrics""" + # calculate earning + # account_value - last_account_value + # for the first trade date, account_value - init_cash + # self.portfolio_metrics.is_empty() to judge is_first_trade_date + # get last_account_value, last_total_cost, last_total_turnover + assert self.portfolio_metrics is not None + + if self.portfolio_metrics.is_empty(): + last_account_value = self.init_cash + last_total_cost = 0 + last_total_turnover = 0 + else: + last_account_value = self.portfolio_metrics.get_latest_account_value() + last_total_cost = self.portfolio_metrics.get_latest_total_cost() + last_total_turnover = self.portfolio_metrics.get_latest_total_turnover() + + # get now_account_value, now_stock_value, now_earning, now_cost, now_turnover + now_account_value = self.current_position.calculate_value() + now_stock_value = self.current_position.calculate_stock_value() + now_earning = now_account_value - last_account_value + now_cost = self.accum_info.get_cost - last_total_cost + now_turnover = self.accum_info.get_turnover - last_total_turnover + + # update portfolio_metrics for today + # judge whether the trading is begin. + # and don't add init account state into portfolio_metrics, due to we don't have excess return in those days. + self.portfolio_metrics.update_portfolio_metrics_record( + trade_start_time=trade_start_time, + trade_end_time=trade_end_time, + account_value=now_account_value, + cash=self.current_position.position["cash"], + return_rate=(now_earning + now_cost) / last_account_value, + # here use earning to calculate return, position's view, earning consider cost, true return + # in order to make same definition with original backtest in evaluate.py + total_turnover=self.accum_info.get_turnover, + turnover_rate=now_turnover / last_account_value, + total_cost=self.accum_info.get_cost, + cost_rate=now_cost / last_account_value, + stock_value=now_stock_value, + ) + + def update_hist_positions(self, trade_start_time: pd.Timestamp) -> None: + """update history position""" + now_account_value = self.current_position.calculate_value() + # set now_account_value to position + self.current_position.position["now_account_value"] = now_account_value + self.current_position.update_weight_all() + # update hist_positions + # note use deepcopy + self.hist_positions[trade_start_time] = copy.deepcopy(self.current_position) + + def update_indicator( + self, + trade_start_time: pd.Timestamp, + trade_exchange: Exchange, + atomic: bool, + outer_trade_decision: BaseTradeDecision, + trade_info: list = [], + inner_order_indicators: List[BaseOrderIndicator] = [], + decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]] = [], + indicator_config: dict = {}, + ) -> None: + """update trade indicators and order indicators in each bar end""" + # TODO: will skip empty decisions make it faster? `outer_trade_decision.empty():` + + # indicator is trading (e.g. high-frequency order execution) related analysis + self.indicator.reset() + + # aggregate the information for each order + if atomic: + self.indicator.update_order_indicators(trade_info) + else: + self.indicator.agg_order_indicators( + inner_order_indicators, + decision_list=decision_list, + outer_trade_decision=outer_trade_decision, + trade_exchange=trade_exchange, + indicator_config=indicator_config, + ) + + # aggregate all the order metrics a single step + self.indicator.cal_trade_indicators(trade_start_time, self.freq, indicator_config) + + # record the metrics + self.indicator.record(trade_start_time) + + def update_bar_end( + self, + trade_start_time: pd.Timestamp, + trade_end_time: pd.Timestamp, + trade_exchange: Exchange, + atomic: bool, + outer_trade_decision: BaseTradeDecision, + trade_info: list = [], + inner_order_indicators: List[BaseOrderIndicator] = [], + decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]] = [], + indicator_config: dict = {}, + ) -> None: + """update account at each trading bar step + + Parameters + ---------- + trade_start_time : pd.Timestamp + closed start time of step + trade_end_time : pd.Timestamp + closed end time of step + trade_exchange : Exchange + trading exchange, used to update current + atomic : bool + whether the trading executor is atomic, which means there is no higher-frequency trading executor inside it + - if atomic is True, calculate the indicators with trade_info + - else, aggregate indicators with inner indicators + outer_trade_decision: BaseTradeDecision + external trade decision + trade_info : List[(Order, float, float, float)], optional + trading information, by default None + - necessary if atomic is True + - list of tuple(order, trade_val, trade_cost, trade_price) + inner_order_indicators : Indicator, optional + indicators of inner executor, by default None + - necessary if atomic is False + - used to aggregate outer indicators + decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]] = None, + The decision list of the inner level: List[Tuple[, , ]] + The inner level + indicator_config : dict, optional + config of calculating indicators, by default {} + """ + if atomic is True and trade_info is None: + raise ValueError("trade_info is necessary in atomic executor") + elif atomic is False and inner_order_indicators is None: + raise ValueError("inner_order_indicators is necessary in un-atomic executor") + + # update current position and hold bar count in each bar end + self.update_current_position(trade_start_time, trade_end_time, trade_exchange) + + if self.is_port_metr_enabled(): + # portfolio_metrics is portfolio related analysis + self.update_portfolio_metrics(trade_start_time, trade_end_time) + self.update_hist_positions(trade_start_time) + + # update indicator in each bar end + self.update_indicator( + trade_start_time=trade_start_time, + trade_exchange=trade_exchange, + atomic=atomic, + outer_trade_decision=outer_trade_decision, + trade_info=trade_info, + inner_order_indicators=inner_order_indicators, + decision_list=decision_list, + indicator_config=indicator_config, + ) + + def get_portfolio_metrics(self) -> Tuple[pd.DataFrame, dict]: + """get the history portfolio_metrics and positions instance""" + if self.is_port_metr_enabled(): + assert self.portfolio_metrics is not None + _portfolio_metrics = self.portfolio_metrics.generate_portfolio_metrics_dataframe() + _positions = self.get_hist_positions() + return _portfolio_metrics, _positions + else: + raise ValueError("generate_portfolio_metrics should be True if you want to generate portfolio_metrics") + + def get_trade_indicator(self) -> Indicator: + """get the trade indicator instance, which has pa/pos/ffr info.""" + return self.indicator diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/backtest.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/backtest.py new file mode 100644 index 0000000000000000000000000000000000000000..418c7ad9fa16fb5a1da588c4b322018c821f1457 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/backtest.py @@ -0,0 +1,109 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from typing import Dict, TYPE_CHECKING, Generator, Optional, Tuple, Union, cast + +import pandas as pd + +from qlib.backtest.decision import BaseTradeDecision +from qlib.backtest.report import Indicator + +if TYPE_CHECKING: + from qlib.strategy.base import BaseStrategy + from qlib.backtest.executor import BaseExecutor + +from tqdm.auto import tqdm + +from ..utils.time import Freq + +PORT_METRIC = Dict[str, Tuple[pd.DataFrame, dict]] +INDICATOR_METRIC = Dict[str, Tuple[pd.DataFrame, Indicator]] + + +def backtest_loop( + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + trade_strategy: BaseStrategy, + trade_executor: BaseExecutor, +) -> Tuple[PORT_METRIC, INDICATOR_METRIC]: + """backtest function for the interaction of the outermost strategy and executor in the nested decision execution + + please refer to the docs of `collect_data_loop` + + Returns + ------- + portfolio_dict: PORT_METRIC + it records the trading portfolio_metrics information + indicator_dict: INDICATOR_METRIC + it computes the trading indicator + """ + return_value: dict = {} + for _decision in collect_data_loop(start_time, end_time, trade_strategy, trade_executor, return_value): + pass + + portfolio_dict = cast(PORT_METRIC, return_value.get("portfolio_dict")) + indicator_dict = cast(INDICATOR_METRIC, return_value.get("indicator_dict")) + + return portfolio_dict, indicator_dict + + +def collect_data_loop( + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + trade_strategy: BaseStrategy, + trade_executor: BaseExecutor, + return_value: dict | None = None, +) -> Generator[BaseTradeDecision, Optional[BaseTradeDecision], None]: + """Generator for collecting the trade decision data for rl training + + Parameters + ---------- + start_time : Union[pd.Timestamp, str] + closed start time for backtest + **NOTE**: This will be applied to the outmost executor's calendar. + end_time : Union[pd.Timestamp, str] + closed end time for backtest + **NOTE**: This will be applied to the outmost executor's calendar. + E.g. Executor[day](Executor[1min]), setting `end_time == 20XX0301` will include all the minutes on 20XX0301 + trade_strategy : BaseStrategy + the outermost portfolio strategy + trade_executor : BaseExecutor + the outermost executor + return_value : dict + used for backtest_loop + + Yields + ------- + object + trade decision + """ + trade_executor.reset(start_time=start_time, end_time=end_time) + trade_strategy.reset(level_infra=trade_executor.get_level_infra()) + + with tqdm(total=trade_executor.trade_calendar.get_trade_len(), desc="backtest loop") as bar: + _execute_result = None + while not trade_executor.finished(): + _trade_decision: BaseTradeDecision = trade_strategy.generate_trade_decision(_execute_result) + _execute_result = yield from trade_executor.collect_data(_trade_decision, level=0) + trade_strategy.post_exe_step(_execute_result) + bar.update(1) + trade_strategy.post_upper_level_exe_step() + + if return_value is not None: + all_executors = trade_executor.get_all_executors() + + portfolio_dict: PORT_METRIC = {} + indicator_dict: INDICATOR_METRIC = {} + + for executor in all_executors: + key = "{}{}".format(*Freq.parse(executor.time_per_step)) + if executor.trade_account.is_port_metr_enabled(): + portfolio_dict[key] = executor.trade_account.get_portfolio_metrics() + + indicator_df = executor.trade_account.get_trade_indicator().generate_trade_indicators_dataframe() + indicator_obj = executor.trade_account.get_trade_indicator() + indicator_dict[key] = (indicator_df, indicator_obj) + + return_value.update({"portfolio_dict": portfolio_dict, "indicator_dict": indicator_dict}) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/decision.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/decision.py new file mode 100644 index 0000000000000000000000000000000000000000..7188bec7a5ea20b5fe667f25f20b7e67429a6023 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/decision.py @@ -0,0 +1,596 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from abc import abstractmethod +from datetime import time +from enum import IntEnum + +# try to fix circular imports when enabling type hints +from typing import TYPE_CHECKING, Any, ClassVar, Generic, List, Optional, Tuple, TypeVar, Union, cast + +from qlib.backtest.utils import TradeCalendarManager +from qlib.data.data import Cal +from qlib.log import get_module_logger +from qlib.utils.time import concat_date_time, epsilon_change + +if TYPE_CHECKING: + from qlib.strategy.base import BaseStrategy + from qlib.backtest.exchange import Exchange + +from dataclasses import dataclass + +import numpy as np +import pandas as pd + +DecisionType = TypeVar("DecisionType") + + +class OrderDir(IntEnum): + # Order direction + SELL = 0 + BUY = 1 + + +@dataclass +class Order: + """ + stock_id : str + amount : float + start_time : pd.Timestamp + closed start time for order trading + end_time : pd.Timestamp + closed end time for order trading + direction : int + Order.SELL for sell; Order.BUY for buy + factor : float + presents the weight factor assigned in Exchange() + """ + + # 1) time invariant values + # - they are set by users and is time-invariant. + stock_id: str + amount: float # `amount` is a non-negative and adjusted value + direction: OrderDir + + # 2) time variant values: + # - Users may want to set these values when using lower level APIs + # - If users don't, TradeDecisionWO will help users to set them + # The interval of the order which belongs to (NOTE: this is not the expected order dealing range time) + start_time: pd.Timestamp + end_time: pd.Timestamp + + # 3) results + # - users should not care about these values + # - they are set by the backtest system after finishing the results. + # What the value should be about in all kinds of cases + # - not tradable: the deal_amount == 0 , factor is None + # - the stock is suspended and the entire order fails. No cost for this order + # - dealt or partially dealt: deal_amount >= 0 and factor is not None + deal_amount: float = 0.0 # `deal_amount` is a non-negative value + factor: Optional[float] = None + + # TODO: + # a status field to indicate the dealing result of the order + + # FIXME: + # for compatible now. + # Please remove them in the future + SELL: ClassVar[OrderDir] = OrderDir.SELL + BUY: ClassVar[OrderDir] = OrderDir.BUY + + def __post_init__(self) -> None: + if self.direction not in {Order.SELL, Order.BUY}: + raise NotImplementedError("direction not supported, `Order.SELL` for sell, `Order.BUY` for buy") + self.deal_amount = 0.0 + self.factor = None + + @property + def amount_delta(self) -> float: + """ + return the delta of amount. + - Positive value indicates buying `amount` of share + - Negative value indicates selling `amount` of share + """ + return self.amount * self.sign + + @property + def deal_amount_delta(self) -> float: + """ + return the delta of deal_amount. + - Positive value indicates buying `deal_amount` of share + - Negative value indicates selling `deal_amount` of share + """ + return self.deal_amount * self.sign + + @property + def sign(self) -> int: + """ + return the sign of trading + - `+1` indicates buying + - `-1` value indicates selling + """ + return self.direction * 2 - 1 + + @staticmethod + def parse_dir(direction: Union[str, int, np.integer, OrderDir, np.ndarray]) -> Union[OrderDir, np.ndarray]: + if isinstance(direction, OrderDir): + return direction + elif isinstance(direction, (int, float, np.integer, np.floating)): + return Order.BUY if direction > 0 else Order.SELL + elif isinstance(direction, str): + dl = direction.lower().strip() + if dl == "sell": + return OrderDir.SELL + elif dl == "buy": + return OrderDir.BUY + else: + raise NotImplementedError(f"This type of input is not supported") + elif isinstance(direction, np.ndarray): + direction_array = direction.copy() + direction_array[direction_array > 0] = Order.BUY + direction_array[direction_array <= 0] = Order.SELL + return direction_array + else: + raise NotImplementedError(f"This type of input is not supported") + + @property + def key_by_day(self) -> tuple: + """A hashable & unique key to identify this order, under the granularity in day.""" + return self.stock_id, self.date, self.direction + + @property + def key(self) -> tuple: + """A hashable & unique key to identify this order.""" + return self.stock_id, self.start_time, self.end_time, self.direction + + @property + def date(self) -> pd.Timestamp: + """Date of the order.""" + return pd.Timestamp(self.start_time.replace(hour=0, minute=0, second=0)) + + +class OrderHelper: + """ + Motivation + - Make generating order easier + - User may have no knowledge about the adjust-factor information about the system. + - It involves too much interaction with the exchange when generating orders. + """ + + def __init__(self, exchange: Exchange) -> None: + self.exchange = exchange + + @staticmethod + def create( + code: str, + amount: float, + direction: OrderDir, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + ) -> Order: + """ + help to create a order + + # TODO: create order for unadjusted amount order + + Parameters + ---------- + code : str + the id of the instrument + amount : float + **adjusted trading amount** + direction : OrderDir + trading direction + start_time : Union[str, pd.Timestamp] (optional) + The interval of the order which belongs to + end_time : Union[str, pd.Timestamp] (optional) + The interval of the order which belongs to + + Returns + ------- + Order: + The created order + """ + # NOTE: factor is a value belongs to the results section. User don't have to care about it when creating orders + return Order( + stock_id=code, + amount=amount, + start_time=None if start_time is None else pd.Timestamp(start_time), + end_time=None if end_time is None else pd.Timestamp(end_time), + direction=direction, + ) + + +class TradeRange: + @abstractmethod + def __call__(self, trade_calendar: TradeCalendarManager) -> Tuple[int, int]: + """ + This method will be call with following way + + The outer strategy give a decision with with `TradeRange` + The decision will be checked by the inner decision. + inner decision will pass its trade_calendar as parameter when getting the trading range + - The framework's step is integer-index based. + + Parameters + ---------- + trade_calendar : TradeCalendarManager + the trade_calendar is from inner strategy + + Returns + ------- + Tuple[int, int]: + the start index and end index which are tradable + + Raises + ------ + NotImplementedError: + Exceptions are raised when no range limitation + """ + raise NotImplementedError(f"Please implement the `__call__` method") + + @abstractmethod + def clip_time_range(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Tuple[pd.Timestamp, pd.Timestamp]: + """ + Parameters + ---------- + start_time : pd.Timestamp + end_time : pd.Timestamp + Both sides (start_time, end_time) are closed + + Returns + ------- + Tuple[pd.Timestamp, pd.Timestamp]: + The tradable time range. + - It is intersection of [start_time, end_time] and the rule of TradeRange itself + """ + raise NotImplementedError(f"Please implement the `clip_time_range` method") + + +class IdxTradeRange(TradeRange): + def __init__(self, start_idx: int, end_idx: int) -> None: + self._start_idx = start_idx + self._end_idx = end_idx + + def __call__(self, trade_calendar: TradeCalendarManager | None = None) -> Tuple[int, int]: + return self._start_idx, self._end_idx + + def clip_time_range(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Tuple[pd.Timestamp, pd.Timestamp]: + raise NotImplementedError + + +class TradeRangeByTime(TradeRange): + """This is a helper function for make decisions""" + + def __init__(self, start_time: str | time, end_time: str | time) -> None: + """ + This is a callable class. + + **NOTE**: + - It is designed for minute-bar for intra-day trading!!!!! + - Both start_time and end_time are **closed** in the range + + Parameters + ---------- + start_time : str | time + e.g. "9:30" + end_time : str | time + e.g. "14:30" + """ + self.start_time = pd.Timestamp(start_time).time() if isinstance(start_time, str) else start_time + self.end_time = pd.Timestamp(end_time).time() if isinstance(end_time, str) else end_time + assert self.start_time < self.end_time + + def __call__(self, trade_calendar: TradeCalendarManager) -> Tuple[int, int]: + if trade_calendar is None: + raise NotImplementedError("trade_calendar is necessary for getting TradeRangeByTime.") + + start_date = trade_calendar.start_time.date() + val_start, val_end = concat_date_time(start_date, self.start_time), concat_date_time(start_date, self.end_time) + return trade_calendar.get_range_idx(val_start, val_end) + + def clip_time_range(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Tuple[pd.Timestamp, pd.Timestamp]: + start_date = start_time.date() + val_start, val_end = concat_date_time(start_date, self.start_time), concat_date_time(start_date, self.end_time) + # NOTE: `end_date` should not be used. Because the `end_date` is for slicing. It may be in the next day + # Assumption: start_time and end_time is for intra-day trading. So it is OK for only using start_date + return max(val_start, start_time), min(val_end, end_time) + + +class BaseTradeDecision(Generic[DecisionType]): + """ + Trade decisions are made by strategy and executed by executor + + Motivation: + Here are several typical scenarios for `BaseTradeDecision` + + Case 1: + 1. Outer strategy makes a decision. The decision is not available at the start of current interval + 2. After a period of time, the decision are updated and become available + 3. The inner strategy try to get the decision and start to execute the decision according to `get_range_limit` + Case 2: + 1. The outer strategy's decision is available at the start of the interval + 2. Same as `case 1.3` + """ + + def __init__(self, strategy: BaseStrategy, trade_range: Union[Tuple[int, int], TradeRange, None] = None) -> None: + """ + Parameters + ---------- + strategy : BaseStrategy + The strategy who make the decision + trade_range: Union[Tuple[int, int], Callable] (optional) + The index range for underlying strategy. + + Here are two examples of trade_range for each type + + 1) Tuple[int, int] + start_index and end_index of the underlying strategy(both sides are closed) + + 2) TradeRange + + """ + self.strategy = strategy + self.start_time, self.end_time = strategy.trade_calendar.get_step_time() + # upper strategy has no knowledge about the sub executor before `_init_sub_trading` + self.total_step: Optional[int] = None + if isinstance(trade_range, tuple): + # for Tuple[int, int] + trade_range = IdxTradeRange(*trade_range) + self.trade_range: Optional[TradeRange] = trade_range + + def get_decision(self) -> List[DecisionType]: + """ + get the **concrete decision** (e.g. execution orders) + This will be called by the inner strategy + + Returns + ------- + List[DecisionType: + The decision result. Typically it is some orders + Example: + []: + Decision not available + [concrete_decision]: + available + """ + raise NotImplementedError(f"This type of input is not supported") + + def update(self, trade_calendar: TradeCalendarManager) -> Optional[BaseTradeDecision]: + """ + Be called at the **start** of each step. + + This function is design for following purpose + 1) Leave a hook for the strategy who make `self` decision to update the decision itself + 2) Update some information from the inner executor calendar + + Parameters + ---------- + trade_calendar : TradeCalendarManager + The calendar of the **inner strategy**!!!!! + + Returns + ------- + BaseTradeDecision: + New update, use new decision. If no updates, return None (use previous decision (or unavailable)) + """ + # purpose 1) + self.total_step = trade_calendar.get_trade_len() + + # purpose 2) + return self.strategy.update_trade_decision(self, trade_calendar) + + def _get_range_limit(self, **kwargs: Any) -> Tuple[int, int]: + if self.trade_range is not None: + return self.trade_range(trade_calendar=cast(TradeCalendarManager, kwargs.get("inner_calendar"))) + else: + raise NotImplementedError("The decision didn't provide an index range") + + def get_range_limit(self, **kwargs: Any) -> Tuple[int, int]: + """ + return the expected step range for limiting the decision execution time + Both left and right are **closed** + + if no available trade_range, `default_value` will be returned + + It is only used in `NestedExecutor` + - The outmost strategy will not follow any range limit (but it may give range_limit) + - The inner most strategy's range_limit will be useless due to atomic executors don't have such + features. + + **NOTE**: + 1) This function must be called after `self.update` in following cases(ensured by NestedExecutor): + - user relies on the auto-clip feature of `self.update` + + 2) This function will be called after _init_sub_trading in NestedExecutor. + + Parameters + ---------- + **kwargs: + { + "default_value": , # using dict is for distinguish no value provided or None provided + "inner_calendar": + # because the range limit will control the step range of inner strategy, inner calendar will be a + # important parameter when trade_range is callable + } + + Returns + ------- + Tuple[int, int]: + + Raises + ------ + NotImplementedError: + If the following criteria meet + 1) the decision can't provide a unified start and end + 2) default_value is not provided + """ + try: + _start_idx, _end_idx = self._get_range_limit(**kwargs) + except NotImplementedError as e: + if "default_value" in kwargs: + return kwargs["default_value"] + else: + # Default to get full index + raise NotImplementedError(f"The decision didn't provide an index range") from e + + # clip index + if getattr(self, "total_step", None) is not None: + # if `self.update` is called. + # Then the _start_idx, _end_idx should be clipped + assert self.total_step is not None + if _start_idx < 0 or _end_idx >= self.total_step: + logger = get_module_logger("decision") + logger.warning( + f"[{_start_idx},{_end_idx}] go beyond the total_step({self.total_step}), it will be clipped.", + ) + _start_idx, _end_idx = max(0, _start_idx), min(self.total_step - 1, _end_idx) + return _start_idx, _end_idx + + def get_data_cal_range_limit(self, rtype: str = "full", raise_error: bool = False) -> Tuple[int, int]: + """ + get the range limit based on data calendar + + NOTE: it is **total** range limit instead of a single step + + The following assumptions are made + 1) The frequency of the exchange in common_infra is the same as the data calendar + 2) Users want the index mod by **day** (i.e. 240 min) + + Parameters + ---------- + rtype: str + - "full": return the full limitation of the decision in the day + - "step": return the limitation of current step + + raise_error: bool + True: raise error if no trade_range is set + False: return full trade calendar. + + It is useful in following cases + - users want to follow the order specific trading time range when decision level trade range is not + available. Raising NotImplementedError to indicates that range limit is not available + + Returns + ------- + Tuple[int, int]: + the range limit in data calendar + + Raises + ------ + NotImplementedError: + If the following criteria meet + 1) the decision can't provide a unified start and end + 2) raise_error is True + """ + # potential performance issue + day_start = pd.Timestamp(self.start_time.date()) + day_end = epsilon_change(day_start + pd.Timedelta(days=1)) + freq = self.strategy.trade_exchange.freq + _, _, day_start_idx, day_end_idx = Cal.locate_index(day_start, day_end, freq=freq) + if self.trade_range is None: + if raise_error: + raise NotImplementedError(f"There is no trade_range in this case") + else: + return 0, day_end_idx - day_start_idx + else: + if rtype == "full": + val_start, val_end = self.trade_range.clip_time_range(day_start, day_end) + elif rtype == "step": + val_start, val_end = self.trade_range.clip_time_range(self.start_time, self.end_time) + else: + raise ValueError(f"This type of input {rtype} is not supported") + _, _, start_idx, end_index = Cal.locate_index(val_start, val_end, freq=freq) + return start_idx - day_start_idx, end_index - day_start_idx + + def empty(self) -> bool: + for obj in self.get_decision(): + if isinstance(obj, Order): + # Zero amount order will be treated as empty + if obj.amount > 1e-6: + return False + else: + return True + return True + + def mod_inner_decision(self, inner_trade_decision: BaseTradeDecision) -> None: + """ + This method will be called on the inner_trade_decision after it is generated. + `inner_trade_decision` will be changed **inplace**. + + Motivation of the `mod_inner_decision` + - Leave a hook for outer decision to affect the decision generated by the inner strategy + - e.g. the outmost strategy generate a time range for trading. But the upper layer can only affect the + nearest layer in the original design. With `mod_inner_decision`, the decision can passed through multiple + layers + + Parameters + ---------- + inner_trade_decision : BaseTradeDecision + """ + # base class provide a default behaviour to modify inner_trade_decision + # trade_range should be propagated when inner trade_range is not set + if inner_trade_decision.trade_range is None: + inner_trade_decision.trade_range = self.trade_range + + +class EmptyTradeDecision(BaseTradeDecision[object]): + def get_decision(self) -> List[object]: + return [] + + def empty(self) -> bool: + return True + + +class TradeDecisionWO(BaseTradeDecision[Order]): + """ + Trade Decision (W)ith (O)rder. + Besides, the time_range is also included. + """ + + def __init__( + self, + order_list: List[Order], + strategy: BaseStrategy, + trade_range: Union[Tuple[int, int], TradeRange, None] = None, + ) -> None: + super().__init__(strategy, trade_range=trade_range) + self.order_list = cast(List[Order], order_list) + start, end = strategy.trade_calendar.get_step_time() + for o in order_list: + assert isinstance(o, Order) + if o.start_time is None: + o.start_time = start + if o.end_time is None: + o.end_time = end + + def get_decision(self) -> List[Order]: + return self.order_list + + def __repr__(self) -> str: + return ( + f"class: {self.__class__.__name__}; " + f"strategy: {self.strategy}; " + f"trade_range: {self.trade_range}; " + f"order_list[{len(self.order_list)}]" + ) + + +class TradeDecisionWithDetails(TradeDecisionWO): + """ + Decision with detail information. + Detail information is used to generate execution reports. + """ + + def __init__( + self, + order_list: List[Order], + strategy: BaseStrategy, + trade_range: Optional[Tuple[int, int]] = None, + details: Optional[Any] = None, + ) -> None: + super().__init__(order_list, strategy, trade_range) + + self.details = details diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/exchange.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/exchange.py new file mode 100644 index 0000000000000000000000000000000000000000..69262fcbbadd79f5e252af7315f3a76b49e77dad --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/exchange.py @@ -0,0 +1,958 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +from __future__ import annotations + +from collections import defaultdict +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Type, Union, cast + +from ..utils.index_data import IndexData + +if TYPE_CHECKING: + from .account import Account + +import random + +import numpy as np +import pandas as pd + +from qlib.backtest.position import BasePosition + +from ..config import C +from ..constant import REG_CN, REG_TW +from ..data.data import D +from ..log import get_module_logger +from .decision import Order, OrderDir, OrderHelper +from .high_performance_ds import BaseQuote, NumpyQuote + + +class Exchange: + # `quote_df` is a pd.DataFrame class that contains basic information for backtesting + # After some processing, the data will later be maintained by `quote_cls` object for faster data retrieving. + # Some conventions for `quote_df` + # - $close is for calculating the total value at end of each day. + # - if $close is None, the stock on that day is regarded as suspended. + # - $factor is for rounding to the trading unit; + # - if any $factor is missing when $close exists, trading unit rounding will be disabled + quote_df: pd.DataFrame + + def __init__( + self, + freq: str = "day", + start_time: Union[pd.Timestamp, str] = None, + end_time: Union[pd.Timestamp, str] = None, + codes: Union[list, str] = "all", + deal_price: Union[str, Tuple[str, str], List[str], None] = None, + subscribe_fields: list = [], + limit_threshold: Union[Tuple[str, str], float, None] = None, + volume_threshold: Union[tuple, dict, None] = None, + open_cost: float = 0.0015, + close_cost: float = 0.0025, + min_cost: float = 5.0, + impact_cost: float = 0.0, + extra_quote: pd.DataFrame = None, + quote_cls: Type[BaseQuote] = NumpyQuote, + **kwargs: Any, + ) -> None: + """__init__ + :param freq: frequency of data + :param start_time: closed start time for backtest + :param end_time: closed end time for backtest + :param codes: list stock_id list or a string of instruments(i.e. all, csi500, sse50) + :param deal_price: Union[str, Tuple[str, str], List[str]] + The `deal_price` supports following two types of input + - : str + - (, ): Tuple[str] or List[str] + , or := + := str + - for example '$close', '$open', '$vwap' ("close" is OK. `Exchange` will help to prepend + "$" to the expression) + :param subscribe_fields: list, subscribe fields. This expressions will be added to the query and `self.quote`. + It is useful when users want more fields to be queried + :param limit_threshold: Union[Tuple[str, str], float, None] + 1) `None`: no limitation + 2) float, 0.1 for example, default None + 3) Tuple[str, str]: (, + ) + `False` value indicates the stock is tradable + `True` value indicates the stock is limited and not tradable + :param volume_threshold: Union[ + Dict[ + "all": ("cum" or "current", limit_str), + "buy": ("cum" or "current", limit_str), + "sell":("cum" or "current", limit_str), + ], + ("cum" or "current", limit_str), + ] + 1) ("cum" or "current", limit_str) denotes a single volume limit. + - limit_str is qlib data expression which is allowed to define your own Operator. + Please refer to qlib/contrib/ops/high_freq.py, here are any custom operator for + high frequency, such as DayCumsum. !!!NOTE: if you want you use the custom + operator, you need to register it in qlib_init. + - "cum" means that this is a cumulative value over time, such as cumulative market + volume. So when it is used as a volume limit, it is necessary to subtract the dealt + amount. + - "current" means that this is a real-time value and will not accumulate over time, + so it can be directly used as a capacity limit. + e.g. ("cum", "0.2 * DayCumsum($volume, '9:45', '14:45')"), ("current", "$bidV1") + 2) "all" means the volume limits are both buying and selling. + "buy" means the volume limits of buying. "sell" means the volume limits of selling. + Different volume limits will be aggregated with min(). If volume_threshold is only + ("cum" or "current", limit_str) instead of a dict, the volume limits are for + both by default. In other words, it is same as {"all": ("cum" or "current", limit_str)}. + 3) e.g. "volume_threshold": { + "all": ("cum", "0.2 * DayCumsum($volume, '9:45', '14:45')"), + "buy": ("current", "$askV1"), + "sell": ("current", "$bidV1"), + } + :param open_cost: cost rate for open, default 0.0015 + :param close_cost: cost rate for close, default 0.0025 + :param trade_unit: trade unit, 100 for China A market. + None for disable trade unit. + **NOTE**: `trade_unit` is included in the `kwargs`. It is necessary because we must + distinguish `not set` and `disable trade_unit` + :param min_cost: min cost, default 5 + :param impact_cost: market impact cost rate (a.k.a. slippage). A recommended value is 0.1. + :param extra_quote: pandas, dataframe consists of + columns: like ['$vwap', '$close', '$volume', '$factor', 'limit_sell', 'limit_buy']. + The limit indicates that the etf is tradable on a specific day. + Necessary fields: + $close is for calculating the total value at end of each day. + Optional fields: + $volume is only necessary when we limit the trade amount or calculate + PA(vwap) indicator + $vwap is only necessary when we use the $vwap price as the deal price + $factor is for rounding to the trading unit + limit_sell will be set to False by default (False indicates we can sell + this target on this day). + limit_buy will be set to False by default (False indicates we can buy + this target on this day). + index: MultipleIndex(instrument, pd.Datetime) + """ + self.freq = freq + self.start_time = start_time + self.end_time = end_time + + self.trade_unit = kwargs.pop("trade_unit", C.trade_unit) + if len(kwargs) > 0: + raise ValueError(f"Get Unexpected arguments {kwargs}") + + if limit_threshold is None: + limit_threshold = C.limit_threshold + if deal_price is None: + deal_price = C.deal_price + + # we have some verbose information here. So logging is enabled + self.logger = get_module_logger("online operator") + + # TODO: the quote, trade_dates, codes are not necessary. + # It is just for performance consideration. + self.limit_type = self._get_limit_type(limit_threshold) + if limit_threshold is None: + if C.region in [REG_CN, REG_TW]: + self.logger.warning(f"limit_threshold not set. The stocks hit the limit may be bought/sold") + elif self.limit_type == self.LT_FLT and abs(cast(float, limit_threshold)) > 0.1: + if C.region in [REG_CN, REG_TW]: + self.logger.warning(f"limit_threshold may not be set to a reasonable value") + + if isinstance(deal_price, str): + if deal_price[0] != "$": + deal_price = "$" + deal_price + self.buy_price = self.sell_price = deal_price + elif isinstance(deal_price, (tuple, list)): + self.buy_price, self.sell_price = cast(Tuple[str, str], deal_price) + else: + raise NotImplementedError(f"This type of input is not supported") + + if isinstance(codes, str): + codes = D.instruments(codes) + self.codes = codes + # Necessary fields + # $close is for calculating the total value at end of each day. + # - if $close is None, the stock on that day is regarded as suspended. + # $factor is for rounding to the trading unit + # $change is for calculating the limit of the stock + + #  get volume limit from kwargs + self.buy_vol_limit, self.sell_vol_limit, vol_lt_fields = self._get_vol_limit(volume_threshold) + + necessary_fields = {self.buy_price, self.sell_price, "$close", "$change", "$factor", "$volume"} + if self.limit_type == self.LT_TP_EXP: + assert isinstance(limit_threshold, tuple) + for exp in limit_threshold: + necessary_fields.add(exp) + all_fields = list(necessary_fields | set(vol_lt_fields) | set(subscribe_fields)) + + self.all_fields = all_fields + + self.open_cost = open_cost + self.close_cost = close_cost + self.min_cost = min_cost + self.impact_cost = impact_cost + + self.limit_threshold: Union[Tuple[str, str], float, None] = limit_threshold + self.volume_threshold = volume_threshold + self.extra_quote = extra_quote + self.get_quote_from_qlib() + + # init quote by quote_df + self.quote_cls = quote_cls + self.quote: BaseQuote = self.quote_cls(self.quote_df, freq) + + def get_quote_from_qlib(self) -> None: + # get stock data from qlib + if len(self.codes) == 0: + self.codes = D.instruments() + self.quote_df = D.features( + self.codes, + self.all_fields, + self.start_time, + self.end_time, + freq=self.freq, + disk_cache=True, + ) + self.quote_df.columns = self.all_fields + + # check buy_price data and sell_price data + for attr in ("buy_price", "sell_price"): + pstr = getattr(self, attr) # price string + if self.quote_df[pstr].isna().any(): + self.logger.warning("{} field data contains nan.".format(pstr)) + + # update trade_w_adj_price + if (self.quote_df["$factor"].isna() & ~self.quote_df["$close"].isna()).any(): + # The 'factor.day.bin' file not exists, and `factor` field contains `nan` + # Use adjusted price + self.trade_w_adj_price = True + self.logger.warning("factor.day.bin file not exists or factor contains `nan`. Order using adjusted_price.") + if self.trade_unit is not None: + self.logger.warning(f"trade unit {self.trade_unit} is not supported in adjusted_price mode.") + else: + # The `factor.day.bin` file exists and all data `close` and `factor` are not `nan` + # Use normal price + self.trade_w_adj_price = False + # update limit + self._update_limit(self.limit_threshold) + + # concat extra_quote + if self.extra_quote is not None: + # process extra_quote + if "$close" not in self.extra_quote: + raise ValueError("$close is necessray in extra_quote") + for attr in "buy_price", "sell_price": + pstr = getattr(self, attr) # price string + if pstr not in self.extra_quote.columns: + self.extra_quote[pstr] = self.extra_quote["$close"] + self.logger.warning(f"No {pstr} set for extra_quote. Use $close as {pstr}.") + if "$factor" not in self.extra_quote.columns: + self.extra_quote["$factor"] = 1.0 + self.logger.warning("No $factor set for extra_quote. Use 1.0 as $factor.") + if "limit_sell" not in self.extra_quote.columns: + self.extra_quote["limit_sell"] = False + self.logger.warning("No limit_sell set for extra_quote. All stock will be able to be sold.") + if "limit_buy" not in self.extra_quote.columns: + self.extra_quote["limit_buy"] = False + self.logger.warning("No limit_buy set for extra_quote. All stock will be able to be bought.") + assert set(self.extra_quote.columns) == set(self.quote_df.columns) - {"$change"} + self.quote_df = pd.concat([self.quote_df, self.extra_quote], sort=False, axis=0) + + LT_TP_EXP = "(exp)" # Tuple[str, str]: the limitation is calculated by a Qlib expression. + LT_FLT = "float" # float: the trading limitation is based on `abs($change) < limit_threshold` + LT_NONE = "none" # none: there is no trading limitation + + def _get_limit_type(self, limit_threshold: Union[tuple, float, None]) -> str: + """get limit type""" + if isinstance(limit_threshold, tuple): + return self.LT_TP_EXP + elif isinstance(limit_threshold, float): + return self.LT_FLT + elif limit_threshold is None: + return self.LT_NONE + else: + raise NotImplementedError(f"This type of `limit_threshold` is not supported") + + def _update_limit(self, limit_threshold: Union[Tuple, float, None]) -> None: + # $close may contain NaN, the nan indicates that the stock is not tradable at that timestamp + suspended = self.quote_df["$close"].isna() + # check limit_threshold + limit_type = self._get_limit_type(limit_threshold) + if limit_type == self.LT_NONE: + self.quote_df["limit_buy"] = suspended + self.quote_df["limit_sell"] = suspended + elif limit_type == self.LT_TP_EXP: + # set limit + limit_threshold = cast(tuple, limit_threshold) + # astype bool is necessary, because quote_df is an expression and could be float + self.quote_df["limit_buy"] = self.quote_df[limit_threshold[0]].astype("bool") | suspended + self.quote_df["limit_sell"] = self.quote_df[limit_threshold[1]].astype("bool") | suspended + elif limit_type == self.LT_FLT: + limit_threshold = cast(float, limit_threshold) + self.quote_df["limit_buy"] = self.quote_df["$change"].ge(limit_threshold) | suspended + self.quote_df["limit_sell"] = ( + self.quote_df["$change"].le(-limit_threshold) | suspended + ) # pylint: disable=E1130 + + @staticmethod + def _get_vol_limit(volume_threshold: Union[tuple, dict, None]) -> Tuple[Optional[list], Optional[list], set]: + """ + preprocess the volume limit. + get the fields need to get from qlib. + get the volume limit list of buying and selling which is composed of all limits. + Parameters + ---------- + volume_threshold : + please refer to the doc of exchange. + Returns + ------- + fields: set + the fields need to get from qlib. + buy_vol_limit: List[Tuple[str]] + all volume limits of buying. + sell_vol_limit: List[Tuple[str]] + all volume limits of selling. + Raises + ------ + ValueError + the format of volume_threshold is not supported. + """ + if volume_threshold is None: + return None, None, set() + + fields = set() + buy_vol_limit = [] + sell_vol_limit = [] + if isinstance(volume_threshold, tuple): + volume_threshold = {"all": volume_threshold} + + assert isinstance(volume_threshold, dict) + for key, vol_limit in volume_threshold.items(): + assert isinstance(vol_limit, tuple) + fields.add(vol_limit[1]) + + if key in ("buy", "all"): + buy_vol_limit.append(vol_limit) + if key in ("sell", "all"): + sell_vol_limit.append(vol_limit) + + return buy_vol_limit, sell_vol_limit, fields + + def check_stock_limit( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + direction: int | None = None, + ) -> bool: + """ + Parameters + ---------- + stock_id : str + start_time: pd.Timestamp + end_time: pd.Timestamp + direction : int, optional + trade direction, by default None + - if direction is None, check if tradable for buying and selling. + - if direction == Order.BUY, check the if tradable for buying + - if direction == Order.SELL, check the sell limit for selling. + + Returns + ------- + True: the trading of the stock is limited (maybe hit the highest/lowest price), hence the stock is not tradable + False: the trading of the stock is not limited, hence the stock may be tradable + """ + # NOTE: + # **all** is used when checking limitation. + # For example, the stock trading is limited in a day if every minute is limited in a day if every minute is limited. + if direction is None: + # The trading limitation is related to the trading direction + # if the direction is not provided, then any limitation from buy or sell will result in trading limitation + buy_limit = self.quote.get_data(stock_id, start_time, end_time, field="limit_buy", method="all") + sell_limit = self.quote.get_data(stock_id, start_time, end_time, field="limit_sell", method="all") + return bool(buy_limit or sell_limit) + elif direction == Order.BUY: + return cast(bool, self.quote.get_data(stock_id, start_time, end_time, field="limit_buy", method="all")) + elif direction == Order.SELL: + return cast(bool, self.quote.get_data(stock_id, start_time, end_time, field="limit_sell", method="all")) + else: + raise ValueError(f"direction {direction} is not supported!") + + def check_stock_suspended( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + ) -> bool: + """if stock is suspended(hence not tradable), True will be returned""" + # is suspended + if stock_id in self.quote.get_all_stock(): + # suspended stocks are represented by None $close stock + # The $close may contain NaN, + close = self.quote.get_data(stock_id, start_time, end_time, "$close") + if close is None: + # if no close record exists + return True + elif isinstance(close, IndexData): + # **any** non-NaN $close represents trading opportunity may exist + # if all returned is nan, then the stock is suspended + return cast(bool, cast(IndexData, close).isna().all()) + else: + # it is single value, make sure is not None + return np.isnan(close) + else: + # if the stock is not in the stock list, then it is not tradable and regarded as suspended + return True + + def is_stock_tradable( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + direction: int | None = None, + ) -> bool: + # check if stock can be traded + return not ( + self.check_stock_suspended(stock_id, start_time, end_time) + or self.check_stock_limit(stock_id, start_time, end_time, direction) + ) + + def check_order(self, order: Order) -> bool: + # check limit and suspended + return self.is_stock_tradable(order.stock_id, order.start_time, order.end_time, order.direction) + + def deal_order( + self, + order: Order, + trade_account: Account | None = None, + position: BasePosition | None = None, + dealt_order_amount: Dict[str, float] = defaultdict(float), + ) -> Tuple[float, float, float]: + """ + Deal order when the actual transaction + the results section in `Order` will be changed. + :param order: Deal the order. + :param trade_account: Trade account to be updated after dealing the order. + :param position: position to be updated after dealing the order. + :param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float} + :return: trade_val, trade_cost, trade_price + """ + # check order first. + if not self.check_order(order): + order.deal_amount = 0.0 + # using np.nan instead of None to make it more convenient to show the value in format string + self.logger.debug(f"Order failed due to trading limitation: {order}") + return 0.0, 0.0, np.nan + + if trade_account is not None and position is not None: + raise ValueError("trade_account and position can only choose one") + + # NOTE: order will be changed in this function + trade_price, trade_val, trade_cost = self._calc_trade_info_by_order( + order, + trade_account.current_position if trade_account else position, + dealt_order_amount, + ) + if trade_val > 1e-5: + # If the order can only be deal 0 value. Nothing to be updated + # Otherwise, it will result in + # 1) some stock with 0 value in the position + # 2) `trade_unit` of trade_cost will be lost in user account + if trade_account: + trade_account.update_order(order=order, trade_val=trade_val, cost=trade_cost, trade_price=trade_price) + elif position: + position.update_order(order=order, trade_val=trade_val, cost=trade_cost, trade_price=trade_price) + + return trade_val, trade_cost, trade_price + + def get_quote_info( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + field: str, + method: str = "ts_data_last", + ) -> Union[None, int, float, bool, IndexData]: + return self.quote.get_data(stock_id, start_time, end_time, field=field, method=method) + + def get_close( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + method: str = "ts_data_last", + ) -> Union[None, int, float, bool, IndexData]: + return self.quote.get_data(stock_id, start_time, end_time, field="$close", method=method) + + def get_volume( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + method: Optional[str] = "sum", + ) -> Union[None, int, float, bool, IndexData]: + """get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time)""" + return self.quote.get_data(stock_id, start_time, end_time, field="$volume", method=method) + + def get_deal_price( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + direction: OrderDir, + method: Optional[str] = "ts_data_last", + ) -> Union[None, int, float, bool, IndexData]: + if direction == OrderDir.SELL: + pstr = self.sell_price + elif direction == OrderDir.BUY: + pstr = self.buy_price + else: + raise NotImplementedError(f"This type of input is not supported") + + deal_price = self.quote.get_data(stock_id, start_time, end_time, field=pstr, method=method) + if method is not None and (deal_price is None or np.isnan(deal_price) or deal_price <= 1e-08): + self.logger.warning(f"(stock_id:{stock_id}, trade_time:{(start_time, end_time)}, {pstr}): {deal_price}!!!") + self.logger.warning(f"setting deal_price to close price") + deal_price = self.get_close(stock_id, start_time, end_time, method) + return deal_price + + def get_factor( + self, + stock_id: str, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + ) -> Optional[float]: + """ + Returns + ------- + Optional[float]: + `None`: if the stock is suspended `None` may be returned + `float`: return factor if the factor exists + """ + assert start_time is not None and end_time is not None, "the time range must be given" + if stock_id not in self.quote.get_all_stock(): + return None + return self.quote.get_data(stock_id, start_time, end_time, field="$factor", method="ts_data_last") + + def generate_amount_position_from_weight_position( + self, + weight_position: dict, + cash: float, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + direction: OrderDir = OrderDir.BUY, + ) -> dict: + """ + Generates the target position according to the weight and the cash. + NOTE: All the cash will be assigned to the tradable stock. + Parameter: + weight_position : dict {stock_id : weight}; allocate cash by weight_position + among then, weight must be in this range: 0 < weight < 1 + cash : cash + start_time : the start time point of the step + end_time : the end time point of the step + direction : the direction of the deal price for estimating the amount + # NOTE: this function is used for calculating target position. So the default direction is buy + """ + + # calculate the total weight of tradable value + tradable_weight = 0.0 + for stock_id, wp in weight_position.items(): + if self.is_stock_tradable(stock_id=stock_id, start_time=start_time, end_time=end_time): + # weight_position must be greater than 0 and less than 1 + if wp < 0 or wp > 1: + raise ValueError( + "weight_position is {}, " "weight_position is not in the range of (0, 1).".format(wp), + ) + tradable_weight += wp + + if tradable_weight - 1.0 >= 1e-5: + raise ValueError("tradable_weight is {}, can not greater than 1.".format(tradable_weight)) + + amount_dict = {} + for stock_id in weight_position: + if weight_position[stock_id] > 0.0 and self.is_stock_tradable( + stock_id=stock_id, + start_time=start_time, + end_time=end_time, + ): + amount_dict[stock_id] = ( + cash + * weight_position[stock_id] + / tradable_weight + // self.get_deal_price( + stock_id=stock_id, + start_time=start_time, + end_time=end_time, + direction=direction, + ) + ) + return amount_dict + + def get_real_deal_amount(self, current_amount: float, target_amount: float, factor: float | None = None) -> float: + """ + Calculate the real adjust deal amount when considering the trading unit + :param current_amount: + :param target_amount: + :param factor: + :return real_deal_amount; Positive deal_amount indicates buying more stock. + """ + if current_amount == target_amount: + return 0 + elif current_amount < target_amount: + deal_amount = target_amount - current_amount + deal_amount = self.round_amount_by_trade_unit(deal_amount, factor) + return deal_amount + else: + if target_amount == 0: + return -current_amount + else: + deal_amount = current_amount - target_amount + deal_amount = self.round_amount_by_trade_unit(deal_amount, factor) + return -deal_amount + + def generate_order_for_target_amount_position( + self, + target_position: dict, + current_position: dict, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + ) -> List[Order]: + """ + Note: some future information is used in this function + Parameter: + target_position : dict { stock_id : amount } + current_position : dict { stock_id : amount} + trade_unit : trade_unit + down sample : for amount 321 and trade_unit 100, deal_amount is 300 + deal order on trade_date + """ + # split buy and sell for further use + buy_order_list = [] + sell_order_list = [] + # three parts: kept stock_id, dropped stock_id, new stock_id + # handle kept stock_id + + # because the order of the set is not fixed, the trading order of the stock is different, so that the backtest + # results of the same parameter are different; + # so here we sort stock_id, and then randomly shuffle the order of stock_id + # because the same random seed is used, the final stock_id order is fixed + sorted_ids = sorted(set(list(current_position.keys()) + list(target_position.keys()))) + random.seed(0) + random.shuffle(sorted_ids) + for stock_id in sorted_ids: + # Do not generate order for the non-tradable stocks + if not self.is_stock_tradable(stock_id=stock_id, start_time=start_time, end_time=end_time): + continue + + target_amount = target_position.get(stock_id, 0) + current_amount = current_position.get(stock_id, 0) + factor = self.get_factor(stock_id, start_time=start_time, end_time=end_time) + + deal_amount = self.get_real_deal_amount(current_amount, target_amount, factor) + if deal_amount == 0: + continue + if deal_amount > 0: + # buy stock + buy_order_list.append( + Order( + stock_id=stock_id, + amount=deal_amount, + direction=Order.BUY, + start_time=start_time, + end_time=end_time, + factor=factor, + ), + ) + else: + # sell stock + sell_order_list.append( + Order( + stock_id=stock_id, + amount=abs(deal_amount), + direction=Order.SELL, + start_time=start_time, + end_time=end_time, + factor=factor, + ), + ) + # return order_list : buy + sell + return sell_order_list + buy_order_list + + def calculate_amount_position_value( + self, + amount_dict: dict, + start_time: pd.Timestamp, + end_time: pd.Timestamp, + only_tradable: bool = False, + direction: OrderDir = OrderDir.SELL, + ) -> float: + """Parameter + position : Position() + amount_dict : {stock_id : amount} + direction : the direction of the deal price for estimating the amount + # NOTE: + This function is used for calculating current position value. + So the default direction is sell. + """ + value = 0 + for stock_id in amount_dict: + if not only_tradable or ( + not self.check_stock_suspended(stock_id=stock_id, start_time=start_time, end_time=end_time) + and not self.check_stock_limit(stock_id=stock_id, start_time=start_time, end_time=end_time) + ): + value += ( + self.get_deal_price( + stock_id=stock_id, + start_time=start_time, + end_time=end_time, + direction=direction, + ) + * amount_dict[stock_id] + ) + return value + + def _get_factor_or_raise_error( + self, + factor: float | None = None, + stock_id: str | None = None, + start_time: pd.Timestamp = None, + end_time: pd.Timestamp = None, + ) -> float: + """Please refer to the docs of get_amount_of_trade_unit""" + if factor is None: + if stock_id is not None and start_time is not None and end_time is not None: + factor = self.get_factor(stock_id=stock_id, start_time=start_time, end_time=end_time) + else: + raise ValueError(f"`factor` and (`stock_id`, `start_time`, `end_time`) can't both be None") + assert factor is not None + return factor + + def get_amount_of_trade_unit( + self, + factor: float | None = None, + stock_id: str | None = None, + start_time: pd.Timestamp = None, + end_time: pd.Timestamp = None, + ) -> Optional[float]: + """ + get the trade unit of amount based on **factor** + the factor can be given directly or calculated in given time range and stock id. + `factor` has higher priority than `stock_id`, `start_time` and `end_time` + Parameters + ---------- + factor : float + the adjusted factor + stock_id : str + the id of the stock + start_time : + the start time of trading range + end_time : + the end time of trading range + """ + if not self.trade_w_adj_price and self.trade_unit is not None: + factor = self._get_factor_or_raise_error( + factor=factor, + stock_id=stock_id, + start_time=start_time, + end_time=end_time, + ) + return self.trade_unit / factor + else: + return None + + def round_amount_by_trade_unit( + self, + deal_amount: float, + factor: float | None = None, + stock_id: str | None = None, + start_time: pd.Timestamp = None, + end_time: pd.Timestamp = None, + ) -> float: + """Parameter + Please refer to the docs of get_amount_of_trade_unit + deal_amount : float, adjusted amount + factor : float, adjusted factor + return : float, real amount + """ + if not self.trade_w_adj_price and self.trade_unit is not None: + # the minimal amount is 1. Add 0.1 for solving precision problem. + factor = self._get_factor_or_raise_error( + factor=factor, + stock_id=stock_id, + start_time=start_time, + end_time=end_time, + ) + return (deal_amount * factor + 0.1) // self.trade_unit * self.trade_unit / factor + return deal_amount + + def _clip_amount_by_volume(self, order: Order, dealt_order_amount: dict) -> Optional[float]: + """parse the capacity limit string and return the actual amount of orders that can be executed. + NOTE: + this function will change the order.deal_amount **inplace** + - This will make the order info more accurate + Parameters + ---------- + order : Order + the order to be executed. + dealt_order_amount : dict + :param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float} + """ + vol_limit = self.buy_vol_limit if order.direction == Order.BUY else self.sell_vol_limit + + if vol_limit is None: + return order.deal_amount + + vol_limit_num: List[float] = [] + for limit in vol_limit: + assert isinstance(limit, tuple) + if limit[0] == "current": + limit_value = self.quote.get_data( + order.stock_id, + order.start_time, + order.end_time, + field=limit[1], + method="sum", + ) + vol_limit_num.append(cast(float, limit_value)) + elif limit[0] == "cum": + limit_value = self.quote.get_data( + order.stock_id, + order.start_time, + order.end_time, + field=limit[1], + method="ts_data_last", + ) + vol_limit_num.append(limit_value - dealt_order_amount[order.stock_id]) + else: + raise ValueError(f"{limit[0]} is not supported") + vol_limit_min = min(vol_limit_num) + orig_deal_amount = order.deal_amount + order.deal_amount = max(min(vol_limit_min, orig_deal_amount), 0) + if vol_limit_min < orig_deal_amount: + self.logger.debug(f"Order clipped due to volume limitation: {order}, {list(zip(vol_limit_num, vol_limit))}") + + return None + + def _get_buy_amount_by_cash_limit(self, trade_price: float, cash: float, cost_ratio: float) -> float: + """return the real order amount after cash limit for buying. + Parameters + ---------- + trade_price : float + cash : float + cost_ratio : float + + Return + ---------- + float + the real order amount after cash limit for buying. + """ + max_trade_amount = 0.0 + if cash >= self.min_cost: + # critical_price means the stock transaction price when the service fee is equal to min_cost. + critical_price = self.min_cost / cost_ratio + self.min_cost + if cash >= critical_price: + # the service fee is equal to cost_ratio * trade_amount + max_trade_amount = cash / (1 + cost_ratio) / trade_price + else: + # the service fee is equal to min_cost + max_trade_amount = (cash - self.min_cost) / trade_price + return max_trade_amount + + def _calc_trade_info_by_order( + self, + order: Order, + position: Optional[BasePosition], + dealt_order_amount: dict, + ) -> Tuple[float, float, float]: + """ + Calculation of trade info + **NOTE**: Order will be changed in this function + :param order: + :param position: Position + :param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float} + :return: trade_price, trade_val, trade_cost + """ + trade_price = cast( + float, + self.get_deal_price(order.stock_id, order.start_time, order.end_time, direction=order.direction), + ) + total_trade_val = cast(float, self.get_volume(order.stock_id, order.start_time, order.end_time)) * trade_price + order.factor = self.get_factor(order.stock_id, order.start_time, order.end_time) + order.deal_amount = order.amount # set to full amount and clip it step by step + # Clipping amount first + # - It simulates that the order is rejected directly by the exchange due to large order + # Another choice is placing it after rounding the order + # - It simulates that the large order is submitted, but partial is dealt regardless of rounding by trading unit. + self._clip_amount_by_volume(order, dealt_order_amount) + + # TODO: the adjusted cost ratio can be overestimated as deal_amount will be clipped in the next steps + trade_val = order.deal_amount * trade_price + if not total_trade_val or np.isnan(total_trade_val): + # TODO: assert trade_val == 0, f"trade_val != 0, total_trade_val: {total_trade_val}; order info: {order}" + adj_cost_ratio = self.impact_cost + else: + adj_cost_ratio = self.impact_cost * (trade_val / total_trade_val) ** 2 + + if order.direction == Order.SELL: + cost_ratio = self.close_cost + adj_cost_ratio + # sell + # if we don't know current position, we choose to sell all + # Otherwise, we clip the amount based on current position + if position is not None: + # TODO: make the trading shortable + current_amount = ( + position.get_stock_amount(order.stock_id) if position.check_stock(order.stock_id) else 0 + ) + if not np.isclose(order.deal_amount, current_amount): + # when not selling last stock. rounding is necessary + order.deal_amount = self.round_amount_by_trade_unit( + min(current_amount, order.deal_amount), + order.factor, + ) + + # in case of negative value of cash + if position.get_cash() + order.deal_amount * trade_price < max( + order.deal_amount * trade_price * cost_ratio, + self.min_cost, + ): + order.deal_amount = 0 + self.logger.debug(f"Order clipped due to cash limitation: {order}") + + elif order.direction == Order.BUY: + cost_ratio = self.open_cost + adj_cost_ratio + # buy + if position is not None: + cash = position.get_cash() + trade_val = order.deal_amount * trade_price + if cash < max(trade_val * cost_ratio, self.min_cost): + # cash cannot cover cost + order.deal_amount = 0 + self.logger.debug(f"Order clipped due to cost higher than cash: {order}") + elif cash < trade_val + max(trade_val * cost_ratio, self.min_cost): + # The money is not enough + max_buy_amount = self._get_buy_amount_by_cash_limit(trade_price, cash, cost_ratio) + order.deal_amount = self.round_amount_by_trade_unit( + min(max_buy_amount, order.deal_amount), + order.factor, + ) + self.logger.debug(f"Order clipped due to cash limitation: {order}") + else: + # The money is enough + order.deal_amount = self.round_amount_by_trade_unit(order.deal_amount, order.factor) + else: + # Unknown amount of money. Just round the amount + order.deal_amount = self.round_amount_by_trade_unit(order.deal_amount, order.factor) + + else: + raise NotImplementedError("order direction {} error".format(order.direction)) + + trade_val = order.deal_amount * trade_price + trade_cost = max(trade_val * cost_ratio, self.min_cost) + if trade_val <= 1e-5: + # if dealing is not successful, the trade_cost should be zero. + trade_cost = 0 + return trade_price, trade_val, trade_cost + + def get_order_helper(self) -> OrderHelper: + if not hasattr(self, "_order_helper"): + # cache to avoid recreate the same instance + self._order_helper = OrderHelper(self) + return self._order_helper diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/executor.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/executor.py new file mode 100644 index 0000000000000000000000000000000000000000..b5d4326a714a4a27dd75aef9daca8a769e44b9b3 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/executor.py @@ -0,0 +1,628 @@ +from __future__ import annotations + +import copy +from abc import abstractmethod +from collections import defaultdict +from types import GeneratorType +from typing import Any, Dict, Generator, List, Tuple, Union, cast + +import pandas as pd + +from qlib.backtest.account import Account +from qlib.backtest.position import BasePosition +from qlib.log import get_module_logger + +from ..strategy.base import BaseStrategy +from ..utils import init_instance_by_config +from .decision import BaseTradeDecision, Order +from .exchange import Exchange +from .utils import CommonInfrastructure, LevelInfrastructure, TradeCalendarManager, get_start_end_idx + + +class BaseExecutor: + """Base executor for trading""" + + def __init__( + self, + time_per_step: str, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + indicator_config: dict = {}, + generate_portfolio_metrics: bool = False, + verbose: bool = False, + track_data: bool = False, + trade_exchange: Exchange | None = None, + common_infra: CommonInfrastructure | None = None, + settle_type: str = BasePosition.ST_NO, + **kwargs: Any, + ) -> None: + """ + Parameters + ---------- + time_per_step : str + trade time per trading step, used for generate the trade calendar + show_indicator: bool, optional + whether to show indicators, : + - 'pa', the price advantage + - 'pos', the positive rate + - 'ffr', the fulfill rate + indicator_config: dict, optional + config for calculating trade indicator, including the following fields: + - 'show_indicator': whether to show indicators, optional, default by False. The indicators includes + - 'pa', the price advantage + - 'pos', the positive rate + - 'ffr', the fulfill rate + - 'pa_config': config for calculating price advantage(pa), optional + - 'base_price': the based price than which the trading price is advanced, Optional, default by 'twap' + - If 'base_price' is 'twap', the based price is the time weighted average price + - If 'base_price' is 'vwap', the based price is the volume weighted average price + - 'weight_method': weighted method when calculating total trading pa by different orders' pa in each + step, optional, default by 'mean' + - If 'weight_method' is 'mean', calculating mean value of different orders' pa + - If 'weight_method' is 'amount_weighted', calculating amount weighted average value of different + orders' pa + - If 'weight_method' is 'value_weighted', calculating value weighted average value of different + orders' pa + - 'ffr_config': config for calculating fulfill rate(ffr), optional + - 'weight_method': weighted method when calculating total trading ffr by different orders' ffr in each + step, optional, default by 'mean' + - If 'weight_method' is 'mean', calculating mean value of different orders' ffr + - If 'weight_method' is 'amount_weighted', calculating amount weighted average value of different + orders' ffr + - If 'weight_method' is 'value_weighted', calculating value weighted average value of different + orders' ffr + Example: + { + 'show_indicator': True, + 'pa_config': { + "agg": "twap", # "vwap" + "price": "$close", # default to use deal price of the exchange + }, + 'ffr_config':{ + 'weight_method': 'value_weighted', + } + } + generate_portfolio_metrics : bool, optional + whether to generate portfolio_metrics, by default False + verbose : bool, optional + whether to print trading info, by default False + track_data : bool, optional + whether to generate trade_decision, will be used when training rl agent + - If `self.track_data` is true, when making data for training, the input `trade_decision` of `execute` will + be generated by `collect_data` + - Else, `trade_decision` will not be generated + + trade_exchange : Exchange + exchange that provides market info, used to generate portfolio_metrics + - If generate_portfolio_metrics is None, trade_exchange will be ignored + - Else If `trade_exchange` is None, self.trade_exchange will be set with common_infra + + common_infra : CommonInfrastructure, optional: + common infrastructure for backtesting, may including: + - trade_account : Account, optional + trade account for trading + - trade_exchange : Exchange, optional + exchange that provides market info + + settle_type : str + Please refer to the docs of BasePosition.settle_start + """ + self.time_per_step = time_per_step + self.indicator_config = indicator_config + self.generate_portfolio_metrics = generate_portfolio_metrics + self.verbose = verbose + self.track_data = track_data + self._trade_exchange = trade_exchange + self.level_infra = LevelInfrastructure() + self.level_infra.reset_infra(common_infra=common_infra, executor=self) + self._settle_type = settle_type + self.reset(start_time=start_time, end_time=end_time, common_infra=common_infra) + if common_infra is None: + get_module_logger("BaseExecutor").warning(f"`common_infra` is not set for {self}") + + # record deal order amount in one day + self.dealt_order_amount: Dict[str, float] = defaultdict(float) + self.deal_day = None + + def reset_common_infra(self, common_infra: CommonInfrastructure, copy_trade_account: bool = False) -> None: + """ + reset infrastructure for trading + - reset trade_account + """ + if not hasattr(self, "common_infra"): + self.common_infra = common_infra + else: + self.common_infra.update(common_infra) + + self.level_infra.reset_infra(common_infra=self.common_infra) + + if common_infra.has("trade_account"): + # NOTE: there is a trick in the code. + # shallow copy is used instead of deepcopy. + # 1. So positions are shared + # 2. Others are not shared, so each level has it own metrics (portfolio and trading metrics) + self.trade_account: Account = ( + copy.copy(common_infra.get("trade_account")) + if copy_trade_account + else common_infra.get("trade_account") + ) + self.trade_account.reset(freq=self.time_per_step, port_metr_enabled=self.generate_portfolio_metrics) + + @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") + + @property + def trade_calendar(self) -> TradeCalendarManager: + """ + Though trade calendar can be accessed from multiple sources, but managing in a centralized way will make the + code easier + """ + return self.level_infra.get("trade_calendar") + + def reset(self, common_infra: CommonInfrastructure | None = None, **kwargs: Any) -> None: + """ + - reset `start_time` and `end_time`, used in trade calendar + - reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc + """ + + if "start_time" in kwargs or "end_time" in kwargs: + start_time = kwargs.get("start_time") + end_time = kwargs.get("end_time") + self.level_infra.reset_cal(freq=self.time_per_step, start_time=start_time, end_time=end_time) + if common_infra is not None: + self.reset_common_infra(common_infra) + + def get_level_infra(self) -> LevelInfrastructure: + return self.level_infra + + def finished(self) -> bool: + return self.trade_calendar.finished() + + def execute(self, trade_decision: BaseTradeDecision, level: int = 0) -> List[object]: + """execute the trade decision and return the executed result + + NOTE: this function is never used directly in the framework. Should we delete it? + + Parameters + ---------- + trade_decision : BaseTradeDecision + + level : int + the level of current executor + + Returns + ---------- + execute_result : List[object] + the executed result for trade decision + """ + return_value: dict = {} + for _decision in self.collect_data(trade_decision, return_value=return_value, level=level): + pass + return cast(list, return_value.get("execute_result")) + + @abstractmethod + def _collect_data( + self, + trade_decision: BaseTradeDecision, + level: int = 0, + ) -> Union[Generator[Any, Any, Tuple[List[object], dict]], Tuple[List[object], dict]]: + """ + Please refer to the doc of collect_data + The only difference between `_collect_data` and `collect_data` is that some common steps are moved into + collect_data + + Parameters + ---------- + Please refer to the doc of collect_data + + + Returns + ------- + Tuple[List[object], dict]: + (, ) + """ + + def collect_data( + self, + trade_decision: BaseTradeDecision, + return_value: dict | None = None, + level: int = 0, + ) -> Generator[Any, Any, List[object]]: + """Generator for collecting the trade decision data for rl training + + his function will make a step forward + + Parameters + ---------- + trade_decision : BaseTradeDecision + + level : int + the level of current executor. 0 indicates the top level + + return_value : dict + the mem address to return the value + e.g. {"return_value": } + + Returns + ---------- + execute_result : List[object] + the executed result for trade decision. + ** NOTE!!!! **: + 1) This is necessary, The return value of generator will be used in NestedExecutor + 2) Please note the executed results are not merged. + + Yields + ------- + object + trade decision + """ + + if self.track_data: + yield trade_decision + + atomic = not issubclass(self.__class__, NestedExecutor) # issubclass(A, A) is True + + if atomic and trade_decision.get_range_limit(default_value=None) is not None: + raise ValueError("atomic executor doesn't support specify `range_limit`") + + if self._settle_type != BasePosition.ST_NO: + self.trade_account.current_position.settle_start(self._settle_type) + + obj = self._collect_data(trade_decision=trade_decision, level=level) + + if isinstance(obj, GeneratorType): + yield_res = yield from obj + assert isinstance(yield_res, tuple) and len(yield_res) == 2 + res, kwargs = yield_res + else: + # Some concrete executor don't have inner decisions + res, kwargs = obj + + trade_start_time, trade_end_time = self.trade_calendar.get_step_time() + # Account will not be changed in this function + self.trade_account.update_bar_end( + trade_start_time, + trade_end_time, + self.trade_exchange, + atomic=atomic, + outer_trade_decision=trade_decision, + indicator_config=self.indicator_config, + **kwargs, + ) + + self.trade_calendar.step() + + if self._settle_type != BasePosition.ST_NO: + self.trade_account.current_position.settle_commit() + + if return_value is not None: + return_value.update({"execute_result": res}) + + return res + + def get_all_executors(self) -> List[BaseExecutor]: + """get all executors""" + return [self] + + +class NestedExecutor(BaseExecutor): + """ + Nested Executor with inner strategy and executor + - At each time `execute` is called, it will call the inner strategy and executor to execute the `trade_decision` + in a higher frequency env. + """ + + def __init__( + self, + time_per_step: str, + inner_executor: Union[BaseExecutor, dict], + inner_strategy: Union[BaseStrategy, dict], + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + indicator_config: dict = {}, + generate_portfolio_metrics: bool = False, + verbose: bool = False, + track_data: bool = False, + skip_empty_decision: bool = True, + align_range_limit: bool = True, + common_infra: CommonInfrastructure | None = None, + **kwargs: Any, + ) -> None: + """ + Parameters + ---------- + inner_executor : BaseExecutor + trading env in each trading bar. + inner_strategy : BaseStrategy + trading strategy in each trading bar + skip_empty_decision: bool + Will the executor skip call inner loop when the decision is empty. + It should be False in following cases + - The decisions may be updated by steps + - The inner executor may not follow the decisions from the outer strategy + align_range_limit: bool + force to align the trade_range decision + It is only for nested executor, because range_limit is given by outer strategy + """ + self.inner_executor: BaseExecutor = init_instance_by_config( + inner_executor, + common_infra=common_infra, + accept_types=BaseExecutor, + ) + self.inner_strategy: BaseStrategy = init_instance_by_config( + inner_strategy, + common_infra=common_infra, + accept_types=BaseStrategy, + ) + + self._skip_empty_decision = skip_empty_decision + self._align_range_limit = align_range_limit + + super(NestedExecutor, self).__init__( + time_per_step=time_per_step, + start_time=start_time, + end_time=end_time, + indicator_config=indicator_config, + generate_portfolio_metrics=generate_portfolio_metrics, + verbose=verbose, + track_data=track_data, + common_infra=common_infra, + **kwargs, + ) + + def reset_common_infra(self, common_infra: CommonInfrastructure, copy_trade_account: bool = False) -> None: + """ + reset infrastructure for trading + - reset inner_strategy and inner_executor common infra + """ + # NOTE: please refer to the docs of BaseExecutor.reset_common_infra for the meaning of `copy_trade_account` + + # The first level follow the `copy_trade_account` from the upper level + super(NestedExecutor, self).reset_common_infra(common_infra, copy_trade_account=copy_trade_account) + + # The lower level have to copy the trade_account + self.inner_executor.reset_common_infra(common_infra, copy_trade_account=True) + self.inner_strategy.reset_common_infra(common_infra) + + def _init_sub_trading(self, trade_decision: BaseTradeDecision) -> None: + trade_start_time, trade_end_time = self.trade_calendar.get_step_time() + self.inner_executor.reset(start_time=trade_start_time, end_time=trade_end_time) + sub_level_infra = self.inner_executor.get_level_infra() + self.level_infra.set_sub_level_infra(sub_level_infra) + self.inner_strategy.reset(level_infra=sub_level_infra, outer_trade_decision=trade_decision) + + def _update_trade_decision(self, trade_decision: BaseTradeDecision) -> BaseTradeDecision: + # outer strategy have chance to update decision each iterator + updated_trade_decision = trade_decision.update(self.inner_executor.trade_calendar) + if updated_trade_decision is not None: # TODO: always is None for now? + trade_decision = updated_trade_decision + # NEW UPDATE + # create a hook for inner strategy to update outer decision + trade_decision = self.inner_strategy.alter_outer_trade_decision(trade_decision) + return trade_decision + + def _collect_data( + self, + trade_decision: BaseTradeDecision, + level: int = 0, + ) -> Generator[Any, Any, Tuple[List[object], dict]]: + execute_result = [] + inner_order_indicators = [] + decision_list = [] + # NOTE: + # - this is necessary to calculating the steps in sub level + # - more detailed information will be set into trade decision + self._init_sub_trading(trade_decision) + + _inner_execute_result = None + while not self.inner_executor.finished(): + trade_decision = self._update_trade_decision(trade_decision) + + if trade_decision.empty() and self._skip_empty_decision: + # give one chance for outer strategy to update the strategy + # - For updating some information in the sub executor (the strategy have no knowledge of the inner + # executor when generating the decision) + break + + sub_cal: TradeCalendarManager = self.inner_executor.trade_calendar + + # NOTE: make sure get_start_end_idx is after `self._update_trade_decision` + start_idx, end_idx = get_start_end_idx(sub_cal, trade_decision) + if not self._align_range_limit or start_idx <= sub_cal.get_trade_step() <= end_idx: + # if force align the range limit, skip the steps outside the decision range limit + + res = self.inner_strategy.generate_trade_decision(_inner_execute_result) + + # NOTE: !!!!! + # the two lines below is for a special case in RL + # To solve the conflicts below + # - Normally, user will create a strategy and embed it into Qlib's executor and simulator interaction + # loop For a _nested qlib example_, (Qlib Strategy) <=> (Qlib Executor[(inner Qlib Strategy) <=> + # (inner Qlib Executor)]) + # - However, RL-based framework has it's own script to run the loop + # For an _RL learning example_, (RL Policy) <=> (RL Env[(inner Qlib Executor)]) + # To make it possible to run _nested qlib example_ and _RL learning example_ together, the solution + # below is proposed + # - The entry script follow the example of _RL learning example_ to be compatible with all kinds of + # RL Framework + # - Each step of (RL Env) will make (inner Qlib Executor) one step forward + # - (inner Qlib Strategy) is a proxy strategy, it will give the program control right to (RL Env) + # by `yield from` and wait for the action from the policy + # So the two lines below is the implementation of yielding control rights + if isinstance(res, GeneratorType): + res = yield from res + + _inner_trade_decision: BaseTradeDecision = res + + trade_decision.mod_inner_decision(_inner_trade_decision) # propagate part of decision information + + # NOTE sub_cal.get_step_time() must be called before collect_data in case of step shifting + decision_list.append((_inner_trade_decision, *sub_cal.get_step_time())) + + # NOTE: Trade Calendar will step forward in the follow line + _inner_execute_result = yield from self.inner_executor.collect_data( + trade_decision=_inner_trade_decision, + level=level + 1, + ) + assert isinstance(_inner_execute_result, list) + self.post_inner_exe_step(_inner_execute_result) + execute_result.extend(_inner_execute_result) + + inner_order_indicators.append( + self.inner_executor.trade_account.get_trade_indicator().get_order_indicator(raw=True), + ) + else: + # do nothing and just step forward + sub_cal.step() + + # Let inner strategy know that the outer level execution is done. + self.inner_strategy.post_upper_level_exe_step() + + return execute_result, {"inner_order_indicators": inner_order_indicators, "decision_list": decision_list} + + def post_inner_exe_step(self, inner_exe_res: List[object]) -> None: + """ + A hook for doing sth after each step of inner strategy + + Parameters + ---------- + inner_exe_res : + the execution result of inner task + """ + self.inner_strategy.post_exe_step(inner_exe_res) + + def get_all_executors(self) -> List[BaseExecutor]: + """get all executors, including self and inner_executor.get_all_executors()""" + return [self, *self.inner_executor.get_all_executors()] + + +def _retrieve_orders_from_decision(trade_decision: BaseTradeDecision) -> List[Order]: + """ + IDE-friendly helper function. + """ + decisions = trade_decision.get_decision() + orders: List[Order] = [] + for decision in decisions: + assert isinstance(decision, Order) + orders.append(decision) + return orders + + +class SimulatorExecutor(BaseExecutor): + """Executor that simulate the true market""" + + # TODO: TT_SERIAL & TT_PARAL will be replaced by feature fix_pos now. + # Please remove them in the future. + + # available trade_types + TT_SERIAL = "serial" + # The orders will be executed serially in a sequence + # In each trading step, it is possible that users sell instruments first and use the money to buy new instruments + TT_PARAL = "parallel" + # The orders will be executed in parallel + # In each trading step, if users try to sell instruments first and buy new instruments with money, failure will + # occur + + def __init__( + self, + time_per_step: str, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + indicator_config: dict = {}, + generate_portfolio_metrics: bool = False, + verbose: bool = False, + track_data: bool = False, + common_infra: CommonInfrastructure | None = None, + trade_type: str = TT_SERIAL, + **kwargs: Any, + ) -> None: + """ + Parameters + ---------- + trade_type: str + please refer to the doc of `TT_SERIAL` & `TT_PARAL` + """ + super(SimulatorExecutor, self).__init__( + time_per_step=time_per_step, + start_time=start_time, + end_time=end_time, + indicator_config=indicator_config, + generate_portfolio_metrics=generate_portfolio_metrics, + verbose=verbose, + track_data=track_data, + common_infra=common_infra, + **kwargs, + ) + + self.trade_type = trade_type + + def _get_order_iterator(self, trade_decision: BaseTradeDecision) -> List[Order]: + """ + + Parameters + ---------- + trade_decision : BaseTradeDecision + the trade decision given by the strategy + + Returns + ------- + List[Order]: + get a list orders according to `self.trade_type` + """ + orders = _retrieve_orders_from_decision(trade_decision) + + if self.trade_type == self.TT_SERIAL: + # Orders will be traded in a parallel way + order_it = orders + elif self.trade_type == self.TT_PARAL: + # NOTE: !!!!!!! + # Assumption: there will not be orders in different trading direction in a single step of a strategy !!!! + # The parallel trading failure will be caused only by the conflicts of money + # Therefore, make the buying go first will make sure the conflicts happen. + # It equals to parallel trading after sorting the order by direction + order_it = sorted(orders, key=lambda order: -order.direction) + else: + raise NotImplementedError(f"This type of input is not supported") + return order_it + + def _collect_data(self, trade_decision: BaseTradeDecision, level: int = 0) -> Tuple[List[object], dict]: + trade_start_time, _ = self.trade_calendar.get_step_time() + execute_result: list = [] + + for order in self._get_order_iterator(trade_decision): + # Each time we move into a new date, clear `self.dealt_order_amount` since it only maintains intraday + # information. + now_deal_day = self.trade_calendar.get_step_time()[0].floor(freq="D") + if self.deal_day is None or now_deal_day > self.deal_day: + self.dealt_order_amount = defaultdict(float) + self.deal_day = now_deal_day + + # execute the order. + # NOTE: The trade_account will be changed in this function + trade_val, trade_cost, trade_price = self.trade_exchange.deal_order( + order, + trade_account=self.trade_account, + dealt_order_amount=self.dealt_order_amount, + ) + execute_result.append((order, trade_val, trade_cost, trade_price)) + + self.dealt_order_amount[order.stock_id] += order.deal_amount + + if self.verbose: + print( + "[I {:%Y-%m-%d %H:%M:%S}]: {} {}, price {:.2f}, amount {}, deal_amount {}, factor {}, " + "value {:.2f}, cash {:.2f}.".format( + trade_start_time, + "sell" if order.direction == Order.SELL else "buy", + order.stock_id, + trade_price, + order.amount, + order.deal_amount, + order.factor, + trade_val, + self.trade_account.get_cash(), + ), + ) + return execute_result, {"trade_info": execute_result} diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/high_performance_ds.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/high_performance_ds.py new file mode 100644 index 0000000000000000000000000000000000000000..f149f13dd5c640dd0fa69b8e509485e6eadfbc52 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/high_performance_ds.py @@ -0,0 +1,658 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import inspect +import logging +from collections import OrderedDict +from functools import lru_cache +from typing import Any, Callable, Dict, Iterable, List, Optional, Text, Union, cast + +import numpy as np +import pandas as pd + +import qlib.utils.index_data as idd + +from ..log import get_module_logger +from ..utils.index_data import IndexData, SingleData +from ..utils.resam import resam_ts_data, ts_data_last +from ..utils.time import Freq, is_single_value + + +class BaseQuote: + def __init__(self, quote_df: pd.DataFrame, freq: str) -> None: + self.logger = get_module_logger("online operator", level=logging.INFO) + + def get_all_stock(self) -> Iterable: + """return all stock codes + + Return + ------ + Iterable + all stock codes + """ + + raise NotImplementedError(f"Please implement the `get_all_stock` method") + + def get_data( + self, + stock_id: str, + start_time: Union[pd.Timestamp, str], + end_time: Union[pd.Timestamp, str], + field: Union[str], + method: Optional[str] = None, + ) -> Union[None, int, float, bool, IndexData]: + """get the specific field of stock data during start time and end_time, + and apply method to the data. + + Example: + .. code-block:: + $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 + + this function is used for three case: + + 1. method is not None. It returns int/float/bool/None. + - It will return None in one case, the method return None + + print(get_data(stock_id="SH600000", start_time="2010-01-04", end_time="2010-01-06", field="$close", method="last")) + + 85.713585 + + 2. method is None. It returns IndexData. + print(get_data(stock_id="SH600000", start_time="2010-01-04", end_time="2010-01-06", field="$close", method=None)) + + IndexData([86.778313, 87.433578, 85.713585], [2010-01-04, 2010-01-05, 2010-01-06]) + + Parameters + ---------- + stock_id: str + start_time : Union[pd.Timestamp, str] + closed start time for backtest + end_time : Union[pd.Timestamp, str] + closed end time for backtest + field : str + the columns of data to fetch + method : Union[str, None] + the method apply to data. + e.g [None, "last", "all", "sum", "mean", "ts_data_last"] + + Return + ---------- + Union[None, int, float, bool, IndexData] + it will return None in following cases + - There is no stock data which meet the query criterion from data source. + - The `method` returns None + """ + + raise NotImplementedError(f"Please implement the `get_data` method") + + +class PandasQuote(BaseQuote): + def __init__(self, quote_df: pd.DataFrame, freq: str) -> None: + super().__init__(quote_df=quote_df, freq=freq) + quote_dict = {} + for stock_id, stock_val in quote_df.groupby(level="instrument", group_keys=False): + quote_dict[stock_id] = stock_val.droplevel(level="instrument") + self.data = quote_dict + + def get_all_stock(self): + return self.data.keys() + + def get_data(self, stock_id, start_time, end_time, field, method=None): + if method == "ts_data_last": + method = ts_data_last + stock_data = resam_ts_data(self.data[stock_id][field], start_time, end_time, method=method) + if stock_data is None: + return None + elif isinstance(stock_data, (bool, np.bool_, int, float, np.number)): + return stock_data + elif isinstance(stock_data, pd.Series): + return idd.SingleData(stock_data) + else: + raise ValueError(f"stock data from resam_ts_data must be a number, pd.Series or pd.DataFrame") + + +class NumpyQuote(BaseQuote): + def __init__(self, quote_df: pd.DataFrame, freq: str, region: str = "cn") -> None: + """NumpyQuote + + Parameters + ---------- + quote_df : pd.DataFrame + the init dataframe from qlib. + self.data : Dict(stock_id, IndexData.DataFrame) + """ + super().__init__(quote_df=quote_df, freq=freq) + quote_dict = {} + for stock_id, stock_val in quote_df.groupby(level="instrument", group_keys=False): + quote_dict[stock_id] = idd.MultiData(stock_val.droplevel(level="instrument")) + quote_dict[stock_id].sort_index() # To support more flexible slicing, we must sort data first + self.data = quote_dict + + n, unit = Freq.parse(freq) + if unit in Freq.SUPPORT_CAL_LIST: + self.freq = Freq.get_timedelta(1, unit) + else: + raise ValueError(f"{freq} is not supported in NumpyQuote") + self.region = region + + def get_all_stock(self): + return self.data.keys() + + @lru_cache(maxsize=512) + def get_data(self, stock_id, start_time, end_time, field, method=None): + # check stock id + if stock_id not in self.get_all_stock(): + return None + + # single data + # If it don't consider the classification of single data, it will consume a lot of time. + if is_single_value(start_time, end_time, self.freq, self.region): + # this is a very special case. + # skip aggregating function to speed-up the query calculation + + # FIXME: + # it will go to the else logic when it comes to the + # 1) the day before holiday when daily trading + # 2) the last minute of the day when intraday trading + try: + return self.data[stock_id].loc[start_time, field] + except KeyError: + return None + else: + data = self.data[stock_id].loc[start_time:end_time, field] + if data.empty: + return None + if method is not None: + data = self._agg_data(data, method) + return data + + @staticmethod + def _agg_data(data: IndexData, method: str) -> Union[IndexData, np.ndarray, None]: + """Agg data by specific method.""" + # FIXME: why not call the method of data directly? + if method == "sum": + return np.nansum(data) + elif method == "mean": + return np.nanmean(data) + elif method == "last": + # FIXME: I've never seen that this method was called. + # Please merge it with "ts_data_last" + return data[-1] + elif method == "all": + return data.all() + elif method == "ts_data_last": + valid_data = data.loc[~data.isna().data.astype(bool)] + if len(valid_data) == 0: + return None + else: + return valid_data.iloc[-1] + else: + raise ValueError(f"{method} is not supported") + + +class BaseSingleMetric: + """ + The data structure of the single metric. + The following methods are used for computing metrics in one indicator. + """ + + def __init__(self, metric: Union[dict, pd.Series]): + """Single data structure for each metric. + + Parameters + ---------- + metric : Union[dict, pd.Series] + keys/index is stock_id, value is the metric value. + for example: + SH600068 NaN + SH600079 1.0 + SH600266 NaN + ... + SZ300692 NaN + SZ300719 NaN, + """ + raise NotImplementedError(f"Please implement the `__init__` method") + + def __add__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__add__` method") + + def __radd__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + return self + other + + def __sub__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__sub__` method") + + def __rsub__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__rsub__` method") + + def __mul__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__mul__` method") + + def __truediv__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__truediv__` method") + + def __eq__(self, other: object) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__eq__` method") + + def __gt__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__gt__` method") + + def __lt__(self, other: Union[BaseSingleMetric, int, float]) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `__lt__` method") + + def __len__(self) -> int: + raise NotImplementedError(f"Please implement the `__len__` method") + + def sum(self) -> float: + raise NotImplementedError(f"Please implement the `sum` method") + + def mean(self) -> float: + raise NotImplementedError(f"Please implement the `mean` method") + + def count(self) -> int: + """Return the count of the single metric, NaN is not included.""" + + raise NotImplementedError(f"Please implement the `count` method") + + def abs(self) -> BaseSingleMetric: + raise NotImplementedError(f"Please implement the `abs` method") + + @property + def empty(self) -> bool: + """If metric is empty, return True.""" + + raise NotImplementedError(f"Please implement the `empty` method") + + def add(self, other: BaseSingleMetric, fill_value: float = None) -> BaseSingleMetric: + """Replace np.nan with fill_value in two metrics and add them.""" + + raise NotImplementedError(f"Please implement the `add` method") + + def replace(self, replace_dict: dict) -> BaseSingleMetric: + """Replace the value of metric according to replace_dict.""" + + raise NotImplementedError(f"Please implement the `replace` method") + + def apply(self, func: Callable) -> BaseSingleMetric: + """Replace the value of metric with func (metric). + Currently, the func is only qlib/backtest/order/Order.parse_dir. + """ + + raise NotImplementedError(f"Please implement the 'apply' method") + + +class BaseOrderIndicator: + """ + The data structure of order indicator. + !!!NOTE: There are two ways to organize the data structure. Please choose a better way. + 1. One way is using BaseSingleMetric to represent each metric. For example, the data + structure of PandasOrderIndicator is Dict[str, PandasSingleMetric]. It uses + PandasSingleMetric based on pd.Series to represent each metric. + 2. The another way doesn't use BaseSingleMetric to represent each metric. The data + structure of PandasOrderIndicator is a whole matrix. It means you are not necessary + to inherit the BaseSingleMetric. + """ + + def __init__(self): + self.data = {} # will be created in the subclass + self.logger = get_module_logger("online operator") + + def assign(self, col: str, metric: Union[dict, pd.Series]) -> None: + """assign one metric. + + Parameters + ---------- + col : str + the metric name of one metric. + metric : Union[dict, pd.Series] + one metric with stock_id index, such as deal_amount, ffr, etc. + for example: + SH600068 NaN + SH600079 1.0 + SH600266 NaN + ... + SZ300692 NaN + SZ300719 NaN, + """ + + raise NotImplementedError(f"Please implement the 'assign' method") + + def transfer(self, func: Callable, new_col: str = None) -> Optional[BaseSingleMetric]: + """compute new metric with existing metrics. + + Parameters + ---------- + func : Callable + the func of computing new metric. + the kwargs of func will be replaced with metric data by name in this function. + e.g. + def func(pa): + return (pa > 0).sum() / pa.count() + new_col : str, optional + New metric will be assigned in the data if new_col is not None, by default None. + + Return + ---------- + BaseSingleMetric + new metric. + """ + func_sig = inspect.signature(func).parameters.keys() + func_kwargs = {sig: self.data[sig] for sig in func_sig} + tmp_metric = func(**func_kwargs) + if new_col is not None: + self.data[new_col] = tmp_metric + return None + else: + return tmp_metric + + def get_metric_series(self, metric: str) -> pd.Series: + """return the single metric with pd.Series format. + + Parameters + ---------- + metric : str + the metric name. + + Return + ---------- + pd.Series + the single metric. + If there is no metric name in the data, return pd.Series(). + """ + + raise NotImplementedError(f"Please implement the 'get_metric_series' method") + + def get_index_data(self, metric: str) -> SingleData: + """get one metric with the format of SingleData + + Parameters + ---------- + metric : str + the metric name. + + Return + ------ + IndexData.Series + one metric with the format of SingleData + """ + + raise NotImplementedError(f"Please implement the 'get_index_data' method") + + @staticmethod + def sum_all_indicators( + order_indicator: BaseOrderIndicator, + indicators: List[BaseOrderIndicator], + metrics: Union[str, List[str]], + fill_value: float = 0, + ) -> None: + """sum indicators with the same metrics. + and assign to the order_indicator(BaseOrderIndicator). + NOTE: indicators could be a empty list when orders in lower level all fail. + + Parameters + ---------- + order_indicator : BaseOrderIndicator + the order indicator to assign. + indicators : List[BaseOrderIndicator] + the list of all inner indicators. + metrics : Union[str, List[str]] + all metrics needs to be sumed. + fill_value : float, optional + fill np.nan with value. By default None. + """ + + raise NotImplementedError(f"Please implement the 'sum_all_indicators' method") + + def to_series(self) -> Dict[Text, pd.Series]: + """return the metrics as pandas series + + for example: { "ffr": + SH600068 NaN + SH600079 1.0 + SH600266 NaN + ... + SZ300692 NaN + SZ300719 NaN, + ... + } + """ + raise NotImplementedError(f"Please implement the `to_series` method") + + +class SingleMetric(BaseSingleMetric): + def __init__(self, metric): + self.metric = metric + + def __add__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric + other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric + other.metric) + else: + return NotImplemented + + def __sub__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric - other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric - other.metric) + else: + return NotImplemented + + def __rsub__(self, other): + if isinstance(other, (int, float)): + return self.__class__(other - self.metric) + elif isinstance(other, self.__class__): + return self.__class__(other.metric - self.metric) + else: + return NotImplemented + + def __mul__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric * other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric * other.metric) + else: + return NotImplemented + + def __truediv__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric / other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric / other.metric) + else: + return NotImplemented + + def __eq__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric == other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric == other.metric) + else: + return NotImplemented + + def __gt__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric > other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric > other.metric) + else: + return NotImplemented + + def __lt__(self, other): + if isinstance(other, (int, float)): + return self.__class__(self.metric < other) + elif isinstance(other, self.__class__): + return self.__class__(self.metric < other.metric) + else: + return NotImplemented + + def __len__(self): + return len(self.metric) + + +class PandasSingleMetric(SingleMetric): + """Each SingleMetric is based on pd.Series.""" + + def __init__(self, metric: Union[dict, pd.Series] = {}): + if isinstance(metric, dict): + self.metric = pd.Series(metric) + elif isinstance(metric, pd.Series): + self.metric = metric + else: + raise ValueError(f"metric must be dict or pd.Series") + + def sum(self): + return self.metric.sum() + + def mean(self): + return self.metric.mean() + + def count(self): + return self.metric.count() + + def abs(self): + return self.__class__(self.metric.abs()) + + @property + def empty(self): + return self.metric.empty + + @property + def index(self): + return list(self.metric.index) + + def add(self, other: BaseSingleMetric, fill_value: float = None) -> PandasSingleMetric: + other = cast(PandasSingleMetric, other) + return self.__class__(self.metric.add(other.metric, fill_value=fill_value)) + + def replace(self, replace_dict: dict) -> PandasSingleMetric: + return self.__class__(self.metric.replace(replace_dict)) + + def apply(self, func: Callable) -> PandasSingleMetric: + return self.__class__(self.metric.apply(func)) + + def reindex(self, index: Any, fill_value: float) -> PandasSingleMetric: + return self.__class__(self.metric.reindex(index, fill_value=fill_value)) + + def __repr__(self): + return repr(self.metric) + + +class PandasOrderIndicator(BaseOrderIndicator): + """ + The data structure is OrderedDict(str: PandasSingleMetric). + Each PandasSingleMetric based on pd.Series is one metric. + Str is the name of metric. + """ + + def __init__(self) -> None: + super(PandasOrderIndicator, self).__init__() + self.data: Dict[str, PandasSingleMetric] = OrderedDict() + + def assign(self, col: str, metric: Union[dict, pd.Series]) -> None: + self.data[col] = PandasSingleMetric(metric) + + def get_index_data(self, metric: str) -> SingleData: + if metric in self.data: + return idd.SingleData(self.data[metric].metric) + else: + return idd.SingleData() + + def get_metric_series(self, metric: str) -> Union[pd.Series]: + if metric in self.data: + return self.data[metric].metric + else: + return pd.Series() + + def to_series(self): + return {k: v.metric for k, v in self.data.items()} + + @staticmethod + def sum_all_indicators( + order_indicator: BaseOrderIndicator, + indicators: List[BaseOrderIndicator], + metrics: Union[str, List[str]], + fill_value: float = 0, + ) -> None: + if isinstance(metrics, str): + metrics = [metrics] + for metric in metrics: + tmp_metric = PandasSingleMetric({}) + for indicator in indicators: + tmp_metric = tmp_metric.add(indicator.data[metric], fill_value) + order_indicator.assign(metric, tmp_metric.metric) + + def __repr__(self): + return repr(self.data) + + +class NumpyOrderIndicator(BaseOrderIndicator): + """ + The data structure is OrderedDict(str: SingleData). + Each idd.SingleData is one metric. + Str is the name of metric. + """ + + def __init__(self) -> None: + super(NumpyOrderIndicator, self).__init__() + self.data: Dict[str, SingleData] = OrderedDict() + + def assign(self, col: str, metric: dict) -> None: + self.data[col] = idd.SingleData(metric) + + def get_index_data(self, metric: str) -> SingleData: + if metric in self.data: + return self.data[metric] + else: + return idd.SingleData() + + def get_metric_series(self, metric: str) -> Union[pd.Series]: + return self.data[metric].to_series() + + def to_series(self) -> Dict[str, pd.Series]: + tmp_metric_dict = {} + for metric in self.data: + tmp_metric_dict[metric] = self.get_metric_series(metric) + return tmp_metric_dict + + @staticmethod + def sum_all_indicators( + order_indicator: BaseOrderIndicator, + indicators: List[BaseOrderIndicator], + metrics: Union[str, List[str]], + fill_value: float = 0, + ) -> None: + # get all index(stock_id) + stock_set: set = set() + for indicator in indicators: + # set(np.ndarray.tolist()) is faster than set(np.ndarray) + stock_set = stock_set | set(indicator.data[metrics[0]].index.tolist()) + stocks = sorted(list(stock_set)) + + # add metric by index + if isinstance(metrics, str): + metrics = [metrics] + for metric in metrics: + order_indicator.data[metric] = idd.sum_by_index( + [indicator.data[metric] for indicator in indicators], + stocks, + fill_value, + ) + + def __repr__(self): + return repr(self.data) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/position.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/position.py new file mode 100644 index 0000000000000000000000000000000000000000..e6f46279f3bf524fc3de64e6ec1f18bd657f1aac --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/position.py @@ -0,0 +1,565 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from datetime import timedelta +from typing import Any, Dict, List, Union + +import numpy as np +import pandas as pd + +from ..data.data import D +from .decision import Order + + +class BasePosition: + """ + The Position wants to maintain the position like a dictionary + Please refer to the `Position` class for the position + """ + + def __init__(self, *args: Any, cash: float = 0.0, **kwargs: Any) -> None: + self._settle_type = self.ST_NO + self.position: dict = {} + + def fill_stock_value(self, start_time: Union[str, pd.Timestamp], freq: str, last_days: int = 30) -> None: + pass + + def skip_update(self) -> bool: + """ + Should we skip updating operation for this position + For example, updating is meaningless for InfPosition + + Returns + ------- + bool: + should we skip the updating operator + """ + return False + + def check_stock(self, stock_id: str) -> bool: + """ + check if is the stock in the position + + Parameters + ---------- + stock_id : str + the id of the stock + + Returns + ------- + bool: + if is the stock in the position + """ + raise NotImplementedError(f"Please implement the `check_stock` method") + + def update_order(self, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + """ + Parameters + ---------- + order : Order + the order to update the position + trade_val : float + the trade value(money) of dealing results + cost : float + the trade cost of the dealing results + trade_price : float + the trade price of the dealing results + """ + raise NotImplementedError(f"Please implement the `update_order` method") + + def update_stock_price(self, stock_id: str, price: float) -> None: + """ + Updating the latest price of the order + The useful when clearing balance at each bar end + + Parameters + ---------- + stock_id : + the id of the stock + price : float + the price to be updated + """ + raise NotImplementedError(f"Please implement the `update stock price` method") + + def calculate_stock_value(self) -> float: + """ + calculate the value of the all assets except cash in the position + + Returns + ------- + float: + the value(money) of all the stock + """ + raise NotImplementedError(f"Please implement the `calculate_stock_value` method") + + def calculate_value(self) -> float: + raise NotImplementedError(f"Please implement the `calculate_value` method") + + def get_stock_list(self) -> List[str]: + """ + Get the list of stocks in the position. + """ + raise NotImplementedError(f"Please implement the `get_stock_list` method") + + def get_stock_price(self, code: str) -> float: + """ + get the latest price of the stock + + Parameters + ---------- + code : + the code of the stock + """ + raise NotImplementedError(f"Please implement the `get_stock_price` method") + + def get_stock_amount(self, code: str) -> float: + """ + get the amount of the stock + + Parameters + ---------- + code : + the code of the stock + + Returns + ------- + float: + the amount of the stock + """ + raise NotImplementedError(f"Please implement the `get_stock_amount` method") + + def get_cash(self, include_settle: bool = False) -> float: + """ + Parameters + ---------- + include_settle: + will the unsettled(delayed) cash included + Default: not include those unavailable cash + + Returns + ------- + float: + the available(tradable) cash in position + """ + raise NotImplementedError(f"Please implement the `get_cash` method") + + def get_stock_amount_dict(self) -> dict: + """ + generate stock amount dict {stock_id : amount of stock} + + Returns + ------- + Dict: + {stock_id : amount of stock} + """ + raise NotImplementedError(f"Please implement the `get_stock_amount_dict` method") + + def get_stock_weight_dict(self, only_stock: bool = False) -> dict: + """ + generate stock weight dict {stock_id : value weight of stock in the position} + it is meaningful in the beginning or the end of each trade step + - During execution of each trading step, the weight may be not consistent with the portfolio value + + Parameters + ---------- + only_stock : bool + If only_stock=True, the weight of each stock in total stock will be returned + If only_stock=False, the weight of each stock in total assets(stock + cash) will be returned + + Returns + ------- + Dict: + {stock_id : value weight of stock in the position} + """ + raise NotImplementedError(f"Please implement the `get_stock_weight_dict` method") + + def add_count_all(self, bar: str) -> None: + """ + Will be called at the end of each bar on each level + + Parameters + ---------- + bar : + The level to be updated + """ + raise NotImplementedError(f"Please implement the `add_count_all` method") + + def update_weight_all(self) -> None: + """ + Updating the position weight; + + # TODO: this function is a little weird. The weight data in the position is in a wrong state after dealing order + # and before updating weight. + """ + raise NotImplementedError(f"Please implement the `add_count_all` method") + + ST_CASH = "cash" + ST_NO = "None" # String is more typehint friendly than None + + def settle_start(self, settle_type: str) -> None: + """ + settlement start + It will act like start and commit a transaction + + Parameters + ---------- + settle_type : str + Should we make delay the settlement in each execution (each execution will make the executor a step forward) + - "cash": make the cash settlement delayed. + - The cash you get can't be used in current step (e.g. you can't sell a stock to get cash to buy another + stock) + - None: not settlement mechanism + - TODO: other assets will be supported in the future. + """ + raise NotImplementedError(f"Please implement the `settle_conf` method") + + def settle_commit(self) -> None: + """ + settlement commit + """ + raise NotImplementedError(f"Please implement the `settle_commit` method") + + def __str__(self) -> str: + return self.__dict__.__str__() + + def __repr__(self) -> str: + return self.__dict__.__repr__() + + +class Position(BasePosition): + """Position + + current state of position + a typical example is :{ + : { + 'count': , + 'amount': , + 'price': , + 'weight': , + }, + } + """ + + def __init__(self, cash: float = 0, position_dict: Dict[str, Union[Dict[str, float], float]] = {}) -> None: + """Init position by cash and position_dict. + + Parameters + ---------- + cash : float, optional + initial cash in account, by default 0 + position_dict : Dict[ + stock_id, + Union[ + int, # it is equal to {"amount": int} + {"amount": int, "price"(optional): float}, + ] + ] + initial stocks with parameters amount and price, + if there is no price key in the dict of stocks, it will be filled by _fill_stock_value. + by default {}. + """ + super().__init__() + + # NOTE: The position dict must be copied!!! + # Otherwise the initial value + self.init_cash = cash + self.position = position_dict.copy() + for stock, value in self.position.items(): + if isinstance(value, int): + self.position[stock] = {"amount": value} + self.position["cash"] = cash + + # If the stock price information is missing, the account value will not be calculated temporarily + try: + self.position["now_account_value"] = self.calculate_value() + except KeyError: + pass + + def fill_stock_value(self, start_time: Union[str, pd.Timestamp], freq: str, last_days: int = 30) -> None: + """fill the stock value by the close price of latest last_days from qlib. + + Parameters + ---------- + start_time : + the start time of backtest. + freq : str + Frequency + last_days : int, optional + the days to get the latest close price, by default 30. + """ + stock_list = [] + for stock, value in self.position.items(): + if not isinstance(value, dict): + continue + if value.get("price", None) is None: + stock_list.append(stock) + + if len(stock_list) == 0: + return + + start_time = pd.Timestamp(start_time) + # note that start time is 2020-01-01 00:00:00 if raw start time is "2020-01-01" + price_end_time = start_time + price_start_time = start_time - timedelta(days=last_days) + price_df = D.features( + stock_list, + ["$close"], + price_start_time, + price_end_time, + freq=freq, + disk_cache=True, + ).dropna() + price_dict = price_df.groupby(["instrument"], group_keys=False).tail(1)["$close"].to_dict() + + if len(price_dict) < len(stock_list): + lack_stock = set(stock_list) - set(price_dict) + raise ValueError(f"{lack_stock} doesn't have close price in qlib in the latest {last_days} days") + + for stock in stock_list: + self.position[stock]["price"] = price_dict[stock] + self.position["now_account_value"] = self.calculate_value() + + def _init_stock(self, stock_id: str, amount: float, price: float | None = None) -> None: + """ + initialization the stock in current position + + Parameters + ---------- + stock_id : + the id of the stock + amount : float + the amount of the stock + price : + the price when buying the init stock + """ + self.position[stock_id] = {} + self.position[stock_id]["amount"] = amount + self.position[stock_id]["price"] = price + self.position[stock_id]["weight"] = 0 # update the weight in the end of the trade date + + def _buy_stock(self, stock_id: str, trade_val: float, cost: float, trade_price: float) -> None: + trade_amount = trade_val / trade_price + if stock_id not in self.position: + self._init_stock(stock_id=stock_id, amount=trade_amount, price=trade_price) + else: + # exist, add amount + self.position[stock_id]["amount"] += trade_amount + + self.position["cash"] -= trade_val + cost + + def _sell_stock(self, stock_id: str, trade_val: float, cost: float, trade_price: float) -> None: + trade_amount = trade_val / trade_price + if stock_id not in self.position: + raise KeyError("{} not in current position".format(stock_id)) + else: + if np.isclose(self.position[stock_id]["amount"], trade_amount): + # Selling all the stocks + # we use np.isclose instead of abs() <= 1e-5 because `np.isclose` consider both + # relative amount and absolute amount + # Using abs() <= 1e-5 will result in error when the amount is large + self._del_stock(stock_id) + else: + # decrease the amount of stock + self.position[stock_id]["amount"] -= trade_amount + # check if to delete + if self.position[stock_id]["amount"] < -1e-5: + raise ValueError( + "only have {} {}, require {}".format( + self.position[stock_id]["amount"] + trade_amount, + stock_id, + trade_amount, + ), + ) + + new_cash = trade_val - cost + if self._settle_type == self.ST_CASH: + self.position["cash_delay"] += new_cash + elif self._settle_type == self.ST_NO: + self.position["cash"] += new_cash + else: + raise NotImplementedError(f"This type of input is not supported") + + def _del_stock(self, stock_id: str) -> None: + del self.position[stock_id] + + def check_stock(self, stock_id: str) -> bool: + return stock_id in self.position + + def update_order(self, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + # handle order, order is a order class, defined in exchange.py + if order.direction == Order.BUY: + # BUY + self._buy_stock(order.stock_id, trade_val, cost, trade_price) + elif order.direction == Order.SELL: + # SELL + self._sell_stock(order.stock_id, trade_val, cost, trade_price) + else: + raise NotImplementedError("do not support order direction {}".format(order.direction)) + + def update_stock_price(self, stock_id: str, price: float) -> None: + self.position[stock_id]["price"] = price + + def update_stock_count(self, stock_id: str, bar: str, count: float) -> None: # TODO: check type of `bar` + self.position[stock_id][f"count_{bar}"] = count + + def update_stock_weight(self, stock_id: str, weight: float) -> None: + self.position[stock_id]["weight"] = weight + + def calculate_stock_value(self) -> float: + stock_list = self.get_stock_list() + value = 0 + for stock_id in stock_list: + value += self.position[stock_id]["amount"] * self.position[stock_id]["price"] + return value + + def calculate_value(self) -> float: + value = self.calculate_stock_value() + value += self.position["cash"] + self.position.get("cash_delay", 0.0) + return value + + def get_stock_list(self) -> List[str]: + stock_list = list(set(self.position.keys()) - {"cash", "now_account_value", "cash_delay"}) + return stock_list + + def get_stock_price(self, code: str) -> float: + return self.position[code]["price"] + + def get_stock_amount(self, code: str) -> float: + return self.position[code]["amount"] if code in self.position else 0 + + def get_stock_count(self, code: str, bar: str) -> float: + """the days the account has been hold, it may be used in some special strategies""" + if f"count_{bar}" in self.position[code]: + return self.position[code][f"count_{bar}"] + else: + return 0 + + def get_stock_weight(self, code: str) -> float: + return self.position[code]["weight"] + + def get_cash(self, include_settle: bool = False) -> float: + cash = self.position["cash"] + if include_settle: + cash += self.position.get("cash_delay", 0.0) + return cash + + def get_stock_amount_dict(self) -> dict: + """generate stock amount dict {stock_id : amount of stock}""" + d = {} + stock_list = self.get_stock_list() + for stock_code in stock_list: + d[stock_code] = self.get_stock_amount(code=stock_code) + return d + + def get_stock_weight_dict(self, only_stock: bool = False) -> dict: + """get_stock_weight_dict + generate stock weight dict {stock_id : value weight of stock in the position} + it is meaningful in the beginning or the end of each trade date + + :param only_stock: If only_stock=True, the weight of each stock in total stock will be returned + If only_stock=False, the weight of each stock in total assets(stock + cash) will be returned + """ + if only_stock: + position_value = self.calculate_stock_value() + else: + position_value = self.calculate_value() + d = {} + stock_list = self.get_stock_list() + for stock_code in stock_list: + d[stock_code] = self.position[stock_code]["amount"] * self.position[stock_code]["price"] / position_value + return d + + def add_count_all(self, bar: str) -> None: + stock_list = self.get_stock_list() + for code in stock_list: + if f"count_{bar}" in self.position[code]: + self.position[code][f"count_{bar}"] += 1 + else: + self.position[code][f"count_{bar}"] = 1 + + def update_weight_all(self) -> None: + weight_dict = self.get_stock_weight_dict() + for stock_code, weight in weight_dict.items(): + self.update_stock_weight(stock_code, weight) + + def settle_start(self, settle_type: str) -> None: + assert self._settle_type == self.ST_NO, "Currently, settlement can't be nested!!!!!" + self._settle_type = settle_type + if settle_type == self.ST_CASH: + self.position["cash_delay"] = 0.0 + + def settle_commit(self) -> None: + if self._settle_type != self.ST_NO: + if self._settle_type == self.ST_CASH: + self.position["cash"] += self.position["cash_delay"] + del self.position["cash_delay"] + else: + raise NotImplementedError(f"This type of input is not supported") + self._settle_type = self.ST_NO + + +class InfPosition(BasePosition): + """ + Position with infinite cash and amount. + + This is useful for generating random orders. + """ + + def skip_update(self) -> bool: + """Updating state is meaningless for InfPosition""" + return True + + def check_stock(self, stock_id: str) -> bool: + # InfPosition always have any stocks + return True + + def update_order(self, order: Order, trade_val: float, cost: float, trade_price: float) -> None: + pass + + def update_stock_price(self, stock_id: str, price: float) -> None: + pass + + def calculate_stock_value(self) -> float: + """ + Returns + ------- + float: + infinity stock value + """ + return np.inf + + def calculate_value(self) -> float: + raise NotImplementedError(f"InfPosition doesn't support calculating value") + + def get_stock_list(self) -> List[str]: + raise NotImplementedError(f"InfPosition doesn't support stock list position") + + def get_stock_price(self, code: str) -> float: + """the price of the inf position is meaningless""" + return np.nan + + def get_stock_amount(self, code: str) -> float: + return np.inf + + def get_cash(self, include_settle: bool = False) -> float: + return np.inf + + def get_stock_amount_dict(self) -> dict: + raise NotImplementedError(f"InfPosition doesn't support get_stock_amount_dict") + + def get_stock_weight_dict(self, only_stock: bool = False) -> dict: + raise NotImplementedError(f"InfPosition doesn't support get_stock_weight_dict") + + def add_count_all(self, bar: str) -> None: + raise NotImplementedError(f"InfPosition doesn't support add_count_all") + + def update_weight_all(self) -> None: + raise NotImplementedError(f"InfPosition doesn't support update_weight_all") + + def settle_start(self, settle_type: str) -> None: + pass + + def settle_commit(self) -> None: + pass diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/profit_attribution.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/profit_attribution.py new file mode 100644 index 0000000000000000000000000000000000000000..05ca8670659cff2ef54deb5a171f79c52cfa1130 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/profit_attribution.py @@ -0,0 +1,334 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +This module is not well maintained. +""" + +import datetime +from pathlib import Path + +import numpy as np +import pandas as pd + +from ..config import C +from ..data import D +from .position import Position + + +def get_benchmark_weight( + bench, + start_date=None, + end_date=None, + path=None, + freq="day", +): + """get_benchmark_weight + + get the stock weight distribution of the benchmark + + :param bench: + :param start_date: + :param end_date: + :param path: + :param freq: + + :return: The weight distribution of the the benchmark described by a pandas dataframe + Every row corresponds to a trading day. + Every column corresponds to a stock. + Every cell represents the strategy. + + """ + if not path: + path = Path(C.dpm.get_data_uri(freq)).expanduser() / "raw" / "AIndexMembers" / "weights.csv" + # TODO: the storage of weights should be implemented in a more elegent way + # TODO: The benchmark is not consistent with the filename in instruments. + bench_weight_df = pd.read_csv(path, usecols=["code", "date", "index", "weight"]) + bench_weight_df = bench_weight_df[bench_weight_df["index"] == bench] + bench_weight_df["date"] = pd.to_datetime(bench_weight_df["date"]) + if start_date is not None: + bench_weight_df = bench_weight_df[bench_weight_df.date >= start_date] + if end_date is not None: + bench_weight_df = bench_weight_df[bench_weight_df.date <= end_date] + bench_stock_weight = bench_weight_df.pivot_table(index="date", columns="code", values="weight") / 100.0 + return bench_stock_weight + + +def get_stock_weight_df(positions): + """get_stock_weight_df + :param positions: Given a positions from backtest result. + :return: A weight distribution for the position + """ + stock_weight = [] + index = [] + for date in sorted(positions.keys()): + pos = positions[date] + if isinstance(pos, dict): + pos = Position(position_dict=pos) + index.append(date) + stock_weight.append(pos.get_stock_weight_dict(only_stock=True)) + return pd.DataFrame(stock_weight, index=index) + + +def decompose_portofolio_weight(stock_weight_df, stock_group_df): + """decompose_portofolio_weight + + ''' + :param stock_weight_df: a pandas dataframe to describe the portofolio by weight. + every row corresponds to a day + every column corresponds to a stock. + Here is an example below. + code SH600004 SH600006 SH600017 SH600022 SH600026 SH600037 \ + date + 2016-01-05 0.001543 0.001570 0.002732 0.001320 0.003000 NaN + 2016-01-06 0.001538 0.001569 0.002770 0.001417 0.002945 NaN + .... + :param stock_group_df: a pandas dataframe to describe the stock group. + every row corresponds to a day + every column corresponds to a stock. + the value in the cell repreponds the group id. + Here is a example by for stock_group_df for industry. The value is the industry code + instrument SH600000 SH600004 SH600005 SH600006 SH600007 SH600008 \ + datetime + 2016-01-05 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + 2016-01-06 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + ... + :return: Two dict will be returned. The group_weight and the stock_weight_in_group. + The key is the group. The value is a Series or Dataframe to describe the weight of group or weight of stock + """ + all_group = np.unique(stock_group_df.values.flatten()) + all_group = all_group[~np.isnan(all_group)] + + group_weight = {} + stock_weight_in_group = {} + for group_key in all_group: + group_mask = stock_group_df == group_key + group_weight[group_key] = stock_weight_df[group_mask].sum(axis=1) + stock_weight_in_group[group_key] = stock_weight_df[group_mask].divide(group_weight[group_key], axis=0) + return group_weight, stock_weight_in_group + + +def decompose_portofolio(stock_weight_df, stock_group_df, stock_ret_df): + """ + :param stock_weight_df: a pandas dataframe to describe the portofolio by weight. + every row corresponds to a day + every column corresponds to a stock. + Here is an example below. + code SH600004 SH600006 SH600017 SH600022 SH600026 SH600037 \ + date + 2016-01-05 0.001543 0.001570 0.002732 0.001320 0.003000 NaN + 2016-01-06 0.001538 0.001569 0.002770 0.001417 0.002945 NaN + 2016-01-07 0.001555 0.001546 0.002772 0.001393 0.002904 NaN + 2016-01-08 0.001564 0.001527 0.002791 0.001506 0.002948 NaN + 2016-01-11 0.001597 0.001476 0.002738 0.001493 0.003043 NaN + .... + + :param stock_group_df: a pandas dataframe to describe the stock group. + every row corresponds to a day + every column corresponds to a stock. + the value in the cell repreponds the group id. + Here is a example by for stock_group_df for industry. The value is the industry code + instrument SH600000 SH600004 SH600005 SH600006 SH600007 SH600008 \ + datetime + 2016-01-05 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + 2016-01-06 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + 2016-01-07 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + 2016-01-08 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + 2016-01-11 801780.0 801170.0 801040.0 801880.0 801180.0 801160.0 + ... + + :param stock_ret_df: a pandas dataframe to describe the stock return. + every row corresponds to a day + every column corresponds to a stock. + the value in the cell repreponds the return of the group. + Here is a example by for stock_ret_df. + instrument SH600000 SH600004 SH600005 SH600006 SH600007 SH600008 \ + datetime + 2016-01-05 0.007795 0.022070 0.099099 0.024707 0.009473 0.016216 + 2016-01-06 -0.032597 -0.075205 -0.098361 -0.098985 -0.099707 -0.098936 + 2016-01-07 -0.001142 0.022544 0.100000 0.004225 0.000651 0.047226 + 2016-01-08 -0.025157 -0.047244 -0.038567 -0.098177 -0.099609 -0.074408 + 2016-01-11 0.023460 0.004959 -0.034384 0.018663 0.014461 0.010962 + ... + + :return: It will decompose the portofolio to the group weight and group return. + """ + all_group = np.unique(stock_group_df.values.flatten()) + all_group = all_group[~np.isnan(all_group)] + + group_weight, stock_weight_in_group = decompose_portofolio_weight(stock_weight_df, stock_group_df) + + group_ret = {} + for group_key, val in stock_weight_in_group.items(): + stock_weight_in_group_start_date = min(val.index) + stock_weight_in_group_end_date = max(val.index) + + temp_stock_ret_df = stock_ret_df[ + (stock_ret_df.index >= stock_weight_in_group_start_date) + & (stock_ret_df.index <= stock_weight_in_group_end_date) + ] + + group_ret[group_key] = (temp_stock_ret_df * val).sum(axis=1) + # If no weight is assigned, then the return of group will be np.nan + group_ret[group_key][group_weight[group_key] == 0.0] = np.nan + + group_weight_df = pd.DataFrame(group_weight) + group_ret_df = pd.DataFrame(group_ret) + return group_weight_df, group_ret_df + + +def get_daily_bin_group(bench_values, stock_values, group_n): + """get_daily_bin_group + Group the values of the stocks of benchmark into several bins in a day. + Put the stocks into these bins. + + :param bench_values: A series contains the value of stocks in benchmark. + The index is the stock code. + :param stock_values: A series contains the value of stocks of your portofolio + The index is the stock code. + :param group_n: Bins will be produced + + :return: A series with the same size and index as the stock_value. + The value in the series is the group id of the bins. + The No.1 bin contains the biggest values. + """ + stock_group = stock_values.copy() + + # get the bin split points based on the daily proportion of benchmark + split_points = np.percentile(bench_values[~bench_values.isna()], np.linspace(0, 100, group_n + 1)) + # Modify the biggest uppper bound and smallest lowerbound + split_points[0], split_points[-1] = -np.inf, np.inf + for i, (lb, up) in enumerate(zip(split_points, split_points[1:])): + stock_group.loc[stock_values[(stock_values >= lb) & (stock_values < up)].index] = group_n - i + return stock_group + + +def get_stock_group(stock_group_field_df, bench_stock_weight_df, group_method, group_n=None): + if group_method == "category": + # use the value of the benchmark as the category + return stock_group_field_df + elif group_method == "bins": + assert group_n is not None + # place the values into `group_n` fields. + # Each bin corresponds to a category. + new_stock_group_df = stock_group_field_df.copy().loc[ + bench_stock_weight_df.index.min() : bench_stock_weight_df.index.max() + ] + for idx, row in (~bench_stock_weight_df.isna()).iterrows(): + bench_values = stock_group_field_df.loc[idx, row[row].index] + new_stock_group_df.loc[idx] = get_daily_bin_group( + bench_values, + stock_group_field_df.loc[idx], + group_n=group_n, + ) + return new_stock_group_df + + +def brinson_pa( + positions, + bench="SH000905", + group_field="industry", + group_method="category", + group_n=None, + deal_price="vwap", + freq="day", +): + """brinson profit attribution + + :param positions: The position produced by the backtest class + :param bench: The benchmark for comparing. TODO: if no benchmark is set, the equal-weighted is used. + :param group_field: The field used to set the group for assets allocation. + `industry` and `market_value` is often used. + :param group_method: 'category' or 'bins'. The method used to set the group for asstes allocation + `bin` will split the value into `group_n` bins and each bins represents a group + :param group_n: . Only used when group_method == 'bins'. + + :return: + A dataframe with three columns: RAA(excess Return of Assets Allocation), RSS(excess Return of Stock Selectino), RTotal(Total excess Return) + Every row corresponds to a trading day, the value corresponds to the next return for this trading day + The middle info of brinson profit attribution + """ + # group_method will decide how to group the group_field. + dates = sorted(positions.keys()) + + start_date, end_date = min(dates), max(dates) + + bench_stock_weight = get_benchmark_weight(bench, start_date, end_date, freq) + + # The attributes for allocation will not + if not group_field.startswith("$"): + group_field = "$" + group_field + if not deal_price.startswith("$"): + deal_price = "$" + deal_price + + # FIXME: In current version. Some attributes(such as market_value) of some + # suspend stock is NAN. So we have to get more date to forward fill the NAN + shift_start_date = start_date - datetime.timedelta(days=250) + instruments = D.list_instruments( + D.instruments(market="all"), + start_time=shift_start_date, + end_time=end_date, + as_list=True, + freq=freq, + ) + stock_df = D.features( + instruments, + [group_field, deal_price], + start_time=shift_start_date, + end_time=end_date, + freq=freq, + ) + stock_df.columns = [group_field, "deal_price"] + + stock_group_field = stock_df[group_field].unstack().T + # FIXME: some attributes of some suspend stock is NAN. + stock_group_field = stock_group_field.ffill() + stock_group_field = stock_group_field.loc[start_date:end_date] + + stock_group = get_stock_group(stock_group_field, bench_stock_weight, group_method, group_n) + + deal_price_df = stock_df["deal_price"].unstack().T + deal_price_df = deal_price_df.ffill() + + # NOTE: + # The return will be slightly different from the of the return in the report. + # Here the position are adjusted at the end of the trading day with close + stock_ret = (deal_price_df - deal_price_df.shift(1)) / deal_price_df.shift(1) + stock_ret = stock_ret.shift(-1).loc[start_date:end_date] + + port_stock_weight_df = get_stock_weight_df(positions) + + # decomposing the portofolio + port_group_weight_df, port_group_ret_df = decompose_portofolio(port_stock_weight_df, stock_group, stock_ret) + bench_group_weight_df, bench_group_ret_df = decompose_portofolio(bench_stock_weight, stock_group, stock_ret) + + # if the group return of the portofolio is NaN, replace it with the market + # value + mod_port_group_ret_df = port_group_ret_df.copy() + mod_port_group_ret_df[mod_port_group_ret_df.isna()] = bench_group_ret_df + + Q1 = (bench_group_weight_df * bench_group_ret_df).sum(axis=1) + Q2 = (port_group_weight_df * bench_group_ret_df).sum(axis=1) + Q3 = (bench_group_weight_df * mod_port_group_ret_df).sum(axis=1) + Q4 = (port_group_weight_df * mod_port_group_ret_df).sum(axis=1) + + return ( + pd.DataFrame( + { + "RAA": Q2 - Q1, # The excess profit from the assets allocation + "RSS": Q3 - Q1, # The excess profit from the stocks selection + # The excess profit from the interaction of assets allocation and stocks selection + "RIN": Q4 - Q3 - Q2 + Q1, + "RTotal": Q4 - Q1, # The totoal excess profit + }, + ), + { + "port_group_ret": port_group_ret_df, + "port_group_weight": port_group_weight_df, + "bench_group_ret": bench_group_ret_df, + "bench_group_weight": bench_group_weight_df, + "stock_group": stock_group, + "bench_stock_weight": bench_stock_weight, + "port_stock_weight": port_stock_weight_df, + "stock_ret": stock_ret, + }, + ) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/report.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/report.py new file mode 100644 index 0000000000000000000000000000000000000000..f1016e24e2a8f8f518176c2196de67cdbf614050 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/report.py @@ -0,0 +1,651 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +import pathlib +from collections import OrderedDict +from typing import Any, Dict, List, Optional, Text, Tuple, Type, Union, cast + +import numpy as np +import pandas as pd + +import qlib.utils.index_data as idd +from qlib.backtest.decision import BaseTradeDecision, Order, OrderDir +from qlib.backtest.exchange import Exchange + +from ..tests.config import CSI300_BENCH +from ..utils.resam import get_higher_eq_freq_feature, resam_ts_data +from .high_performance_ds import BaseOrderIndicator, BaseSingleMetric, NumpyOrderIndicator + + +class PortfolioMetrics: + """ + Motivation: + PortfolioMetrics is for supporting portfolio related metrics. + + Implementation: + + daily portfolio metrics of the account + contain those followings: return, cost, turnover, account, cash, bench, value + For each step(bar/day/minute), each column represents + - return: the return of the portfolio generated by strategy **without transaction fee**. + - cost: the transaction fee and slippage. + - account: the total value of assets(cash and securities are both included) in user account based on the close price of each step. + - cash: the amount of cash in user's account. + - bench: the return of the benchmark + - value: the total value of securities/stocks/instruments (cash is excluded). + + update report + """ + + def __init__(self, freq: str = "day", benchmark_config: dict = {}) -> None: + """ + Parameters + ---------- + freq : str + frequency of trading bar, used for updating hold count of trading bar + benchmark_config : dict + config of benchmark, may including the following arguments: + - benchmark : Union[str, list, pd.Series] + - If `benchmark` is pd.Series, `index` is trading date; the value T is the change from T-1 to T. + example: + print( + D.features(D.instruments('csi500'), + ['$close/Ref($close, 1)-1'])['$close/Ref($close, 1)-1'].head() + ) + 2017-01-04 0.011693 + 2017-01-05 0.000721 + 2017-01-06 -0.004322 + 2017-01-09 0.006874 + 2017-01-10 -0.003350 + - If `benchmark` is list, will use the daily average change of the stock pool in the list as the + 'bench'. + - If `benchmark` is str, will use the daily change as the 'bench'. + benchmark code, default is SH000300 CSI300 + - start_time : Union[str, pd.Timestamp], optional + - If `benchmark` is pd.Series, it will be ignored + - Else, it represent start time of benchmark, by default None + - end_time : Union[str, pd.Timestamp], optional + - If `benchmark` is pd.Series, it will be ignored + - Else, it represent end time of benchmark, by default None + + """ + + self.init_vars() + self.init_bench(freq=freq, benchmark_config=benchmark_config) + + def init_vars(self) -> None: + self.accounts: dict = OrderedDict() # account position value for each trade time + self.returns: dict = OrderedDict() # daily return rate for each trade time + self.total_turnovers: dict = OrderedDict() # total turnover for each trade time + self.turnovers: dict = OrderedDict() # turnover for each trade time + self.total_costs: dict = OrderedDict() # total trade cost for each trade time + self.costs: dict = OrderedDict() # trade cost rate for each trade time + self.values: dict = OrderedDict() # value for each trade time + self.cashes: dict = OrderedDict() + self.benches: dict = OrderedDict() + self.latest_pm_time: Optional[pd.TimeStamp] = None + + def init_bench(self, freq: str | None = None, benchmark_config: dict | None = None) -> None: + if freq is not None: + self.freq = freq + self.benchmark_config = benchmark_config + self.bench = self._cal_benchmark(self.benchmark_config, self.freq) + + @staticmethod + def _cal_benchmark(benchmark_config: Optional[dict], freq: str) -> Optional[pd.Series]: + if benchmark_config is None: + return None + benchmark = benchmark_config.get("benchmark", CSI300_BENCH) + if benchmark is None: + return None + + if isinstance(benchmark, pd.Series): + return benchmark + else: + start_time = benchmark_config.get("start_time", None) + end_time = benchmark_config.get("end_time", None) + + if freq is None: + raise ValueError("benchmark freq can't be None!") + _codes = benchmark if isinstance(benchmark, (list, dict)) else [benchmark] + fields = ["$close/Ref($close,1)-1"] + _temp_result, _ = get_higher_eq_freq_feature(_codes, fields, start_time, end_time, freq=freq) + if len(_temp_result) == 0: + raise ValueError(f"The benchmark {_codes} does not exist. Please provide the right benchmark") + return ( + _temp_result.groupby(level="datetime", group_keys=False)[_temp_result.columns.tolist()[0]] + .mean() + .fillna(0) + ) + + def _sample_benchmark( + self, + bench: pd.Series, + trade_start_time: Union[str, pd.Timestamp], + trade_end_time: Union[str, pd.Timestamp], + ) -> Optional[float]: + if self.bench is None: + return None + + def cal_change(x): + return (x + 1).prod() + + _ret = resam_ts_data(bench, trade_start_time, trade_end_time, method=cal_change) + return 0.0 if _ret is None else _ret - 1 + + def is_empty(self) -> bool: + return len(self.accounts) == 0 + + def get_latest_date(self) -> pd.Timestamp: + return self.latest_pm_time + + def get_latest_account_value(self) -> float: + return self.accounts[self.latest_pm_time] + + def get_latest_total_cost(self) -> Any: + return self.total_costs[self.latest_pm_time] + + def get_latest_total_turnover(self) -> Any: + return self.total_turnovers[self.latest_pm_time] + + def update_portfolio_metrics_record( + self, + trade_start_time: Union[str, pd.Timestamp] = None, + trade_end_time: Union[str, pd.Timestamp] = None, + account_value: float | None = None, + cash: float | None = None, + return_rate: float | None = None, + total_turnover: float | None = None, + turnover_rate: float | None = None, + total_cost: float | None = None, + cost_rate: float | None = None, + stock_value: float | None = None, + bench_value: float | None = None, + ) -> None: + # check data + if None in [ + trade_start_time, + account_value, + cash, + return_rate, + total_turnover, + turnover_rate, + total_cost, + cost_rate, + stock_value, + ]: + raise ValueError( + "None in [trade_start_time, account_value, cash, return_rate, total_turnover, turnover_rate, " + "total_cost, cost_rate, stock_value]", + ) + + if trade_end_time is None and bench_value is None: + raise ValueError("Both trade_end_time and bench_value is None, benchmark is not usable.") + elif bench_value is None: + bench_value = self._sample_benchmark(self.bench, trade_start_time, trade_end_time) + + # update pm data + self.accounts[trade_start_time] = account_value + self.returns[trade_start_time] = return_rate + self.total_turnovers[trade_start_time] = total_turnover + self.turnovers[trade_start_time] = turnover_rate + self.total_costs[trade_start_time] = total_cost + self.costs[trade_start_time] = cost_rate + self.values[trade_start_time] = stock_value + self.cashes[trade_start_time] = cash + self.benches[trade_start_time] = bench_value + # update pm + self.latest_pm_time = trade_start_time + # finish pm update in each step + + def generate_portfolio_metrics_dataframe(self) -> pd.DataFrame: + pm = pd.DataFrame() + pm["account"] = pd.Series(self.accounts) + pm["return"] = pd.Series(self.returns) + pm["total_turnover"] = pd.Series(self.total_turnovers) + pm["turnover"] = pd.Series(self.turnovers) + pm["total_cost"] = pd.Series(self.total_costs) + pm["cost"] = pd.Series(self.costs) + pm["value"] = pd.Series(self.values) + pm["cash"] = pd.Series(self.cashes) + pm["bench"] = pd.Series(self.benches) + pm.index.name = "datetime" + return pm + + def save_portfolio_metrics(self, path: str) -> None: + r = self.generate_portfolio_metrics_dataframe() + r.to_csv(path) + + def load_portfolio_metrics(self, path: str) -> None: + """load pm from a file + should have format like + columns = ['account', 'return', 'total_turnover', 'turnover', 'cost', 'total_cost', 'value', 'cash', 'bench'] + :param + path: str/ pathlib.Path() + """ + with pathlib.Path(path).open("rb") as f: + r = pd.read_csv(f, index_col=0) + r.index = pd.DatetimeIndex(r.index) + + index = r.index + self.init_vars() + for trade_start_time in index: + self.update_portfolio_metrics_record( + trade_start_time=trade_start_time, + account_value=r.loc[trade_start_time]["account"], + cash=r.loc[trade_start_time]["cash"], + return_rate=r.loc[trade_start_time]["return"], + total_turnover=r.loc[trade_start_time]["total_turnover"], + turnover_rate=r.loc[trade_start_time]["turnover"], + total_cost=r.loc[trade_start_time]["total_cost"], + cost_rate=r.loc[trade_start_time]["cost"], + stock_value=r.loc[trade_start_time]["value"], + bench_value=r.loc[trade_start_time]["bench"], + ) + + +class Indicator: + """ + `Indicator` is implemented in a aggregate way. + All the metrics are calculated aggregately. + All the metrics are calculated for a separated stock and in a specific step on a specific level. + + | indicator | desc. | + |--------------+--------------------------------------------------------------| + | amount | the *target* amount given by the outer strategy | + | deal_amount | the real deal amount | + | inner_amount | the total *target* amount of inner strategy | + | trade_price | the average deal price | + | trade_value | the total trade value | + | trade_cost | the total trade cost (base price need drection) | + | trade_dir | the trading direction | + | ffr | full fill rate | + | pa | price advantage | + | pos | win rate | + | base_price | the price of baseline | + | base_volume | the volume of baseline (for weighted aggregating base_price) | + + **NOTE**: + The `base_price` and `base_volume` can't be NaN when there are not trading on that step. Otherwise + aggregating get wrong results. + + So `base_price` will not be calculated in a aggregate way!! + + """ + + def __init__(self, order_indicator_cls: Type[BaseOrderIndicator] = NumpyOrderIndicator) -> None: + self.order_indicator_cls = order_indicator_cls + + # order indicator is metrics for a single order for a specific step + self.order_indicator_his: dict = OrderedDict() + self.order_indicator: BaseOrderIndicator = self.order_indicator_cls() + + # trade indicator is metrics for all orders for a specific step + self.trade_indicator_his: dict = OrderedDict() + self.trade_indicator: Dict[str, Optional[BaseSingleMetric]] = OrderedDict() + + self._trade_calendar = None + + # def reset(self, trade_calendar: TradeCalendarManager): + def reset(self) -> None: + self.order_indicator = self.order_indicator_cls() + self.trade_indicator = OrderedDict() + # self._trade_calendar = trade_calendar + + def record(self, trade_start_time: Union[str, pd.Timestamp]) -> None: + self.order_indicator_his[trade_start_time] = self.get_order_indicator() + self.trade_indicator_his[trade_start_time] = self.get_trade_indicator() + + def _update_order_trade_info(self, trade_info: List[Tuple[Order, float, float, float]]) -> None: + amount = dict() + deal_amount = dict() + trade_price = dict() + trade_value = dict() + trade_cost = dict() + trade_dir = dict() + pa = dict() + + for order, _trade_val, _trade_cost, _trade_price in trade_info: + amount[order.stock_id] = order.amount_delta + deal_amount[order.stock_id] = order.deal_amount_delta + trade_price[order.stock_id] = _trade_price + trade_value[order.stock_id] = _trade_val * order.sign + trade_cost[order.stock_id] = _trade_cost + trade_dir[order.stock_id] = order.direction + # The PA in the innermost layer is meanless + pa[order.stock_id] = 0 + + self.order_indicator.assign("amount", amount) + self.order_indicator.assign("inner_amount", amount) + self.order_indicator.assign("deal_amount", deal_amount) + # NOTE: trade_price and baseline price will be same on the lowest-level + self.order_indicator.assign("trade_price", trade_price) + self.order_indicator.assign("trade_value", trade_value) + self.order_indicator.assign("trade_cost", trade_cost) + self.order_indicator.assign("trade_dir", trade_dir) + self.order_indicator.assign("pa", pa) + + def _update_order_fulfill_rate(self) -> None: + def func(deal_amount, amount): + # deal_amount is np.nan or None when there is no inner decision. So full fill rate is 0. + tmp_deal_amount = deal_amount.reindex(amount.index, 0) + tmp_deal_amount = tmp_deal_amount.replace({np.nan: 0}) + return tmp_deal_amount / amount + + self.order_indicator.transfer(func, "ffr") + + def update_order_indicators(self, trade_info: List[Tuple[Order, float, float, float]]) -> None: + self._update_order_trade_info(trade_info=trade_info) + self._update_order_fulfill_rate() + + def _agg_order_trade_info(self, inner_order_indicators: List[BaseOrderIndicator]) -> None: + # calculate total trade amount with each inner order indicator. + def trade_amount_func(deal_amount, trade_price): + return deal_amount * trade_price + + for indicator in inner_order_indicators: + indicator.transfer(trade_amount_func, "trade_price") + + # sum inner order indicators with same metric. + all_metric = ["inner_amount", "deal_amount", "trade_price", "trade_value", "trade_cost", "trade_dir"] + self.order_indicator_cls.sum_all_indicators( + self.order_indicator, + inner_order_indicators, + all_metric, + fill_value=0, + ) + + def func(trade_price, deal_amount): + # trade_price is np.nan instead of inf when deal_amount is zero. + tmp_deal_amount = deal_amount.replace({0: np.nan}) + return trade_price / tmp_deal_amount + + self.order_indicator.transfer(func, "trade_price") + + def func_apply(trade_dir): + return trade_dir.apply(Order.parse_dir) + + self.order_indicator.transfer(func_apply, "trade_dir") + + def _update_trade_amount(self, outer_trade_decision: BaseTradeDecision) -> None: + # NOTE: these indicator is designed for order execution, so the + decision: List[Order] = cast(List[Order], outer_trade_decision.get_decision()) + if len(decision) == 0: + self.order_indicator.assign("amount", {}) + else: + self.order_indicator.assign("amount", {order.stock_id: order.amount_delta for order in decision}) + + def _get_base_vol_pri( + self, + inst: str, + trade_start_time: pd.Timestamp, + trade_end_time: pd.Timestamp, + direction: OrderDir, + decision: BaseTradeDecision, + trade_exchange: Exchange, + pa_config: dict = {}, + ) -> Tuple[Optional[float], Optional[float]]: + """ + Get the base volume and price information + All the base price values are rooted from this function + """ + + agg = pa_config.get("agg", "twap").lower() + price = pa_config.get("price", "deal_price").lower() + + if decision.trade_range is not None: + trade_start_time, trade_end_time = decision.trade_range.clip_time_range( + start_time=trade_start_time, + end_time=trade_end_time, + ) + + if price == "deal_price": + price_s = trade_exchange.get_deal_price( + inst, + trade_start_time, + trade_end_time, + direction=direction, + method=None, + ) + else: + raise NotImplementedError(f"This type of input is not supported") + + # if there is no stock data during the time period + if price_s is None: + return None, None + + if isinstance(price_s, (int, float, np.number)): + price_s = idd.SingleData(price_s, [trade_start_time]) + elif isinstance(price_s, idd.SingleData): + pass + else: + raise NotImplementedError(f"This type of input is not supported") + + # NOTE: there are some zeros in the trading price. These cases are known meaningless + # for aligning the previous logic, remove it. + # remove zero and negative values. + assert isinstance(price_s, idd.SingleData) + price_s = price_s.loc[(price_s > 1e-08).data.astype(bool)] + # NOTE ~(price_s < 1e-08) is different from price_s >= 1e-8 + # ~(np.nan < 1e-8) -> ~(False) -> True + + # if price_s is empty + if price_s.empty: + return None, None + + assert isinstance(price_s, idd.SingleData) + if agg == "vwap": + volume_s = trade_exchange.get_volume(inst, trade_start_time, trade_end_time, method=None) + if isinstance(volume_s, (int, float, np.number)): + volume_s = idd.SingleData(volume_s, [trade_start_time]) + assert isinstance(volume_s, idd.SingleData) + volume_s = volume_s.reindex(price_s.index) + elif agg == "twap": + volume_s = idd.SingleData(1, price_s.index) + else: + raise NotImplementedError(f"This type of input is not supported") + + assert isinstance(volume_s, idd.SingleData) + base_volume = volume_s.sum() + base_price = (price_s * volume_s).sum() / base_volume + return base_price, base_volume + + def _agg_base_price( + self, + inner_order_indicators: List[BaseOrderIndicator], + decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]], + trade_exchange: Exchange, + pa_config: dict = {}, + ) -> None: + """ + # NOTE:!!!! + # Strong assumption!!!!!! + # the correctness of the base_price relies on that the **same** exchange is used + + Parameters + ---------- + inner_order_indicators : List[BaseOrderIndicator] + the indicators of account of inner executor + decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]], + a list of decisions according to inner_order_indicators + trade_exchange : Exchange + for retrieving trading price + pa_config : dict + For example + { + "agg": "twap", # "vwap" + "price": "$close", # TODO: this is not supported now!!!!! + # default to use deal price of the exchange + } + """ + + # TODO: I think there are potentials to be optimized + trade_dir = self.order_indicator.get_index_data("trade_dir") + if len(trade_dir) > 0: + bp_all, bv_all = [], [] + # + for oi, (dec, start, end) in zip(inner_order_indicators, decision_list): + bp_s = oi.get_index_data("base_price").reindex(trade_dir.index) + bv_s = oi.get_index_data("base_volume").reindex(trade_dir.index) + + bp_new, bv_new = {}, {} + for pr, v, (inst, direction) in zip(bp_s.data, bv_s.data, zip(trade_dir.index, trade_dir.data)): + if np.isnan(pr): + bp_tmp, bv_tmp = self._get_base_vol_pri( + inst, + start, + end, + decision=dec, + direction=direction, + trade_exchange=trade_exchange, + pa_config=pa_config, + ) + if (bp_tmp is not None) and (bv_tmp is not None): + bp_new[inst], bv_new[inst] = bp_tmp, bv_tmp + else: + bp_new[inst], bv_new[inst] = pr, v + + bp_new = idd.SingleData(bp_new) + bv_new = idd.SingleData(bv_new) + bp_all.append(bp_new) + bv_all.append(bv_new) + bp_all_multi_data = idd.concat(bp_all, axis=1) + bv_all_multi_data = idd.concat(bv_all, axis=1) + + base_volume = bv_all_multi_data.sum(axis=1) + self.order_indicator.assign("base_volume", base_volume.to_dict()) + self.order_indicator.assign( + "base_price", + ((bp_all_multi_data * bv_all_multi_data).sum(axis=1) / base_volume).to_dict(), + ) + + def _agg_order_price_advantage(self) -> None: + def if_empty_func(trade_price): + return trade_price.empty + + if_empty = self.order_indicator.transfer(if_empty_func) + if not if_empty: + + def func(trade_dir, trade_price, base_price): + sign = 1 - trade_dir * 2 + return sign * (trade_price / base_price - 1) + + self.order_indicator.transfer(func, "pa") + else: + self.order_indicator.assign("pa", {}) + + def agg_order_indicators( + self, + inner_order_indicators: List[BaseOrderIndicator], + decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]], + outer_trade_decision: BaseTradeDecision, + trade_exchange: Exchange, + indicator_config: dict = {}, + ) -> None: + self._agg_order_trade_info(inner_order_indicators) + self._update_trade_amount(outer_trade_decision) + self._update_order_fulfill_rate() + pa_config = indicator_config.get("pa_config", {}) + self._agg_base_price(inner_order_indicators, decision_list, trade_exchange, pa_config=pa_config) # TODO + self._agg_order_price_advantage() + + def _cal_trade_fulfill_rate(self, method: str = "mean") -> Optional[BaseSingleMetric]: + if method == "mean": + return self.order_indicator.transfer( + lambda ffr: ffr.mean(), + ) + elif method == "amount_weighted": + return self.order_indicator.transfer( + lambda ffr, deal_amount: (ffr * deal_amount.abs()).sum() / (deal_amount.abs().sum()), + ) + elif method == "value_weighted": + return self.order_indicator.transfer( + lambda ffr, trade_value: (ffr * trade_value.abs()).sum() / (trade_value.abs().sum()), + ) + else: + raise ValueError(f"method {method} is not supported!") + + def _cal_trade_price_advantage(self, method: str = "mean") -> Optional[BaseSingleMetric]: + if method == "mean": + return self.order_indicator.transfer(lambda pa: pa.mean()) + elif method == "amount_weighted": + return self.order_indicator.transfer( + lambda pa, deal_amount: (pa * deal_amount.abs()).sum() / (deal_amount.abs().sum()), + ) + elif method == "value_weighted": + return self.order_indicator.transfer( + lambda pa, trade_value: (pa * trade_value.abs()).sum() / (trade_value.abs().sum()), + ) + else: + raise ValueError(f"method {method} is not supported!") + + def _cal_trade_positive_rate(self) -> Optional[BaseSingleMetric]: + def func(pa): + return (pa > 0).sum() / pa.count() + + return self.order_indicator.transfer(func) + + def _cal_deal_amount(self) -> Optional[BaseSingleMetric]: + def func(deal_amount): + return deal_amount.abs().sum() + + return self.order_indicator.transfer(func) + + def _cal_trade_value(self) -> Optional[BaseSingleMetric]: + def func(trade_value): + return trade_value.abs().sum() + + return self.order_indicator.transfer(func) + + def _cal_trade_order_count(self) -> Optional[BaseSingleMetric]: + def func(amount): + return amount.count() + + return self.order_indicator.transfer(func) + + def cal_trade_indicators( + self, + trade_start_time: Union[str, pd.Timestamp], + freq: str, + indicator_config: dict = {}, + ) -> None: + show_indicator = indicator_config.get("show_indicator", False) + ffr_config = indicator_config.get("ffr_config", {}) + pa_config = indicator_config.get("pa_config", {}) + fulfill_rate = self._cal_trade_fulfill_rate(method=ffr_config.get("weight_method", "mean")) + price_advantage = self._cal_trade_price_advantage(method=pa_config.get("weight_method", "mean")) + positive_rate = self._cal_trade_positive_rate() + deal_amount = self._cal_deal_amount() + trade_value = self._cal_trade_value() + order_count = self._cal_trade_order_count() + self.trade_indicator["ffr"] = fulfill_rate + self.trade_indicator["pa"] = price_advantage + self.trade_indicator["pos"] = positive_rate + self.trade_indicator["deal_amount"] = deal_amount + self.trade_indicator["value"] = trade_value + self.trade_indicator["count"] = order_count + if show_indicator: + print( + "[Indicator({}) {}]: FFR: {}, PA: {}, POS: {}".format( + freq, + ( + trade_start_time + if isinstance(trade_start_time, str) + else trade_start_time.strftime("%Y-%m-%d %H:%M:%S") + ), + fulfill_rate, + price_advantage, + positive_rate, + ), + ) + + def get_order_indicator(self, raw: bool = True) -> Union[BaseOrderIndicator, Dict[Text, pd.Series]]: + return self.order_indicator if raw else self.order_indicator.to_series() + + def get_trade_indicator(self) -> Dict[str, Optional[BaseSingleMetric]]: + return self.trade_indicator + + def generate_trade_indicators_dataframe(self) -> pd.DataFrame: + return pd.DataFrame.from_dict(self.trade_indicator_his, orient="index") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/signal.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/signal.py new file mode 100644 index 0000000000000000000000000000000000000000..cedc9bb175cd34b30c15a1c18a18c5eb16653c9d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/signal.py @@ -0,0 +1,105 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +import abc +from typing import Dict, List, Text, Tuple, Union + +import pandas as pd + +from qlib.utils import init_instance_by_config + +from ..data.dataset import Dataset +from ..data.dataset.utils import convert_index_format +from ..model.base import BaseModel +from ..utils.resam import resam_ts_data + + +class Signal(metaclass=abc.ABCMeta): + """ + Some trading strategy make decisions based on other prediction signals + The signals may comes from different sources(e.g. prepared data, online prediction from model and dataset) + + This interface is tries to provide unified interface for those different sources + """ + + @abc.abstractmethod + def get_signal(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Union[pd.Series, pd.DataFrame, None]: + """ + get the signal at the end of the decision step(from `start_time` to `end_time`) + + Returns + ------- + Union[pd.Series, pd.DataFrame, None]: + returns None if no signal in the specific day + """ + + +class SignalWCache(Signal): + """ + Signal With pandas with based Cache + SignalWCache will store the prepared signal as a attribute and give the according signal based on input query + """ + + def __init__(self, signal: Union[pd.Series, pd.DataFrame]) -> None: + """ + + Parameters + ---------- + signal : Union[pd.Series, pd.DataFrame] + The expected format of the signal is like the data below (the order of index is not important and can be + automatically adjusted) + + instrument datetime + SH600000 2008-01-02 0.079704 + 2008-01-03 0.120125 + 2008-01-04 0.878860 + 2008-01-07 0.505539 + 2008-01-08 0.395004 + """ + self.signal_cache = convert_index_format(signal, level="datetime") + + def get_signal(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Union[pd.Series, pd.DataFrame]: + # the frequency of the signal may not align with the decision frequency of strategy + # so resampling from the data is necessary + # the latest signal leverage more recent data and therefore is used in trading. + signal = resam_ts_data(self.signal_cache, start_time=start_time, end_time=end_time, method="last") + return signal + + +class ModelSignal(SignalWCache): + def __init__(self, model: BaseModel, dataset: Dataset) -> None: + self.model = model + self.dataset = dataset + pred_scores = self.model.predict(dataset) + if isinstance(pred_scores, pd.DataFrame): + pred_scores = pred_scores.iloc[:, 0] + super().__init__(pred_scores) + + def _update_model(self) -> None: + """ + When using online data, update model in each bar as the following steps: + - update dataset with online data, the dataset should support online update + - make the latest prediction scores of the new bar + - update the pred score into the latest prediction + """ + # TODO: this method is not included in the framework and could be refactor later + raise NotImplementedError("_update_model is not implemented!") + + +def create_signal_from( + obj: Union[Signal, Tuple[BaseModel, Dataset], List, Dict, Text, pd.Series, pd.DataFrame], +) -> Signal: + """ + create signal from diverse information + This method will choose the right method to create a signal based on `obj` + Please refer to the code below. + """ + if isinstance(obj, Signal): + return obj + elif isinstance(obj, (tuple, list)): + return ModelSignal(*obj) + elif isinstance(obj, (dict, str)): + return init_instance_by_config(obj) + elif isinstance(obj, (pd.DataFrame, pd.Series)): + return SignalWCache(signal=obj) + else: + raise NotImplementedError(f"This type of signal is not supported") diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/utils.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4210c9548a8164f710d9cdd9852c74d2f80ab4ec --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/backtest/utils.py @@ -0,0 +1,290 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +from __future__ import annotations + +from abc import abstractmethod +from typing import Any, Set, Tuple, TYPE_CHECKING, Union + +import numpy as np + +from qlib.utils.time import epsilon_change + +if TYPE_CHECKING: + from qlib.backtest.decision import BaseTradeDecision + +import warnings + +import pandas as pd + +from ..data.data import Cal + + +class TradeCalendarManager: + """ + Manager for trading calendar + - BaseStrategy and BaseExecutor will use it + """ + + def __init__( + self, + freq: str, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + level_infra: LevelInfrastructure | None = None, + ) -> None: + """ + Parameters + ---------- + freq : str + frequency of trading calendar, also trade time per trading step + start_time : Union[str, pd.Timestamp], optional + closed start of the trading calendar, by default None + If `start_time` is None, it must be reset before trading. + end_time : Union[str, pd.Timestamp], optional + closed end of the trade time range, by default None + If `end_time` is None, it must be reset before trading. + """ + self.level_infra = level_infra + self.reset(freq=freq, start_time=start_time, end_time=end_time) + + def reset( + self, + freq: str, + start_time: Union[str, pd.Timestamp] = None, + end_time: Union[str, pd.Timestamp] = None, + ) -> None: + """ + Please refer to the docs of `__init__` + + Reset the trade calendar + - self.trade_len : The total count for trading step + - self.trade_step : The number of trading step finished, self.trade_step can be + [0, 1, 2, ..., self.trade_len - 1] + """ + self.freq = freq + self.start_time = pd.Timestamp(start_time) if start_time else None + self.end_time = pd.Timestamp(end_time) if end_time else None + + _calendar = Cal.calendar(freq=freq, future=True) + assert isinstance(_calendar, np.ndarray) + self._calendar = _calendar + _, _, _start_index, _end_index = Cal.locate_index(start_time, end_time, freq=freq, future=True) + self.start_index = _start_index + self.end_index = _end_index + self.trade_len = _end_index - _start_index + 1 + self.trade_step = 0 + + def finished(self) -> bool: + """ + Check if the trading finished + - Should check before calling strategy.generate_decisions and executor.execute + - If self.trade_step >= self.self.trade_len, it means the trading is finished + - If self.trade_step < self.self.trade_len, it means the number of trading step finished is self.trade_step + """ + return self.trade_step >= self.trade_len + + def step(self) -> None: + if self.finished(): + raise RuntimeError(f"The calendar is finished, please reset it if you want to call it!") + self.trade_step += 1 + + def get_freq(self) -> str: + return self.freq + + def get_trade_len(self) -> int: + """get the total step length""" + return self.trade_len + + def get_trade_step(self) -> int: + return self.trade_step + + def get_step_time(self, trade_step: int | None = None, shift: int = 0) -> Tuple[pd.Timestamp, pd.Timestamp]: + """ + Get the left and right endpoints of the trade_step'th trading interval + + About the endpoints: + - Qlib uses the closed interval in time-series data selection, which has the same performance as + pandas.Series.loc + # - The returned right endpoints should minus 1 seconds because of the closed interval representation in + # Qlib. + # Note: Qlib supports up to minutely decision execution, so 1 seconds is less than any trading time + # interval. + + Parameters + ---------- + trade_step : int, optional + the number of trading step finished, by default None to indicate current step + shift : int, optional + shift bars , by default 0 + + Returns + ------- + Tuple[pd.Timestamp, pd.Timestamp] + - If shift == 0, return the trading time range + - If shift > 0, return the trading time range of the earlier shift bars + - If shift < 0, return the trading time range of the later shift bar + """ + if trade_step is None: + trade_step = self.get_trade_step() + calendar_index = self.start_index + trade_step - shift + return self._calendar[calendar_index], epsilon_change(self._calendar[calendar_index + 1]) + + def get_data_cal_range(self, rtype: str = "full") -> Tuple[int, int]: + """ + get the calendar range + The following assumptions are made + 1) The frequency of the exchange in common_infra is the same as the data calendar + 2) Users want the **data index** mod by **day** (i.e. 240 min) + + Parameters + ---------- + rtype: str + - "full": return the full limitation of the decision in the day + - "step": return the limitation of current step + + Returns + ------- + Tuple[int, int]: + """ + # potential performance issue + assert self.level_infra is not None + + day_start = pd.Timestamp(self.start_time.date()) + day_end = epsilon_change(day_start + pd.Timedelta(days=1)) + freq = self.level_infra.get("common_infra").get("trade_exchange").freq + _, _, day_start_idx, _ = Cal.locate_index(day_start, day_end, freq=freq) + + if rtype == "full": + _, _, start_idx, end_index = Cal.locate_index(self.start_time, self.end_time, freq=freq) + elif rtype == "step": + _, _, start_idx, end_index = Cal.locate_index(*self.get_step_time(), freq=freq) + else: + raise ValueError(f"This type of input {rtype} is not supported") + + return start_idx - day_start_idx, end_index - day_start_idx + + def get_all_time(self) -> Tuple[pd.Timestamp, pd.Timestamp]: + """Get the start_time and end_time for trading""" + return self.start_time, self.end_time + + # helper functions + def get_range_idx(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Tuple[int, int]: + """ + get the range index which involve start_time~end_time (both sides are closed) + + Parameters + ---------- + start_time : pd.Timestamp + end_time : pd.Timestamp + + Returns + ------- + Tuple[int, int]: + the index of the range. **the left and right are closed** + """ + left = int(np.searchsorted(self._calendar, start_time, side="right") - 1) + right = int(np.searchsorted(self._calendar, end_time, side="right") - 1) + left -= self.start_index + right -= self.start_index + + def clip(idx: int) -> int: + return min(max(0, idx), self.trade_len - 1) + + return clip(left), clip(right) + + def __repr__(self) -> str: + return ( + f"class: {self.__class__.__name__}; " + f"{self.start_time}[{self.start_index}]~{self.end_time}[{self.end_index}]: " + f"[{self.trade_step}/{self.trade_len}]" + ) + + +class BaseInfrastructure: + def __init__(self, **kwargs: Any) -> None: + self.reset_infra(**kwargs) + + @abstractmethod + def get_support_infra(self) -> Set[str]: + raise NotImplementedError("`get_support_infra` is not implemented!") + + def reset_infra(self, **kwargs: Any) -> None: + support_infra = self.get_support_infra() + for k, v in kwargs.items(): + if k in support_infra: + setattr(self, k, v) + else: + warnings.warn(f"{k} is ignored in `reset_infra`!") + + def get(self, infra_name: str) -> Any: + if hasattr(self, infra_name): + return getattr(self, infra_name) + else: + warnings.warn(f"infra {infra_name} is not found!") + + def has(self, infra_name: str) -> bool: + return infra_name in self.get_support_infra() and hasattr(self, infra_name) + + def update(self, other: BaseInfrastructure) -> None: + support_infra = other.get_support_infra() + infra_dict = {_infra: getattr(other, _infra) for _infra in support_infra if hasattr(other, _infra)} + self.reset_infra(**infra_dict) + + +class CommonInfrastructure(BaseInfrastructure): + def get_support_infra(self) -> Set[str]: + return {"trade_account", "trade_exchange"} + + +class LevelInfrastructure(BaseInfrastructure): + """level infrastructure is created by executor, and then shared to strategies on the same level""" + + def get_support_infra(self) -> Set[str]: + """ + Descriptions about the infrastructure + + sub_level_infra: + - **NOTE**: this will only work after _init_sub_trading !!! + """ + return {"trade_calendar", "sub_level_infra", "common_infra", "executor"} + + def reset_cal( + self, + freq: str, + start_time: Union[str, pd.Timestamp, None], + end_time: Union[str, pd.Timestamp, None], + ) -> None: + """reset trade calendar manager""" + if self.has("trade_calendar"): + self.get("trade_calendar").reset(freq, start_time=start_time, end_time=end_time) + else: + self.reset_infra( + trade_calendar=TradeCalendarManager(freq, start_time=start_time, end_time=end_time, level_infra=self), + ) + + def set_sub_level_infra(self, sub_level_infra: LevelInfrastructure) -> None: + """this will make the calendar access easier when crossing multi-levels""" + self.reset_infra(sub_level_infra=sub_level_infra) + + +def get_start_end_idx(trade_calendar: TradeCalendarManager, outer_trade_decision: BaseTradeDecision) -> Tuple[int, int]: + """ + A helper function for getting the decision-level index range limitation for inner strategy + - NOTE: this function is not applicable to order-level + + Parameters + ---------- + trade_calendar : TradeCalendarManager + outer_trade_decision : BaseTradeDecision + the trade decision made by outer strategy + + Returns + ------- + Union[int, int]: + start index and end index + """ + try: + return outer_trade_decision.get_range_limit(inner_calendar=trade_calendar) + except NotImplementedError: + return 0, trade_calendar.get_trade_len() - 1 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/data.py new file mode 100644 index 0000000000000000000000000000000000000000..c6da08202f5e90b47924f788269d04914df5807d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/data.py @@ -0,0 +1,8 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import fire +from qlib.tests.data import GetData + +if __name__ == "__main__": + fire.Fire(GetData) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/run.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/run.py new file mode 100644 index 0000000000000000000000000000000000000000..c2dcdc2ef0cb414455fe17bebb9be811d63bedb4 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/cli/run.py @@ -0,0 +1,157 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +import logging +import os +from pathlib import Path +import sys + +import fire +from jinja2 import Template, meta +from ruamel.yaml import YAML + +import qlib +from qlib.config import C +from qlib.log import get_module_logger +from qlib.model.trainer import task_train +from qlib.utils import set_log_with_config +from qlib.utils.data import update_config + +set_log_with_config(C.logging_config) +logger = get_module_logger("qrun", logging.INFO) + + +def get_path_list(path): + if isinstance(path, str): + return [path] + else: + return list(path) + + +def sys_config(config, config_path): + """ + Configure the `sys` section + + Parameters + ---------- + config : dict + configuration of the workflow. + config_path : str + path of the configuration + """ + sys_config = config.get("sys", {}) + + # abspath + for p in get_path_list(sys_config.get("path", [])): + sys.path.append(p) + + # relative path to config path + for p in get_path_list(sys_config.get("rel_path", [])): + sys.path.append(str(Path(config_path).parent.resolve().absolute() / p)) + + +def render_template(config_path: str) -> str: + """ + render the template based on the environment + + Parameters + ---------- + config_path : str + configuration path + + Returns + ------- + str + the rendered content + """ + with open(config_path, "r") as f: + config = f.read() + # Set up the Jinja2 environment + template = Template(config) + + # Parse the template to find undeclared variables + env = template.environment + parsed_content = env.parse(config) + variables = meta.find_undeclared_variables(parsed_content) + + # Get context from os.environ according to the variables + context = {var: os.getenv(var, "") for var in variables if var in os.environ} + logger.info(f"Render the template with the context: {context}") + + # Render the template with the context + rendered_content = template.render(context) + return rendered_content + + +# workflow handler function +def workflow(config_path, experiment_name="workflow", uri_folder="mlruns"): + """ + This is a Qlib CLI entrance. + User can run the whole Quant research workflow defined by a configure file + - the code is located here ``qlib/cli/run.py`` + + User can specify a base_config file in your workflow.yml file by adding "BASE_CONFIG_PATH". + Qlib will load the configuration in BASE_CONFIG_PATH first, and the user only needs to update the custom fields + in their own workflow.yml file. + + For examples: + + qlib_init: + provider_uri: "~/.qlib/qlib_data/cn_data" + region: cn + BASE_CONFIG_PATH: "workflow_config_lightgbm_Alpha158_csi500.yaml" + market: csi300 + + """ + # Render the template + rendered_yaml = render_template(config_path) + yaml = YAML(typ="safe", pure=True) + config = yaml.load(rendered_yaml) + + base_config_path = config.get("BASE_CONFIG_PATH", None) + if base_config_path: + logger.info(f"Use BASE_CONFIG_PATH: {base_config_path}") + base_config_path = Path(base_config_path) + + # it will find config file in absolute path and relative path + if base_config_path.exists(): + path = base_config_path + else: + logger.info( + f"Can't find BASE_CONFIG_PATH base on: {Path.cwd()}, " + f"try using relative path to config path: {Path(config_path).absolute()}" + ) + relative_path = Path(config_path).absolute().parent.joinpath(base_config_path) + if relative_path.exists(): + path = relative_path + else: + raise FileNotFoundError(f"Can't find the BASE_CONFIG file: {base_config_path}") + + with open(path) as fp: + yaml = YAML(typ="safe", pure=True) + base_config = yaml.load(fp) + logger.info(f"Load BASE_CONFIG_PATH succeed: {path.resolve()}") + config = update_config(base_config, config) + + # config the `sys` section + sys_config(config, config_path) + + if "exp_manager" in config.get("qlib_init"): + qlib.init(**config.get("qlib_init")) + else: + exp_manager = C["exp_manager"] + exp_manager["kwargs"]["uri"] = "file:" + str(Path(os.getcwd()).resolve() / uri_folder) + qlib.init(**config.get("qlib_init"), exp_manager=exp_manager) + + if "experiment_name" in config: + experiment_name = config["experiment_name"] + recorder = task_train(config.get("task"), experiment_name=experiment_name) + recorder.save_objects(config=config) + + +# function to run workflow by config +def run(): + fire.Fire(workflow) + + +if __name__ == "__main__": + run() diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/config.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/config.py new file mode 100644 index 0000000000000000000000000000000000000000..ae05037e2ffabdebea28d3fa4373bfe4e74db782 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/config.py @@ -0,0 +1,527 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +""" +About the configs +================= + +The config will be based on _default_config. +Two modes are supported +- client +- server + +""" + +from __future__ import annotations + +import os +import re +import copy +import logging +import platform +import multiprocessing +from pathlib import Path +from typing import Callable, Optional, Union +from typing import TYPE_CHECKING + +from qlib.constant import REG_CN, REG_US, REG_TW + +if TYPE_CHECKING: + from qlib.utils.time import Freq + +from pydantic_settings import BaseSettings, SettingsConfigDict + + +class MLflowSettings(BaseSettings): + uri: str = "file:" + str(Path(os.getcwd()).resolve() / "mlruns") + default_exp_name: str = "Experiment" + + +class QSettings(BaseSettings): + """ + Qlib's settings. + It tries to provide a default settings for most of Qlib's components. + But it would be a long journey to provide a comprehensive settings for all of Qlib's components. + + Here is some design guidelines: + - The priority of settings is + - Actively passed-in settings, like `qlib.init(provider_uri=...)` + - The default settings + - QSettings tries to provide default settings for most of Qlib's components. + """ + + mlflow: MLflowSettings = MLflowSettings() + provider_uri: str = "~/.qlib/qlib_data/cn_data" + + model_config = SettingsConfigDict( + env_prefix="QLIB_", + env_nested_delimiter="_", + ) + + +QSETTINGS = QSettings() + + +class Config: + def __init__(self, default_conf): + self.__dict__["_default_config"] = copy.deepcopy(default_conf) # avoiding conflicts with __getattr__ + self.reset() + + def __getitem__(self, key): + return self.__dict__["_config"][key] + + def __getattr__(self, attr): + if attr in self.__dict__["_config"]: + return self.__dict__["_config"][attr] + + raise AttributeError(f"No such `{attr}` in self._config") + + def get(self, key, default=None): + return self.__dict__["_config"].get(key, default) + + def __setitem__(self, key, value): + self.__dict__["_config"][key] = value + + def __setattr__(self, attr, value): + self.__dict__["_config"][attr] = value + + def __contains__(self, item): + return item in self.__dict__["_config"] + + def __getstate__(self): + return self.__dict__ + + def __setstate__(self, state): + self.__dict__.update(state) + + def __str__(self): + return str(self.__dict__["_config"]) + + def __repr__(self): + return str(self.__dict__["_config"]) + + def reset(self): + self.__dict__["_config"] = copy.deepcopy(self._default_config) + + def update(self, *args, **kwargs): + self.__dict__["_config"].update(*args, **kwargs) + + def set_conf_from_C(self, config_c): + self.update(**config_c.__dict__["_config"]) + + @staticmethod + def register_from_C(config, skip_register=True): + from .utils import set_log_with_config # pylint: disable=C0415 + + if C.registered and skip_register: + return + + C.set_conf_from_C(config) + if C.logging_config: + set_log_with_config(C.logging_config) + C.register() + + +# pickle.dump protocol version: https://docs.python.org/3/library/pickle.html#data-stream-format +PROTOCOL_VERSION = 4 + +NUM_USABLE_CPU = max(multiprocessing.cpu_count() - 2, 1) + +DISK_DATASET_CACHE = "DiskDatasetCache" +SIMPLE_DATASET_CACHE = "SimpleDatasetCache" +DISK_EXPRESSION_CACHE = "DiskExpressionCache" + +DEPENDENCY_REDIS_CACHE = (DISK_DATASET_CACHE, DISK_EXPRESSION_CACHE) + +_default_config = { + # data provider config + "calendar_provider": "LocalCalendarProvider", + "instrument_provider": "LocalInstrumentProvider", + "feature_provider": "LocalFeatureProvider", + "pit_provider": "LocalPITProvider", + "expression_provider": "LocalExpressionProvider", + "dataset_provider": "LocalDatasetProvider", + "provider": "LocalProvider", + # config it in qlib.init() + # "provider_uri" str or dict: + # # str + # "~/.qlib/stock_data/cn_data" + # # dict + # {"day": "~/.qlib/stock_data/cn_data", "1min": "~/.qlib/stock_data/cn_data_1min"} + # NOTE: provider_uri priority: + # 1. backend_config: backend_obj["kwargs"]["provider_uri"] + # 2. backend_config: backend_obj["kwargs"]["provider_uri_map"] + # 3. qlib.init: provider_uri + "provider_uri": "", + # cache + "expression_cache": None, + "calendar_cache": None, + # for simple dataset cache + "local_cache_path": None, + # kernels can be a fixed value or a callable function lie `def (freq: str) -> int` + # If the kernels are arctic_kernels, `min(NUM_USABLE_CPU, 30)` may be a good value + "kernels": NUM_USABLE_CPU, + # pickle.dump protocol version + "dump_protocol_version": PROTOCOL_VERSION, + # How many tasks belong to one process. Recommend 1 for high-frequency data and None for daily data. + "maxtasksperchild": None, + # If joblib_backend is None, use loky + "joblib_backend": "multiprocessing", + "default_disk_cache": 1, # 0:skip/1:use + "mem_cache_size_limit": 500, + "mem_cache_limit_type": "length", + # memory cache expire second, only in used 'DatasetURICache' and 'client D.calendar' + # default 1 hour + "mem_cache_expire": 60 * 60, + # cache dir name + "dataset_cache_dir_name": "dataset_cache", + "features_cache_dir_name": "features_cache", + # redis + # in order to use cache + "redis_host": "127.0.0.1", + "redis_port": 6379, + "redis_task_db": 1, + "redis_password": None, + # This value can be reset via qlib.init + "logging_level": logging.INFO, + # Global configuration of qlib log + # logging_level can control the logging level more finely + "logging_config": { + "version": 1, + "formatters": { + "logger_format": { + "format": "[%(process)s:%(threadName)s](%(asctime)s) %(levelname)s - %(name)s - [%(filename)s:%(lineno)d] - %(message)s" + } + }, + "filters": { + "field_not_found": { + "()": "qlib.log.LogFilter", + "param": [".*?WARN: data not found for.*?"], + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": logging.DEBUG, + "formatter": "logger_format", + "filters": ["field_not_found"], + } + }, + # Normally this should be set to `False` to avoid duplicated logging [1]. + # However, due to bug in pytest, it requires log message to propagate to root logger to be captured by `caplog` [2]. + # [1] https://github.com/microsoft/qlib/pull/1661 + # [2] https://github.com/pytest-dev/pytest/issues/3697 + "loggers": {"qlib": {"level": logging.DEBUG, "handlers": ["console"], "propagate": False}}, + # To let qlib work with other packages, we shouldn't disable existing loggers. + # Note that this param is default to True according to the documentation of logging. + "disable_existing_loggers": False, + }, + # Default config for experiment manager + "exp_manager": { + "class": "MLflowExpManager", + "module_path": "qlib.workflow.expm", + "kwargs": { + "uri": QSETTINGS.mlflow.uri, + "default_exp_name": QSETTINGS.mlflow.default_exp_name, + }, + }, + "pit_record_type": { + "date": "I", # uint32 + "period": "I", # uint32 + "value": "d", # float64 + "index": "I", # uint32 + }, + "pit_record_nan": { + "date": 0, + "period": 0, + "value": float("NAN"), + "index": 0xFFFFFFFF, + }, + # Default config for MongoDB + "mongo": { + "task_url": "mongodb://localhost:27017/", + "task_db_name": "default_task_db", + }, + # Shift minute for highfreq minute data, used in backtest + # if min_data_shift == 0, use default market time [9:30, 11:29, 1:00, 2:59] + # if min_data_shift != 0, use shifted market time [9:30, 11:29, 1:00, 2:59] - shift*minute + "min_data_shift": 0, +} + +MODE_CONF = { + "server": { + # config it in qlib.init() + "provider_uri": "", + # redis + "redis_host": "127.0.0.1", + "redis_port": 6379, + "redis_task_db": 1, + # cache + "expression_cache": DISK_EXPRESSION_CACHE, + "dataset_cache": DISK_DATASET_CACHE, + "local_cache_path": Path("~/.cache/qlib_simple_cache").expanduser().resolve(), + "mount_path": None, + }, + "client": { + # config it in user's own code + "provider_uri": QSETTINGS.provider_uri, + # cache + # Using parameter 'remote' to announce the client is using server_cache, and the writing access will be disabled. + # Disable cache by default. Avoid introduce advanced features for beginners + "dataset_cache": None, + # SimpleDatasetCache directory + "local_cache_path": Path("~/.cache/qlib_simple_cache").expanduser().resolve(), + # client config + "mount_path": None, + "auto_mount": False, # The nfs is already mounted on our server[auto_mount: False]. + # The nfs should be auto-mounted by qlib on other + # serversS(such as PAI) [auto_mount:True] + "timeout": 100, + "logging_level": logging.INFO, + "region": REG_CN, + # custom operator + # each element of custom_ops should be Type[ExpressionOps] or dict + # if element of custom_ops is Type[ExpressionOps], it represents the custom operator class + # if element of custom_ops is dict, it represents the config of custom operator and should include `class` and `module_path` keys. + "custom_ops": [], + }, +} + +HIGH_FREQ_CONFIG = { + "provider_uri": "~/.qlib/qlib_data/cn_data_1min", + "dataset_cache": None, + "expression_cache": "DiskExpressionCache", + "region": REG_CN, +} + +_default_region_config = { + REG_CN: { + "trade_unit": 100, + "limit_threshold": 0.095, + "deal_price": "close", + }, + REG_US: { + "trade_unit": 1, + "limit_threshold": None, + "deal_price": "close", + }, + REG_TW: { + "trade_unit": 1000, + "limit_threshold": 0.1, + "deal_price": "close", + }, +} + + +class QlibConfig(Config): + # URI_TYPE + LOCAL_URI = "local" + NFS_URI = "nfs" + DEFAULT_FREQ = "__DEFAULT_FREQ" + + def __init__(self, default_conf): + super().__init__(default_conf) + self._registered = False + + class DataPathManager: + """ + Motivation: + - get the right path (e.g. data uri) for accessing data based on given information(e.g. provider_uri, mount_path and frequency) + - some helper functions to process uri. + """ + + def __init__(self, provider_uri: Union[str, Path, dict], mount_path: Union[str, Path, dict]): + """ + The relation of `provider_uri` and `mount_path` + - `mount_path` is used only if provider_uri is an NFS path + - otherwise, provider_uri will be used for accessing data + """ + self.provider_uri = provider_uri + self.mount_path = mount_path + + @staticmethod + def format_provider_uri(provider_uri: Union[str, dict, Path]) -> dict: + if provider_uri is None: + raise ValueError("provider_uri cannot be None") + if isinstance(provider_uri, (str, dict, Path)): + if not isinstance(provider_uri, dict): + provider_uri = {QlibConfig.DEFAULT_FREQ: provider_uri} + else: + raise TypeError(f"provider_uri does not support {type(provider_uri)}") + for freq, _uri in provider_uri.items(): + if QlibConfig.DataPathManager.get_uri_type(_uri) == QlibConfig.LOCAL_URI: + provider_uri[freq] = str(Path(_uri).expanduser().resolve()) + return provider_uri + + @staticmethod + def get_uri_type(uri: Union[str, Path]): + uri = uri if isinstance(uri, str) else str(uri.expanduser().resolve()) + is_win = re.match("^[a-zA-Z]:.*", uri) is not None # such as 'C:\\data', 'D:' + # such as 'host:/data/' (User may define short hostname by themselves or use localhost) + is_nfs_or_win = re.match("^[^/]+:.+", uri) is not None + + if is_nfs_or_win and not is_win: + return QlibConfig.NFS_URI + else: + return QlibConfig.LOCAL_URI + + def get_data_uri(self, freq: Optional[Union[str, Freq]] = None) -> Path: + """ + please refer DataPathManager's __init__ and class doc + """ + if freq is not None: + freq = str(freq) # converting Freq to string + if freq is None or freq not in self.provider_uri: + freq = QlibConfig.DEFAULT_FREQ + _provider_uri = self.provider_uri[freq] + if self.get_uri_type(_provider_uri) == QlibConfig.LOCAL_URI: + return Path(_provider_uri) + elif self.get_uri_type(_provider_uri) == QlibConfig.NFS_URI: + if "win" in platform.system().lower(): + # windows, mount_path is the drive + _path = str(self.mount_path[freq]) + return Path(f"{_path}:\\") if ":" not in _path else Path(_path) + return Path(self.mount_path[freq]) + else: + raise NotImplementedError(f"This type of uri is not supported") + + def set_mode(self, mode): + # raise KeyError + self.update(MODE_CONF[mode]) + # TODO: update region based on kwargs + + def set_region(self, region): + # raise KeyError + self.update(_default_region_config[region]) + + @staticmethod + def is_depend_redis(cache_name: str): + return cache_name in DEPENDENCY_REDIS_CACHE + + @property + def dpm(self): + return self.DataPathManager(self["provider_uri"], self["mount_path"]) + + def resolve_path(self): + # resolve path + _mount_path = self["mount_path"] + _provider_uri = self.DataPathManager.format_provider_uri(self["provider_uri"]) + if not isinstance(_mount_path, dict): + _mount_path = {_freq: _mount_path for _freq in _provider_uri.keys()} + + # check provider_uri and mount_path + _miss_freq = set(_provider_uri.keys()) - set(_mount_path.keys()) + assert len(_miss_freq) == 0, f"mount_path is missing freq: {_miss_freq}" + + # resolve + for _freq in _provider_uri.keys(): + # mount_path + _mount_path[_freq] = ( + _mount_path[_freq] if _mount_path[_freq] is None else str(Path(_mount_path[_freq]).expanduser()) + ) + self["provider_uri"] = _provider_uri + self["mount_path"] = _mount_path + + def set(self, default_conf: str = "client", **kwargs): + """ + configure qlib based on the input parameters + + The configuration will act like a dictionary. + + Normally, it literally is replaced the value according to the keys. + However, sometimes it is hard for users to set the config when the configuration is nested and complicated + + So this API provides some special parameters for users to set the keys in a more convenient way. + - region: REG_CN, REG_US + - several region-related config will be changed + + Parameters + ---------- + default_conf : str + the default config template chosen by user: "server", "client" + """ + from .utils import set_log_with_config, get_module_logger, can_use_cache # pylint: disable=C0415 + + self.reset() + + _logging_config = kwargs.get("logging_config", self.logging_config) + + # set global config + if _logging_config: + set_log_with_config(_logging_config) + + logger = get_module_logger("Initialization", kwargs.get("logging_level", self.logging_level)) + logger.info(f"default_conf: {default_conf}.") + + self.set_mode(default_conf) + self.set_region(kwargs.get("region", self["region"] if "region" in self else REG_CN)) + + for k, v in kwargs.items(): + if k not in self: + logger.warning("Unrecognized config %s" % k) + self[k] = v + + self.resolve_path() + + if not (self["expression_cache"] is None and self["dataset_cache"] is None): + # check redis + if not can_use_cache(): + log_str = "" + # check expression cache + if self.is_depend_redis(self["expression_cache"]): + log_str += self["expression_cache"] + self["expression_cache"] = None + # check dataset cache + if self.is_depend_redis(self["dataset_cache"]): + log_str += f" and {self['dataset_cache']}" if log_str else self["dataset_cache"] + self["dataset_cache"] = None + if log_str: + logger.warning( + f"redis connection failed(host={self['redis_host']} port={self['redis_port']}), " + f"{log_str} will not be used!" + ) + + def register(self): + from .utils import init_instance_by_config # pylint: disable=C0415 + from .data.ops import register_all_ops # pylint: disable=C0415 + from .data.data import register_all_wrappers # pylint: disable=C0415 + from .workflow import R, QlibRecorder # pylint: disable=C0415 + from .workflow.utils import experiment_exit_handler # pylint: disable=C0415 + + register_all_ops(self) + register_all_wrappers(self) + # set up QlibRecorder + exp_manager = init_instance_by_config(self["exp_manager"]) + qr = QlibRecorder(exp_manager) + R.register(qr) + # clean up experiment when python program ends + experiment_exit_handler() + + # Supporting user reset qlib version (useful when user want to connect to qlib server with old version) + self.reset_qlib_version() + + self._registered = True + + def reset_qlib_version(self): + import qlib # pylint: disable=C0415 + + reset_version = self.get("qlib_reset_version", None) + if reset_version is not None: + qlib.__version__ = reset_version + else: + qlib.__version__ = getattr(qlib, "__version__bak") + # Due to a bug? that converting __version__ to _QlibConfig__version__bak + # Using __version__bak instead of __version__ + + def get_kernels(self, freq: str): + """get number of processors given frequency""" + if isinstance(self["kernels"], Callable): + return self["kernels"](freq) + return self["kernels"] + + @property + def registered(self): + return self._registered + + +# global config +C = QlibConfig(_default_config) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/constant.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/constant.py new file mode 100644 index 0000000000000000000000000000000000000000..ac6c76ae22c9c9782d0537a33da40b4cb1a2c77b --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/constant.py @@ -0,0 +1,22 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# REGION CONST +from typing import TypeVar + +import numpy as np +import pandas as pd + +REG_CN = "cn" +REG_US = "us" +REG_TW = "tw" + +# Epsilon for avoiding division by zero. +EPS = 1e-12 + +# Infinity in integer +INF = int(1e18) +ONE_DAY = pd.Timedelta("1day") +ONE_MIN = pd.Timedelta("1min") +EPS_T = pd.Timedelta("1s") # use 1 second to exclude the right interval point +float_or_ndarray = TypeVar("float_or_ndarray", float, np.ndarray) diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/__init__.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/data.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/data.py new file mode 100644 index 0000000000000000000000000000000000000000..c153cfb8f6dfa75be394339be56c66425802563d --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/data.py @@ -0,0 +1,55 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +# We remove arctic from core framework of Qlib to contrib due to +# - Arctic has very strict limitation on pandas and numpy version +# - https://github.com/man-group/arctic/pull/908 +# - pip fail to computing the right version number!!!! +# - Maybe we can solve this problem by poetry + +# FIXME: So if you want to use arctic-based provider, please install arctic manually +# `pip install arctic` may not be enough. +from arctic import Arctic +import pandas as pd +import pymongo + +from qlib.data.data import FeatureProvider + + +class ArcticFeatureProvider(FeatureProvider): + def __init__( + self, uri="127.0.0.1", retry_time=0, market_transaction_time_list=[("09:15", "11:30"), ("13:00", "15:00")] + ): + super().__init__() + self.uri = uri + # TODO: + # retry connecting if error occurs + # does it real matters? + self.retry_time = retry_time + # NOTE: this is especially important for TResample operator + self.market_transaction_time_list = market_transaction_time_list + + def feature(self, instrument, field, start_index, end_index, freq): + field = str(field)[1:] + with pymongo.MongoClient(self.uri) as client: + # TODO: this will result in frequently connecting the server and performance issue + arctic = Arctic(client) + + if freq not in arctic.list_libraries(): + raise ValueError("lib {} not in arctic".format(freq)) + + if instrument not in arctic[freq].list_symbols(): + # instruments does not exist + return pd.Series() + else: + df = arctic[freq].read(instrument, columns=[field], chunk_range=(start_index, end_index)) + s = df[field] + + if not s.empty: + s = pd.concat( + [ + s.between_time(time_tuple[0], time_tuple[1]) + for time_tuple in self.market_transaction_time_list + ] + ) + return s diff --git a/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/dataset.py b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd7fcf0062f493aa98d339316843cc52f8067a5 --- /dev/null +++ b/Kronos/qlib/build/lib.linux-x86_64-cpython-39/qlib/contrib/data/dataset.py @@ -0,0 +1,362 @@ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. + +import copy +import torch +import warnings +import numpy as np +import pandas as pd +from qlib.utils.data import guess_horizon +from qlib.utils import init_instance_by_config + +from qlib.data.dataset import DatasetH + +device = "cuda" if torch.cuda.is_available() else "cpu" + + +def _to_tensor(x): + if not isinstance(x, torch.Tensor): + return torch.tensor(x, dtype=torch.float, device=device) # pylint: disable=E1101 + return x + + +def _create_ts_slices(index, seq_len): + """ + create time series slices from pandas index + + Args: + index (pd.MultiIndex): pandas multiindex with order + seq_len (int): sequence length + """ + assert isinstance(index, pd.MultiIndex), "unsupported index type" + assert seq_len > 0, "sequence length should be larger than 0" + assert index.is_monotonic_increasing, "index should be sorted" + + # number of dates for each instrument + sample_count_by_insts = index.to_series().groupby(level=0, group_keys=False).size().values + + # start index for each instrument + start_index_of_insts = np.roll(np.cumsum(sample_count_by_insts), 1) + start_index_of_insts[0] = 0 + + # all the [start, stop) indices of features + # features between [start, stop) will be used to predict label at `stop - 1` + slices = [] + for cur_loc, cur_cnt in zip(start_index_of_insts, sample_count_by_insts): + for stop in range(1, cur_cnt + 1): + end = cur_loc + stop + start = max(end - seq_len, 0) + slices.append(slice(start, end)) + slices = np.array(slices, dtype="object") + + assert len(slices) == len(index) # the i-th slice = index[i] + + return slices + + +def _get_date_parse_fn(target): + """get date parse function + + This method is used to parse date arguments as target type. + + Example: + get_date_parse_fn('20120101')('2017-01-01') => '20170101' + get_date_parse_fn(20120101)('2017-01-01') => 20170101 + """ + if isinstance(target, int): + + def _fn(x): + return int(str(x).replace("-", "")[:8]) # 20200201 + + elif isinstance(target, str) and len(target) == 8: + + def _fn(x): + return str(x).replace("-", "")[:8] # '20200201' + + else: + + def _fn(x): + return x # '2021-01-01' + + return _fn + + +def _maybe_padding(x, seq_len, zeros=None): + """padding 2d