How To Compute Commodity Channel Index (CCI) using JavaScript?

by tyrel_franecki , in category: Technology , 2 months ago

How To Compute Commodity Channel Index (CCI) using JavaScript?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by matilde , 2 months ago

@tyrel_franecki 

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

  1. Define the period length for the CCI calculation. The standard period length is 20.
  2. Calculate the typical price for each data point. The typical price is calculated as the average of the high, low, and close prices for each period.
  3. Calculate the simple moving average (SMA) of the typical prices over the defined period length.
  4. Calculate the mean deviation for each data point. Mean deviation is the sum of the absolute differences between the typical price and the SMA over the specified period, divided by the period length.
  5. Calculate the CCI using the formula: CCI = (Typical Price - SMA of Typical Price) / (0.015 * Mean Deviation)


Here is an example code snippet in JavaScript 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function calculateCCI(data, period) {
  let cciValues = [];

  for (let i = period - 1; i < data.length; i++) {
    let typicalPrice = (data[i].high + data[i].low + data[i].close) / 3;

    let sumTypicalPrice = 0;
    for (let j = i - (period - 1); j <= i; j++) {
      sumTypicalPrice += (data[j].high + data[j].low + data[j].close) / 3;
    }

    let smaTypicalPrice = sumTypicalPrice / period;

    let sumMeanDeviation = 0;
    for (let j = i - (period - 1); j <= i; j++) {
      let meanDeviation = Math.abs((data[j].high + data[j].low + data[j].close) / 3 - smaTypicalPrice);
      sumMeanDeviation += meanDeviation;
    }

    let meanDeviation = sumMeanDeviation / period;

    let cci = (typicalPrice - smaTypicalPrice) / (0.015 * meanDeviation);
    cciValues.push(cci);
  }

  return cciValues;
}

// Example data for testing
const data = [
  { high: 50, low: 45, close: 48 },
  { high: 55, low: 47, close: 52 },
  // Add more data points as needed
];

const period = 20;
const cciValues = calculateCCI(data, period);
console.log(cciValues);


Please note that this code is a basic example and may need to be modified based on your specific requirements and data structure. Make sure to test the code with your own data to verify its accuracy.