I want to calculate the increased moving averages.
My main aim is to get increased MAs, such that first MA is average of first value, next MA is Average of first 2 values, next MA is Average of first 4 values, next MA is Average of first 6 values and so on.
How can I do this using numpy library in Python?
I am doing my analysis on time series data using Python. I am also interested in moving averages, to calculate moving averages for my target variable, I used the following function to calculate MA over my target variable.
def movingaverage(values, avg_number):
weights = np.repeat(1.0, avg_number)/avg_number
smas = np.convolve(values, weights, 'valid')
return smas
In this function, I supply my pandas Series and the average number to calc. corresponding averages.
Now, I want to calculate increased moving averages. like in the above the averages are being calculated over fixed number, say 90.
But, in case of reduced/increased moving averages, this number will reduce/increase at each next value.
My main aim is to get increased MAs, such that first MA is average of first value, next MA is Average of first 2 values, next MA is Average of first 4 values, next MA is Average of first 6 values and so on.
How can I do this using numpy library in Python?
If input is [1,5,3,6,8,4,6,8,4,2,3,5,8,6,4] and output will be increased moving averages like [1,3,3,3.75....]
You can use cumsum and np.arange i.e
x = np.array([1,5,3,6,8,4,6,8,4,2,3,5,8,6,4])
y = x.cumsum()/np.arange(1,len(x)+1)
Output :
array([ 1. , 3. , 3. , 3.75 , 4.6 ,
4.5 , 4.71428571, 5.125 , 5. , 4.7 ,
4.54545455, 4.58333333, 4.84615385, 4.92857143, 4.86666667])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With