17 using System.Collections.Generic;
37 private readonly
int _lookback;
38 private readonly
int _period;
42 private readonly Dictionary<Symbol, ReturnsSymbolData> _symbolDataDict;
60 double targetReturn = 0.02,
62 : this(rebalancingDateRules.ToFunc(), portfolioBias, lookback, period, resolution, targetReturn, optimizer)
81 double targetReturn = 0.02,
83 : this(rebalanceResolution.ToTimeSpan(), portfolioBias, lookback, period, resolution, targetReturn, optimizer)
102 double targetReturn = 0.02,
104 : this(dt => dt.Add(timeSpan), portfolioBias, lookback, period, resolution, targetReturn, optimizer)
129 double targetReturn = 0.02,
130 PyObject optimizer =
null)
131 : this((Func<DateTime, DateTime?>)null, portfolioBias, lookback, period, resolution, targetReturn, null)
135 if (optimizer !=
null)
139 _optimizer = csharpOptimizer;
164 double targetReturn = 0.02,
166 : this(rebalancingFunc != null ? (Func<DateTime, DateTime?>)(timeUtc => rebalancingFunc(timeUtc)) : null,
193 double targetReturn = 0.02,
195 : base(rebalancingFunc)
197 _lookback = lookback;
199 _resolution = resolution;
200 _portfolioBias = portfolioBias;
206 _symbolDataDict =
new Dictionary<Symbol, ReturnsSymbolData>();
218 if (filteredInsight ==
null)
224 if (_symbolDataDict.TryGetValue(insight.
Symbol, out data))
229 new ArgumentNullException(
231 "MeanVarianceOptimizationPortfolioConstructionModel does not accept 'null' as Insight.Magnitude. " +
232 "Please checkout the selected Alpha Model specifications: " + insight.
SourceModel));
248 var targets =
new Dictionary<Insight, double>();
251 if (activeInsights.IsNullOrEmpty())
256 var symbols = activeInsights.Select(x => x.Symbol).ToList();
261 var returns = _symbolDataDict.FormReturnsMatrix(symbols);
264 var w = _optimizer.Optimize(returns);
270 foreach (var symbol
in symbols)
272 var weight = w[sidx];
276 && Math.Sign(weight) != (
int)_portfolioBias)
281 targets[activeInsights.First(insight => insight.Symbol == symbol)] = weight;
297 base.OnSecuritiesChanged(algorithm, changes);
299 foreach (var removed
in changes.RemovedSecurities)
302 if (_symbolDataDict.TryGetValue(removed.Symbol, out data))
304 _symbolDataDict.Remove(removed.Symbol);
308 if (changes.AddedSecurities.Count == 0)
312 foreach (var added
in changes.AddedSecurities)
314 if (!_symbolDataDict.ContainsKey(added.Symbol))
317 _symbolDataDict[added.Symbol] = symbolData;
322 algorithm.History(changes.AddedSecurities.Select(security => security.Symbol), _lookback * _period, _resolution)
326 if (_symbolDataDict.TryGetValue(bar.Symbol, out symbolData))
328 symbolData.Update(bar.EndTime, bar.Value);