mirror of
https://github.com/microsoft/qlib.git
synced 2026-07-06 20:41:09 +08:00
black format & add comments & add randStrategy direction
This commit is contained in:
@@ -92,7 +92,9 @@ def get_exchange(
|
||||
return init_instance_by_config(exchange, accept_types=Exchange)
|
||||
|
||||
|
||||
def create_account_instance(start_time, end_time, benchmark: str, account: float, pos_type: str="Position") -> Account:
|
||||
def create_account_instance(
|
||||
start_time, end_time, benchmark: str, account: float, pos_type: str = "Position"
|
||||
) -> Account:
|
||||
"""
|
||||
# TODO: is very strange pass benchmark_config in the account(maybe for report)
|
||||
# There should be a post-step to process the report.
|
||||
@@ -119,26 +121,25 @@ def create_account_instance(start_time, end_time, benchmark: str, account: float
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
},
|
||||
"pos_type": pos_type
|
||||
"pos_type": pos_type,
|
||||
}
|
||||
return Account(**kwargs)
|
||||
|
||||
|
||||
def get_strategy_executor(start_time,
|
||||
end_time,
|
||||
strategy: BaseStrategy,
|
||||
executor: BaseExecutor,
|
||||
benchmark: str = "SH000300",
|
||||
account: Union[float, str] = 1e9,
|
||||
exchange_kwargs: dict = {},
|
||||
pos_type: str = "Position",
|
||||
):
|
||||
def get_strategy_executor(
|
||||
start_time,
|
||||
end_time,
|
||||
strategy: BaseStrategy,
|
||||
executor: BaseExecutor,
|
||||
benchmark: str = "SH000300",
|
||||
account: Union[float, str] = 1e9,
|
||||
exchange_kwargs: dict = {},
|
||||
pos_type: str = "Position",
|
||||
):
|
||||
|
||||
trade_account = create_account_instance(start_time=start_time,
|
||||
end_time=end_time,
|
||||
benchmark=benchmark,
|
||||
account=account,
|
||||
pos_type=pos_type)
|
||||
trade_account = create_account_instance(
|
||||
start_time=start_time, end_time=end_time, benchmark=benchmark, account=account, pos_type=pos_type
|
||||
)
|
||||
|
||||
exchange_kwargs = copy.copy(exchange_kwargs)
|
||||
if "start_time" not in exchange_kwargs:
|
||||
@@ -154,14 +155,16 @@ def get_strategy_executor(start_time,
|
||||
return trade_strategy, trade_executor
|
||||
|
||||
|
||||
def backtest(start_time,
|
||||
end_time,
|
||||
strategy,
|
||||
executor,
|
||||
benchmark="SH000300",
|
||||
account=1e9,
|
||||
exchange_kwargs={},
|
||||
pos_type: str = "Position"):
|
||||
def backtest(
|
||||
start_time,
|
||||
end_time,
|
||||
strategy,
|
||||
executor,
|
||||
benchmark="SH000300",
|
||||
account=1e9,
|
||||
exchange_kwargs={},
|
||||
pos_type: str = "Position",
|
||||
):
|
||||
|
||||
trade_strategy, trade_executor = get_strategy_executor(
|
||||
start_time,
|
||||
@@ -178,14 +181,16 @@ def backtest(start_time,
|
||||
return report_dict, indicator_dict
|
||||
|
||||
|
||||
def collect_data(start_time,
|
||||
end_time,
|
||||
strategy,
|
||||
executor,
|
||||
benchmark="SH000300",
|
||||
account=1e9,
|
||||
exchange_kwargs={},
|
||||
pos_type: str = "Position"):
|
||||
def collect_data(
|
||||
start_time,
|
||||
end_time,
|
||||
strategy,
|
||||
executor,
|
||||
benchmark="SH000300",
|
||||
account=1e9,
|
||||
exchange_kwargs={},
|
||||
pos_type: str = "Position",
|
||||
):
|
||||
|
||||
trade_strategy, trade_executor = get_strategy_executor(
|
||||
start_time,
|
||||
|
||||
@@ -63,7 +63,9 @@ class AccumulatedInfo:
|
||||
|
||||
|
||||
class Account:
|
||||
def __init__(self, init_cash: float=1e9, freq: str = "day", benchmark_config: dict = {}, pos_type:str = "Position"):
|
||||
def __init__(
|
||||
self, init_cash: float = 1e9, freq: str = "day", benchmark_config: dict = {}, pos_type: str = "Position"
|
||||
):
|
||||
self.pos_type = pos_type
|
||||
self.init_vars(init_cash, freq, benchmark_config)
|
||||
|
||||
@@ -71,13 +73,13 @@ class Account:
|
||||
|
||||
# init cash
|
||||
self.init_cash = init_cash
|
||||
self.current: BasePosition = init_instance_by_config({
|
||||
'class': self.pos_type,
|
||||
'kwargs': {
|
||||
"cash": init_cash
|
||||
},
|
||||
'module_path': "qlib.backtest.position",
|
||||
})
|
||||
self.current: BasePosition = init_instance_by_config(
|
||||
{
|
||||
"class": self.pos_type,
|
||||
"kwargs": {"cash": init_cash},
|
||||
"module_path": "qlib.backtest.position",
|
||||
}
|
||||
)
|
||||
self.accum_info = AccumulatedInfo()
|
||||
self.reset(freq=freq, benchmark_config=benchmark_config, init_report=True)
|
||||
|
||||
|
||||
@@ -23,7 +23,9 @@ def backtest_loop(start_time, end_time, trade_strategy: BaseStrategy, trade_exec
|
||||
return return_value.get("report"), return_value.get("indicator")
|
||||
|
||||
|
||||
def collect_data_loop(start_time, end_time, trade_strategy: BaseStrategy, trade_executor: BaseExecutor, return_value: dict = None):
|
||||
def collect_data_loop(
|
||||
start_time, end_time, trade_strategy: BaseStrategy, trade_executor: BaseExecutor, return_value: dict = None
|
||||
):
|
||||
"""Generator for collecting the trade decision data for rl training
|
||||
|
||||
Parameters
|
||||
@@ -68,7 +70,7 @@ def collect_data_loop(start_time, end_time, trade_strategy: BaseStrategy, trade_
|
||||
}
|
||||
all_indicators = {}
|
||||
for _executor in all_executors:
|
||||
key = "{}{}".format( *Freq.parse(_executor.time_per_step))
|
||||
key = "{}{}".format(*Freq.parse(_executor.time_per_step))
|
||||
all_indicators[key] = _executor.get_trade_indicator().generate_trade_indicators_dataframe()
|
||||
all_indicators[key + "_obj"] = _executor.get_trade_indicator()
|
||||
return_value.update({"report": all_reports, "indicator": all_indicators})
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
# Licensed under the MIT License.
|
||||
# TODO: rename it with decision.py
|
||||
from __future__ import annotations
|
||||
|
||||
# try to fix circular imports when enabling type hints
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from qlib.strategy.base import BaseStrategy
|
||||
from qlib.backtest.utils import TradeCalendarManager
|
||||
@@ -59,6 +61,7 @@ class BaseTradeDecision:
|
||||
1. The outer strategy's decision is available at the start of the interval
|
||||
2. Same as `case 1.3`
|
||||
"""
|
||||
|
||||
def __init__(self, strategy: BaseStrategy):
|
||||
"""
|
||||
Parameters
|
||||
@@ -125,7 +128,8 @@ class TradeDecisionWO(BaseTradeDecision):
|
||||
Trade Decision (W)ith (O)rder.
|
||||
Besides, the time_range is also included.
|
||||
"""
|
||||
def __init__(self, order_list: List[Order], strategy: BaseStrategy, idx_range: Tuple=None):
|
||||
|
||||
def __init__(self, order_list: List[Order], strategy: BaseStrategy, idx_range: Tuple = None):
|
||||
super().__init__(strategy)
|
||||
self.order_list = order_list
|
||||
self.idx_range = idx_range
|
||||
@@ -198,8 +202,7 @@ class TradeDecisionWithOrderPool:
|
||||
|
||||
class BaseDecisionUpdater:
|
||||
def update_decision(self, decision, trade_calendar) -> BaseTradeDecision:
|
||||
"""[summary]
|
||||
|
||||
"""
|
||||
Parameters
|
||||
----------
|
||||
decision : BaseTradeDecision
|
||||
|
||||
@@ -15,7 +15,8 @@ class BasePosition:
|
||||
The Position want to maintain the position like a dictionary
|
||||
Please refer to the `Position` class for the position
|
||||
"""
|
||||
def __init__(self, cash=0., *args, **kwargs) -> None:
|
||||
|
||||
def __init__(self, cash=0.0, *args, **kwargs) -> None:
|
||||
pass
|
||||
|
||||
def skip_update(self) -> bool:
|
||||
@@ -46,7 +47,6 @@ class BasePosition:
|
||||
"""
|
||||
raise NotImplementedError(f"Please implement the `check_stock` method")
|
||||
|
||||
|
||||
def update_order(self, order: Order, trade_val: float, cost: float, trade_price: float):
|
||||
"""
|
||||
Parameters
|
||||
@@ -86,6 +86,7 @@ class BasePosition:
|
||||
the value(money) of all the stock
|
||||
"""
|
||||
raise NotImplementedError(f"Please implement the `calculate_stock_value` method")
|
||||
|
||||
def get_stock_list(self) -> List:
|
||||
"""
|
||||
Get the list of stocks in the position.
|
||||
@@ -140,7 +141,7 @@ class BasePosition:
|
||||
"""
|
||||
raise NotImplementedError(f"Please implement the `get_stock_amount_dict` method")
|
||||
|
||||
def get_stock_weight_dict(self, only_stock: bool=False) -> Dict:
|
||||
def get_stock_weight_dict(self, only_stock: bool = False) -> 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
|
||||
@@ -399,13 +400,13 @@ class Position(BasePosition):
|
||||
self.position["now_account_value"] = now_account_value
|
||||
|
||||
|
||||
|
||||
class InfPosition(BasePosition):
|
||||
"""
|
||||
Position with infinite cash and amount.
|
||||
|
||||
This is useful for generating random orders.
|
||||
"""
|
||||
|
||||
def skip_update(self) -> bool:
|
||||
""" Updating state is meaningless for InfPosition """
|
||||
return True
|
||||
|
||||
@@ -18,7 +18,7 @@ from ..tests.config import CSI300_BENCH
|
||||
|
||||
|
||||
class Report:
|
||||
'''
|
||||
"""
|
||||
Motivation:
|
||||
Report is for supporting portfolio related metrics.
|
||||
|
||||
@@ -26,7 +26,8 @@ class Report:
|
||||
daily report of the account
|
||||
contain those followings: returns, costs turnovers, accounts, cash, bench, value
|
||||
update report
|
||||
'''
|
||||
"""
|
||||
|
||||
def __init__(self, freq: str = "day", benchmark_config: dict = {}):
|
||||
"""
|
||||
Parameters
|
||||
|
||||
@@ -140,7 +140,6 @@ class BaseInfrastructure:
|
||||
self.reset_infra(**infra_dict)
|
||||
|
||||
|
||||
|
||||
class CommonInfrastructure(BaseInfrastructure):
|
||||
def get_support_infra(self):
|
||||
return ["trade_account", "trade_exchange"]
|
||||
|
||||
Reference in New Issue
Block a user