How To Compute Commodity Channel Index (CCI) in Swift?

by cathrine_goyette , in category: General Help , 2 months ago

How To Compute Commodity Channel Index (CCI) in Swift?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by adolf , 2 months ago

@cathrine_goyette 

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

  1. Define variables for the typical price (TP), simple moving average (SMA), and mean deviation values.
  2. Calculate the typical price (TP) by averaging the high, low, and close prices for each period.
  3. Calculate the simple moving average (SMA) of the typical prices for the desired period.
  4. Calculate the mean deviation (MD) by taking the absolute difference between the typical price and the SMA and then averaging these values.
  5. Calculate the Commodity Channel Index (CCI) using the formula: (TP - SMA) / (0.015 * MD)
  6. Repeat steps 2-5 for each data point in your dataset to generate the CCI values for each period.


Here is a sample code snippet in Swift to compute the Commodity Channel Index (CCI):

 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
let period = 20 // Desired period for CCI calculation

func calculateCCI(data: [Double]) -> [Double] {
    var cciValues = [Double]()

    for i in period..<data.count {
        let tp = (data[i] + data[i - 1] + data[i - 2]) / 3.0
        
        let sma = (data[i-period..<i].reduce(0, +)) / Double(period)
        
        let mdSum = data[i-period..<i].reduce(0) { result, value in
            result + abs(tp - value)
        }
        let md = mdSum / Double(period)
        
        let cci = (tp - sma) / (0.015 * md)
        
        cciValues.append(cci)
    }

    return cciValues
}

// Sample data
let data = [100.0, 105.0, 110.0, 115.0, 120.0, 115.0, 110.0, 105.0, 100.0, 95.0, 90.0, 85.0, 80.0]

let cciValues = calculateCCI(data: data)
print(cciValues)


This code snippet calculates the CCI values for a sample dataset of price values. You can adjust the period variable to change the desired period for CCI calculation.