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 __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 |
def return_task(self, task, status=STATUS_WAITING):
"""
Return a task to status. Always using in error handling.
Args:
task ([type]): [description]
status (str, optional): STATUS_WAITING, STATUS_RUNNING, STATUS_DONE, STATUS_PART_DONE. Defaults to STATUS_WAITING.
... |
Return a task to status. Always using in error handling.
Args:
task ([type]): [description]
status (str, optional): STATUS_WAITING, STATUS_RUNNING, STATUS_DONE, STATUS_PART_DONE. Defaults to STATUS_WAITING.
| return_task | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def remove(self, query={}):
"""
Remove the task using query
Parameters
----------
query: dict
the dict of query
"""
query = query.copy()
query = self._decode_query(query)
self.task_pool.delete_many(query) |
Remove the task using query
Parameters
----------
query: dict
the dict of query
| remove | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def task_stat(self, query={}) -> dict:
"""
Count the tasks in every status.
Args:
query (dict, optional): the query dict. Defaults to {}.
Returns:
dict
"""
query = query.copy()
query = self._decode_query(query)
tasks = self.query(... |
Count the tasks in every status.
Args:
query (dict, optional): the query dict. Defaults to {}.
Returns:
dict
| task_stat | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def reset_waiting(self, query={}):
"""
Reset all running task into waiting status. Can be used when some running task exit unexpected.
Args:
query (dict, optional): the query dict. Defaults to {}.
"""
query = query.copy()
# default query
if "status" n... |
Reset all running task into waiting status. Can be used when some running task exit unexpected.
Args:
query (dict, optional): the query dict. Defaults to {}.
| reset_waiting | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def prioritize(self, task, priority: int):
"""
Set priority for task
Parameters
----------
task : dict
The task query from the database
priority : int
the target priority
"""
update_dict = {"$set": {"priority": priority}}
s... |
Set priority for task
Parameters
----------
task : dict
The task query from the database
priority : int
the target priority
| prioritize | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def wait(self, query={}):
"""
When multiprocessing, the main progress may fetch nothing from TaskManager because there are still some running tasks.
So main progress should wait until all tasks are trained well by other progress or machines.
Args:
query (dict, optional): the... |
When multiprocessing, the main progress may fetch nothing from TaskManager because there are still some running tasks.
So main progress should wait until all tasks are trained well by other progress or machines.
Args:
query (dict, optional): the query dict. Defaults to {}.
| wait | python | microsoft/qlib | qlib/workflow/task/manage.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/manage.py | MIT |
def get_mongodb() -> Database:
"""
Get database in MongoDB, which means you need to declare the address and the name of a database at first.
For example:
Using qlib.init():
.. code-block:: python
mongo_conf = {
"task_url": task_url, # your MongoDB... |
Get database in MongoDB, which means you need to declare the address and the name of a database at first.
For example:
Using qlib.init():
.. code-block:: python
mongo_conf = {
"task_url": task_url, # your MongoDB url
"task_db_name... | get_mongodb | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def list_recorders(experiment, rec_filter_func=None):
"""
List all recorders which can pass the filter in an experiment.
Args:
experiment (str or Experiment): the name of an Experiment or an instance
rec_filter_func (Callable, optional): return True to retain the given recorder. Defaults to... |
List all recorders which can pass the filter in an experiment.
Args:
experiment (str or Experiment): the name of an Experiment or an instance
rec_filter_func (Callable, optional): return True to retain the given recorder. Defaults to None.
Returns:
dict: a dict {rid: recorder} aft... | list_recorders | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def get(self, idx: int):
"""
Get datetime by index.
Parameters
----------
idx : int
index of the calendar
"""
if idx is None or idx >= len(self.cals):
return None
return self.cals[idx] |
Get datetime by index.
Parameters
----------
idx : int
index of the calendar
| get | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def align_idx(self, time_point, tp_type="start") -> int:
"""
Align the index of time_point in the calendar.
Parameters
----------
time_point
tp_type : str
Returns
-------
index : int
"""
if time_point is None:
# `None`... |
Align the index of time_point in the calendar.
Parameters
----------
time_point
tp_type : str
Returns
-------
index : int
| align_idx | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def align_time(self, time_point, tp_type="start") -> pd.Timestamp:
"""
Align time_point to trade date of calendar
Args:
time_point
Time point
tp_type : str
time point type (`"start"`, `"end"`)
Returns:
pd.Timestamp
... |
Align time_point to trade date of calendar
Args:
time_point
Time point
tp_type : str
time point type (`"start"`, `"end"`)
Returns:
pd.Timestamp
| align_time | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def align_seg(self, segment: Union[dict, tuple]) -> Union[dict, tuple]:
"""
Align the given date to the trade date
for example:
.. code-block:: python
input: {'train': ('2008-01-01', '2014-12-31'), 'valid': ('2015-01-01', '2016-12-31'), 'test': ('2017-01-01', '2020... |
Align the given date to the trade date
for example:
.. code-block:: python
input: {'train': ('2008-01-01', '2014-12-31'), 'valid': ('2015-01-01', '2016-12-31'), 'test': ('2017-01-01', '2020-08-01')}
output: {'train': (Timestamp('2008-01-02 00:00:00'), Tim... | align_seg | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def truncate(self, segment: tuple, test_start, days: int) -> tuple:
"""
Truncate the segment based on the test_start date
Parameters
----------
segment : tuple
time segment
test_start
days : int
The trading days to be truncated
... |
Truncate the segment based on the test_start date
Parameters
----------
segment : tuple
time segment
test_start
days : int
The trading days to be truncated
the data in this segment may need 'days' data
`days` are based on ... | truncate | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def shift(self, seg: tuple, step: int, rtype=SHIFT_SD) -> tuple:
"""
Shift the datetime of segment
If there are None (which indicates unbounded index) in the segment, this method will return None.
Parameters
----------
seg :
datetime segment
step : i... |
Shift the datetime of segment
If there are None (which indicates unbounded index) in the segment, this method will return None.
Parameters
----------
seg :
datetime segment
step : int
rolling step
rtype : str
rolling type ("s... | shift | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def replace_task_handler_with_cache(task: dict, cache_dir: Union[str, Path] = ".") -> dict:
"""
Replace the handler in task with a cache handler.
It will automatically cache the file and save it in cache_dir.
>>> import qlib
>>> qlib.auto_init()
>>> import datetime
>>> # it is simplified ta... |
Replace the handler in task with a cache handler.
It will automatically cache the file and save it in cache_dir.
>>> import qlib
>>> qlib.auto_init()
>>> import datetime
>>> # it is simplified task
>>> task = {"dataset": {"kwargs":{'handler': {'class': 'Alpha158', 'module_path': 'qlib.cont... | replace_task_handler_with_cache | python | microsoft/qlib | qlib/workflow/task/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/workflow/task/utils.py | MIT |
def __init__(
self,
qlib_dir: str,
csv_path: str,
check_fields: str = None,
freq: str = "day",
symbol_field_name: str = "symbol",
date_field_name: str = "date",
file_suffix: str = ".csv",
max_workers: int = 16,
):
"""
Parameter... |
Parameters
----------
qlib_dir : str
qlib dir
csv_path : str
origin csv path
check_fields : str, optional
check fields, by default None, check qlib_dir/features/<first_dir>/*.<freq>.bin
freq : str, optional
freq, value fro... | __init__ | python | microsoft/qlib | scripts/check_dump_bin.py | https://github.com/microsoft/qlib/blob/master/scripts/check_dump_bin.py | MIT |
def check(self):
"""Check whether the bin file after ``dump_bin.py`` is executed is consistent with the original csv file data"""
logger.info("start check......")
error_list = []
not_in_features = []
compare_false = []
with tqdm(total=len(self.csv_files)) as p_bar:
... | Check whether the bin file after ``dump_bin.py`` is executed is consistent with the original csv file data | check | python | microsoft/qlib | scripts/check_dump_bin.py | https://github.com/microsoft/qlib/blob/master/scripts/check_dump_bin.py | MIT |
def _dump_pit(
self,
file_path: str,
interval: str = "quarterly",
overwrite: bool = False,
):
"""
dump data as the following format:
`/path/to/<field>.data`
[date, period, value, _next]
[date, period, value, _next]
... |
dump data as the following format:
`/path/to/<field>.data`
[date, period, value, _next]
[date, period, value, _next]
[...]
`/path/to/<field>.index`
[first_year, index, index, ...]
`<field.data>` contains the data a... | _dump_pit | python | microsoft/qlib | scripts/dump_pit.py | https://github.com/microsoft/qlib/blob/master/scripts/dump_pit.py | MIT |
def get_data(
self, symbol: str, interval: str, start_datetime: pd.Timestamp, end_datetime: pd.Timestamp
) -> pd.DataFrame:
"""get data with symbol
Parameters
----------
symbol: str
interval: str
value from [1min, 1d]
start_datetime: pd.Timestamp
... | get data with symbol
Parameters
----------
symbol: str
interval: str
value from [1min, 1d]
start_datetime: pd.Timestamp
end_datetime: pd.Timestamp
Returns
---------
pd.DataFrame, "symbol" and "date"in pd.columns
| get_data | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def save_instrument(self, symbol, df: pd.DataFrame):
"""save instrument data to file
Parameters
----------
symbol: str
instrument code
df : pd.DataFrame
df.columns must contain "symbol" and "datetime"
"""
if df is None or df.empty:
... | save instrument data to file
Parameters
----------
symbol: str
instrument code
df : pd.DataFrame
df.columns must contain "symbol" and "datetime"
| save_instrument | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(self, date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs):
"""
Parameters
----------
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, default is symbol
"""
... |
Parameters
----------
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, default is symbol
| __init__ | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(
self,
source_dir: [str, Path],
target_dir: [str, Path],
normalize_class: Type[BaseNormalize],
max_workers: int = 16,
date_field_name: str = "date",
symbol_field_name: str = "symbol",
**kwargs,
):
"""
Parameters
--... |
Parameters
----------
source_dir: str or Path
The directory where the raw data collected from the Internet is saved
target_dir: str or Path
Directory for normalize data
normalize_class: Type[YahooNormalize]
normalize class
max_workers... | __init__ | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(self, source_dir=None, normalize_dir=None, max_workers=1, interval="1d"):
"""
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_dir: str
... |
Parameters
----------
source_dir: str
The directory where the raw data collected from the Internet is saved, default "Path(__file__).parent/source"
normalize_dir: str
Directory for normalize data, default "Path(__file__).parent/normalize"
max_workers: in... | __init__ | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def normalize_data(self, date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs):
"""normalize data
Parameters
----------
date_field_name: str
date field name, default date
symbol_field_name: str
symbol field name, default symbol
... | normalize data
Parameters
----------
date_field_name: str
date field name, default date
symbol_field_name: str
symbol field name, default symbol
Examples
---------
$ python collector.py normalize_data --source_dir ~/.qlib/instrument_d... | normalize_data | python | microsoft/qlib | scripts/data_collector/base.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/base.py | MIT |
def __init__(self, qlib_dir: Union[str, Path], start_date: str = None, end_date: str = None):
"""
Parameters
----------
qlib_dir:
qlib data directory
start_date
start date
end_date
end date
"""
self.qlib_dir = Path(qlib... |
Parameters
----------
qlib_dir:
qlib data directory
start_date
start date
end_date
end date
| __init__ | python | microsoft/qlib | scripts/data_collector/future_calendar_collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/future_calendar_collector.py | MIT |
def run(qlib_dir: Union[str, Path], region: str = "cn", start_date: str = None, end_date: str = None):
"""Collect future calendar(day)
Parameters
----------
qlib_dir:
qlib data directory
region:
cn/CN or us/US
start_date
start date
end_date
end date
Exam... | Collect future calendar(day)
Parameters
----------
qlib_dir:
qlib data directory
region:
cn/CN or us/US
start_date
start date
end_date
end date
Examples
-------
# get cn future calendar
$ python future_calendar_collector.py --qlib_data_1d... | run | python | microsoft/qlib | scripts/data_collector/future_calendar_collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/future_calendar_collector.py | MIT |
def __init__(
self,
index_name: str,
qlib_dir: [str, Path] = None,
freq: str = "day",
request_retry: int = 5,
retry_sleep: int = 3,
):
"""
Parameters
----------
index_name: str
index name
qlib_dir: str
q... |
Parameters
----------
index_name: str
index name
qlib_dir: str
qlib directory, by default Path(__file__).resolve().parent.joinpath("qlib_data")
freq: str
freq, value from ["day", "1min"]
request_retry: int
request retry, b... | __init__ | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def save_new_companies(self):
"""save new companies
Examples
-------
$ python collector.py save_new_companies --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
"""
df = self.get_new_companies()
if df is None or df.empty:
raise ValueError(f"... | save new companies
Examples
-------
$ python collector.py save_new_companies --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
| save_new_companies | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def get_changes_with_history_companies(self, history_companies: pd.DataFrame) -> pd.DataFrame:
"""get changes with history companies
Parameters
----------
history_companies : pd.DataFrame
symbol date
SH600000 2020-11-11
dtypes:
... | get changes with history companies
Parameters
----------
history_companies : pd.DataFrame
symbol date
SH600000 2020-11-11
dtypes:
symbol: str
date: pd.Timestamp
Return
--------
pd.DataFram... | get_changes_with_history_companies | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def parse_instruments(self):
"""parse instruments, eg: csi300.txt
Examples
-------
$ python collector.py parse_instruments --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
"""
logger.info(f"start parse {self.index_name.lower()} companies.....")
instru... | parse instruments, eg: csi300.txt
Examples
-------
$ python collector.py parse_instruments --index_name CSI300 --qlib_dir ~/.qlib/qlib_data/cn_data
| parse_instruments | python | microsoft/qlib | scripts/data_collector/index.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/index.py | MIT |
def get_calendar_list(bench_code="CSI300") -> List[pd.Timestamp]:
"""get SH/SZ history calendar list
Parameters
----------
bench_code: str
value from ["CSI300", "CSI500", "ALL", "US_ALL"]
Returns
-------
history calendar list
"""
logger.info(f"get calendar list: {bench... | get SH/SZ history calendar list
Parameters
----------
bench_code: str
value from ["CSI300", "CSI500", "ALL", "US_ALL"]
Returns
-------
history calendar list
| get_calendar_list | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_calendar_list_by_ratio(
source_dir: [str, Path],
date_field_name: str = "date",
threshold: float = 0.5,
minimum_count: int = 10,
max_workers: int = 16,
) -> list:
"""get calendar list by selecting the date when few funds trade in this day
Parameters
----------
source_dir: st... | get calendar list by selecting the date when few funds trade in this day
Parameters
----------
source_dir: str or Path
The directory where the raw data collected from the Internet is saved
date_field_name: str
date field name, default is date
threshold: float
threshold t... | get_calendar_list_by_ratio | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_hs_stock_symbols() -> list:
"""get SH/SZ stock symbols
Returns
-------
stock symbols
"""
global _HS_SYMBOLS # pylint: disable=W0603
def _get_symbol():
"""
Get the stock pool from a web page and process it into the format required by yahooquery.
Format o... | get SH/SZ stock symbols
Returns
-------
stock symbols
| get_hs_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def _get_symbol():
"""
Get the stock pool from a web page and process it into the format required by yahooquery.
Format of data retrieved from the web page: 600519, 000001
The data format required by yahooquery: 600519.ss, 000001.sz
Returns
-------
set: Retur... |
Get the stock pool from a web page and process it into the format required by yahooquery.
Format of data retrieved from the web page: 600519, 000001
The data format required by yahooquery: 600519.ss, 000001.sz
Returns
-------
set: Returns the set of symbol codes.
... | _get_symbol | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_us_stock_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get US stock symbols
Returns
-------
stock symbols
"""
global _US_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_eastmoney():
url = "http://4.push2.eastmoney.com/api/qt/clist/get?pn=1&pz=10000&f... | get US stock symbols
Returns
-------
stock symbols
| get_us_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_in_stock_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get IN stock symbols
Returns
-------
stock symbols
"""
global _IN_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_nifty():
url = f"https://www1.nseindia.com/content/equities/EQUITY_L.csv"
... | get IN stock symbols
Returns
-------
stock symbols
| get_in_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_br_stock_symbols(qlib_data_path: [str, Path] = None) -> list:
"""get Brazil(B3) stock symbols
Returns
-------
B3 stock symbols
"""
global _BR_SYMBOLS # pylint: disable=W0603
@deco_retry
def _get_ibovespa():
_symbols = []
url = "https://www.fundamentus.com.b... | get Brazil(B3) stock symbols
Returns
-------
B3 stock symbols
| get_br_stock_symbols | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def symbol_suffix_to_prefix(symbol: str, capital: bool = True) -> str:
"""symbol suffix to prefix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
"""
code, exchange = symbol.split(".")
if exchange.lower() in ["sh", "ss"]:
... | symbol suffix to prefix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
| symbol_suffix_to_prefix | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def symbol_prefix_to_sufix(symbol: str, capital: bool = True) -> str:
"""symbol prefix to sufix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
"""
res = f"{symbol[:-2]}.{symbol[-2:]}"
return res.upper() if capital else re... | symbol prefix to sufix
Parameters
----------
symbol: str
symbol
capital : bool
by default True
Returns
-------
| symbol_prefix_to_sufix | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_trading_date_by_shift(trading_list: list, trading_date: pd.Timestamp, shift: int = 1):
"""get trading date by shift
Parameters
----------
trading_list: list
trading calendar list
shift : int
shift, default is 1
trading_date : pd.Timestamp
trading date
Return... | get trading date by shift
Parameters
----------
trading_list: list
trading calendar list
shift : int
shift, default is 1
trading_date : pd.Timestamp
trading date
Returns
-------
| get_trading_date_by_shift | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def generate_minutes_calendar_from_daily(
calendars: Iterable,
freq: str = "1min",
am_range: Tuple[str, str] = ("09:30:00", "11:29:00"),
pm_range: Tuple[str, str] = ("13:00:00", "14:59:00"),
) -> pd.Index:
"""generate minutes calendar
Parameters
----------
calendars: Iterable
da... | generate minutes calendar
Parameters
----------
calendars: Iterable
daily calendar
freq: str
by default 1min
am_range: Tuple[str, str]
AM Time Range, by default China-Stock: ("09:30:00", "11:29:00")
pm_range: Tuple[str, str]
PM Time Range, by default China-Stock:... | generate_minutes_calendar_from_daily | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_instruments(
qlib_dir: str,
index_name: str,
method: str = "parse_instruments",
freq: str = "day",
request_retry: int = 5,
retry_sleep: int = 3,
market_index: str = "cn_index",
):
"""
Parameters
----------
qlib_dir: str
qlib data dir, default "Path(__file__).... |
Parameters
----------
qlib_dir: str
qlib data dir, default "Path(__file__).parent/qlib_data"
index_name: str
index name, value from ["csi100", "csi300"]
method: str
method, value from ["parse_instruments", "save_new_companies"]
freq: str
freq, value from ["day",... | get_instruments | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def get_1d_data(
_date_field_name: str,
_symbol_field_name: str,
symbol: str,
start: str,
end: str,
_1d_data_all: pd.DataFrame,
) -> pd.DataFrame:
"""get 1d data
Returns
------
data_1d: pd.DataFrame
data_1d.columns = [_date_field_name, _symbol_field_name, "paused... | get 1d data
Returns
------
data_1d: pd.DataFrame
data_1d.columns = [_date_field_name, _symbol_field_name, "paused", "volume", "factor", "close"]
| get_1d_data | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def calc_adjusted_price(
df: pd.DataFrame,
_1d_data_all: pd.DataFrame,
_date_field_name: str,
_symbol_field_name: str,
frequence: str,
consistent_1d: bool = True,
calc_paused: bool = True,
) -> pd.DataFrame:
"""calc adjusted price
This method does 4 things.
1. Adds the `paused` f... | calc adjusted price
This method does 4 things.
1. Adds the `paused` field.
- The added paused field comes from the paused field of the 1d data.
2. Aligns the time of the 1d data.
3. The data is reweighted.
- The reweighting method:
- volume / factor
- open * facto... | calc_adjusted_price | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def calc_paused_num(df: pd.DataFrame, _date_field_name, _symbol_field_name):
"""calc paused num
This method adds the paused_num field
- The `paused_num` is the number of consecutive days of trading suspension.
"""
_symbol = df.iloc[0][_symbol_field_name]
df = df.copy()
df["_tmp_date"] = ... | calc paused num
This method adds the paused_num field
- The `paused_num` is the number of consecutive days of trading suspension.
| calc_paused_num | python | microsoft/qlib | scripts/data_collector/utils.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/utils.py | MIT |
def __init__(
self, qlib_data_1d_dir: [str, Path], date_field_name: str = "date", symbol_field_name: str = "symbol", **kwargs
):
"""
Parameters
----------
qlib_data_1d_dir: str, Path
the qlib data to be updated for yahoo, usually from: Normalised to 5min using lo... |
Parameters
----------
qlib_data_1d_dir: str, Path
the qlib data to be updated for yahoo, usually from: Normalised to 5min using local 1d data
date_field_name: str
date field name, default is date
symbol_field_name: str
symbol field name, defa... | __init__ | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def __init__(self, source_dir=None, normalize_dir=None, max_workers=1, interval="5min", region="HS300"):
"""
Changed the default value of: scripts.data_collector.base.BaseRun.
"""
super().__init__(source_dir, normalize_dir, max_workers, interval)
self.region = region |
Changed the default value of: scripts.data_collector.base.BaseRun.
| __init__ | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def download_data(
self,
max_collector_count=2,
delay=0.5,
start=None,
end=None,
check_data_length=None,
limit_nums=None,
):
"""download data from Baostock
Notes
-----
check_data_length, example:
hs300 5min,... | download data from Baostock
Notes
-----
check_data_length, example:
hs300 5min, a week: 4 * 60 * 5
Examples
---------
# get hs300 5min data
$ python collector.py download_data --source_dir ~/.qlib/stock_data/source/hs300_5min_original... | download_data | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def normalize_data(
self,
date_field_name: str = "date",
symbol_field_name: str = "symbol",
end_date: str = None,
qlib_data_1d_dir: str = None,
):
"""normalize data
Attention
---------
qlib_data_1d_dir cannot be None, normalize 5min needs to u... | normalize data
Attention
---------
qlib_data_1d_dir cannot be None, normalize 5min needs to use 1d data;
qlib_data_1d can be obtained like this:
$ python scripts/get_data.py qlib_data --target_dir ~/.qlib/qlib_data/cn_data --interval 1d --region cn --version v3
... | normalize_data | python | microsoft/qlib | scripts/data_collector/baostock_5min/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/baostock_5min/collector.py | MIT |
def get_current_4_month_period(self, current_month: int):
"""
This function is used to calculated what is the current
four month period for the current month. For example,
If the current month is August 8, its four month period
is 2Q.
OBS: In english Q is used to represe... |
This function is used to calculated what is the current
four month period for the current month. For example,
If the current month is August 8, its four month period
is 2Q.
OBS: In english Q is used to represent *quarter*
which means a three month period. However, in
... | get_current_4_month_period | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def get_four_month_period(self):
"""
The ibovespa index is updated every four months.
Therefore, we will represent each time period as 2003_1Q
which means 2003 first four mount period (Jan, Feb, Mar, Apr)
"""
four_months_period = ["1Q", "2Q", "3Q"]
init_year = 200... |
The ibovespa index is updated every four months.
Therefore, we will represent each time period as 2003_1Q
which means 2003 first four mount period (Jan, Feb, Mar, Apr)
| get_four_month_period | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def format_datetime(self, inst_df: pd.DataFrame) -> pd.DataFrame:
"""formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
... | formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
inst_df: pd.DataFrame
| format_datetime | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def format_quarter(self, cell: str):
"""
Parameters
----------
cell: str
It must be on the format 2003_1Q --> years_4_month_periods
Returns
----------
date: str
Returns date in format 2003-03-01
"""
cell_split = cell.split(... |
Parameters
----------
cell: str
It must be on the format 2003_1Q --> years_4_month_periods
Returns
----------
date: str
Returns date in format 2003-03-01
| format_quarter | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def get_changes(self):
"""
Access the index historic composition and compare it quarter
by quarter and year by year in order to generate a file that
keeps track of which stocks have been removed and which have
been added.
The Dataframe used as reference will provided the... |
Access the index historic composition and compare it quarter
by quarter and year by year in order to generate a file that
keeps track of which stocks have been removed and which have
been added.
The Dataframe used as reference will provided the index
composition for eac... | get_changes | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def get_new_companies(self):
"""
Get latest index composition.
The repo indicated on README has implemented a script
to get the latest index composition from B3 website using
selenium. Therefore, this method will download the file
containing such composition
Para... |
Get latest index composition.
The repo indicated on README has implemented a script
to get the latest index composition from B3 website using
selenium. Therefore, this method will download the file
containing such composition
Parameters
----------
self: ... | get_new_companies | python | microsoft/qlib | scripts/data_collector/br_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/br_index/collector.py | MIT |
def calendar_list(self) -> List[pd.Timestamp]:
"""get history trading date
Returns
-------
calendar list
"""
_calendar = getattr(self, "_calendar_list", None)
if not _calendar:
_calendar = get_calendar_list(bench_code=self.index_name.upper())
... | get history trading date
Returns
-------
calendar list
| calendar_list | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def format_datetime(self, inst_df: pd.DataFrame) -> pd.DataFrame:
"""formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
... | formatting the datetime in an instrument
Parameters
----------
inst_df: pd.DataFrame
inst_df.columns = [self.SYMBOL_FIELD_NAME, self.START_DATE_FIELD, self.END_DATE_FIELD]
Returns
-------
| format_datetime | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
def get_changes(self) -> pd.DataFrame:
"""get companies changes
Returns
-------
pd.DataFrame:
symbol date type
SH600000 2019-11-11 add
SH600000 2020-11-10 remove
dtypes:
symbol: str
... | get companies changes
Returns
-------
pd.DataFrame:
symbol date type
SH600000 2019-11-11 add
SH600000 2020-11-10 remove
dtypes:
symbol: str
date: pd.Timestamp
type... | get_changes | python | microsoft/qlib | scripts/data_collector/cn_index/collector.py | https://github.com/microsoft/qlib/blob/master/scripts/data_collector/cn_index/collector.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.