# 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)
print(i)