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 fetch(
self,
selector: Union[pd.Timestamp, slice, str] = slice(None, None),
level: Union[str, int] = "datetime",
col_set=DataHandler.CS_ALL,
data_key: DATA_KEY_TYPE = DK_I,
squeeze: bool = False,
proc_func: Callable = None,
) -> pd.DataFrame:
"""
... |
fetch data from underlying data source
Parameters
----------
selector : Union[pd.Timestamp, slice, str]
describe how to select data by index.
level : Union[str, int]
which index level to select the data.
col_set : str
select a set of ... | fetch | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def get_cols(self, col_set=DataHandler.CS_ALL, data_key: DATA_KEY_TYPE = DK_I) -> list:
"""
get the column names
Parameters
----------
col_set : str
select a set of meaningful columns.(e.g. features, columns).
data_key : DATA_KEY_TYPE
the data to ... |
get the column names
Parameters
----------
col_set : str
select a set of meaningful columns.(e.g. features, columns).
data_key : DATA_KEY_TYPE
the data to fetch: DK_*.
Returns
-------
list:
list of column names
... | get_cols | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def cast(cls, handler: "DataHandlerLP") -> "DataHandlerLP":
"""
Motivation
- A user creates a datahandler in his customized package. Then he wants to share the processed handler to
other users without introduce the package dependency and complicated data processing logic.
- Th... |
Motivation
- A user creates a datahandler in his customized package. Then he wants to share the processed handler to
other users without introduce the package dependency and complicated data processing logic.
- This class make it possible by casting the class to DataHandlerLP and onl... | cast | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def load(self, instruments, start_time=None, end_time=None) -> pd.DataFrame:
"""
load the data as pd.DataFrame.
Example of the data (The multi-index of the columns is optional.):
.. code-block:: text
feature ... |
load the data as pd.DataFrame.
Example of the data (The multi-index of the columns is optional.):
.. code-block:: text
feature label
$close $vol... | load | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def __init__(self, config: Union[list, tuple, dict]):
"""
Parameters
----------
config : Union[list, tuple, dict]
Config will be used to describe the fields and column names
.. code-block::
<config> := {
"group_name1": <fields... |
Parameters
----------
config : Union[list, tuple, dict]
Config will be used to describe the fields and column names
.. code-block::
<config> := {
"group_name1": <fields_info1>
"group_name2": <fields_info2>
... | __init__ | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def load_group_df(
self,
instruments,
exprs: list,
names: list,
start_time: Union[str, pd.Timestamp] = None,
end_time: Union[str, pd.Timestamp] = None,
gp_name: str = None,
) -> pd.DataFrame:
"""
load the dataframe for specific group
P... |
load the dataframe for specific group
Parameters
----------
instruments :
the instruments.
exprs : list
the expressions to describe the content of the data.
names : list
the name of the data.
Returns
-------
p... | load_group_df | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def __init__(
self,
config: Tuple[list, tuple, dict],
filter_pipe: List = None,
swap_level: bool = True,
freq: Union[str, dict] = "day",
inst_processors: Union[dict, list] = None,
):
"""
Parameters
----------
config : Tuple[list, tuple,... |
Parameters
----------
config : Tuple[list, tuple, dict]
Please refer to the doc of DLWParser
filter_pipe :
Filter pipe for the instruments
swap_level :
Whether to swap level of MultiIndex
freq: dict or str
If type(config) ... | __init__ | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def __init__(self, config: Union[dict, str, pd.DataFrame], join="outer"):
"""
Parameters
----------
config : dict
{fields_group: <path or object>}
join : str
How to align different dataframes
"""
self._config = config # using "_" to avoid ... |
Parameters
----------
config : dict
{fields_group: <path or object>}
join : str
How to align different dataframes
| __init__ | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def __init__(self, dataloader_l: List[Dict], join="left") -> None:
"""
Parameters
----------
dataloader_l : list[dict]
A list of dataloader, for exmaple
.. code-block:: python
nd = NestedDataLoader(
dataloader_l=[
... |
Parameters
----------
dataloader_l : list[dict]
A list of dataloader, for exmaple
.. code-block:: python
nd = NestedDataLoader(
dataloader_l=[
{
"class": "qlib.contrib.data.loader.... | __init__ | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def __init__(self, handler_config: dict, fetch_kwargs: dict = {}, is_group=False):
"""
Parameters
----------
handler_config : dict
handler_config will be used to describe the handlers
.. code-block::
<handler_config> := {
"gro... |
Parameters
----------
handler_config : dict
handler_config will be used to describe the handlers
.. code-block::
<handler_config> := {
"group_name1": <handler>
"group_name2": <handler>
}
... | __init__ | python | microsoft/qlib | qlib/data/dataset/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/loader.py | MIT |
def get_group_columns(df: pd.DataFrame, group: Union[Text, None]):
"""
get a group of columns from multi-index columns DataFrame
Parameters
----------
df : pd.DataFrame
with multi of columns.
group : str
the name of the feature group, i.e. the first level value of the group inde... |
get a group of columns from multi-index columns DataFrame
Parameters
----------
df : pd.DataFrame
with multi of columns.
group : str
the name of the feature group, i.e. the first level value of the group index.
| get_group_columns | python | microsoft/qlib | qlib/data/dataset/processor.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/processor.py | MIT |
def fit(self, df: pd.DataFrame = None):
"""
learn data processing parameters
Parameters
----------
df : pd.DataFrame
When we fit and process data with processor one by one. The fit function reiles on the output of previous
processor, i.e. `df`.
"... |
learn data processing parameters
Parameters
----------
df : pd.DataFrame
When we fit and process data with processor one by one. The fit function reiles on the output of previous
processor, i.e. `df`.
| fit | python | microsoft/qlib | qlib/data/dataset/processor.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/processor.py | MIT |
def __call__(self, df: pd.DataFrame):
"""
process the data
NOTE: **The processor could change the content of `df` inplace !!!!! **
User should keep a copy of data outside
Parameters
----------
df : pd.DataFrame
The raw_df of handler or result from pr... |
process the data
NOTE: **The processor could change the content of `df` inplace !!!!! **
User should keep a copy of data outside
Parameters
----------
df : pd.DataFrame
The raw_df of handler or result from previous processor.
| __call__ | python | microsoft/qlib | qlib/data/dataset/processor.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/processor.py | MIT |
def __init__(
self,
start_time: Optional[Union[pd.Timestamp, str]] = None,
end_time: Optional[Union[pd.Timestamp, str]] = None,
freq: str = "day",
):
"""
Parameters
----------
start_time : Optional[Union[pd.Timestamp, str]]
The data must st... |
Parameters
----------
start_time : Optional[Union[pd.Timestamp, str]]
The data must start earlier (or equal) than `start_time`
None indicates data will not be filtered based on `start_time`
end_time : Optional[Union[pd.Timestamp, str]]
similar to star... | __init__ | python | microsoft/qlib | qlib/data/dataset/processor.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/processor.py | MIT |
def fetch(
self,
selector: Union[pd.Timestamp, slice, str, list] = slice(None, None),
level: Union[str, int] = "datetime",
col_set: Union[str, List[str]] = DataHandler.CS_ALL,
fetch_orig: bool = True,
proc_func: Callable = None,
**kwargs,
) -> pd.DataFrame:
... | fetch data from the data storage
Parameters
----------
selector : Union[pd.Timestamp, slice, str]
describe how to select data by index
level : Union[str, int]
which index level to select the data
- if level is None, apply selector to df directly
... | fetch | python | microsoft/qlib | qlib/data/dataset/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/storage.py | MIT |
def _fetch_hash_df_by_stock(self, selector, level):
"""fetch the data with stock selector
Parameters
----------
selector : Union[pd.Timestamp, slice, str]
describe how to select data by index
level : Union[str, int]
which index level to select the data
... | fetch the data with stock selector
Parameters
----------
selector : Union[pd.Timestamp, slice, str]
describe how to select data by index
level : Union[str, int]
which index level to select the data
- if level is None, apply selector to df directly
... | _fetch_hash_df_by_stock | python | microsoft/qlib | qlib/data/dataset/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/storage.py | MIT |
def get_level_index(df: pd.DataFrame, level: Union[str, int]) -> int:
"""
get the level index of `df` given `level`
Parameters
----------
df : pd.DataFrame
data
level : Union[str, int]
index level
Returns
-------
int:
The level index in the multiple index
... |
get the level index of `df` given `level`
Parameters
----------
df : pd.DataFrame
data
level : Union[str, int]
index level
Returns
-------
int:
The level index in the multiple index
| get_level_index | python | microsoft/qlib | qlib/data/dataset/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/utils.py | MIT |
def fetch_df_by_index(
df: pd.DataFrame,
selector: Union[pd.Timestamp, slice, str, list, pd.Index],
level: Union[str, int],
fetch_orig=True,
) -> pd.DataFrame:
"""
fetch data from `data` with `selector` and `level`
selector are assumed to be well processed.
`fetch_df_by_index` is only r... |
fetch data from `data` with `selector` and `level`
selector are assumed to be well processed.
`fetch_df_by_index` is only responsible for get the right level
Parameters
----------
selector : Union[pd.Timestamp, slice, str, list]
selector
level : Union[int, str]
the level t... | fetch_df_by_index | python | microsoft/qlib | qlib/data/dataset/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/utils.py | MIT |
def convert_index_format(df: Union[pd.DataFrame, pd.Series], level: str = "datetime") -> Union[pd.DataFrame, pd.Series]:
"""
Convert the format of df.MultiIndex according to the following rules:
- If `level` is the first level of df.MultiIndex, do nothing
- If `level` is the second level of df.M... |
Convert the format of df.MultiIndex according to the following rules:
- If `level` is the first level of df.MultiIndex, do nothing
- If `level` is the second level of df.MultiIndex, swap the level of index.
NOTE:
the number of levels of df.MultiIndex should be 2
Parameters
---... | convert_index_format | python | microsoft/qlib | qlib/data/dataset/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/utils.py | MIT |
def init_task_handler(task: dict) -> DataHandler:
"""
initialize the handler part of the task **inplace**
Parameters
----------
task : dict
the task to be handled
Returns
-------
Union[DataHandler, None]:
returns
"""
# avoid recursive import
from .handler im... |
initialize the handler part of the task **inplace**
Parameters
----------
task : dict
the task to be handled
Returns
-------
Union[DataHandler, None]:
returns
| init_task_handler | python | microsoft/qlib | qlib/data/dataset/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/utils.py | MIT |
def setup_data(self, **kwargs):
"""
Setup the data.
We split the setup_data function for following situation:
- User have a Dataset object with learned status on disk.
- User load the Dataset object from the disk.
- User call `setup_data` to load new data.
- ... |
Setup the data.
We split the setup_data function for following situation:
- User have a Dataset object with learned status on disk.
- User load the Dataset object from the disk.
- User call `setup_data` to load new data.
- User prepare data for model based on previo... | setup_data | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def prepare(self, **kwargs) -> object:
"""
The type of dataset depends on the model. (It could be pd.DataFrame, pytorch.DataLoader, etc.)
The parameters should specify the scope for the prepared data
The method should:
- process the data
- return the processed data
... |
The type of dataset depends on the model. (It could be pd.DataFrame, pytorch.DataLoader, etc.)
The parameters should specify the scope for the prepared data
The method should:
- process the data
- return the processed data
Returns
-------
object:
... | prepare | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def __init__(
self,
handler: Union[Dict, DataHandler],
segments: Dict[Text, Tuple],
fetch_kwargs: Dict = {},
**kwargs,
):
"""
Setup the underlying data.
Parameters
----------
handler : Union[dict, DataHandler]
handler could... |
Setup the underlying data.
Parameters
----------
handler : Union[dict, DataHandler]
handler could be:
- instance of `DataHandler`
- config of `DataHandler`. Please refer to `DataHandler`
segments : dict
Describe the options to... | __init__ | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def config(self, handler_kwargs: dict = None, **kwargs):
"""
Initialize the DatasetH
Parameters
----------
handler_kwargs : dict
Config of DataHandler, which could include the following arguments:
- arguments of DataHandler.conf_data, such as 'instrument... |
Initialize the DatasetH
Parameters
----------
handler_kwargs : dict
Config of DataHandler, which could include the following arguments:
- arguments of DataHandler.conf_data, such as 'instruments', 'start_time' and 'end_time'.
kwargs : dict
... | config | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def setup_data(self, handler_kwargs: dict = None, **kwargs):
"""
Setup the Data
Parameters
----------
handler_kwargs : dict
init arguments of DataHandler, which could include the following arguments:
- init_type : Init Type of Handler
- enab... |
Setup the Data
Parameters
----------
handler_kwargs : dict
init arguments of DataHandler, which could include the following arguments:
- init_type : Init Type of Handler
- enable_cache : whether to enable cache
| setup_data | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def _prepare_seg(self, slc, **kwargs):
"""
Give a query, retrieve the according data
Parameters
----------
slc : please refer to the docs of `prepare`
NOTE: it may not be an instance of slice. It may be a segment of `segments` from `def prepare`
"""
... |
Give a query, retrieve the according data
Parameters
----------
slc : please refer to the docs of `prepare`
NOTE: it may not be an instance of slice. It may be a segment of `segments` from `def prepare`
| _prepare_seg | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def prepare(
self,
segments: Union[List[Text], Tuple[Text], Text, slice, pd.Index],
col_set=DataHandler.CS_ALL,
data_key=DataHandlerLP.DK_I,
**kwargs,
) -> Union[List[pd.DataFrame], pd.DataFrame]:
"""
Prepare the data for learning and inference.
Param... |
Prepare the data for learning and inference.
Parameters
----------
segments : Union[List[Text], Tuple[Text], Text, slice]
Describe the scope of the data to be prepared
Here are some examples:
- 'train'
- ['train', 'valid']
col_... | prepare | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def _get_extrema(segments, idx: int, cmp: Callable, key_func=pd.Timestamp):
"""it will act like sort and return the max value or None"""
candidate = None
for k, seg in segments.items():
point = seg[idx]
if point is None:
# None indicates unbounded, return ... | it will act like sort and return the max value or None | _get_extrema | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def __init__(
self,
data: pd.DataFrame,
start,
end,
step_len: int,
fillna_type: str = "none",
dtype=None,
flt_data=None,
):
"""
Build a dataset which looks like torch.data.utils.Dataset.
Parameters
----------
da... |
Build a dataset which looks like torch.data.utils.Dataset.
Parameters
----------
data : pd.DataFrame
The raw tabular data whose index order is <"datetime", "instrument">
start :
The indexable start time
end :
The indexable end time
... | __init__ | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def build_index(data: pd.DataFrame) -> Tuple[pd.DataFrame, dict]:
"""
The relation of the data
Parameters
----------
data : pd.DataFrame
A DataFrame with index in order <instrument, datetime>
RSQR5 RESI5 WVMA5 LABEL0
... |
The relation of the data
Parameters
----------
data : pd.DataFrame
A DataFrame with index in order <instrument, datetime>
RSQR5 RESI5 WVMA5 LABEL0
instrument datetime
SH600000 2017-01-03 0.016389 ... | build_index | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def _get_indices(self, row: int, col: int) -> np.array:
"""
get series indices of self.data_arr from the row, col indices of self.idx_df
Parameters
----------
row : int
the row in self.idx_df
col : int
the col in self.idx_df
Returns
... |
get series indices of self.data_arr from the row, col indices of self.idx_df
Parameters
----------
row : int
the row in self.idx_df
col : int
the col in self.idx_df
Returns
-------
np.array:
The indices of data of the... | _get_indices | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def _get_row_col(self, idx) -> Tuple[int]:
"""
get the col index and row index of a given sample index in self.idx_df
Parameters
----------
idx :
the input of `__getitem__`
Returns
-------
Tuple[int]:
the row and col index
... |
get the col index and row index of a given sample index in self.idx_df
Parameters
----------
idx :
the input of `__getitem__`
Returns
-------
Tuple[int]:
the row and col index
| _get_row_col | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def __getitem__(self, idx: Union[int, Tuple[object, str], List[int]]):
"""
# We have two method to get the time-series of a sample
tsds is a instance of TSDataSampler
# 1) sample by int index directly
tsds[len(tsds) - 1]
# 2) sample by <datetime,instrument> index
... |
# We have two method to get the time-series of a sample
tsds is a instance of TSDataSampler
# 1) sample by int index directly
tsds[len(tsds) - 1]
# 2) sample by <datetime,instrument> index
tsds['2016-12-31', "SZ300315"]
# The return value will be similar to th... | __getitem__ | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def _prepare_seg(self, slc: slice, **kwargs) -> TSDataSampler:
"""
split the _prepare_raw_seg is to leave a hook for data preprocessing before creating processing data
NOTE: TSDatasetH only support slc segment on datetime !!!
"""
dtype = kwargs.pop("dtype", None)
if not i... |
split the _prepare_raw_seg is to leave a hook for data preprocessing before creating processing data
NOTE: TSDatasetH only support slc segment on datetime !!!
| _prepare_seg | python | microsoft/qlib | qlib/data/dataset/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/__init__.py | MIT |
def _freq_file(self) -> str:
"""the freq to read from file"""
if not hasattr(self, "_freq_file_cache"):
freq = Freq(self.freq)
if freq not in self.support_freq:
# NOTE: uri
# 1. If `uri` does not exist
# - Get the `min_uri` ... | the freq to read from file | _freq_file | python | microsoft/qlib | qlib/data/storage/file_storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/storage/file_storage.py | MIT |
def __delitem__(self, i) -> None:
"""
Raises
------
ValueError
If the data(storage) does not exist, raise ValueError
"""
raise NotImplementedError(
"Subclass of CalendarStorage must implement `__delitem__(i: int)`/`__delitem__(s: slice)` method"
... |
Raises
------
ValueError
If the data(storage) does not exist, raise ValueError
| __delitem__ | python | microsoft/qlib | qlib/data/storage/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/storage/storage.py | MIT |
def __getitem__(self, i) -> CalVT:
"""
Raises
------
ValueError
If the data(storage) does not exist, raise ValueError
"""
raise NotImplementedError(
"Subclass of CalendarStorage must implement `__getitem__(i: int)`/`__getitem__(s: slice)` method... |
Raises
------
ValueError
If the data(storage) does not exist, raise ValueError
| __getitem__ | python | microsoft/qlib | qlib/data/storage/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/storage/storage.py | MIT |
def rebase(self, start_index: int = None, end_index: int = None):
"""Rebase the start_index and end_index of the FeatureStorage.
start_index and end_index are closed intervals: [start_index, end_index]
Examples
---------
.. code-block::
feature:
... | Rebase the start_index and end_index of the FeatureStorage.
start_index and end_index are closed intervals: [start_index, end_index]
Examples
---------
.. code-block::
feature:
3 4
4 5
... | rebase | python | microsoft/qlib | qlib/data/storage/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/storage/storage.py | MIT |
def __getitem__(self, s: slice) -> pd.Series:
"""x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step]
Returns
-------
pd.Series(values, index=pd.RangeIndex(start, len(values))
""" | x.__getitem__(slice(start: int, stop: int, step: int)) <==> x[start:stop:step]
Returns
-------
pd.Series(values, index=pd.RangeIndex(start, len(values))
| __getitem__ | python | microsoft/qlib | qlib/data/storage/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/storage/storage.py | MIT |
def __getitem__(self, i) -> Union[Tuple[int, float], pd.Series]:
"""x.__getitem__(y) <==> x[y]
Notes
-------
if data(storage) does not exist:
if isinstance(i, int):
return (None, None)
if isinstance(i, slice):
# return empty pd.Se... | x.__getitem__(y) <==> x[y]
Notes
-------
if data(storage) does not exist:
if isinstance(i, int):
return (None, None)
if isinstance(i, slice):
# return empty pd.Series
return pd.Series(dtype=np.float32)
| __getitem__ | python | microsoft/qlib | qlib/data/storage/storage.py | https://github.com/microsoft/qlib/blob/master/qlib/data/storage/storage.py | MIT |
def begin_task_train(task_config: dict, experiment_name: str, recorder_name: str = None) -> Recorder:
"""
Begin task training to start a recorder and save the task config.
Args:
task_config (dict): the config of a task
experiment_name (str): the name of experiment
recorder_name (str... |
Begin task training to start a recorder and save the task config.
Args:
task_config (dict): the config of a task
experiment_name (str): the name of experiment
recorder_name (str): the given name will be the recorder name. None for using rid.
Returns:
Recorder: the model re... | begin_task_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def end_task_train(rec: Recorder, experiment_name: str) -> Recorder:
"""
Finish task training with real model fitting and saving.
Args:
rec (Recorder): the recorder will be resumed
experiment_name (str): the name of experiment
Returns:
Recorder: the model recorder
"""
w... |
Finish task training with real model fitting and saving.
Args:
rec (Recorder): the recorder will be resumed
experiment_name (str): the name of experiment
Returns:
Recorder: the model recorder
| end_task_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def task_train(task_config: dict, experiment_name: str, recorder_name: str = None) -> Recorder:
"""
Task based training, will be divided into two steps.
Parameters
----------
task_config : dict
The config of a task.
experiment_name: str
The name of experiment
recorder_name: ... |
Task based training, will be divided into two steps.
Parameters
----------
task_config : dict
The config of a task.
experiment_name: str
The name of experiment
recorder_name: str
The name of recorder
Returns
----------
Recorder: The instance of the recorder... | task_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def __init__(
self,
experiment_name: Optional[str] = None,
train_func: Callable = task_train,
call_in_subproc: bool = False,
default_rec_name: Optional[str] = None,
):
"""
Init TrainerR.
Args:
experiment_name (str, optional): the default n... |
Init TrainerR.
Args:
experiment_name (str, optional): the default name of experiment.
train_func (Callable, optional): default training method. Defaults to `task_train`.
call_in_subproc (bool): call the process in subprocess to force memory release
| __init__ | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def train(self, tasks: list, train_func: Callable = None, experiment_name: str = None, **kwargs) -> List[Recorder]:
"""
Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed.
Args:
tasks (list): a list of definitions based on `task` dict
... |
Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed.
Args:
tasks (list): a list of definitions based on `task` dict
train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default trainin... | train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def end_train(self, models: list, **kwargs) -> List[Recorder]:
"""
Set STATUS_END tag to the recorders.
Args:
models (list): a list of trained recorders.
Returns:
List[Recorder]: the same list as the param.
"""
if isinstance(models, Recorder):
... |
Set STATUS_END tag to the recorders.
Args:
models (list): a list of trained recorders.
Returns:
List[Recorder]: the same list as the param.
| end_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def __init__(
self, experiment_name: str = None, train_func=begin_task_train, end_train_func=end_task_train, **kwargs
):
"""
Init TrainerRM.
Args:
experiment_name (str): the default name of experiment.
train_func (Callable, optional): default train method. De... |
Init TrainerRM.
Args:
experiment_name (str): the default name of experiment.
train_func (Callable, optional): default train method. Defaults to `begin_task_train`.
end_train_func (Callable, optional): default end_train method. Defaults to `end_task_train`.
| __init__ | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def end_train(self, models, end_train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]:
"""
Given a list of Recorder and return a list of trained Recorder.
This class will finish real data loading and model fitting.
Args:
models (list): a list of Recorder,... |
Given a list of Recorder and return a list of trained Recorder.
This class will finish real data loading and model fitting.
Args:
models (list): a list of Recorder, the tasks have been saved to them
end_train_func (Callable, optional): the end_train method which needs a... | end_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def __init__(
self,
experiment_name: str = None,
task_pool: str = None,
train_func=task_train,
skip_run_task: bool = False,
default_rec_name: Optional[str] = None,
):
"""
Init TrainerR.
Args:
experiment_name (str): the default name... |
Init TrainerR.
Args:
experiment_name (str): the default name of experiment.
task_pool (str): task pool name in TaskManager. None for use same name as experiment_name.
train_func (Callable, optional): default training method. Defaults to `task_train`.
ski... | __init__ | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def train(
self,
tasks: list,
train_func: Callable = None,
experiment_name: str = None,
before_status: str = TaskManager.STATUS_WAITING,
after_status: str = TaskManager.STATUS_DONE,
default_rec_name: Optional[str] = None,
**kwargs,
) -> List[Recorder]:... |
Given a list of `tasks` and return a list of trained Recorder. The order can be guaranteed.
This method defaults to a single process, but TaskManager offered a great way to parallel training.
Users can customize their train_func to realize multiple processes or even multiple machines.
... | train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def end_train(self, recs: list, **kwargs) -> List[Recorder]:
"""
Set STATUS_END tag to the recorders.
Args:
recs (list): a list of trained recorders.
Returns:
List[Recorder]: the same list as the param.
"""
if isinstance(recs, Recorder):
... |
Set STATUS_END tag to the recorders.
Args:
recs (list): a list of trained recorders.
Returns:
List[Recorder]: the same list as the param.
| end_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def worker(
self,
train_func: Callable = None,
experiment_name: str = None,
):
"""
The multiprocessing method for `train`. It can share a same task_pool with `train` and can run in other progress or other machines.
Args:
train_func (Callable): the trainin... |
The multiprocessing method for `train`. It can share a same task_pool with `train` and can run in other progress or other machines.
Args:
train_func (Callable): the training method which needs at least `tasks` and `experiment_name`. None for the default training method.
experim... | worker | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def __init__(
self,
experiment_name: str = None,
task_pool: str = None,
train_func=begin_task_train,
end_train_func=end_task_train,
skip_run_task: bool = False,
**kwargs,
):
"""
Init DelayTrainerRM.
Args:
experiment_name (s... |
Init DelayTrainerRM.
Args:
experiment_name (str): the default name of experiment.
task_pool (str): task pool name in TaskManager. None for use same name as experiment_name.
train_func (Callable, optional): default train method. Defaults to `begin_task_train`.
... | __init__ | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def train(self, tasks: list, train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]:
"""
Same as `train` of TrainerRM, after_status will be STATUS_PART_DONE.
Args:
tasks (list): a list of definition based on `task` dict
train_func (Callable): the train... |
Same as `train` of TrainerRM, after_status will be STATUS_PART_DONE.
Args:
tasks (list): a list of definition based on `task` dict
train_func (Callable): the train method which need at least `tasks` and `experiment_name`. Defaults to None for using self.train_func.
... | train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def end_train(self, recs, end_train_func=None, experiment_name: str = None, **kwargs) -> List[Recorder]:
"""
Given a list of Recorder and return a list of trained Recorder.
This class will finish real data loading and model fitting.
Args:
recs (list): a list of Recorder, the... |
Given a list of Recorder and return a list of trained Recorder.
This class will finish real data loading and model fitting.
Args:
recs (list): a list of Recorder, the tasks have been saved to them.
end_train_func (Callable, optional): the end_train method which need at ... | end_train | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def worker(self, end_train_func=None, experiment_name: str = None):
"""
The multiprocessing method for `end_train`. It can share a same task_pool with `end_train` and can run in other progress or other machines.
Args:
end_train_func (Callable, optional): the end_train method which n... |
The multiprocessing method for `end_train`. It can share a same task_pool with `end_train` and can run in other progress or other machines.
Args:
end_train_func (Callable, optional): the end_train method which need at least `recorders` and `experiment_name`. Defaults to None for using self... | worker | python | microsoft/qlib | qlib/model/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/model/trainer.py | MIT |
def __call__(self, ensemble_dict: dict) -> pd.DataFrame:
"""using sample:
from qlib.model.ens.ensemble import AverageEnsemble
pred_res['new_key_name'] = AverageEnsemble()(predict_dict)
Parameters
----------
ensemble_dict : dict
Dictionary you want to ensemble... | using sample:
from qlib.model.ens.ensemble import AverageEnsemble
pred_res['new_key_name'] = AverageEnsemble()(predict_dict)
Parameters
----------
ensemble_dict : dict
Dictionary you want to ensemble
Returns
-------
pd.DataFrame
T... | __call__ | python | microsoft/qlib | qlib/model/ens/ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/model/ens/ensemble.py | MIT |
def __init__(self, group_func=None, ens: Ensemble = None):
"""
Init Group.
Args:
group_func (Callable, optional): Given a dict and return the group key and one of the group elements.
For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: objec... |
Init Group.
Args:
group_func (Callable, optional): Given a dict and return the group key and one of the group elements.
For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}}
Defaults to None.
ens (Ensemble, optiona... | __init__ | python | microsoft/qlib | qlib/model/ens/group.py | https://github.com/microsoft/qlib/blob/master/qlib/model/ens/group.py | MIT |
def group(self, *args, **kwargs) -> dict:
"""
Group a set of objects and change them to a dict.
For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}}
Returns:
dict: grouped dict
"""
if isinstance(getattr(self, "_group_func", ... |
Group a set of objects and change them to a dict.
For example: {(A,B,C1): object, (A,B,C2): object} -> {(A,B): {C1: object, C2: object}}
Returns:
dict: grouped dict
| group | python | microsoft/qlib | qlib/model/ens/group.py | https://github.com/microsoft/qlib/blob/master/qlib/model/ens/group.py | MIT |
def reduce(self, *args, **kwargs) -> dict:
"""
Reduce grouped dict.
For example: {(A,B): {C1: object, C2: object}} -> {(A,B): object}
Returns:
dict: reduced dict
"""
if isinstance(getattr(self, "_ens_func", None), Callable):
return self._ens_func... |
Reduce grouped dict.
For example: {(A,B): {C1: object, C2: object}} -> {(A,B): object}
Returns:
dict: reduced dict
| reduce | python | microsoft/qlib | qlib/model/ens/group.py | https://github.com/microsoft/qlib/blob/master/qlib/model/ens/group.py | MIT |
def __call__(self, ungrouped_dict: dict, n_jobs: int = 1, verbose: int = 0, *args, **kwargs) -> dict:
"""
Group the ungrouped_dict into different groups.
Args:
ungrouped_dict (dict): the ungrouped dict waiting for grouping like {name: things}
Returns:
dict: grou... |
Group the ungrouped_dict into different groups.
Args:
ungrouped_dict (dict): the ungrouped dict waiting for grouping like {name: things}
Returns:
dict: grouped_dict like {G1: object, G2: object}
n_jobs: how many progress you need.
verbose: the p... | __call__ | python | microsoft/qlib | qlib/model/ens/group.py | https://github.com/microsoft/qlib/blob/master/qlib/model/ens/group.py | MIT |
def group(self, rolling_dict: dict) -> dict:
"""Given an rolling dict likes {(A,B,R): things}, return the grouped dict likes {(A,B): {R:things}}
NOTE: There is an assumption which is the rolling key is at the end of the key tuple, because the rolling results always need to be ensemble firstly.
... | Given an rolling dict likes {(A,B,R): things}, return the grouped dict likes {(A,B): {R:things}}
NOTE: There is an assumption which is the rolling key is at the end of the key tuple, because the rolling results always need to be ensemble firstly.
Args:
rolling_dict (dict): an rolling dict.... | group | python | microsoft/qlib | qlib/model/ens/group.py | https://github.com/microsoft/qlib/blob/master/qlib/model/ens/group.py | MIT |
def get_feature_importance(self) -> pd.Series:
"""get feature importance
Returns
-------
The index is the feature name.
The greater the value, the higher importance.
""" | get feature importance
Returns
-------
The index is the feature name.
The greater the value, the higher importance.
| get_feature_importance | python | microsoft/qlib | qlib/model/interpret/base.py | https://github.com/microsoft/qlib/blob/master/qlib/model/interpret/base.py | MIT |
def get_feature_importance(self, *args, **kwargs) -> pd.Series:
"""get feature importance
Notes
-----
parameters reference:
https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html?highlight=feature_importance#lightgbm.Booster.feature_importance
... | get feature importance
Notes
-----
parameters reference:
https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html?highlight=feature_importance#lightgbm.Booster.feature_importance
| get_feature_importance | python | microsoft/qlib | qlib/model/interpret/base.py | https://github.com/microsoft/qlib/blob/master/qlib/model/interpret/base.py | MIT |
def __init__(self, segments: Union[Dict[Text, Tuple], float], *args, **kwargs):
"""
The meta-dataset maintains a list of meta-tasks when it is initialized.
The segments indicates the way to divide the data
The duty of the `__init__` function of MetaTaskDataset
- initialize the ... |
The meta-dataset maintains a list of meta-tasks when it is initialized.
The segments indicates the way to divide the data
The duty of the `__init__` function of MetaTaskDataset
- initialize the tasks
| __init__ | python | microsoft/qlib | qlib/model/meta/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/model/meta/dataset.py | MIT |
def prepare_tasks(self, segments: Union[List[Text], Text], *args, **kwargs) -> List[MetaTask]:
"""
Prepare the data in each meta-task and ready for training.
The following code example shows how to retrieve a list of meta-tasks from the `meta_dataset`:
.. code-block:: Python
... |
Prepare the data in each meta-task and ready for training.
The following code example shows how to retrieve a list of meta-tasks from the `meta_dataset`:
.. code-block:: Python
# get the train segment and the test segment, both of them are lists
train_meta... | prepare_tasks | python | microsoft/qlib | qlib/model/meta/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/model/meta/dataset.py | MIT |
def _prepare_seg(self, segment: Text):
"""
prepare a single segment of data for training data
Parameters
----------
seg : Text
the name of the segment
""" |
prepare a single segment of data for training data
Parameters
----------
seg : Text
the name of the segment
| _prepare_seg | python | microsoft/qlib | qlib/model/meta/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/model/meta/dataset.py | MIT |
def fit(self, *args, **kwargs):
"""
The training process of the meta-model.
""" |
The training process of the meta-model.
| fit | python | microsoft/qlib | qlib/model/meta/model.py | https://github.com/microsoft/qlib/blob/master/qlib/model/meta/model.py | MIT |
def inference(self, *args, **kwargs) -> object:
"""
The inference process of the meta-model.
Returns
-------
object:
Some information to guide the model learning
""" |
The inference process of the meta-model.
Returns
-------
object:
Some information to guide the model learning
| inference | python | microsoft/qlib | qlib/model/meta/model.py | https://github.com/microsoft/qlib/blob/master/qlib/model/meta/model.py | MIT |
def __init__(self, task: dict, meta_info: object, mode: str = PROC_MODE_FULL):
"""
The `__init__` func is responsible for
- store the task
- store the origin input data for
- process the input data for meta data
Parameters
----------
task : dict
... |
The `__init__` func is responsible for
- store the task
- store the origin input data for
- process the input data for meta data
Parameters
----------
task : dict
the task to be enhanced by meta model
meta_info : object
the inpu... | __init__ | python | microsoft/qlib | qlib/model/meta/task.py | https://github.com/microsoft/qlib/blob/master/qlib/model/meta/task.py | MIT |
def __init__(self, nan_option: str = "ignore", assume_centered: bool = False, scale_return: bool = True):
"""
Args:
nan_option (str): nan handling option (`ignore`/`mask`/`fill`).
assume_centered (bool): whether the data is assumed to be centered.
scale_return (bool):... |
Args:
nan_option (str): nan handling option (`ignore`/`mask`/`fill`).
assume_centered (bool): whether the data is assumed to be centered.
scale_return (bool): whether scale returns as percentage.
| __init__ | python | microsoft/qlib | qlib/model/riskmodel/base.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/base.py | MIT |
def predict(
self,
X: Union[pd.Series, pd.DataFrame, np.ndarray],
return_corr: bool = False,
is_price: bool = True,
return_decomposed_components=False,
) -> Union[pd.DataFrame, np.ndarray, tuple]:
"""
Args:
X (pd.Series, pd.DataFrame or np.ndarray)... |
Args:
X (pd.Series, pd.DataFrame or np.ndarray): data from which to estimate the covariance,
with variables as columns and observations as rows.
return_corr (bool): whether return the correlation matrix.
is_price (bool): whether `X` contains price (if not ass... | predict | python | microsoft/qlib | qlib/model/riskmodel/base.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/base.py | MIT |
def _predict(self, X: np.ndarray) -> np.ndarray:
"""covariance estimation implementation
This method should be overridden by child classes.
By default, this method implements the empirical covariance estimation.
Args:
X (np.ndarray): data matrix containing multiple variabl... | covariance estimation implementation
This method should be overridden by child classes.
By default, this method implements the empirical covariance estimation.
Args:
X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows).
Returns:
... | _predict | python | microsoft/qlib | qlib/model/riskmodel/base.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/base.py | MIT |
def _preprocess(self, X: np.ndarray) -> Union[np.ndarray, np.ma.MaskedArray]:
"""handle nan and centerize data
Note:
if `nan_option='mask'` then the returned array will be `np.ma.MaskedArray`.
"""
# handle nan
if self.nan_option == self.FILL_NAN:
X = np.n... | handle nan and centerize data
Note:
if `nan_option='mask'` then the returned array will be `np.ma.MaskedArray`.
| _preprocess | python | microsoft/qlib | qlib/model/riskmodel/base.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/base.py | MIT |
def __init__(self, num_factors: int = 0, thresh: float = 1.0, thresh_method: str = "soft", **kwargs):
"""
Args:
num_factors (int): number of factors (if set to zero, no factor model will be used).
thresh (float): the positive constant for thresholding.
thresh_method (... |
Args:
num_factors (int): number of factors (if set to zero, no factor model will be used).
thresh (float): the positive constant for thresholding.
thresh_method (str): thresholding method, which can be
- 'soft': soft thresholding.
- 'hard': ha... | __init__ | python | microsoft/qlib | qlib/model/riskmodel/poet.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/poet.py | MIT |
def __init__(self, alpha: Union[str, float] = 0.0, target: Union[str, np.ndarray] = "const_var", **kwargs):
"""
Args:
alpha (str or float): shrinking parameter or estimator (`lw`/`oas`)
target (str or np.ndarray): shrinking target (`const_var`/`const_corr`/`single_factor`)
... |
Args:
alpha (str or float): shrinking parameter or estimator (`lw`/`oas`)
target (str or np.ndarray): shrinking target (`const_var`/`const_corr`/`single_factor`)
kwargs: see `RiskModel` for more information
| __init__ | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_target_const_var(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
"""get shrinking target with constant variance
This target assumes zero pair-wise correlation and constant variance.
The constant variance is estimated by averaging all sample's variances.
"""
n ... | get shrinking target with constant variance
This target assumes zero pair-wise correlation and constant variance.
The constant variance is estimated by averaging all sample's variances.
| _get_shrink_target_const_var | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_target_const_corr(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
"""get shrinking target with constant correlation
This target assumes constant pair-wise correlation but keep the sample variance.
The constant correlation is estimated by averaging all pairwise correlations.
... | get shrinking target with constant correlation
This target assumes constant pair-wise correlation but keep the sample variance.
The constant correlation is estimated by averaging all pairwise correlations.
| _get_shrink_target_const_corr | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_target_single_factor(self, X: np.ndarray, S: np.ndarray) -> np.ndarray:
"""get shrinking target with single factor model"""
X_mkt = np.nanmean(X, axis=1)
cov_mkt = np.asarray(X.T.dot(X_mkt) / len(X))
var_mkt = np.asarray(X_mkt.dot(X_mkt) / len(X))
F = np.outer(cov... | get shrinking target with single factor model | _get_shrink_target_single_factor | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_param(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
"""get shrinking parameter `alpha`
Note:
The Ledoit-Wolf shrinking parameter estimator consists of three different methods.
"""
if self.alpha == self.SHR_OAS:
return self._get_shri... | get shrinking parameter `alpha`
Note:
The Ledoit-Wolf shrinking parameter estimator consists of three different methods.
| _get_shrink_param | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_param_oas(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
"""Oracle Approximating Shrinkage Estimator
This method uses the following formula to estimate the `alpha`
parameter for the shrink covariance estimator:
A = (1 - 2 / p) * trace(S^2) + trace^2(S)
... | Oracle Approximating Shrinkage Estimator
This method uses the following formula to estimate the `alpha`
parameter for the shrink covariance estimator:
A = (1 - 2 / p) * trace(S^2) + trace^2(S)
B = (n + 1 - 2 / p) * (trace(S^2) - trace^2(S) / p)
alpha = A / B
... | _get_shrink_param_oas | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_param_lw_const_var(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
"""Ledoit-Wolf Shrinkage Estimator (Constant Variance)
This method shrinks the covariance matrix towards the constand variance target.
"""
t, n = X.shape
y = X**2
phi = np.su... | Ledoit-Wolf Shrinkage Estimator (Constant Variance)
This method shrinks the covariance matrix towards the constand variance target.
| _get_shrink_param_lw_const_var | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_param_lw_const_corr(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
"""Ledoit-Wolf Shrinkage Estimator (Constant Correlation)
This method shrinks the covariance matrix towards the constand correlation target.
"""
t, n = X.shape
var = np.diag(S)
... | Ledoit-Wolf Shrinkage Estimator (Constant Correlation)
This method shrinks the covariance matrix towards the constand correlation target.
| _get_shrink_param_lw_const_corr | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def _get_shrink_param_lw_single_factor(self, X: np.ndarray, S: np.ndarray, F: np.ndarray) -> float:
"""Ledoit-Wolf Shrinkage Estimator (Single Factor Model)
This method shrinks the covariance matrix towards the single factor model target.
"""
t, n = X.shape
X_mkt = np.nanmean(X... | Ledoit-Wolf Shrinkage Estimator (Single Factor Model)
This method shrinks the covariance matrix towards the single factor model target.
| _get_shrink_param_lw_single_factor | python | microsoft/qlib | qlib/model/riskmodel/shrink.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/shrink.py | MIT |
def __init__(self, factor_model: str = "pca", num_factors: int = 10, **kwargs):
"""
Args:
factor_model (str): the latent factor models used to estimate the structured covariance (`pca`/`fa`).
num_factors (int): number of components to keep.
kwargs: see `RiskModel` for... |
Args:
factor_model (str): the latent factor models used to estimate the structured covariance (`pca`/`fa`).
num_factors (int): number of components to keep.
kwargs: see `RiskModel` for more information
| __init__ | python | microsoft/qlib | qlib/model/riskmodel/structured.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/structured.py | MIT |
def _predict(self, X: np.ndarray, return_decomposed_components=False) -> Union[np.ndarray, tuple]:
"""
covariance estimation implementation
Args:
X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows).
return_decomposed_components (bo... |
covariance estimation implementation
Args:
X (np.ndarray): data matrix containing multiple variables (columns) and observations (rows).
return_decomposed_components (bool): whether return decomposed components of the covariance matrix.
Returns:
tuple or np.... | _predict | python | microsoft/qlib | qlib/model/riskmodel/structured.py | https://github.com/microsoft/qlib/blob/master/qlib/model/riskmodel/structured.py | MIT |
def _gym_space_contains(space: gym.Space, x: Any) -> None:
"""Strengthened version of gym.Space.contains.
Giving more diagnostic information on why validation fails.
Throw exception rather than returning true or false.
"""
if isinstance(space, spaces.Dict):
if not isinstance(x, dict) or len... | Strengthened version of gym.Space.contains.
Giving more diagnostic information on why validation fails.
Throw exception rather than returning true or false.
| _gym_space_contains | python | microsoft/qlib | qlib/rl/interpreter.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/interpreter.py | MIT |
def _generate_report(
decisions: List[BaseTradeDecision],
report_indicators: List[INDICATOR_METRIC],
) -> Dict[str, Tuple[pd.DataFrame, pd.DataFrame]]:
"""Generate backtest reports
Parameters
----------
decisions:
List of trade decisions.
report_indicators
List of indicator ... | Generate backtest reports
Parameters
----------
decisions:
List of trade decisions.
report_indicators
List of indicator reports.
Returns
-------
| _generate_report | python | microsoft/qlib | qlib/rl/contrib/backtest.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/contrib/backtest.py | MIT |
def init_qlib(qlib_config: dict) -> None:
"""Initialize necessary resource to launch the workflow, including data direction, feature columns, etc..
Parameters
----------
qlib_config:
Qlib configuration.
Example::
{
"provider_uri_day": DATA_ROOT_DIR / "qlib_... | Initialize necessary resource to launch the workflow, including data direction, feature columns, etc..
Parameters
----------
qlib_config:
Qlib configuration.
Example::
{
"provider_uri_day": DATA_ROOT_DIR / "qlib_1d",
"provider_uri_1min": DATA_RO... | init_qlib | python | microsoft/qlib | qlib/rl/data/integration.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/data/integration.py | MIT |
def get_deal_price(self) -> pd.Series:
"""Return a pandas series that can be indexed with time.
See :attribute:`DealPriceType` for details."""
if self.deal_price_type in ("bid_or_ask", "bid_or_ask_fill"):
if self.order_dir is None:
raise ValueError("Order direction ca... | Return a pandas series that can be indexed with time.
See :attribute:`DealPriceType` for details. | get_deal_price | python | microsoft/qlib | qlib/rl/data/pickle_styled.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/data/pickle_styled.py | MIT |
def load_orders(
order_path: Path,
start_time: pd.Timestamp = None,
end_time: pd.Timestamp = None,
) -> Sequence[Order]:
"""Load orders, and set start time and end time for the orders."""
start_time = start_time or pd.Timestamp("0:00:00")
end_time = end_time or pd.Timestamp("23:59:59")
if ... | Load orders, and set start time and end time for the orders. | load_orders | python | microsoft/qlib | qlib/rl/data/pickle_styled.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/data/pickle_styled.py | MIT |
def forward(self, batch: Batch) -> torch.Tensor:
"""
Input should be a dict (at least) containing:
- data_processed: [N, T, C]
- cur_step: [N] (int)
- cur_time: [N] (int)
- position_history: [N, S] (S is number of steps)
- target: [N]
- num_step: [N] ... |
Input should be a dict (at least) containing:
- data_processed: [N, T, C]
- cur_step: [N] (int)
- cur_time: [N] (int)
- position_history: [N, S] (S is number of steps)
- target: [N]
- num_step: [N] (int)
- acquiring: [N] (0 or 1)
| forward | python | microsoft/qlib | qlib/rl/order_execution/network.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/network.py | MIT |
def _iter_strategy(self, action: Optional[float] = None) -> SAOEStrategy:
"""Iterate the _collect_data_loop until we get the next yield SAOEStrategy."""
assert self._collect_data_loop is not None
obj = next(self._collect_data_loop) if action is None else self._collect_data_loop.send(action)
... | Iterate the _collect_data_loop until we get the next yield SAOEStrategy. | _iter_strategy | python | microsoft/qlib | qlib/rl/order_execution/simulator_qlib.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/simulator_qlib.py | MIT |
def step(self, action: Optional[float]) -> None:
"""Execute one step or SAOE.
Parameters
----------
action (float):
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
"""
assert not self.done(), "Simulator h... | Execute one step or SAOE.
Parameters
----------
action (float):
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
| step | python | microsoft/qlib | qlib/rl/order_execution/simulator_qlib.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/simulator_qlib.py | MIT |
def step(self, amount: float) -> None:
"""Execute one step or SAOE.
Parameters
----------
amount
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
"""
assert not self.done()
self.market_price = sel... | Execute one step or SAOE.
Parameters
----------
amount
The amount you wish to deal. The simulator doesn't guarantee all the amount to be successfully dealt.
| step | python | microsoft/qlib | qlib/rl/order_execution/simulator_simple.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/simulator_simple.py | MIT |
def _next_time(self) -> pd.Timestamp:
"""The "current time" (``cur_time``) for next step."""
# Look for next time on time index
current_loc = self.ticks_index.get_loc(self.cur_time)
next_loc = current_loc + self.ticks_per_step
# Calibrate the next location to multiple of ticks_p... | The "current time" (``cur_time``) for next step. | _next_time | python | microsoft/qlib | qlib/rl/order_execution/simulator_simple.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/simulator_simple.py | MIT |
def _split_exec_vol(self, exec_vol_sum: float) -> np.ndarray:
"""
Split the volume in each step into minutes, considering possible constraints.
This follows TWAP strategy.
"""
next_time = self._next_time()
# get the backtest data for next interval
self.market_vol... |
Split the volume in each step into minutes, considering possible constraints.
This follows TWAP strategy.
| _split_exec_vol | python | microsoft/qlib | qlib/rl/order_execution/simulator_simple.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/simulator_simple.py | MIT |
def fill_missing_data(
original_data: np.ndarray,
fill_method: Callable = np.nanmedian,
) -> np.ndarray:
"""Fill missing data.
Parameters
----------
original_data
Original data without missing values.
fill_method
Method used to fill the missing data.
Returns
-------... | Fill missing data.
Parameters
----------
original_data
Original data without missing values.
fill_method
Method used to fill the missing data.
Returns
-------
The filled data.
| fill_missing_data | python | microsoft/qlib | qlib/rl/order_execution/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/strategy.py | MIT |
def generate_metrics_after_done(self) -> None:
"""Generate metrics once the upper level execution is done"""
self.metrics = self._collect_single_order_metric(
self.order,
self.backtest_data.ticks_index[0], # start time
self.history_exec["market_volume"],
... | Generate metrics once the upper level execution is done | generate_metrics_after_done | python | microsoft/qlib | qlib/rl/order_execution/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/strategy.py | MIT |
def generate_trade_decision(
self,
execute_result: list | None = None,
) -> Union[BaseTradeDecision, Generator[Any, Any, BaseTradeDecision]]:
"""
For SAOEStrategy, we need to update the `self._last_step_range` every time a decision is generated.
This operation should be invis... |
For SAOEStrategy, we need to update the `self._last_step_range` every time a decision is generated.
This operation should be invisible to developers, so we implement it in `generate_trade_decision()`
The concrete logic to generate decisions should be implemented in `_generate_trade_decision()`.... | generate_trade_decision | python | microsoft/qlib | qlib/rl/order_execution/strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/order_execution/strategy.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.