How To Calculate Average True Range (ATR) using Perl?

Member

by norberto , in category: Technical Analysis , a month ago

How To Calculate Average True Range (ATR) using Perl?

Facebook Twitter LinkedIn Whatsapp

1 answer

Member

by caitlyn , a month ago

@norberto 

To calculate the Average True Range (ATR) using Perl, you can use the following formula:

  1. First, calculate the True Range for each period. True Range is the maximum of the following three values: High of the current period - Low of the current period Absolute value of High of the current period - Close of the previous period Absolute value of Low of the current period - Close of the previous period
  2. Next, calculate the ATR for the desired number of periods by taking the average of the True Range values over those periods.


Here is an example of a Perl code that calculates the ATR for a given set of price data:

 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
use strict;
use warnings;

my @highs = (50, 55, 60, 58, 65);
my @lows = (45, 48, 55, 54, 60);
my @closes = (48, 53, 58, 56, 62);
my $periods = 4;

my @tr_values;
my $atr = 0;

for (my $i = 1; $i < scalar(@highs); $i++) {
    my $tr = max($highs[$i] - $lows[$i], abs($highs[$i] - $closes[$i - 1]), abs($lows[$i] - $closes[$i - 1]));
    push @tr_values, $tr;
}

for (my $i = 0; $i < $periods-1; $i++) {
    $atr += $tr_values[$i];
}

$atr /= $periods;

print "Average True Range: $atr
";

sub max {
    my $max = shift;
    foreach my $value (@_) {
        $max = $value if $value > $max;
    }
    return $max;
}


In this code, the @highs, @lows, and @closes arrays represent the high, low, and close prices for each period. The $periods variable represents the number of periods for which you want to calculate the ATR.


The code calculates the True Range for each period, then calculates the ATR by taking the average of the True Range values over the specified number of periods. Finally, it prints the calculated ATR value.