Lean  $LEAN_TAG$
EmaCrossUniverseSelectionModel.cs
1 /*
2  * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
3  * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
4  *
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14 */
15 
16 using System;
17 using System.Collections.Concurrent;
18 using System.Collections.Generic;
19 using System.Linq;
23 
25 {
26  /// <summary>
27  /// Provides an implementation of <see cref="FundamentalUniverseSelectionModel"/> that subscribes
28  /// to symbols with the larger delta by percentage between the two exponential moving average
29  /// </summary>
31  {
32  private const decimal _tolerance = 0.01m;
33  private readonly int _fastPeriod;
34  private readonly int _slowPeriod;
35  private readonly int _universeCount;
36 
37  // holds our coarse fundamental indicators by symbol
38  private readonly ConcurrentDictionary<Symbol, SelectionData> _averages;
39 
40  /// <summary>
41  /// Initializes a new instance of the <see cref="EmaCrossUniverseSelectionModel"/> class
42  /// </summary>
43  /// <param name="fastPeriod">Fast EMA period</param>
44  /// <param name="slowPeriod">Slow EMA period</param>
45  /// <param name="universeCount">Maximum number of members of this universe selection</param>
46  /// <param name="universeSettings">The settings used when adding symbols to the algorithm, specify null to use algorithm.UniverseSettings</param>
48  int fastPeriod = 100,
49  int slowPeriod = 300,
50  int universeCount = 500,
51  UniverseSettings universeSettings = null)
52  : base(false, universeSettings)
53  {
54  _fastPeriod = fastPeriod;
55  _slowPeriod = slowPeriod;
56  _universeCount = universeCount;
57  _averages = new ConcurrentDictionary<Symbol, SelectionData>();
58  }
59 
60  /// <summary>
61  /// Defines the coarse fundamental selection function.
62  /// </summary>
63  /// <param name="algorithm">The algorithm instance</param>
64  /// <param name="coarse">The coarse fundamental data used to perform filtering</param>
65  /// <returns>An enumerable of symbols passing the filter</returns>
66  public override IEnumerable<Symbol> SelectCoarse(QCAlgorithm algorithm, IEnumerable<CoarseFundamental> coarse)
67  {
68  return (from cf in coarse
69  // grab th SelectionData instance for this symbol
70  let avg = _averages.GetOrAdd(cf.Symbol, sym => new SelectionData(_fastPeriod, _slowPeriod))
71  // Update returns true when the indicators are ready, so don't accept until they are
72  where avg.Update(cf.EndTime, cf.AdjustedPrice)
73  // only pick symbols who have their _fastPeriod-day ema over their _slowPeriod-day ema
74  where avg.Fast > avg.Slow * (1 + _tolerance)
75  // prefer symbols with a larger delta by percentage between the two averages
76  orderby avg.ScaledDelta descending
77  // we only need to return the symbol and return 'Count' symbols
78  select cf.Symbol).Take(_universeCount);
79  }
80 
81  // class used to improve readability of the coarse selection function
82  private class SelectionData
83  {
84  public readonly ExponentialMovingAverage Fast;
85  public readonly ExponentialMovingAverage Slow;
86 
87  public SelectionData(int fastPeriod, int slowPeriod)
88  {
89  Fast = new ExponentialMovingAverage(fastPeriod);
90  Slow = new ExponentialMovingAverage(slowPeriod);
91  }
92 
93  // computes an object score of how much large the fast is than the slow
94  public decimal ScaledDelta => (Fast - Slow) / ((Fast + Slow) / 2m);
95 
96  // updates the EMAFast and EMASlow indicators, returning true when they're both ready
97  public bool Update(DateTime time, decimal value) => Fast.Update(time, value) & Slow.Update(time, value);
98  }
99  }
100 }