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

by erin_nader , in category: Technical Analysis , 2 months ago

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

Facebook Twitter LinkedIn Whatsapp

1 answer

by sadie.maggio , 2 months ago

@erin_nader 

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

  1. Define a function that calculates the CCI value based on the formula: CCI = (Typical Price - SMA) / (0.015 * Mean Deviation) where Typical Price = (High + Low + Close) / 3 SMA = Simple Moving Average of Typical Price over a specified period Mean Deviation = Average of the absolute values of the differences between the Typical Price and the SMA over the specified period
  2. Create an array of High, Low, and Close prices for the specified period.
  3. Calculate the Typical Price for each period in the array.
  4. Calculate the Simple Moving Average (SMA) of the Typical Price over the specified period.
  5. Calculate the Mean Deviation by finding the absolute differences between the Typical Price and SMA for each period, then calculating the average of these differences.
  6. Finally, compute the CCI value for each period using the CCI formula.


Here is an example Swift code snippet to calculate the CCI value for a given period:

 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
func calculateCCI(high: [Double], low: [Double], close: [Double], period: Int) -> [Double] {
    var cciValues: [Double] = []
    
    for i in 0..<close.count {
        var typicalPrice = (high[i] + low[i] + close[i]) / 3
        
        let sma = calculateSMA(typicalPrice: typicalPrice, period: period)
        
        var sumDiff = 0.0
        for j in max(0, i-period+1)...i {
            sumDiff += abs(typicalPrice - sma)
        }
        
        let meanDeviation = sumDiff / Double(min(period, i + 1))
        
        let cci = (typicalPrice - sma) / (0.015 * meanDeviation)
        cciValues.append(cci)
    }
    
    return cciValues
}

func calculateSMA(typicalPrice: Double, period: Int) -> Double {
    // Calculate the Simple Moving Average of the Typical Price over the specified period
    return 0.0 // Implement SMA calculation logic here
}

// Example usage
let highPrices = [100.0, 110.0, 105.0, 120.0, 125.0]
let lowPrices = [90.0, 100.0, 95.0, 110.0, 115.0]
let closePrices = [95.0, 105.0, 100.0, 115.0, 120.0]
let period = 14

let cciValues = calculateCCI(high: highPrices, low: lowPrices, close: closePrices, period: period)
print(cciValues)


This code snippet provides a basic implementation of the CCI calculation in Swift. You may need to implement the calculateSMA function and adjust the code based on your specific requirements and data source.