-
Notifications
You must be signed in to change notification settings - Fork 5.4k
Support Highfreq Backtest with the Model/Rule/RL Strategy #408
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
28 commits
Select commit
Hold shift + click to select a range
d3a1e03
add sample & base class
bxdd 971d6a2
update strategy
bxdd 8979d78
update report & account
bxdd 39deb7d
update env & strategy, add workflow
bxdd b14efa1
update trade calendar & backtest workflow
bxdd af0053e
fix bug
bxdd 8920c19
del outdate file
bxdd 86a6f56
trade_account support multi bar report
bxdd 49cdaf8
update port_ana_record
bxdd f404a03
black format
bxdd a109df3
fix bug in recorder
bxdd d297a49
fix bugs
bxdd e30df11
solve the conflict
bxdd ae33950
del old strategy
bxdd 7540ecd
fix trade time bug
bxdd bc3eada
black format
bxdd f7d3096
update the internal bar strategy
bxdd 621cb24
fix some comments and add docstring
bxdd 07eaada
fix comments
bxdd c703dab
fix rule_strategy reset method
bxdd de2658a
fix rule_strategy bug
bxdd ea60e60
update rule_startegy & add README, notebook for multi-level trading
bxdd eaa719d
optimize rule_strategy performance
bxdd dda509d
Update record_temp.py
you-n-g 26d75b7
Update sample.py
you-n-g 0c6e505
fix comments
bxdd 75fcb38
Merge branch 'qlib_highfreq_backtest' of github.com:bxdd/qlib into bx…
bxdd ee74489
solve the conflict
bxdd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| # Multi-level Trading | ||
|
|
||
| This worflow is an example for multi-level trading. | ||
|
|
||
| ## Introduction | ||
|
|
||
| Qlib supports backtesting of various strategies, including portfolio management strategies, order split strategies, model-based strategies (such as deep learning models), rule-based strategies, and RL-based strategies. | ||
|
|
||
| And, Qlib also supports multi-level trading and backtesting. It means that users can use different strategies to trade at different frequencies. | ||
|
|
||
| This example uses a DropoutTopkStrategy (a strategy based on the daily frequency Lightgbm model) in weekly frequency for portfolio generation. And, at the daily frequency level, this example uses SBBStrategyEMA (a rule-based strategy that uses EMA for decision-making) to split orders. | ||
|
|
||
| ## Usage | ||
|
|
||
| Start backtesting by running the following command: | ||
| ```bash | ||
| python workflow.py backtest | ||
| ``` | ||
|
|
||
| Start collecting data by running the following command: | ||
| ```bash | ||
| python workflow.py collect_data | ||
| ``` | ||
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,173 @@ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
|
|
||
|
|
||
| import qlib | ||
| import fire | ||
| from qlib.config import REG_CN | ||
|
|
||
| from qlib.utils import exists_qlib_data, init_instance_by_config, flatten_dict | ||
| from qlib.workflow import R | ||
| from qlib.workflow.record_temp import SignalRecord, PortAnaRecord | ||
| from qlib.tests.data import GetData | ||
| from qlib.contrib.backtest import collect_data | ||
|
|
||
|
|
||
| class MultiLevelTradingWorkflow: | ||
|
|
||
| market = "csi300" | ||
| benchmark = "SH000300" | ||
|
|
||
| data_handler_config = { | ||
| "start_time": "2008-01-01", | ||
| "end_time": "2020-08-01", | ||
| "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": ("2008-01-01", "2014-12-31"), | ||
| "valid": ("2015-01-01", "2016-12-31"), | ||
| "test": ("2017-01-01", "2020-08-01"), | ||
| }, | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| trade_start_time = "2017-01-01" | ||
| trade_end_time = "2020-08-01" | ||
|
|
||
| port_analysis_config = { | ||
| "executor": { | ||
| "class": "SplitExecutor", | ||
| "module_path": "qlib.contrib.backtest.executor", | ||
| "kwargs": { | ||
| "step_bar": "week", | ||
| "sub_executor": { | ||
| "class": "SimulatorExecutor", | ||
| "module_path": "qlib.contrib.backtest.executor", | ||
| "kwargs": { | ||
| "step_bar": "day", | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Let's figure out a better name for
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Please send all the new names to the group for discussion |
||
| "verbose": True, | ||
| "generate_report": True, | ||
| }, | ||
| }, | ||
| "sub_strategy": { | ||
| "class": "SBBStrategyEMA", | ||
| "module_path": "qlib.contrib.strategy.rule_strategy", | ||
| "kwargs": { | ||
| "freq": "day", | ||
| "instruments": market, | ||
| }, | ||
| }, | ||
| "track_data": True, | ||
| }, | ||
| }, | ||
| "backtest": { | ||
| "start_time": trade_start_time, | ||
| "end_time": trade_end_time, | ||
| "account": 100000000, | ||
| "benchmark": benchmark, | ||
| "exchange_kwargs": { | ||
| "freq": "day", | ||
| "limit_threshold": 0.095, | ||
| "deal_price": "close", | ||
| "open_cost": 0.0005, | ||
| "close_cost": 0.0015, | ||
| "min_cost": 5, | ||
| }, | ||
| }, | ||
| } | ||
|
|
||
| def _init_qlib(self): | ||
| """initialize qlib""" | ||
| # use yahoo_cn_1min data | ||
| provider_uri = "~/.qlib/qlib_data/cn_data" # target_dir | ||
| if not exists_qlib_data(provider_uri): | ||
| print(f"Qlib data is not found in {provider_uri}") | ||
| GetData().qlib_data(target_dir=provider_uri, region=REG_CN) | ||
| qlib.init(provider_uri=provider_uri, region=REG_CN) | ||
|
|
||
| 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() | ||
|
|
||
| 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.model_strategy", | ||
| "kwargs": { | ||
| "model": model, | ||
| "dataset": dataset, | ||
| "topk": 50, | ||
| "n_drop": 5, | ||
| }, | ||
| } | ||
| self.port_analysis_config["strategy"] = strategy_config | ||
| with R.start(experiment_name="backtest"): | ||
|
|
||
| recorder = R.get_recorder() | ||
| par = PortAnaRecord(recorder, self.port_analysis_config, "day") | ||
| par.generate() | ||
|
|
||
| def collect_data(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) | ||
| executor_config = self.port_analysis_config["executor"] | ||
| backtest_config = self.port_analysis_config["backtest"] | ||
| strategy_config = { | ||
| "class": "TopkDropoutStrategy", | ||
| "module_path": "qlib.contrib.strategy.model_strategy", | ||
| "kwargs": { | ||
| "model": model, | ||
| "dataset": dataset, | ||
| "topk": 50, | ||
| "n_drop": 5, | ||
| }, | ||
| } | ||
| data_generator = collect_data(executor=executor_config, strategy=strategy_config, **backtest_config) | ||
| for trade_decision in data_generator: | ||
| print(trade_decision) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| fire.Fire(MultiLevelTradingWorkflow) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Where is the yield example for collecting data?