In this discussion we are going to see how to Calculate Moving Averages in Python in this discussion we will write a proper explanation
What is Moving Averages?
Moving Averages, a statistical method in data analysis, smooths fluctuations in time-series data to reveal underlying trends. Calculating the average within a specified window and shifting it through the dataset, provides a clearer trend representation. Widely applied in finance, economics, and signal processing, Moving Averages come in types like Simple Moving Average (SMA) and Exponential Moving Average (EMA), each with unique weighting methods for data points.
Consider the set of n observations and k be the size of the window for determining the average at any time t. Then moving average list is calculated by initially taking the average of the first k observations present in the current window and storing it in the list. Now, the window is expanded according to the condition of the moving average to be determined and again average of the elements present in the window is calculated and stored in the list. This process is continued until the window has reached the end of the set.Â
Example:
Given a list of five integers arr=[1, 2, 3, 7, 9] and we need to calculate moving averages of the list with window size specified as 3. We will first calculate average of first 3 elements and that will be stored as first moving average. Then window will be shifted one position to the right and again average of elements present in the window will be calculated and stored in the list. Similarly, the process will repeat till the window reaches the last element of the array. Following is the illustration of the above approach:
Code Implementation of the above approach:
Here Python code computes the moving averages of a given array (arr
) with a window size of 3. It iterates through the array, calculating the average for each window and storing the results in a list called moving_averages
. The final output is the list [2.0, 4.0, 6.33]
.
Python3
arr = [ 1 , 2 , 3 , 7 , 9 ]
window_size = 3
i = 0
moving_averages = []
while i < len (arr) - window_size + 1 :
window = arr[i : i + window_size]
window_average = round ( sum (window) / window_size, 2 )
moving_averages.append(window_average)
i + = 1
print (moving_averages)
|
Output:
[2.0, 4.0, 6.33]
Calculate Moving Averages in Python
There are mainly three types of method for Calculate Moving Averages in Python which are following
- Simple Moving Averages
- Cumulative Moving Averages
- Exponential Moving Averages
Simple Moving Average
SMA is calculated by taking the unweighted mean of k (size of the window) observations at a time that is present in the current window. It is used for analyzing trends.
Formula:
where,
- SMAj = Simple Moving Average of jth window
- k = size of the window
- ai = ith element of the set of observations
There are various method for calculate simple moving averages in python, here we are explaining some generally used method for Calculate Moving Averages in Python .
Using Numpy
Numpy module of Python provides an easy way to calculate the simple moving average of the array of observations. It provides a method called numpy.sum() which returns the sum of elements of the given array. A moving average can be calculated by finding the sum of elements present in the window and dividing it with window size.
Example : In this example below Python code employs NumPy to swiftly compute moving averages for a given array (arr
) with a window size of 3. It iterates through the array, calculates window averages using NumPy’s sum
function, and appends them to moving_averages
. The final output is the list [2.0, 4.0, 6.33]
. NumPy enhances efficiency and simplifies array operations in the code.
Python3
import numpy as np
arr = [ 1 , 2 , 3 , 7 , 9 ]
window_size = 3
i = 0
moving_averages = []
while i < len (arr) - window_size + 1 :
window_average = round (np. sum (arr[
i:i + window_size]) / window_size, 2 )
moving_averages.append(window_average)
i + = 1
print (moving_averages)
|
Output:
[2.0, 4.0, 6.33]
Using Pandas
Pandas module of Python provides an easy way to calculate the simple moving average of the series of observations. It provides a method called pandas.Series.rolling(window_size) which returns a rolling window of specified size. The mean of the window can be calculated by using pandas.Series.mean() function on the object of window obtained above. pandas.Series.rolling(window_size) will return some null series since it need at least k (size of window) elements to be rolling.Â
Example : In this example the Python code efficiently calculates the first element and simple moving averages for an array (`arr`) using Pandas with a window size of 3. The output, `[1.0, 2.0, 4.0, 6.33]`, reflects the computed averages. Pandas streamlines the process of handling rolling windows and calculating moving averages.
Python
import pandas as pd
arr = [ 1 , 2 , 3 , 7 , 9 ]
window_size = 3
numbers_series = pd.Series(arr)
windows = numbers_series.rolling(window_size)
moving_averages = windows.mean()
moving_averages_list = moving_averages.tolist()
final_list = moving_averages_list[window_size - 1 :]
print (final_list)
|
Output:
[2.0, 4.0, 6.33]
Cumulative Moving Average
CMA is calculated by taking the unweighted mean of all the observations up to the time of calculation. It is used for time series analysis.
Formula:
where:
- CMAt = Cumulative Moving Average at time t
- kt = number of observations upto time t
- ai = ith element of the set of observations
There are various method for calculate cumulative moving averages in python, here we are explaining some generally used method for Calculate Moving Averages in Python .
Using Numpy
Numpy module of Python provides an easy way to calculate the cumulative moving average of the array of observations. It provides a method called numpy.cumsum() which returns the array of the cumulative sum of elements of the given array. A moving average can be calculated by dividing the cumulative sum of elements by window size.
Example : In this example this Python code uses NumPy to efficiently compute cumulative moving averages for an array (arr
). It calculates cumulative sums, iterates through the array, and stores the cumulative averages. The output, [1.0, 1.5, 2.0, 3.25, 4.4]
, reflects the cumulative moving averages. NumPy simplifies the computation, improving program efficiency.
Python
import numpy as np
arr = [ 1 , 2 , 3 , 7 , 9 ]
i = 1
moving_averages = []
cum_sum = np.cumsum(arr);
while i < = len (arr):
window_average = round (cum_sum[i - 1 ] / i, 2 )
moving_averages.append(window_average)
i + = 1
print (moving_averages)
|
Output :
[1.0, 1.5, 2.0, 3.25, 4.4]
Using Pandas
Pandas module of Python provides an easy way to calculate the cumulative moving average of the series of observations. It provides a method called pandas.Series.expanding() which returns a window spanning over all the observations up to time t. Mean of the window can be calculated by using pandas.Series.mean() function on the object of window obtained above.Â
Example : In this example the Python code uses Pandas to swiftly compute cumulative moving averages for an array (`arr`) with a window size of 3. Converting the array to a Pandas Series, it applies an expanding window, calculates the mean, and outputs the list `[1.0, 1.5, 2.0, 3.25, 4.4]`. Pandas simplifies the process of handling expanding windows and computing cumulative moving averages.
Python
import pandas as pd
arr = [ 1 , 2 , 3 , 7 , 9 ]
window_size = 3
numbers_series = pd.Series(arr)
windows = numbers_series.expanding()
moving_averages = windows.mean()
moving_averages_list = moving_averages.tolist()
print (moving_averages_list)
|
Output :
[1.0, 1.5, 2.0, 3.25, 4.4]
Exponential Moving Average
EMA is calculated by taking the weighted mean of the observations at a time. The weight of the observation exponentially decreases with time. It is used for analyzing recent changes.
Formula:
where:
- EMAt = Exponential Moving Average at time t
- α = degree of decrease in weight of observation with time
- at = observation at time t
There are various method for Calculate Exponential Moving Averages in Python, here we are explaining some generally used method for Calculate Moving Averages in Python .
Using Numpy
In this example, Python code calculates exponential moving averages for an array (arr
) using a specified smoothing factor (x
). It iterates through the array, applying the exponential moving average formula, and stores the results in a list. The output, moving_averages
, is the list of computed exponential moving averages.
Python
import numpy as np
arr = [ 1 , 2 , 3 , 7 , 9 ]
x = 0.5
i = 1
moving_averages = []
moving_averages.append(arr[ 0 ])
while i < len (arr):
window_average = round ((x * arr[i]) +
( 1 - x) * moving_averages[ - 1 ], 2 )
moving_averages.append(window_average)
i + = 1
print (moving_averages)
|
Output :
[1, 1.5, 2.25, 4.62, 6.81]
Using Pandas
Pandas module of Python provides an easy way to calculate the exponential moving average of the series of observations. It provides a method called pandas.Series.ewm.mean() calculates the exponential moving average of given observations. pandas.Series.ewm() takes a parameter called smoothening factor i.e. degree with which weight of observation decrease with time. The value of a smoothening factor is always between 0 and 1.
Example : In this example, Python code employs Pandas to calculate exponential moving averages (EWMA) for an array (arr
) with a smoothing factor of 0.5. Converting the array to a Pandas Series, it applies EWMA, rounding the results to two decimal places, and outputs the list [1.0, 1.67, 2.67, 4.83, 7.42]
.
Python
import pandas as pd
arr = [ 1 , 2 , 3 , 7 , 9 ]
numbers_series = pd.Series(arr)
moving_averages = round (numbers_series.ewm(
alpha = 0.5 , adjust = False ).mean(), 2 )
moving_averages_list = moving_averages.tolist()
print (moving_averages_list)
|
Output:
[1.0, 1.5, 2.25, 4.62, 6.81]
Applications
- Time-Series Analysis: It is used to smooth out short-term variation and highlight long-term observations such as trends and cycles.
- Financial Analysis: It is used in financial analysis of stock markets like calculation of stock prices, returns, and analyzing trends of the market.
- Environmental Engineering: It is used in analyzing environmental conditions by considering various factors such as the concentration of pollutants, etc.
- Computer Performance Analysis: It is used in analyzing computer performance by calculating metrics such as average CPU utilization, average process queue length, etc.
Share your thoughts in the comments
Please Login to comment...