-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path__main__.py
More file actions
326 lines (263 loc) · 11.2 KB
/
Copy path__main__.py
File metadata and controls
326 lines (263 loc) · 11.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import errno
import os
import shutil
from importlib import import_module
import six
import click
import ruamel.yaml as yaml
from .utils.click_helper import Date
from .utils.config import parse_config, get_mod_config_path, load_config, dump_config
@click.group()
@click.option('-v', '--verbose', count=True)
@click.pass_context
def cli(ctx, verbose):
ctx.obj["VERBOSE"] = verbose
def entry_point():
from rqalpha.mod import SYSTEM_MOD_LIST
from rqalpha.utils.package_helper import import_mod
mod_config_path = get_mod_config_path()
mod_config = load_config(mod_config_path, loader=yaml.RoundTripLoader)
for mod_name, config in six.iteritems(mod_config['mod']):
lib_name = "rqalpha_mod_{}".format(mod_name)
if not config['enabled']:
continue
if mod_name in SYSTEM_MOD_LIST:
# inject system mod
import_mod("rqalpha.mod." + lib_name)
else:
# inject third part mod
import_mod(lib_name)
# 原本是注入系统中所有的Mod对应的命令,现在修改为只注入用户启动的Mod对应的命令
# from . import mod
# from pkgutil import iter_modules
# from rqalpha.utils.package_helper import import_mod
# # inject system mod
# for package_name in mod.SYSTEM_MOD_LIST:
# import_mod("rqalpha.mod.rqalpha_mod_" + package_name)
# # inject user mod
# for package in iter_modules():
# if "rqalpha_mod_" in package[1]:
# import_mod(package[1])
cli(obj={})
@cli.command()
@click.option('-d', '--data-bundle-path', default=os.path.expanduser("~/.rqalpha"), type=click.Path(file_okay=False))
@click.option('--locale', 'locale', type=click.STRING, default="zh_Hans_CN")
def update_bundle(data_bundle_path, locale):
"""
Sync Data Bundle
"""
from . import main
main.update_bundle(data_bundle_path, locale)
@cli.command()
@click.help_option('-h', '--help')
# -- Base Configuration
@click.option('-d', '--data-bundle-path', 'base__data_bundle_path', type=click.Path(exists=True))
@click.option('-f', '--strategy-file', 'base__strategy_file', type=click.Path(exists=True))
@click.option('-s', '--start-date', 'base__start_date', type=Date())
@click.option('-e', '--end-date', 'base__end_date', type=Date())
@click.option('-sc', '--stock-starting-cash', 'base__stock_starting_cash', type=click.FLOAT)
@click.option('-fc', '--future-starting-cash', 'base__future_starting_cash', type=click.FLOAT)
@click.option('-bm', '--benchmark', 'base__benchmark', type=click.STRING, default=None)
@click.option('-mm', '--margin-multiplier', 'base__margin_multiplier', type=click.FLOAT)
@click.option('-st', '--security', 'base__securities', multiple=True, type=click.Choice(['stock', 'future']))
@click.option('-fq', '--frequency', 'base__frequency', type=click.Choice(['1d', '1m']))
@click.option('-rt', '--run-type', 'base__run_type', type=click.Choice(['b', 'p']), default="b")
@click.option('--resume', 'base__resume_mode', is_flag=True)
@click.option('--handle-split/--not-handle-split', 'base__handle_split', default=None, help="handle split")
# -- Extra Configuration
@click.option('-l', '--log-level', 'extra__log_level', type=click.Choice(['verbose', 'debug', 'info', 'error', 'none']))
@click.option('--locale', 'extra__locale', type=click.Choice(['cn', 'en']), default="cn")
@click.option('--disable-user-system-log', 'extra__user_system_log_disabled', is_flag=True, help='disable user system log')
@click.option('--extra-vars', 'extra__context_vars', type=click.STRING, help="override context vars")
@click.option("--enable-profiler", "extra__enable_profiler", is_flag=True, help="add line profiler to profile your strategy")
@click.option('--config', 'config_path', type=click.STRING, help="config file path")
# -- Mod Configuration
@click.option('-mc', '--mod-config', 'mod_configs', nargs=2, multiple=True, type=click.STRING, help="mod extra config")
# -- DEPRECATED ARGS && WILL BE REMOVED AFTER VERSION 3.0.0
@click.option('-i', '--init-cash', 'base__stock_starting_cash', type=click.FLOAT, help="[Deprecated]")
@click.option('-k', '--kind', 'base__securities', type=click.Choice(['stock', 'future', 'stock_future']), help="[Deprecated]")
@click.option('--strategy-type', 'base__securities', type=click.Choice(['stock', 'future']), help="[Deprecated]")
def run(**kwargs):
"""
Start to run a strategy
"""
config_path = kwargs.get('config_path', None)
if config_path is not None:
config_path = os.path.abspath(config_path)
from . import main
main.run(parse_config(kwargs, config_path))
@cli.command()
@click.option('-d', '--directory', default="./", type=click.Path(), required=True)
def examples(directory):
"""
Generate example strategies to target folder
"""
source_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "examples")
try:
shutil.copytree(source_dir, os.path.join(directory, "examples"))
except OSError as e:
if e.errno == errno.EEXIST:
print("Folder examples is exists.")
@cli.command()
@click.option('-v', '--verbose', is_flag=True)
def version(**kwargs):
"""
Output Version Info
"""
from rqalpha import version_info
print("Current Version: ", version_info)
@cli.command()
@click.option('-d', '--directory', default="./", type=click.Path(), required=True)
def generate_config(directory):
"""
Generate default config file
"""
default_config = os.path.join(os.path.dirname(os.path.realpath(__file__)), "default_config.yml")
target_config_path = os.path.abspath(os.path.join(directory, 'config.yml'))
shutil.copy(default_config, target_config_path)
print("Config file has been generated in", target_config_path)
# For Mod Cli
@cli.command(context_settings=dict(
ignore_unknown_options=True,
))
@click.help_option('-h', '--help')
@click.argument('cmd', nargs=1, type=click.Choice(['list', 'enable', 'disable', 'install', 'uninstall']))
@click.argument('params', nargs=-1)
def mod(cmd, params):
"""
Mod management command
rqalpha mod list \n
rqalpha mod install xxx \n
rqalpha mod uninstall xxx \n
rqalpha mod enable xxx \n
rqalpha mod disable xxx \n
"""
def list(params):
"""
List all mod configuration
"""
from colorama import init, Fore
from tabulate import tabulate
init()
mod_config_path = get_mod_config_path(generate=True)
mod_config = load_config(mod_config_path, loader=yaml.RoundTripLoader)
table = []
for mod_name, mod in six.iteritems(mod_config['mod']):
table.append([
Fore.RESET + mod_name,
Fore.GREEN + "enabled" + Fore.RESET if mod['enabled'] else Fore.RED + "disabled" + Fore.RESET
])
headers = [
Fore.CYAN + "name",
Fore.CYAN + "status" + Fore.RESET
]
print(tabulate(table, headers=headers, tablefmt="psql"))
print(Fore.LIGHTYELLOW_EX + "You can use `rqalpha mod list/install/uninstall/enable/disable` to manage your mods")
def install(params):
"""
Install third-party Mod
"""
from pip import main as pip_main
from pip.commands.install import InstallCommand
params = [param for param in params]
options, mod_list = InstallCommand().parse_args(params)
params = ["install"] + params
for mod_name in mod_list:
mod_name_index = params.index(mod_name)
if mod_name.startswith("rqalpha_mod_sys_"):
print('System Mod can not be installed or uninstalled')
return
if "rqalpha_mod_" in mod_name:
lib_name = mod_name
mod_name = lib_name.replace("rqalpha_mod_", "")
else:
lib_name = "rqalpha_mod_" + mod_name
params[mod_name_index] = lib_name
# Install Mod
pip_main(params)
# Export config
mod_config_path = get_mod_config_path(generate=True)
mod_config = load_config(mod_config_path, loader=yaml.RoundTripLoader)
for mod_name in mod_list:
mod_config['mod'][mod_name] = {}
mod_config['mod'][mod_name]['enabled'] = False
dump_config(mod_config_path, mod_config)
list({})
def uninstall(params):
"""
Uninstall third-party Mod
"""
from pip import main as pip_main
from pip.commands.uninstall import UninstallCommand
params = [param for param in params]
options, mod_list = UninstallCommand().parse_args(params)
params = ["uninstall"] + params
for mod_name in mod_list:
mod_name_index = params.index(mod_name)
if mod_name.startswith("rqalpha_mod_sys_"):
print('System Mod can not be installed or uninstalled')
return
if "rqalpha_mod_" in mod_name:
lib_name = mod_name
else:
lib_name = "rqalpha_mod_" + mod_name
params[mod_name_index] = lib_name
# Uninstall Mod
pip_main(params)
# Remove Mod Config
mod_config_path = get_mod_config_path(generate=True)
mod_config = load_config(mod_config_path, loader=yaml.RoundTripLoader)
for mod_name in mod_list:
if "rqalpha_mod_" in mod_name:
mod_name = mod_name.replace("rqalpha_mod_", "")
del mod_config['mod'][mod_name]
dump_config(mod_config_path, mod_config)
list({})
def enable(params):
"""
enable mod
"""
mod_name = params[0]
if "rqalpha_mod_" in mod_name:
mod_name = mod_name.replace("rqalpha_mod_", "")
# check whether is installed
module_name = "rqalpha_mod_" + mod_name
try:
import_module(module_name)
except ImportError:
install([module_name])
mod_config_path = get_mod_config_path(generate=True)
mod_config = load_config(mod_config_path, loader=yaml.RoundTripLoader)
mod_config['mod'][mod_name]['enabled'] = True
dump_config(mod_config_path, mod_config)
list({})
def disable(params):
"""
disable mod
"""
mod_name = params[0]
if "rqalpha_mod_" in mod_name:
mod_name = mod_name.replace("rqalpha_mod_", "")
mod_config_path = get_mod_config_path(generate=True)
mod_config = load_config(mod_config_path, loader=yaml.RoundTripLoader)
mod_config['mod'][mod_name]['enabled'] = False
dump_config(mod_config_path, mod_config)
list({})
locals()[cmd](params)
if __name__ == '__main__':
entry_point()