@cathrine_goyette
To compute the Commodity Channel Index (CCI) in Swift, you can follow these steps:
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.