The Simple Moving Average (SMA) is the most basic time series smoothing technique. It computes the unweighted mean of a sliding window of consecutive observations, producing a smoother signal that filters out short-term fluctuations and highlights longer-term trends.
Given a list of numeric values and a window size k, compute the SMA for each valid window position.
For each position i from 0 to n - k, compute the average of k consecutive values:
SMA[i]=k1j=0∑k−1x[i+j]The output has length n - k + 1, where n is the input length.
Input:
values = [1, 2, 3, 4, 5], window_size = 3
Output:
[2.0, 3.0, 4.0]
Three windows: (1+2+3)/3=2.0, (2+3+4)/3=3.0, (3+4+5)/3=4.0.
Input:
values = [10, 20, 30, 40], window_size = 2
Output:
[15.0, 25.0, 35.0]
Three windows of size 2: (10+20)/2=15.0, (20+30)/2=25.0, (30+40)/2=35.0.
Loop from i = 0 to len(values) - window_size. At each position, take the slice values[i:i+window_size], sum it, and divide by window_size.
For efficiency, you can maintain a running sum: subtract the element leaving the window and add the element entering. But the straightforward approach of summing each window works within the time limit.
Sign in to take notes on this problem
Accepts: array
Accepts: number
The Simple Moving Average (SMA) is the most basic time series smoothing technique. It computes the unweighted mean of a sliding window of consecutive observations, producing a smoother signal that filters out short-term fluctuations and highlights longer-term trends.
Given a list of numeric values and a window size k, compute the SMA for each valid window position.
For each position i from 0 to n - k, compute the average of k consecutive values:
SMA[i]=k1j=0∑k−1x[i+j]The output has length n - k + 1, where n is the input length.
Input:
values = [1, 2, 3, 4, 5], window_size = 3
Output:
[2.0, 3.0, 4.0]
Three windows: (1+2+3)/3=2.0, (2+3+4)/3=3.0, (3+4+5)/3=4.0.
Input:
values = [10, 20, 30, 40], window_size = 2
Output:
[15.0, 25.0, 35.0]
Three windows of size 2: (10+20)/2=15.0, (20+30)/2=25.0, (30+40)/2=35.0.
Loop from i = 0 to len(values) - window_size. At each position, take the slice values[i:i+window_size], sum it, and divide by window_size.
For efficiency, you can maintain a running sum: subtract the element leaving the window and add the element entering. But the straightforward approach of summing each window works within the time limit.
Sign in to take notes on this problem
Accepts: array
Accepts: number