How To Calculate Simple Moving Average (SMA) using Perl?

Member

by maiya , in category: Technology , 10 months ago

How To Calculate Simple Moving Average (SMA) using Perl?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by trycia.jones , 10 months ago

@maiya 

To calculate a simple moving average (SMA) using Perl, 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
use strict;
use warnings;

sub sma {
    my ($data, $period) = @_;
    my @sma_values;

    for (my $i = $period - 1; $i < scalar(@$data); $i++) {
        my $sum = 0;
        for (my $j = $i - ($period - 1); $j <= $i; $j++) {
            $sum += $data->[$j];
        }
        my $average = $sum / $period;
        push @sma_values, $average;
    }

    return @sma_values;
}

# Example usage
my @data = (2, 4, 6, 8, 10, 12, 14, 16, 18, 20);
my $period = 3;

my $sma_values = sma(@data, $period);

for my $i (0 .. $#{$sma_values}) {
    print "SMA for period $period at index $i: $sma_values->[$i]
";
}


In this code snippet, the sma function takes two arguments: an array reference containing the data points and the period for which you want to calculate the SMA. The function loops through the data array and calculates the average of the last $period data points to get the SMA value. Finally, it returns an array reference containing the SMA values.


You can test the code by creating a sample data array and calling the sma function with the data array and the desired period. The resulting SMA values will be printed to the console.