Skip to content
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

Support Highfreq Backtest with the Model/Rule/RL Strategy #438

Merged
merged 223 commits into from
Sep 30, 2021
Merged
Show file tree
Hide file tree
Changes from 62 commits
Commits
Show all changes
223 commits
Select commit Hold shift + click to select a range
d3a1e03
add sample & base class
bxdd Mar 19, 2021
971d6a2
update strategy
bxdd Apr 21, 2021
8979d78
update report & account
bxdd Apr 21, 2021
39deb7d
update env & strategy, add workflow
bxdd Apr 22, 2021
b14efa1
update trade calendar & backtest workflow
bxdd Apr 23, 2021
af0053e
fix bug
bxdd Apr 24, 2021
8920c19
del outdate file
bxdd Apr 26, 2021
86a6f56
trade_account support multi bar report
bxdd Apr 28, 2021
49cdaf8
update port_ana_record
bxdd Apr 28, 2021
f404a03
black format
bxdd Apr 28, 2021
a109df3
fix bug in recorder
bxdd Apr 29, 2021
d297a49
fix bugs
bxdd Apr 30, 2021
e30df11
solve the conflict
bxdd Apr 30, 2021
ae33950
del old strategy
bxdd Apr 30, 2021
7540ecd
fix trade time bug
bxdd May 6, 2021
bc3eada
black format
bxdd May 6, 2021
f7d3096
update the internal bar strategy
bxdd May 6, 2021
621cb24
fix some comments and add docstring
bxdd May 11, 2021
07eaada
fix comments
bxdd May 12, 2021
c703dab
fix rule_strategy reset method
bxdd May 12, 2021
de2658a
fix rule_strategy bug
bxdd May 13, 2021
ea60e60
update rule_startegy & add README, notebook for multi-level trading
bxdd May 13, 2021
eaa719d
optimize rule_strategy performance
bxdd May 14, 2021
dda509d
Update record_temp.py
you-n-g May 19, 2021
26d75b7
Update sample.py
you-n-g May 19, 2021
0c6e505
fix comments
bxdd May 24, 2021
75fcb38
Merge branch 'qlib_highfreq_backtest' of github.com:bxdd/qlib into bx…
bxdd May 24, 2021
ee74489
solve the conflict
bxdd May 24, 2021
2ad61f1
rename var in backtest
bxdd May 27, 2021
4085b44
move backtest to core, fix calendar bugs, add some docstring
bxdd May 27, 2021
6a63654
Merge github.com:microsoft/qlib into bxdd-qlib_highfreq_backtest
bxdd May 27, 2021
c26bee1
Support loading for backtest
ultmaster May 28, 2021
029b63c
fix bugs & add highfreq backtest example
bxdd May 28, 2021
96e393b
del DEBUG log
bxdd May 28, 2021
bf3b757
fix bugs
bxdd May 28, 2021
60e082e
add infra interface & fix no KeyboardInterpret bug
bxdd May 31, 2021
d3dac06
Update simple playground
ultmaster Jun 1, 2021
cdc59a7
Merge branch 'nested_decision_exe' into rl-dummy
ultmaster Jun 1, 2021
bf16e1a
update Order with dataclass
bxdd Jun 1, 2021
a46d99a
black format
bxdd Jun 1, 2021
a183d8a
update workflow_by_code & update executor
bxdd Jun 1, 2021
04fff8c
solve conflict
bxdd Jun 1, 2021
449e3f4
Update init in backtest
ultmaster Jun 1, 2021
a8e96e5
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
ultmaster Jun 1, 2021
83535bf
Playground checkpoint
ultmaster Jun 1, 2021
4d48c96
fix CI
bxdd Jun 1, 2021
3200bb8
Update an initial version of RL
ultmaster Jun 2, 2021
d515efb
Finish RL dummy example
ultmaster Jun 2, 2021
cc8339a
Add a few comments
ultmaster Jun 2, 2021
2314405
Rename files
ultmaster Jun 2, 2021
f5ac623
Refactor for strategy
ultmaster Jun 2, 2021
bf02fc2
Add RL strategy demo
ultmaster Jun 2, 2021
8aee853
update Exchange
bxdd Jun 3, 2021
c43805e
Update end-to-end example and requirements
ultmaster Jun 4, 2021
1581ef1
Update impl for robustness
ultmaster Jun 4, 2021
46d253b
update Exchange.deal_order
bxdd Jun 4, 2021
a06fa2b
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
ultmaster Jun 4, 2021
76be5d5
Refine example
ultmaster Jun 7, 2021
f78e901
fix comments & add VAStrategy & add trade indicator
bxdd Jun 14, 2021
9e45528
update backtest time range
bxdd Jun 14, 2021
4ac6e6e
fix account bug & update indicator_analysis & fix some comments
bxdd Jun 21, 2021
56cf43d
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jun 22, 2021
7525854
Add shortcut in init
Jun 22, 2021
ab97e82
fix bug in Exchange
bxdd Jun 22, 2021
d226ac8
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jun 22, 2021
583fbbe
Resolve init conflict
Jun 22, 2021
1517a9e
add default executor config & update bug in indicator
bxdd Jun 24, 2021
b6564cd
support trade decision update
bxdd Jun 24, 2021
284d967
fix bug in resam feature
bxdd Jun 27, 2021
4f384d3
API enhancement
you-n-g Jun 25, 2021
b68294d
add InfPosition
you-n-g Jun 25, 2021
b41267f
successful run random order gen in day script
you-n-g Jun 25, 2021
9b91758
performance optimization for cal_sam_minute
you-n-g Jun 27, 2021
e78cdd4
return the detailed order indicator
you-n-g Jun 27, 2021
c907d8d
fix bugs of random strategy
you-n-g Jun 27, 2021
72c9593
adapting strategies to latest interfaces.
you-n-g Jun 28, 2021
27f0db6
black format & add comments & add randStrategy direction
you-n-g Jun 28, 2021
8e8bba1
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
ultmaster Jun 28, 2021
20d566c
Merge branch 'rl-dummy' of github.com:ultmaster/qlib into rl-dummy
ultmaster Jun 28, 2021
e1b6f31
add Handler Storage
bxdd Jun 28, 2021
90bbf2b
Fix account update bar_count bug
you-n-g Jun 30, 2021
9985bef
update HashingStockStorage
bxdd Jun 29, 2021
8d1b197
update handler_storage test
bxdd Jun 29, 2021
b242d6e
delMiniTimer in haandler storage test
bxdd Jun 29, 2021
bbf5d1b
add file order strategy
you-n-g Jun 30, 2021
24d5a31
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jun 30, 2021
a401f1e
improve the docstring
you-n-g Jun 30, 2021
2b4a493
Order patch
Jul 1, 2021
8b85b9e
optimize performance of resam data in rule_strategy & exchange
bxdd Jul 1, 2021
8dd5788
fix comments & update resam ts_last method
bxdd Jul 1, 2021
ef7fe8a
support parallel HF trading
you-n-g Jul 3, 2021
ecf2f24
fix comments
bxdd Jul 3, 2021
9b74a19
Merge pull request #493 from bxdd/optimize_resam_data
bxdd Jul 3, 2021
50c0e99
fix ffr and order amount
you-n-g Jul 4, 2021
7048bef
fix ffr and order amount
you-n-g Jul 4, 2021
e063d35
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 5, 2021
8264523
Support order dataframe
Jul 6, 2021
cb72857
fix annotation recursive error
you-n-g Jul 6, 2021
bdac9f4
supporting seperated buy and sell price
you-n-g Jul 6, 2021
e214557
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 6, 2021
354f7e6
Constrain TWAP trade step
Jul 6, 2021
03d6fac
fix TWAP strategy
you-n-g Jul 6, 2021
dd8231e
simplify the portfolio-based report
you-n-g Jul 6, 2021
6fd50a5
Supporting skip empty decisions
you-n-g Jul 6, 2021
4e41e9c
simplify the portfolio-based report
you-n-g Jul 6, 2021
e42aa67
Supporting skip empty decisions
you-n-g Jul 6, 2021
d6984a3
fill_placehorder
gandalf-in-web3 Jun 19, 2021
d1b8ed9
fix qrun
gandalf-in-web3 Jun 22, 2021
85c75a6
config_extend
Jun 22, 2021
cbe7c52
high_fre_yaml
wangwenxi-handsome Jun 23, 2021
bd6080b
yaml update
wangwenxi-handsome Jun 23, 2021
4488c3b
code optimization
wangwenxi-handsome Jun 23, 2021
8b28575
fill placehorder dict and list
wangwenxi-handsome Jun 24, 2021
267ee35
fix all example
wangwenxi-handsome Jun 28, 2021
93796bd
add exchange kwargs
wangwenxi-handsome Jun 29, 2021
8c743a4
use init_instance_by_config
wangwenxi-handsome Jul 4, 2021
1fb50d5
Merge branch 'main' into nested_decision_exe
you-n-g Jul 7, 2021
0c946cf
add supporting setting trade unit in exchange
you-n-g Jul 7, 2021
e8f5a1e
black format
you-n-g Jul 7, 2021
5c5379e
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 7, 2021
32ae6e4
fix calculating base_price
you-n-g Jul 8, 2021
eada864
align range limit
you-n-g Jul 8, 2021
17d8b8a
fix calculating base_price
you-n-g Jul 8, 2021
cbd52b7
align range limit
you-n-g Jul 8, 2021
80f5426
update docsting
you-n-g Jul 9, 2021
ece7b66
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 9, 2021
155019b
move the pa sign from last step to first
you-n-g Jul 9, 2021
45bde75
move the pa sign from last step to first
you-n-g Jul 9, 2021
c29e5b2
Fix circular import
Jul 12, 2021
4c4b30e
fix base price and volumn
wangwenxi-handsome Jul 13, 2021
9b38e62
Add more friendly index range by timing
you-n-g Jul 13, 2021
ca14e36
initial account by position
wangwenxi-handsome Jul 13, 2021
0646e53
fix spell error
wangwenxi-handsome Jul 13, 2021
7b9e338
add docs
wangwenxi-handsome Jul 13, 2021
831773a
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 14, 2021
571d27c
exchange support expression buy sell limit
you-n-g Jul 14, 2021
94b4567
refactor index_range to trade_range
you-n-g Jul 15, 2021
870f834
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 15, 2021
d907817
unify variable names
you-n-g Jul 15, 2021
aae4b02
*tuple
wangwenxi-handsome Jul 15, 2021
f295497
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
wangwenxi-handsome Jul 15, 2021
344f4f6
add data calendar API and refine order cal api
you-n-g Jul 16, 2021
5241b2f
Merge branch 'nested_decision_exe' of github.com:microsoft/qlib into …
you-n-g Jul 16, 2021
65b4434
add PandasQuote
wangwenxi-handsome Jul 16, 2021
110141d
add doc
wangwenxi-handsome Jul 16, 2021
567841e
get qlib data in exchange
wangwenxi-handsome Jul 16, 2021
6ad52e8
black and doc
wangwenxi-handsome Jul 16, 2021
2b8d4dc
callable
wangwenxi-handsome Jul 16, 2021
7738f39
filter zero base price
you-n-g Jul 17, 2021
5f50614
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 17, 2021
ed12c7f
add common_infra warning and fix time bug
you-n-g Jul 18, 2021
572181e
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 18, 2021
4a62e02
add get_data_cal_avail_range method
you-n-g Jul 18, 2021
25ff62f
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 18, 2021
92f2891
fix order factor setting issue
you-n-g Jul 19, 2021
62583ea
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 19, 2021
4e862f7
add print cash in verbose mode and code format
you-n-g Jul 20, 2021
9bf8c99
type checking update
Jul 20, 2021
83d4387
pandas_order_indicator
wangwenxi-handsome Jul 21, 2021
10c182e
add order_indicator doc
wangwenxi-handsome Jul 21, 2021
2c8a3de
high_performance_data_structure
wangwenxi-handsome Jul 22, 2021
bbba960
Merge branch 'nested_decision_exe' into nested_decision_exe
you-n-g Jul 23, 2021
d445f28
Merge branch 'main' into nested_decision_exe
you-n-g Jul 23, 2021
0ec6b87
fix little bug
wangwenxi-handsome Jul 23, 2021
301e047
Merge branch 'nested_decision_exe' of https://github.com/wangwenxi-ha…
wangwenxi-handsome Jul 23, 2021
9e6f4ec
Merge pull request #520 from wangwenxi-handsome/nested_decision_exe
you-n-g Jul 23, 2021
a8ea66b
black
wangwenxi-handsome Jul 23, 2021
9d732e9
Update Action
wangwenxi-handsome Jul 23, 2021
6dcbf51
update action
wangwenxi-handsome Jul 24, 2021
4ffb05a
Update Action
wangwenxi-handsome Jul 23, 2021
103d303
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
wangwenxi-handsome Jul 25, 2021
e88c45e
update position
wangwenxi-handsome Jul 25, 2021
bdebe12
support empty benchmark
you-n-g Jul 26, 2021
c202a4b
fix _get_base_vol_pri clip_time_range
wangwenxi-handsome Jul 26, 2021
4924717
fix black
wangwenxi-handsome Jul 26, 2021
fcca242
add cash settlement mechanism
you-n-g Jul 26, 2021
66971d5
fix indicator
wangwenxi-handsome Jul 27, 2021
ba1c575
doc and black for indicator
wangwenxi-handsome Jul 27, 2021
0d41ca2
fix data format bug & twap peeking strategy
you-n-g Jul 27, 2021
0b607da
Merge branch 'nested_decision_exe' of https://github.com/microsoft/ql…
Jul 27, 2021
e817413
Restore examples
Jul 27, 2021
c1992b1
Merge pull request #456 from ultmaster/rl-dummy
you-n-g Jul 27, 2021
ab3c4a2
new twap (more even)
you-n-g Jul 28, 2021
73f5cc0
add suspend check in twap
you-n-g Jul 29, 2021
5c2ddac
volume limit
wangwenxi-handsome Jul 31, 2021
0f2d85d
volume limit update
wangwenxi-handsome Aug 1, 2021
f5db0e1
fix vol limit bug
wangwenxi-handsome Aug 2, 2021
3ff1d91
add __init__
wangwenxi-handsome Aug 2, 2021
8e87950
Print volume limitation log
you-n-g Aug 4, 2021
74e1ee6
update position and negative cash
wangwenxi-handsome Aug 6, 2021
7c85880
add position test
wangwenxi-handsome Aug 8, 2021
05b9fb5
Fix bug when Account.benchmark_config is None
you-n-g Aug 9, 2021
735153a
Cash Update (#559)
wangwenxi-handsome Aug 12, 2021
309dfa3
Add a example to collecting all the decisions
you-n-g Aug 15, 2021
2da6a8c
fix Path re
wangwenxi-handsome Aug 31, 2021
f67b99a
update exchange
wangwenxi-handsome Aug 15, 2021
222c2fd
fix exchange bug
wangwenxi-handsome Aug 15, 2021
8eb7a1f
numpy_order_indicator
wangwenxi-handsome Aug 17, 2021
f7d7f1a
fix nanmean
wangwenxi-handsome Aug 17, 2021
16b9548
get_base_info
wangwenxi-handsome Aug 18, 2021
e134c35
fix index data bug
wangwenxi-handsome Aug 18, 2021
be0d9e6
update freq
wangwenxi-handsome Aug 18, 2021
f111e34
align interface
wangwenxi-handsome Aug 19, 2021
9c326fd
add import order
you-n-g Aug 20, 2021
13a9b7c
type error bug
you-n-g Aug 20, 2021
d9ad8ff
index_data
wangwenxi-handsome Aug 26, 2021
25f54dd
new high freq struc
wangwenxi-handsome Aug 26, 2021
7ee4a20
add lru
wangwenxi-handsome Aug 26, 2021
43a8f50
fix bug
wangwenxi-handsome Aug 27, 2021
d39c8de
draft design
you-n-g Aug 31, 2021
9a74471
Pass basic tests
you-n-g Aug 31, 2021
5f0ee6c
fix bugs
you-n-g Aug 31, 2021
5003e49
fix metric calculation error
you-n-g Sep 1, 2021
9446116
redundant references
wangwenxi-handsome Sep 1, 2021
4da3f3b
broadcast_to and get single data
wangwenxi-handsome Sep 1, 2021
9193805
close and reindex
wangwenxi-handsome Sep 1, 2021
f71b0c1
250s
wangwenxi-handsome Sep 1, 2021
88d2f92
fix sum index data bug
you-n-g Sep 2, 2021
6203e4c
Update the docs of Report
you-n-g Sep 13, 2021
163e3c6
replace multi processing with joblib (#477)
you-n-g Sep 13, 2021
3760a18
Merge nested main (#597)
wangwenxi-handsome Sep 30, 2021
4099050
Merge remote-tracking branch 'origin/main' into nested_decision_exe
you-n-g Sep 30, 2021
48a860c
fix backtest yaml
you-n-g Sep 30, 2021
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions examples/nested_decision_execution/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Nested Decision Execution

This workflow is an example for nested decision execution in backtesting. Qlib supports nested decision execution in backtesting. It means that users can use different strategies to make trade decision in different frequencies.

## Weekly Portfolio Generation and Daily Order Execution

This workflow provides an example that uses a DropoutTopkStrategy (a strategy based on the daily frequency Lightgbm model) in weekly frequency for portfolio generation and uses SBBStrategyEMA (a rule-based strategy that uses EMA for decision-making) to execute orders in daily frequency.

### 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
```

## Daily Portfolio Generation and Minutely Order Execution

This workflow also provides a high-frequency example that uses a DropoutTopkStrategy for portfolio generation in daily frequency and uses SBBStrategyEMA to execute orders in minutely frequency.

### Usage

Start backtesting by running the following command:
```bash
python workflow.py backtest_highfreq
```
232 changes: 232 additions & 0 deletions examples/nested_decision_execution/workflow.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,232 @@
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.


import qlib
import fire
from qlib.config import REG_CN, HIGH_FREQ_CONFIG
from qlib.data import D
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.backtest import collect_data


class NestedDecisionExecutionWorkflow:

market = "csi300"
benchmark = "SH000300"
data_handler_config = {
"start_time": "2008-01-01",
"end_time": "2020-12-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", "2020-12-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_report": True,
"verbose": True,
"indicator_config": {
"show_indicator": True,
},
},
},
"inner_strategy": {
"class": "TWAPStrategy",
"module_path": "qlib.contrib.strategy.rule_strategy",
},
"generate_report": 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_report": True,
"indicator_config": {
"show_indicator": True,
},
},
},
"backtest": {
"start_time": "2020-01-01",
"end_time": "2020-12-31",
"account": 100000000,
"exchange_kwargs": {
"freq": "1min",
"limit_threshold": 0.095,
"deal_price": "close",
"open_cost": 0.0005,
"close_cost": 0.0015,
"min_cost": 5,
},
},
}

def _init_qlib(self):
"""initialize qlib"""
# provider_uri_day = "/data/stock_data/huaxia/qlib"
# provider_uri_1min = "/data2/stock_data/huaxia_1min_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}
wangwenxi-handsome marked this conversation as resolved.
Show resolved Hide resolved
client_config = {
"calendar_provider": {
"class": "LocalCalendarProvider",
"module_path": "qlib.data.data",
"kwargs": {
"backend": {
"class": "FileCalendarStorage",
"module_path": "qlib.data.storage.file_storage",
"kwargs": {"provider_uri_map": provider_uri_map},
}
},
},
"feature_provider": {
"class": "LocalFeatureProvider",
"module_path": "qlib.data.data",
"kwargs": {
"backend": {
"class": "FileFeatureStorage",
"module_path": "qlib.data.storage.file_storage",
"kwargs": {"provider_uri_map": provider_uri_map},
}
},
},
}
qlib.init(provider_uri=provider_uri_day, **client_config, redis_port=-1)
wangwenxi-handsome marked this conversation as resolved.
Show resolved Hide resolved

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):
wangwenxi-handsome marked this conversation as resolved.
Show resolved Hide resolved
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
self.port_analysis_config["backtest"]["benchmark"] = D.list_instruments(
wangwenxi-handsome marked this conversation as resolved.
Show resolved Hide resolved
instruments=D.instruments(market=self.market), as_list=True
)
with R.start(experiment_name="backtest"):

recorder = R.get_recorder()
par = PortAnaRecord(
recorder,
self.port_analysis_config,
risk_analysis_freq=["day", "30min", "5min"],
indicator_analysis_freq=["day", "30min", "5min"],
indicator_analysis_method="value_weighted",
)
par.generate()

# report_normal_df = recorder.load_object("portfolio_analysis/report_normal_1day.pkl")
# from qlib.contrib.report import analysis_position
# analysis_position.report_graph(report_normal_df)

def collect_data(self):
you-n-g marked this conversation as resolved.
Show resolved Hide resolved
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"]
backtest_config["benchmark"] = D.list_instruments(instruments=D.instruments(market=self.market), as_list=True)
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(NestedDecisionExecutionWorkflow)
1 change: 0 additions & 1 deletion examples/rolling_process_data/workflow.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ class RollingDataWorkflow:

def _init_qlib(self):
"""initialize qlib"""
# use yahoo_cn_1min data
provider_uri = "~/.qlib/qlib_data/cn_data" # target_dir
GetData().qlib_data(target_dir=provider_uri, region=REG_CN, exists_skip=True)
qlib.init(provider_uri=provider_uri, region=REG_CN)
Expand Down
39 changes: 26 additions & 13 deletions examples/workflow_by_code.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@
"from qlib.config import REG_CN\n",
"from qlib.contrib.model.gbdt import LGBModel\n",
"from qlib.contrib.data.handler import Alpha158\n",
"from qlib.contrib.strategy.strategy import TopkDropoutStrategy\n",
"from qlib.contrib.evaluate import (\n",
" backtest as normal_backtest,\n",
" risk_analysis,\n",
Expand Down Expand Up @@ -197,27 +196,40 @@
"# prediction, backtest & analysis\n",
"###################################\n",
"port_analysis_config = {\n",
" \"executor\": {\n",
" \"class\": \"SimulatorExecutor\",\n",
" \"module_path\": \"qlib.backtest.executor\",\n",
" \"kwargs\": {\n",
" \"time_per_step\": \"day\",\n",
" \"generate_report\": True,\n",
" },\n",
" },\n",
" \"strategy\": {\n",
" \"class\": \"TopkDropoutStrategy\",\n",
" \"module_path\": \"qlib.contrib.strategy.strategy\",\n",
" \"module_path\": \"qlib.contrib.strategy.model_strategy\",\n",
" \"kwargs\": {\n",
" \"model\": model,\n",
" \"dataset\": dataset,\n",
" \"topk\": 50,\n",
" \"n_drop\": 5,\n",
" },\n",
" },\n",
" \"backtest\": {\n",
" \"verbose\": False,\n",
" \"limit_threshold\": 0.095,\n",
" \"start_time\": \"2017-01-01\",\n",
" \"end_time\": \"2020-08-01\",\n",
" \"account\": 100000000,\n",
" \"benchmark\": benchmark,\n",
" \"deal_price\": \"close\",\n",
" \"open_cost\": 0.0005,\n",
" \"close_cost\": 0.0015,\n",
" \"min_cost\": 5,\n",
" \"exchange_kwargs\": {\n",
" \"freq\": \"day\",\n",
" \"limit_threshold\": 0.095,\n",
" \"deal_price\": \"close\",\n",
" \"open_cost\": 0.0005,\n",
" \"close_cost\": 0.0015,\n",
" \"min_cost\": 5,\n",
" },\n",
" },\n",
"}\n",
"\n",
"\n",
"# backtest and analysis\n",
"with R.start(experiment_name=\"backtest_analysis\"):\n",
" recorder = R.get_recorder(rid, experiment_name=\"train_model\")\n",
Expand All @@ -230,7 +242,7 @@
" sr.generate()\n",
"\n",
" # backtest & analysis\n",
" par = PortAnaRecord(recorder, port_analysis_config)\n",
" par = PortAnaRecord(recorder, port_analysis_config, \"day\")\n",
" par.generate()\n"
]
},
Expand All @@ -250,11 +262,12 @@
"from qlib.contrib.report import analysis_model, analysis_position\n",
"from qlib.data import D\n",
"recorder = R.get_recorder(ba_rid, experiment_name=\"backtest_analysis\")\n",
"print(recorder)\n",
"pred_df = recorder.load_object(\"pred.pkl\")\n",
"pred_df_dates = pred_df.index.get_level_values(level='datetime')\n",
"report_normal_df = recorder.load_object(\"portfolio_analysis/report_normal.pkl\")\n",
"positions = recorder.load_object(\"portfolio_analysis/positions_normal.pkl\")\n",
"analysis_df = recorder.load_object(\"portfolio_analysis/port_analysis.pkl\")"
"report_normal_df = recorder.load_object(\"portfolio_analysis/report_normal_1day.pkl\")\n",
"positions = recorder.load_object(\"portfolio_analysis/positions_normal_1day.pkl\")\n",
"analysis_df = recorder.load_object(\"portfolio_analysis/port_analysis_1day.pkl\")"
]
},
{
Expand Down
Loading