forked from QuantConnect/Lean
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQCAlgorithm.Framework.cs
415 lines (371 loc) · 16.5 KB
/
QCAlgorithm.Framework.cs
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
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 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.
*/
using System;
using System.Linq;
using QuantConnect.Algorithm.Framework.Alphas;
using QuantConnect.Algorithm.Framework.Alphas.Analysis;
using QuantConnect.Algorithm.Framework.Execution;
using QuantConnect.Algorithm.Framework.Portfolio;
using QuantConnect.Algorithm.Framework.Risk;
using QuantConnect.Algorithm.Framework.Selection;
using QuantConnect.Data;
using QuantConnect.Data.UniverseSelection;
using QuantConnect.Util;
namespace QuantConnect.Algorithm
{
public partial class QCAlgorithm
{
private readonly ISecurityValuesProvider _securityValuesProvider;
private bool _isEmitWarmupInsightWarningSent;
/// <summary>
/// Enables additional logging of framework models including:
/// All insights, portfolio targets, order events, and any risk management altered targets
/// </summary>
public bool DebugMode { get; set; }
/// <summary>
/// Gets or sets the universe selection model.
/// </summary>
public IUniverseSelectionModel UniverseSelection { get; set; }
/// <summary>
/// Gets or sets the alpha model
/// </summary>
public IAlphaModel Alpha { get; set; }
/// <summary>
/// Gets or sets the portfolio construction model
/// </summary>
public IPortfolioConstructionModel PortfolioConstruction { get; set; }
/// <summary>
/// Gets or sets the execution model
/// </summary>
public IExecutionModel Execution { get; set; }
/// <summary>
/// Gets or sets the risk management model
/// </summary>
public IRiskManagementModel RiskManagement { get; set; }
/// <summary>
/// Called by setup handlers after Initialize and allows the algorithm a chance to organize
/// the data gather in the Initialize method
/// </summary>
public void FrameworkPostInitialize()
{
foreach (var universe in UniverseSelection.CreateUniverses(this))
{
AddUniverse(universe);
}
if (DebugMode)
{
InsightsGenerated += (algorithm, data) => Log($"{Time}: {string.Join(" | ", data.Insights.OrderBy(i => i.Symbol.ToString()))}");
}
}
/// <summary>
/// Used to send data updates to algorithm framework models
/// </summary>
/// <param name="slice">The current data slice</param>
public void OnFrameworkData(Slice slice)
{
if (UtcTime >= UniverseSelection.GetNextRefreshTimeUtc())
{
var universes = UniverseSelection.CreateUniverses(this).ToDictionary(u => u.Configuration.Symbol);
// remove deselected universes by symbol
foreach (var ukvp in UniverseManager)
{
var universeSymbol = ukvp.Key;
var qcUserDefined = UserDefinedUniverse.CreateSymbol(ukvp.Value.SecurityType, ukvp.Value.Market);
if (universeSymbol.Equals(qcUserDefined))
{
// prevent removal of qc algorithm created user defined universes
continue;
}
Universe universe;
if (!universes.TryGetValue(universeSymbol, out universe))
{
if (ukvp.Value.DisposeRequested)
{
UniverseManager.Remove(universeSymbol);
}
// mark this universe as disposed to remove all child subscriptions
ukvp.Value.Dispose();
}
}
// add newly selected universes
foreach (var ukvp in universes)
{
// note: UniverseManager.Add uses TryAdd, so don't need to worry about duplicates here
UniverseManager.Add(ukvp);
}
}
// we only want to run universe selection if there's no data available in the slice
if (!slice.HasData)
{
return;
}
// insight timestamping handled via InsightsGenerated event handler
var insightsEnumerable = Alpha.Update(this, slice);
// for performance only call 'ToArray' if not empty enumerable (which is static)
var insights = insightsEnumerable == Enumerable.Empty<Insight>()
? new Insight[] { } : insightsEnumerable.ToArray();
// only fire insights generated event if we actually have insights
if (insights.Length != 0)
{
OnInsightsGenerated(insights.Select(InitializeInsightFields));
}
ProcessInsights(insights);
}
/// <summary>
/// They different framework models will process the new provided insight.
/// The <see cref="IPortfolioConstructionModel"/> will create targets,
/// the <see cref="IRiskManagementModel"/> will adjust the targets
/// and the <see cref="IExecutionModel"/> will execute the <see cref="IPortfolioTarget"/>
/// </summary>
/// <param name="insights">The insight to process</param>
private void ProcessInsights(Insight[] insights)
{
// construct portfolio targets from insights
var targetsEnumerable = PortfolioConstruction.CreateTargets(this, insights);
// for performance only call 'ToArray' if not empty enumerable (which is static)
var targets = targetsEnumerable == Enumerable.Empty<IPortfolioTarget>()
? new IPortfolioTarget[] {} : targetsEnumerable.ToArray();
// set security targets w/ those generated via portfolio construction module
foreach (var target in targets)
{
var security = Securities[target.Symbol];
security.Holdings.Target = target;
}
if (DebugMode)
{
// debug printing of generated targets
if (targets.Length > 0)
{
Log($"{Time}: PORTFOLIO: {string.Join(" | ", targets.Select(t => t.ToString()).OrderBy(t => t))}");
}
}
var riskTargetOverridesEnumerable = RiskManagement.ManageRisk(this, targets);
// for performance only call 'ToArray' if not empty enumerable (which is static)
var riskTargetOverrides = riskTargetOverridesEnumerable == Enumerable.Empty<IPortfolioTarget>()
? new IPortfolioTarget[] { } : riskTargetOverridesEnumerable.ToArray();
// override security targets w/ those generated via risk management module
foreach (var target in riskTargetOverrides)
{
var security = Securities[target.Symbol];
security.Holdings.Target = target;
}
if (DebugMode)
{
// debug printing of generated risk target overrides
if (riskTargetOverrides.Length > 0)
{
Log($"{Time}: RISK: {string.Join(" | ", riskTargetOverrides.Select(t => t.ToString()).OrderBy(t => t))}");
}
}
IPortfolioTarget[] riskAdjustedTargets;
// for performance we check the length before
if (riskTargetOverrides.Length != 0
|| targets.Length != 0)
{
// execute on the targets, overriding targets for symbols w/ risk targets
riskAdjustedTargets = riskTargetOverrides.Concat(targets).DistinctBy(pt => pt.Symbol).ToArray();
}
else
{
riskAdjustedTargets = new IPortfolioTarget[] { };
}
if (DebugMode)
{
// only log adjusted targets if we've performed an adjustment
if (riskTargetOverrides.Length > 0)
{
Log($"{Time}: RISK ADJUSTED TARGETS: {string.Join(" | ", riskAdjustedTargets.Select(t => t.ToString()).OrderBy(t => t))}");
}
}
if (riskAdjustedTargets.Length > 0
&& Execution.GetType() != typeof(NullExecutionModel)
&& BrokerageModel.AccountType == AccountType.Cash)
{
throw new InvalidOperationException($"Non null {nameof(IExecutionModel)} and {nameof(IPortfolioConstructionModel)} are currently unsuitable for Cash Modeled brokerages (e.g. GDAX) and may result in unexpected trades."
+ " To prevent possible user error we've restricted them to Margin trading. You can select margin account types with"
+ $" SetBrokerage( ... AccountType.Margin). Or please set them to {nameof(NullExecutionModel)}, {nameof(NullPortfolioConstructionModel)}");
}
Execution.Execute(this, riskAdjustedTargets);
}
/// <summary>
/// Used to send security changes to algorithm framework models
/// </summary>
/// <param name="changes">Security additions/removals for this time step</param>
public void OnFrameworkSecuritiesChanged(SecurityChanges changes)
{
if (DebugMode)
{
Log($"{Time}: {changes}");
}
Alpha.OnSecuritiesChanged(this, changes);
PortfolioConstruction.OnSecuritiesChanged(this, changes);
Execution.OnSecuritiesChanged(this, changes);
RiskManagement.OnSecuritiesChanged(this, changes);
}
/// <summary>
/// Sets the universe selection model
/// </summary>
/// <param name="universeSelection">Model defining universes for the algorithm</param>
public void SetUniverseSelection(IUniverseSelectionModel universeSelection)
{
UniverseSelection = universeSelection;
}
/// <summary>
/// Adds a new universe selection model
/// </summary>
/// <param name="universeSelection">Model defining universes for the algorithm to add</param>
public void AddUniverseSelection(IUniverseSelectionModel universeSelection)
{
if (UniverseSelection.GetType() != typeof(NullUniverseSelectionModel))
{
var compositeUniverseSelection = UniverseSelection as CompositeUniverseSelectionModel;
if (compositeUniverseSelection != null)
{
compositeUniverseSelection.AddUniverseSelection(universeSelection);
}
else
{
UniverseSelection = new CompositeUniverseSelectionModel(UniverseSelection, universeSelection);
}
}
else
{
UniverseSelection = universeSelection;
}
}
/// <summary>
/// Sets the alpha model
/// </summary>
/// <param name="alpha">Model that generates alpha</param>
public void SetAlpha(IAlphaModel alpha)
{
Alpha = alpha;
}
/// <summary>
/// Adds a new alpha model
/// </summary>
/// <param name="alpha">Model that generates alpha to add</param>
public void AddAlpha(IAlphaModel alpha)
{
if (Alpha.GetType() != typeof(NullAlphaModel))
{
var compositeAlphaModel = Alpha as CompositeAlphaModel;
if (compositeAlphaModel != null)
{
compositeAlphaModel.AddAlpha(alpha);
}
else
{
Alpha = new CompositeAlphaModel(Alpha, alpha);
}
}
else
{
Alpha = alpha;
}
}
/// <summary>
/// Sets the portfolio construction model
/// </summary>
/// <param name="portfolioConstruction">Model defining how to build a portfolio from insights</param>
public void SetPortfolioConstruction(IPortfolioConstructionModel portfolioConstruction)
{
PortfolioConstruction = portfolioConstruction;
}
/// <summary>
/// Sets the execution model
/// </summary>
/// <param name="execution">Model defining how to execute trades to reach a portfolio target</param>
public void SetExecution(IExecutionModel execution)
{
Execution = execution;
}
/// <summary>
/// Sets the risk management model
/// </summary>
/// <param name="riskManagement">Model defining how risk is managed</param>
public void SetRiskManagement(IRiskManagementModel riskManagement)
{
RiskManagement = riskManagement;
}
/// <summary>
/// Adds a new risk management model
/// </summary>
/// <param name="riskManagement">Model defining how risk is managed to add</param>
public void AddRiskManagement(IRiskManagementModel riskManagement)
{
if (RiskManagement.GetType() != typeof(NullRiskManagementModel))
{
var compositeRiskModel = RiskManagement as CompositeRiskManagementModel;
if (compositeRiskModel != null)
{
compositeRiskModel.AddRiskManagement(riskManagement);
}
else
{
RiskManagement = new CompositeRiskManagementModel(RiskManagement, riskManagement);
}
}
else
{
RiskManagement = riskManagement;
}
}
/// <summary>
/// Manually emit insights from an algorithm.
/// This is typically invoked before calls to submit orders in algorithms written against
/// QCAlgorithm that have been ported into the algorithm framework.
/// </summary>
/// <param name="insights">The array of insights to be emitted</param>
public void EmitInsights(params Insight[] insights)
{
if (IsWarmingUp)
{
if (!_isEmitWarmupInsightWarningSent)
{
Error("Warning: insights emitted during algorithm warmup are ignored.");
_isEmitWarmupInsightWarningSent = true;
}
return;
}
OnInsightsGenerated(insights.Select(InitializeInsightFields));
ProcessInsights(insights);
}
/// <summary>
/// Manually emit insights from an algorithm.
/// This is typically invoked before calls to submit orders in algorithms written against
/// QCAlgorithm that have been ported into the algorithm framework.
/// </summary>
/// <param name="insight">The insight to be emitted</param>
public void EmitInsights(Insight insight)
{
EmitInsights(new []{insight});
}
/// <summary>
/// Helper class used to set values not required to be set by alpha models
/// </summary>
/// <param name="insight">The <see cref="Insight"/> to set the values for</param>
/// <returns>The same <see cref="Insight"/> instance with the values set</returns>
private Insight InitializeInsightFields(Insight insight)
{
insight.GeneratedTimeUtc = UtcTime;
insight.ReferenceValue = _securityValuesProvider.GetValues(insight.Symbol).Get(insight.Type);
insight.SourceModel = string.IsNullOrEmpty(insight.SourceModel) ? Alpha.GetModelName() : insight.SourceModel;
var exchangeHours = MarketHoursDatabase.GetExchangeHours(insight.Symbol.ID.Market, insight.Symbol, insight.Symbol.SecurityType);
insight.SetPeriodAndCloseTime(exchangeHours);
return insight;
}
}
}