Lean  $LEAN_TAG$
WilderMovingAverage.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 
17 {
18  /// <summary>
19  /// Represents the moving average indicator defined by Welles Wilder in his book:
20  /// New Concepts in Technical Trading Systems.
21  /// </summary>
23  {
24  private readonly decimal _k;
25  private readonly int _period;
26  private readonly IndicatorBase<IndicatorDataPoint> _sma;
27 
28  /// <summary>
29  /// Initializes a new instance of the WilderMovingAverage class with the specified name and period
30  /// </summary>
31  /// <param name="name">The name of this indicator</param>
32  /// <param name="period">The period of the Wilder Moving Average</param>
33  public WilderMovingAverage(string name, int period)
34  : base(name)
35  {
36  _period = period;
37  _k = 1m / period;
38  _sma = new SimpleMovingAverage(name + "_SMA", period);
39  }
40 
41  /// <summary>
42  /// Initializes a new instance of the WilderMovingAverage class with the default name and period
43  /// </summary>
44  /// <param name="period">The period of the Wilder Moving Average</param>
45  public WilderMovingAverage(int period)
46  : this("WWMA" + period, period)
47  {
48  }
49 
50  /// <summary>
51  /// Gets a flag indicating when this indicator is ready and fully initialized
52  /// </summary>
53  public override bool IsReady => Samples >= _period;
54 
55  /// <summary>
56  /// Required period, in data points, for the indicator to be ready and fully initialized.
57  /// </summary>
58  public int WarmUpPeriod => _period;
59 
60  /// <summary>
61  /// Resets this indicator to its initial state
62  /// </summary>
63  public override void Reset()
64  {
65  _sma.Reset();
66  base.Reset();
67  }
68 
69  /// <summary>
70  /// Computes the next value of this indicator from the given state
71  /// </summary>
72  /// <param name="input">The input given to the indicator</param>
73  /// <returns>A new value for this indicator</returns>
74  protected override decimal ComputeNextValue(IndicatorDataPoint input)
75  {
76  if (!IsReady)
77  {
78  _sma.Update(input);
79  return _sma.Current.Value;
80  }
81  return input.Value * _k + Current.Value * (1 - _k);
82  }
83  }
84 }