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 run( self, times=1, models=None, dataset="Alpha360", universe="", exclude=False, qlib_uri: str = "git+https://github.com/microsoft/qlib#egg=pyqlib", exp_folder_name: str = "run_all_model_records", wait_before_rm_env: bool = False, wait_...
Please be aware that this function can only work under Linux. MacOS and Windows will be supported in the future. Any PR to enhance this method is highly welcomed. Besides, this script doesn't support parallel running the same model for multiple times, and this will be fixed in the future develo...
run
python
microsoft/qlib
examples/run_all_model.py
https://github.com/microsoft/qlib/blob/master/examples/run_all_model.py
MIT
def process_qlib_data(df, dataset, fillna=False): """Prepare data to fit the TFT model. Args: df: Original DataFrame. fillna: Whether to fill the data with the mean values. Returns: Transformed DataFrame. """ # Several features selected manually feature_col = DATASET_SETTING...
Prepare data to fit the TFT model. Args: df: Original DataFrame. fillna: Whether to fill the data with the mean values. Returns: Transformed DataFrame.
process_qlib_data
python
microsoft/qlib
examples/benchmarks/TFT/tft.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/tft.py
MIT
def process_predicted(df, col_name): """Transform the TFT predicted data into Qlib format. Args: df: Original DataFrame. fillna: New column name. Returns: Transformed DataFrame. """ df_res = df.copy() df_res = df_res.rename(columns={"forecast_time": "datetime", "identifier":...
Transform the TFT predicted data into Qlib format. Args: df: Original DataFrame. fillna: New column name. Returns: Transformed DataFrame.
process_predicted
python
microsoft/qlib
examples/benchmarks/TFT/tft.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/tft.py
MIT
def to_pickle(self, path: Union[Path, str]): """ Tensorflow model can't be dumped directly. So the data should be save separately **TODO**: Please implement the function to load the files Parameters ---------- path : Union[Path, str] the target path ...
Tensorflow model can't be dumped directly. So the data should be save separately **TODO**: Please implement the function to load the files Parameters ---------- path : Union[Path, str] the target path to be dumped
to_pickle
python
microsoft/qlib
examples/benchmarks/TFT/tft.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/tft.py
MIT
def get_column_definition(self): """Returns formatted column definition in order expected by the TFT.""" column_definition = self._column_definition # Sanity checks first. # Ensure only one ID and time column exist def _check_single_column(input_type): length = len(...
Returns formatted column definition in order expected by the TFT.
get_column_definition
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/base.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/base.py
MIT
def _get_tft_input_indices(self): """Returns the relevant indexes and input sizes required by TFT.""" # Functions def _extract_tuples_from_data_type(data_type, defn): return [tup for tup in defn if tup[1] == data_type and tup[2] not in {InputTypes.ID, InputTypes.TIME}] def ...
Returns the relevant indexes and input sizes required by TFT.
_get_tft_input_indices
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/base.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/base.py
MIT
def get_experiment_params(self): """Returns fixed model parameters for experiments.""" required_keys = [ "total_time_steps", "num_encoder_steps", "num_epochs", "early_stopping_patience", "multiprocessing_workers", ] fixed_para...
Returns fixed model parameters for experiments.
get_experiment_params
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/base.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/base.py
MIT
def split_data(self, df, valid_boundary=2016, test_boundary=2018): """Splits data frame into training-validation-test data frames. This also calibrates scaling object, and transforms data for each split. Args: df: Source data frame to split. valid_boundary: Starting year fo...
Splits data frame into training-validation-test data frames. This also calibrates scaling object, and transforms data for each split. Args: df: Source data frame to split. valid_boundary: Starting year for validation data test_boundary: Starting year for test data ...
split_data
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
MIT
def set_scalers(self, df): """Calibrates scalers using the data supplied. Args: df: Data to use to calibrate scalers. """ print("Setting scalers with training data...") column_definitions = self.get_column_definition() id_column = utils.get_single_col_by_input...
Calibrates scalers using the data supplied. Args: df: Data to use to calibrate scalers.
set_scalers
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
MIT
def transform_inputs(self, df): """Performs feature transformations. This includes both feature engineering, preprocessing and normalisation. Args: df: Data frame to transform. Returns: Transformed data frame. """ output = df.copy() if sel...
Performs feature transformations. This includes both feature engineering, preprocessing and normalisation. Args: df: Data frame to transform. Returns: Transformed data frame.
transform_inputs
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
MIT
def format_predictions(self, predictions): """Reverts any normalisation to give predictions in original scale. Args: predictions: Dataframe of model predictions. Returns: Data frame of unnormalised predictions. """ output = predictions.copy() column...
Reverts any normalisation to give predictions in original scale. Args: predictions: Dataframe of model predictions. Returns: Data frame of unnormalised predictions.
format_predictions
python
microsoft/qlib
examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/data_formatters/qlib_Alpha158.py
MIT
def __init__(self, experiment="volatility", root_folder=None): """Creates configs based on default experiment chosen. Args: experiment: Name of experiment. root_folder: Root folder to save all outputs of training. """ if experiment not in self.default_experiments: ...
Creates configs based on default experiment chosen. Args: experiment: Name of experiment. root_folder: Root folder to save all outputs of training.
__init__
python
microsoft/qlib
examples/benchmarks/TFT/expt_settings/configs.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/expt_settings/configs.py
MIT
def make_data_formatter(self): """Gets a data formatter object for experiment. Returns: Default DataFormatter per experiment. """ data_formatter_class = { "Alpha158": data_formatters.qlib_Alpha158.Alpha158Formatter, } return data_formatter_class[s...
Gets a data formatter object for experiment. Returns: Default DataFormatter per experiment.
make_data_formatter
python
microsoft/qlib
examples/benchmarks/TFT/expt_settings/configs.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/expt_settings/configs.py
MIT
def __init__(self, param_ranges, fixed_params, model_folder, override_w_fixed_params=True): """Instantiates model. Args: param_ranges: Discrete hyperparameter range for random search. fixed_params: Fixed model parameters per experiment. model_folder: Folder to store optimi...
Instantiates model. Args: param_ranges: Discrete hyperparameter range for random search. fixed_params: Fixed model parameters per experiment. model_folder: Folder to store optimisation artifacts. override_w_fixed_params: Whether to override serialsed fixed model ...
__init__
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def load_results(self): """Loads results from previous hyperparameter optimisation. Returns: A boolean indicating if previous results can be loaded. """ print("Loading results from", self.hyperparam_folder) results_file = os.path.join(self.hyperparam_folder, "results....
Loads results from previous hyperparameter optimisation. Returns: A boolean indicating if previous results can be loaded.
load_results
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def _get_params_from_name(self, name): """Returns previously saved parameters given a key.""" params = self.saved_params selected_params = dict(params[name]) if self._override_w_fixed_params: for k in self.fixed_params: selected_params[k] = self.fixed_params...
Returns previously saved parameters given a key.
_get_params_from_name
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def clear(self): """Clears all previous results and saved parameters.""" shutil.rmtree(self.hyperparam_folder) os.makedirs(self.hyperparam_folder) self.results = pd.DataFrame() self.saved_params = pd.DataFrame()
Clears all previous results and saved parameters.
clear
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def _check_params(self, params): """Checks that parameter map is properly defined.""" valid_fields = list(self.param_ranges.keys()) + list(self.fixed_params.keys()) invalid_fields = [k for k in params if k not in valid_fields] missing_fields = [k for k in valid_fields if k not in params...
Checks that parameter map is properly defined.
_check_params
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def _get_name(self, params): """Returns a unique key for the supplied set of params.""" self._check_params(params) fields = list(params.keys()) fields.sort() return "_".join([str(params[k]) for k in fields])
Returns a unique key for the supplied set of params.
_get_name
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def get_next_parameters(self, ranges_to_skip=None): """Returns the next set of parameters to optimise. Args: ranges_to_skip: Explicitly defines a set of keys to skip. """ if ranges_to_skip is None: ranges_to_skip = set(self.results.index) if not isinstance...
Returns the next set of parameters to optimise. Args: ranges_to_skip: Explicitly defines a set of keys to skip.
get_next_parameters
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def _get_next(): """Returns next hyperparameter set per try.""" parameters = {k: np.random.choice(self.param_ranges[k]) for k in param_range_keys} # Adds fixed params for k in self.fixed_params: parameters[k] = self.fixed_params[k] return pa...
Returns next hyperparameter set per try.
_get_next
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def update_score(self, parameters, loss, model, info=""): """Updates the results from last optimisation run. Args: parameters: Hyperparameters used in optimisation. loss: Validation loss obtained. model: Model to serialised if required. info: Any ancillary inform...
Updates the results from last optimisation run. Args: parameters: Hyperparameters used in optimisation. loss: Validation loss obtained. model: Model to serialised if required. info: Any ancillary information to tag on to results. Returns: Boolean flag ...
update_score
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def __init__( self, param_ranges, fixed_params, root_model_folder, worker_number, search_iterations=1000, num_iterations_per_worker=5, clear_serialised_params=False, ): """Instantiates optimisation manager. This hyperparameter optimisa...
Instantiates optimisation manager. This hyperparameter optimisation pre-generates #search_iterations hyperparameter combinations and serialises them at the start. At runtime, each worker goes through their own set of parameter ranges. The pregeneration allows for multiple worker...
__init__
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def get_next_parameters(self): """Returns next dictionary of hyperparameters to optimise.""" param_name = self.worker_search_queue.pop() params = self.global_hyperparam_df.loc[param_name, :].to_dict() # Always override! for k in self.fixed_params: print("Overriding ...
Returns next dictionary of hyperparameters to optimise.
get_next_parameters
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def load_serialised_hyperparam_df(self): """Loads serialsed hyperparameter ranges from file. Returns: DataFrame containing hyperparameter combinations. """ print( "Loading params for {} search iterations form {}".format( self.total_search_iterations...
Loads serialsed hyperparameter ranges from file. Returns: DataFrame containing hyperparameter combinations.
load_serialised_hyperparam_df
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def update_serialised_hyperparam_df(self): """Regenerates hyperparameter combinations and saves to file. Returns: DataFrame containing hyperparameter combinations. """ search_df = self._generate_full_hyperparam_df() print( "Serialising params for {} search...
Regenerates hyperparameter combinations and saves to file. Returns: DataFrame containing hyperparameter combinations.
update_serialised_hyperparam_df
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def _generate_full_hyperparam_df(self): """Generates actual hyperparameter combinations. Returns: DataFrame containing hyperparameter combinations. """ np.random.seed(131) # for reproducibility of hyperparam list name_list = [] param_list = [] for _ ...
Generates actual hyperparameter combinations. Returns: DataFrame containing hyperparameter combinations.
_generate_full_hyperparam_df
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def clear(self): # reset when cleared """Clears results for hyperparameter manager and resets.""" super().clear() self.worker_search_queue = self._get_worker_search_queue()
Clears results for hyperparameter manager and resets.
clear
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def load_results(self): """Load results from file and queue parameter combinations to try. Returns: Boolean indicating if results were successfully loaded. """ success = super().load_results() if success: self.worker_search_queue = self._get_worker_search_...
Load results from file and queue parameter combinations to try. Returns: Boolean indicating if results were successfully loaded.
load_results
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def _get_worker_search_queue(self): """Generates the queue of param combinations for current worker. Returns: Queue of hyperparameter combinations outstanding. """ global_df = self.assign_worker_numbers(self.global_hyperparam_df) worker_df = global_df[global_df["worker...
Generates the queue of param combinations for current worker. Returns: Queue of hyperparameter combinations outstanding.
_get_worker_search_queue
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def assign_worker_numbers(self, df): """Updates parameter combinations with the index of the worker used. Args: df: DataFrame of parameter combinations. Returns: Updated DataFrame with worker number. """ output = df.copy() n = self.total_search_iter...
Updates parameter combinations with the index of the worker used. Args: df: DataFrame of parameter combinations. Returns: Updated DataFrame with worker number.
assign_worker_numbers
python
microsoft/qlib
examples/benchmarks/TFT/libs/hyperparam_opt.py
https://github.com/microsoft/qlib/blob/master/examples/benchmarks/TFT/libs/hyperparam_opt.py
MIT
def linear_layer(size, activation=None, use_time_distributed=False, use_bias=True): """Returns simple Keras linear layer. Args: size: Output size activation: Activation function to apply if required use_time_distributed: Whether to apply layer across time use_bias: Whether bias should b...
Returns simple Keras linear layer. Args: size: Output size activation: Activation function to apply if required use_time_distributed: Whether to apply layer across time use_bias: Whether bias should be included in layer
linear_layer
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 apply_mlp( inputs, hidden_size, output_size, output_activation=None, hidden_activation="tanh", use_time_distributed=False ): """Applies simple feed-forward network to an input. Args: inputs: MLP inputs hidden_size: Hidden state size output_size: Output size of MLP output_activat...
Applies simple feed-forward network to an input. Args: inputs: MLP inputs hidden_size: Hidden state size output_size: Output size of MLP output_activation: Activation function to apply on output hidden_activation: Activation function to apply on input use_time_distributed: Wheth...
apply_mlp
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 apply_gating_layer(x, hidden_layer_size, dropout_rate=None, use_time_distributed=True, activation=None): """Applies a Gated Linear Unit (GLU) to an input. Args: x: Input to gating layer hidden_layer_size: Dimension of GLU dropout_rate: Dropout rate to apply if any use_time_distribut...
Applies a Gated Linear Unit (GLU) to an input. Args: x: Input to gating layer hidden_layer_size: Dimension of GLU dropout_rate: Dropout rate to apply if any use_time_distributed: Whether to apply across time activation: Activation function to apply to the linear feature transform if ...
apply_gating_layer
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 add_and_norm(x_list): """Applies skip connection followed by layer normalisation. Args: x_list: List of inputs to sum for skip connection Returns: Tensor output from layer. """ tmp = Add()(x_list) tmp = LayerNorm()(tmp) return tmp
Applies skip connection followed by layer normalisation. Args: x_list: List of inputs to sum for skip connection Returns: Tensor output from layer.
add_and_norm
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 gated_residual_network( x, hidden_layer_size, output_size=None, dropout_rate=None, use_time_distributed=True, additional_context=None, return_gate=False, ): """Applies the gated residual network (GRN) as defined in paper. Args: x: Network inputs hidden_layer_size: In...
Applies the gated residual network (GRN) as defined in paper. Args: x: Network inputs hidden_layer_size: Internal state size output_size: Size of output layer dropout_rate: Dropout rate if dropout is applied use_time_distributed: Whether to apply network across time dimension ad...
gated_residual_network
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_decoder_mask(self_attn_inputs): """Returns causal mask to apply for self-attention layer. Args: self_attn_inputs: Inputs to self attention layer to determine mask shape """ len_s = tf.shape(self_attn_inputs)[1] bs = tf.shape(self_attn_inputs)[:1] mask = K.cumsum(tf.eye(len_s, batc...
Returns causal mask to apply for self-attention layer. Args: self_attn_inputs: Inputs to self attention layer to determine mask shape
get_decoder_mask
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 __call__(self, q, k, v, mask): """Applies scaled dot product attention. Args: q: Queries k: Keys v: Values mask: Masking if required -- sets softmax to very large value Returns: Tuple of (layer outputs, attention weights) """ ...
Applies scaled dot product attention. Args: q: Queries k: Keys v: Values mask: Masking if required -- sets softmax to very large value Returns: Tuple of (layer outputs, attention weights)
__call__
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 __init__(self, n_head, d_model, dropout): """Initialises layer. Args: n_head: Number of heads d_model: TFT state dimensionality dropout: Dropout discard rate """ self.n_head = n_head self.d_k = self.d_v = d_k = d_v = d_model // n_head s...
Initialises layer. Args: n_head: Number of heads d_model: TFT state dimensionality dropout: Dropout discard rate
__init__
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 __call__(self, q, k, v, mask=None): """Applies interpretable multihead attention. Using T to denote the number of time steps fed into the transformer. Args: q: Query tensor of shape=(?, T, d_model) k: Key of shape=(?, T, d_model) v: Values of shape=(?, T, d_mo...
Applies interpretable multihead attention. Using T to denote the number of time steps fed into the transformer. Args: q: Query tensor of shape=(?, T, d_model) k: Key of shape=(?, T, d_model) v: Values of shape=(?, T, d_model) mask: Masking if required with shape...
__call__
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 __init__(self, raw_params, use_cudnn=False): """Builds TFT from parameters. Args: raw_params: Parameters to define TFT use_cudnn: Whether to use CUDNN GPU optimised LSTM """ self.name = self.__class__.__name__ params = dict(raw_params) # copy locally ...
Builds TFT from parameters. Args: raw_params: Parameters to define TFT use_cudnn: Whether to use CUDNN GPU optimised LSTM
__init__
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_tft_embeddings(self, all_inputs): """Transforms raw inputs to embeddings. Applies linear transformation onto continuous variables and uses embeddings for categorical variables. Args: all_inputs: Inputs to transform Returns: Tensors for transformed i...
Transforms raw inputs to embeddings. Applies linear transformation onto continuous variables and uses embeddings for categorical variables. Args: all_inputs: Inputs to transform Returns: Tensors for transformed inputs.
get_tft_embeddings
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 cache_batched_data(self, data, cache_key, num_samples=-1): """Batches and caches data once for using during training. Args: data: Data to batch and cache cache_key: Key used for cache num_samples: Maximum number of samples to extract (-1 to use all data) """ ...
Batches and caches data once for using during training. Args: data: Data to batch and cache cache_key: Key used for cache num_samples: Maximum number of samples to extract (-1 to use all data)
cache_batched_data
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 _batch_sampled_data(self, data, max_samples): """Samples segments into a compatible format. Args: data: Sources data to sample and batch max_samples: Maximum number of samples in batch Returns: Dictionary of batched data with the maximum samples specified. ...
Samples segments into a compatible format. Args: data: Sources data to sample and batch max_samples: Maximum number of samples in batch Returns: Dictionary of batched data with the maximum samples specified.
_batch_sampled_data
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 _batch_data(self, data): """Batches data for training. Converts raw dataframe from a 2-D tabular format to a batched 3-D array to feed into Keras model. Args: data: DataFrame to batch Returns: Batched Numpy array with shape=(?, self.time_steps, self.inp...
Batches data for training. Converts raw dataframe from a 2-D tabular format to a batched 3-D array to feed into Keras model. Args: data: DataFrame to batch Returns: Batched Numpy array with shape=(?, self.time_steps, self.input_size)
_batch_data
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 _build_base_graph(self): """Returns graph defining layers of the TFT.""" # Size definitions. time_steps = self.time_steps combined_input_size = self.input_size encoder_steps = self.num_encoder_steps # Inputs. all_inputs = tf.keras.layers.Input( s...
Returns graph defining layers of the TFT.
_build_base_graph
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 static_combine_and_mask(embedding): """Applies variable selection network to static inputs. Args: embedding: Transformed static inputs Returns: Tensor output for variable selection network """ # Add temporal features ...
Applies variable selection network to static inputs. Args: embedding: Transformed static inputs Returns: Tensor output for variable selection network
static_combine_and_mask
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 lstm_combine_and_mask(embedding): """Apply temporal variable selection networks. Args: embedding: Transformed inputs. Returns: Processed tensor outputs. """ # Add temporal features _, time_steps, embedding_dim, nu...
Apply temporal variable selection networks. Args: embedding: Transformed inputs. Returns: Processed tensor outputs.
lstm_combine_and_mask
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_lstm(return_state): """Returns LSTM cell initialized with default parameters.""" if self.use_cudnn: lstm = tf.keras.layers.CuDNNLSTM( self.hidden_layer_size, return_sequences=True, return_state=return_state, ...
Returns LSTM cell initialized with default parameters.
get_lstm
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 build_model(self): """Build model and defines training losses. Returns: Fully defined Keras model. """ with tf.variable_scope(self.name): transformer_layer, all_inputs, attention_components = self._build_base_graph() outputs = tf.keras.layers.Time...
Build model and defines training losses. Returns: Fully defined Keras model.
build_model
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 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