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 quantile_loss(self, a, b): """Returns quantile loss for specified quantiles. Args: a: Targets b: Predictions """ quantiles_used = set(self.quantiles) loss = 0.0 ...
Returns quantile loss for specified quantiles. Args: a: Targets b: Predictions
quantile_loss
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def fit(self, train_df=None, valid_df=None): """Fits deep neural network for given training and validation data. Args: train_df: DataFrame for training data valid_df: DataFrame for validation data """ print("*** Fitting {} ***".format(self.name)) # Add rele...
Fits deep neural network for given training and validation data. Args: train_df: DataFrame for training data valid_df: DataFrame for validation data
fit
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def evaluate(self, data=None, eval_metric="loss"): """Applies evaluation metric to the training data. Args: data: Dataframe for evaluation eval_metric: Evaluation metic to return, based on model definition. Returns: Computed evaluation loss. """ i...
Applies evaluation metric to the training data. Args: data: Dataframe for evaluation eval_metric: Evaluation metic to return, based on model definition. Returns: Computed evaluation loss.
evaluate
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def predict(self, df, return_targets=False): """Computes predictions for a given input dataset. Args: df: Input dataframe return_targets: Whether to also return outputs aligned with predictions to facilitate evaluation Returns: Input dataframe or tuple...
Computes predictions for a given input dataset. Args: df: Input dataframe return_targets: Whether to also return outputs aligned with predictions to facilitate evaluation Returns: Input dataframe or tuple of (input dataframe, aligned output dataframe). ...
predict
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def get_attention(self, df): """Computes TFT attention weights for a given dataset. Args: df: Input dataframe Returns: Dictionary of numpy arrays for temporal attention weights and variable selection weights, along with their identifiers and time indices ...
Computes TFT attention weights for a given dataset. Args: df: Input dataframe Returns: Dictionary of numpy arrays for temporal attention weights and variable selection weights, along with their identifiers and time indices
get_attention
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def get_batch_attention_weights(input_batch): """Returns weights for a given minibatch of data.""" input_placeholder = self._input_placeholder attention_weights = {} for k in self._attention_components: attention_weight = tf.keras.backend.get_session().run...
Returns weights for a given minibatch of data.
get_batch_attention_weights
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def reset_temp_folder(self): """Deletes and recreates folder with temporary Keras training outputs.""" print("Resetting temp folder...") utils.create_folder_if_not_exist(self._temp_folder) shutil.rmtree(self._temp_folder) os.makedirs(self._temp_folder)
Deletes and recreates folder with temporary Keras training outputs.
reset_temp_folder
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def save(self, model_folder): """Saves optimal TFT weights. Args: model_folder: Location to serialze model. """ # Allows for direct serialisation of tensorflow variables to avoid spurious # issue with Keras that leads to different performance evaluation results ...
Saves optimal TFT weights. Args: model_folder: Location to serialze model.
save
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def load(self, model_folder, use_keras_loadings=False): """Loads TFT weights. Args: model_folder: Folder containing serialized models. use_keras_loadings: Whether to load from Keras checkpoint. Returns: """ if use_keras_loadings: # Loads tempora...
Loads TFT weights. Args: model_folder: Folder containing serialized models. use_keras_loadings: Whether to load from Keras checkpoint. Returns:
load
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def get_hyperparm_choices(cls): """Returns hyperparameter ranges for random search.""" return { "dropout_rate": [0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.9], "hidden_layer_size": [10, 20, 40, 80, 160, 240, 320], "minibatch_size": [64, 128, 256], "learning_rate": [1...
Returns hyperparameter ranges for random search.
get_hyperparm_choices
python
microsoft/qlib
examples/benchmarks/TFT/libs/tft_model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/tft_model.py
MIT
def get_single_col_by_input_type(input_type, column_definition): """Returns name of single column. Args: input_type: Input type of column to extract column_definition: Column definition list for experiment """ l = [tup[0] for tup in column_definition if tup[2] == input_type] if len(l)...
Returns name of single column. Args: input_type: Input type of column to extract column_definition: Column definition list for experiment
get_single_col_by_input_type
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.py
MIT
def tensorflow_quantile_loss(y, y_pred, quantile): """Computes quantile loss for tensorflow. Standard quantile loss as defined in the "Training Procedure" section of the main TFT paper Args: y: Targets y_pred: Predictions quantile: Quantile to use for loss calculations (between 0 & 1...
Computes quantile loss for tensorflow. Standard quantile loss as defined in the "Training Procedure" section of the main TFT paper Args: y: Targets y_pred: Predictions quantile: Quantile to use for loss calculations (between 0 & 1) Returns: Tensor for quantile loss.
tensorflow_quantile_loss
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.py
MIT
def numpy_normalised_quantile_loss(y, y_pred, quantile): """Computes normalised quantile loss for numpy arrays. Uses the q-Risk metric as defined in the "Training Procedure" section of the main TFT paper. Args: y: Targets y_pred: Predictions quantile: Quantile to use for loss calcula...
Computes normalised quantile loss for numpy arrays. Uses the q-Risk metric as defined in the "Training Procedure" section of the main TFT paper. Args: y: Targets y_pred: Predictions quantile: Quantile to use for loss calculations (between 0 & 1) Returns: Float for normalised q...
numpy_normalised_quantile_loss
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.py
MIT
def get_default_tensorflow_config(tf_device="gpu", gpu_id=0): """Creates tensorflow config for graphs to run on CPU or GPU. Specifies whether to run graph on gpu or cpu and which GPU ID to use for multi GPU machines. Args: tf_device: 'cpu' or 'gpu' gpu_id: GPU ID to use if relevant Re...
Creates tensorflow config for graphs to run on CPU or GPU. Specifies whether to run graph on gpu or cpu and which GPU ID to use for multi GPU machines. Args: tf_device: 'cpu' or 'gpu' gpu_id: GPU ID to use if relevant Returns: Tensorflow config.
get_default_tensorflow_config
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.py
MIT
def save(tf_session, model_folder, cp_name, scope=None): """Saves Tensorflow graph to checkpoint. Saves all trainiable variables under a given variable scope to checkpoint. Args: tf_session: Session containing graph model_folder: Folder to save models cp_name: Name of Tensorflow checkpoi...
Saves Tensorflow graph to checkpoint. Saves all trainiable variables under a given variable scope to checkpoint. Args: tf_session: Session containing graph model_folder: Folder to save models cp_name: Name of Tensorflow checkpoint scope: Variable scope containing variables to save
save
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.py
MIT
def load(tf_session, model_folder, cp_name, scope=None, verbose=False): """Loads Tensorflow graph from checkpoint. Args: tf_session: Session to load graph into model_folder: Folder containing serialised model cp_name: Name of Tensorflow checkpoint scope: Variable scope to use. ver...
Loads Tensorflow graph from checkpoint. Args: tf_session: Session to load graph into model_folder: Folder containing serialised model cp_name: Name of Tensorflow checkpoint scope: Variable scope to use. verbose: Whether to print additional debugging information.
load
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.py
MIT
def print_weights_in_checkpoint(model_folder, cp_name): """Prints all weights in Tensorflow checkpoint. Args: model_folder: Folder containing checkpoint cp_name: Name of checkpoint Returns: """ load_path = os.path.join(model_folder, "{0}.ckpt".format(cp_name)) print_tensors_in_ch...
Prints all weights in Tensorflow checkpoint. Args: model_folder: Folder containing checkpoint cp_name: Name of checkpoint Returns:
print_weights_in_checkpoint
python
microsoft/qlib
examples/benchmarks/TFT/libs/utils.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/utils.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 index.is_lexsorted(), "index should be sorted" # number of dates for...
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
examples/benchmarks/TRA/src/dataset.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TRA/src/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, pd.Timestamp): ...
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
examples/benchmarks/TRA/src/dataset.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TRA/src/dataset.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
examples/benchmarks/TRA/src/model.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TRA/src/model.py
MIT
def get_data(self): """use dataset to get highreq data""" self._init_qlib() self._prepare_calender_cache() dataset = init_instance_by_config(self.task["dataset"]) xtrain, xtest = dataset.prepare(["train", "test"]) print(xtrain, xtest) dataset_backtest = init_ins...
use dataset to get highreq data
get_data
python
microsoft/qlib
examples/highfreq/workflow.py
https://github.com/microsoft/qlib/blob/master/examples/highfreq/workflow.py
MIT
def dump_and_load_dataset(self): """dump and load dataset state on disk""" self._init_qlib() self._prepare_calender_cache() dataset = init_instance_by_config(self.task["dataset"]) dataset_backtest = init_instance_by_config(self.task["dataset_backtest"]) ##=============du...
dump and load dataset state on disk
dump_and_load_dataset
python
microsoft/qlib
examples/highfreq/workflow.py
https://github.com/microsoft/qlib/blob/master/examples/highfreq/workflow.py
MIT
def backtest_only_daily(self): """ This backtest is used for comparing the nested execution and single layer execution Due to the low quality daily-level and miniute-level data, they are hardly comparable. So it is used for detecting serious bugs which make the results different greatly....
This backtest is used for comparing the nested execution and single layer execution Due to the low quality daily-level and miniute-level data, they are hardly comparable. So it is used for detecting serious bugs which make the results different greatly. .. code-block:: shell ...
backtest_only_daily
python
microsoft/qlib
examples/nested_decision_execution/workflow.py
https://github.com/microsoft/qlib/blob/master/examples/nested_decision_execution/workflow.py
MIT
def __init__( self, provider_uri="~/.qlib/qlib_data/cn_data", region="cn", exp_name="rolling_exp", task_url="mongodb://10.0.0.4:27017/", # not necessary when using TrainerR or DelayTrainerR task_db_name="rolling_db", # not necessary when using TrainerR or DelayTrainerR ...
Init OnlineManagerExample. Args: provider_uri (str, optional): the provider uri. Defaults to "~/.qlib/qlib_data/cn_data". region (str, optional): the stock region. Defaults to "cn". exp_name (str, optional): the experiment name. Defaults to "rolling_exp". ...
__init__
python
microsoft/qlib
examples/online_srv/online_management_simulate.py
https://github.com/microsoft/qlib/blob/master/examples/online_srv/online_management_simulate.py
MIT
def add_one_stock_daily_data(filepath, type, exchange_place, arc, date): """ exchange_place: "SZ" OR "SH" type: "tick", "orderbook", ... filepath: the path of csv arc: arclink created by a process """ code = os.path.split(filepath)[-1].split(".csv")[0] if exchange_place == "SH" and code[...
exchange_place: "SZ" OR "SH" type: "tick", "orderbook", ... filepath: the path of csv arc: arclink created by a process
add_one_stock_daily_data
python
microsoft/qlib
examples/orderbook_data/create_dataset.py
https://github.com/microsoft/qlib/blob/master/examples/orderbook_data/create_dataset.py
MIT
def __init__(self, provider_uri: Union[str, Path, dict], mount_path: Union[str, Path, dict]): """ The relation of `provider_uri` and `mount_path` - `mount_path` is used only if provider_uri is an NFS path - otherwise, provider_uri will be used for accessing data ...
The relation of `provider_uri` and `mount_path` - `mount_path` is used only if provider_uri is an NFS path - otherwise, provider_uri will be used for accessing data
__init__
python
microsoft/qlib
qlib/config.py
https://github.com/microsoft/qlib/blob/master/qlib/config.py
MIT
def get_data_uri(self, freq: Optional[Union[str, Freq]] = None) -> Path: """ please refer DataPathManager's __init__ and class doc """ if freq is not None: freq = str(freq) # converting Freq to string if freq is None or freq not in self.provid...
please refer DataPathManager's __init__ and class doc
get_data_uri
python
microsoft/qlib
qlib/config.py
https://github.com/microsoft/qlib/blob/master/qlib/config.py
MIT
def set(self, default_conf: str = "client", **kwargs): """ configure qlib based on the input parameters The configuration will act like a dictionary. Normally, it literally is replaced the value according to the keys. However, sometimes it is hard for users to set the config wh...
configure qlib based on the input parameters The configuration will act like a dictionary. Normally, it literally is replaced the value according to the keys. However, sometimes it is hard for users to set the config when the configuration is nested and complicated So this AP...
set
python
microsoft/qlib
qlib/config.py
https://github.com/microsoft/qlib/blob/master/qlib/config.py
MIT
def get_kernels(self, freq: str): """get number of processors given frequency""" if isinstance(self["kernels"], Callable): return self["kernels"](freq) return self["kernels"]
get number of processors given frequency
get_kernels
python
microsoft/qlib
qlib/config.py
https://github.com/microsoft/qlib/blob/master/qlib/config.py
MIT
def __call__(self, module_name, level: Optional[int] = None) -> QlibLogger: """ Get a logger for a specific module. :param module_name: str Logic module name. :param level: int :return: Logger Logger object. """ if level is None: ...
Get a logger for a specific module. :param module_name: str Logic module name. :param level: int :return: Logger Logger object.
__call__
python
microsoft/qlib
qlib/log.py
https://github.com/microsoft/qlib/blob/master/qlib/log.py
MIT
def set_time_mark(cls): """ Set a time mark with current time, and this time mark will push into a stack. :return: float A timestamp for current time. """ _time = time() cls.time_marks.append(_time) return _time
Set a time mark with current time, and this time mark will push into a stack. :return: float A timestamp for current time.
set_time_mark
python
microsoft/qlib
qlib/log.py
https://github.com/microsoft/qlib/blob/master/qlib/log.py
MIT
def log_cost_time(cls, info="Done"): """ Get last time mark from stack, calculate time diff with current time, and log time diff and info. :param info: str Info that will be logged into stdout. """ cost_time = time() - cls.time_marks.pop() cls.timer_logger.inf...
Get last time mark from stack, calculate time diff with current time, and log time diff and info. :param info: str Info that will be logged into stdout.
log_cost_time
python
microsoft/qlib
qlib/log.py
https://github.com/microsoft/qlib/blob/master/qlib/log.py
MIT
def logt(cls, name="", show_start=False): """logt. Log the time of the inside code Parameters ---------- name : name show_start : show_start """ if show_start: cls.timer_logger.info(f"{name} Begin") cls.set_time...
logt. Log the time of the inside code Parameters ---------- name : name show_start : show_start
logt
python
microsoft/qlib
qlib/log.py
https://github.com/microsoft/qlib/blob/master/qlib/log.py
MIT
def set_global_logger_level(level: int, return_orig_handler_level: bool = False): """set qlib.xxx logger handlers level Parameters ---------- level: int logger level return_orig_handler_level: bool return origin handler level map Examples --------- .. code-block::...
set qlib.xxx logger handlers level Parameters ---------- level: int logger level return_orig_handler_level: bool return origin handler level map Examples --------- .. code-block:: python import qlib import logging from qlib.log imp...
set_global_logger_level
python
microsoft/qlib
qlib/log.py
https://github.com/microsoft/qlib/blob/master/qlib/log.py
MIT
def set_global_logger_level_cm(level: int): """set qlib.xxx logger handlers level to use contextmanager Parameters ---------- level: int logger level Examples --------- .. code-block:: python import qlib import logging from qlib.log import ...
set qlib.xxx logger handlers level to use contextmanager Parameters ---------- level: int logger level Examples --------- .. code-block:: python import qlib import logging from qlib.log import get_module_logger, set_global_logger_level_cm ...
set_global_logger_level_cm
python
microsoft/qlib
qlib/log.py
https://github.com/microsoft/qlib/blob/master/qlib/log.py
MIT
def init(default_conf="client", **kwargs): """ Parameters ---------- default_conf: str the default value is client. Accepted values: client/server. **kwargs : clear_mem_cache: str the default value is True; Will the memory cache be clear. It is of...
Parameters ---------- default_conf: str the default value is client. Accepted values: client/server. **kwargs : clear_mem_cache: str the default value is True; Will the memory cache be clear. It is often used to improve performance when init will be ...
init
python
microsoft/qlib
qlib/__init__.py
https://github.com/microsoft/qlib/blob/master/qlib/__init__.py
MIT
def init_from_yaml_conf(conf_path, **kwargs): """init_from_yaml_conf :param conf_path: A path to the qlib config in yml format """ if conf_path is None: config = {} else: with open(conf_path) as f: yaml = YAML(typ="safe", pure=True) config = yaml.load(f) ...
init_from_yaml_conf :param conf_path: A path to the qlib config in yml format
init_from_yaml_conf
python
microsoft/qlib
qlib/__init__.py
https://github.com/microsoft/qlib/blob/master/qlib/__init__.py
MIT
def get_project_path(config_name="config.yaml", cur_path: Union[Path, str, None] = None) -> Path: """ If users are building a project follow the following pattern. - Qlib is a sub folder in project path - There is a file named `config.yaml` in qlib. For example: If your project file system ...
If users are building a project follow the following pattern. - Qlib is a sub folder in project path - There is a file named `config.yaml` in qlib. For example: If your project file system structure follows such a pattern <project_path>/ - config.yaml -...
get_project_path
python
microsoft/qlib
qlib/__init__.py
https://github.com/microsoft/qlib/blob/master/qlib/__init__.py
MIT
def auto_init(**kwargs): """ This function will init qlib automatically with following priority - Find the project configuration and init qlib - The parsing process will be affected by the `conf_type` of the configuration file - Init qlib with default config - Skip initialization if already ...
This function will init qlib automatically with following priority - Find the project configuration and init qlib - The parsing process will be affected by the `conf_type` of the configuration file - Init qlib with default config - Skip initialization if already initialized :**kwargs: it m...
auto_init
python
microsoft/qlib
qlib/__init__.py
https://github.com/microsoft/qlib/blob/master/qlib/__init__.py
MIT
def __init__( self, init_cash: float = 1e9, position_dict: dict = {}, freq: str = "day", benchmark_config: dict = {}, pos_type: str = "Position", port_metr_enabled: bool = True, ) -> None: """the trade account of backtest. Parameters -...
the trade account of backtest. Parameters ---------- init_cash : float, optional initial cash, by default 1e9 position_dict : Dict[ stock_id, Union[ int, # it is equal to {"amount": int}...
__init__
python
microsoft/qlib
qlib/backtest/account.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/account.py
MIT
def reset( self, freq: str | None = None, benchmark_config: dict | None = None, port_metr_enabled: bool | None = None ) -> None: """reset freq and report of account Parameters ---------- freq : str, optional frequency of account & report, by default None ...
reset freq and report of account Parameters ---------- freq : str, optional frequency of account & report, by default None benchmark_config : {}, optional benchmark config of report, by default None port_metr_enabled: bool
reset
python
microsoft/qlib
qlib/backtest/account.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/account.py
MIT
def update_current_position( self, trade_start_time: pd.Timestamp, trade_end_time: pd.Timestamp, trade_exchange: Exchange, ) -> None: """ Update current to make rtn consistent with earning at the end of bar, and update holding bar count of stock """ # ...
Update current to make rtn consistent with earning at the end of bar, and update holding bar count of stock
update_current_position
python
microsoft/qlib
qlib/backtest/account.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/account.py
MIT
def update_indicator( self, trade_start_time: pd.Timestamp, trade_exchange: Exchange, atomic: bool, outer_trade_decision: BaseTradeDecision, trade_info: list = [], inner_order_indicators: List[BaseOrderIndicator] = [], decision_list: List[Tuple[BaseTradeDe...
update trade indicators and order indicators in each bar end
update_indicator
python
microsoft/qlib
qlib/backtest/account.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/account.py
MIT
def update_bar_end( self, trade_start_time: pd.Timestamp, trade_end_time: pd.Timestamp, trade_exchange: Exchange, atomic: bool, outer_trade_decision: BaseTradeDecision, trade_info: list = [], inner_order_indicators: List[BaseOrderIndicator] = [], d...
update account at each trading bar step Parameters ---------- trade_start_time : pd.Timestamp closed start time of step trade_end_time : pd.Timestamp closed end time of step trade_exchange : Exchange trading exchange, used to update current ...
update_bar_end
python
microsoft/qlib
qlib/backtest/account.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/account.py
MIT
def get_portfolio_metrics(self) -> Tuple[pd.DataFrame, dict]: """get the history portfolio_metrics and positions instance""" if self.is_port_metr_enabled(): assert self.portfolio_metrics is not None _portfolio_metrics = self.portfolio_metrics.generate_portfolio_metrics_dataframe(...
get the history portfolio_metrics and positions instance
get_portfolio_metrics
python
microsoft/qlib
qlib/backtest/account.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/account.py
MIT
def backtest_loop( start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], trade_strategy: BaseStrategy, trade_executor: BaseExecutor, ) -> Tuple[PORT_METRIC, INDICATOR_METRIC]: """backtest function for the interaction of the outermost strategy and executor in the nested decision e...
backtest function for the interaction of the outermost strategy and executor in the nested decision execution please refer to the docs of `collect_data_loop` Returns ------- portfolio_dict: PORT_METRIC it records the trading portfolio_metrics information indicator_dict: INDICATOR_METRIC ...
backtest_loop
python
microsoft/qlib
qlib/backtest/backtest.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/backtest.py
MIT
def collect_data_loop( start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], trade_strategy: BaseStrategy, trade_executor: BaseExecutor, return_value: dict | None = None, ) -> Generator[BaseTradeDecision, Optional[BaseTradeDecision], None]: """Generator for collecting the tra...
Generator for collecting the trade decision data for rl training Parameters ---------- start_time : Union[pd.Timestamp, str] closed start time for backtest **NOTE**: This will be applied to the outmost executor's calendar. end_time : Union[pd.Timestamp, str] closed end time for ...
collect_data_loop
python
microsoft/qlib
qlib/backtest/backtest.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/backtest.py
MIT
def create( code: str, amount: float, direction: OrderDir, start_time: Union[str, pd.Timestamp] = None, end_time: Union[str, pd.Timestamp] = None, ) -> Order: """ help to create a order # TODO: create order for unadjusted amount order Paramet...
help to create a order # TODO: create order for unadjusted amount order Parameters ---------- code : str the id of the instrument amount : float **adjusted trading amount** direction : OrderDir trading direction star...
create
python
microsoft/qlib
qlib/backtest/decision.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py
MIT
def __init__(self, start_time: str | time, end_time: str | time) -> None: """ This is a callable class. **NOTE**: - It is designed for minute-bar for intra-day trading!!!!! - Both start_time and end_time are **closed** in the range Parameters ---------- ...
This is a callable class. **NOTE**: - It is designed for minute-bar for intra-day trading!!!!! - Both start_time and end_time are **closed** in the range Parameters ---------- start_time : str | time e.g. "9:30" end_time : str | time ...
__init__
python
microsoft/qlib
qlib/backtest/decision.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py
MIT
def __init__(self, strategy: BaseStrategy, trade_range: Union[Tuple[int, int], TradeRange, None] = None) -> None: """ Parameters ---------- strategy : BaseStrategy The strategy who make the decision trade_range: Union[Tuple[int, int], Callable] (optional) ...
Parameters ---------- strategy : BaseStrategy The strategy who make the decision trade_range: Union[Tuple[int, int], Callable] (optional) The index range for underlying strategy. Here are two examples of trade_range for each type 1) Tupl...
__init__
python
microsoft/qlib
qlib/backtest/decision.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py
MIT
def update(self, trade_calendar: TradeCalendarManager) -> Optional[BaseTradeDecision]: """ Be called at the **start** of each step. This function is design for following purpose 1) Leave a hook for the strategy who make `self` decision to update the decision itself 2) Update som...
Be called at the **start** of each step. This function is design for following purpose 1) Leave a hook for the strategy who make `self` decision to update the decision itself 2) Update some information from the inner executor calendar Parameters ---------- trad...
update
python
microsoft/qlib
qlib/backtest/decision.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py
MIT
def mod_inner_decision(self, inner_trade_decision: BaseTradeDecision) -> None: """ This method will be called on the inner_trade_decision after it is generated. `inner_trade_decision` will be changed **inplace**. Motivation of the `mod_inner_decision` - Leave a hook for outer de...
This method will be called on the inner_trade_decision after it is generated. `inner_trade_decision` will be changed **inplace**. Motivation of the `mod_inner_decision` - Leave a hook for outer decision to affect the decision generated by the inner strategy - e.g. the outmo...
mod_inner_decision
python
microsoft/qlib
qlib/backtest/decision.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py
MIT
def check_stock_suspended( self, stock_id: str, start_time: pd.Timestamp, end_time: pd.Timestamp, ) -> bool: """if stock is suspended(hence not tradable), True will be returned""" # is suspended if stock_id in self.quote.get_all_stock(): # suspende...
if stock is suspended(hence not tradable), True will be returned
check_stock_suspended
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def deal_order( self, order: Order, trade_account: Account | None = None, position: BasePosition | None = None, dealt_order_amount: Dict[str, float] = defaultdict(float), ) -> Tuple[float, float, float]: """ Deal order when the actual transaction the r...
Deal order when the actual transaction the results section in `Order` will be changed. :param order: Deal the order. :param trade_account: Trade account to be updated after dealing the order. :param position: position to be updated after dealing the order. :param dealt_...
deal_order
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def get_volume( self, stock_id: str, start_time: pd.Timestamp, end_time: pd.Timestamp, method: Optional[str] = "sum", ) -> Union[None, int, float, bool, IndexData]: """get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time)"...
get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time)
get_volume
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def get_factor( self, stock_id: str, start_time: pd.Timestamp, end_time: pd.Timestamp, ) -> Optional[float]: """ Returns ------- Optional[float]: `None`: if the stock is suspended `None` may be returned `float`: return factor if...
Returns ------- Optional[float]: `None`: if the stock is suspended `None` may be returned `float`: return factor if the factor exists
get_factor
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def generate_amount_position_from_weight_position( self, weight_position: dict, cash: float, start_time: pd.Timestamp, end_time: pd.Timestamp, direction: OrderDir = OrderDir.BUY, ) -> dict: """ Generates the target position according to the weight and ...
Generates the target position according to the weight and the cash. NOTE: All the cash will be assigned to the tradable stock. Parameter: weight_position : dict {stock_id : weight}; allocate cash by weight_position among then, weight must be in this range: 0 < weight < 1 ...
generate_amount_position_from_weight_position
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def get_real_deal_amount(self, current_amount: float, target_amount: float, factor: float | None = None) -> float: """ Calculate the real adjust deal amount when considering the trading unit :param current_amount: :param target_amount: :param factor: :return real_deal_am...
Calculate the real adjust deal amount when considering the trading unit :param current_amount: :param target_amount: :param factor: :return real_deal_amount; Positive deal_amount indicates buying more stock.
get_real_deal_amount
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def generate_order_for_target_amount_position( self, target_position: dict, current_position: dict, start_time: pd.Timestamp, end_time: pd.Timestamp, ) -> List[Order]: """ Note: some future information is used in this function Parameter: target...
Note: some future information is used in this function Parameter: target_position : dict { stock_id : amount } current_position : dict { stock_id : amount} trade_unit : trade_unit down sample : for amount 321 and trade_unit 100, deal_amount is 300 deal order on t...
generate_order_for_target_amount_position
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def calculate_amount_position_value( self, amount_dict: dict, start_time: pd.Timestamp, end_time: pd.Timestamp, only_tradable: bool = False, direction: OrderDir = OrderDir.SELL, ) -> float: """Parameter position : Position() amount_dict : {stoc...
Parameter position : Position() amount_dict : {stock_id : amount} direction : the direction of the deal price for estimating the amount # NOTE: This function is used for calculating current position value. So the default direction is se...
calculate_amount_position_value
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def _get_factor_or_raise_error( self, factor: float | None = None, stock_id: str | None = None, start_time: pd.Timestamp = None, end_time: pd.Timestamp = None, ) -> float: """Please refer to the docs of get_amount_of_trade_unit""" if factor is None: ...
Please refer to the docs of get_amount_of_trade_unit
_get_factor_or_raise_error
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def get_amount_of_trade_unit( self, factor: float | None = None, stock_id: str | None = None, start_time: pd.Timestamp = None, end_time: pd.Timestamp = None, ) -> Optional[float]: """ get the trade unit of amount based on **factor** the factor can be g...
get the trade unit of amount based on **factor** the factor can be given directly or calculated in given time range and stock id. `factor` has higher priority than `stock_id`, `start_time` and `end_time` Parameters ---------- factor : float the adjusted facto...
get_amount_of_trade_unit
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def round_amount_by_trade_unit( self, deal_amount: float, factor: float | None = None, stock_id: str | None = None, start_time: pd.Timestamp = None, end_time: pd.Timestamp = None, ) -> float: """Parameter Please refer to the docs of get_amount_of_trade...
Parameter Please refer to the docs of get_amount_of_trade_unit deal_amount : float, adjusted amount factor : float, adjusted factor return : float, real amount
round_amount_by_trade_unit
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def _calc_trade_info_by_order( self, order: Order, position: Optional[BasePosition], dealt_order_amount: dict, ) -> Tuple[float, float, float]: """ Calculation of trade info **NOTE**: Order will be changed in this function :param order: :param ...
Calculation of trade info **NOTE**: Order will be changed in this function :param order: :param position: Position :param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float} :return: trade_price, trade_val, trade_cost
_calc_trade_info_by_order
python
microsoft/qlib
qlib/backtest/exchange.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py
MIT
def __init__( self, time_per_step: str, start_time: Union[str, pd.Timestamp] = None, end_time: Union[str, pd.Timestamp] = None, indicator_config: dict = {}, generate_portfolio_metrics: bool = False, verbose: bool = False, track_data: bool = False, ...
Parameters ---------- time_per_step : str trade time per trading step, used for generate the trade calendar show_indicator: bool, optional whether to show indicators, : - 'pa', the price advantage - 'pos', the positive rate - '...
__init__
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def reset(self, common_infra: CommonInfrastructure | None = None, **kwargs: Any) -> None: """ - reset `start_time` and `end_time`, used in trade calendar - reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc """ if "start_time" in kwargs or "end_time" in ...
- reset `start_time` and `end_time`, used in trade calendar - reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc
reset
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def execute(self, trade_decision: BaseTradeDecision, level: int = 0) -> List[object]: """execute the trade decision and return the executed result NOTE: this function is never used directly in the framework. Should we delete it? Parameters ---------- trade_decision : BaseTradeD...
execute the trade decision and return the executed result NOTE: this function is never used directly in the framework. Should we delete it? Parameters ---------- trade_decision : BaseTradeDecision level : int the level of current executor Returns -...
execute
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def _collect_data( self, trade_decision: BaseTradeDecision, level: int = 0, ) -> Union[Generator[Any, Any, Tuple[List[object], dict]], Tuple[List[object], dict]]: """ Please refer to the doc of collect_data The only difference between `_collect_data` and `collect_data...
Please refer to the doc of collect_data The only difference between `_collect_data` and `collect_data` is that some common steps are moved into collect_data Parameters ---------- Please refer to the doc of collect_data Returns ------- Tuple[Lis...
_collect_data
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def collect_data( self, trade_decision: BaseTradeDecision, return_value: dict | None = None, level: int = 0, ) -> Generator[Any, Any, List[object]]: """Generator for collecting the trade decision data for rl training his function will make a step forward Par...
Generator for collecting the trade decision data for rl training his function will make a step forward Parameters ---------- trade_decision : BaseTradeDecision level : int the level of current executor. 0 indicates the top level return_value : dict ...
collect_data
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def reset_common_infra(self, common_infra: CommonInfrastructure, copy_trade_account: bool = False) -> None: """ reset infrastructure for trading - reset inner_strategy and inner_executor common infra """ # NOTE: please refer to the docs of BaseExecutor.reset_common_infra for ...
reset infrastructure for trading - reset inner_strategy and inner_executor common infra
reset_common_infra
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def __init__( self, time_per_step: str, start_time: Union[str, pd.Timestamp] = None, end_time: Union[str, pd.Timestamp] = None, indicator_config: dict = {}, generate_portfolio_metrics: bool = False, verbose: bool = False, track_data: bool = False, ...
Parameters ---------- trade_type: str please refer to the doc of `TT_SERIAL` & `TT_PARAL`
__init__
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def _get_order_iterator(self, trade_decision: BaseTradeDecision) -> List[Order]: """ Parameters ---------- trade_decision : BaseTradeDecision the trade decision given by the strategy Returns ------- List[Order]: get a list orders accordin...
Parameters ---------- trade_decision : BaseTradeDecision the trade decision given by the strategy Returns ------- List[Order]: get a list orders according to `self.trade_type`
_get_order_iterator
python
microsoft/qlib
qlib/backtest/executor.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py
MIT
def get_data( self, stock_id: str, start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], field: Union[str], method: Optional[str] = None, ) -> Union[None, int, float, bool, IndexData]: """get the specific field of stock data during start ti...
get the specific field of stock data during start time and end_time, and apply method to the data. Example: .. code-block:: $close $volume instrument datetime SH600000 2010-01-04 86.778313 16162960.0 ...
get_data
python
microsoft/qlib
qlib/backtest/high_performance_ds.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py
MIT
def __init__(self, quote_df: pd.DataFrame, freq: str, region: str = "cn") -> None: """NumpyQuote Parameters ---------- quote_df : pd.DataFrame the init dataframe from qlib. self.data : Dict(stock_id, IndexData.DataFrame) """ super().__init__(quote_df=...
NumpyQuote Parameters ---------- quote_df : pd.DataFrame the init dataframe from qlib. self.data : Dict(stock_id, IndexData.DataFrame)
__init__
python
microsoft/qlib
qlib/backtest/high_performance_ds.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py
MIT
def transfer(self, func: Callable, new_col: str = None) -> Optional[BaseSingleMetric]: """compute new metric with existing metrics. Parameters ---------- func : Callable the func of computing new metric. the kwargs of func will be replaced with metric data by nam...
compute new metric with existing metrics. Parameters ---------- func : Callable the func of computing new metric. the kwargs of func will be replaced with metric data by name in this function. e.g. def func(pa): return (pa ...
transfer
python
microsoft/qlib
qlib/backtest/high_performance_ds.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py
MIT
def sum_all_indicators( order_indicator: BaseOrderIndicator, indicators: List[BaseOrderIndicator], metrics: Union[str, List[str]], fill_value: float = 0, ) -> None: """sum indicators with the same metrics. and assign to the order_indicator(BaseOrderIndicator). ...
sum indicators with the same metrics. and assign to the order_indicator(BaseOrderIndicator). NOTE: indicators could be a empty list when orders in lower level all fail. Parameters ---------- order_indicator : BaseOrderIndicator the order indicator to assign. ...
sum_all_indicators
python
microsoft/qlib
qlib/backtest/high_performance_ds.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py
MIT
def __init__(self, cash: float = 0, position_dict: Dict[str, Union[Dict[str, float], float]] = {}) -> None: """Init position by cash and position_dict. Parameters ---------- cash : float, optional initial cash in account, by default 0 position_dict : Dict[ ...
Init position by cash and position_dict. Parameters ---------- cash : float, optional initial cash in account, by default 0 position_dict : Dict[ stock_id, Union[ int, # it is equal to {...
__init__
python
microsoft/qlib
qlib/backtest/position.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py
MIT
def fill_stock_value(self, start_time: Union[str, pd.Timestamp], freq: str, last_days: int = 30) -> None: """fill the stock value by the close price of latest last_days from qlib. Parameters ---------- start_time : the start time of backtest. freq : str F...
fill the stock value by the close price of latest last_days from qlib. Parameters ---------- start_time : the start time of backtest. freq : str Frequency last_days : int, optional the days to get the latest close price, by default 30. ...
fill_stock_value
python
microsoft/qlib
qlib/backtest/position.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py
MIT
def _init_stock(self, stock_id: str, amount: float, price: float | None = None) -> None: """ initialization the stock in current position Parameters ---------- stock_id : the id of the stock amount : float the amount of the stock price : ...
initialization the stock in current position Parameters ---------- stock_id : the id of the stock amount : float the amount of the stock price : the price when buying the init stock
_init_stock
python
microsoft/qlib
qlib/backtest/position.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py
MIT
def get_stock_count(self, code: str, bar: str) -> float: """the days the account has been hold, it may be used in some special strategies""" if f"count_{bar}" in self.position[code]: return self.position[code][f"count_{bar}"] else: return 0
the days the account has been hold, it may be used in some special strategies
get_stock_count
python
microsoft/qlib
qlib/backtest/position.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py
MIT
def get_stock_amount_dict(self) -> dict: """generate stock amount dict {stock_id : amount of stock}""" d = {} stock_list = self.get_stock_list() for stock_code in stock_list: d[stock_code] = self.get_stock_amount(code=stock_code) return d
generate stock amount dict {stock_id : amount of stock}
get_stock_amount_dict
python
microsoft/qlib
qlib/backtest/position.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py
MIT
def get_stock_weight_dict(self, only_stock: bool = False) -> dict: """get_stock_weight_dict generate stock weight dict {stock_id : value weight of stock in the position} it is meaningful in the beginning or the end of each trade date :param only_stock: If only_stock=True, the weight of ...
get_stock_weight_dict generate stock weight dict {stock_id : value weight of stock in the position} it is meaningful in the beginning or the end of each trade date :param only_stock: If only_stock=True, the weight of each stock in total stock will be returned If only_...
get_stock_weight_dict
python
microsoft/qlib
qlib/backtest/position.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py
MIT
def get_benchmark_weight( bench, start_date=None, end_date=None, path=None, freq="day", ): """get_benchmark_weight get the stock weight distribution of the benchmark :param bench: :param start_date: :param end_date: :param path: :param freq: :return: The weight dis...
get_benchmark_weight get the stock weight distribution of the benchmark :param bench: :param start_date: :param end_date: :param path: :param freq: :return: The weight distribution of the the benchmark described by a pandas dataframe Every row corresponds to a trading day. ...
get_benchmark_weight
python
microsoft/qlib
qlib/backtest/profit_attribution.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py
MIT
def get_stock_weight_df(positions): """get_stock_weight_df :param positions: Given a positions from backtest result. :return: A weight distribution for the position """ stock_weight = [] index = [] for date in sorted(positions.keys()): pos = positions[date] if isinst...
get_stock_weight_df :param positions: Given a positions from backtest result. :return: A weight distribution for the position
get_stock_weight_df
python
microsoft/qlib
qlib/backtest/profit_attribution.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py
MIT
def decompose_portofolio_weight(stock_weight_df, stock_group_df): """decompose_portofolio_weight ''' :param stock_weight_df: a pandas dataframe to describe the portofolio by weight. every row corresponds to a day every column corresponds to a stock. ...
decompose_portofolio_weight ''' :param stock_weight_df: a pandas dataframe to describe the portofolio by weight. every row corresponds to a day every column corresponds to a stock. Here is an example below. code SH600004 S...
decompose_portofolio_weight
python
microsoft/qlib
qlib/backtest/profit_attribution.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py
MIT
def decompose_portofolio(stock_weight_df, stock_group_df, stock_ret_df): """ :param stock_weight_df: a pandas dataframe to describe the portofolio by weight. every row corresponds to a day every column corresponds to a stock. Here is an example below....
:param stock_weight_df: a pandas dataframe to describe the portofolio by weight. every row corresponds to a day every column corresponds to a stock. Here is an example below. code SH600004 SH600006 SH600017 SH600022 SH60002...
decompose_portofolio
python
microsoft/qlib
qlib/backtest/profit_attribution.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py
MIT
def get_daily_bin_group(bench_values, stock_values, group_n): """get_daily_bin_group Group the values of the stocks of benchmark into several bins in a day. Put the stocks into these bins. :param bench_values: A series contains the value of stocks in benchmark. The index is the...
get_daily_bin_group Group the values of the stocks of benchmark into several bins in a day. Put the stocks into these bins. :param bench_values: A series contains the value of stocks in benchmark. The index is the stock code. :param stock_values: A series contains the value of ...
get_daily_bin_group
python
microsoft/qlib
qlib/backtest/profit_attribution.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py
MIT
def brinson_pa( positions, bench="SH000905", group_field="industry", group_method="category", group_n=None, deal_price="vwap", freq="day", ): """brinson profit attribution :param positions: The position produced by the backtest class :param bench: The benchmark for comparing. TO...
brinson profit attribution :param positions: The position produced by the backtest class :param bench: The benchmark for comparing. TODO: if no benchmark is set, the equal-weighted is used. :param group_field: The field used to set the group for assets allocation. `industry` and `ma...
brinson_pa
python
microsoft/qlib
qlib/backtest/profit_attribution.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py
MIT
def load_portfolio_metrics(self, path: str) -> None: """load pm from a file should have format like columns = ['account', 'return', 'total_turnover', 'turnover', 'cost', 'total_cost', 'value', 'cash', 'bench'] :param path: str/ pathlib.Path() """ with ...
load pm from a file should have format like columns = ['account', 'return', 'total_turnover', 'turnover', 'cost', 'total_cost', 'value', 'cash', 'bench'] :param path: str/ pathlib.Path()
load_portfolio_metrics
python
microsoft/qlib
qlib/backtest/report.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/report.py
MIT
def _get_base_vol_pri( self, inst: str, trade_start_time: pd.Timestamp, trade_end_time: pd.Timestamp, direction: OrderDir, decision: BaseTradeDecision, trade_exchange: Exchange, pa_config: dict = {}, ) -> Tuple[Optional[float], Optional[float]]: ...
Get the base volume and price information All the base price values are rooted from this function
_get_base_vol_pri
python
microsoft/qlib
qlib/backtest/report.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/report.py
MIT
def _agg_base_price( self, inner_order_indicators: List[BaseOrderIndicator], decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]], trade_exchange: Exchange, pa_config: dict = {}, ) -> None: """ # NOTE:!!!! # Strong assumption!!!!!!...
# NOTE:!!!! # Strong assumption!!!!!! # the correctness of the base_price relies on that the **same** exchange is used Parameters ---------- inner_order_indicators : List[BaseOrderIndicator] the indicators of account of inner executor decision_list: ...
_agg_base_price
python
microsoft/qlib
qlib/backtest/report.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/report.py
MIT
def get_signal(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Union[pd.Series, pd.DataFrame, None]: """ get the signal at the end of the decision step(from `start_time` to `end_time`) Returns ------- Union[pd.Series, pd.DataFrame, None]: returns None if n...
get the signal at the end of the decision step(from `start_time` to `end_time`) Returns ------- Union[pd.Series, pd.DataFrame, None]: returns None if no signal in the specific day
get_signal
python
microsoft/qlib
qlib/backtest/signal.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/signal.py
MIT
def _update_model(self) -> None: """ When using online data, update model in each bar as the following steps: - update dataset with online data, the dataset should support online update - make the latest prediction scores of the new bar - update the pred score into th...
When using online data, update model in each bar as the following steps: - update dataset with online data, the dataset should support online update - make the latest prediction scores of the new bar - update the pred score into the latest prediction
_update_model
python
microsoft/qlib
qlib/backtest/signal.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/signal.py
MIT
def create_signal_from( obj: Union[Signal, Tuple[BaseModel, Dataset], List, Dict, Text, pd.Series, pd.DataFrame], ) -> Signal: """ create signal from diverse information This method will choose the right method to create a signal based on `obj` Please refer to the code below. """ if isinstan...
create signal from diverse information This method will choose the right method to create a signal based on `obj` Please refer to the code below.
create_signal_from
python
microsoft/qlib
qlib/backtest/signal.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/signal.py
MIT
def __init__( self, freq: str, start_time: Union[str, pd.Timestamp] = None, end_time: Union[str, pd.Timestamp] = None, level_infra: LevelInfrastructure | None = None, ) -> None: """ Parameters ---------- freq : str frequency of trad...
Parameters ---------- freq : str frequency of trading calendar, also trade time per trading step start_time : Union[str, pd.Timestamp], optional closed start of the trading calendar, by default None If `start_time` is None, it must be reset before tra...
__init__
python
microsoft/qlib
qlib/backtest/utils.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py
MIT
def reset( self, freq: str, start_time: Union[str, pd.Timestamp] = None, end_time: Union[str, pd.Timestamp] = None, ) -> None: """ Please refer to the docs of `__init__` Reset the trade calendar - self.trade_len : The total count for trading step ...
Please refer to the docs of `__init__` Reset the trade calendar - self.trade_len : The total count for trading step - self.trade_step : The number of trading step finished, self.trade_step can be [0, 1, 2, ..., self.trade_len - 1]
reset
python
microsoft/qlib
qlib/backtest/utils.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py
MIT
def get_step_time(self, trade_step: int | None = None, shift: int = 0) -> Tuple[pd.Timestamp, pd.Timestamp]: """ Get the left and right endpoints of the trade_step'th trading interval About the endpoints: - Qlib uses the closed interval in time-series data selection, which has the s...
Get the left and right endpoints of the trade_step'th trading interval About the endpoints: - Qlib uses the closed interval in time-series data selection, which has the same performance as pandas.Series.loc # - The returned right endpoints should minus 1 seconds bec...
get_step_time
python
microsoft/qlib
qlib/backtest/utils.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py
MIT
def get_range_idx(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Tuple[int, int]: """ get the range index which involve start_time~end_time (both sides are closed) Parameters ---------- start_time : pd.Timestamp end_time : pd.Timestamp Returns ...
get the range index which involve start_time~end_time (both sides are closed) Parameters ---------- start_time : pd.Timestamp end_time : pd.Timestamp Returns ------- Tuple[int, int]: the index of the range. **the left and right are closed*...
get_range_idx
python
microsoft/qlib
qlib/backtest/utils.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py
MIT
def create_account_instance( start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], benchmark: Optional[str], account: Union[float, int, dict], pos_type: str = "Position", ) -> Account: """ # TODO: is very strange pass benchmark_config in the account (maybe for report) ...
# TODO: is very strange pass benchmark_config in the account (maybe for report) # There should be a post-step to process the report. Parameters ---------- start_time start time of the benchmark end_time end time of the benchmark benchmark : str the benchmark for rep...
create_account_instance
python
microsoft/qlib
qlib/backtest/__init__.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py
MIT
def backtest( 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 = "Po...
initialize the strategy and executor, then backtest function for the interaction of the outermost strategy and executor in the nested decision execution Parameters ---------- start_time : Union[pd.Timestamp, str] closed start time for backtest **NOTE**: This will be applied to the outmo...
backtest
python
microsoft/qlib
qlib/backtest/__init__.py
https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py
MIT