How To Calculate Moving Averages (MA) in Erlang?

by dalton_moen , in category: Third Party Scripts , 4 months ago

How To Calculate Moving Averages (MA) in Erlang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by deron , 4 months ago

@dalton_moen 

To calculate Moving Averages in Erlang, you can use the following code snippet:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
moving_average([], _, _, _, ResultList) -> lists:reverse(ResultList);
moving_average([Head|Tail], Period, Count, Sum, ResultList) ->
    case Count == 0 of
        true ->
            Avg = Sum / Period,
            moving_average(Tail, Period, 1, Head, [Avg | ResultList]);
        false ->
            NewSum = Sum + Head,
            NewCount = Count + 1,
            moving_average(Tail, Period, NewCount, NewSum, ResultList)
    end.

%% Example Usage
Data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
Period = 3,
moving_average(Data, Period, 0, 0, []).


In this code snippet, the moving_average/5 function takes the Data list, the Period for the moving average calculation, a Count variable to keep track of the number of elements considered in the moving average calculation, a Sum variable to keep track of the sum of elements, and a ResultList to store the moving averages.


The function recursively processes the input list one element at a time, calculating the moving average based on the specified period. It updates the sum and count variables accordingly and adds the calculated average to the ResultList. Finally, it returns the ResultList as the output.


You can test the moving_average/5 function by providing a sample data list and the period for moving average calculation as shown in the example usage section.