17 using System.Collections.Generic;
32 private Func<DateTime, DateTime?> _rebalancingFunc;
33 private DateTime? _rebalancingTime;
34 private bool _securityChanges;
66 _rebalancingFunc = rebalancingFunc;
75 : this(rebalancingFunc != null ? (Func<DateTime, DateTime?>)(timeUtc => rebalancingFunc(timeUtc)) : null)
103 var targets =
new List<IPortfolioTarget>();
108 var errorSymbols =
new HashSet<Symbol>();
114 foreach (var insight
in lastActiveInsights)
116 if (!percents.TryGetValue(insight, out var percent))
128 errorSymbols.Add(insight.Symbol);
133 var expiredInsights =
Algorithm.
Insights.RemoveExpiredInsights(algorithm.UtcTime);
135 var expiredTargets = from insight in expiredInsights
136 group insight.Symbol by insight.Symbol into g
137 where !
Algorithm.
Insights.HasActiveInsights(g.Key, algorithm.UtcTime) && !errorSymbols.Contains(g.Key)
140 targets.AddRange(expiredTargets);
157 algorithm?.
Insights.Expire(removedSymbols);
174 return (from insight in activeInsights
175 group insight by insight.
Symbol into g
176 select g.OrderBy(x => x.GeneratedTimeUtc).Last()).ToList();
197 throw new NotImplementedException(
"Types deriving from 'PortfolioConstructionModel' must implement the 'Dictionary<Insight, double> DetermineTargetPercent(ICollection<Insight>)' method.");
215 if (rebalance.TryConvert(out dateRules))
217 _rebalancingFunc = dateRules.ToFunc();
219 else if (!rebalance.TryConvertToDelegate(out _rebalancingFunc))
226 timeSpan = rebalance.As<TimeSpan>();
227 if (timeSpan !=
default(TimeSpan))
229 _rebalancingFunc = time => time.Add(timeSpan);
235 _rebalancingFunc =
null;
252 if (_rebalancingFunc ==
null)
262 if (_rebalancingTime ==
null)
264 _rebalancingTime = _rebalancingFunc(algorithmUtc);
266 if (_rebalancingTime !=
null && _rebalancingTime <= algorithmUtc)
272 _rebalancingTime =
null;
273 _securityChanges =
false;
278 if (_rebalancingTime !=
null && _rebalancingTime <= algorithmUtc
281 && (insights.Length != 0
282 || nextInsightExpiryTime !=
null && nextInsightExpiryTime < algorithmUtc))
296 if (_rebalancingFunc !=
null)
298 _rebalancingTime = _rebalancingFunc(algorithmUtc);
300 _securityChanges =
false;
313 var result = insights.Where(insight =>
315 if (!insight.Magnitude.HasValue || insight.Magnitude == 0)
320 var absoluteMagnitude = Math.Abs(insight.Magnitude.Value);
324 algorithm.Error(
"PortfolioConstructionModel.FilterInvalidInsightMagnitude():" +
325 $
"The insight target Magnitude: {insight.Magnitude}, will not comply with the current " +
326 $
"'Algorithm.Settings' 'MaxAbsolutePortfolioTargetPercentage': {algorithm.Settings.MaxAbsolutePortfolioTargetPercentage}" +
327 $
" or 'MinAbsolutePortfolioTargetPercentage': {algorithm.Settings.MinAbsolutePortfolioTargetPercentage}. Skipping insight."
334 return result.ToArray();