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 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 |
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:
nam... |
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_templat... | __init__ | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
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.
A... |
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 as... | get_collector | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
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 da... |
Use rolling_gen to generate different tasks based on task_template.
Returns:
List[dict]: a list of tasks
| first_tasks | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
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... |
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.
| prepare_tasks | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
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) ... |
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
| _list_latest | python | microsoft/qlib | qlib/workflow/online/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/strategy.py | MIT |
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
... |
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
... | get_dataset | python | microsoft/qlib | qlib/workflow/online/update.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/update.py | MIT |
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:
... |
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.
... | __init__ | python | microsoft/qlib | qlib/workflow/online/update.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/update.py | MIT |
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:
... |
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
| prepare_data | python | microsoft/qlib | qlib/workflow/online/update.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/update.py | MIT |
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... |
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
-------
... | update | python | microsoft/qlib | qlib/workflow/online/update.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/update.py | MIT |
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. pr... |
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)
| get_update_data | python | microsoft/qlib | qlib/workflow/online/update.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/update.py | MIT |
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 |
Init OnlineToolR.
Args:
default_exp_name (str): the default experiment name.
| __init__ | python | microsoft/qlib | qlib/workflow/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/utils.py | MIT |
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 o... |
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
| set_online_tag | python | microsoft/qlib | qlib/workflow/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/utils.py | MIT |
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(sel... |
Given a model recorder and return its online tag.
Args:
recorder (Recorder): an instance of recorder
Returns:
str: the online tag
| get_online_tag | python | microsoft/qlib | qlib/workflow/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/utils.py | MIT |
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... |
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.
| reset_online_tag | python | microsoft/qlib | qlib/workflow/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/utils.py | MIT |
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_... |
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.
| online_models | python | microsoft/qlib | qlib/workflow/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/utils.py | MIT |
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)... |
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.
| update_online_pred | python | microsoft/qlib | qlib/workflow/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/online/utils.py | MIT |
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.p... |
Init Collector.
Args:
process_list (list or Callable): the list of processors or the instance of a processor to process dict.
| __init__ | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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... |
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... | process_collect | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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, *a... |
Do the workflow including ``collect`` and ``process_collect``
Returns:
dict: the dict after collecting and processing.
| __call__ | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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 processo... |
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. T... | __init__ | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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():
... |
Collect all results of collector_dict and change the outermost key to a recombination key.
Returns:
dict: the dict after collecting.
| collect | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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 RecorderColl... |
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... | __init__ | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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_f... |
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.
... | collect | python | microsoft/qlib | qlib/workflow/task/collect.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/collect.py | MIT |
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_g... |
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*... | task_generator | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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
""" |
Generate different tasks based on a task template
Parameters
----------
task: dict
a task template
Returns
-------
typing.List[dict]:
A list of tasks
| generate | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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 e... |
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 chan... | handler_mod | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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
tes... |
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**
| trunc_segments | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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 task... |
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 act... | __init__ | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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 in... |
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 follo... | gen_following_tasks | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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": {
... |
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",
... | generate | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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
... |
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... | __init__ | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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
""" |
This method is designed to change the task **in place**
Parameters
----------
task : dict
Qlib's task
hr : int
the horizon of task
| set_horizon | python | microsoft/qlib | qlib/workflow/task/gen.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/gen.py | MIT |
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
----------
... |
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 Collec... | __init__ | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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
... |
_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
... | _decode_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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. Defa... |
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:
d... | _decode_query | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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.repla... |
Use a new task to replace a old one
Args:
task: old task
new_task: new task
| replace_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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... |
Insert a task.
Args:
task: the task waiting for insert
Returns:
pymongo.results.InsertOneResult
| insert_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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(
{
... |
Insert a task to task_pool
Parameters
----------
task_def: dict
the task definition
Returns
-------
pymongo.results.InsertOneResult
| insert_task_def | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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
... |
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 ... | create_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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 i... |
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
| fetch_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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
... |
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
| safe_fetch_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
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 <your task pool> query '{"_id": "615498be837d... |
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 <your task pool> query '{"_id": "615498be837d0053acbc5d58"}'
Parameters
-------... | query | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.