How To Calculate Williams %R in Perl?

by lucas.hilpert , in category: Technical Analysis , a month ago

How To Calculate Williams %R in Perl?

Facebook Twitter LinkedIn Whatsapp

1 answer

by noemie_rogahn , a month ago

@lucas.hilpert 

Williams %R is a technical indicator used in stock and commodities trading to help identify overbought or oversold conditions. It is calculated using the following formula:


%R = (Highest High - Close)/(Highest High - Lowest Low) * -100


Where:

  • Highest High = the highest price the stock reached in the look-back period
  • Lowest Low = the lowest price the stock reached in the look-back period
  • Close = the closing price of the stock on the current day


Here is an example code snippet in Perl to calculate Williams %R:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
sub williams_r {
    my ($data, $period) = @_;
    
    my @w_r;
    
    for (my $i = $period - 1; $i < scalar(@$data); $i++) {
        my $highest_high = max(@$data[$i - $period + 1 .. $i]);
        my $lowest_low = min(@$data[$i - $period + 1 .. $i]);
        my $close = @$data[$i];
        
        my $r = ($highest_high - $close) / ($highest_high - $lowest_low) * -100;
        push @w_r, $r;
    }
    
    return @w_r;
}

# Example usage
my @prices = (12.34, 13.45, 11.98, 14.23, 15.67, 16.34, 14.56, 13.67);
my $period = 5;

my $w_r_values = williams_r(@prices, $period);
print join(", ", @$w_r_values) . "
";


In this code snippet, we define a subroutine williams_r that takes an array reference of stock prices and a period as input, and calculates Williams %R for each day in the data. We then calculate the highest high, lowest low, and closing price for each day and use them to calculate %R. Finally, we return an array reference of %R values.


You can customize the input data (@prices) and the period to suit your specific requirements.