How To Compute Simple Moving Average (SMA) in F#?

by thelma.stanton , in category: General Help , 2 months ago

How To Compute Simple Moving Average (SMA) in F#?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aliya.yundt , 2 months ago

@thelma.stanton 

To compute the Simple Moving Average (SMA) in F#, you can follow these steps:

  1. Define the function for calculating the SMA:
1
2
3
4
5
6
7
8
let sma (values: float list) (n: int) =
    let rec loop sum count = function
        | [] -> sum / float count
        | x::xs ->
            let count' = min n (count + 1)
            let sum' = sum + x - (if count = n then List.head xs else 0.0)
            loop sum' count' xs
    loop 0.0 0 values


  1. Call the sma function with a list of values and the number of periods for the moving average:
1
2
3
4
5
let values = [10.0; 15.0; 20.0; 25.0; 30.0; 35.0; 40.0]
let n = 3
let result = sma values n

printfn "Simple Moving Average (SMA) for the given values: %f" result


In this example, the sma function takes a list of floating-point values and an integer n representing the number of periods for the moving average calculation. The function then calculates the SMA using a loop that iterates through the list of values and keeps track of the sum and count of elements.


Finally, the computed SMA value is printed to the console using printfn.


You can customize the list of values and the number of periods based on your specific requirements.