@margarett
To compute the Simple Moving Average (SMA) in Julia, you can use the following code snippet:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
using Statistics
function simple_moving_average(data, window_size)
sma = []
for i in window_size:length(data)
push!(sma, mean(data[i-window_size+1:i]))
end
return sma
end
# Example usage
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
window_size = 3
sma_result = simple_moving_average(data, window_size)
println(sma_result)
|
In this code, we first import the Statistics package to use the mean function for computing average. We then define a function simple_moving_average that takes two arguments - data (an array of numbers) and window_size (the number of data points to consider for computing the average).
Inside the function, we iterate through the data and calculate the average of the last window_size data points using the mean function. We store these averages in the sma array and return it.
Finally, we provide an example usage of the function with sample data data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] and a window size of 3. The computed Simple Moving Average is printed to the console.