How To Compute Average Directional Index (ADX) in Golang?

by creola.ebert , in category: SEO Tools , 9 months ago

How To Compute Average Directional Index (ADX) in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by bertha , 9 months ago

@creola.ebert 

To compute the Average Directional Index (ADX) in Golang, you can use the following code snippet:

 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
54
55
56
57
58
59
60
61
62
63
64
65
66
package main

import (
	"fmt"
)

func CalculateADX(high []float64, low []float64, close []float64, period int) []float64 {
	var dx []float64
	var adx []float64

	tr := make([]float64, len(close))
	plusDI := make([]float64, len(close))
	minusDI := make([]float64, len(close))
	adxValues := make([]float64, len(close))

	for i := 1; i < len(close); i++ {
		tr[i] = max(high[i]-low[i], max(abs(high[i]-close[i-1]), abs(low[i]-close[i-1])))
		plusDM := high[i] - high[i-1]
		minusDM := low[i-1] - low[i]
		if plusDM > minusDM && plusDM > 0 {
			plusDI[i] = plusDM
		}
		if minusDM > plusDM && minusDM > 0 {
			minusDI[i] = minusDM
		}
	}

	for i := period; i < len(close); i++ {
		sumTR := 0.0
		sumPlusDI := 0.0
		sumMinusDI := 0.0
		for j := 0; j < period; j++ {
			sumTR += tr[i-j]
			sumPlusDI += plusDI[i-j]
			sumMinusDI += minusDI[i-j]
		}
		adxValues[i] = 100 * (abs((sumPlusDI-sumMinusDI)/(sumPlusDI+sumMinusDI)) / (sumTR / float64(period)))
	}

	return adxValues
}

func max(a, b float64) float64 {
	if a > b {
		return a
	}
	return b
}

func abs(x float64) float64 {
	if x < 0 {
		return -x
	}
	return x
}

func main() {
	// Sample data
	high := []float64{100, 102, 98, 105, 110, 108, 112}
	low := []float64{95, 97, 93, 98, 102, 104, 106}
	close := []float64{98, 101, 96, 103, 108, 106, 110}
	period := 3

	adx := CalculateADX(high, low, close, period)
	fmt.Println(adx)
}


This code calculates the Average Directional Index (ADX) using the True Range (TR), Plus Directional Movement (+DM), Minus Directional Movement (-DM), and the ADX calculation formula. The CalculateADX function takes in high, low, and close prices of a financial instrument, as well as the period for the ADX calculation, and returns the ADX values for each period.


You can customize the input data and period as needed for your analysis.