-
Notifications
You must be signed in to change notification settings - Fork 100
/
create_project.py
473 lines (433 loc) · 17.4 KB
/
create_project.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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
# 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 click import Choice, option, argument
from lean.click import LeanCommand
from lean.commands import lean
from lean.container import container
from lean.models.api import QCLanguage
from lean.models.errors import MoreInfoError
from lean.components.util.name_extraction import convert_to_class_name
from lean.components import reserved_names
DEFAULT_PYTHON_MAIN = '''
# region imports
from AlgorithmImports import *
# endregion
class $CLASS_NAME$(QCAlgorithm):
def initialize(self):
# Locally Lean installs free sample data, to download more data please visit https://www.quantconnect.com/docs/v2/lean-cli/datasets/downloading-data
self.set_start_date(2013, 10, 7) # Set Start Date
self.set_end_date(2013, 10, 11) # Set End Date
self.set_cash(100000) # Set Strategy Cash
self.add_equity("SPY", Resolution.MINUTE)
def on_data(self, data: Slice):
"""on_data event is the primary entry point for your algorithm. Each new data point will be pumped in here.
Arguments:
data: Slice object keyed by symbol containing the stock data
"""
if not self.portfolio.invested:
self.set_holdings("SPY", 1)
self.debug("Purchased Stock")
'''.strip() + "\n"
LIBRARY_PYTHON_MAIN = '''
#region imports
from AlgorithmImports import *
#endregion
### Library classes are snippets of code/classes you can reuse between projects. They are
### added to projects on compile.
###
### To import this class use the following import with your values subbed in for the {} sections:
### from {libraryProjectName} import Library
###
### Example using your newly imported library from 'Library.py' like so:
###
### from $PROJECT_NAME$ import Library
### x = Library.add(1,1)
### print(x)
###
def add(a: int, b: int):
return a + b
'''.strip() + "\n"
DEFAULT_PYTHON_NOTEBOOK = """
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![QuantConnect Logo](https://cdn.quantconnect.com/web/i/icon.png)\\n",
"<hr>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# QuantBook Analysis Tool \\n",
"# For more information see [https://www.quantconnect.com/docs/v2/our-platform/research/getting-started]\\n",
"qb = QuantBook()\\n",
"spy = qb.add_equity(\\"SPY\\")\\n",
"# Locally Lean installs free sample data, to download more data please visit https://www.quantconnect.com/docs/v2/lean-cli/datasets/downloading-data \\n",
"qb.set_start_date(2013, 10, 11)\\n",
"history = qb.history(qb.securities.keys(), 360, Resolution.DAILY)\\n",
"\\n",
"# Indicator Analysis\\n",
"bbdf = qb.indicator(BollingerBands(30, 2), spy.symbol, 360, Resolution.DAILY)\\n",
"bbdf.drop('standarddeviation', axis=1).plot()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
""".strip() + "\n"
DEFAULT_CSHARP_MAIN = """
#region imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Drawing;
using QuantConnect;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Portfolio.SignalExports;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Api;
using QuantConnect.Parameters;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Configuration;
using QuantConnect.Util;
using QuantConnect.Interfaces;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Custom.IconicTypes;
using QuantConnect.DataSource;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Data.Shortable;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.OptionExercise;
using QuantConnect.Orders.Slippage;
using QuantConnect.Orders.TimeInForces;
using QuantConnect.Python;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Positions;
using QuantConnect.Securities.Forex;
using QuantConnect.Securities.Crypto;
using QuantConnect.Securities.CryptoFuture;
using QuantConnect.Securities.Interfaces;
using QuantConnect.Securities.Volatility;
using QuantConnect.Storage;
using QuantConnect.Statistics;
using QCAlgorithmFramework = QuantConnect.Algorithm.QCAlgorithm;
using QCAlgorithmFrameworkBridge = QuantConnect.Algorithm.QCAlgorithm;
#endregion
namespace QuantConnect.Algorithm.CSharp
{
public class $CLASS_NAME$ : QCAlgorithm
{
public override void Initialize()
{
// Locally Lean installs free sample data, to download more data please visit https://www.quantconnect.com/docs/v2/lean-cli/datasets/downloading-data
SetStartDate(2013, 10, 7); // Set Start Date
SetEndDate(2013, 10, 11); // Set Start Date
SetCash(100000); //Set Strategy Cash
AddEquity("SPY", Resolution.Minute);
}
/// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.
/// Slice object keyed by symbol containing the stock data
public override void OnData(Slice data)
{
if (!Portfolio.Invested)
{
SetHoldings("SPY", 1);
Debug("Purchased Stock");
}
}
}
}
""".strip() + "\n"
LIBRARY_CSHARP_MAIN = """
#region imports
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Drawing;
using QuantConnect;
using QuantConnect.Algorithm.Framework;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Portfolio.SignalExports;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Api;
using QuantConnect.Parameters;
using QuantConnect.Benchmarks;
using QuantConnect.Brokerages;
using QuantConnect.Configuration;
using QuantConnect.Util;
using QuantConnect.Interfaces;
using QuantConnect.Algorithm;
using QuantConnect.Indicators;
using QuantConnect.Data;
using QuantConnect.Data.Auxiliary;
using QuantConnect.Data.Consolidators;
using QuantConnect.Data.Custom;
using QuantConnect.Data.Custom.IconicTypes;
using QuantConnect.DataSource;
using QuantConnect.Data.Fundamental;
using QuantConnect.Data.Market;
using QuantConnect.Data.Shortable;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Notifications;
using QuantConnect.Orders;
using QuantConnect.Orders.Fees;
using QuantConnect.Orders.Fills;
using QuantConnect.Orders.OptionExercise;
using QuantConnect.Orders.Slippage;
using QuantConnect.Orders.TimeInForces;
using QuantConnect.Python;
using QuantConnect.Scheduling;
using QuantConnect.Securities;
using QuantConnect.Securities.Equity;
using QuantConnect.Securities.Future;
using QuantConnect.Securities.Option;
using QuantConnect.Securities.Positions;
using QuantConnect.Securities.Forex;
using QuantConnect.Securities.Crypto;
using QuantConnect.Securities.CryptoFuture;
using QuantConnect.Securities.Interfaces;
using QuantConnect.Securities.Volatility;
using QuantConnect.Storage;
using QuantConnect.Statistics;
using QCAlgorithmFramework = QuantConnect.Algorithm.QCAlgorithm;
using QCAlgorithmFrameworkBridge = QuantConnect.Algorithm.QCAlgorithm;
#endregion
namespace QuantConnect
{
/// <summary>
/// Template Library Class
///
/// Library classes are snippets of code you can reuse between projects. They are added to projects on compile. This can be useful for reusing
/// indicators, math components, risk modules etc. If you use a custom namespace make sure you add the correct using statement to the
/// algorithm.
/// </summary>
public static class $CLASS_NAME$
{
/*
* To use this library; add its namespace at the top of the page:
* using QuantConnect
*
* Then use the static class:
* var x = $CLASS_NAME$.Add(1, 5);
* Console.Out.WriteLine(x);
*/
public static int Add(int a, int b)
{
return a + b;
}
public static int Subtract(int a, int b)
{
return a - b;
}
public static int Divide(int a, int b){
return a / b;
}
}
}
""".strip() + "\n"
DEFAULT_CSHARP_NOTEBOOK = """
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![QuantConnect Logo](https://cdn.quantconnect.com/web/i/icon.png)\\n",
"<hr>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"// We need to load assemblies at the start in their own cell\\n",
"#load \\"../Initialize.csx\\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"// QuantBook C# Research Environment\\n",
"// For more information see https://www.quantconnect.com/docs/v2/our-platform/research/getting-started\\n",
"#load \\"../QuantConnect.csx\\"\\n",
"\\n",
"using QuantConnect;\\n",
"using QuantConnect.Data;\\n",
"using QuantConnect.Research;\\n",
"using QuantConnect.Algorithm;\\n",
"\\n",
"var qb = new QuantBook();\\n",
"// Locally Lean installs free sample data, to download more data please visit https://www.quantconnect.com/docs/v2/lean-cli/datasets/downloading-data \\n",
"qb.SetStartDate(2013, 10, 11);\\n",
"var spy = qb.AddEquity(\\"SPY\\");\\n",
"var history = qb.History(qb.Securities.Keys, 360, Resolution.Daily);"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"foreach (var slice in history.Take(5)) {\\n",
" Console.WriteLine(slice.Bars[spy.Symbol].ToString());\\n",
"}"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": ".NET (C#)",
"language": "C#",
"name": ".net-csharp"
},
"language_info": {
"file_extension": ".cs",
"mimetype": "text/x-csharp",
"name": "C#",
"pygments_lexer": "csharp",
"version": "9.0"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
""".strip() + "\n"
def _not_identifier_char(text):
problematic_char = text[-1]
for i in range(1, len(text)):
substring = text[:i]
if not substring.isidentifier():
problematic_char = substring[-1]
break
return problematic_char
@lean.command(cls=LeanCommand, name="project-create", aliases=["create-project"])
@argument("name", type=str)
@option("--language", "-l",
type=Choice(container.cli_config_manager.default_language.allowed_values, case_sensitive=False),
help="The language of the project to create")
def create_project(name: str, language: str) -> None:
"""Create a new project containing starter code.
If NAME is a path containing subdirectories those will be created automatically.
The default language can be set using `lean config set default-language python/csharp`.
"""
cli_config_manager = container.cli_config_manager
language = language if language is not None else cli_config_manager.default_language.get_value()
if language is None:
raise MoreInfoError(
"Please specify a language with --language or set the default language using `lean config set default-language python/csharp`",
"https://www.lean.io/docs/v2/lean-cli/projects/project-management")
full_path = Path.cwd() / name
try:
cli_root_dir = container.lean_config_manager.get_cli_root_directory()
relative_path = full_path.relative_to(cli_root_dir).as_posix()
except MoreInfoError:
relative_path = name
if not container.path_manager.is_cli_path_valid(full_path) or not container.path_manager.is_name_valid(relative_path):
raise MoreInfoError(f"Invalid project name. Can only contain letters, numbers & spaces. Can not start with empty char ' ' or be a reserved name [ {', '.join(reserved_names)} ]",
"https://www.lean.io/docs/v2/lean-cli/key-concepts/troubleshooting#02-Common-Errors")
is_library_project = False
try:
library_dir = container.lean_config_manager.get_cli_root_directory() / "Library"
is_library_project = library_dir in full_path.parents
if is_library_project:
# Make sure we always use the same casing 'Library' for the library directory
full_path = library_dir / full_path.relative_to(library_dir)
except:
# get_cli_root_directory() raises an error if there is no such directory
pass
id_name = full_path.name
if is_library_project and language == "python" and not id_name.isidentifier():
problematic_char = _not_identifier_char(id_name)
raise RuntimeError(
f"""'{id_name}' is not a valid Python identifier, which is required for Python library projects to be importable.
Please remove the character '{problematic_char}' and retry""")
if full_path.exists():
raise RuntimeError(f"A project named '{name}' already exists, please choose a different name")
else:
project_manager = container.project_manager
project_manager.create_new_project(full_path, QCLanguage.Python if language == "python" else QCLanguage.CSharp)
class_name = convert_to_class_name(full_path)
if language == "python":
main_name = "main.py" if not is_library_project else "Library.py"
research_name = "research.ipynb"
main_content = DEFAULT_PYTHON_MAIN if not is_library_project else LIBRARY_PYTHON_MAIN
else:
main_name = "Main.cs" if not is_library_project else "Library.cs"
research_name = "Research.ipynb"
main_content = DEFAULT_CSHARP_MAIN if not is_library_project else LIBRARY_CSHARP_MAIN
with (full_path / main_name).open("w+", encoding="utf-8") as file:
file.write(main_content.replace("$CLASS_NAME$", class_name).replace("$PROJECT_NAME$", full_path.name))
if not is_library_project:
with (full_path / research_name).open("w+", encoding="utf-8") as file:
file.write(DEFAULT_PYTHON_NOTEBOOK if language == "python" else DEFAULT_CSHARP_NOTEBOOK)
if language == "csharp":
project_manager = container.project_manager
project_csproj_file = project_manager.get_csproj_file_path(full_path)
original_csproj_content = project_csproj_file.read_text(encoding="utf-8")
project_manager.try_restore_csharp_project(project_csproj_file, original_csproj_content, False)
logger = container.logger
logger.info(f"Successfully created {'Python' if language == 'python' else 'C#'} project '{name}'")