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 update(self, trade_calendar: TradeCalendarManager) -> Optional[BaseTradeDecision]:
"""
Be called at the **start** of each step.
This function is design for following purpose
1) Leave a hook for the strategy who make `self` decision to update the decision itself
2) Update som... |
Be called at the **start** of each step.
This function is design for following purpose
1) Leave a hook for the strategy who make `self` decision to update the decision itself
2) Update some information from the inner executor calendar
Parameters
----------
trad... | update | python | microsoft/qlib | qlib/backtest/decision.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py | MIT |
def mod_inner_decision(self, inner_trade_decision: BaseTradeDecision) -> None:
"""
This method will be called on the inner_trade_decision after it is generated.
`inner_trade_decision` will be changed **inplace**.
Motivation of the `mod_inner_decision`
- Leave a hook for outer de... |
This method will be called on the inner_trade_decision after it is generated.
`inner_trade_decision` will be changed **inplace**.
Motivation of the `mod_inner_decision`
- Leave a hook for outer decision to affect the decision generated by the inner strategy
- e.g. the outmo... | mod_inner_decision | python | microsoft/qlib | qlib/backtest/decision.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/decision.py | MIT |
def check_stock_suspended(
self,
stock_id: str,
start_time: pd.Timestamp,
end_time: pd.Timestamp,
) -> bool:
"""if stock is suspended(hence not tradable), True will be returned"""
# is suspended
if stock_id in self.quote.get_all_stock():
# suspende... | if stock is suspended(hence not tradable), True will be returned | check_stock_suspended | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def deal_order(
self,
order: Order,
trade_account: Account | None = None,
position: BasePosition | None = None,
dealt_order_amount: Dict[str, float] = defaultdict(float),
) -> Tuple[float, float, float]:
"""
Deal order when the actual transaction
the r... |
Deal order when the actual transaction
the results section in `Order` will be changed.
:param order: Deal the order.
:param trade_account: Trade account to be updated after dealing the order.
:param position: position to be updated after dealing the order.
:param dealt_... | deal_order | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def get_volume(
self,
stock_id: str,
start_time: pd.Timestamp,
end_time: pd.Timestamp,
method: Optional[str] = "sum",
) -> Union[None, int, float, bool, IndexData]:
"""get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time)"... | get the total deal volume of stock with `stock_id` between the time interval [start_time, end_time) | get_volume | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def get_factor(
self,
stock_id: str,
start_time: pd.Timestamp,
end_time: pd.Timestamp,
) -> Optional[float]:
"""
Returns
-------
Optional[float]:
`None`: if the stock is suspended `None` may be returned
`float`: return factor if... |
Returns
-------
Optional[float]:
`None`: if the stock is suspended `None` may be returned
`float`: return factor if the factor exists
| get_factor | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def generate_amount_position_from_weight_position(
self,
weight_position: dict,
cash: float,
start_time: pd.Timestamp,
end_time: pd.Timestamp,
direction: OrderDir = OrderDir.BUY,
) -> dict:
"""
Generates the target position according to the weight and ... |
Generates the target position according to the weight and the cash.
NOTE: All the cash will be assigned to the tradable stock.
Parameter:
weight_position : dict {stock_id : weight}; allocate cash by weight_position
among then, weight must be in this range: 0 < weight < 1
... | generate_amount_position_from_weight_position | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def get_real_deal_amount(self, current_amount: float, target_amount: float, factor: float | None = None) -> float:
"""
Calculate the real adjust deal amount when considering the trading unit
:param current_amount:
:param target_amount:
:param factor:
:return real_deal_am... |
Calculate the real adjust deal amount when considering the trading unit
:param current_amount:
:param target_amount:
:param factor:
:return real_deal_amount; Positive deal_amount indicates buying more stock.
| get_real_deal_amount | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def generate_order_for_target_amount_position(
self,
target_position: dict,
current_position: dict,
start_time: pd.Timestamp,
end_time: pd.Timestamp,
) -> List[Order]:
"""
Note: some future information is used in this function
Parameter:
target... |
Note: some future information is used in this function
Parameter:
target_position : dict { stock_id : amount }
current_position : dict { stock_id : amount}
trade_unit : trade_unit
down sample : for amount 321 and trade_unit 100, deal_amount is 300
deal order on t... | generate_order_for_target_amount_position | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def calculate_amount_position_value(
self,
amount_dict: dict,
start_time: pd.Timestamp,
end_time: pd.Timestamp,
only_tradable: bool = False,
direction: OrderDir = OrderDir.SELL,
) -> float:
"""Parameter
position : Position()
amount_dict : {stoc... | Parameter
position : Position()
amount_dict : {stock_id : amount}
direction : the direction of the deal price for estimating the amount
# NOTE:
This function is used for calculating current position value.
So the default direction is se... | calculate_amount_position_value | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def _get_factor_or_raise_error(
self,
factor: float | None = None,
stock_id: str | None = None,
start_time: pd.Timestamp = None,
end_time: pd.Timestamp = None,
) -> float:
"""Please refer to the docs of get_amount_of_trade_unit"""
if factor is None:
... | Please refer to the docs of get_amount_of_trade_unit | _get_factor_or_raise_error | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def get_amount_of_trade_unit(
self,
factor: float | None = None,
stock_id: str | None = None,
start_time: pd.Timestamp = None,
end_time: pd.Timestamp = None,
) -> Optional[float]:
"""
get the trade unit of amount based on **factor**
the factor can be g... |
get the trade unit of amount based on **factor**
the factor can be given directly or calculated in given time range and stock id.
`factor` has higher priority than `stock_id`, `start_time` and `end_time`
Parameters
----------
factor : float
the adjusted facto... | get_amount_of_trade_unit | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def round_amount_by_trade_unit(
self,
deal_amount: float,
factor: float | None = None,
stock_id: str | None = None,
start_time: pd.Timestamp = None,
end_time: pd.Timestamp = None,
) -> float:
"""Parameter
Please refer to the docs of get_amount_of_trade... | Parameter
Please refer to the docs of get_amount_of_trade_unit
deal_amount : float, adjusted amount
factor : float, adjusted factor
return : float, real amount
| round_amount_by_trade_unit | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def _calc_trade_info_by_order(
self,
order: Order,
position: Optional[BasePosition],
dealt_order_amount: dict,
) -> Tuple[float, float, float]:
"""
Calculation of trade info
**NOTE**: Order will be changed in this function
:param order:
:param ... |
Calculation of trade info
**NOTE**: Order will be changed in this function
:param order:
:param position: Position
:param dealt_order_amount: the dealt order amount dict with the format of {stock_id: float}
:return: trade_price, trade_val, trade_cost
| _calc_trade_info_by_order | python | microsoft/qlib | qlib/backtest/exchange.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/exchange.py | MIT |
def __init__(
self,
time_per_step: str,
start_time: Union[str, pd.Timestamp] = None,
end_time: Union[str, pd.Timestamp] = None,
indicator_config: dict = {},
generate_portfolio_metrics: bool = False,
verbose: bool = False,
track_data: bool = False,
... |
Parameters
----------
time_per_step : str
trade time per trading step, used for generate the trade calendar
show_indicator: bool, optional
whether to show indicators, :
- 'pa', the price advantage
- 'pos', the positive rate
- '... | __init__ | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def reset(self, common_infra: CommonInfrastructure | None = None, **kwargs: Any) -> None:
"""
- reset `start_time` and `end_time`, used in trade calendar
- reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc
"""
if "start_time" in kwargs or "end_time" in ... |
- reset `start_time` and `end_time`, used in trade calendar
- reset `common_infra`, used to reset `trade_account`, `trade_exchange`, .etc
| reset | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def execute(self, trade_decision: BaseTradeDecision, level: int = 0) -> List[object]:
"""execute the trade decision and return the executed result
NOTE: this function is never used directly in the framework. Should we delete it?
Parameters
----------
trade_decision : BaseTradeD... | execute the trade decision and return the executed result
NOTE: this function is never used directly in the framework. Should we delete it?
Parameters
----------
trade_decision : BaseTradeDecision
level : int
the level of current executor
Returns
-... | execute | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def _collect_data(
self,
trade_decision: BaseTradeDecision,
level: int = 0,
) -> Union[Generator[Any, Any, Tuple[List[object], dict]], Tuple[List[object], dict]]:
"""
Please refer to the doc of collect_data
The only difference between `_collect_data` and `collect_data... |
Please refer to the doc of collect_data
The only difference between `_collect_data` and `collect_data` is that some common steps are moved into
collect_data
Parameters
----------
Please refer to the doc of collect_data
Returns
-------
Tuple[Lis... | _collect_data | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def collect_data(
self,
trade_decision: BaseTradeDecision,
return_value: dict | None = None,
level: int = 0,
) -> Generator[Any, Any, List[object]]:
"""Generator for collecting the trade decision data for rl training
his function will make a step forward
Par... | Generator for collecting the trade decision data for rl training
his function will make a step forward
Parameters
----------
trade_decision : BaseTradeDecision
level : int
the level of current executor. 0 indicates the top level
return_value : dict
... | collect_data | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def reset_common_infra(self, common_infra: CommonInfrastructure, copy_trade_account: bool = False) -> None:
"""
reset infrastructure for trading
- reset inner_strategy and inner_executor common infra
"""
# NOTE: please refer to the docs of BaseExecutor.reset_common_infra for ... |
reset infrastructure for trading
- reset inner_strategy and inner_executor common infra
| reset_common_infra | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def __init__(
self,
time_per_step: str,
start_time: Union[str, pd.Timestamp] = None,
end_time: Union[str, pd.Timestamp] = None,
indicator_config: dict = {},
generate_portfolio_metrics: bool = False,
verbose: bool = False,
track_data: bool = False,
... |
Parameters
----------
trade_type: str
please refer to the doc of `TT_SERIAL` & `TT_PARAL`
| __init__ | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def _get_order_iterator(self, trade_decision: BaseTradeDecision) -> List[Order]:
"""
Parameters
----------
trade_decision : BaseTradeDecision
the trade decision given by the strategy
Returns
-------
List[Order]:
get a list orders accordin... |
Parameters
----------
trade_decision : BaseTradeDecision
the trade decision given by the strategy
Returns
-------
List[Order]:
get a list orders according to `self.trade_type`
| _get_order_iterator | python | microsoft/qlib | qlib/backtest/executor.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/executor.py | MIT |
def get_data(
self,
stock_id: str,
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
field: Union[str],
method: Optional[str] = None,
) -> Union[None, int, float, bool, IndexData]:
"""get the specific field of stock data during start ti... | get the specific field of stock data during start time and end_time,
and apply method to the data.
Example:
.. code-block::
$close $volume
instrument datetime
SH600000 2010-01-04 86.778313 16162960.0
... | get_data | python | microsoft/qlib | qlib/backtest/high_performance_ds.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py | MIT |
def __init__(self, quote_df: pd.DataFrame, freq: str, region: str = "cn") -> None:
"""NumpyQuote
Parameters
----------
quote_df : pd.DataFrame
the init dataframe from qlib.
self.data : Dict(stock_id, IndexData.DataFrame)
"""
super().__init__(quote_df=... | NumpyQuote
Parameters
----------
quote_df : pd.DataFrame
the init dataframe from qlib.
self.data : Dict(stock_id, IndexData.DataFrame)
| __init__ | python | microsoft/qlib | qlib/backtest/high_performance_ds.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py | MIT |
def transfer(self, func: Callable, new_col: str = None) -> Optional[BaseSingleMetric]:
"""compute new metric with existing metrics.
Parameters
----------
func : Callable
the func of computing new metric.
the kwargs of func will be replaced with metric data by nam... | compute new metric with existing metrics.
Parameters
----------
func : Callable
the func of computing new metric.
the kwargs of func will be replaced with metric data by name in this function.
e.g.
def func(pa):
return (pa ... | transfer | python | microsoft/qlib | qlib/backtest/high_performance_ds.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py | MIT |
def sum_all_indicators(
order_indicator: BaseOrderIndicator,
indicators: List[BaseOrderIndicator],
metrics: Union[str, List[str]],
fill_value: float = 0,
) -> None:
"""sum indicators with the same metrics.
and assign to the order_indicator(BaseOrderIndicator).
... | sum indicators with the same metrics.
and assign to the order_indicator(BaseOrderIndicator).
NOTE: indicators could be a empty list when orders in lower level all fail.
Parameters
----------
order_indicator : BaseOrderIndicator
the order indicator to assign.
... | sum_all_indicators | python | microsoft/qlib | qlib/backtest/high_performance_ds.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/high_performance_ds.py | MIT |
def __init__(self, cash: float = 0, position_dict: Dict[str, Union[Dict[str, float], float]] = {}) -> None:
"""Init position by cash and position_dict.
Parameters
----------
cash : float, optional
initial cash in account, by default 0
position_dict : Dict[
... | Init position by cash and position_dict.
Parameters
----------
cash : float, optional
initial cash in account, by default 0
position_dict : Dict[
stock_id,
Union[
int, # it is equal to {... | __init__ | python | microsoft/qlib | qlib/backtest/position.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py | MIT |
def fill_stock_value(self, start_time: Union[str, pd.Timestamp], freq: str, last_days: int = 30) -> None:
"""fill the stock value by the close price of latest last_days from qlib.
Parameters
----------
start_time :
the start time of backtest.
freq : str
F... | fill the stock value by the close price of latest last_days from qlib.
Parameters
----------
start_time :
the start time of backtest.
freq : str
Frequency
last_days : int, optional
the days to get the latest close price, by default 30.
... | fill_stock_value | python | microsoft/qlib | qlib/backtest/position.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py | MIT |
def _init_stock(self, stock_id: str, amount: float, price: float | None = None) -> None:
"""
initialization the stock in current position
Parameters
----------
stock_id :
the id of the stock
amount : float
the amount of the stock
price :
... |
initialization the stock in current position
Parameters
----------
stock_id :
the id of the stock
amount : float
the amount of the stock
price :
the price when buying the init stock
| _init_stock | python | microsoft/qlib | qlib/backtest/position.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py | MIT |
def get_stock_count(self, code: str, bar: str) -> float:
"""the days the account has been hold, it may be used in some special strategies"""
if f"count_{bar}" in self.position[code]:
return self.position[code][f"count_{bar}"]
else:
return 0 | the days the account has been hold, it may be used in some special strategies | get_stock_count | python | microsoft/qlib | qlib/backtest/position.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py | MIT |
def get_stock_amount_dict(self) -> dict:
"""generate stock amount dict {stock_id : amount of stock}"""
d = {}
stock_list = self.get_stock_list()
for stock_code in stock_list:
d[stock_code] = self.get_stock_amount(code=stock_code)
return d | generate stock amount dict {stock_id : amount of stock} | get_stock_amount_dict | python | microsoft/qlib | qlib/backtest/position.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py | MIT |
def get_stock_weight_dict(self, only_stock: bool = False) -> dict:
"""get_stock_weight_dict
generate stock weight dict {stock_id : value weight of stock in the position}
it is meaningful in the beginning or the end of each trade date
:param only_stock: If only_stock=True, the weight of ... | get_stock_weight_dict
generate stock weight dict {stock_id : value weight of stock in the position}
it is meaningful in the beginning or the end of each trade date
:param only_stock: If only_stock=True, the weight of each stock in total stock will be returned
If only_... | get_stock_weight_dict | python | microsoft/qlib | qlib/backtest/position.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/position.py | MIT |
def get_benchmark_weight(
bench,
start_date=None,
end_date=None,
path=None,
freq="day",
):
"""get_benchmark_weight
get the stock weight distribution of the benchmark
:param bench:
:param start_date:
:param end_date:
:param path:
:param freq:
:return: The weight dis... | get_benchmark_weight
get the stock weight distribution of the benchmark
:param bench:
:param start_date:
:param end_date:
:param path:
:param freq:
:return: The weight distribution of the the benchmark described by a pandas dataframe
Every row corresponds to a trading day.
... | get_benchmark_weight | python | microsoft/qlib | qlib/backtest/profit_attribution.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py | MIT |
def get_stock_weight_df(positions):
"""get_stock_weight_df
:param positions: Given a positions from backtest result.
:return: A weight distribution for the position
"""
stock_weight = []
index = []
for date in sorted(positions.keys()):
pos = positions[date]
if isinst... | get_stock_weight_df
:param positions: Given a positions from backtest result.
:return: A weight distribution for the position
| get_stock_weight_df | python | microsoft/qlib | qlib/backtest/profit_attribution.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py | MIT |
def decompose_portofolio_weight(stock_weight_df, stock_group_df):
"""decompose_portofolio_weight
'''
:param stock_weight_df: a pandas dataframe to describe the portofolio by weight.
every row corresponds to a day
every column corresponds to a stock.
... | decompose_portofolio_weight
'''
:param stock_weight_df: a pandas dataframe to describe the portofolio by weight.
every row corresponds to a day
every column corresponds to a stock.
Here is an example below.
code SH600004 S... | decompose_portofolio_weight | python | microsoft/qlib | qlib/backtest/profit_attribution.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py | MIT |
def decompose_portofolio(stock_weight_df, stock_group_df, stock_ret_df):
"""
:param stock_weight_df: a pandas dataframe to describe the portofolio by weight.
every row corresponds to a day
every column corresponds to a stock.
Here is an example below.... |
:param stock_weight_df: a pandas dataframe to describe the portofolio by weight.
every row corresponds to a day
every column corresponds to a stock.
Here is an example below.
code SH600004 SH600006 SH600017 SH600022 SH60002... | decompose_portofolio | python | microsoft/qlib | qlib/backtest/profit_attribution.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py | MIT |
def get_daily_bin_group(bench_values, stock_values, group_n):
"""get_daily_bin_group
Group the values of the stocks of benchmark into several bins in a day.
Put the stocks into these bins.
:param bench_values: A series contains the value of stocks in benchmark.
The index is the... | get_daily_bin_group
Group the values of the stocks of benchmark into several bins in a day.
Put the stocks into these bins.
:param bench_values: A series contains the value of stocks in benchmark.
The index is the stock code.
:param stock_values: A series contains the value of ... | get_daily_bin_group | python | microsoft/qlib | qlib/backtest/profit_attribution.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py | MIT |
def brinson_pa(
positions,
bench="SH000905",
group_field="industry",
group_method="category",
group_n=None,
deal_price="vwap",
freq="day",
):
"""brinson profit attribution
:param positions: The position produced by the backtest class
:param bench: The benchmark for comparing. TO... | brinson profit attribution
:param positions: The position produced by the backtest class
:param bench: The benchmark for comparing. TODO: if no benchmark is set, the equal-weighted is used.
:param group_field: The field used to set the group for assets allocation.
`industry` and `ma... | brinson_pa | python | microsoft/qlib | qlib/backtest/profit_attribution.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/profit_attribution.py | MIT |
def load_portfolio_metrics(self, path: str) -> None:
"""load pm from a file
should have format like
columns = ['account', 'return', 'total_turnover', 'turnover', 'cost', 'total_cost', 'value', 'cash', 'bench']
:param
path: str/ pathlib.Path()
"""
with ... | load pm from a file
should have format like
columns = ['account', 'return', 'total_turnover', 'turnover', 'cost', 'total_cost', 'value', 'cash', 'bench']
:param
path: str/ pathlib.Path()
| load_portfolio_metrics | python | microsoft/qlib | qlib/backtest/report.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/report.py | MIT |
def _get_base_vol_pri(
self,
inst: str,
trade_start_time: pd.Timestamp,
trade_end_time: pd.Timestamp,
direction: OrderDir,
decision: BaseTradeDecision,
trade_exchange: Exchange,
pa_config: dict = {},
) -> Tuple[Optional[float], Optional[float]]:
... |
Get the base volume and price information
All the base price values are rooted from this function
| _get_base_vol_pri | python | microsoft/qlib | qlib/backtest/report.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/report.py | MIT |
def _agg_base_price(
self,
inner_order_indicators: List[BaseOrderIndicator],
decision_list: List[Tuple[BaseTradeDecision, pd.Timestamp, pd.Timestamp]],
trade_exchange: Exchange,
pa_config: dict = {},
) -> None:
"""
# NOTE:!!!!
# Strong assumption!!!!!!... |
# NOTE:!!!!
# Strong assumption!!!!!!
# the correctness of the base_price relies on that the **same** exchange is used
Parameters
----------
inner_order_indicators : List[BaseOrderIndicator]
the indicators of account of inner executor
decision_list: ... | _agg_base_price | python | microsoft/qlib | qlib/backtest/report.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/report.py | MIT |
def get_signal(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Union[pd.Series, pd.DataFrame, None]:
"""
get the signal at the end of the decision step(from `start_time` to `end_time`)
Returns
-------
Union[pd.Series, pd.DataFrame, None]:
returns None if n... |
get the signal at the end of the decision step(from `start_time` to `end_time`)
Returns
-------
Union[pd.Series, pd.DataFrame, None]:
returns None if no signal in the specific day
| get_signal | python | microsoft/qlib | qlib/backtest/signal.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/signal.py | MIT |
def _update_model(self) -> None:
"""
When using online data, update model in each bar as the following steps:
- update dataset with online data, the dataset should support online update
- make the latest prediction scores of the new bar
- update the pred score into th... |
When using online data, update model in each bar as the following steps:
- update dataset with online data, the dataset should support online update
- make the latest prediction scores of the new bar
- update the pred score into the latest prediction
| _update_model | python | microsoft/qlib | qlib/backtest/signal.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/signal.py | MIT |
def create_signal_from(
obj: Union[Signal, Tuple[BaseModel, Dataset], List, Dict, Text, pd.Series, pd.DataFrame],
) -> Signal:
"""
create signal from diverse information
This method will choose the right method to create a signal based on `obj`
Please refer to the code below.
"""
if isinstan... |
create signal from diverse information
This method will choose the right method to create a signal based on `obj`
Please refer to the code below.
| create_signal_from | python | microsoft/qlib | qlib/backtest/signal.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/signal.py | MIT |
def __init__(
self,
freq: str,
start_time: Union[str, pd.Timestamp] = None,
end_time: Union[str, pd.Timestamp] = None,
level_infra: LevelInfrastructure | None = None,
) -> None:
"""
Parameters
----------
freq : str
frequency of trad... |
Parameters
----------
freq : str
frequency of trading calendar, also trade time per trading step
start_time : Union[str, pd.Timestamp], optional
closed start of the trading calendar, by default None
If `start_time` is None, it must be reset before tra... | __init__ | python | microsoft/qlib | qlib/backtest/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py | MIT |
def reset(
self,
freq: str,
start_time: Union[str, pd.Timestamp] = None,
end_time: Union[str, pd.Timestamp] = None,
) -> None:
"""
Please refer to the docs of `__init__`
Reset the trade calendar
- self.trade_len : The total count for trading step
... |
Please refer to the docs of `__init__`
Reset the trade calendar
- self.trade_len : The total count for trading step
- self.trade_step : The number of trading step finished, self.trade_step can be
[0, 1, 2, ..., self.trade_len - 1]
| reset | python | microsoft/qlib | qlib/backtest/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py | MIT |
def get_step_time(self, trade_step: int | None = None, shift: int = 0) -> Tuple[pd.Timestamp, pd.Timestamp]:
"""
Get the left and right endpoints of the trade_step'th trading interval
About the endpoints:
- Qlib uses the closed interval in time-series data selection, which has the s... |
Get the left and right endpoints of the trade_step'th trading interval
About the endpoints:
- Qlib uses the closed interval in time-series data selection, which has the same performance as
pandas.Series.loc
# - The returned right endpoints should minus 1 seconds bec... | get_step_time | python | microsoft/qlib | qlib/backtest/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py | MIT |
def get_range_idx(self, start_time: pd.Timestamp, end_time: pd.Timestamp) -> Tuple[int, int]:
"""
get the range index which involve start_time~end_time (both sides are closed)
Parameters
----------
start_time : pd.Timestamp
end_time : pd.Timestamp
Returns
... |
get the range index which involve start_time~end_time (both sides are closed)
Parameters
----------
start_time : pd.Timestamp
end_time : pd.Timestamp
Returns
-------
Tuple[int, int]:
the index of the range. **the left and right are closed*... | get_range_idx | python | microsoft/qlib | qlib/backtest/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/utils.py | MIT |
def create_account_instance(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
benchmark: Optional[str],
account: Union[float, int, dict],
pos_type: str = "Position",
) -> Account:
"""
# TODO: is very strange pass benchmark_config in the account (maybe for report)
... |
# TODO: is very strange pass benchmark_config in the account (maybe for report)
# There should be a post-step to process the report.
Parameters
----------
start_time
start time of the benchmark
end_time
end time of the benchmark
benchmark : str
the benchmark for rep... | create_account_instance | python | microsoft/qlib | qlib/backtest/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py | MIT |
def backtest(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
strategy: Union[str, dict, object, Path],
executor: Union[str, dict, object, Path],
benchmark: str = "SH000300",
account: Union[float, int, dict] = 1e9,
exchange_kwargs: dict = {},
pos_type: str = "Po... | initialize the strategy and executor, then backtest function for the interaction of the outermost strategy and
executor in the nested decision execution
Parameters
----------
start_time : Union[pd.Timestamp, str]
closed start time for backtest
**NOTE**: This will be applied to the outmo... | backtest | python | microsoft/qlib | qlib/backtest/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py | MIT |
def collect_data(
start_time: Union[pd.Timestamp, str],
end_time: Union[pd.Timestamp, str],
strategy: Union[str, dict, object, Path],
executor: Union[str, dict, object, Path],
benchmark: str = "SH000300",
account: Union[float, int, dict] = 1e9,
exchange_kwargs: dict = {},
pos_type: str =... | initialize the strategy and executor, then collect the trade decision data for rl training
please refer to the docs of the backtest for the explanation of the parameters
Yields
-------
object
trade decision
| collect_data | python | microsoft/qlib | qlib/backtest/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py | MIT |
def format_decisions(
decisions: List[BaseTradeDecision],
) -> Optional[Tuple[str, List[Tuple[BaseTradeDecision, Union[Tuple, None]]]]]:
"""
format the decisions collected by `qlib.backtest.collect_data`
The decisions will be organized into a tree-like structure.
Parameters
----------
decis... |
format the decisions collected by `qlib.backtest.collect_data`
The decisions will be organized into a tree-like structure.
Parameters
----------
decisions : List[BaseTradeDecision]
decisions collected by `qlib.backtest.collect_data`
Returns
-------
Tuple[str, List[Tuple[BaseTr... | format_decisions | python | microsoft/qlib | qlib/backtest/__init__.py | https://github.com/microsoft/qlib/blob/master/qlib/backtest/__init__.py | MIT |
def risk_analysis(r, N: int = None, freq: str = "day", mode: Literal["sum", "product"] = "sum"):
"""Risk Analysis
NOTE:
The calculation of annualized return is different from the definition of annualized return.
It is implemented by design.
Qlib tries to cumulate returns by summation instead of prod... | Risk Analysis
NOTE:
The calculation of annualized return is different from the definition of annualized return.
It is implemented by design.
Qlib tries to cumulate returns by summation instead of production to avoid the cumulated curve being skewed exponentially.
All the calculation of annualized re... | risk_analysis | python | microsoft/qlib | qlib/contrib/evaluate.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate.py | MIT |
def indicator_analysis(df, method="mean"):
"""analyze statistical time-series indicators of trading
Parameters
----------
df : pandas.DataFrame
columns: like ['pa', 'pos', 'ffr', 'deal_amount', 'value'].
Necessary fields:
- 'pa' is the price advantage in trade indica... | analyze statistical time-series indicators of trading
Parameters
----------
df : pandas.DataFrame
columns: like ['pa', 'pos', 'ffr', 'deal_amount', 'value'].
Necessary fields:
- 'pa' is the price advantage in trade indicators
- 'pos' is the positive rate ... | indicator_analysis | python | microsoft/qlib | qlib/contrib/evaluate.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate.py | MIT |
def _get_position_value_from_df(evaluate_date, position, close_data_df):
"""Get position value by existed close data df
close_data_df:
pd.DataFrame
multi-index
close_data_df['$close'][stock_id][evaluate_date]: close price for (stock_id, evaluate_date)
position:
same in get_po... | Get position value by existed close data df
close_data_df:
pd.DataFrame
multi-index
close_data_df['$close'][stock_id][evaluate_date]: close price for (stock_id, evaluate_date)
position:
same in get_position_value()
| _get_position_value_from_df | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_position_value(evaluate_date, position):
"""sum of close*amount
get value of position
use close price
positions:
{
Timestamp('2016-01-05 00:00:00'):
{
'SH600022':
{
'amount':100.00,
'pr... | sum of close*amount
get value of position
use close price
positions:
{
Timestamp('2016-01-05 00:00:00'):
{
'SH600022':
{
'amount':100.00,
'price':12.00
},
'cash':10... | get_position_value | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_daily_return_series_from_positions(positions, init_asset_value):
"""Parameters
generate daily return series from position view
positions: positions generated by strategy
init_asset_value : init asset value
return: pd.Series of daily return , return_series[date] = daily return rate
"""
... | Parameters
generate daily return series from position view
positions: positions generated by strategy
init_asset_value : init asset value
return: pd.Series of daily return , return_series[date] = daily return rate
| get_daily_return_series_from_positions | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_annual_return_from_positions(positions, init_asset_value):
"""Annualized Returns
p_r = (p_end / p_start)^{(250/n)} - 1
p_r annual return
p_end final value
p_start init value
n days of backtest
"""
date_range_list = sorted(list(positions.keys()))
end_time = date... | Annualized Returns
p_r = (p_end / p_start)^{(250/n)} - 1
p_r annual return
p_end final value
p_start init value
n days of backtest
| get_annual_return_from_positions | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_annaul_return_from_return_series(r, method="ci"):
"""Risk Analysis from daily return series
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
"""
mean = r.mean()
annual ... | Risk Analysis from daily return series
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
| get_annaul_return_from_return_series | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_sharpe_ratio_from_return_series(r, risk_free_rate=0.00, method="ci"):
"""Risk Analysis
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
risk_free_rate : float
risk_free... | Risk Analysis
Parameters
----------
r : pandas.Series
daily return series
method : str
interest calculation method, ci(compound interest)/si(simple interest)
risk_free_rate : float
risk_free_rate, default as 0.00, can set as 0.03 etc
| get_sharpe_ratio_from_return_series | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_max_drawdown_from_series(r):
"""Risk Analysis from asset value
cumprod way
Parameters
----------
r : pandas.Series
daily return series
"""
# mdd = ((r.cumsum() - r.cumsum().cummax()) / (1 + r.cumsum().cummax())).min()
mdd = (((1 + r).cumprod() - (1 + r).cumprod().cumma... | Risk Analysis from asset value
cumprod way
Parameters
----------
r : pandas.Series
daily return series
| get_max_drawdown_from_series | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def get_beta(r, b):
"""Risk Analysis beta
Parameters
----------
r : pandas.Series
daily return series of strategy
b : pandas.Series
daily return series of baseline
"""
cov_r_b = np.cov(r, b)
var_b = np.var(b)
return cov_r_b / var_b | Risk Analysis beta
Parameters
----------
r : pandas.Series
daily return series of strategy
b : pandas.Series
daily return series of baseline
| get_beta | python | microsoft/qlib | qlib/contrib/evaluate_portfolio.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/evaluate_portfolio.py | MIT |
def _maybe_padding(x, seq_len, zeros=None):
"""padding 2d <time * feature> data with zeros
Args:
x (np.ndarray): 2d data with shape <time * feature>
seq_len (int): target sequence length
zeros (np.ndarray): zeros with shape <seq_len * feature>
"""
assert seq_len > 0, "sequence l... | padding 2d <time * feature> data with zeros
Args:
x (np.ndarray): 2d data with shape <time * feature>
seq_len (int): target sequence length
zeros (np.ndarray): zeros with shape <seq_len * feature>
| _maybe_padding | python | microsoft/qlib | qlib/contrib/data/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/dataset.py | MIT |
def get_pre_datasets(self):
"""Generate the training, validation and test datasets for prediction
Returns:
Tuple[BaseDataset, BaseDataset, BaseDataset]: The training and test datasets
"""
dict_feature_path = self.feature_conf["path"]
train_feature_path = dict_featur... | Generate the training, validation and test datasets for prediction
Returns:
Tuple[BaseDataset, BaseDataset, BaseDataset]: The training and test datasets
| get_pre_datasets | python | microsoft/qlib | qlib/contrib/data/highfreq_provider.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/highfreq_provider.py | MIT |
def get_feature_config(
config={
"kbar": {},
"price": {
"windows": [0],
"feature": ["OPEN", "HIGH", "LOW", "VWAP"],
},
"rolling": {},
}
):
"""create factors from config
config = {
'kbar': {},... | create factors from config
config = {
'kbar': {}, # whether to use some hard-code kbar features
'price': { # whether to use raw price features
'windows': [0, 1, 2, 3, 4], # use price at n days ago
'feature': ['OPEN', 'HIGH', 'LOW'] # which price field to ... | get_feature_config | python | microsoft/qlib | qlib/contrib/data/loader.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/loader.py | MIT |
def __init__(self, df_dict: Dict[str, pd.DataFrame], join: str, skip_align=False):
"""
initialize the data based on the dataframe dictionary
Parameters
----------
df_dict : Dict[str, pd.DataFrame]
dataframe dictionary
join : str
how to join the da... |
initialize the data based on the dataframe dictionary
Parameters
----------
df_dict : Dict[str, pd.DataFrame]
dataframe dictionary
join : str
how to join the data
It will reindex the dataframe based on the join key.
If join is Non... | __init__ | python | microsoft/qlib | qlib/contrib/data/utils/sepdf.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/utils/sepdf.py | MIT |
def apply_each(self, method: str, skip_align=True, *args, **kwargs):
"""
Assumptions:
- inplace methods will return None
"""
inplace = False
df_dict = {}
for k, df in self._df_dict.items():
df_dict[k] = getattr(df, method)(*args, **kwargs)
... |
Assumptions:
- inplace methods will return None
| apply_each | python | microsoft/qlib | qlib/contrib/data/utils/sepdf.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/data/utils/sepdf.py | MIT |
def calc_long_short_prec(
pred: pd.Series, label: pd.Series, date_col="datetime", quantile: float = 0.2, dropna=False, is_alpha=False
) -> Tuple[pd.Series, pd.Series]:
"""
calculate the precision for long and short operation
:param pred/label: index is **pd.MultiIndex**, index name is **[datetime, ins... |
calculate the precision for long and short operation
:param pred/label: index is **pd.MultiIndex**, index name is **[datetime, instruments]**; columns names is **[score]**.
.. code-block:: python
score
datetime instrume... | calc_long_short_prec | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def calc_long_short_return(
pred: pd.Series,
label: pd.Series,
date_col: str = "datetime",
quantile: float = 0.2,
dropna: bool = False,
) -> Tuple[pd.Series, pd.Series]:
"""
calculate long-short return
Note:
`label` must be raw stock returns.
Parameters
----------
p... |
calculate long-short return
Note:
`label` must be raw stock returns.
Parameters
----------
pred : pd.Series
stock predictions
label : pd.Series
stock returns
date_col : str
datetime index name
quantile : float
long-short quantile
Returns
... | calc_long_short_return | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def pred_autocorr_all(pred_dict, n_jobs=-1, **kwargs):
"""
calculate auto correlation for pred_dict
Parameters
----------
pred_dict : dict
A dict like {<method_name>: <prediction>}
kwargs :
all these arguments will be passed into pred_autocorr
"""
ac_dict = {}
for k... |
calculate auto correlation for pred_dict
Parameters
----------
pred_dict : dict
A dict like {<method_name>: <prediction>}
kwargs :
all these arguments will be passed into pred_autocorr
| pred_autocorr_all | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def calc_ic(pred: pd.Series, label: pd.Series, date_col="datetime", dropna=False) -> (pd.Series, pd.Series):
"""calc_ic.
Parameters
----------
pred :
pred
label :
label
date_col :
date_col
Returns
-------
(pd.Series, pd.Series)
ic and rank ic
"""... | calc_ic.
Parameters
----------
pred :
pred
label :
label
date_col :
date_col
Returns
-------
(pd.Series, pd.Series)
ic and rank ic
| calc_ic | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def calc_all_ic(pred_dict_all, label, date_col="datetime", dropna=False, n_jobs=-1):
"""calc_all_ic.
Parameters
----------
pred_dict_all :
A dict like {<method_name>: <prediction>}
label:
A pd.Series of label values
Returns
-------
{'Q2+IND_z': {'ic': <ic series like>
... | calc_all_ic.
Parameters
----------
pred_dict_all :
A dict like {<method_name>: <prediction>}
label:
A pd.Series of label values
Returns
-------
{'Q2+IND_z': {'ic': <ic series like>
2016-01-04 -0.057407
...
... | calc_all_ic | python | microsoft/qlib | qlib/contrib/eva/alpha.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/eva/alpha.py | MIT |
def setup(self, trainer=TrainerR, trainer_kwargs={}):
"""
after running this function `self.data_ic_df` will become set.
Each col represents a data.
Each row represents the Timestamp of performance of that data.
For example,
.. code-block:: python
... |
after running this function `self.data_ic_df` will become set.
Each col represents a data.
Each row represents the Timestamp of performance of that data.
For example,
.. code-block:: python
2021-06-21 2021-06-04 2021-05-21 2021-05-07 2021-04-20 2021-04-0... | setup | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def update(self):
"""update the data for online trading"""
# TODO:
# when new data are totally(including label) available
# - update the prediction
# - update the data similarity map(if applied) | update the data for online trading | update | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def __init__(self, task: dict, meta_info: pd.DataFrame, mode: str = MetaTask.PROC_MODE_FULL, fill_method="max"):
"""
The description of the processed data
time_perf: A array with shape <hist_step_n * step, data pieces> -> data piece performance
time_belong: A array with sh... |
The description of the processed data
time_perf: A array with shape <hist_step_n * step, data pieces> -> data piece performance
time_belong: A array with shape <sample, data pieces> -> belong or not (1. or 0.)
array([[1., 0., 0., ..., 0., 0., 0.],
... | __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def __init__(
self,
*,
task_tpl: Union[dict, list],
step: int,
trunc_days: int = None,
rolling_ext_days: int = 0,
exp_name: Union[str, InternalData],
segments: Union[Dict[Text, Tuple], float, str],
hist_step_n: int = 10,
task_mode: str = Me... |
A dataset for meta model.
Parameters
----------
task_tpl : Union[dict, list]
Decide what tasks are used.
- dict : the task template, the prepared task is generated with `step`, `trunc_days` and `RollingGen`
- list : when list, use the list of tasks d... | __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def _prepare_meta_ipt(self, task) -> pd.DataFrame:
"""
Please refer to `self.internal_data.setup` for detailed information about `self.internal_data.data_ic_df`
Indices with format below can be successfully sliced by `ic_df.loc[:end, pd.IndexSlice[:, :end]]`
2021-06-21 2021-06-... |
Please refer to `self.internal_data.setup` for detailed information about `self.internal_data.data_ic_df`
Indices with format below can be successfully sliced by `ic_df.loc[:end, pd.IndexSlice[:, :end]]`
2021-06-21 2021-06-04 .. 2021-03-22 2021-03-08
2021-07-02 2021-06-... | _prepare_meta_ipt | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def mask_overlap(s):
"""
mask overlap information
data after self.name[end] with self.trunc_days that contains future info are also considered as overlap info
Approximately the diagnal + horizon length of data are masked.
"""
start, end = s.name
... |
mask overlap information
data after self.name[end] with self.trunc_days that contains future info are also considered as overlap info
Approximately the diagnal + horizon length of data are masked.
| mask_overlap | python | microsoft/qlib | qlib/contrib/meta/data_selection/dataset.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/dataset.py | MIT |
def __init__(
self,
step,
hist_step_n,
clip_method="tanh",
clip_weight=2.0,
criterion="ic_loss",
lr=0.0001,
max_epoch=100,
seed=43,
alpha=0.0,
loss_skip_thresh=50,
):
"""
loss_skip_size: int
The numbe... |
loss_skip_size: int
The number of threshold to skip the loss calculation for each day.
| __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/model.py | MIT |
def fit(self, meta_dataset: MetaDatasetDS):
"""
The meta-learning-based data selection interacts directly with meta-dataset due to the close-form proxy measurement.
Parameters
----------
meta_dataset : MetaDatasetDS
The meta-model takes the meta-dataset for its train... |
The meta-learning-based data selection interacts directly with meta-dataset due to the close-form proxy measurement.
Parameters
----------
meta_dataset : MetaDatasetDS
The meta-model takes the meta-dataset for its training process.
| fit | python | microsoft/qlib | qlib/contrib/meta/data_selection/model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/model.py | MIT |
def __init__(self, step, hist_step_n, clip_weight=None, clip_method="tanh", alpha: float = 0.0):
"""
Parameters
----------
alpha : float
the regularization for sub model (useful when align meta model with linear submodel)
"""
super().__init__()
self.st... |
Parameters
----------
alpha : float
the regularization for sub model (useful when align meta model with linear submodel)
| __init__ | python | microsoft/qlib | qlib/contrib/meta/data_selection/net.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/net.py | MIT |
def forward(self, X, y, time_perf, time_belong, X_test, ignore_weight=False):
"""Please refer to the docs of MetaTaskDS for the description of the variables"""
weights = self.get_sample_weights(X, time_perf, time_belong, ignore_weight=ignore_weight)
X_w = X.T * weights.view(1, -1)
theta ... | Please refer to the docs of MetaTaskDS for the description of the variables | forward | python | microsoft/qlib | qlib/contrib/meta/data_selection/net.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/net.py | MIT |
def forward(self, pred, y, idx):
"""forward.
FIXME:
- Some times it will be a slightly different from the result from `pandas.corr()`
- It may be caused by the precision problem of model;
:param pred:
:param y:
:param idx: Assume the level of the idx is (date, in... | forward.
FIXME:
- Some times it will be a slightly different from the result from `pandas.corr()`
- It may be caused by the precision problem of model;
:param pred:
:param y:
:param idx: Assume the level of the idx is (date, inst), and it is sorted
| forward | python | microsoft/qlib | qlib/contrib/meta/data_selection/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/utils.py | MIT |
def preds_to_weight_with_clamp(preds, clip_weight=None, clip_method="tanh"):
"""
Clip the weights.
Parameters
----------
clip_weight: float
The clip threshold.
clip_method: str
The clip method. Current available: "clamp", "tanh", and "sigmoid".
"""
if clip_weight is not ... |
Clip the weights.
Parameters
----------
clip_weight: float
The clip threshold.
clip_method: str
The clip method. Current available: "clamp", "tanh", and "sigmoid".
| preds_to_weight_with_clamp | python | microsoft/qlib | qlib/contrib/meta/data_selection/utils.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/meta/data_selection/utils.py | MIT |
def get_feature_importance(self, *args, **kwargs) -> pd.Series:
"""get feature importance
Notes
-----
parameters references:
https://catboost.ai/docs/concepts/python-reference_catboost_get_feature_importance.html#python-reference_catboost_get_feature_importance
"... | get feature importance
Notes
-----
parameters references:
https://catboost.ai/docs/concepts/python-reference_catboost_get_feature_importance.html#python-reference_catboost_get_feature_importance
| get_feature_importance | python | microsoft/qlib | qlib/contrib/model/catboost_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/catboost_model.py | MIT |
def sample_reweight(self, loss_curve, loss_values, k_th):
"""
the SR module of Double Ensemble
:param loss_curve: the shape is NxT
the loss curve for the previous sub-model, where the element (i, t) if the error on the i-th sample
after the t-th iteration in the training of the p... |
the SR module of Double Ensemble
:param loss_curve: the shape is NxT
the loss curve for the previous sub-model, where the element (i, t) if the error on the i-th sample
after the t-th iteration in the training of the previous sub-model.
:param loss_values: the shape is N
... | sample_reweight | python | microsoft/qlib | qlib/contrib/model/double_ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/double_ensemble.py | MIT |
def feature_selection(self, df_train, loss_values):
"""
the FS module of Double Ensemble
:param df_train: the shape is NxF
:param loss_values: the shape is N
the loss of the current ensemble on the i-th sample.
:return: res_feat: in the form of pandas.Index
"""
... |
the FS module of Double Ensemble
:param df_train: the shape is NxF
:param loss_values: the shape is N
the loss of the current ensemble on the i-th sample.
:return: res_feat: in the form of pandas.Index
| feature_selection | python | microsoft/qlib | qlib/contrib/model/double_ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/double_ensemble.py | MIT |
def get_feature_importance(self, *args, **kwargs) -> pd.Series:
"""get feature importance
Notes
-----
parameters reference:
https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html?highlight=feature_importance#lightgbm.Booster.feature_importance
... | get feature importance
Notes
-----
parameters reference:
https://lightgbm.readthedocs.io/en/latest/pythonapi/lightgbm.Booster.html?highlight=feature_importance#lightgbm.Booster.feature_importance
| get_feature_importance | python | microsoft/qlib | qlib/contrib/model/double_ensemble.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/double_ensemble.py | MIT |
def _prepare_data(self, dataset: DatasetH, reweighter=None) -> List[Tuple[lgb.Dataset, str]]:
"""
The motivation of current version is to make validation optional
- train segment is necessary;
"""
ds_l = []
assert "train" in dataset.segments
for key in ["train", "... |
The motivation of current version is to make validation optional
- train segment is necessary;
| _prepare_data | python | microsoft/qlib | qlib/contrib/model/gbdt.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/gbdt.py | MIT |
def finetune(self, dataset: DatasetH, num_boost_round=10, verbose_eval=20, reweighter=None):
"""
finetune model
Parameters
----------
dataset : DatasetH
dataset for finetuning
num_boost_round : int
number of round to finetune model
verbose... |
finetune model
Parameters
----------
dataset : DatasetH
dataset for finetuning
num_boost_round : int
number of round to finetune model
verbose_eval : int
verbose level
| finetune | python | microsoft/qlib | qlib/contrib/model/gbdt.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/gbdt.py | MIT |
def _cal_signal_metrics(self, y_test, l_cut, r_cut):
"""
Calcaute the signal metrics by daily level
"""
up_pre, down_pre = [], []
up_alpha_ll, down_alpha_ll = [], []
for date in y_test.index.get_level_values(0).unique():
df_res = y_test.loc[date].sort_values("... |
Calcaute the signal metrics by daily level
| _cal_signal_metrics | python | microsoft/qlib | qlib/contrib/model/highfreq_gdbt_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/highfreq_gdbt_model.py | MIT |
def hf_signal_test(self, dataset: DatasetH, threhold=0.2):
"""
Test the signal in high frequency test set
"""
if self.model is None:
raise ValueError("Model hasn't been trained yet")
df_test = dataset.prepare("test", col_set=["feature", "label"], data_key=DataHandlerL... |
Test the signal in high frequency test set
| hf_signal_test | python | microsoft/qlib | qlib/contrib/model/highfreq_gdbt_model.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/highfreq_gdbt_model.py | MIT |
def __init__(self, estimator="ols", alpha=0.0, fit_intercept=False, include_valid: bool = False):
"""
Parameters
----------
estimator : str
which estimator to use for linear regression
alpha : float
l1 or l2 regularization parameter
fit_intercept :... |
Parameters
----------
estimator : str
which estimator to use for linear regression
alpha : float
l1 or l2 regularization parameter
fit_intercept : bool
whether fit intercept
include_valid: bool
Should the validation data be... | __init__ | python | microsoft/qlib | qlib/contrib/model/linear.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/linear.py | MIT |
def calc_all_metrics(pred):
"""pred is a pandas dataframe that has two attributes: score (pred) and label (real)"""
res = {}
ic = pred.groupby(level="datetime", group_keys=False).apply(lambda x: x.label.corr(x.score))
rank_ic = pred.groupby(level="datetime", group_keys=False).apply(
... | pred is a pandas dataframe that has two attributes: score (pred) and label (real) | calc_all_metrics | python | microsoft/qlib | qlib/contrib/model/pytorch_adarnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_adarnn.py | MIT |
def __init__(self, loss_type="cosine", input_dim=512, GPU=0):
"""
Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
"""
self.loss_type = loss_type
self.input_dim = input_dim
self.device = torch.device("cuda:%d" % GPU if torch.cuda.is_available()... |
Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_adarnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_adarnn.py | MIT |
def compute(self, X, Y):
"""Compute adaptation loss
Arguments:
X {tensor} -- source matrix
Y {tensor} -- target matrix
Returns:
[tensor] -- transfer loss
"""
loss = None
if self.loss_type in ("mmd_lin", "mmd"):
mmdloss = M... | Compute adaptation loss
Arguments:
X {tensor} -- source matrix
Y {tensor} -- target matrix
Returns:
[tensor] -- transfer loss
| compute | python | microsoft/qlib | qlib/contrib/model/pytorch_adarnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_adarnn.py | MIT |
def __init__(self, gamma=0.1, gamma_clip=0.4, *args, **kwargs):
"""
A gradient reversal layer.
This layer has no parameters, and simply reverses the gradient
in the backward pass.
"""
super().__init__(*args, **kwargs)
self.gamma = gamma
self.gamma_clip = ... |
A gradient reversal layer.
This layer has no parameters, and simply reverses the gradient
in the backward pass.
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_add.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_add.py | MIT |
def _get_fl(self, data: torch.Tensor):
"""
get feature and label from data
- Handle the different data shape of time series and tabular data
Parameters
----------
data : torch.Tensor
input data which maybe 3 dimension or 2 dimension
- 3dim: [batch... |
get feature and label from data
- Handle the different data shape of time series and tabular data
Parameters
----------
data : torch.Tensor
input data which maybe 3 dimension or 2 dimension
- 3dim: [batch_size, time_step, feature_dim]
- 2dim:... | _get_fl | python | microsoft/qlib | qlib/contrib/model/pytorch_general_nn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_general_nn.py | MIT |
def __init__(self, input_dim, output_dim, kernel_size, device):
"""Build a basic CNN encoder
Parameters
----------
input_dim : int
The input dimension
output_dim : int
The output dimension
kernel_size : int
The size of convolutional ke... | Build a basic CNN encoder
Parameters
----------
input_dim : int
The input dimension
output_dim : int
The output dimension
kernel_size : int
The size of convolutional kernels
| __init__ | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
def forward(self, x):
"""
Parameters
----------
x : torch.Tensor
input data
Returns
-------
torch.Tensor
Updated representations
"""
# input shape: [batch_size, seq_len*input_dim]
# output shape: [batch_size, seq_l... |
Parameters
----------
x : torch.Tensor
input data
Returns
-------
torch.Tensor
Updated representations
| forward | python | microsoft/qlib | qlib/contrib/model/pytorch_krnn.py | https://github.com/microsoft/qlib/blob/master/qlib/contrib/model/pytorch_krnn.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.