How To Calculate Commodity Channel Index (CCI) in C#?

by keegan.towne , in category: General Help , 8 months ago

How To Calculate Commodity Channel Index (CCI) in C#?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by cecelia , 8 months ago

@keegan.towne 

To calculate the Commodity Channel Index (CCI) in C#, you can follow these steps:

  1. Define a period for which you want to calculate the CCI. The typical period used is 20 days.
  2. Calculate the typical price for each period using the formula: Typical Price = (High + Low + Close) / 3
  3. Calculate the simple moving average (SMA) of the typical prices for the specified period.
  4. Calculate the mean deviation for each period using the formula: Mean Deviation = Sum of |Typical Price - SMA| / Period
  5. Calculate the Commodity Channel Index (CCI) using the formula: CCI = (Typical Price - SMA) / (0.015 * Mean Deviation)


Here is a sample code snippet in C# to calculate the CCI for a given data set:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public double CalculateCCI(List<double> highs, List<double> lows, List<double> closes, int period)
{
    List<double> typicalPrices = new List<double>();
    List<double> smaTypicalPrices = new List<double>();
    List<double> meanDeviations = new List<double>();
    List<double> cciValues = new List<double>();

    for (int i = period; i < highs.Count; i++)
    {
        double typicalPrice = (highs[i] + lows[i] + closes[i]) / 3;
        typicalPrices.Add(typicalPrice);

        double sma = typicalPrices.Skip(i - period).Take(period).Average();
        smaTypicalPrices.Add(sma);

        double meanDeviation = typicalPrices.Skip(i - period).Take(period).Select(tp => Math.Abs(tp - sma)).Sum() / period;
        meanDeviations.Add(meanDeviation);

        double cci = (typicalPrice - sma) / (0.015 * meanDeviation);
        cciValues.Add(cci);
    }

    return cciValues.Last();
}


This code snippet demonstrates how to calculate the CCI for a given data set. Make sure to replace the placeholders for highs, lows, closes, and the period with your actual data before running the code.