How To Calculate Commodity Channel Index (CCI) using Groovy?

by herminia_bruen , in category: Third Party Scripts , 7 months ago

How To Calculate Commodity Channel Index (CCI) using Groovy?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by wilmer.lemke , 7 months ago

@herminia_bruen 

To calculate the Commodity Channel Index (CCI) using Groovy, you can follow these steps:

  1. Decide on a period for calculating the CCI. The typical period used is 20 days.
  2. Get the closing prices for the specified period.
  3. Calculate the Typical Price (TP) for each day by averaging the high, low, and closing prices for that day.
  4. Calculate the Simple Moving Average (SMA) of the Typical Prices for the specified period. This will be used as the base line for CCI calculation.
  5. Calculate the Mean Deviation (MD) for each day by subtracting the Typical Price from the SMA and taking the absolute value.
  6. Calculate the Average Mean Deviation (AMD) by averaging the Mean Deviation values for the specified period.
  7. Calculate the CCI by dividing the Mean Deviation of the current day by 0.015 times the AMD.


Here is a sample Groovy code snippet to calculate the CCI for a given dataset:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
def data = [10.0, 12.0, 11.5, 13.0, 14.5, 15.0, 16.0, 15.5, 14.0, 12.5, 11.0]

def period = 10
def typicalPrices = []
def sma = []
def meanDeviations = []
def cci = []

data.eachWithIndex { price, index ->
    if (index >= period - 1) {
        def tp = data.subList(index - period + 1, index + 1).sum() / period
        typicalPrices.add(tp)

        if (typicalPrices.size() == period) {
            sma.add(typicalPrices.sum() / period)
        }

        if (typicalPrices.size() > period) {
            def md = Math.abs(tp - sma.last())
            meanDeviations.add(md)
        }

        if (meanDeviations.size() == period) {
            def amd = meanDeviations.sum() / period
            cci.add((tp - sma.last()) / (0.015 * amd))
        }
    }
}

println "CCI values: $cci"


This code snippet calculates the CCI for a given dataset using a period of 10 days. You can modify the period and input dataset as needed for your specific calculation.