code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
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
... |
Parameters
----------
indexing :
query for data
Raises
------
KeyError:
If the non-slice index is queried but does not exist, `KeyError` is raised.
| __getitem__ | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
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(... |
meta class for auto generating operations for index data.
| index_data_ops_creator | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def abs(self):
"""get the abs of data except np.nan."""
tmp_data = np.absolute(self.data)
return self.__class__(tmp_data, *self.indices) | get the abs of data except np.nan. | abs | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
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, floa... | 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 ... | __init__ | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
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
-------
... | 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
| reindex | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
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.
Param... | 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[L... | __init__ | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
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, Modul... | Load module path
:param module_path:
:return:
:raises: ModuleNotFoundError
| get_module_by_module_path | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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)
ret... |
Parameters
----------
module_path : str
e.g. "a.b.c.ClassName"
Returns
-------
Tuple[str, str]
e.g. ("a.b.c", "ClassName")
| split_module_path | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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_m... |
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 wi... | get_callable_kwargs | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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
... |
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'] ... | init_instance_by_config | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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... |
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
| class_casting | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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.h... |
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)
[<class 'qlib.contrib.data.handler.Alpha158'>, <class 'qlib.c... | find_all_classes | python | microsoft/qlib | qlib/utils/mod.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/mod.py | MIT |
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_fu... | 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 fu... | datetime_groupby_apply | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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_i... | _replace_and_get_dt.
FIXME: this function may cause infinite loop when the complex data-structure contains loop-reference
Parameters
----------
complex_iter :
complex_iter
| _replace_and_get_dt | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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 ... | _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
| _recover_dt | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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_... | 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)... | complex_parallel | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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
-------
Callabl... |
Parameters
----------
func : Callable
the function to be wrapped
qlib_config : QlibConfig
Qlib config for initialization in subprocess
Returns
-------
Callable
| __init__ | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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) | Modify the initial function by adding Qlib initialization | _func_mod | python | microsoft/qlib | qlib/utils/paral.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/paral.py | MIT |
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.
P... |
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 ... | resam_calendar | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
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: ... | get the feature with higher or equal frequency than `freq`.
Returns
-------
pd.DataFrame
the feature with higher or equal frequency
| get_higher_eq_freq_feature | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
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 Mult... |
Resample value from time-series data
- If `feature` has MultiIndex[instrument, datetime], apply the `method` to each instruemnt data with datetime in [start_time, end_time]
Example:
.. code-block::
print(feature)
$close ... | resam_ts_data | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
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 the first/last not nan value of pd.Series|DataFrame with single level index | _ts_data_valid | python | microsoft/qlib | qlib/utils/resam.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/resam.py | MIT |
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}"):
... |
What attribute will not be in specific list
Parameters
----------
attr_type : str
"include" or "exclude"
Returns
-------
list:
| _get_attr_list | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
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 ... |
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
... | config | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
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
Wha... |
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
... | to_pickle | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
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)`
"""
wi... |
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)`
| load | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
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... |
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
| get_backend | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
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)... |
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
| general_dump | python | microsoft/qlib | qlib/utils/serial.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/serial.py | MIT |
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... |
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
-------
L... | get_min_cal | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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 ... | 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
----... | is_single_value | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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]
... |
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 u... | parse | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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,
... | Calculate freq delta
Parameters
----------
left_frq: str
right_freq: str
Returns
-------
| get_min_delta | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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
... | 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
| get_recent_freq | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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 : ... |
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... | get_day_min_idx_range | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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
... |
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
Reg... | cal_sam_minute | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
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" ... |
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.... | epsilon_change | python | microsoft/qlib | qlib/utils/time.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/time.py | MIT |
def get_period_list(first: int, last: int, quarterly: bool) -> 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 yearl... |
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 betwee... | get_period_list | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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
... |
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... | read_period_data | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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.maxim... |
forward fill a 1D numpy array
Parameters
----------
arr : np.array
Input numpy 1D array
| np_ffill | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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:
... | multi fields list lower bound.
for single field list use `bisect.bisect_left` instead
| lower_bound | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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:
... | multi fields list upper bound.
for single field list use `bisect.bisect_right` instead
| upper_bound | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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(sel... | Compare dict value
:param src_data:
:param dst_data:
:return:
| compare_dict_value | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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) | remove repeat field
:param fields: list; features fields
:return: list
| remove_repeat_field | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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] | remove fields space
:param fields: features fields
:return: list or str
| remove_fields_space | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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:
... | normalize cache instruments
:return: list or dict
| normalize_cache_instruments | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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()) | judgy whether date is a tradable date
----------
date : pandas.Timestamp
current date
| is_tradable_date | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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... | get trading date range by shift
Parameters
----------
trading_date: pd.Timestamp
left_shift: int
right_shift: int
future: bool
| get_date_range | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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
---------... | 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, ... | get_date_by_shift | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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 ... | 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
| transform_end_date | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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 | Get the date(YYYY-MM-DD) written in file name
Parameter
file_name : str
:return
date : str
'YYYY-MM-DD'
| get_date_in_file_name | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
def split_pred(pred, number=None, split_date=None):
"""split the score file into two part
Parameter
---------
pred : pd.DataFrame (index:<instrument, datetime>)
A score file of stocks
number: the number of dates for pred_left
split_date: the last date of the pred_left
... | split the score file into two part
Parameter
---------
pred : pd.DataFrame (index:<instrument, datetime>)
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... | split_pred | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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... |
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.Timestam... | time_to_slc_point | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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:
... |
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
| lazy_sort_index | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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' :... |
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':... | flatten_dict | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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.
... |
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'... | get_item_from_obj | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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 conf... |
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>": model, "<DATASET>": dataset}`, "<MODEL... | fill_placeholder | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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 ... |
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 f... | auto_filter_kwargs | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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, ... | register_wrapper
:param wrapper: A wrapper.
:param cls_or_obj: A class or class name or object instance.
| register_wrapper | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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_ob... | load dataset from multiple file formats | load_dataset | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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-c... | stock code to file name
Parameters
----------
code: str
| code_to_fname | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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 | file name to stock code
Parameters
----------
fname: str
| fname_to_code | python | microsoft/qlib | qlib/utils/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/__init__.py | MIT |
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... |
Configure the `sys` section
Parameters
----------
config : dict
configuration of the workflow.
config_path : str
path of the configuration
| sys_config | python | microsoft/qlib | qlib/workflow/cli.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/cli.py | MIT |
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()
... |
render the template based on the environment
Parameters
----------
config_path : str
configuration path
Returns
-------
str
the rendered content
| render_template | python | microsoft/qlib | qlib/workflow/cli.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/cli.py | MIT |
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/workflow/cli.py`
User can specify a base_config file in your workflow.yml file by... |
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/workflow/cli.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_PAT... | workflow | python | microsoft/qlib | qlib/workflow/cli.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/cli.py | MIT |
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 m... |
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 automati... | get_recorder | python | microsoft/qlib | qlib/workflow/exp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/exp.py | MIT |
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... |
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.
| _get_or_create_rec | python | microsoft/qlib | qlib/workflow/exp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/exp.py | MIT |
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 `... |
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... | list_recorders | python | microsoft/qlib | qlib/workflow/exp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/exp.py | MIT |
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_... |
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.
| _get_recorder | python | microsoft/qlib | qlib/workflow/exp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/exp.py | MIT |
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,
) -> Exp... |
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 : ... | start_exp | python | microsoft/qlib | qlib/workflow/expm.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/expm.py | MIT |
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
... |
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
... | end_exp | python | microsoft/qlib | qlib/workflow/expm.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/expm.py | MIT |
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 retu... |
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... | get_exp | python | microsoft/qlib | qlib/workflow/expm.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/expm.py | MIT |
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.
"""
... |
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.
| _get_or_create_exp | python | microsoft/qlib | qlib/workflow/expm.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/expm.py | MIT |
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"] |
Get the default tracking URI from qlib.config.C
| default_uri | python | microsoft/qlib | qlib/workflow/expm.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/expm.py | MIT |
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 Non... |
Method for getting or creating an experiment. It will try to first get a valid experiment, if exception occurs, it will
raise errors.
| _get_exp | python | microsoft/qlib | qlib/workflow/expm.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/expm.py | MIT |
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:
... |
This function will return the directory path of this recorder.
| get_local_dir | python | microsoft/qlib | qlib/workflow/recorder.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/recorder.py | MIT |
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 exc... |
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: t... | load_object | python | microsoft/qlib | qlib/workflow/recorder.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/recorder.py | MIT |
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.... |
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`
| save | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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 t... |
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... | load | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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
... |
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... | check | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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 ... | automatically checking the files and then run the concrete generating task | generate | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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")
... |
Parameters
----------
label : Optional[pd.DataFrame]
Label should be a dataframe.
| _generate | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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
... |
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]
... | __init__ | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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
... |
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.
| __init__ | python | microsoft/qlib | qlib/workflow/record_temp.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/record_temp.py | MIT |
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
"""
... |
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
| experiment_exception_hook | python | microsoft/qlib | qlib/workflow/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/utils.py | MIT |
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 ... |
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(da... | start | python | microsoft/qlib | qlib/workflow/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/__init__.py | MIT |
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 ma... |
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')
... | start_exp | python | microsoft/qlib | qlib/workflow/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/__init__.py | MIT |
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... |
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:
- ... | get_exp | python | microsoft/qlib | qlib/workflow/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/__init__.py | MIT |
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... |
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
| uri_context | python | microsoft/qlib | qlib/workflow/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/__init__.py | MIT |
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 a... |
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... | get_recorder | python | microsoft/qlib | qlib/workflow/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/__init__.py | MIT |
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
... |
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 A... | save_objects | python | microsoft/qlib | qlib/workflow/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/__init__.py | MIT |
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.
... |
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 ... | __init__ | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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 (Li... |
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 defa... | first_train | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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... |
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 fin... | routine | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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_c... |
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 coll... | get_collector | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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):
... |
Add some new strategies to OnlineManager.
Args:
strategy (Union[OnlineStrategy, List[OnlineStrategy]]): a list of OnlineStrategy
| add_strategy | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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... |
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... | prepare_signals | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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 traini... |
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 w... | simulate | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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:
# T... |
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`
| delay_prepare | python | microsoft/qlib | qlib/workflow/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/manager.py | MIT |
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)... |
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.
... | __init__ | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
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 l... |
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 ... | prepare_online_models | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.