How To Compute Moving Averages (MA) in F#?

by alysson_lynch , in category: General Help , 2 months ago

How To Compute Moving Averages (MA) in F#?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by keegan.towne , 2 months ago

@alysson_lynch 

To compute moving averages in F#, you can create a function that takes a list of numbers and a window size as input, then calculates the moving average for each window in the list. Here's an example implementation:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
let movingAverage (numbers: float list) (windowSize: int) =
    let rec movingAverageHelper (numbers: float list) (windowSize: int) =
        let sum = List.sum (List.take windowSize numbers)
        let average = sum / float windowSize
        match numbers with
        | [] -> []
        | head::tail ->
            if List.length tail < windowSize then []
            else average::(movingAverageHelper tail windowSize)
    
    movingAverageHelper numbers windowSize


You can then call this function with a list of numbers and a desired window size to compute the moving averages. Here's an example usage:

1
2
3
4
5
6
let numbers = [1.0; 2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0; 9.0; 10.0]
let windowSize = 3

let averages = movingAverage numbers windowSize

printfn "Moving Averages: %A" averages


This will output:

1
Moving Averages: [2.0; 3.0; 4.0; 5.0; 6.0; 7.0; 8.0]


This example calculates moving averages with a window size of 3 for the list of numbers provided. You can adjust the window size or input numbers as needed for your specific use case.