How To Compute Moving Averages (MA) using Scala?

Member

by melvina , in category: Technology , 9 months ago

How To Compute Moving Averages (MA) using Scala?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kim , 9 months ago

@melvina 

To compute Moving Averages (MA) using Scala, you can use the following code snippet:

1
2
3
4
5
6
7
8
9
def movingAverage(data: List[Double], windowSize: Int): List[Double] = {
  data.sliding(windowSize).map(window => window.sum / windowSize).toList
}

// Example usage
val data = List(1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
val windowSize = 3
val maValues = movingAverage(data, windowSize)
println(maValues)


In this code snippet, the movingAverage function takes a list of data points and a window size as input arguments. It then calculates the moving average by sliding a window of the specified size over the data points and calculating the average for each window. The function returns a list of moving average values.


You can adjust the data and windowSize variables to calculate moving averages for different datasets and window sizes.