How To Compute Moving Averages (MA) in Golang?

by lindsey.homenick , in category: Third Party Scripts , 5 months ago

How To Compute Moving Averages (MA) in Golang?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by mallory_cormier , 5 months ago

@lindsey.homenick 

To compute moving averages in Golang, 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
30
package main

import "fmt"

func calculateMovingAverage(data []float64, windowSize int) []float64 {
    movingAverages := make([]float64, len(data)-windowSize+1)
    sum := 0.0

    for i := 0; i < windowSize; i++ {
        sum += data[i]
    }

    movingAverages[0] = sum / float64(windowSize)

    for i := windowSize; i < len(data); i++ {
        sum = sum - data[i-windowSize] + data[i]
        movingAverages[i-windowSize+1] = sum / float64(windowSize)
    }

    return movingAverages
}

func main() {
    data := []float64{10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
    windowSize := 3

    movingAverages := calculateMovingAverage(data, windowSize)

    fmt.Println(movingAverages)
}


In this code, the calculateMovingAverage function takes an array of data and a window size as input and returns an array of moving averages. It calculates the moving average by iterating through the data and computing the average of the current window. The moving average is then stored in the movingAverages slice.


You can customize the data array and windowSize variable according to your requirements. When you run this code, it will output the moving averages for the given data array and window size.