前两期中分别介绍了数据下载与处理,工作流 和 策略的实现,本期在此基础上讨论高频交易及在线交易的实现。
高频交易
回顾Qlib 的 Workflow层,Trading Agent 在前几期中已着重介绍,主要用于信息提取、模型预测和决策生存,类似于强化学习中的动作空间,本期将着重介绍Execution Env,即决策的执行过程,该过程能够内置细粒度的交易算法和子工作流(如高频交易)。
Step 1: 参数设置
注意其中"freq" 设为 "1min"。
market = "csi300"
benchmark = "SH000300"
data_handler_config = {
"start_time": "2008-01-01",
"end_time": "2021-05-31",
"fit_start_time": "2008-01-01",
"fit_end_time": "2014-12-31",
"instruments": market,
}
task = {
"model": {
"class": "LGBModel",
"module_path": "qlib.contrib.model.gbdt",
"kwargs": {
"loss": "mse",
"colsample_bytree": 0.8879,
"learning_rate": 0.0421,
"subsample": 0.8789,
"lambda_l1": 205.6999,
"lambda_l2": 580.9768,
"max_depth": 8,
"num_leaves": 210,
"num_threads": 20,
},
},
"dataset": {
"class": "DatasetH",
"module_path": "qlib.data.dataset",
"kwargs": {
"handler": {
"class": "Alpha158",
"module_path": "qlib.contrib.data.handler",
"kwargs": data_handler_config,
},
"segments": {
"train": ("2007-01-01", "2014-12-31"),
"valid": ("2015-01-01", "2016-12-31"),
"test": ("2020-01-01", "2021-05-31"),
},
},
},
}
port_analysis_config = {
"executor": {
"class": "NestedExecutor",
"module_path": "qlib.backtest.executor",
"kwargs": {
"time_per_step": "day", # 操作周期
"inner_executor": {
"class": "NestedExecutor",
"module_path": "qlib.backtest.executor",
"kwargs": {
"time_per_step": "30min", # 粒度细分
"inner_executor": {
"class": "SimulatorExecutor",
"module_path": "qlib.backtest.executor",
"kwargs": {
"time_per_step": "5min", # 进一步细分
"generate_portfolio_metrics": True,
"verbose": True,
"indicator_config": {
"show_indicator": True,
},
},
},
"inner_strategy": {
"class": "TWAPStrategy",
"module_path": "qlib.contrib.strategy.rule_strategy",
},
"generate_portfolio_metrics": True,
"indicator_config": {
"show_indicator": True,
},
},
},
"inner_strategy": {
"class": "SBBStrategyEMA",
"module_path": "qlib.contrib.strategy.rule_strategy",
"kwargs": {
"instruments": market,
"freq": "1min",
},
},
"track_data": True,
"generate_portfolio_metrics": True,
"indicator_config": {
"show_indicator": True,
},
},
},
"backtest": {
"start_time": "2020-09-20",
"end_time": "2021-05-20",
"account": 100000000, # 账户初始值
"exchange_kwargs": {
"freq": "1min",
"limit_threshold": 0.095,
"deal_price": "close",
"open_cost": 0.0005, # 买入交易费率
"close_cost": 0.0015, # 卖出交易费率
"min_cost": 5, # 最小交易费用
},
},Step 2: 加载数据并初始化
def _init_qlib(self):
"""initialize qlib"""
provider_uri_day = "~/.qlib/qlib_data/cn_data" # target_dir
GetData().qlib_data(target_dir=provider_uri_day, region=REG_CN, version="v2", exists_skip=True)
provider_uri_1min = HIGH_FREQ_CONFIG.get("provider_uri")
GetData().qlib_data(
target_dir=provider_uri_1min, interval="1min", region=REG_CN, version="v2", exists_skip=True
)
provider_uri_map = {"1min": provider_uri_1min, "day": provider_uri_day}
qlib.init(provider_uri=provider_uri_map, dataset_cache=None, expression_cache=None)Step 3: 模型训练
def _train_model(self, model, dataset):
with R.start(experiment_name="train"):
R.log_params(**flatten_dict(self.task))
model.fit(dataset)
R.save_objects(**{"params.pkl": model})
# prediction
recorder = R.get_recorder()
sr = SignalRecord(model, dataset, recorder)
sr.generate()Step 4: 交易回测
def backtest(self):
self._init_qlib()
model = init_instance_by_config(self.task["model"])
dataset = init_instance_by_config(self.task["dataset"])
self._train_model(model, dataset)
strategy_config = {
"class": "TopkDropoutStrategy",
"module_path": "qlib.contrib.strategy.signal_strategy",
"kwargs": {
"signal": (model, dataset),
"topk": 50,
"n_drop": 5,
},
}
self.port_analysis_config["strategy"] = strategy_config
self.port_analysis_config["backtest"]["benchmark"] = self.benchmark
with R.start(experiment_name="backtest"):
recorder = R.get_recorder()
par = PortAnaRecord(
recorder,
self.port_analysis_config,
indicator_analysis_method="value_weighted",
)
par.generate()交易过程的监控如下:
[I 2021-05-19 13:10:00]: buy SZ000708, price 11.70, amount 41504.288867153955, deal_amount 4539.531594844963, factor 0.46260279417037964, value 53130.00, cash 916.60.
[Indicator(5min) 2021-05-19 13:10:00]: FFR: 0.5546875000000001, PA: 0.0, POS: 0.0
[I 2021-05-19 13:15:00]: sell SH601919, price 1.40, amount 37695.54699419826, deal_amount 37695.54699419827, factor 0.06366799771785736, value 52824.00, cash 53661.37.
[I 2021-05-19 13:15:00]: buy SZ000708, price 11.73, amount 59013.91073298453, deal_amount 4539.531594844963, factor 0.46260279417037964, value 53235.00, cash 399.75.
[Indicator(5min) 2021-05-19 13:15:00]: FFR: 0.5384615384615385, PA: 0.0, POS: 0.0
[I 2021-05-19 13:20:00]: sell SH601919, price 1.40, amount 36124.89920277333, deal_amount 36124.89920277334, factor 0.06366799771785736, value 50715.00, cash 51038.68.其中监控指标含义如下:
| indicator | desc. |
|--------------+--------------------------------------------------------------|
| amount | the *target* amount given by the outer strategy |
| deal_amount | the real deal amount |
| inner_amount | the total *target* amount of inner strategy |
| trade_price | the average deal price |
| trade_value | the total trade value |
| trade_cost | the total trade cost (base price need drection) |
| trade_dir | the trading direction |
| ffr | full fill rate |
| pa | price advantage |
| pos | win rate |
| base_price | the price of baseline |
| base_volume | the volume of baseline (for weighted aggregating base_price) |统计1天的检测指标:
'The following are analysis results of indicators(1day).'
value
ffr 0.945241
pa 0.000225
pos 0.538067回测结果如下:
'The following are analysis results of benchmark return(1day).'
risk
mean 0.000651
std 0.012472
annualized_return 0.154967
information_ratio 0.805422
max_drawdown -0.160445
'The following are analysis results of the excess return without cost(1day).'
risk
mean 0.000467
std 0.007178
annualized_return 0.111101
information_ratio 1.003316
max_drawdown -0.104557
'The following are analysis results of the excess return with cost(1day).'
risk
mean 0.000323
std 0.007183
annualized_return 0.076929
information_ratio 0.694242
max_drawdown -0.108544在线交易
除了回测外,验证模型的有效方法便是在线实测。Online Serving 框架如下图所示,主要包括Online Manager, Online Strategy, Online Tool, Updater。下面将逐一简要介绍这几部分:
Online Manager
在线管理器能够管理多个在线策略并动态运行这些策略,在不同trainer下共有4种状态:
- Online + Trainer
- Online + DelayTrainer
- Simulation + Trainer
- Simulation + DelayTrainer
详情参见qlib.workflow.online.manager.OnlineManager。
Online Strategy
在线策略是在线服务的一个部分,主要包括 OnlineStrategy 和 RollingStrategy,详情参见 qlib.workflow.online.strategy 。
Online Tool
在线工具用以确定在时间序列中模型的使用,详情参见qlib.workflow.online.utils.OnlineTool。
Updater
更新器随着股票数据的变化更新模型结果,详情参见qlib.workflow.online.update 。 |
|