Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 266
Dorrin Samadian Avatar asked May 02 '26 17:05

Dorrin Samadian


1 Answers

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])
like image 104
trincot Avatar answered May 05 '26 22:05

trincot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!