Lean  $LEAN_TAG$
Variance.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 
19 {
20  /// <summary>
21  /// This indicator computes the n-period population variance.
22  /// </summary>
23  public class Variance : WindowIndicator<IndicatorDataPoint>, IIndicatorWarmUpPeriodProvider
24  {
25  private decimal _rollingSum;
26  private decimal _rollingSumOfSquares;
27 
28  /// <summary>
29  /// Initializes a new instance of the <see cref="Variance"/> class using the specified period.
30  /// </summary>
31  /// <param name="period">The period of the indicator</param>
32  public Variance(int period)
33  : this($"VAR({period})", period)
34  {
35  }
36 
37  /// <summary>
38  /// Initializes a new instance of the <see cref="Variance"/> class using the specified name and period.
39  /// </summary>
40  /// <param name="name">The name of this indicator</param>
41  /// <param name="period">The period of the indicator</param>
42  public Variance(string name, int period)
43  : base(name, period)
44  {
45  }
46 
47  /// <summary>
48  /// Required period, in data points, for the indicator to be ready and fully initialized.
49  /// </summary>
50  public int WarmUpPeriod => Period;
51 
52  /// <summary>
53  /// Computes the next value of this indicator from the given state
54  /// </summary>
55  /// <param name="input">The input given to the indicator</param>
56  /// <param name="window">The window for the input history</param>
57  /// <returns>A new value for this indicator</returns>
59  {
60  _rollingSum += input.Value;
61  _rollingSumOfSquares += input.Value * input.Value;
62 
63  if (Samples < 2)
64  return 0m;
65 
66  var n = Math.Min(Period, Samples);
67  var meanValue1 = _rollingSum / n;
68  var meanValue2 = _rollingSumOfSquares / n;
69 
70  if (n == Period)
71  {
72  var removedValue = window[Period - 1];
73  _rollingSum -= removedValue.Value;
74  _rollingSumOfSquares -= removedValue.Value * removedValue.Value;
75  }
76 
77  // Ensure non-negative variance
78  return Math.Max(0m, meanValue2 - meanValue1 * meanValue1);
79  }
80 
81  /// <summary>
82  /// Resets this indicator to its initial state
83  /// </summary>
84  public override void Reset()
85  {
86  _rollingSum = 0;
87  _rollingSumOfSquares = 0;
88  base.Reset();
89  }
90  }
91 }