forked from QuantConnect/lean-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backtest.py
408 lines (322 loc) · 16 KB
/
backtest.py
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
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect Corporation.
#
# 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.
from pathlib import Path
from typing import List, Optional, Tuple
from click import command, option, argument, Choice
from lean.click import LeanCommand, PathParameter
from lean.constants import DEFAULT_ENGINE_IMAGE, LEAN_ROOT_PATH
from lean.container import container, Logger
from lean.models.api import QCMinimalOrganization
from lean.models.utils import DebuggingMethod
from lean.models.logger import Option
from lean.models.data_providers import QuantConnectDataProvider, all_data_providers
from lean.models.addon_modules import all_addon_modules
from lean.models.addon_modules.addon_module import AddonModule
# The _migrate_* methods automatically update launch configurations for a given debugging method.
#
# Occasionally we make changes which require updated launch configurations.
# Projects which are created after these update have the correct configuration already,
# but projects created before that need changes.
#
# These methods checks if the project has outdated configurations, and if so, update them to keep it working.
def _migrate_python_pycharm(logger: Logger, project_dir: Path) -> None:
from os import path
from click import Abort
workspace_xml_path = project_dir / ".idea" / "workspace.xml"
if not workspace_xml_path.is_file():
return
xml_manager = container.xml_manager
current_content = xml_manager.parse(workspace_xml_path.read_text(encoding="utf-8"))
config = current_content.find('.//configuration[@name="Debug with Lean CLI"]')
if config is None:
return
path_mappings = config.find('.//PathMappingSettings/option[@name="pathMappings"]/list')
if path_mappings is None:
return
made_changes = False
has_library_mapping = False
library_dir = container.lean_config_manager.get_cli_root_directory() / "Library"
if library_dir.is_dir():
library_dir = f"$PROJECT_DIR$/{path.relpath(library_dir, project_dir)}".replace("\\", "/")
else:
library_dir = None
for mapping in path_mappings.findall(".//mapping"):
if mapping.get("local-root") == "$PROJECT_DIR$" and mapping.get("remote-root") == LEAN_ROOT_PATH:
mapping.set("remote-root", "/LeanCLI")
made_changes = True
if library_dir is not None \
and mapping.get("local-root") == library_dir \
and mapping.get("remote-root") == "/Library":
has_library_mapping = True
if library_dir is not None and not has_library_mapping:
library_mapping = xml_manager.parse("<mapping/>")
library_mapping.set("local-root", library_dir)
library_mapping.set("remote-root", "/Library")
path_mappings.append(library_mapping)
made_changes = True
if made_changes:
workspace_xml_path.write_text(xml_manager.to_string(current_content), encoding="utf-8")
logger = container.logger
logger.warn("Your run configuration has been updated to work with the latest version of LEAN")
logger.warn("Please restart the debugger in PyCharm and run this command again")
raise Abort()
def _migrate_python_vscode(project_dir: Path) -> None:
from json import dumps, loads
launch_json_path = project_dir / ".vscode" / "launch.json"
if not launch_json_path.is_file():
return
current_content = loads(launch_json_path.read_text(encoding="utf-8"))
if "configurations" not in current_content or not isinstance(current_content["configurations"], list):
return
config = next((c for c in current_content["configurations"] if c["name"] == "Debug with Lean CLI"), None)
if config is None:
return
made_changes = False
has_library_mapping = False
library_dir = container.lean_config_manager.get_cli_root_directory() / "Library"
if not library_dir.is_dir():
library_dir = None
for mapping in config["pathMappings"]:
if mapping["localRoot"] == "${workspaceFolder}" and mapping["remoteRoot"] == LEAN_ROOT_PATH:
mapping["remoteRoot"] = "/LeanCLI"
made_changes = True
if library_dir is not None and mapping["localRoot"] == str(library_dir) and mapping["remoteRoot"] == "/Library":
has_library_mapping = True
if library_dir is not None and not has_library_mapping:
config["pathMappings"].append({
"localRoot": str(library_dir),
"remoteRoot": "/Library"
})
made_changes = True
if made_changes:
launch_json_path.write_text(dumps(current_content, indent=4), encoding="utf-8")
def _migrate_csharp_rider(logger: Logger, project_dir: Path) -> None:
from click import Abort
made_changes = False
xml_manager = container.xml_manager
for dir_name in [f".idea.{project_dir.stem}", f".idea.{project_dir.stem}.dir"]:
workspace_xml_path = project_dir / ".idea" / dir_name / ".idea" / "workspace.xml"
if not workspace_xml_path.is_file():
continue
current_content = xml_manager.parse(workspace_xml_path.read_text(encoding="utf-8"))
run_manager = current_content.find(".//component[@name='RunManager']")
if run_manager is None:
continue
config = run_manager.find(".//configuration[@name='Debug with Lean CLI']")
if config is None:
continue
run_manager.remove(config)
workspace_xml_path.write_text(xml_manager.to_string(current_content), encoding="utf-8")
made_changes = True
if made_changes:
container.project_manager.generate_rider_config()
logger.warn("Your run configuration has been updated to work with the .NET 5 version of LEAN")
logger.warn("Please restart Rider and start debugging again")
logger.warn(
"See https://www.lean.io/docs/v2/lean-cli/backtesting/debugging#05-C-and-Rider for the updated instructions")
raise Abort()
def _migrate_csharp_vscode(project_dir: Path) -> None:
from json import dumps, loads
launch_json_path = project_dir / ".vscode" / "launch.json"
if not launch_json_path.is_file():
return
current_content = loads(launch_json_path.read_text(encoding="utf-8"))
if "configurations" not in current_content or not isinstance(current_content["configurations"], list):
return
config = next((c for c in current_content["configurations"] if c["name"] == "Debug with Lean CLI"), None)
if config is None:
return
if config["type"] != "mono" and config["processId"] != "${command:pickRemoteProcess}":
return
config.pop("address", None)
config.pop("port", None)
config["type"] = "coreclr"
config["processId"] = "1"
config["pipeTransport"] = {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "docker",
"pipeArgs": ["exec", "-i", "lean_cli_vsdbg"],
"debuggerPath": "/root/vsdbg/vsdbg",
"quoteArgs": False
}
config["logging"] = {
"moduleLoad": False
}
launch_json_path.write_text(dumps(current_content, indent=4), encoding="utf-8")
def _migrate_csharp_csproj(project_dir: Path) -> None:
csproj_path = next((f for f in project_dir.rglob("*.csproj")), None)
if csproj_path is None:
return
xml_manager = container.xml_manager
current_content = xml_manager.parse(csproj_path.read_text(encoding="utf-8"))
if current_content.find(".//PropertyGroup/DefaultItemExcludes") is not None:
return
property_group = current_content.find(".//PropertyGroup")
if property_group is None:
property_group = xml_manager.parse("<PropertyGroup/>")
current_content.append(property_group)
default_item_excludes = xml_manager.parse(
"<DefaultItemExcludes>$(DefaultItemExcludes);backtests/*/code/**;live/*/code/**;optimizations/*/code/**</DefaultItemExcludes>")
property_group.append(default_item_excludes)
csproj_path.write_text(xml_manager.to_string(current_content), encoding="utf-8")
def _select_organization() -> QCMinimalOrganization:
"""Asks the user for the organization that should be charged when downloading data.
:return: the selected organization
"""
api_client = container.api_client
organizations = api_client.organizations.get_all()
options = [Option(id=organization, label=organization.name) for organization in organizations]
logger = container.logger
return logger.prompt_list("Select the organization to purchase and download data with", options)
@command(cls=LeanCommand, requires_lean_config=True, requires_docker=True)
@argument("project", type=PathParameter(exists=True, file_okay=True, dir_okay=True))
@option("--output",
type=PathParameter(exists=False, file_okay=False, dir_okay=True),
help="Directory to store results in (defaults to PROJECT/backtests/TIMESTAMP)")
@option("--detach", "-d",
is_flag=True,
default=False,
help="Run the backtest in a detached Docker container and return immediately")
@option("--debug",
type=Choice(["pycharm", "ptvsd", "vsdbg", "rider"], case_sensitive=False),
help="Enable a certain debugging method (see --help for more information)")
@option("--data-provider",
type=Choice([dp.get_name() for dp in all_data_providers], case_sensitive=False),
help="Update the Lean configuration file to retrieve data from the given provider")
@option("--download-data",
is_flag=True,
default=False,
help="Update the Lean configuration file to download data from the QuantConnect API, alias for --data-provider QuantConnect")
@option("--data-purchase-limit",
type=int,
help="The maximum amount of QCC to spend on downloading data during the backtest when using QuantConnect as data provider")
@option("--release",
is_flag=True,
default=False,
help="Compile C# projects in release configuration instead of debug")
@option("--image",
type=str,
help=f"The LEAN engine image to use (defaults to {DEFAULT_ENGINE_IMAGE})")
@option("--python-venv",
type=str,
help=f"The path of the python virtual environment to be used")
@option("--update",
is_flag=True,
default=False,
help="Pull the LEAN engine image before running the backtest")
@option("--backtest-name",
type=str,
help="Backtest name")
@option("--addon-module",
type=str,
multiple=True,
hidden=True)
@option("--extra-config",
type=(str, str),
multiple=True,
hidden=True)
def backtest(project: Path,
output: Optional[Path],
detach: bool,
debug: Optional[str],
data_provider: Optional[str],
download_data: bool,
data_purchase_limit: Optional[int],
release: bool,
image: Optional[str],
python_venv: Optional[str],
update: bool,
backtest_name: str,
addon_module: Optional[List[str]],
extra_config: Optional[Tuple[str, str]]) -> None:
"""Backtest a project locally using Docker.
\b
If PROJECT is a directory, the algorithm in the main.py or Main.cs file inside it will be executed.
If PROJECT is a file, the algorithm in the specified file will be executed.
\b
Go to the following url to learn how to debug backtests locally using the Lean CLI:
https://www.lean.io/docs/v2/lean-cli/backtesting/debugging
By default the official LEAN engine image is used.
You can override this using the --image option.
Alternatively you can set the default engine image for all commands using `lean config set engine-image <image>`.
"""
from datetime import datetime
addon_modules_to_build: List[AddonModule] = []
logger = container.logger
project_manager = container.project_manager
algorithm_file = project_manager.find_algorithm_file(Path(project))
lean_config_manager = container.lean_config_manager
if output is None:
output = algorithm_file.parent / "backtests" / datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
debugging_method = None
if debug == "pycharm":
debugging_method = DebuggingMethod.PyCharm
_migrate_python_pycharm(logger, algorithm_file.parent)
elif debug == "ptvsd":
debugging_method = DebuggingMethod.PTVSD
_migrate_python_vscode(algorithm_file.parent)
elif debug == "vsdbg":
debugging_method = DebuggingMethod.VSDBG
_migrate_csharp_vscode(algorithm_file.parent)
elif debug == "rider":
debugging_method = DebuggingMethod.Rider
_migrate_csharp_rider(logger, algorithm_file.parent)
if debugging_method is not None and detach:
raise RuntimeError("Running a debugging session in a detached container is not supported")
if algorithm_file.name.endswith(".cs"):
_migrate_csharp_csproj(algorithm_file.parent)
lean_config = lean_config_manager.get_complete_lean_config("backtesting", algorithm_file, debugging_method)
if download_data:
data_provider = QuantConnectDataProvider.get_name()
if data_provider is not None:
data_provider = next(dp for dp in all_data_providers if dp.get_name() == data_provider)
data_provider.build(lean_config, logger).configure(lean_config, "backtesting")
lean_config_manager.configure_data_purchase_limit(lean_config, data_purchase_limit)
cli_config_manager = container.cli_config_manager
project_config_manager = container.project_config_manager
project_config = project_config_manager.get_project_config(algorithm_file.parent)
engine_image = cli_config_manager.get_engine_image(image or project_config.get("engine-image", None))
if str(engine_image) != DEFAULT_ENGINE_IMAGE:
logger.warn(f'A custom engine image: "{engine_image}" is being used!')
container.update_manager.pull_docker_image_if_necessary(engine_image, update)
if not output.exists():
output.mkdir(parents=True)
output_config_manager = container.output_config_manager
lean_config["algorithm-id"] = str(output_config_manager.get_backtest_id(output))
# Set backtest name
if backtest_name is not None and backtest_name != "":
lean_config["backtest-name"] = backtest_name
# Set extra config
for key, value in extra_config:
lean_config[key] = value
if python_venv is not None and python_venv != "":
lean_config["python-venv"] = f'{"/" if python_venv[0] != "/" else ""}{python_venv}'
for given_module in addon_module:
found_module = next((module for module in all_addon_modules if module.get_name().lower() == given_module.lower()), None)
if found_module:
addon_modules_to_build.append(found_module)
else:
logger.error(f"Addon module '{given_module}' not found")
# build and configure addon modules
for module in addon_modules_to_build:
module.build(lean_config, logger).configure(lean_config, "backtesting")
module.ensure_module_installed(container.organization_manager.try_get_working_organization_id())
lean_runner = container.lean_runner
lean_runner.run_lean(lean_config,
"backtesting",
algorithm_file,
output,
engine_image,
debugging_method,
release,
detach)