17 using System.Collections.Generic;
31 private readonly
int _lookback;
33 private readonly TimeSpan _predictionInterval;
34 private readonly Dictionary<Symbol, SymbolData> _symbolDataBySymbol;
48 _resolution = resolution;
49 _predictionInterval = _resolution.ToTimeSpan().Multiply(_lookback);
50 _symbolDataBySymbol =
new Dictionary<Symbol, SymbolData>();
52 Name = $
"{nameof(HistoricalReturnsAlphaModel)}({lookback},{resolution})";
64 var insights =
new List<Insight>();
65 foreach (var (symbol, symbolData) in _symbolDataBySymbol)
67 if (symbolData.CanEmit())
70 var magnitude = (double)symbolData.ROC.Current.Value;
76 CancelInsights(algorithm, symbol);
80 insights.Add(
Insight.
Price(symbolData.Security.Symbol, _predictionInterval, direction, magnitude,
null));
83 _insightCollection.AddRange(insights);
95 foreach (var removed
in changes.RemovedSecurities)
98 if (_symbolDataBySymbol.TryGetValue(removed.Symbol, out data))
100 _symbolDataBySymbol.Remove(removed.Symbol);
101 algorithm.SubscriptionManager.RemoveConsolidator(removed.Symbol, data.Consolidator);
104 CancelInsights(algorithm, removed.Symbol);
108 var addedSymbols =
new List<Symbol>();
109 foreach (var added
in changes.AddedSecurities)
111 if (!_symbolDataBySymbol.ContainsKey(added.Symbol))
113 var symbolData =
new SymbolData(algorithm, added, _lookback, _resolution);
114 _symbolDataBySymbol[added.Symbol] = symbolData;
115 addedSymbols.Add(symbolData.Security.Symbol);
119 if (addedSymbols.Count > 0)
122 algorithm.History(addedSymbols, _lookback, _resolution)
125 SymbolData symbolData;
126 if (_symbolDataBySymbol.TryGetValue(bar.Symbol, out symbolData))
128 symbolData.ROC.Update(bar.EndTime, bar.Value);
136 if (_insightCollection.TryGetValue(symbol, out var insights))
138 algorithm.
Insights.Cancel(insights);
139 _insightCollection.Clear(
new[] { symbol });
146 private class SymbolData
151 public long previous = 0;
153 public SymbolData(QCAlgorithm algorithm,
Security security,
int lookback,
Resolution resolution)
156 Consolidator = algorithm.ResolveConsolidator(security.
Symbol, resolution);
157 algorithm.SubscriptionManager.AddConsolidator(security.
Symbol, Consolidator);
159 algorithm.RegisterIndicator(security.
Symbol, ROC, Consolidator);
162 public bool CanEmit()
164 if (previous == ROC.Samples)
return false;
165 previous = ROC.Samples;