Exponential moving average in python

 


Write a program (you can use MATLAB or Octave or Python) that will smooth an array of data using an exponential moving average. For the input data we assume a row vector with N elements. We use the following expression for the average: Xavg.k = axavg.X-1 + (1 - a) · Xk, except for k = 1, where Xavg.1 = x;. You can use the following statement (for MATLAB) to create a row vector of data with noise from a normal distribution with a mean of 5.0 and a standard deviation of 3.0 to test your program: • inputData = 5.0 + 3.0 - randn(1,100); a = 0.8; Please use only basic operators like assignment, comparison, conditional statement, and loops. Do not use built in functions or advanced possibilities of a specific programming language (e.g. vectorization in MATLAB).

Solution:

import numpy as np
import random
def exponential_smoothing(series, alpha):
"""given a series and alpha, return series of expoentially smoothed points"""
results = np.zeros_like(series)
results[0] = series[0]
for t in range(1, series.shape[0]):
results[t] = alpha * series[t] + (1 - alpha) * results[t - 1]

return results

Data=random.sample(range(1,100), 10)
inputData=[]
for i in Data:
num= 5.0+3.0*float(i)
inputData.append(num)
print(inputData)
inputData = np.array(inputData).reshape(len(inputData),1)
result=exponential_smoothing(inputData,0.8)
answer=np.array(result).reshape(1,len(result))
for i in answer:
print(i)







Share on Google Plus

About Ashadullah Shawon

I am Ashadullah Shawon. I am a Software Engineer. I studied Computer Science and Engineering (CSE) at RUET. I Like To Share Knowledge. Learn More: Click Here
    Blogger Comment
    Facebook Comment

1 comments:

  1. The best approach to wrap furniture for moving relies upon particulars of your turn. Is it highway move, the nation over, or neighborhood moving around the square? Stacking PODS or worldwide steel trailer, or moving to long haul stockpiling? Europa-Road targonca szállítás Debrecen

    ReplyDelete