Demand forecasting : Moving average model

The moving average model is the simplest forescasting model. It assumes that the future demand is a function of recent demand and is expressed as: $$f_t = \frac{1}{n} \sum_{i=0}^{n} d_{t-i}$$ 
where, for a given period, t:
f  is the forecast, 
d is the demand, and
n is the number of periods we take the average for

The moving average model gets more "naive" and follows the demand in the latest periods as n gets smaller. It is simplest when n=1 and forecast follows the last observed demand.It will be highly sensitive to any variations in demand as well as to any noise in the demand data. To decrease the sensitivity, one must consider a higher value for n. 

While the advantage of the moving average model is that it is highly simple, its drawbacks include: 
1. Inability to extrapolate to identify potential trends farther into the future 
2. Inability to factor in seasonality, and 
3. A flat historical weighing that does not allow you to assign higher weights to select demand periods.

Here is the python implementation of the moving average model:
 

# This function takes demand and the period that moving average is calculated 
# It returns the forecast

def moving_avg(d,period):
    d=np.append(d,[np.nan])
    f=np.full(len(d),np.nan)
    
    for t in range (period,len(d)):
        f[t]=round(np.mean(d[t-period:t]),2)
       
    df=pd.DataFrame.from_dict({'Demand':d,'Forecast':f})
    
    return df

# For my test, I have used a csv file with demand data for the last 50 periods.
# The contents were generated using the random() function in excel.

df_read=pd.read_csv('Demand50.csv')
demand=df_read.values
period=6
df_avg=moving_avg(demand,period)
df_avg.index.name ='Period'
df_avg[['Demand','Forecast']].plot() 


Comments