Lean  $LEAN_TAG$
Correlation.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;
18 
20 {
21  /// <summary>
22  /// The Correlation Indicator is a valuable tool in technical analysis, designed to quantify the degree of
23  /// relationship between the price movements of a target security (e.g., a stock or ETF) and a reference
24  /// market index. It measures how closely the target’s price changes are aligned with the fluctuations of
25  /// the index over a specific period of time, providing insights into the target’s susceptibility to market
26  /// movements.
27  /// A positive correlation indicates that the target tends to move in the same direction as the market index,
28  /// while a negative correlation suggests an inverse relationship. A correlation close to 0 implies a weak or
29  /// no linear relationship.
30  /// Commonly, the SPX index is employed as the benchmark for the overall market when calculating correlation,
31  /// ensuring a consistent and reliable reference point. This helps traders and investors make informed decisions
32  /// regarding the risk and behavior of the target security in relation to market trends.
33  ///
34  /// The indicator only updates when both assets have a price for a time step. When a bar is missing for one of the assets,
35  /// the indicator value fills forward to improve the accuracy of the indicator.
36  /// </summary>
37  public class Correlation : DualSymbolIndicator<double>
38  {
39  /// <summary>
40  /// Correlation type
41  /// </summary>
42  private readonly CorrelationType _correlationType;
43 
44  /// <summary>
45  /// Gets a flag indicating when the indicator is ready and fully initialized
46  /// </summary>
47  public override bool IsReady => TargetDataPoints.IsReady && ReferenceDataPoints.IsReady;
48 
49  /// <summary>
50  /// Creates a new Correlation indicator with the specified name, target, reference,
51  /// and period values
52  /// </summary>
53  /// <param name="name">The name of this indicator</param>
54  /// <param name="targetSymbol">The target symbol of this indicator</param>
55  /// <param name="period">The period of this indicator</param>
56  /// <param name="referenceSymbol">The reference symbol of this indicator</param>
57  /// <param name="correlationType">Correlation type</param>
58  public Correlation(string name, Symbol targetSymbol, Symbol referenceSymbol, int period, CorrelationType correlationType = CorrelationType.Pearson)
59  : base(name, targetSymbol, referenceSymbol, period)
60  {
61  // Assert the period is greater than two, otherwise the correlation can not be computed
62  if (period < 2)
63  {
64  throw new ArgumentException($"Period parameter for Correlation indicator must be greater than 2 but was {period}");
65  }
66  WarmUpPeriod = period + (IsTimezoneDifferent ? 1 : 0);
67  _correlationType = correlationType;
68  }
69 
70  /// <summary>
71  /// Creates a new Correlation indicator with the specified target, reference,
72  /// and period values
73  /// </summary>
74  /// <param name="targetSymbol">The target symbol of this indicator</param>
75  /// <param name="period">The period of this indicator</param>
76  /// <param name="referenceSymbol">The reference symbol of this indicator</param>
77  /// <param name="correlationType">Correlation type</param>
78  public Correlation(Symbol targetSymbol, Symbol referenceSymbol, int period, CorrelationType correlationType = CorrelationType.Pearson)
79  : this($"Correlation({period})", targetSymbol, referenceSymbol, period, correlationType)
80  {
81  }
82 
83  /// <summary>
84  /// Adds the closing price to the target or reference symbol's data set.
85  /// </summary>
86  /// <param name="input">The input value for this symbol</param>
87  /// <exception cref="ArgumentException">Thrown if the input symbol is not the target or reference symbol.</exception>
88  protected override void AddDataPoint(IBaseDataBar input)
89  {
90  if (input.Symbol == TargetSymbol)
91  {
92  TargetDataPoints.Add((double)input.Close);
93  }
94  else if (input.Symbol == ReferenceSymbol)
95  {
96  ReferenceDataPoints.Add((double)input.Close);
97  }
98  else
99  {
100  throw new ArgumentException($"The given symbol {input.Symbol} was not {TargetSymbol} or {ReferenceSymbol} symbol");
101  }
102  }
103 
104  /// <summary>
105  /// Computes the correlation value usuing symbols values
106  /// correlation values assing into _correlation property
107  /// </summary>
108  protected override void ComputeIndicator()
109  {
110  var newCorrelation = 0d;
111  if (_correlationType == CorrelationType.Pearson)
112  {
113  newCorrelation = MathNet.Numerics.Statistics.Correlation.Pearson(TargetDataPoints, ReferenceDataPoints);
114  }
115  if (_correlationType == CorrelationType.Spearman)
116  {
117  newCorrelation = MathNet.Numerics.Statistics.Correlation.Spearman(TargetDataPoints, ReferenceDataPoints);
118  }
119  if (newCorrelation.IsNaNOrZero())
120  {
121  newCorrelation = 0;
122  }
123  IndicatorValue = Extensions.SafeDecimalCast(newCorrelation);
124  }
125  }
126 }