,

@samara

To calculate the Average Directional Index (ADX) in Swift, you can use the following formula:

- Calculate the True Range (TR) for each period:

- TR = Max(High - Low, Abs(High - PreviousClose), Abs(Low - PreviousClose))

- Calculate the +DI (Positive Directional Indicator) and -DI (Negative Directional Indicator) for each period:

- +DI = (H - H') / TR
- -DI = (L' - L) / TR
- Where H = High of the current period, L = Low of the current period, H' = High of the previous period, L' = Low of the previous period

- Calculate the Directional Movement Index (DX) for each period:

- DX = Abs(+DI - -DI) / (+DI + -DI)

- Calculate the Average Directional Index (ADX) using the Wilder's Smoothing Formula:

- ADX = ((PreviousADX * 13) + DX) / 14

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.

How To Compute Moving Average Convergence Divergence (MACD) in Swift?

How To Calculate Chaikin Money Flow (CMF) using Swift?

How to calculate average of array in php?

How To Calculate Simple Moving Average (SMA) in Lua?

How To Calculate Average True Range (ATR) in Ruby?

How to calculate average of count per day in mysql?