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