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 collect_data(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
strategy: Union[str, dict, object, Path],
executor: Union[str, dict, object, Path],
benchmark: str = "SH000300",
account: Union[float, int, dict] = 1e9,
exchange_kwargs: dict = {},
pos_type: str =... | initialize the strategy and executor, then collect the trade decision data for rl training
please refer to the docs of the backtest for the explanation of the parameters
Yields
-------
object
trade decision
| collect_data | python | microsoft/qlib | qlib/backtest/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py | MIT |
def format_decisions(
decisions: List[BaseTradeDecision],
) -> Optional[Tuple[str, List[Tuple[BaseTradeDecision, Union[Tuple, None]]]]]:
"""
format the decisions collected by `qlib.backtest.collect_data`
The decisions will be organized into a tree-like structure.
Parameters
----------
decis... |
format the decisions collected by `qlib.backtest.collect_data`
The decisions will be organized into a tree-like structure.
Parameters
----------
decisions : List[BaseTradeDecision]
decisions collected by `qlib.backtest.collect_data`
Returns
-------
Tuple[str, List[Tuple[BaseTr... | format_decisions | python | microsoft/qlib | qlib/backtest/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py | MIT |
def risk_analysis(r, N: int = None, freq: str = "day", mode: Literal["sum", "product"] = "sum"):
"""Risk Analysis
NOTE:
The calculation of annualized return is different from the definition of annualized return.
It is implemented by design.
Qlib tries to cumulate returns by summation instead of prod... | Risk Analysis
NOTE:
The calculation of annualized return is different from the definition of annualized return.
It is implemented by design.
Qlib tries to cumulate returns by summation instead of production to avoid the cumulated curve being skewed exponentially.
All the calculation of annualized re... | risk_analysis | python | microsoft/qlib | qlib/contrib/evaluate.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate.py | MIT |
def indicator_analysis(df, method="mean"):
"""analyze statistical time-series indicators of trading
Parameters
----------
df : pandas.DataFrame
columns: like ['pa', 'pos', 'ffr', 'deal_amount', 'value'].
Necessary fields:
- 'pa' is the price advantage in trade indica... | analyze statistical time-series indicators of trading
Parameters
----------
df : pandas.DataFrame
columns: like ['pa', 'pos', 'ffr', 'deal_amount', 'value'].
Necessary fields:
- 'pa' is the price advantage in trade indicators
- 'pos' is the positive rate ... | indicator_analysis | python | microsoft/qlib | qlib/contrib/evaluate.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate.py | MIT |
def _get_position_value_from_df(evaluate_date, position, close_data_df):
"""Get position value by existed close data df
close_data_df:
pd.DataFrame
multi-index
close_data_df['$close'][stock_id][evaluate_date]: close price for (stock_id, evaluate_date)
position:
same in get_po... | Get position value by existed close data df
close_data_df:
pd.DataFrame
multi-index
close_data_df['$close'][stock_id][evaluate_date]: close price for (stock_id, evaluate_date)
position:
same in get_position_value()
| _get_position_value_from_df | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_position_value(evaluate_date, position):
"""sum of close*amount
get value of position
use close price
positions:
{
Timestamp('2016-01-05 00:00:00'):
{
'SH600022':
{
'amount':100.00,
'pr... | sum of close*amount
get value of position
use close price
positions:
{
Timestamp('2016-01-05 00:00:00'):
{
'SH600022':
{
'amount':100.00,
'price':12.00
},
'cash':10... | get_position_value | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_daily_return_series_from_positions(positions, init_asset_value):
"""Parameters
generate daily return series from position view
positions: positions generated by strategy
init_asset_value : init asset value
return: pd.Series of daily return , return_series[date] = daily return rate
"""
... | Parameters
generate daily return series from position view
positions: positions generated by strategy
init_asset_value : init asset value
return: pd.Series of daily return , return_series[date] = daily return rate
| get_daily_return_series_from_positions | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_annual_return_from_positions(positions, init_asset_value):
"""Annualized Returns
p_r = (p_end / p_start)^{(250/n)} - 1
p_r annual return
p_end final value
p_start init value
n days of backtest
"""
date_range_list = sorted(list(positions.keys()))
end_time = date... | Annualized Returns
p_r = (p_end / p_start)^{(250/n)} - 1
p_r annual return
p_end final value
p_start init value
n days of backtest
| get_annual_return_from_positions | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_annaul_return_from_return_series(r, method="ci"):
"""Risk Analysis from daily return series
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
"""
mean = r.mean()
annual ... | Risk Analysis from daily return series
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
| get_annaul_return_from_return_series | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_sharpe_ratio_from_return_series(r, risk_free_rate=0.00, method="ci"):
"""Risk Analysis
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
risk_free_rate : float
risk_free... | Risk Analysis
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
risk_free_rate : float
risk_free_rate, default as 0.00, can set as 0.03 etc
| get_sharpe_ratio_from_return_series | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_max_drawdown_from_series(r):
"""Risk Analysis from asset value
cumprod way
Parameters
----------
r : pandas.Series
daily return series
"""
# mdd = ((r.cumsum() - r.cumsum().cummax()) / (1 + r.cumsum().cummax())).min()
mdd = (((1 + r).cumprod() - (1 + r).cumprod().cumma... | Risk Analysis from asset value
cumprod way
Parameters
----------
r : pandas.Series
daily return series
| get_max_drawdown_from_series | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_beta(r, b):
"""Risk Analysis beta
Parameters
----------
r : pandas.Series
daily return series of strategy
b : pandas.Series
daily return series of baseline
"""
cov_r_b = np.cov(r, b)
var_b = np.var(b)
return cov_r_b / var_b | Risk Analysis beta
Parameters
----------
r : pandas.Series
daily return series of strategy
b : pandas.Series
daily return series of baseline
| get_beta | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def _create_ts_slices(index, seq_len):
"""
create time series slices from pandas index
Args:
index (pd.MultiIndex): pandas multiindex with <instrument, datetime> order
seq_len (int): sequence length
"""
assert isinstance(index, pd.MultiIndex), "unsupported index type"
assert seq... |
create time series slices from pandas index
Args:
index (pd.MultiIndex): pandas multiindex with <instrument, datetime> order
seq_len (int): sequence length
| _create_ts_slices | python | microsoft/qlib | qlib/contrib/data/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/dataset.py | MIT |
def _get_date_parse_fn(target):
"""get date parse function
This method is used to parse date arguments as target type.
Example:
get_date_parse_fn('20120101')('2017-01-01') => '20170101'
get_date_parse_fn(20120101)('2017-01-01') => 20170101
"""
if isinstance(target, int):
d... | get date parse function
This method is used to parse date arguments as target type.
Example:
get_date_parse_fn('20120101')('2017-01-01') => '20170101'
get_date_parse_fn(20120101)('2017-01-01') => 20170101
| _get_date_parse_fn | python | microsoft/qlib | qlib/contrib/data/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/dataset.py | MIT |
def _maybe_padding(x, seq_len, zeros=None):
"""padding 2d <time * feature> data with zeros
Args:
x (np.ndarray): 2d data with shape <time * feature>
seq_len (int): target sequence length
zeros (np.ndarray): zeros with shape <seq_len * feature>
"""
assert seq_len > 0, "sequence l... | padding 2d <time * feature> data with zeros
Args:
x (np.ndarray): 2d data with shape <time * feature>
seq_len (int): target sequence length
zeros (np.ndarray): zeros with shape <seq_len * feature>
| _maybe_padding | python | microsoft/qlib | qlib/contrib/data/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/dataset.py | MIT |
def get_pre_datasets(self):
"""Generate the training, validation and test datasets for prediction
Returns:
Tuple[BaseDataset, BaseDataset, BaseDataset]: The training and test datasets
"""
dict_feature_path = self.feature_conf["path"]
train_feature_path = dict_featur... | Generate the training, validation and test datasets for prediction
Returns:
Tuple[BaseDataset, BaseDataset, BaseDataset]: The training and test datasets
| get_pre_datasets | python | microsoft/qlib | qlib/contrib/data/highfreq_provider.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/highfreq_provider.py | MIT |
def get_feature_config(
config={
"kbar": {},
"price": {
"windows": [0],
"feature": ["OPEN", "HIGH", "LOW", "VWAP"],
},
"rolling": {},
}
):
"""create factors from config
config = {
'kbar': {},... | create factors from config
config = {
'kbar': {}, # whether to use some hard-code kbar features
'price': { # whether to use raw price features
'windows': [0, 1, 2, 3, 4], # use price at n days ago
'feature': ['OPEN', 'HIGH', 'LOW'] # which price field to ... | get_feature_config | python | microsoft/qlib | qlib/contrib/data/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/loader.py | MIT |
def __init__(self, df_dict: Dict[str, pd.DataFrame], join: str, skip_align=False):
"""
initialize the data based on the dataframe dictionary
Parameters
----------
df_dict : Dict[str, pd.DataFrame]
dataframe dictionary
join : str
how to join the da... |
initialize the data based on the dataframe dictionary
Parameters
----------
df_dict : Dict[str, pd.DataFrame]
dataframe dictionary
join : str
how to join the data
It will reindex the dataframe based on the join key.
If join is Non... | __init__ | python | microsoft/qlib | qlib/contrib/data/utils/sepdf.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/utils/sepdf.py | MIT |
def apply_each(self, method: str, skip_align=True, *args, **kwargs):
"""
Assumptions:
- inplace methods will return None
"""
inplace = False
df_dict = {}
for k, df in self._df_dict.items():
df_dict[k] = getattr(df, method)(*args, **kwargs)
... |
Assumptions:
- inplace methods will return None
| apply_each | python | microsoft/qlib | qlib/contrib/data/utils/sepdf.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/utils/sepdf.py | MIT |
def calc_long_short_prec(
pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropna=False, is_alpha=False
) -> Tuple[pd.Series, pd.Series]:
"""
calculate the precision for long and short operation
:param pred/label: index is **pd.MultiIndex**, index name is **[datetime, ins... |
calculate the precision for long and short operation
:param pred/label: index is **pd.MultiIndex**, index name is **[datetime, instruments]**; columns names is **[score]**.
.. code-block:: python
score
datetime instrume... | calc_long_short_prec | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def calc_long_short_return(
pred: pd.Series,
label: pd.Series,
date_col: str = "datetime",
quantile: float = 0.2,
dropna: bool = False,
) -> Tuple[pd.Series, pd.Series]:
"""
calculate long-short return
Note:
`label` must be raw stock returns.
Parameters
----------
p... |
calculate long-short return
Note:
`label` must be raw stock returns.
Parameters
----------
pred : pd.Series
stock predictions
label : pd.Series
stock returns
date_col : str
datetime index name
quantile : float
long-short quantile
Returns
... | calc_long_short_return | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def pred_autocorr_all(pred_dict, n_jobs=-1, **kwargs):
"""
calculate auto correlation for pred_dict
Parameters
----------
pred_dict : dict
A dict like {<method_name>: <prediction>}
kwargs :
all these arguments will be passed into pred_autocorr
"""
ac_dict = {}
for k... |
calculate auto correlation for pred_dict
Parameters
----------
pred_dict : dict
A dict like {<method_name>: <prediction>}
kwargs :
all these arguments will be passed into pred_autocorr
| pred_autocorr_all | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def calc_ic(pred: pd.Series, label: pd.Series, date_col="datetime", dropna=False) -> (pd.Series, pd.Series):
"""calc_ic.
Parameters
----------
pred :
pred
label :
label
date_col :
date_col
Returns
-------
(pd.Series, pd.Series)
ic and rank ic
"""... | calc_ic.
Parameters
----------
pred :
pred
label :
label
date_col :
date_col
Returns
-------
(pd.Series, pd.Series)
ic and rank ic
| calc_ic | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def calc_all_ic(pred_dict_all, label, date_col="datetime", dropna=False, n_jobs=-1):
"""calc_all_ic.
Parameters
----------
pred_dict_all :
A dict like {<method_name>: <prediction>}
label:
A pd.Series of label values
Returns
-------
{'Q2+IND_z': {'ic': <ic series like>
... | calc_all_ic.
Parameters
----------
pred_dict_all :
A dict like {<method_name>: <prediction>}
label:
A pd.Series of label values
Returns
-------
{'Q2+IND_z': {'ic': <ic series like>
2016-01-04 -0.057407
...
... | calc_all_ic | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def setup(self, trainer=TrainerR, trainer_kwargs={}):
"""
after running this function `self.data_ic_df` will become set.
Each col represents a data.
Each row represents the Timestamp of performance of that data.
For example,
.. code-block:: python
... |
after running this function `self.data_ic_df` will become set.
Each col represents a data.
Each row represents the Timestamp of performance of that data.
For example,
.. code-block:: python
2021-06-21 2021-06-04 2021-05-21 2021-05-07 2021-04-20 2021-04-0... | setup | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def update(self):
"""update the data for online trading"""
# TODO:
# when new data are totally(including label) available
# - update the prediction
# - update the data similarity map(if applied) | update the data for online trading | update | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def __init__(self, task: dict, meta_info: pd.DataFrame, mode: str = MetaTask.PROC_MODE_FULL, fill_method="max"):
"""
The description of the processed data
time_perf: A array with shape <hist_step_n * step, data pieces> -> data piece performance
time_belong: A array with sh... |
The description of the processed data
time_perf: A array with shape <hist_step_n * step, data pieces> -> data piece performance
time_belong: A array with shape <sample, data pieces> -> belong or not (1. or 0.)
array([[1., 0., 0., ..., 0., 0., 0.],
... | __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def __init__(
self,
*,
task_tpl: Union[dict, list],
step: int,
trunc_days: int = None,
rolling_ext_days: int = 0,
exp_name: Union[str, InternalData],
segments: Union[Dict[Text, Tuple], float, str],
hist_step_n: int = 10,
task_mode: str = Me... |
A dataset for meta model.
Parameters
----------
task_tpl : Union[dict, list]
Decide what tasks are used.
- dict : the task template, the prepared task is generated with `step`, `trunc_days` and `RollingGen`
- list : when list, use the list of tasks d... | __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def _prepare_meta_ipt(self, task) -> pd.DataFrame:
"""
Please refer to `self.internal_data.setup` for detailed information about `self.internal_data.data_ic_df`
Indices with format below can be successfully sliced by `ic_df.loc[:end, pd.IndexSlice[:, :end]]`
2021-06-21 2021-06-... |
Please refer to `self.internal_data.setup` for detailed information about `self.internal_data.data_ic_df`
Indices with format below can be successfully sliced by `ic_df.loc[:end, pd.IndexSlice[:, :end]]`
2021-06-21 2021-06-04 .. 2021-03-22 2021-03-08
2021-07-02 2021-06-... | _prepare_meta_ipt | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def mask_overlap(s):
"""
mask overlap information
data after self.name[end] with self.trunc_days that contains future info are also considered as overlap info
Approximately the diagnal + horizon length of data are masked.
"""
start, end = s.name
... |
mask overlap information
data after self.name[end] with self.trunc_days that contains future info are also considered as overlap info
Approximately the diagnal + horizon length of data are masked.
| mask_overlap | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def __init__(
self,
step,
hist_step_n,
clip_method="tanh",
clip_weight=2.0,
criterion="ic_loss",
lr=0.0001,
max_epoch=100,
seed=43,
alpha=0.0,
loss_skip_thresh=50,
):
"""
loss_skip_size: int
The numbe... |
loss_skip_size: int
The number of threshold to skip the loss calculation for each day.
| __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/model.py | MIT |
def fit(self, meta_dataset: MetaDatasetDS):
"""
The meta-learning-based data selection interacts directly with meta-dataset due to the close-form proxy measurement.
Parameters
----------
meta_dataset : MetaDatasetDS
The meta-model takes the meta-dataset for its train... |
The meta-learning-based data selection interacts directly with meta-dataset due to the close-form proxy measurement.
Parameters
----------
meta_dataset : MetaDatasetDS
The meta-model takes the meta-dataset for its training process.
| fit | python | microsoft/qlib | qlib/contrib/meta/data_selection/model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/model.py | MIT |
def __init__(self, step, hist_step_n, clip_weight=None, clip_method="tanh", alpha: float = 0.0):
"""
Parameters
----------
alpha : float
the regularization for sub model (useful when align meta model with linear submodel)
"""
super().__init__()
self.st... |
Parameters
----------
alpha : float
the regularization for sub model (useful when align meta model with linear submodel)
| __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/net.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/net.py | MIT |
def forward(self, X, y, time_perf, time_belong, X_test, ignore_weight=False):
"""Please refer to the docs of MetaTaskDS for the description of the variables"""
weights = self.get_sample_weights(X, time_perf, time_belong, ignore_weight=ignore_weight)
X_w = X.T * weights.view(1, -1)
theta ... | Please refer to the docs of MetaTaskDS for the description of the variables | forward | python | microsoft/qlib | qlib/contrib/meta/data_selection/net.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/net.py | MIT |
def forward(self, pred, y, idx):
"""forward.
FIXME:
- Some times it will be a slightly different from the result from `pandas.corr()`
- It may be caused by the precision problem of model;
:param pred:
:param y:
:param idx: Assume the level of the idx is (date, in... | forward.
FIXME:
- Some times it will be a slightly different from the result from `pandas.corr()`
- It may be caused by the precision problem of model;
:param pred:
:param y:
:param idx: Assume the level of the idx is (date, inst), and it is sorted
| forward | python | microsoft/qlib | qlib/contrib/meta/data_selection/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/utils.py | MIT |
def preds_to_weight_with_clamp(preds, clip_weight=None, clip_method="tanh"):
"""
Clip the weights.
Parameters
----------
clip_weight: float
The clip threshold.
clip_method: str
The clip method. Current available: "clamp", "tanh", and "sigmoid".
"""
if clip_weight is not ... |
Clip the weights.
Parameters
----------
clip_weight: float
The clip threshold.
clip_method: str
The clip method. Current available: "clamp", "tanh", and "sigmoid".
| preds_to_weight_with_clamp | python | microsoft/qlib | qlib/contrib/meta/data_selection/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/utils.py | MIT |
def get_feature_importance(self, *args, **kwargs) -> pd.Series:
"""get feature importance
Notes
-----
parameters references:
https://catboost.ai/docs/concepts/python-reference_catboost_get_feature_importance.html#python-reference_catboost_get_feature_importance
"... | get feature importance
Notes
-----
parameters references:
https://catboost.ai/docs/concepts/python-reference_catboost_get_feature_importance.html#python-reference_catboost_get_feature_importance
| get_feature_importance | python | microsoft/qlib | qlib/contrib/model/catboost_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/catboost_model.py | MIT |
def sample_reweight(self, loss_curve, loss_values, k_th):
"""
the SR module of Double Ensemble
:param loss_curve: the shape is NxT
the loss curve for the previous sub-model, where the element (i, t) if the error on the i-th sample
after the t-th iteration in the training of the p... |
the SR module of Double Ensemble
:param loss_curve: the shape is NxT
the loss curve for the previous sub-model, where the element (i, t) if the error on the i-th sample
after the t-th iteration in the training of the previous sub-model.
:param loss_values: the shape is N
... | sample_reweight | python | microsoft/qlib | qlib/contrib/model/double_ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/double_ensemble.py | MIT |
def feature_selection(self, df_train, loss_values):
"""
the FS module of Double Ensemble
:param df_train: the shape is NxF
:param loss_values: the shape is N
the loss of the current ensemble on the i-th sample.
:return: res_feat: in the form of pandas.Index
"""
... |
the FS module of Double Ensemble
:param df_train: the shape is NxF
:param loss_values: the shape is N
the loss of the current ensemble on the i-th sample.
:return: res_feat: in the form of pandas.Index
| feature_selection | python | microsoft/qlib | qlib/contrib/model/double_ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/double_ensemble.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/contrib/model/double_ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/double_ensemble.py | MIT |
def _prepare_data(self, dataset: DatasetH, reweighter=None) -> List[Tuple[lgb.Dataset, str]]:
"""
The motivation of current version is to make validation optional
- train segment is necessary;
"""
ds_l = []
assert "train" in dataset.segments
for key in ["train", "... |
The motivation of current version is to make validation optional
- train segment is necessary;
| _prepare_data | python | microsoft/qlib | qlib/contrib/model/gbdt.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/gbdt.py | MIT |
def finetune(self, dataset: DatasetH, num_boost_round=10, verbose_eval=20, reweighter=None):
"""
finetune model
Parameters
----------
dataset : DatasetH
dataset for finetuning
num_boost_round : int
number of round to finetune model
verbose... |
finetune model
Parameters
----------
dataset : DatasetH
dataset for finetuning
num_boost_round : int
number of round to finetune model
verbose_eval : int
verbose level
| finetune | python | microsoft/qlib | qlib/contrib/model/gbdt.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/gbdt.py | MIT |
def _cal_signal_metrics(self, y_test, l_cut, r_cut):
"""
Calcaute the signal metrics by daily level
"""
up_pre, down_pre = [], []
up_alpha_ll, down_alpha_ll = [], []
for date in y_test.index.get_level_values(0).unique():
df_res = y_test.loc[date].sort_values("... |
Calcaute the signal metrics by daily level
| _cal_signal_metrics | python | microsoft/qlib | qlib/contrib/model/highfreq_gdbt_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/highfreq_gdbt_model.py | MIT |
def hf_signal_test(self, dataset: DatasetH, threhold=0.2):
"""
Test the signal in high frequency test set
"""
if self.model is None:
raise ValueError("Model hasn't been trained yet")
df_test = dataset.prepare("test", col_set=["feature", "label"], data_key=DataHandlerL... |
Test the signal in high frequency test set
| hf_signal_test | python | microsoft/qlib | qlib/contrib/model/highfreq_gdbt_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/highfreq_gdbt_model.py | MIT |
def finetune(self, dataset: DatasetH, num_boost_round=10, verbose_eval=20):
"""
finetune model
Parameters
----------
dataset : DatasetH
dataset for finetuning
num_boost_round : int
number of round to finetune model
verbose_eval : int
... |
finetune model
Parameters
----------
dataset : DatasetH
dataset for finetuning
num_boost_round : int
number of round to finetune model
verbose_eval : int
verbose level
| finetune | python | microsoft/qlib | qlib/contrib/model/highfreq_gdbt_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/highfreq_gdbt_model.py | MIT |
def __init__(self, estimator="ols", alpha=0.0, fit_intercept=False, include_valid: bool = False):
"""
Parameters
----------
estimator : str
which estimator to use for linear regression
alpha : float
l1 or l2 regularization parameter
fit_intercept :... |
Parameters
----------
estimator : str
which estimator to use for linear regression
alpha : float
l1 or l2 regularization parameter
fit_intercept : bool
whether fit intercept
include_valid: bool
Should the validation data be... | __init__ | python | microsoft/qlib | qlib/contrib/model/linear.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/linear.py | MIT |
def calc_all_metrics(pred):
"""pred is a pandas dataframe that has two attributes: score (pred) and label (real)"""
res = {}
ic = pred.groupby(level="datetime", group_keys=False).apply(lambda x: x.label.corr(x.score))
rank_ic = pred.groupby(level="datetime", group_keys=False).apply(
... | pred is a pandas dataframe that has two attributes: score (pred) and label (real) | calc_all_metrics | python | microsoft/qlib | qlib/contrib/model/pytorch_adarnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_adarnn.py | MIT |
def __init__(self, loss_type="cosine", input_dim=512, GPU=0):
"""
Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
"""
self.loss_type = loss_type
self.input_dim = input_dim
self.device = torch.device("cuda:%d" % GPU if torch.cuda.is_available()... |
Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_adarnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_adarnn.py | MIT |
def compute(self, X, Y):
"""Compute adaptation loss
Arguments:
X {tensor} -- source matrix
Y {tensor} -- target matrix
Returns:
[tensor] -- transfer loss
"""
loss = None
if self.loss_type in ("mmd_lin", "mmd"):
mmdloss = M... | Compute adaptation loss
Arguments:
X {tensor} -- source matrix
Y {tensor} -- target matrix
Returns:
[tensor] -- transfer loss
| compute | python | microsoft/qlib | qlib/contrib/model/pytorch_adarnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_adarnn.py | MIT |
def __init__(self, gamma=0.1, gamma_clip=0.4, *args, **kwargs):
"""
A gradient reversal layer.
This layer has no parameters, and simply reverses the gradient
in the backward pass.
"""
super().__init__(*args, **kwargs)
self.gamma = gamma
self.gamma_clip = ... |
A gradient reversal layer.
This layer has no parameters, and simply reverses the gradient
in the backward pass.
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_add.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_add.py | MIT |
def _get_fl(self, data: torch.Tensor):
"""
get feature and label from data
- Handle the different data shape of time series and tabular data
Parameters
----------
data : torch.Tensor
input data which maybe 3 dimension or 2 dimension
- 3dim: [batch... |
get feature and label from data
- Handle the different data shape of time series and tabular data
Parameters
----------
data : torch.Tensor
input data which maybe 3 dimension or 2 dimension
- 3dim: [batch_size, time_step, feature_dim]
- 2dim:... | _get_fl | python | microsoft/qlib | qlib/contrib/model/pytorch_general_nn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_general_nn.py | MIT |
def __init__(self, input_dim, output_dim, kernel_size, device):
"""Build a basic CNN encoder
Parameters
----------
input_dim : int
The input dimension
output_dim : int
The output dimension
kernel_size : int
The size of convolutional ke... | Build a basic CNN encoder
Parameters
----------
input_dim : int
The input dimension
output_dim : int
The output dimension
kernel_size : int
The size of convolutional kernels
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def forward(self, x):
"""
Parameters
----------
x : torch.Tensor
input data
Returns
-------
torch.Tensor
Updated representations
"""
# input shape: [batch_size, seq_len*input_dim]
# output shape: [batch_size, seq_l... |
Parameters
----------
x : torch.Tensor
input data
Returns
-------
torch.Tensor
Updated representations
| forward | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def __init__(self, input_dim, output_dim, dup_num, rnn_layers, dropout, device):
"""Build K parallel RNNs
Parameters
----------
input_dim : int
The input dimension
output_dim : int
The output dimension
dup_num : int
The number of paral... | Build K parallel RNNs
Parameters
----------
input_dim : int
The input dimension
output_dim : int
The output dimension
dup_num : int
The number of parallel RNNs
rnn_layers: int
The number of RNN layers
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def forward(self, x):
"""
Parameters
----------
x : torch.Tensor
Input data
n_id : torch.Tensor
Node indices
Returns
-------
torch.Tensor
Updated representations
"""
# input shape: [batch_size, seq_len,... |
Parameters
----------
x : torch.Tensor
Input data
n_id : torch.Tensor
Node indices
Returns
-------
torch.Tensor
Updated representations
| forward | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def __init__(
self, cnn_input_dim, cnn_output_dim, cnn_kernel_size, rnn_output_dim, rnn_dup_num, rnn_layers, dropout, device
):
"""Build an encoder composed of CNN and KRNN
Parameters
----------
cnn_input_dim : int
The input dimension of CNN
cnn_output_di... | Build an encoder composed of CNN and KRNN
Parameters
----------
cnn_input_dim : int
The input dimension of CNN
cnn_output_dim : int
The output dimension of CNN
cnn_kernel_size : int
The size of convolutional kernels
rnn_output_dim : in... | __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def forward(self, x):
"""
Parameters
----------
x : torch.Tensor
Input data
n_id : torch.Tensor
Node indices
Returns
-------
torch.Tensor
Updated representations
"""
cnn_out = self.cnn_encoder(x)
... |
Parameters
----------
x : torch.Tensor
Input data
n_id : torch.Tensor
Node indices
Returns
-------
torch.Tensor
Updated representations
| forward | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def __init__(self, fea_dim, cnn_dim, cnn_kernel_size, rnn_dim, rnn_dups, rnn_layers, dropout, device, **params):
"""Build a KRNN model
Parameters
----------
fea_dim : int
The feature dimension
cnn_dim : int
The hidden dimension of CNN
cnn_kernel_s... | Build a KRNN model
Parameters
----------
fea_dim : int
The feature dimension
cnn_dim : int
The hidden dimension of CNN
cnn_kernel_size : int
The size of convolutional kernels
rnn_dim : int
The hidden dimension of KRNN
... | __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def _nn_predict(self, data, return_cpu=True):
"""Reusing predicting NN.
Scenarios
1) test inference (data may come from CPU and expect the output data is on CPU)
2) evaluation on training (data may come from GPU)
"""
if not isinstance(data, torch.Tensor):
if i... | Reusing predicting NN.
Scenarios
1) test inference (data may come from CPU and expect the output data is on CPU)
2) evaluation on training (data may come from GPU)
| _nn_predict | python | microsoft/qlib | qlib/contrib/model/pytorch_nn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_nn.py | MIT |
def __init__(
self,
fea_dim,
cnn_dim_1,
cnn_dim_2,
cnn_kernel_size,
rnn_dim_1,
rnn_dim_2,
rnn_dups,
rnn_layers,
dropout,
device,
**params,
):
"""Build a Sandwich model
Parameters
----------
... | Build a Sandwich model
Parameters
----------
fea_dim : int
The feature dimension
cnn_dim_1 : int
The hidden dimension of the first CNN
cnn_dim_2 : int
The hidden dimension of the second CNN
cnn_kernel_size : int
The size of... | __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_sandwich.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_sandwich.py | MIT |
def __init__(
self,
d_feat=158,
out_dim=64,
final_out_dim=1,
batch_size=4096,
n_d=64,
n_a=64,
n_shared=2,
n_ind=2,
n_steps=5,
n_epochs=100,
pretrain_n_epochs=50,
relax=1.3,
vbs=2048,
seed=993,
... |
TabNet model for Qlib
Args:
ps: probability to generate the bernoulli mask
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_tabnet.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tabnet.py | MIT |
def pretrain_loss_fn(self, f_hat, f, S):
"""
Pretrain loss function defined in the original paper, read "Tabular self-supervised learning" in https://arxiv.org/pdf/1908.07442.pdf
"""
down_mean = torch.mean(f, dim=0)
down = torch.sqrt(torch.sum(torch.square(f - down_mean), dim=0))... |
Pretrain loss function defined in the original paper, read "Tabular self-supervised learning" in https://arxiv.org/pdf/1908.07442.pdf
| pretrain_loss_fn | python | microsoft/qlib | qlib/contrib/model/pytorch_tabnet.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tabnet.py | MIT |
def __init__(self, inp_dim, out_dim, n_shared, n_ind, vbs, n_steps):
"""
TabNet decoder that is used in pre-training
"""
super().__init__()
self.out_dim = out_dim
if n_shared > 0:
self.shared = nn.ModuleList()
self.shared.append(nn.Linear(inp_dim, ... |
TabNet decoder that is used in pre-training
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_tabnet.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tabnet.py | MIT |
def __init__(self, inp_dim=6, out_dim=6, n_d=64, n_a=64, n_shared=2, n_ind=2, n_steps=5, relax=1.2, vbs=1024):
"""
TabNet AKA the original encoder
Args:
n_d: dimension of the features used to calculate the final results
n_a: dimension of the features input to the attenti... |
TabNet AKA the original encoder
Args:
n_d: dimension of the features used to calculate the final results
n_a: dimension of the features input to the attention transformer of the next step
n_shared: numbr of shared steps in feature transformer(optional)
n... | __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_tabnet.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tabnet.py | MIT |
def shoot_infs(inp_tensor):
"""Replaces inf by maximum of tensor"""
mask_inf = torch.isinf(inp_tensor)
ind_inf = torch.nonzero(mask_inf, as_tuple=False)
if len(ind_inf) > 0:
for ind in ind_inf:
if len(ind) == 2:
inp_tensor[ind[0], ind[1]] = 0
elif len(ind)... | Replaces inf by maximum of tensor | shoot_infs | python | microsoft/qlib | qlib/contrib/model/pytorch_tra.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tra.py | MIT |
def transport_sample(all_preds, label, choice, prob, hist_loss, count, transport_method, alpha, training=False):
"""
sample-wise transport
Args:
all_preds (torch.Tensor): predictions from all predictors, [sample x states]
label (torch.Tensor): label, [sample]
choice (torch.Tensor): ... |
sample-wise transport
Args:
all_preds (torch.Tensor): predictions from all predictors, [sample x states]
label (torch.Tensor): label, [sample]
choice (torch.Tensor): gumbel softmax choice, [sample x states]
prob (torch.Tensor): router predicted probility, [sample x states]
... | transport_sample | python | microsoft/qlib | qlib/contrib/model/pytorch_tra.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tra.py | MIT |
def transport_daily(all_preds, label, choice, prob, hist_loss, count, transport_method, alpha, training=False):
"""
daily transport
Args:
all_preds (torch.Tensor): predictions from all predictors, [sample x states]
label (torch.Tensor): label, [sample]
choice (torch.Tensor): gumbel ... |
daily transport
Args:
all_preds (torch.Tensor): predictions from all predictors, [sample x states]
label (torch.Tensor): label, [sample]
choice (torch.Tensor): gumbel softmax choice, [days x states]
prob (torch.Tensor): router predicted probility, [days x states]
hist_l... | transport_daily | python | microsoft/qlib | qlib/contrib/model/pytorch_tra.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tra.py | MIT |
def load_state_dict_unsafe(model, state_dict):
"""
Load state dict to provided model while ignore exceptions.
"""
missing_keys = []
unexpected_keys = []
error_msgs = []
# copy state_dict so _load_from_state_dict can modify it
metadata = getattr(state_dict, "_metadata", None)
state_... |
Load state dict to provided model while ignore exceptions.
| load_state_dict_unsafe | python | microsoft/qlib | qlib/contrib/model/pytorch_tra.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_tra.py | MIT |
def count_parameters(models_or_parameters, unit="m"):
"""
This function is to obtain the storage size unit of a (or multiple) models.
Parameters
----------
models_or_parameters : PyTorch model(s) or a list of parameters.
unit : the storage size unit.
Returns
-------
The number of p... |
This function is to obtain the storage size unit of a (or multiple) models.
Parameters
----------
models_or_parameters : PyTorch model(s) or a list of parameters.
unit : the storage size unit.
Returns
-------
The number of parameters of the given model(s) or parameters.
| count_parameters | python | microsoft/qlib | qlib/contrib/model/pytorch_utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_utils.py | MIT |
def __init__(self, user_data_path, save_report=True):
"""
This module is designed to manager the users in online system
all users' data were assumed to be saved in user_data_path
Parameter
user_data_path : string
data path that all users' data were... |
This module is designed to manager the users in online system
all users' data were assumed to be saved in user_data_path
Parameter
user_data_path : string
data path that all users' data were saved in
variables:
data_path : string
... | __init__ | python | microsoft/qlib | qlib/contrib/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/manager.py | MIT |
def load_users(self):
"""
load all users' data into manager
"""
self.users = {}
self.user_record = pd.read_csv(self.users_file, index_col=0)
for user_id in self.user_record.index:
self.users[user_id] = self.load_user(user_id) |
load all users' data into manager
| load_users | python | microsoft/qlib | qlib/contrib/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/manager.py | MIT |
def load_user(self, user_id):
"""
return a instance of User() represents a user to be processed
Parameter
user_id : string
:return
user : User()
"""
account_path = self.data_path / user_id
strategy_file = self.data_path / us... |
return a instance of User() represents a user to be processed
Parameter
user_id : string
:return
user : User()
| load_user | python | microsoft/qlib | qlib/contrib/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/manager.py | MIT |
def save_user_data(self, user_id):
"""
save a instance of User() to user data path
Parameter
user_id : string
"""
if not user_id in self.users:
raise ValueError("Cannot find user {}".format(user_id))
self.users[user_id].account.save_account... |
save a instance of User() to user data path
Parameter
user_id : string
| save_user_data | python | microsoft/qlib | qlib/contrib/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/manager.py | MIT |
def add_user(self, user_id, config_file, add_date):
"""
add the new user {user_id} into user data
will create a new folder named "{user_id}" in user data path
Parameter
user_id : string
init_cash : int
config_file : str/pathlib.Path()
... |
add the new user {user_id} into user data
will create a new folder named "{user_id}" in user data path
Parameter
user_id : string
init_cash : int
config_file : str/pathlib.Path()
path of config file
| add_user | python | microsoft/qlib | qlib/contrib/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/manager.py | MIT |
def remove_user(self, user_id):
"""
remove user {user_id} in current user dataset
will delete the folder "{user_id}" in user data path
:param
user_id : string
"""
user_path = self.data_path / user_id
if not user_path.exists():
raise... |
remove user {user_id} in current user dataset
will delete the folder "{user_id}" in user data path
:param
user_id : string
| remove_user | python | microsoft/qlib | qlib/contrib/online/manager.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/manager.py | MIT |
def __init__(self, client: str):
"""
Parameters
----------
client: str
The qlib client config file(.yaml)
"""
self.logger = get_module_logger("online operator", level=logging.INFO)
self.client = client |
Parameters
----------
client: str
The qlib client config file(.yaml)
| __init__ | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def init(client, path, date=None):
"""Initial UserManager(), get predict date and trade date
Parameters
----------
client: str
The qlib client config file(.yaml)
path : str
Path to save user account.
date : str (YYYY-MM-DD)
... | Initial UserManager(), get predict date and trade date
Parameters
----------
client: str
The qlib client config file(.yaml)
path : str
Path to save user account.
date : str (YYYY-MM-DD)
Trade date, when the generated ord... | init | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def add_user(self, id, config, path, date):
"""Add a new user into the a folder to run 'online' module.
Parameters
----------
id : str
User id, should be unique.
config : str
The file path (yaml) of user config
path : str
Path to save ... | Add a new user into the a folder to run 'online' module.
Parameters
----------
id : str
User id, should be unique.
config : str
The file path (yaml) of user config
path : str
Path to save user account.
date : str (YYYY-MM-DD)
... | add_user | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def generate(self, date, path):
"""Generate order list that will be traded at 'date'.
Parameters
----------
date : str (YYYY-MM-DD)
Trade date, when the generated order list will be traded.
path : str
Path to save user account.
"""
um, pre... | Generate order list that will be traded at 'date'.
Parameters
----------
date : str (YYYY-MM-DD)
Trade date, when the generated order list will be traded.
path : str
Path to save user account.
| generate | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def execute(self, date, exchange_config, path):
"""Execute the orderlist at 'date'.
Parameters
----------
date : str (YYYY-MM-DD)
Trade date, that the generated order list will be traded.
exchange_config: str
The file path (yaml) of exchange c... | Execute the orderlist at 'date'.
Parameters
----------
date : str (YYYY-MM-DD)
Trade date, that the generated order list will be traded.
exchange_config: str
The file path (yaml) of exchange config
path : str
Path to save use... | execute | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def update(self, date, path, type="SIM"):
"""Update account at 'date'.
Parameters
----------
date : str (YYYY-MM-DD)
Trade date, that the generated order list will be traded.
path : str
Path to save user account.
type : str
which execu... | Update account at 'date'.
Parameters
----------
date : str (YYYY-MM-DD)
Trade date, that the generated order list will be traded.
path : str
Path to save user account.
type : str
which executor was been used to execute the order list
... | update | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def simulate(self, id, config, exchange_config, start, end, path, bench="SH000905"):
"""Run the ( generate_trade_decision -> execute_order_list -> update_account) process everyday
from start date to end date.
Parameters
----------
id : str
user id, need to be uni... | Run the ( generate_trade_decision -> execute_order_list -> update_account) process everyday
from start date to end date.
Parameters
----------
id : str
user id, need to be unique
config : str
The file path (yaml) of user config
exchange_config... | simulate | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def show(self, id, path, bench="SH000905"):
"""show the newly report (mean, std, information_ratio, annualized_return)
Parameters
----------
id : str
user id, need to be unique
path : str
Path to save user account.
bench : str
The benc... | show the newly report (mean, std, information_ratio, annualized_return)
Parameters
----------
id : str
user id, need to be unique
path : str
Path to save user account.
bench : str
The benchmark that our result compared with.
'SH000... | show | python | microsoft/qlib | qlib/contrib/online/operator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/operator.py | MIT |
def __init__(self, account, strategy, model, verbose=False):
"""
A user in online system, which contains account, strategy and model three module.
Parameter
account : Account()
strategy :
a strategy instance
model :
... |
A user in online system, which contains account, strategy and model three module.
Parameter
account : Account()
strategy :
a strategy instance
model :
a model instance
report_save_path : string
... | __init__ | python | microsoft/qlib | qlib/contrib/online/user.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/user.py | MIT |
def init_state(self, date):
"""
init state when each trading date begin
Parameter
date : pd.Timestamp
"""
self.account.init_state(today=date)
self.strategy.init_state(trade_date=date, model=self.model, account=self.account)
return |
init state when each trading date begin
Parameter
date : pd.Timestamp
| init_state | python | microsoft/qlib | qlib/contrib/online/user.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/user.py | MIT |
def get_latest_trading_date(self):
"""
return the latest trading date for user {user_id}
Parameter
user_id : string
:return
date : string (e.g '2018-10-08')
"""
if not self.account.last_trade_date:
return None
re... |
return the latest trading date for user {user_id}
Parameter
user_id : string
:return
date : string (e.g '2018-10-08')
| get_latest_trading_date | python | microsoft/qlib | qlib/contrib/online/user.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/user.py | MIT |
def showReport(self, benchmark="SH000905"):
"""
show the newly report (mean, std, information_ratio, annualized_return)
Parameter
benchmark : string
bench that to be compared, 'SH000905' for csi500
"""
bench = D.features([benchmark], ["$cha... |
show the newly report (mean, std, information_ratio, annualized_return)
Parameter
benchmark : string
bench that to be compared, 'SH000905' for csi500
| showReport | python | microsoft/qlib | qlib/contrib/online/user.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/user.py | MIT |
def load_instance(file_path):
"""
load a pickle file
Parameter
file_path : string / pathlib.Path()
path of file to be loaded
:return
An instance loaded from file
"""
file_path = pathlib.Path(file_path)
if not file_path.exists():
raise Va... |
load a pickle file
Parameter
file_path : string / pathlib.Path()
path of file to be loaded
:return
An instance loaded from file
| load_instance | python | microsoft/qlib | qlib/contrib/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/utils.py | MIT |
def save_instance(instance, file_path):
"""
save(dump) an instance to a pickle file
Parameter
instance :
data to be dumped
file_path : string / pathlib.Path()
path of file to be dumped
"""
file_path = pathlib.Path(file_path)
with file_p... |
save(dump) an instance to a pickle file
Parameter
instance :
data to be dumped
file_path : string / pathlib.Path()
path of file to be dumped
| save_instance | python | microsoft/qlib | qlib/contrib/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/utils.py | MIT |
def prepare(um, today, user_id, exchange_config=None):
"""
1. Get the dates that need to do trading till today for user {user_id}
dates[0] indicate the latest trading date of User{user_id},
if User{user_id} haven't do trading before, than dates[0] presents the init date of User{user_id}.
2. ... |
1. Get the dates that need to do trading till today for user {user_id}
dates[0] indicate the latest trading date of User{user_id},
if User{user_id} haven't do trading before, than dates[0] presents the init date of User{user_id}.
2. Set the exchange with exchange_config file
Parameter
... | prepare | python | microsoft/qlib | qlib/contrib/online/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/online/utils.py | MIT |
def get_calendar_day(freq="1min", future=False):
"""
Load High-Freq Calendar Date Using Memcache.
!!!NOTE: Loading the calendar is quite slow. So loading calendar before start multiprocessing will make it faster.
Parameters
----------
freq : str
frequency of read calendar file.
futu... |
Load High-Freq Calendar Date Using Memcache.
!!!NOTE: Loading the calendar is quite slow. So loading calendar before start multiprocessing will make it faster.
Parameters
----------
freq : str
frequency of read calendar file.
future : bool
whether including future trading day.
... | get_calendar_day | python | microsoft/qlib | qlib/contrib/ops/high_freq.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/ops/high_freq.py | MIT |
def get_calendar_minute(freq="day", future=False):
"""Load High-Freq Calendar Minute Using Memcache"""
flag = f"{freq}_future_{future}_day"
if flag in H["c"]:
_calendar = H["c"][flag]
else:
_calendar = np.array(list(map(lambda x: x.minute // 30, Cal.load_calendar(freq, future))))
... | Load High-Freq Calendar Minute Using Memcache | get_calendar_minute | python | microsoft/qlib | qlib/contrib/ops/high_freq.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/ops/high_freq.py | MIT |
def __init__(
self, df: pd.DataFrame = None, layout: dict = None, graph_kwargs: dict = None, name_dict: dict = None, **kwargs
):
"""
:param df:
:param layout:
:param graph_kwargs:
:param name_dict:
:param kwargs:
layout: dict
go.La... |
:param df:
:param layout:
:param graph_kwargs:
:param name_dict:
:param kwargs:
layout: dict
go.Layout parameters
graph_kwargs: dict
Graph parameters, eg: go.Bar(**graph_kwargs)
| __init__ | python | microsoft/qlib | qlib/contrib/report/graph.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/graph.py | MIT |
def __init__(
self,
df: pd.DataFrame = None,
kind_map: dict = None,
layout: dict = None,
sub_graph_layout: dict = None,
sub_graph_data: list = None,
subplots_kwargs: dict = None,
**kwargs,
):
"""
:param df: pd.DataFrame
:param... |
:param df: pd.DataFrame
:param kind_map: dict, subplots graph kind and kwargs
eg: dict(kind='ScatterGraph', kwargs=dict())
:param layout: `go.Layout` parameters
:param sub_graph_layout: Layout of each graphic, similar to 'layout'
:param sub_graph_data: Instantia... | __init__ | python | microsoft/qlib | qlib/contrib/report/graph.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/graph.py | MIT |
def guess_plotly_rangebreaks(dt_index: pd.DatetimeIndex):
"""
This function `guesses` the rangebreaks required to remove gaps in datetime index.
It basically calculates the difference between a `continuous` datetime index and index given.
For more details on `rangebreaks` params in plotly, see
http... |
This function `guesses` the rangebreaks required to remove gaps in datetime index.
It basically calculates the difference between a `continuous` datetime index and index given.
For more details on `rangebreaks` params in plotly, see
https://plotly.com/python/reference/layout/xaxis/#layout-xaxis-rangeb... | guess_plotly_rangebreaks | python | microsoft/qlib | qlib/contrib/report/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/utils.py | MIT |
def _pred_ic(
pred_label: pd.DataFrame = None, methods: Sequence[Literal["IC", "Rank IC"]] = ("IC", "Rank IC"), **kwargs
) -> tuple:
"""
:param pred_label: pd.DataFrame
must contain one column of realized return with name `label` and one column of predicted score names `score`.
:param methods: Sequ... |
:param pred_label: pd.DataFrame
must contain one column of realized return with name `label` and one column of predicted score names `score`.
:param methods: Sequence[Literal["IC", "Rank IC"]]
IC series to plot.
IC is sectional pearson correlation between label and score
Rank IC is the spearma... | _pred_ic | python | microsoft/qlib | qlib/contrib/report/analysis_model/analysis_model_performance.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_model/analysis_model_performance.py | MIT |
def ic_figure(ic_df: pd.DataFrame, show_nature_day=True, **kwargs) -> go.Figure:
r"""IC figure
:param ic_df: ic DataFrame
:param show_nature_day: whether to display the abscissa of non-trading day
:param \*\*kwargs: contains some parameters to control plot style in plotly. Currently, supports
- ... | IC figure
:param ic_df: ic DataFrame
:param show_nature_day: whether to display the abscissa of non-trading day
:param \*\*kwargs: contains some parameters to control plot style in plotly. Currently, supports
- `rangebreaks`: https://plotly.com/python/time-series/#Hiding-Weekends-and-Holidays
:r... | ic_figure | python | microsoft/qlib | qlib/contrib/report/analysis_model/analysis_model_performance.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_model/analysis_model_performance.py | MIT |
def model_performance_graph(
pred_label: pd.DataFrame,
lag: int = 1,
N: int = 5,
reverse=False,
rank=False,
graph_names: list = ["group_return", "pred_ic", "pred_autocorr"],
show_notebook: bool = True,
show_nature_day: bool = False,
**kwargs,
) -> [list, tuple]:
r"""Model perform... | Model performance
:param pred_label: index is **pd.MultiIndex**, index name is **[instrument, datetime]**; columns names is **[score, label]**.
It is usually same as the label of model training(e.g. "Ref($close, -2)/Ref($close, -1) - 1").
.. code-block:: python
instrument ... | model_performance_graph | python | microsoft/qlib | qlib/contrib/report/analysis_model/analysis_model_performance.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_model/analysis_model_performance.py | MIT |
def _get_cum_return_data_with_position(
position: dict,
report_normal: pd.DataFrame,
label_data: pd.DataFrame,
start_date=None,
end_date=None,
):
"""
:param position:
:param report_normal:
:param label_data:
:param start_date:
:param end_date:
:return:
"""
_cumul... |
:param position:
:param report_normal:
:param label_data:
:param start_date:
:param end_date:
:return:
| _get_cum_return_data_with_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/cumulative_return.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/cumulative_return.py | MIT |
def _get_figure_with_position(
position: dict,
report_normal: pd.DataFrame,
label_data: pd.DataFrame,
start_date=None,
end_date=None,
) -> Iterable[go.Figure]:
"""Get average analysis figures
:param position: position
:param report_normal:
:param label_data:
:param start_date:
... | Get average analysis figures
:param position: position
:param report_normal:
:param label_data:
:param start_date:
:param end_date:
:return:
| _get_figure_with_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/cumulative_return.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/cumulative_return.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.