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, 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 __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 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 |
def parse_position(position: dict = None) -> pd.DataFrame:
"""Parse position dict to position DataFrame
:param position: position data
:return: position DataFrame;
.. code-block:: python
position_df = parse_position(positions)
print(position_df.head())
# statu... | Parse position dict to position DataFrame
:param position: position data
:return: position DataFrame;
.. code-block:: python
position_df = parse_position(positions)
print(position_df.head())
# status: 0-hold, -1-sell, 1-buy
... | parse_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _add_label_to_position(position_df: pd.DataFrame, label_data: pd.DataFrame) -> pd.DataFrame:
"""Concat position with custom label
:param position_df: position DataFrame
:param label_data:
:return: concat result
"""
_start_time = position_df.index.get_level_values(level="datetime").min()
... | Concat position with custom label
:param position_df: position DataFrame
:param label_data:
:return: concat result
| _add_label_to_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _add_bench_to_position(position_df: pd.DataFrame = None, bench: pd.Series = None) -> pd.DataFrame:
"""Concat position with bench
:param position_df: position DataFrame
:param bench: report normal data
:return: concat result
"""
_temp_df = position_df.reset_index(level="instrument")
# FI... | Concat position with bench
:param position_df: position DataFrame
:param bench: report normal data
:return: concat result
| _add_bench_to_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _calculate_label_rank(df: pd.DataFrame) -> pd.DataFrame:
"""calculate label rank
:param df:
:return:
"""
_label_name = "label"
def _calculate_day_value(g_df: pd.DataFrame):
g_df = g_df.copy()
g_df["rank_ratio"] = g_df[_label_name].rank(ascending=False) / len(g_df) * 100
... | calculate label rank
:param df:
:return:
| _calculate_label_rank | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def get_position_data(
position: dict,
label_data: pd.DataFrame,
report_normal: pd.DataFrame = None,
calculate_label_rank=False,
start_date=None,
end_date=None,
) -> pd.DataFrame:
"""Concat position data with pred/report_normal
:param position: position data
:param report_normal: re... | Concat position data with pred/report_normal
:param position: position data
:param report_normal: report normal, must be container 'bench' column
:param label_data:
:param calculate_label_rank:
:param start_date: start date
:param end_date: end date
:return: concat result,
columns: ... | get_position_data | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _get_figure_with_position(
position: dict, label_data: pd.DataFrame, start_date=None, end_date=None
) -> Iterable[go.Figure]:
"""Get average analysis figures
:param position: position
:param label_data:
:param start_date:
:param end_date:
:return:
"""
_position_df = get_position... | Get average analysis figures
:param position: position
:param label_data:
:param start_date:
:param end_date:
:return:
| _get_figure_with_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/rank_label.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/rank_label.py | MIT |
def _get_risk_analysis_data_with_report(
report_normal_df: pd.DataFrame,
# report_long_short_df: pd.DataFrame,
date: pd.Timestamp,
) -> pd.DataFrame:
"""Get risk analysis data with report
:param report_normal_df: report data
:param report_long_short_df: report data
:param date: date string
... | Get risk analysis data with report
:param report_normal_df: report data
:param report_long_short_df: report data
:param date: date string
:return:
| _get_risk_analysis_data_with_report | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_all_risk_analysis(risk_df: pd.DataFrame) -> pd.DataFrame:
"""risk_df to standard
:param risk_df: risk data
:return:
"""
if risk_df is None:
return pd.DataFrame()
risk_df = risk_df.unstack()
risk_df.columns = risk_df.columns.droplevel(0)
return risk_df.drop("mean", axis=... | risk_df to standard
:param risk_df: risk data
:return:
| _get_all_risk_analysis | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_monthly_risk_analysis_with_report(report_normal_df: pd.DataFrame) -> pd.DataFrame:
"""Get monthly analysis data
:param report_normal_df:
# :param report_long_short_df:
:return:
"""
# Group by month
report_normal_gp = report_normal_df.groupby(
[report_normal_df.index.year, ... | Get monthly analysis data
:param report_normal_df:
# :param report_long_short_df:
:return:
| _get_monthly_risk_analysis_with_report | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_risk_analysis_figure(analysis_df: pd.DataFrame) -> Iterable[py.Figure]:
"""Get analysis graph figure
:param analysis_df:
:return:
"""
if analysis_df is None:
return []
_figure = SubplotsGraph(
_get_all_risk_analysis(analysis_df),
kind_map=dict(kind="BarGraph", ... | Get analysis graph figure
:param analysis_df:
:return:
| _get_risk_analysis_figure | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_monthly_risk_analysis_figure(report_normal_df: pd.DataFrame) -> Iterable[py.Figure]:
"""Get analysis monthly graph figure
:param report_normal_df:
:param report_long_short_df:
:return:
"""
# if report_normal_df is None and report_long_short_df is None:
# return []
if repor... | Get analysis monthly graph figure
:param report_normal_df:
:param report_long_short_df:
:return:
| _get_monthly_risk_analysis_figure | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def score_ic_graph(pred_label: pd.DataFrame, show_notebook: bool = True, **kwargs) -> [list, tuple]:
"""score IC
Example:
.. code-block:: python
from qlib.data import D
from qlib.contrib.report import analysis_position
pred_df_dates = pred_df.i... | score IC
Example:
.. code-block:: python
from qlib.data import D
from qlib.contrib.report import analysis_position
pred_df_dates = pred_df.index.get_level_values(level='datetime')
features_df = D.features(D.instruments('csi500'), ['... | score_ic_graph | python | microsoft/qlib | qlib/contrib/report/analysis_position/score_ic.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/score_ic.py | MIT |
def __init__(self, dataset: pd.DataFrame):
"""
Parameters
----------
dataset : pd.DataFrame
We often have multiple columns for dataset. Each column corresponds to one sub figure.
There will be a datatime column in the index levels.
Aggretation will b... |
Parameters
----------
dataset : pd.DataFrame
We often have multiple columns for dataset. Each column corresponds to one sub figure.
There will be a datatime column in the index levels.
Aggretation will be used for more summarized metrics overtime.
... | __init__ | python | microsoft/qlib | qlib/contrib/report/data/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/data/base.py | MIT |
def __init__(
self,
conf_path: Union[str, Path],
exp_name: Optional[str] = None,
horizon: Optional[int] = 20,
step: int = 20,
h_path: Optional[str] = None,
train_start: Optional[str] = None,
test_end: Optional[str] = None,
task_ext_conf: Optional[d... |
Parameters
----------
conf_path : str
Path to the config for rolling.
exp_name : Optional[str]
The exp name of the outputs (Output is a record which contains the concatenated predictions of rolling records).
horizon: Optional[int] = 20,
The ho... | __init__ | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def _replace_handler_with_cache(self, task: dict):
"""
Due to the data processing part in original rolling is slow. So we have to
This class tries to add more feature
"""
if self.h_path is not None:
h_path = Path(self.h_path)
task["dataset"]["kwargs"]["han... |
Due to the data processing part in original rolling is slow. So we have to
This class tries to add more feature
| _replace_handler_with_cache | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def basic_task(self, enable_handler_cache: Optional[bool] = True):
"""
The basic task may not be the exactly same as the config from `conf_path` from __init__ due to
- some parameters could be overriding by some parameters from __init__
- user could implementing sublcass to change it for... |
The basic task may not be the exactly same as the config from `conf_path` from __init__ due to
- some parameters could be overriding by some parameters from __init__
- user could implementing sublcass to change it for higher performance
| basic_task | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def run_basic_task(self):
"""
Run the basic task without rolling.
This is for fast testing for model tunning.
"""
task = self.basic_task()
print(task)
trainer = TrainerR(experiment_name=self.exp_name)
trainer([task]) |
Run the basic task without rolling.
This is for fast testing for model tunning.
| run_basic_task | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def get_task_list(self) -> List[dict]:
"""return a batch of tasks for rolling."""
task = self.basic_task()
task_l = task_generator(
task, RollingGen(step=self.step, trunc_days=self.horizon + 1)
) # the last two days should be truncated to avoid information leakage
fo... | return a batch of tasks for rolling. | get_task_list | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def __init__(
self,
sim_task_model: UTIL_MODEL_TYPE = "gbdt",
meta_1st_train_end: Optional[str] = None,
alpha: float = 0.01,
loss_skip_thresh: int = 50,
fea_imp_n: Optional[int] = 30,
meta_data_proc: Optional[str] = "V01",
segments: Union[float, str] = 0.6... |
Parameters
----------
sim_task_model: Literal["linear", "gbdt"] = "gbdt",
The model for calculating similarity between data.
meta_1st_train_end: Optional[str]
the datetime of training end of the first meta_task
alpha: float
Setting the L2 reg... | __init__ | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _adjust_task(self, task: dict, astype: UTIL_MODEL_TYPE):
"""
Base on the original task, we need to do some extra things.
For example:
- GBDT for calculating feature importance
- Linear or GBDT for calculating similarity
- Datset (well processed) that aligned to Linea... |
Base on the original task, we need to do some extra things.
For example:
- GBDT for calculating feature importance
- Linear or GBDT for calculating similarity
- Datset (well processed) that aligned to Linear that for meta learning
So we may need to change the dataset a... | _adjust_task | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _dump_data_for_proxy_model(self):
"""
Dump data for training meta model.
The meta model will be trained upon the proxy forecasting model.
This dataset is for the proxy forecasting model.
"""
# NOTE: adjusting to `self.sim_task_model` just for aligning with previous i... |
Dump data for training meta model.
The meta model will be trained upon the proxy forecasting model.
This dataset is for the proxy forecasting model.
| _dump_data_for_proxy_model | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _dump_meta_ipt(self):
"""
Dump data for training meta model.
This function will dump the input data for meta model
"""
# According to the experiments, the choice of the model type is very important for achieving good results
sim_task = self._adjust_task(self.basic_tas... |
Dump data for training meta model.
This function will dump the input data for meta model
| _dump_meta_ipt | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _train_meta_model(self, fill_method="max"):
"""
training a meta model based on a simplified linear proxy model;
"""
# 1) leverage the simplified proxy forecasting model to train meta model.
# - Only the dataset part is important, in current version of meta model will integra... |
training a meta model based on a simplified linear proxy model;
| _train_meta_model | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def get_task_list(self):
"""
Leverage meta-model for inference:
- Given
- baseline tasks
- input for meta model(internal data)
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
"""
... |
Leverage meta-model for inference:
- Given
- baseline tasks
- input for meta model(internal data)
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
| get_task_list | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def __init__(
self,
model,
dataset,
topk,
order_generator_cls_or_obj=OrderGenWInteract,
max_sold_weight=1.0,
risk_degree=0.95,
buy_method="first_fill",
trade_exchange=None,
level_infra=None,
common_infra=None,
**kwargs,
... |
Parameters
----------
topk : int
top-N stocks to buy
risk_degree : float
position percentage of total value buy_method:
rank_fill: assign the weight stocks that rank high first(1/topk max)
average_fill: assign the weight to the st... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/cost_control.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/cost_control.py | MIT |
def generate_target_weight_position(self, score, current, trade_start_time, trade_end_time):
"""
Parameters
----------
score:
pred score for this trade date, pd.Series, index is stock_id, contain 'score' column
current:
current position, use Position() cla... |
Parameters
----------
score:
pred score for this trade date, pd.Series, index is stock_id, contain 'score' column
current:
current position, use Position() class
trade_date:
trade date
generate target position from score for this ... | generate_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/cost_control.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/cost_control.py | MIT |
def generate_order_list_from_target_weight_position(
self,
current: Position,
trade_exchange: Exchange,
target_weight_position: dict,
risk_degree: float,
pred_start_time: pd.Timestamp,
pred_end_time: pd.Timestamp,
trade_start_time: pd.Timestamp,
tr... | generate_order_list_from_target_weight_position
:param current: The current position
:type current: Position
:param trade_exchange:
:type trade_exchange: Exchange
:param target_weight_position: {stock_id : weight}
:type target_weight_position: dict
:param risk_de... | generate_order_list_from_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/order_generator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/order_generator.py | MIT |
def generate_order_list_from_target_weight_position(
self,
current: Position,
trade_exchange: Exchange,
target_weight_position: dict,
risk_degree: float,
pred_start_time: pd.Timestamp,
pred_end_time: pd.Timestamp,
trade_start_time: pd.Timestamp,
tr... | generate_order_list_from_target_weight_position
No adjustment for for the nontradable share.
All the tadable value is assigned to the tadable stock according to the weight.
if interact == True, will use the price at trade date to generate order list
else, will only use the price before ... | generate_order_list_from_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/order_generator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/order_generator.py | MIT |
def generate_order_list_from_target_weight_position(
self,
current: Position,
trade_exchange: Exchange,
target_weight_position: dict,
risk_degree: float,
pred_start_time: pd.Timestamp,
pred_end_time: pd.Timestamp,
trade_start_time: pd.Timestamp,
tr... | generate_order_list_from_target_weight_position
generate order list directly not using the information (e.g. whether can be traded, the accurate trade price)
at trade date.
In target weight position, generating order list need to know the price of objective stock in trade date,
but we ... | generate_order_list_from_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/order_generator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/order_generator.py | MIT |
def __init__(
self,
outer_trade_decision: BaseTradeDecision = None,
instruments: Union[List, str] = "csi300",
freq: str = "day",
trade_exchange: Exchange = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
**kwargs,
... |
Parameters
----------
instruments : Union[List, str], optional
instruments of EMA signal, by default "csi300"
freq : str, optional
freq of EMA signal, by default "day"
Note: `freq` may be different from `time_per_step`
| __init__ | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def __init__(
self,
lamb: float = 1e-6,
eta: float = 2.5e-6,
window_size: int = 20,
outer_trade_decision: BaseTradeDecision = None,
instruments: Union[List, str] = "csi300",
freq: str = "day",
trade_exchange: Exchange = None,
level_infra: LevelInfr... |
Parameters
----------
instruments : Union[List, str], optional
instruments of Volatility, by default "csi300"
freq : str, optional
freq of Volatility, by default "day"
Note: `freq` may be different from `time_per_step`
| __init__ | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def __init__(
self,
trade_range: Union[Tuple[int, int], TradeRange], # The range is closed on both left and right.
sample_ratio: float = 1.0,
volume_ratio: float = 0.01,
market: str = "all",
direction: int = Order.BUY,
*args,
**kwargs,
):
"""
... |
Parameters
----------
trade_range : Tuple
please refer to the `trade_range` parameter of BaseStrategy
sample_ratio : float
the ratio of all orders are sampled
volume_ratio : float
the volume of the total day
raito of the total volu... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def generate_trade_decision(self, execute_result=None) -> TradeDecisionWO:
"""
Parameters
----------
execute_result :
execute_result will be ignored in FileOrderStrategy
"""
oh: OrderHelper = self.common_infra.get("trade_exchange").get_order_helper()
s... |
Parameters
----------
execute_result :
execute_result will be ignored in FileOrderStrategy
| generate_trade_decision | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def __init__(
self,
*,
signal: Union[Signal, Tuple[BaseModel, Dataset], List, Dict, Text, pd.Series, pd.DataFrame] = None,
model=None,
dataset=None,
risk_degree: float = 0.95,
trade_exchange=None,
level_infra=None,
common_infra=None,
**kwar... |
Parameters
-----------
signal :
the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from`
the decision of the strategy will base on the given signal
risk_degree : float
position percentage of total val... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/signal_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/signal_strategy.py | MIT |
def __init__(
self,
*,
order_generator_cls_or_obj=OrderGenWOInteract,
**kwargs,
):
"""
signal :
the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from`
the decision of the strategy will base o... |
signal :
the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from`
the decision of the strategy will base on the given signal
trade_exchange : Exchange
exchange that provides market info, used to deal order and genera... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/signal_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/signal_strategy.py | MIT |
def __call__(
self,
r: np.ndarray,
F: np.ndarray,
cov_b: np.ndarray,
var_u: np.ndarray,
w0: np.ndarray,
wb: np.ndarray,
mfh: Optional[np.ndarray] = None,
mfs: Optional[np.ndarray] = None,
) -> np.ndarray:
"""
Args:
r... |
Args:
r (np.ndarray): expected returns
F (np.ndarray): factor exposure
cov_b (np.ndarray): factor covariance
var_u (np.ndarray): residual variance
w0 (np.ndarray): current holding weights
wb (np.ndarray): benchmark weights
mfh ... | __call__ | python | microsoft/qlib | qlib/contrib/strategy/optimizer/enhanced_indexing.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/enhanced_indexing.py | MIT |
def __call__(
self,
S: Union[np.ndarray, pd.DataFrame],
r: Optional[Union[np.ndarray, pd.Series]] = None,
w0: Optional[Union[np.ndarray, pd.Series]] = None,
) -> Union[np.ndarray, pd.Series]:
"""
Args:
S (np.ndarray or pd.DataFrame): covariance matrix
... |
Args:
S (np.ndarray or pd.DataFrame): covariance matrix
r (np.ndarray or pd.Series): expected return
w0 (np.ndarray or pd.Series): initial weights (for turnover control)
Returns:
np.ndarray or pd.Series: optimized portfolio allocation
| __call__ | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _optimize_mvo(
self, S: np.ndarray, r: Optional[np.ndarray] = None, w0: Optional[np.ndarray] = None
) -> np.ndarray:
"""optimize mean-variance portfolio
This method solves the following optimization problem
min_w - w' r + lamb * w' S w
s.t. w >= 0, sum(w) == ... | optimize mean-variance portfolio
This method solves the following optimization problem
min_w - w' r + lamb * w' S w
s.t. w >= 0, sum(w) == 1
where `S` is the covariance matrix, `u` is the expected returns,
and `lamb` is the risk aversion parameter.
| _optimize_mvo | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_objective_gmv(self, S: np.ndarray) -> Callable:
"""global minimum variance optimization objective
Optimization objective
min_w w' S w
"""
def func(x):
return x @ S @ x
return func | global minimum variance optimization objective
Optimization objective
min_w w' S w
| _get_objective_gmv | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_objective_mvo(self, S: np.ndarray, r: np.ndarray = None) -> Callable:
"""mean-variance optimization objective
Optimization objective
min_w - w' r + lamb * w' S w
"""
def func(x):
risk = x @ S @ x
ret = x @ r
return -ret + self.la... | mean-variance optimization objective
Optimization objective
min_w - w' r + lamb * w' S w
| _get_objective_mvo | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_objective_rp(self, S: np.ndarray) -> Callable:
"""risk-parity optimization objective
Optimization objective
min_w sum_i [w_i - (w' S w) / ((S w)_i * N)]**2
"""
def func(x):
N = len(x)
Sx = S @ x
xSx = x @ Sx
return np... | risk-parity optimization objective
Optimization objective
min_w sum_i [w_i - (w' S w) / ((S w)_i * N)]**2
| _get_objective_rp | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_constrains(self, w0: Optional[np.ndarray] = None):
"""optimization constraints
Defines the following constraints:
- no shorting and leverage: 0 <= w <= 1
- full investment: sum(w) == 1
- turnover constraint: |w - w0| <= delta
"""
# no shorti... | optimization constraints
Defines the following constraints:
- no shorting and leverage: 0 <= w <= 1
- full investment: sum(w) == 1
- turnover constraint: |w - w0| <= delta
| _get_constrains | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _solve(self, n: int, obj: Callable, bounds: so.Bounds, cons: List) -> np.ndarray:
"""solve optimization
Args:
n (int): number of parameters
obj (callable): optimization objective
bounds (Bounds): bounds of parameters
cons (list): optimization constrai... | solve optimization
Args:
n (int): number of parameters
obj (callable): optimization objective
bounds (Bounds): bounds of parameters
cons (list): optimization constraints
| _solve | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def __init__(self, config, TUNER_CONFIG_MANAGER):
"""
:param config: The config dict for tuner experiment
:param TUNER_CONFIG_MANAGER: The tuner config manager
"""
self.name = config.get("name", "tuner_experiment")
# The dir of the config
self.global_dir = conf... |
:param config: The config dict for tuner experiment
:param TUNER_CONFIG_MANAGER: The tuner config manager
| __init__ | python | microsoft/qlib | qlib/contrib/tuner/config.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/tuner/config.py | MIT |
def init_tuner(self, tuner_index, tuner_config):
"""
Implement this method to build the tuner by config
return: tuner
"""
# 1. Add experiment config in tuner_config
tuner_config["experiment"] = {
"name": "estimator_experiment_{}".format(tuner_index),
... |
Implement this method to build the tuner by config
return: tuner
| init_tuner | python | microsoft/qlib | qlib/contrib/tuner/pipeline.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/tuner/pipeline.py | MIT |
def load(self, instrument, start_index, end_index, *args):
"""load feature
This function is responsible for loading feature/expression based on the expression engine.
The concrete implementation will be separated into two parts:
1) caching data, handle errors.
- This part... | load feature
This function is responsible for loading feature/expression based on the expression engine.
The concrete implementation will be separated into two parts:
1) caching data, handle errors.
- This part is shared by all the expressions and implemented in Expression
... | load | python | microsoft/qlib | qlib/data/base.py | https://github.com/microsoft/qlib/blob/master/qlib/data/base.py | MIT |
def get_longest_back_rolling(self):
"""Get the longest length of historical data the feature has accessed
This is designed for getting the needed range of the data to calculate
the features in specific range at first. However, situations like
Ref(Ref($close, -1), 1) can not be handled ... | Get the longest length of historical data the feature has accessed
This is designed for getting the needed range of the data to calculate
the features in specific range at first. However, situations like
Ref(Ref($close, -1), 1) can not be handled rightly.
So this will only used for de... | get_longest_back_rolling | python | microsoft/qlib | qlib/data/base.py | https://github.com/microsoft/qlib/blob/master/qlib/data/base.py | MIT |
def get_cache(mem_cache, key):
"""get mem cache
:param mem_cache: MemCache attribute('c'/'i'/'f').
:param key: cache key.
:return: cache value; if cache not exist, return None.
"""
value = None
expire = False
if key in mem_cache:
value, latest... | get mem cache
:param mem_cache: MemCache attribute('c'/'i'/'f').
:param key: cache key.
:return: cache value; if cache not exist, return None.
| get_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def expression(self, instrument, field, start_time, end_time, freq):
"""Get expression data.
.. note:: Same interface as `expression` method in expression provider
"""
try:
return self._expression(instrument, field, start_time, end_time, freq)
except NotImplementedEr... | Get expression data.
.. note:: Same interface as `expression` method in expression provider
| expression | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def dataset(
self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
):
"""Get feature dataset.
.. note:: Same interface as `dataset` method in dataset provider
.. note:: The server use redis_lock to make sure
read-write c... | Get feature dataset.
.. note:: Same interface as `dataset` method in dataset provider
.. note:: The server use redis_lock to make sure
read-write conflicts will not be triggered
but client readers are not considered.
| dataset | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def _dataset(
self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
):
"""Get feature dataset using cache.
Override this method to define how to get feature dataset corresponding to users' own cache mechanism.
"""
raise NotIm... | Get feature dataset using cache.
Override this method to define how to get feature dataset corresponding to users' own cache mechanism.
| _dataset | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def _dataset_uri(
self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
):
"""Get a uri of feature dataset using cache.
specially:
disk_cache=1 means using data set cache and return the uri of cache file.
disk_cache=0 ... | Get a uri of feature dataset using cache.
specially:
disk_cache=1 means using data set cache and return the uri of cache file.
disk_cache=0 means client knows the path of expression cache,
server checks if the cache exists(if not, generate it), and client loads d... | _dataset_uri | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def cache_to_origin_data(data, fields):
"""cache data to origin data
:param data: pd.DataFrame, cache data.
:param fields: feature fields.
:return: pd.DataFrame.
"""
not_space_fields = remove_fields_space(fields)
data = data.loc[:, not_space_fields]
# set... | cache data to origin data
:param data: pd.DataFrame, cache data.
:param fields: feature fields.
:return: pd.DataFrame.
| cache_to_origin_data | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def gen_expression_cache(self, expression_data, cache_path, instrument, field, freq, last_update):
"""use bin file to save like feature-data."""
# Make sure the cache runs right when the directory is deleted
# while running
meta = {
"info": {"instrument": instrument, "field":... | use bin file to save like feature-data. | gen_expression_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def read_data_from_cache(cls, cache_path: Union[str, Path], start_time, end_time, fields):
"""read_cache_from
This function can read data from the disk cache dataset
:param cache_path:
:param start_time:
:param end_time:
:param fields: The fields order of the dataset ca... | read_cache_from
This function can read data from the disk cache dataset
:param cache_path:
:param start_time:
:param end_time:
:param fields: The fields order of the dataset cache is sorted. So rearrange the columns to make it consistent.
:return:
| read_data_from_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.