# Moving Average Method for Time-series forecasting In this post, you will learn about the concepts of the moving average method in relation to time-series forecasting. You will get to learn Python examples in relation to training a moving average machine learning model.  The following are some of the topics which will get covered in this post:

• What is the moving average method?
• Why use the moving average method?
• Python code example for the moving average methods

## What is Moving Average method?

The moving average is a statistical method used for forecasting long-term trends. The technique represents taking an average of a set of numbers in a given range while moving the range. For example, let’s say the sales figure of 6 years from 2000 to 2005 is given and it is required to calculate the moving average taking three years at a time. In order to calculate the moving average, one would take an average of 2000-2002, 2001-2003, 2002-2004, 2003-2005, and 2004-2006. Let’s understand it with example.

Plotting the moving average from the above table would look like the following. The moving average are usually plotted for visualisation purpose.

There are different variations of moving average technique (also termed as rolling mean) such as some of the following:

• Simple moving average (SMA): Simple moving average takes the sliding window over a given time period as shown in the above example (3 years interval). It can be termed as an equally weighted mean of n records.
• Cumulative moving average
• Weighted moving average
• Exponential moving average

## Why use Moving Average method?

The moving average method is used with time-series data to smooth out short-term fluctuations and long-term trends. The application of moving average is found in the science & engineering field and financial applications.

## Python Example for Moving Average Method

Here is the Python code for calculating moving average for sales figure. The code that calculates the moving average or rolling mean is df[‘Sales’].rolling(window=3).mean(). The example below represents the calculation of simple moving average (SMA).

import pandas as pd
import numpy as np
#
# Create a numpy array of years and sales
#
arr = np.array([['2000', 4], ['2001',7],
['2002',4], ['2003',9],
['2004',7], ['2005',10]])
#
# Transpose array
#
arr_tp = arr.transpose()
#
# Create a dataframe
#
df = pd.DataFrame({'Years': arr_tp, 'Sales': arr_tp})
#
# Calculate rolling mean
#
df['MA'] = df['Sales'].rolling(window=3).mean()
#
# 