Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Numpy exercise
  • pandas
  • Matplotlib
  • Data visulisation
  • EDA
  • Machin Learning
  • Deep Learning
  • NLP
  • Data science
  • ML Tutorial
  • Computer Vision
  • ML project
Open In App
Next Article:
How to Compute a Moving Average in PL/SQL?
Next article icon

How to Calculate Moving Averages in Python?

Last Updated : 07 Dec, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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:

ngjsdbgs

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
# Program to calculate moving average arr = [1, 2, 3, 7, 9] window_size = 3  i = 0 # Initialize an empty list to store moving averages moving_averages = []  # Loop through the array to consider # every window of size 3 while i < len(arr) - window_size + 1:        # Store elements from i to i+window_size     # in list to get the current window     window = arr[i : i + window_size]      # Calculate the average of current window     window_average = round(sum(window) / window_size, 2)          # Store the average of current     # window in moving average list     moving_averages.append(window_average)          # Shift window to right by one position     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:

SMAj = (1/k) * ∑ (i=j-1 to j+k-1)  ai

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
  • Using Pandas

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
# Program to calculate moving average using numpy  import numpy as np  arr = [1, 2, 3, 7, 9] window_size = 3  i = 0 # Initialize an empty list to store moving averages moving_averages = []  # Loop through the array t o #consider every window of size 3 while i < len(arr) - window_size + 1:      # Calculate the average of current window     window_average = round(np.sum(arr[       i:i+window_size]) / window_size, 2)          # Store the average of current     # window in moving average list     moving_averages.append(window_average)          # Shift window to right by one position     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
# Python program to calculate # simple moving averages using pandas import pandas as pd  arr = [1, 2, 3, 7, 9] window_size = 3  # Convert array of integers to pandas series numbers_series = pd.Series(arr)  # Get the window of series # of observations of specified window size windows = numbers_series.rolling(window_size)  # Create a series of moving # averages of each window moving_averages = windows.mean()  # Convert pandas series back to list moving_averages_list = moving_averages.tolist()  # Remove null entries from the list 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:

CMAt = (1/kt) * ∑ (i=0 to k)  ai

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
  • Using Pandas

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
# Program to calculate cumulative moving average # using numpy  import numpy as np  arr = [1, 2, 3, 7, 9]  i = 1 # Initialize an empty list to store cumulative moving # averages moving_averages = []  # Store cumulative sums of array in cum_sum array cum_sum = np.cumsum(arr);  # Loop through the array elements while i <= len(arr):      # Calculate the cumulative average by dividing     # cumulative sum by number of elements till      # that position     window_average = round(cum_sum[i-1] / i, 2)          # Store the cumulative average of     # current window in moving average list     moving_averages.append(window_average)          # Shift window to right by one position     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
# Python program to calculate # cumulative moving averages using pandas import pandas as pd  arr = [1, 2, 3, 7, 9] window_size = 3  # Convert array of integers to pandas series numbers_series = pd.Series(arr)  # Get the window of series of # observations till the current time windows = numbers_series.expanding()  # Create a series of moving averages of each window moving_averages = windows.mean()  # Convert pandas series back to list 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:

EMAt =  αat + (1- α)EMAt-1 

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
  • Using Pandas

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
# Program to calculate exponential # moving average using formula  import numpy as np  arr = [1, 2, 3, 7, 9] x=0.5  # smoothening factor  i = 1 # Initialize an empty list to # store exponential moving averages moving_averages = []  # Insert first exponential average in the list moving_averages.append(arr[0])  # Loop through the array elements while i < len(arr):      # Calculate the exponential     # average by using the formula     window_average = round((x*arr[i])+                            (1-x)*moving_averages[-1], 2)          # Store the cumulative average     # of current window in moving average list     moving_averages.append(window_average)          # Shift window to right by one position     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
# Python program to # calculate exponential moving averages import pandas as pd  arr = [1, 2, 3, 7, 9]  # Convert array of integers to pandas series numbers_series = pd.Series(arr)  # Get the moving averages of series # of observations till the current time moving_averages = round(numbers_series.ewm(   alpha=0.5, adjust=False).mean(), 2)  # Convert pandas series back to list moving_averages_list = moving_averages.tolist()  print(moving_averages_list) 

Output:

[1.0, 1.5, 2.25, 4.62, 6.81]

Applications

  1. Time-Series Analysis: It is used to smooth out short-term variation and highlight long-term observations such as trends and cycles.
  2. Financial Analysis: It is used in financial analysis of stock markets like calculation of stock prices, returns, and analyzing trends of the market.
  3. Environmental Engineering: It is used in analyzing environmental conditions by considering various factors such as the concentration of pollutants, etc.
  4. Computer Performance Analysis: It is used in analyzing computer performance by calculating metrics such as average CPU utilization, average process queue length, etc.

Next Article
How to Compute a Moving Average in PL/SQL?

S

saxenaanjali239
Improve
Article Tags :
  • Python
  • Python-numpy
  • Python-pandas
Practice Tags :
  • python

Similar Reads

  • How to Calculate an Exponential Moving Average in Python?
    Moving Averages are financial indicators which are used to analyze stock values over a long period of time. i.e. Average value for that long period is calculated. Exponential Moving Averages (EMA) is a type of Moving Averages. It helps users to filter noise and produce a smooth curve. In Moving Aver
    3 min read
  • How to calculate MOVING AVERAGE in a Pandas DataFrame?
    Calculating the moving average in a Pandas DataFrame is used for smoothing time series data and identifying trends. The moving average, also known as the rolling mean, helps reduce noise and highlight significant patterns by averaging data points over a specific window. In Pandas, this can be achiev
    7 min read
  • Calculate Moving Averages in SQL
    In data analysis, smoothing out short-term fluctuations in time-series data is essential for identifying long-term trends. One effective method for achieving this is through the moving average, a widely used technique in business analytics, finance and forecasting. SQL provides several ways to compu
    4 min read
  • How to Calculate MAPE in Python?
    In this article, we will see how to compute one of the methods to determine forecast accuracy called the Mean. Absolute Percentage Error (or simply MAPE) also known as Mean Absolute Percentage Deviation (MAPD) in python. The MAPE term determines how better accuracy does our forecast gives. The 'M' i
    4 min read
  • How to Compute a Moving Average in PL/SQL?
    A moving average is a technique we use to analyze and determine some specific trends in our provided data. Through moving averages, we can analyze and determine trends in our data along with some other benefits like noise reduction in our data. In this article, we are going to learn about "how to co
    5 min read
  • How to Calculate Mean Absolute Error in Python?
    When building machine learning models, our aim is to make predictions as accurately as possible. However, not all models are perfect some predictions will surely deviate from the actual values. To evaluate how well a model performs, we rely on error metrics. One widely used metric for measuring pred
    4 min read
  • How to Calculate Weighted Average in Pandas?
    A weighted average is a computation that considers the relative value of the integers in a data collection. Each value in the data set is scaled by a predefined weight before the final computation is completed when computing a weighted average. Syntax: def weighted_average(dataframe, value, weight):
    3 min read
  • How to Calculate Weighted Average?
    Weighted Average is a method of finding the average of a set of numbers where each number (or data point) is given a weight based on its importance or relevance. Weighted averages are commonly used in various fields such as finance, economics, education, and statistics, where different data points m
    7 min read
  • How to Calculate Autocorrelation in Python?
    Correlation generally determines the relationship between two variables. Correlation is calculated between the variable and itself at previous time steps, such a correlation is called Autocorrelation. Method 1 : Using lagplot() The daily minimum temperatures dataset is used for this example. As the
    3 min read
  • How to Calculate Weighted Average in Excel
    Understanding how to calculate a weighted average in Excel can be a game-changer for anyone dealing with data analysis, financial modeling, or academic grading. Unlike a simple average, a weighted average considers the relative importance of each data point, providing a more accurate reflection of t
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences