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 parse_position(position: dict = None) -> pd.DataFrame:
"""Parse position dict to position DataFrame
:param position: position data
:return: position DataFrame;
.. code-block:: python
position_df = parse_position(positions)
print(position_df.head())
# statu... | Parse position dict to position DataFrame
:param position: position data
:return: position DataFrame;
.. code-block:: python
position_df = parse_position(positions)
print(position_df.head())
# status: 0-hold, -1-sell, 1-buy
... | parse_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _add_label_to_position(position_df: pd.DataFrame, label_data: pd.DataFrame) -> pd.DataFrame:
"""Concat position with custom label
:param position_df: position DataFrame
:param label_data:
:return: concat result
"""
_start_time = position_df.index.get_level_values(level="datetime").min()
... | Concat position with custom label
:param position_df: position DataFrame
:param label_data:
:return: concat result
| _add_label_to_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _add_bench_to_position(position_df: pd.DataFrame = None, bench: pd.Series = None) -> pd.DataFrame:
"""Concat position with bench
:param position_df: position DataFrame
:param bench: report normal data
:return: concat result
"""
_temp_df = position_df.reset_index(level="instrument")
# FI... | Concat position with bench
:param position_df: position DataFrame
:param bench: report normal data
:return: concat result
| _add_bench_to_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _calculate_label_rank(df: pd.DataFrame) -> pd.DataFrame:
"""calculate label rank
:param df:
:return:
"""
_label_name = "label"
def _calculate_day_value(g_df: pd.DataFrame):
g_df = g_df.copy()
g_df["rank_ratio"] = g_df[_label_name].rank(ascending=False) / len(g_df) * 100
... | calculate label rank
:param df:
:return:
| _calculate_label_rank | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def get_position_data(
position: dict,
label_data: pd.DataFrame,
report_normal: pd.DataFrame = None,
calculate_label_rank=False,
start_date=None,
end_date=None,
) -> pd.DataFrame:
"""Concat position data with pred/report_normal
:param position: position data
:param report_normal: re... | Concat position data with pred/report_normal
:param position: position data
:param report_normal: report normal, must be container 'bench' column
:param label_data:
:param calculate_label_rank:
:param start_date: start date
:param end_date: end date
:return: concat result,
columns: ... | get_position_data | python | microsoft/qlib | qlib/contrib/report/analysis_position/parse_position.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/parse_position.py | MIT |
def _get_figure_with_position(
position: dict, label_data: pd.DataFrame, start_date=None, end_date=None
) -> Iterable[go.Figure]:
"""Get average analysis figures
:param position: position
:param label_data:
:param start_date:
:param end_date:
:return:
"""
_position_df = get_position... | Get average analysis figures
:param position: position
:param label_data:
:param start_date:
:param end_date:
:return:
| _get_figure_with_position | python | microsoft/qlib | qlib/contrib/report/analysis_position/rank_label.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/rank_label.py | MIT |
def _get_risk_analysis_data_with_report(
report_normal_df: pd.DataFrame,
# report_long_short_df: pd.DataFrame,
date: pd.Timestamp,
) -> pd.DataFrame:
"""Get risk analysis data with report
:param report_normal_df: report data
:param report_long_short_df: report data
:param date: date string
... | Get risk analysis data with report
:param report_normal_df: report data
:param report_long_short_df: report data
:param date: date string
:return:
| _get_risk_analysis_data_with_report | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_all_risk_analysis(risk_df: pd.DataFrame) -> pd.DataFrame:
"""risk_df to standard
:param risk_df: risk data
:return:
"""
if risk_df is None:
return pd.DataFrame()
risk_df = risk_df.unstack()
risk_df.columns = risk_df.columns.droplevel(0)
return risk_df.drop("mean", axis=... | risk_df to standard
:param risk_df: risk data
:return:
| _get_all_risk_analysis | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_monthly_risk_analysis_with_report(report_normal_df: pd.DataFrame) -> pd.DataFrame:
"""Get monthly analysis data
:param report_normal_df:
# :param report_long_short_df:
:return:
"""
# Group by month
report_normal_gp = report_normal_df.groupby(
[report_normal_df.index.year, ... | Get monthly analysis data
:param report_normal_df:
# :param report_long_short_df:
:return:
| _get_monthly_risk_analysis_with_report | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_risk_analysis_figure(analysis_df: pd.DataFrame) -> Iterable[py.Figure]:
"""Get analysis graph figure
:param analysis_df:
:return:
"""
if analysis_df is None:
return []
_figure = SubplotsGraph(
_get_all_risk_analysis(analysis_df),
kind_map=dict(kind="BarGraph", ... | Get analysis graph figure
:param analysis_df:
:return:
| _get_risk_analysis_figure | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def _get_monthly_risk_analysis_figure(report_normal_df: pd.DataFrame) -> Iterable[py.Figure]:
"""Get analysis monthly graph figure
:param report_normal_df:
:param report_long_short_df:
:return:
"""
# if report_normal_df is None and report_long_short_df is None:
# return []
if repor... | Get analysis monthly graph figure
:param report_normal_df:
:param report_long_short_df:
:return:
| _get_monthly_risk_analysis_figure | python | microsoft/qlib | qlib/contrib/report/analysis_position/risk_analysis.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/risk_analysis.py | MIT |
def score_ic_graph(pred_label: pd.DataFrame, show_notebook: bool = True, **kwargs) -> [list, tuple]:
"""score IC
Example:
.. code-block:: python
from qlib.data import D
from qlib.contrib.report import analysis_position
pred_df_dates = pred_df.i... | score IC
Example:
.. code-block:: python
from qlib.data import D
from qlib.contrib.report import analysis_position
pred_df_dates = pred_df.index.get_level_values(level='datetime')
features_df = D.features(D.instruments('csi500'), ['... | score_ic_graph | python | microsoft/qlib | qlib/contrib/report/analysis_position/score_ic.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/analysis_position/score_ic.py | MIT |
def __init__(self, dataset: pd.DataFrame):
"""
Parameters
----------
dataset : pd.DataFrame
We often have multiple columns for dataset. Each column corresponds to one sub figure.
There will be a datatime column in the index levels.
Aggretation will b... |
Parameters
----------
dataset : pd.DataFrame
We often have multiple columns for dataset. Each column corresponds to one sub figure.
There will be a datatime column in the index levels.
Aggretation will be used for more summarized metrics overtime.
... | __init__ | python | microsoft/qlib | qlib/contrib/report/data/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/report/data/base.py | MIT |
def __init__(
self,
conf_path: Union[str, Path],
exp_name: Optional[str] = None,
horizon: Optional[int] = 20,
step: int = 20,
h_path: Optional[str] = None,
train_start: Optional[str] = None,
test_end: Optional[str] = None,
task_ext_conf: Optional[d... |
Parameters
----------
conf_path : str
Path to the config for rolling.
exp_name : Optional[str]
The exp name of the outputs (Output is a record which contains the concatenated predictions of rolling records).
horizon: Optional[int] = 20,
The ho... | __init__ | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def _replace_handler_with_cache(self, task: dict):
"""
Due to the data processing part in original rolling is slow. So we have to
This class tries to add more feature
"""
if self.h_path is not None:
h_path = Path(self.h_path)
task["dataset"]["kwargs"]["han... |
Due to the data processing part in original rolling is slow. So we have to
This class tries to add more feature
| _replace_handler_with_cache | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def basic_task(self, enable_handler_cache: Optional[bool] = True):
"""
The basic task may not be the exactly same as the config from `conf_path` from __init__ due to
- some parameters could be overriding by some parameters from __init__
- user could implementing sublcass to change it for... |
The basic task may not be the exactly same as the config from `conf_path` from __init__ due to
- some parameters could be overriding by some parameters from __init__
- user could implementing sublcass to change it for higher performance
| basic_task | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def run_basic_task(self):
"""
Run the basic task without rolling.
This is for fast testing for model tunning.
"""
task = self.basic_task()
print(task)
trainer = TrainerR(experiment_name=self.exp_name)
trainer([task]) |
Run the basic task without rolling.
This is for fast testing for model tunning.
| run_basic_task | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def get_task_list(self) -> List[dict]:
"""return a batch of tasks for rolling."""
task = self.basic_task()
task_l = task_generator(
task, RollingGen(step=self.step, trunc_days=self.horizon + 1)
) # the last two days should be truncated to avoid information leakage
fo... | return a batch of tasks for rolling. | get_task_list | python | microsoft/qlib | qlib/contrib/rolling/base.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/base.py | MIT |
def __init__(
self,
sim_task_model: UTIL_MODEL_TYPE = "gbdt",
meta_1st_train_end: Optional[str] = None,
alpha: float = 0.01,
loss_skip_thresh: int = 50,
fea_imp_n: Optional[int] = 30,
meta_data_proc: Optional[str] = "V01",
segments: Union[float, str] = 0.6... |
Parameters
----------
sim_task_model: Literal["linear", "gbdt"] = "gbdt",
The model for calculating similarity between data.
meta_1st_train_end: Optional[str]
the datetime of training end of the first meta_task
alpha: float
Setting the L2 reg... | __init__ | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _adjust_task(self, task: dict, astype: UTIL_MODEL_TYPE):
"""
Base on the original task, we need to do some extra things.
For example:
- GBDT for calculating feature importance
- Linear or GBDT for calculating similarity
- Datset (well processed) that aligned to Linea... |
Base on the original task, we need to do some extra things.
For example:
- GBDT for calculating feature importance
- Linear or GBDT for calculating similarity
- Datset (well processed) that aligned to Linear that for meta learning
So we may need to change the dataset a... | _adjust_task | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _dump_data_for_proxy_model(self):
"""
Dump data for training meta model.
The meta model will be trained upon the proxy forecasting model.
This dataset is for the proxy forecasting model.
"""
# NOTE: adjusting to `self.sim_task_model` just for aligning with previous i... |
Dump data for training meta model.
The meta model will be trained upon the proxy forecasting model.
This dataset is for the proxy forecasting model.
| _dump_data_for_proxy_model | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _dump_meta_ipt(self):
"""
Dump data for training meta model.
This function will dump the input data for meta model
"""
# According to the experiments, the choice of the model type is very important for achieving good results
sim_task = self._adjust_task(self.basic_tas... |
Dump data for training meta model.
This function will dump the input data for meta model
| _dump_meta_ipt | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def _train_meta_model(self, fill_method="max"):
"""
training a meta model based on a simplified linear proxy model;
"""
# 1) leverage the simplified proxy forecasting model to train meta model.
# - Only the dataset part is important, in current version of meta model will integra... |
training a meta model based on a simplified linear proxy model;
| _train_meta_model | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def get_task_list(self):
"""
Leverage meta-model for inference:
- Given
- baseline tasks
- input for meta model(internal data)
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
"""
... |
Leverage meta-model for inference:
- Given
- baseline tasks
- input for meta model(internal data)
- meta model (its learnt knowledge on proxy forecasting model is expected to transfer to normal forecasting model)
| get_task_list | python | microsoft/qlib | qlib/contrib/rolling/ddgda.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/rolling/ddgda.py | MIT |
def __init__(
self,
model,
dataset,
topk,
order_generator_cls_or_obj=OrderGenWInteract,
max_sold_weight=1.0,
risk_degree=0.95,
buy_method="first_fill",
trade_exchange=None,
level_infra=None,
common_infra=None,
**kwargs,
... |
Parameters
----------
topk : int
top-N stocks to buy
risk_degree : float
position percentage of total value buy_method:
rank_fill: assign the weight stocks that rank high first(1/topk max)
average_fill: assign the weight to the st... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/cost_control.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/cost_control.py | MIT |
def generate_target_weight_position(self, score, current, trade_start_time, trade_end_time):
"""
Parameters
----------
score:
pred score for this trade date, pd.Series, index is stock_id, contain 'score' column
current:
current position, use Position() cla... |
Parameters
----------
score:
pred score for this trade date, pd.Series, index is stock_id, contain 'score' column
current:
current position, use Position() class
trade_date:
trade date
generate target position from score for this ... | generate_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/cost_control.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/cost_control.py | MIT |
def generate_order_list_from_target_weight_position(
self,
current: Position,
trade_exchange: Exchange,
target_weight_position: dict,
risk_degree: float,
pred_start_time: pd.Timestamp,
pred_end_time: pd.Timestamp,
trade_start_time: pd.Timestamp,
tr... | generate_order_list_from_target_weight_position
:param current: The current position
:type current: Position
:param trade_exchange:
:type trade_exchange: Exchange
:param target_weight_position: {stock_id : weight}
:type target_weight_position: dict
:param risk_de... | generate_order_list_from_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/order_generator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/order_generator.py | MIT |
def generate_order_list_from_target_weight_position(
self,
current: Position,
trade_exchange: Exchange,
target_weight_position: dict,
risk_degree: float,
pred_start_time: pd.Timestamp,
pred_end_time: pd.Timestamp,
trade_start_time: pd.Timestamp,
tr... | generate_order_list_from_target_weight_position
No adjustment for for the nontradable share.
All the tadable value is assigned to the tadable stock according to the weight.
if interact == True, will use the price at trade date to generate order list
else, will only use the price before ... | generate_order_list_from_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/order_generator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/order_generator.py | MIT |
def generate_order_list_from_target_weight_position(
self,
current: Position,
trade_exchange: Exchange,
target_weight_position: dict,
risk_degree: float,
pred_start_time: pd.Timestamp,
pred_end_time: pd.Timestamp,
trade_start_time: pd.Timestamp,
tr... | generate_order_list_from_target_weight_position
generate order list directly not using the information (e.g. whether can be traded, the accurate trade price)
at trade date.
In target weight position, generating order list need to know the price of objective stock in trade date,
but we ... | generate_order_list_from_target_weight_position | python | microsoft/qlib | qlib/contrib/strategy/order_generator.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/order_generator.py | MIT |
def __init__(
self,
outer_trade_decision: BaseTradeDecision = None,
instruments: Union[List, str] = "csi300",
freq: str = "day",
trade_exchange: Exchange = None,
level_infra: LevelInfrastructure = None,
common_infra: CommonInfrastructure = None,
**kwargs,
... |
Parameters
----------
instruments : Union[List, str], optional
instruments of EMA signal, by default "csi300"
freq : str, optional
freq of EMA signal, by default "day"
Note: `freq` may be different from `time_per_step`
| __init__ | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def __init__(
self,
lamb: float = 1e-6,
eta: float = 2.5e-6,
window_size: int = 20,
outer_trade_decision: BaseTradeDecision = None,
instruments: Union[List, str] = "csi300",
freq: str = "day",
trade_exchange: Exchange = None,
level_infra: LevelInfr... |
Parameters
----------
instruments : Union[List, str], optional
instruments of Volatility, by default "csi300"
freq : str, optional
freq of Volatility, by default "day"
Note: `freq` may be different from `time_per_step`
| __init__ | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def __init__(
self,
trade_range: Union[Tuple[int, int], TradeRange], # The range is closed on both left and right.
sample_ratio: float = 1.0,
volume_ratio: float = 0.01,
market: str = "all",
direction: int = Order.BUY,
*args,
**kwargs,
):
"""
... |
Parameters
----------
trade_range : Tuple
please refer to the `trade_range` parameter of BaseStrategy
sample_ratio : float
the ratio of all orders are sampled
volume_ratio : float
the volume of the total day
raito of the total volu... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def generate_trade_decision(self, execute_result=None) -> TradeDecisionWO:
"""
Parameters
----------
execute_result :
execute_result will be ignored in FileOrderStrategy
"""
oh: OrderHelper = self.common_infra.get("trade_exchange").get_order_helper()
s... |
Parameters
----------
execute_result :
execute_result will be ignored in FileOrderStrategy
| generate_trade_decision | python | microsoft/qlib | qlib/contrib/strategy/rule_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/rule_strategy.py | MIT |
def __init__(
self,
*,
signal: Union[Signal, Tuple[BaseModel, Dataset], List, Dict, Text, pd.Series, pd.DataFrame] = None,
model=None,
dataset=None,
risk_degree: float = 0.95,
trade_exchange=None,
level_infra=None,
common_infra=None,
**kwar... |
Parameters
-----------
signal :
the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from`
the decision of the strategy will base on the given signal
risk_degree : float
position percentage of total val... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/signal_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/signal_strategy.py | MIT |
def __init__(
self,
*,
order_generator_cls_or_obj=OrderGenWOInteract,
**kwargs,
):
"""
signal :
the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from`
the decision of the strategy will base o... |
signal :
the information to describe a signal. Please refer to the docs of `qlib.backtest.signal.create_signal_from`
the decision of the strategy will base on the given signal
trade_exchange : Exchange
exchange that provides market info, used to deal order and genera... | __init__ | python | microsoft/qlib | qlib/contrib/strategy/signal_strategy.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/signal_strategy.py | MIT |
def __call__(
self,
r: np.ndarray,
F: np.ndarray,
cov_b: np.ndarray,
var_u: np.ndarray,
w0: np.ndarray,
wb: np.ndarray,
mfh: Optional[np.ndarray] = None,
mfs: Optional[np.ndarray] = None,
) -> np.ndarray:
"""
Args:
r... |
Args:
r (np.ndarray): expected returns
F (np.ndarray): factor exposure
cov_b (np.ndarray): factor covariance
var_u (np.ndarray): residual variance
w0 (np.ndarray): current holding weights
wb (np.ndarray): benchmark weights
mfh ... | __call__ | python | microsoft/qlib | qlib/contrib/strategy/optimizer/enhanced_indexing.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/enhanced_indexing.py | MIT |
def __call__(
self,
S: Union[np.ndarray, pd.DataFrame],
r: Optional[Union[np.ndarray, pd.Series]] = None,
w0: Optional[Union[np.ndarray, pd.Series]] = None,
) -> Union[np.ndarray, pd.Series]:
"""
Args:
S (np.ndarray or pd.DataFrame): covariance matrix
... |
Args:
S (np.ndarray or pd.DataFrame): covariance matrix
r (np.ndarray or pd.Series): expected return
w0 (np.ndarray or pd.Series): initial weights (for turnover control)
Returns:
np.ndarray or pd.Series: optimized portfolio allocation
| __call__ | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _optimize_mvo(
self, S: np.ndarray, r: Optional[np.ndarray] = None, w0: Optional[np.ndarray] = None
) -> np.ndarray:
"""optimize mean-variance portfolio
This method solves the following optimization problem
min_w - w' r + lamb * w' S w
s.t. w >= 0, sum(w) == ... | optimize mean-variance portfolio
This method solves the following optimization problem
min_w - w' r + lamb * w' S w
s.t. w >= 0, sum(w) == 1
where `S` is the covariance matrix, `u` is the expected returns,
and `lamb` is the risk aversion parameter.
| _optimize_mvo | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_objective_gmv(self, S: np.ndarray) -> Callable:
"""global minimum variance optimization objective
Optimization objective
min_w w' S w
"""
def func(x):
return x @ S @ x
return func | global minimum variance optimization objective
Optimization objective
min_w w' S w
| _get_objective_gmv | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_objective_mvo(self, S: np.ndarray, r: np.ndarray = None) -> Callable:
"""mean-variance optimization objective
Optimization objective
min_w - w' r + lamb * w' S w
"""
def func(x):
risk = x @ S @ x
ret = x @ r
return -ret + self.la... | mean-variance optimization objective
Optimization objective
min_w - w' r + lamb * w' S w
| _get_objective_mvo | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_objective_rp(self, S: np.ndarray) -> Callable:
"""risk-parity optimization objective
Optimization objective
min_w sum_i [w_i - (w' S w) / ((S w)_i * N)]**2
"""
def func(x):
N = len(x)
Sx = S @ x
xSx = x @ Sx
return np... | risk-parity optimization objective
Optimization objective
min_w sum_i [w_i - (w' S w) / ((S w)_i * N)]**2
| _get_objective_rp | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _get_constrains(self, w0: Optional[np.ndarray] = None):
"""optimization constraints
Defines the following constraints:
- no shorting and leverage: 0 <= w <= 1
- full investment: sum(w) == 1
- turnover constraint: |w - w0| <= delta
"""
# no shorti... | optimization constraints
Defines the following constraints:
- no shorting and leverage: 0 <= w <= 1
- full investment: sum(w) == 1
- turnover constraint: |w - w0| <= delta
| _get_constrains | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def _solve(self, n: int, obj: Callable, bounds: so.Bounds, cons: List) -> np.ndarray:
"""solve optimization
Args:
n (int): number of parameters
obj (callable): optimization objective
bounds (Bounds): bounds of parameters
cons (list): optimization constrai... | solve optimization
Args:
n (int): number of parameters
obj (callable): optimization objective
bounds (Bounds): bounds of parameters
cons (list): optimization constraints
| _solve | python | microsoft/qlib | qlib/contrib/strategy/optimizer/optimizer.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/strategy/optimizer/optimizer.py | MIT |
def __init__(self, config, TUNER_CONFIG_MANAGER):
"""
:param config: The config dict for tuner experiment
:param TUNER_CONFIG_MANAGER: The tuner config manager
"""
self.name = config.get("name", "tuner_experiment")
# The dir of the config
self.global_dir = conf... |
:param config: The config dict for tuner experiment
:param TUNER_CONFIG_MANAGER: The tuner config manager
| __init__ | python | microsoft/qlib | qlib/contrib/tuner/config.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/tuner/config.py | MIT |
def init_tuner(self, tuner_index, tuner_config):
"""
Implement this method to build the tuner by config
return: tuner
"""
# 1. Add experiment config in tuner_config
tuner_config["experiment"] = {
"name": "estimator_experiment_{}".format(tuner_index),
... |
Implement this method to build the tuner by config
return: tuner
| init_tuner | python | microsoft/qlib | qlib/contrib/tuner/pipeline.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/tuner/pipeline.py | MIT |
def load(self, instrument, start_index, end_index, *args):
"""load feature
This function is responsible for loading feature/expression based on the expression engine.
The concrete implementation will be separated into two parts:
1) caching data, handle errors.
- This part... | load feature
This function is responsible for loading feature/expression based on the expression engine.
The concrete implementation will be separated into two parts:
1) caching data, handle errors.
- This part is shared by all the expressions and implemented in Expression
... | load | python | microsoft/qlib | qlib/data/base.py | https://github.com/microsoft/qlib/blob/master/qlib/data/base.py | MIT |
def get_longest_back_rolling(self):
"""Get the longest length of historical data the feature has accessed
This is designed for getting the needed range of the data to calculate
the features in specific range at first. However, situations like
Ref(Ref($close, -1), 1) can not be handled ... | Get the longest length of historical data the feature has accessed
This is designed for getting the needed range of the data to calculate
the features in specific range at first. However, situations like
Ref(Ref($close, -1), 1) can not be handled rightly.
So this will only used for de... | get_longest_back_rolling | python | microsoft/qlib | qlib/data/base.py | https://github.com/microsoft/qlib/blob/master/qlib/data/base.py | MIT |
def get_cache(mem_cache, key):
"""get mem cache
:param mem_cache: MemCache attribute('c'/'i'/'f').
:param key: cache key.
:return: cache value; if cache not exist, return None.
"""
value = None
expire = False
if key in mem_cache:
value, latest... | get mem cache
:param mem_cache: MemCache attribute('c'/'i'/'f').
:param key: cache key.
:return: cache value; if cache not exist, return None.
| get_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def expression(self, instrument, field, start_time, end_time, freq):
"""Get expression data.
.. note:: Same interface as `expression` method in expression provider
"""
try:
return self._expression(instrument, field, start_time, end_time, freq)
except NotImplementedEr... | Get expression data.
.. note:: Same interface as `expression` method in expression provider
| expression | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def dataset(
self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
):
"""Get feature dataset.
.. note:: Same interface as `dataset` method in dataset provider
.. note:: The server use redis_lock to make sure
read-write c... | Get feature dataset.
.. note:: Same interface as `dataset` method in dataset provider
.. note:: The server use redis_lock to make sure
read-write conflicts will not be triggered
but client readers are not considered.
| dataset | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def _dataset(
self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
):
"""Get feature dataset using cache.
Override this method to define how to get feature dataset corresponding to users' own cache mechanism.
"""
raise NotIm... | Get feature dataset using cache.
Override this method to define how to get feature dataset corresponding to users' own cache mechanism.
| _dataset | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def _dataset_uri(
self, instruments, fields, start_time=None, end_time=None, freq="day", disk_cache=1, inst_processors=[]
):
"""Get a uri of feature dataset using cache.
specially:
disk_cache=1 means using data set cache and return the uri of cache file.
disk_cache=0 ... | Get a uri of feature dataset using cache.
specially:
disk_cache=1 means using data set cache and return the uri of cache file.
disk_cache=0 means client knows the path of expression cache,
server checks if the cache exists(if not, generate it), and client loads d... | _dataset_uri | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def cache_to_origin_data(data, fields):
"""cache data to origin data
:param data: pd.DataFrame, cache data.
:param fields: feature fields.
:return: pd.DataFrame.
"""
not_space_fields = remove_fields_space(fields)
data = data.loc[:, not_space_fields]
# set... | cache data to origin data
:param data: pd.DataFrame, cache data.
:param fields: feature fields.
:return: pd.DataFrame.
| cache_to_origin_data | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def gen_expression_cache(self, expression_data, cache_path, instrument, field, freq, last_update):
"""use bin file to save like feature-data."""
# Make sure the cache runs right when the directory is deleted
# while running
meta = {
"info": {"instrument": instrument, "field":... | use bin file to save like feature-data. | gen_expression_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def read_data_from_cache(cls, cache_path: Union[str, Path], start_time, end_time, fields):
"""read_cache_from
This function can read data from the disk cache dataset
:param cache_path:
:param start_time:
:param end_time:
:param fields: The fields order of the dataset ca... | read_cache_from
This function can read data from the disk cache dataset
:param cache_path:
:param start_time:
:param end_time:
:param fields: The fields order of the dataset cache is sorted. So rearrange the columns to make it consistent.
:return:
| read_data_from_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def gen_dataset_cache(self, cache_path: Union[str, Path], instruments, fields, freq, inst_processors=[]):
"""gen_dataset_cache
.. note:: This function does not consider the cache read write lock. Please
acquire the lock outside this function
The format the cache contains 3 parts(fo... | gen_dataset_cache
.. note:: This function does not consider the cache read write lock. Please
acquire the lock outside this function
The format the cache contains 3 parts(followed by typical filename).
- index : cache/d41366901e25de3ec47297f12e2ba11d.index
- The conte... | gen_dataset_cache | python | microsoft/qlib | qlib/data/cache.py | https://github.com/microsoft/qlib/blob/master/qlib/data/cache.py | MIT |
def send_request(self, request_type, request_content, msg_queue, msg_proc_func=None):
"""Send a certain request to server.
Parameters
----------
request_type : str
type of proposed request, 'calendar'/'instrument'/'feature'.
request_content : dict
records... | Send a certain request to server.
Parameters
----------
request_type : str
type of proposed request, 'calendar'/'instrument'/'feature'.
request_content : dict
records the information of the request.
msg_proc_func : func
the function to process... | send_request | python | microsoft/qlib | qlib/data/client.py | https://github.com/microsoft/qlib/blob/master/qlib/data/client.py | MIT |
def request_callback(*args):
"""callback_wrapper
:param *args: args[0] is the response content
"""
# args[0] is the response content
self.logger.debug("receive data and enter queue")
msg = dict(args[0])
if msg["detailed_info"] is not N... | callback_wrapper
:param *args: args[0] is the response content
| request_callback | python | microsoft/qlib | qlib/data/client.py | https://github.com/microsoft/qlib/blob/master/qlib/data/client.py | MIT |
def calendar(self, start_time=None, end_time=None, freq="day", future=False):
"""Get calendar of certain market in given time range.
Parameters
----------
start_time : str
start of the time range.
end_time : str
end of the time range.
freq : str
... | Get calendar of certain market in given time range.
Parameters
----------
start_time : str
start of the time range.
end_time : str
end of the time range.
freq : str
time frequency, available: year/quarter/month/week/day.
future : bool
... | calendar | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def locate_index(
self, start_time: Union[pd.Timestamp, str], end_time: Union[pd.Timestamp, str], freq: str, future: bool = False
):
"""Locate the start time index and end time index in a calendar under certain frequency.
Parameters
----------
start_time : pd.Timestamp
... | Locate the start time index and end time index in a calendar under certain frequency.
Parameters
----------
start_time : pd.Timestamp
start of the time range.
end_time : pd.Timestamp
end of the time range.
freq : str
time frequency, available:... | locate_index | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def _get_calendar(self, freq, future):
"""Load calendar using memcache.
Parameters
----------
freq : str
frequency of read calendar file.
future : bool
whether including future trading day.
Returns
-------
list
list of... | Load calendar using memcache.
Parameters
----------
freq : str
frequency of read calendar file.
future : bool
whether including future trading day.
Returns
-------
list
list of timestamps.
dict
dict compose... | _get_calendar | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def instruments(market: Union[List, str] = "all", filter_pipe: Union[List, None] = None):
"""Get the general config dictionary for a base market adding several dynamic filters.
Parameters
----------
market : Union[List, str]
str:
market/industry/index shortna... | Get the general config dictionary for a base market adding several dynamic filters.
Parameters
----------
market : Union[List, str]
str:
market/industry/index shortname, e.g. all/sse/szse/sse50/csi300/csi500.
list:
["ID1", "ID2"]. A list o... | instruments | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def period_feature(
self,
instrument,
field,
start_index: int,
end_index: int,
cur_time: pd.Timestamp,
period: Optional[int] = None,
) -> pd.Series:
"""
get the historical periods data series between `start_index` and `end_index`
Param... |
get the historical periods data series between `start_index` and `end_index`
Parameters
----------
start_index: int
start_index is a relative index to the latest period to cur_time
end_index: int
end_index is a relative index to the latest period to cur... | period_feature | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def _uri(
self,
instruments,
fields,
start_time=None,
end_time=None,
freq="day",
disk_cache=1,
inst_processors=[],
**kwargs,
):
"""Get task uri, used when generating rabbitmq task in qlib_server
Parameters
----------
... | Get task uri, used when generating rabbitmq task in qlib_server
Parameters
----------
instruments : list or dict
list/dict of instruments or dict of stockpool config.
fields : list
list of feature instances.
start_time : str
start of the time ... | _uri | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def get_instruments_d(instruments, freq):
"""
Parse different types of input instruments to output instruments_d
Wrong format of input instruments will lead to exception.
"""
if isinstance(instruments, dict):
if "market" in instruments:
# dict of stoc... |
Parse different types of input instruments to output instruments_d
Wrong format of input instruments will lead to exception.
| get_instruments_d | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def get_column_names(fields):
"""
Get column names from input fields
"""
if len(fields) == 0:
raise ValueError("fields cannot be empty")
column_names = [str(f) for f in fields]
return column_names |
Get column names from input fields
| get_column_names | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def dataset_processor(instruments_d, column_names, start_time, end_time, freq, inst_processors=[]):
"""
Load and process the data, return the data set.
- default using multi-kernel method.
"""
normalize_column_names = normalize_cache_fields(column_names)
# One process fo... |
Load and process the data, return the data set.
- default using multi-kernel method.
| dataset_processor | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def inst_calculator(inst, start_time, end_time, freq, column_names, spans=None, g_config=None, inst_processors=[]):
"""
Calculate the expressions for **one** instrument, return a df result.
If the expression has been calculated before, load from cache.
return value: A data frame with in... |
Calculate the expressions for **one** instrument, return a df result.
If the expression has been calculated before, load from cache.
return value: A data frame with index 'datetime' and other data columns.
| inst_calculator | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def load_calendar(self, freq, future):
"""Load original calendar timestamp from file.
Parameters
----------
freq : str
frequency of read calendar file.
future: bool
Returns
----------
list
list of timestamps
"""
try... | Load original calendar timestamp from file.
Parameters
----------
freq : str
frequency of read calendar file.
future: bool
Returns
----------
list
list of timestamps
| load_calendar | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def __init__(self, align_time: bool = True):
"""
Parameters
----------
align_time : bool
Will we align the time to calendar
the frequency is flexible in some dataset and can't be aligned.
For the data with fixed frequency with a shared calendar, the al... |
Parameters
----------
align_time : bool
Will we align the time to calendar
the frequency is flexible in some dataset and can't be aligned.
For the data with fixed frequency with a shared calendar, the align data to the calendar will provides following benefit... | __init__ | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def multi_cache_walker(instruments, fields, start_time=None, end_time=None, freq="day"):
"""
This method is used to prepare the expression cache for the client.
Then the client will load the data from expression cache by itself.
"""
instruments_d = DatasetProvider.get_instrument... |
This method is used to prepare the expression cache for the client.
Then the client will load the data from expression cache by itself.
| multi_cache_walker | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def cache_walker(inst, start_time, end_time, freq, column_names):
"""
If the expressions of one instrument haven't been calculated before,
calculate it and write it into expression cache.
"""
for field in column_names:
ExpressionD.expression(inst, field, start_time, ... |
If the expressions of one instrument haven't been calculated before,
calculate it and write it into expression cache.
| cache_walker | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def features(
self,
instruments,
fields,
start_time=None,
end_time=None,
freq="day",
disk_cache=None,
inst_processors=[],
):
"""
Parameters
----------
disk_cache : int
whether to skip(0)/use(1)/replace(2) dis... |
Parameters
----------
disk_cache : int
whether to skip(0)/use(1)/replace(2) disk_cache
This function will try to use cache method which has a keyword `disk_cache`,
and will use provider method if a type error is raised because the DatasetD instance
is a pro... | features | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def _uri(self, type, **kwargs):
"""_uri
The server hope to get the uri of the request. The uri will be decided
by the dataprovider. For ex, different cache layer has different uri.
:param type: The type of resource for the uri
:param **kwargs:
"""
if type == "cal... | _uri
The server hope to get the uri of the request. The uri will be decided
by the dataprovider. For ex, different cache layer has different uri.
:param type: The type of resource for the uri
:param **kwargs:
| _uri | python | microsoft/qlib | qlib/data/data.py | https://github.com/microsoft/qlib/blob/master/qlib/data/data.py | MIT |
def __init__(self, fstart_time=None, fend_time=None, keep=False):
"""Init function for filter base class.
Filter a set of instruments based on a certain rule within a certain period assigned by fstart_time and fend_time.
Parameters
----------
fstart_time: str
the... | Init function for filter base class.
Filter a set of instruments based on a certain rule within a certain period assigned by fstart_time and fend_time.
Parameters
----------
fstart_time: str
the time for the filter rule to start filter the instruments.
fend_time:... | __init__ | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def _getTimeBound(self, instruments):
"""Get time bound for all instruments.
Parameters
----------
instruments: dict
the dict of instruments in the form {instrument_name => list of timestamp tuple}.
Returns
----------
pd.Timestamp, pd.Timestamp
... | Get time bound for all instruments.
Parameters
----------
instruments: dict
the dict of instruments in the form {instrument_name => list of timestamp tuple}.
Returns
----------
pd.Timestamp, pd.Timestamp
the lower time bound and upper time bound ... | _getTimeBound | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def _toSeries(self, time_range, target_timestamp):
"""Convert the target timestamp to a pandas series of bool value within a time range.
Make the time inside the target_timestamp range TRUE, others FALSE.
Parameters
----------
time_range : D.calendar
the time ran... | Convert the target timestamp to a pandas series of bool value within a time range.
Make the time inside the target_timestamp range TRUE, others FALSE.
Parameters
----------
time_range : D.calendar
the time range of the instruments.
target_timestamp : list
... | _toSeries | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def _filterSeries(self, timestamp_series, filter_series):
"""Filter the timestamp series with filter series by using element-wise AND operation of the two series.
Parameters
----------
timestamp_series : pd.Series
the series of bool value indicating existing time.
fi... | Filter the timestamp series with filter series by using element-wise AND operation of the two series.
Parameters
----------
timestamp_series : pd.Series
the series of bool value indicating existing time.
filter_series : pd.Series
the series of bool value indicati... | _filterSeries | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def _toTimestamp(self, timestamp_series):
"""Convert the timestamp series to a list of tuple (timestamp, timestamp) indicating a continuous range of TRUE.
Parameters
----------
timestamp_series: pd.Series
the series of bool value after being filtered.
Returns
... | Convert the timestamp series to a list of tuple (timestamp, timestamp) indicating a continuous range of TRUE.
Parameters
----------
timestamp_series: pd.Series
the series of bool value after being filtered.
Returns
----------
list
the list of tup... | _toTimestamp | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def __call__(self, instruments, start_time=None, end_time=None, freq="day"):
"""Call this filter to get filtered instruments list"""
self.filter_freq = freq
return self.filter_main(instruments, start_time, end_time) | Call this filter to get filtered instruments list | __call__ | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def filter_main(self, instruments, start_time=None, end_time=None):
"""Implement this method to filter the instruments.
Parameters
----------
instruments: dict
input instruments to be filtered.
start_time: str
start of the time range.
end_time: st... | Implement this method to filter the instruments.
Parameters
----------
instruments: dict
input instruments to be filtered.
start_time: str
start of the time range.
end_time: str
end of the time range.
Returns
----------
... | filter_main | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def __init__(self, name_rule_re, fstart_time=None, fend_time=None):
"""Init function for name filter class
Parameters
----------
name_rule_re: str
regular expression for the name rule.
"""
super(NameDFilter, self).__init__(fstart_time, fend_time)
self... | Init function for name filter class
Parameters
----------
name_rule_re: str
regular expression for the name rule.
| __init__ | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def __init__(self, rule_expression, fstart_time=None, fend_time=None, keep=False):
"""Init function for expression filter class
Parameters
----------
fstart_time: str
filter the feature starting from this time.
fend_time: str
filter the feature ending by ... | Init function for expression filter class
Parameters
----------
fstart_time: str
filter the feature starting from this time.
fend_time: str
filter the feature ending by this time.
rule_expression: str
an input expression for the rule.
| __init__ | python | microsoft/qlib | qlib/data/filter.py | https://github.com/microsoft/qlib/blob/master/qlib/data/filter.py | MIT |
def __call__(self, df: pd.DataFrame, instrument, *args, **kwargs):
"""
process the data
NOTE: **The processor could change the content of `df` inplace !!!!! **
User should keep a copy of data outside
Parameters
----------
df : pd.DataFrame
The raw_df... |
process the data
NOTE: **The processor could change the content of `df` inplace !!!!! **
User should keep a copy of data outside
Parameters
----------
df : pd.DataFrame
The raw_df of handler or result from previous processor.
| __call__ | python | microsoft/qlib | qlib/data/inst_processor.py | https://github.com/microsoft/qlib/blob/master/qlib/data/inst_processor.py | MIT |
def _load_internal(self, instrument, start_index, end_index, *args):
"""
To avoid error raised by bool type input, we transform the data into float32.
"""
series = self.feature.load(instrument, start_index, end_index, *args)
# TODO: More precision types should be configurable
... |
To avoid error raised by bool type input, we transform the data into float32.
| _load_internal | python | microsoft/qlib | qlib/data/ops.py | https://github.com/microsoft/qlib/blob/master/qlib/data/ops.py | MIT |
def __init__(self, feature, freq, func):
"""
Resampling the data to target frequency.
The resample function of pandas is used.
- the timestamp will be at the start of the time span after resample.
Parameters
----------
feature : Expression
An express... |
Resampling the data to target frequency.
The resample function of pandas is used.
- the timestamp will be at the start of the time span after resample.
Parameters
----------
feature : Expression
An expression for calculating the feature
freq : str
... | __init__ | python | microsoft/qlib | qlib/data/ops.py | https://github.com/microsoft/qlib/blob/master/qlib/data/ops.py | MIT |
def register(self, ops_list: List[Union[Type[ExpressionOps], dict]]):
"""register operator
Parameters
----------
ops_list : List[Union[Type[ExpressionOps], dict]]
- if type(ops_list) is List[Type[ExpressionOps]], each element of ops_list represents the operator class, which ... | register operator
Parameters
----------
ops_list : List[Union[Type[ExpressionOps], dict]]
- if type(ops_list) is List[Type[ExpressionOps]], each element of ops_list represents the operator class, which should be the subclass of `ExpressionOps`.
- if type(ops_list) is Lis... | register | python | microsoft/qlib | qlib/data/ops.py | https://github.com/microsoft/qlib/blob/master/qlib/data/ops.py | MIT |
def __init__(
self,
instruments=None,
start_time=None,
end_time=None,
data_loader: Union[dict, str, DataLoader] = None,
init_data=True,
fetch_orig=True,
):
"""
Parameters
----------
instruments :
The stock list to re... |
Parameters
----------
instruments :
The stock list to retrieve.
start_time :
start_time of the original data.
end_time :
end_time of the original data.
data_loader : Union[dict, str, DataLoader]
data loader to load the data... | __init__ | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def config(self, **kwargs):
"""
configuration of data.
# what data to be loaded from data source
This method will be used when loading pickled handler from dataset.
The data will be initialized with different time range.
"""
attr_list = {"instruments", "start_ti... |
configuration of data.
# what data to be loaded from data source
This method will be used when loading pickled handler from dataset.
The data will be initialized with different time range.
| config | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def setup_data(self, enable_cache: bool = False):
"""
Set Up the data in case of running initialization for multiple time
It is responsible for maintaining following variable
1) self._data
Parameters
----------
enable_cache : bool
default value is fa... |
Set Up the data in case of running initialization for multiple time
It is responsible for maintaining following variable
1) self._data
Parameters
----------
enable_cache : bool
default value is false:
- if `enable_cache` == True:
... | setup_data | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def fetch(
self,
selector: Union[pd.Timestamp, slice, str, pd.Index] = slice(None, None),
level: Union[str, int] = "datetime",
col_set: Union[str, List[str]] = CS_ALL,
squeeze: bool = False,
proc_func: Callable = None,
) -> pd.DataFrame:
"""
fetch data... |
fetch data from underlying data source
Design motivation:
- providing a unified interface for underlying data.
- Potential to make the interface more friendly.
- User can improve performance when fetching data in this extra layer
Parameters
----------
s... | fetch | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def get_cols(self, col_set=CS_ALL) -> list:
"""
get the column names
Parameters
----------
col_set : str
select a set of meaningful columns.(e.g. features, columns)
Returns
-------
list:
list of column names
"""
df... |
get the column names
Parameters
----------
col_set : str
select a set of meaningful columns.(e.g. features, columns)
Returns
-------
list:
list of column names
| get_cols | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def get_range_selector(self, cur_date: Union[pd.Timestamp, str], periods: int) -> slice:
"""
get range selector by number of periods
Args:
cur_date (pd.Timestamp or str): current date
periods (int): number of periods
"""
trading_dates = self._data.index.u... |
get range selector by number of periods
Args:
cur_date (pd.Timestamp or str): current date
periods (int): number of periods
| get_range_selector | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def get_range_iterator(
self, periods: int, min_periods: Optional[int] = None, **kwargs
) -> Iterator[Tuple[pd.Timestamp, pd.DataFrame]]:
"""
get an iterator of sliced data with given periods
Args:
periods (int): number of periods.
min_periods (int): minimum ... |
get an iterator of sliced data with given periods
Args:
periods (int): number of periods.
min_periods (int): minimum periods for sliced dataframe.
kwargs (dict): will be passed to `self.fetch`.
| get_range_iterator | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def __init__(
self,
instruments=None,
start_time=None,
end_time=None,
data_loader: Union[dict, str, DataLoader] = None,
infer_processors: List = [],
learn_processors: List = [],
shared_processors: List = [],
process_type=PTYPE_A,
drop_raw=F... |
Parameters
----------
infer_processors : list
- list of <description info> of processors to generate data for inference
- example of <description info>:
.. code-block::
1) classname & kwargs:
{
"c... | __init__ | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def fit(self):
"""
fit data without processing the data
"""
for proc in self.get_all_processors():
with TimeInspector.logt(f"{proc.__class__.__name__}"):
proc.fit(self._data) |
fit data without processing the data
| fit | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def _is_proc_readonly(proc_l: List[processor_module.Processor]):
"""
NOTE: it will return True if `len(proc_l) == 0`
"""
for p in proc_l:
if not p.readonly():
return False
return True |
NOTE: it will return True if `len(proc_l) == 0`
| _is_proc_readonly | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def process_data(self, with_fit: bool = False):
"""
process_data data. Fun `processor.fit` if necessary
Notation: (data) [processor]
# data processing flow of self.process_type == DataHandlerLP.PTYPE_I
.. code-block:: text
(self._data)-[shared_processors]-(_share... |
process_data data. Fun `processor.fit` if necessary
Notation: (data) [processor]
# data processing flow of self.process_type == DataHandlerLP.PTYPE_I
.. code-block:: text
(self._data)-[shared_processors]-(_shared_df)-[learn_processors]-(_learn_df)
... | process_data | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def config(self, processor_kwargs: dict = None, **kwargs):
"""
configuration of data.
# what data to be loaded from data source
This method will be used when loading pickled handler from dataset.
The data will be initialized with different time range.
"""
super(... |
configuration of data.
# what data to be loaded from data source
This method will be used when loading pickled handler from dataset.
The data will be initialized with different time range.
| config | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
def setup_data(self, init_type: str = IT_FIT_SEQ, **kwargs):
"""
Set up the data in case of running initialization for multiple time
Parameters
----------
init_type : str
The type `IT_*` listed above.
enable_cache : bool
default value is false:
... |
Set up the data in case of running initialization for multiple time
Parameters
----------
init_type : str
The type `IT_*` listed above.
enable_cache : bool
default value is false:
- if `enable_cache` == True:
the processed d... | setup_data | python | microsoft/qlib | qlib/data/dataset/handler.py | https://github.com/microsoft/qlib/blob/master/qlib/data/dataset/handler.py | MIT |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves Python code examples from Django repository that contain 'django' in the code, which helps identify Django-specific code snippets but provides limited analytical insights beyond basic filtering.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.