What is wrong with the function below for calculating simple moving average?

372 views Asked by At

I have written the function below in order to find the SMA of a csv file according to the desired SMA formula, However, something is wrong with my formula which I can't figure it out.

def SMA_calculation(t, w):
    s = np.size(t)
    g = np.zeros(s)
    for i in range(0, s):
        if i < w-1:
            g[i] = np.NaN
        else:
            g[i] = np.mean(t[i-w:i])
    return g
2

There are 2 answers

0
trincot On

The first time the else block is executed, is when i == w - 1. This means the argument passed to mean is t[-1:w-1]. This is wrong. The first slice you want to get the mean of is t[:w]. So you need to add one to both start and end indices of the slice:

g[i] = np.mean(t[i-w+1:i+1])
0
Parham Hasani On

To understand the error I change the code like this:

import numpy as np
t = np.array([1,2,3,4,5,6])
def SMA_calculation(t, w):
    s = np.size(t)
    g = np.zeros(s)
    for i in range(0, s):
        if i < w-1:
            # g[i] = np.NaN
            print(i)
        else:
            # g[i] = np.mean(t[i-w:i])
            print(f"0{i}")
            print(t[i-w:i])
w = 3
SMA_calculation(t,w)
>>
0
1
02
[]
03
[1 2 3]
04
[2 3 4]
05
[3 4 5]

you can see your function has a null array. to solve this issue you can convert t[i-w:I] to t[i-w+1:i]. good luck ;)