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, 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 __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 |
def train(
simulator_fn: Callable[[InitialStateType], Simulator],
state_interpreter: StateInterpreter,
action_interpreter: ActionInterpreter,
initial_states: Sequence[InitialStateType],
policy: BasePolicy,
reward: Reward,
vessel_kwargs: Dict[str, Any],
trainer_kwargs: Dict[str, Any],
) -... | Train a policy with the parallelism provided by RL framework.
Experimental API. Parameters might change shortly.
Parameters
----------
simulator_fn
Callable receiving initial seed, returning a simulator.
state_interpreter
Interprets the state of simulators.
action_interpreter
... | train | python | microsoft/qlib | qlib/rl/trainer/api.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/api.py | MIT |
def backtest(
simulator_fn: Callable[[InitialStateType], Simulator],
state_interpreter: StateInterpreter,
action_interpreter: ActionInterpreter,
initial_states: Sequence[InitialStateType],
policy: BasePolicy,
logger: LogWriter | List[LogWriter],
reward: Reward | None = None,
finite_env_t... | Backtest with the parallelism provided by RL framework.
Experimental API. Parameters might change shortly.
Parameters
----------
simulator_fn
Callable receiving initial seed, returning a simulator.
state_interpreter
Interprets the state of simulators.
action_interpreter
... | backtest | python | microsoft/qlib | qlib/rl/trainer/api.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/api.py | MIT |
def on_train_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None:
"""Called when the training ends.
To access all outputs produced during training, cache the data in either trainer and vessel,
and post-process them in this hook.
""" | Called when the training ends.
To access all outputs produced during training, cache the data in either trainer and vessel,
and post-process them in this hook.
| on_train_end | python | microsoft/qlib | qlib/rl/trainer/callbacks.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/callbacks.py | MIT |
def on_iter_end(self, trainer: Trainer, vessel: TrainingVesselBase) -> None:
"""Called upon every end of iteration.
This is called **after** the bump of ``current_iter``,
when the previous iteration is considered complete.
""" | Called upon every end of iteration.
This is called **after** the bump of ``current_iter``,
when the previous iteration is considered complete.
| on_iter_end | python | microsoft/qlib | qlib/rl/trainer/callbacks.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/callbacks.py | MIT |
def initialize(self):
"""Initialize the whole training process.
The states here should be synchronized with state_dict.
"""
self.should_stop = False
self.current_iter = 0
self.current_episode = 0
self.current_stage = "train" | Initialize the whole training process.
The states here should be synchronized with state_dict.
| initialize | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def state_dict(self) -> dict:
"""Putting every states of current training into a dict, at best effort.
It doesn't try to handle all the possible kinds of states in the middle of one training collect.
For most cases at the end of each iteration, things should be usually correct.
Note th... | Putting every states of current training into a dict, at best effort.
It doesn't try to handle all the possible kinds of states in the middle of one training collect.
For most cases at the end of each iteration, things should be usually correct.
Note that it's also intended behavior that repla... | state_dict | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def load_state_dict(self, state_dict: dict) -> None:
"""Load all states into current trainer."""
self.vessel.load_state_dict(state_dict["vessel"])
for name, callback in self.named_callbacks().items():
callback.load_state_dict(state_dict["callbacks"][name])
for name, logger in... | Load all states into current trainer. | load_state_dict | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def fit(self, vessel: TrainingVesselBase, ckpt_path: Path | None = None) -> None:
"""Train the RL policy upon the defined simulator.
Parameters
----------
vessel
A bundle of all elements used in training.
ckpt_path
Load a pre-trained / paused training che... | Train the RL policy upon the defined simulator.
Parameters
----------
vessel
A bundle of all elements used in training.
ckpt_path
Load a pre-trained / paused training checkpoint.
| fit | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def test(self, vessel: TrainingVesselBase) -> None:
"""Test the RL policy against the simulator.
The simulator will be fed with data generated in ``test_seed_iterator``.
Parameters
----------
vessel
A bundle of all related elements.
"""
self.vessel =... | Test the RL policy against the simulator.
The simulator will be fed with data generated in ``test_seed_iterator``.
Parameters
----------
vessel
A bundle of all related elements.
| test | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def venv_from_iterator(self, iterator: Iterable[InitialStateType]) -> FiniteVectorEnv:
"""Create a vectorized environment from iterator and the training vessel."""
def env_factory():
# FIXME: state_interpreter and action_interpreter are stateful (having a weakref of env),
# and ... | Create a vectorized environment from iterator and the training vessel. | venv_from_iterator | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def _wrap_context(obj):
"""Make any object a (possibly dummy) context manager."""
if isinstance(obj, AbstractContextManager):
# obj has __enter__ and __exit__
with obj as ctx:
yield ctx
else:
yield obj | Make any object a (possibly dummy) context manager. | _wrap_context | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def _named_collection(seq: Sequence[T]) -> Dict[str, T]:
"""Convert a list into a dict, where each item is named with its type."""
res = {}
retry_cnt: collections.Counter = collections.Counter()
for item in seq:
typename = type(item).__name__.lower()
key = typename if retry_cnt[typename]... | Convert a list into a dict, where each item is named with its type. | _named_collection | python | microsoft/qlib | qlib/rl/trainer/trainer.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/trainer.py | MIT |
def train(self, vector_env: FiniteVectorEnv) -> Dict[str, Any]:
"""Create a collector and collects ``episode_per_iter`` episodes.
Update the policy on the collected replay buffer.
"""
self.policy.train()
with vector_env.collector_guard():
collector = Collector(
... | Create a collector and collects ``episode_per_iter`` episodes.
Update the policy on the collected replay buffer.
| train | python | microsoft/qlib | qlib/rl/trainer/vessel.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/trainer/vessel.py | MIT |
def reset(self, **kwargs: Any) -> ObsType:
"""
Try to get a state from state queue, and init the simulator with this state.
If the queue is exhausted, generate an invalid (nan) observation.
"""
try:
if self.seed_iterator is None:
raise RuntimeError("Y... |
Try to get a state from state queue, and init the simulator with this state.
If the queue is exhausted, generate an invalid (nan) observation.
| reset | python | microsoft/qlib | qlib/rl/utils/env_wrapper.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/env_wrapper.py | MIT |
def step(self, policy_action: PolicyActType, **kwargs: Any) -> Tuple[ObsType, float, bool, InfoDict]:
"""Environment step.
See the code along with comments to get a sequence of things happening here.
"""
if self.seed_iterator is None:
raise RuntimeError("State queue is alre... | Environment step.
See the code along with comments to get a sequence of things happening here.
| step | python | microsoft/qlib | qlib/rl/utils/env_wrapper.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/env_wrapper.py | MIT |
def generate_nan_observation(obs_space: gym.Space) -> Any:
"""The NaN observation that indicates the environment receives no seed.
We assume that obs is complex and there must be something like float.
Otherwise this logic doesn't work.
"""
sample = obs_space.sample()
sample = fill_invalid(samp... | The NaN observation that indicates the environment receives no seed.
We assume that obs is complex and there must be something like float.
Otherwise this logic doesn't work.
| generate_nan_observation | python | microsoft/qlib | qlib/rl/utils/finite_env.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/finite_env.py | MIT |
def collector_guard(self) -> Generator[FiniteVectorEnv, None, None]:
"""Guard the collector. Recommended to guard every collect.
This guard is for two purposes.
1. Catch and ignore the StopIteration exception, which is the stopping signal
thrown by FiniteEnv to let tianshou know tha... | Guard the collector. Recommended to guard every collect.
This guard is for two purposes.
1. Catch and ignore the StopIteration exception, which is the stopping signal
thrown by FiniteEnv to let tianshou know that ``collector.collect()`` should exit.
2. Notify the loggers that the co... | collector_guard | python | microsoft/qlib | qlib/rl/utils/finite_env.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/finite_env.py | MIT |
def vectorize_env(
env_factory: Callable[..., gym.Env],
env_type: FiniteEnvType,
concurrency: int,
logger: LogWriter | List[LogWriter],
) -> FiniteVectorEnv:
"""Helper function to create a vector env. Can be used to replace usual VectorEnv.
For example, once you wrote: ::
DummyVectorEn... | Helper function to create a vector env. Can be used to replace usual VectorEnv.
For example, once you wrote: ::
DummyVectorEnv([lambda: gym.make(task) for _ in range(env_num)])
Now you can replace it with: ::
finite_env_factory(lambda: gym.make(task), "dummy", env_num, my_logger)
By doi... | vectorize_env | python | microsoft/qlib | qlib/rl/utils/finite_env.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/finite_env.py | MIT |
def add_string(self, name: str, string: str, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
"""Add a string with name into logged contents."""
if loglevel < self._min_loglevel:
return
if not isinstance(string, str):
raise TypeError(f"{string} is not a string.")
... | Add a string with name into logged contents. | add_string | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def add_scalar(self, name: str, scalar: Any, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
"""Add a scalar with name into logged contents.
Scalar will be converted into a float.
"""
if loglevel < self._min_loglevel:
return
if hasattr(scalar, "item"):
... | Add a scalar with name into logged contents.
Scalar will be converted into a float.
| add_scalar | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def add_array(
self,
name: str,
array: np.ndarray | pd.DataFrame | pd.Series,
loglevel: int | LogLevel = LogLevel.PERIODIC,
) -> None:
"""Add an array with name into logging."""
if loglevel < self._min_loglevel:
return
if not isinstance(array, (np... | Add an array with name into logging. | add_array | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def add_any(self, name: str, obj: Any, loglevel: int | LogLevel = LogLevel.PERIODIC) -> None:
"""Log something with any type.
As it's an "any" object, the only LogWriter accepting it is pickle.
Therefore, pickle must be able to serialize it.
"""
if loglevel < self._min_loglevel:... | Log something with any type.
As it's an "any" object, the only LogWriter accepting it is pickle.
Therefore, pickle must be able to serialize it.
| add_any | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def clear(self):
"""Clear all the metrics for a fresh start.
To make the logger instance reusable.
"""
self.episode_count = self.step_count = 0
self.active_env_ids = set() | Clear all the metrics for a fresh start.
To make the logger instance reusable.
| clear | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def state_dict(self) -> dict:
"""Save the states of the logger to a dict."""
return {
"episode_count": self.episode_count,
"step_count": self.step_count,
"global_step": self.global_step,
"global_episode": self.global_episode,
"active_env_ids": ... | Save the states of the logger to a dict. | state_dict | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def load_state_dict(self, state_dict: dict) -> None:
"""Load the states of current logger from a dict."""
self.episode_count = state_dict["episode_count"]
self.step_count = state_dict["step_count"]
self.global_step = state_dict["global_step"]
self.global_episode = state_dict["glo... | Load the states of current logger from a dict. | load_state_dict | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def aggregation(array: Sequence[Any], name: str | None = None) -> Any:
"""Aggregation function from step-wise to episode-wise.
If it's a sequence of float, take the mean.
Otherwise, take the first element.
If a name is specified and,
- if it's ``reward``, the reduction will be... | Aggregation function from step-wise to episode-wise.
If it's a sequence of float, take the mean.
Otherwise, take the first element.
If a name is specified and,
- if it's ``reward``, the reduction will be sum.
| aggregation | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def log_episode(self, length: int, rewards: List[float], contents: List[Dict[str, Any]]) -> None:
"""This is triggered at the end of each trajectory.
Parameters
----------
length
Length of this trajectory.
rewards
A list of rewards at each step of this ep... | This is triggered at the end of each trajectory.
Parameters
----------
length
Length of this trajectory.
rewards
A list of rewards at each step of this episode.
contents
Logged contents for every step.
| log_episode | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def log_step(self, reward: float, contents: Dict[str, Any]) -> None:
"""This is triggered at each step.
Parameters
----------
reward
Reward for this step.
contents
Logged contents for this step.
""" | This is triggered at each step.
Parameters
----------
reward
Reward for this step.
contents
Logged contents for this step.
| log_step | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def on_env_step(self, env_id: int, obs: ObsType, rew: float, done: bool, info: InfoDict) -> None:
"""Callback for finite env, on each step."""
# Update counter
self.global_step += 1
self.step_count += 1
self.active_env_ids.add(env_id)
self.episode_lengths[env_id] += 1
... | Callback for finite env, on each step. | on_env_step | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def episode_metrics(self) -> dict[str, float]:
"""Retrieve the numeric metrics of the latest episode."""
if self._latest_metrics is None:
raise ValueError("No episode metrics available yet.")
return self._latest_metrics | Retrieve the numeric metrics of the latest episode. | episode_metrics | python | microsoft/qlib | qlib/rl/utils/log.py | https://github.com/microsoft/qlib/blob/master/qlib/rl/utils/log.py | MIT |
def __init__(
self,
outer_trade_decision: BaseTradeDecision = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
trade_exchange: Exchange = None,
) -> None:
"""
Parameters
----------
outer_trade_decision :... |
Parameters
----------
outer_trade_decision : BaseTradeDecision, optional
the trade decision of outer strategy which this strategy relies, and it will be traded in
[start_time, end_time], by default None
- If the strategy is used to split trade decision, it w... | __init__ | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def reset(
self,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
outer_trade_decision: BaseTradeDecision = None,
**kwargs,
) -> None:
"""
- reset `level_infra`, used to reset trade calendar, .etc
- reset `common_infr... |
- reset `level_infra`, used to reset trade calendar, .etc
- reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc
- reset `outer_trade_decision`, used to make split decision
**NOTE**:
split this function into `reset` and `_reset` will make following cases ... | reset | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def _reset(
self,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
outer_trade_decision: BaseTradeDecision = None,
):
"""
Please refer to the docs of `reset`
"""
if level_infra is not None:
self.reset_leve... |
Please refer to the docs of `reset`
| _reset | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def generate_trade_decision(
self,
execute_result: list = None,
) -> Union[BaseTradeDecision, Generator[Any, Any, BaseTradeDecision]]:
"""Generate trade decision in each trading bar
Parameters
----------
execute_result : List[object], optional
the execute... | Generate trade decision in each trading bar
Parameters
----------
execute_result : List[object], optional
the executed result for trade decision, by default None
- When call the generate_trade_decision firstly, `execute_result` could be None
| generate_trade_decision | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def update_trade_decision(
trade_decision: BaseTradeDecision,
trade_calendar: TradeCalendarManager,
) -> Optional[BaseTradeDecision]:
"""
update trade decision in each step of inner execution, this method enable all order
Parameters
----------
trade_decision ... |
update trade decision in each step of inner execution, this method enable all order
Parameters
----------
trade_decision : BaseTradeDecision
the trade decision that will be updated
trade_calendar : TradeCalendarManager
The calendar of the **inner strateg... | update_trade_decision | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def alter_outer_trade_decision(self, outer_trade_decision: BaseTradeDecision) -> BaseTradeDecision:
"""
A method for updating the outer_trade_decision.
The outer strategy may change its decision during updating.
Parameters
----------
outer_trade_decision : BaseTradeDecis... |
A method for updating the outer_trade_decision.
The outer strategy may change its decision during updating.
Parameters
----------
outer_trade_decision : BaseTradeDecision
the decision updated by the outer strategy
Returns
-------
BaseTra... | alter_outer_trade_decision | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def post_upper_level_exe_step(self) -> None:
"""
A hook for doing sth after the upper level executor finished its execution (for example, finalize
the metrics collection).
""" |
A hook for doing sth after the upper level executor finished its execution (for example, finalize
the metrics collection).
| post_upper_level_exe_step | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def post_exe_step(self, execute_result: Optional[list]) -> None:
"""
A hook for doing sth after the corresponding executor finished its execution.
Parameters
----------
execute_result :
the execution result
""" |
A hook for doing sth after the corresponding executor finished its execution.
Parameters
----------
execute_result :
the execution result
| post_exe_step | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def __init__(
self,
policy,
outer_trade_decision: BaseTradeDecision = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
**kwargs,
) -> None:
"""
Parameters
----------
policy :
RL polic... |
Parameters
----------
policy :
RL policy for generate action
| __init__ | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def __init__(
self,
policy,
state_interpreter: dict | StateInterpreter,
action_interpreter: dict | ActionInterpreter,
outer_trade_decision: BaseTradeDecision = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
**kwar... |
Parameters
----------
state_interpreter : Union[dict, StateInterpreter]
interpreter that interprets the qlib execute result into rl env state
action_interpreter : Union[dict, ActionInterpreter]
interpreter that interprets the rl agent action into qlib order list
... | __init__ | python | microsoft/qlib | qlib/strategy/base.py | https://github.com/microsoft/qlib/blob/master/qlib/strategy/base.py | MIT |
def download(self, url: str, target_path: [Path, str]):
"""
Download a file from the specified url.
Parameters
----------
url: str
The url of the data.
target_path: str
The location where the data is saved, including the file name.
"""
... |
Download a file from the specified url.
Parameters
----------
url: str
The url of the data.
target_path: str
The location where the data is saved, including the file name.
| download | python | microsoft/qlib | qlib/tests/data.py | https://github.com/microsoft/qlib/blob/master/qlib/tests/data.py | MIT |
def download_data(self, file_name: str, target_dir: [Path, str], delete_old: bool = True):
"""
Download the specified file to the target folder.
Parameters
----------
target_dir: str
data save directory
file_name: str
dataset name, needs to endwit... |
Download the specified file to the target folder.
Parameters
----------
target_dir: str
data save directory
file_name: str
dataset name, needs to endwith .zip, value from [rl_data.zip, csv_data_cn.zip, ...]
may contain folder names, for examp... | download_data | python | microsoft/qlib | qlib/tests/data.py | https://github.com/microsoft/qlib/blob/master/qlib/tests/data.py | MIT |
def qlib_data(
self,
name="qlib_data",
target_dir="~/.qlib/qlib_data/cn_data",
version=None,
interval="1d",
region="cn",
delete_old=True,
exists_skip=False,
):
"""download cn qlib data from remote
Parameters
----------
... | download cn qlib data from remote
Parameters
----------
target_dir: str
data save directory
name: str
dataset name, value from [qlib_data, qlib_data_simple], by default qlib_data
version: str
data version, value from [v1, ...], by default None... | qlib_data | python | microsoft/qlib | qlib/tests/data.py | https://github.com/microsoft/qlib/blob/master/qlib/tests/data.py | MIT |
def robust_zscore(x: pd.Series, zscore=False):
"""Robust ZScore Normalization
Use robust statistics for Z-Score normalization:
mean(x) = median(x)
std(x) = MAD(x) * 1.4826
Reference:
https://en.wikipedia.org/wiki/Median_absolute_deviation.
"""
x = x - x.median()
mad = x... | Robust ZScore Normalization
Use robust statistics for Z-Score normalization:
mean(x) = median(x)
std(x) = MAD(x) * 1.4826
Reference:
https://en.wikipedia.org/wiki/Median_absolute_deviation.
| robust_zscore | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def deepcopy_basic_type(obj: object) -> object:
"""
deepcopy an object without copy the complicated objects.
This is useful when you want to generate Qlib tasks and share the handler
NOTE:
- This function can't handle recursive objects!!!!!
Parameters
----------
obj : object
... |
deepcopy an object without copy the complicated objects.
This is useful when you want to generate Qlib tasks and share the handler
NOTE:
- This function can't handle recursive objects!!!!!
Parameters
----------
obj : object
the object to be copied
Returns
-------
... | deepcopy_basic_type | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def update_config(base_config: dict, ext_config: Union[dict, List[dict]]):
"""
supporting adding base config based on the ext_config
>>> bc = {"a": "xixi"}
>>> ec = {"b": "haha"}
>>> new_bc = update_config(bc, ec)
>>> print(new_bc)
{'a': 'xixi', 'b': 'haha'}
>>> print(bc) # base config... |
supporting adding base config based on the ext_config
>>> bc = {"a": "xixi"}
>>> ec = {"b": "haha"}
>>> new_bc = update_config(bc, ec)
>>> print(new_bc)
{'a': 'xixi', 'b': 'haha'}
>>> print(bc) # base config should not be changed
{'a': 'xixi'}
>>> print(update_config(bc, {"b": S_D... | update_config | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def guess_horizon(label: List):
"""
Try to guess the horizon by parsing label
"""
expr = DatasetProvider.parse_fields(label)[0]
lft_etd, rght_etd = expr.get_extended_window_size()
return rght_etd |
Try to guess the horizon by parsing label
| guess_horizon | python | microsoft/qlib | qlib/utils/data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/data.py | MIT |
def get_or_create_path(path: Optional[Text] = None, return_dir: bool = False):
"""Create or get a file or directory given the path and return_dir.
Parameters
----------
path: a string indicates the path or None indicates creating a temporary path.
return_dir: if True, create and return a directory;... | Create or get a file or directory given the path and return_dir.
Parameters
----------
path: a string indicates the path or None indicates creating a temporary path.
return_dir: if True, create and return a directory; otherwise c&r a file.
| get_or_create_path | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def save_multiple_parts_file(filename, format="gztar"):
"""Save multiple parts file
Implementation process:
1. get the absolute path to 'filename'
2. create a 'filename' directory
3. user does something with file_path('filename/')
4. remove 'filename' directory
5. make_a... | Save multiple parts file
Implementation process:
1. get the absolute path to 'filename'
2. create a 'filename' directory
3. user does something with file_path('filename/')
4. remove 'filename' directory
5. make_archive 'filename' directory, and rename 'archive file' to filen... | save_multiple_parts_file | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def unpack_archive_with_buffer(buffer, format="gztar"):
"""Unpack archive with archive buffer
After the call is finished, the archive file and directory will be deleted.
Implementation process:
1. create 'tempfile' in '~/tmp/' and directory
2. 'buffer' write to 'tempfile'
3. unpack ... | Unpack archive with archive buffer
After the call is finished, the archive file and directory will be deleted.
Implementation process:
1. create 'tempfile' in '~/tmp/' and directory
2. 'buffer' write to 'tempfile'
3. unpack archive file('tempfile')
4. user does something with fi... | unpack_archive_with_buffer | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def get_io_object(file: Union[IO, str, Path], *args, **kwargs) -> IO:
"""
providing a easy interface to get an IO object
Parameters
----------
file : Union[IO, str, Path]
a object representing the file
Returns
-------
IO:
a IO-like object
Raises
------
NotI... |
providing a easy interface to get an IO object
Parameters
----------
file : Union[IO, str, Path]
a object representing the file
Returns
-------
IO:
a IO-like object
Raises
------
NotImplementedError:
| get_io_object | python | microsoft/qlib | qlib/utils/file.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/file.py | MIT |
def concat(data_list: Union[SingleData], axis=0) -> MultiData:
"""concat all SingleData by index.
TODO: now just for SingleData.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to concat.
Returns
-------
MultiData
the MultiData with ndim ==... | concat all SingleData by index.
TODO: now just for SingleData.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to concat.
Returns
-------
MultiData
the MultiData with ndim == 2
| concat | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def sum_by_index(data_list: Union[SingleData], new_index: list, fill_value=0) -> SingleData:
"""concat all SingleData by new index.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to sum.
new_index : list
the new_index of new SingleData.
fill_value ... | concat all SingleData by new index.
Parameters
----------
data_list : List[SingleData]
the list of all SingleData to sum.
new_index : list
the new_index of new SingleData.
fill_value : float
fill the missing values or replace np.nan.
Returns
-------
SingleData
... | sum_by_index | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def _convert_type(self, item):
"""
After user creates indices with Type A, user may query data with other types with the same info.
This method try to make type conversion and make query sane rather than raising KeyError strictly
Parameters
----------
item :
... |
After user creates indices with Type A, user may query data with other types with the same info.
This method try to make type conversion and make query sane rather than raising KeyError strictly
Parameters
----------
item :
The item to query index
| _convert_type | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def index(self, item) -> int:
"""
Given the index value, get the integer index
Parameters
----------
item :
The item to query
Returns
-------
int:
The index of the item
Raises
------
KeyError:
... |
Given the index value, get the integer index
Parameters
----------
item :
The item to query
Returns
-------
int:
The index of the item
Raises
------
KeyError:
If the query item does not exist
| index | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def sort(self) -> Tuple["Index", np.ndarray]:
"""
sort the index
Returns
-------
Tuple["Index", np.ndarray]:
the sorted Index and the changed index
"""
sorted_idx = np.argsort(self.idx_list)
idx = Index(self.idx_list[sorted_idx])
idx._... |
sort the index
Returns
-------
Tuple["Index", np.ndarray]:
the sorted Index and the changed index
| sort | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def proc_idx_l(indices: List[Union[List, pd.Index, Index]], data_shape: Tuple = None) -> List[Index]:
"""process the indices from user and output a list of `Index`"""
res = []
for i, idx in enumerate(indices):
res.append(Index(data_shape[i] if len(idx) == 0 else idx))
return ... | process the indices from user and output a list of `Index` | proc_idx_l | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
def _slc_convert(self, index: Index, indexing: slice) -> slice:
"""
convert value-based indexing to integer-based indexing.
Parameters
----------
index : Index
index data.
indexing : slice
value based indexing data with slice type for indexing.
... |
convert value-based indexing to integer-based indexing.
Parameters
----------
index : Index
index data.
indexing : slice
value based indexing data with slice type for indexing.
Returns
-------
slice:
the integer based... | _slc_convert | python | microsoft/qlib | qlib/utils/index_data.py | https://github.com/microsoft/qlib/blob/master/qlib/utils/index_data.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.