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

by annabell_mcdermott , in category: SEO Tools , 9 months ago

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

Facebook Twitter LinkedIn Telegram Whatsapp Pocket

1 answer

Member

by vinnie , 9 months ago

@annabell_mcdermott 

To calculate the Average True Range (ATR) in Groovy, 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
def calculateATR(List<Double> high, List<Double> low, List<Double> close, int period) {
    def atrValues = []
    
    for (int i = 0; i < close.size() - period; i++) {
        def trValues = []
        
        for (int j = i; j < i + period; j++) {
            def tr = Math.max(high.get(j) - low.get(j),
                              Math.max(Math.abs(high.get(j) - close.get(j)),
                                       Math.abs(low.get(j) - close.get(j))))
            
            trValues.add(tr)
        }
        
        def atr = trValues.sum() / period
        atrValues.add(atr)
    }
    
    return atrValues
}


In this code snippet, the function calculateATR takes the lists of high, low, and close prices, as well as the period for which you want to calculate the ATR. It calculates the True Range (TR) for each period based on the high, low, and close prices, and then calculates the ATR.


Here's an example of how to use the calculateATR function with sample data:

1
2
3
4
5
6
7
8
def high = [10.5, 12.0, 11.5, 12.5, 13.0, 14.0, 14.5, 15.0]
def low = [9.5, 10.5, 10.0, 11.0, 11.5, 12.0, 13.0, 13.5]
def close = [10.0, 11.0, 10.5, 12.0, 12.5, 13.5, 14.0, 14.0]
def period = 5

def atrValues = calculateATR(high, low, close, period)

println atrValues


This will output the ATR values for each period based on the sample data provided.