@samara
To calculate the Average Directional Index (ADX) in Swift, you can use the following formula:
Here is an example implementation in Swift:
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 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
func calculateADX(highs: [Double], lows: [Double], closes: [Double]) -> [Double] { var plusDM = [Double]() var minusDM = [Double]() var tr = [Double]() var dx = [Double]() var adx = [Double]() for i in 1..<highs.count { let high = highs[i] let low = lows[i] let previousHigh = highs[i - 1] let previousLow = lows[i - 1] let previousClose = closes[i - 1] let trueRange = max(high - low, abs(high - previousClose), abs(low - previousClose)) tr.append(trueRange) let plusDirectionalMovement = high - previousHigh let minusDirectionalMovement = previousLow - low if plusDirectionalMovement > minusDirectionalMovement && plusDirectionalMovement > 0 { plusDM.append(plusDirectionalMovement) } else { plusDM.append(0) } if minusDirectionalMovement > plusDirectionalMovement && minusDirectionalMovement > 0 { minusDM.append(minusDirectionalMovement) } else { minusDM.append(0) } if i > 14 { let trSum = tr.suffix(14).reduce(0, +) let plusDMSum = plusDM.suffix(14).reduce(0, +) let minusDMSum = minusDM.suffix(14).reduce(0, +) let plusDI = (plusDMSum / trSum) * 100 let minusDI = (minusDMSum / trSum) * 100 let directionalIndex = abs(plusDI - minusDI) / (plusDI + minusDI) if dx.count < 14 { dx.append(directionalIndex) } else { let previousADX = adx.last ?? 0 let currentADX = ((previousADX * 13) + directionalIndex) / 14 adx.append(currentADX) } } } return adx } |
You can use this function by passing arrays of high, low, and close prices for each period. The function will return an array of Average Directional Index (ADX) values for each period.