The Wayback Machine - https://web.archive.org/web/20241010014129/https://www.geeksforgeeks.org/how-to-calculate-moving-average-in-a-pandas-dataframe/
Open In App

How to calculate MOVING AVERAGE in a Pandas DataFrame?

Last Updated : 15 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In this article, we will be looking at how to calculate the moving average in a Pandas data frame. Moving Average calculates the average of data over some periods. The moving average is also known as the rolling mean and is calculated by averaging data of the time series within k periods. 

Calculating Moving Averages using Pandas

There are various methods to calculate the moving average in Pandas DataFrame, we are discussing some generally used methods for calculating the moving average in Pandas DataFrame which are the following

The link to the data used is RELIANCE.NS_

Simple Moving Average (SMA) Syntax

To calculate a Simple Moving Average in Pandas DataFrame we will use Pandas dataframe.rolling() action that helps us to make calculations on a rolling window. On the rolling window, we will use .mean() function to calculate the mean of each window.

Syntax: DataFrame.rolling(window, min_periods=None, center=False, win_type=None, on=None, axis=0).mean()

Parameters :

  • window : Size of the window. That is how many observations we have to take for the calculation of each window.
  • min_periods : Least number of observations in a window required to have a value (otherwise result is NA).
  • center : It is used to set the labels at the center of the window.
  • win_type : It is used to set the window type.
  • on : Datetime column of our dataframe on which we have to calculate rolling mean.
  • axis : integer or string, default 0

Simple Moving Average (SMA)

A simple moving average tells us the unweighted mean of the previous K data points. The more the value of K the more smooth is the curve, but increasing K decreases accuracy. If the data points are p1,  p2, . . . , pn then we calculate the simple moving average.

Simple Moving Average in Pandas

In Python, we can calculate the moving average using .rolling() method. This method provides rolling windows over the data, and we can use the mean function over these windows to calculate moving averages. The size of the window is passed as a parameter in the function .rolling(window).

Now let’s see an example of how to calculate a simple rolling mean over a period of 30 days.

Step 1: Importing Libraries

In below code we are import the Pandas library as ‘pd’ and the NumPy library as ‘np’ for data manipulation and mathematical calculations, respectively. Additionally, Matplotlib’s pyplot module is imported as ‘plt’ for plotting graphs, with the default style set, and `%matplotlib inline` is included to display the plots inline in Jupyter notebooks.

Python3




# importing Libraries
 
# importing pandas as pd
import pandas as pd
 
# importing numpy as np
# for Mathematical calculations
import numpy as np
 
# importing pyplot from matplotlib as plt
# for plotting graphs
import matplotlib.pyplot as plt
plt.style.use('default')
%matplotlib inline


Step 2: Importing Data 

To import data we will use pandas  .read_csv() function.

Python3




# importing time-series data
reliance = pd.read_csv('RELIANCE.NS.csv', index_col='Date',
                       parse_dates=True)
 
# Printing dataFrame
reliance.head()


Output:

c1

Step 3: Dataframe by extract Columns

In this example the below code refines ‘reliance’ DataFrame by extracting the ‘Close’ column, computes a 30-day SMA, and prints the cleaned DataFrame, a standard step in financial analysis for technical indicator computation.

Python3




# Extract 'Close' column and convert to DataFrame
reliance = reliance['Close'].to_frame()
 
# Calculate 30-day Simple Moving Average (SMA)
reliance['SMA30'] = reliance['Close'].rolling(30).mean()
 
# Remove NULL values
reliance.dropna(inplace=True)
 
# Print DataFrame
reliance


Output:

c3

Step 4: Plotting Simple Moving Averages

In this example the code uses the `plot()` method to visualize the Close price and a 30-day Simple Moving Average (SMA) of the ‘reliance’ DataFrame, with ‘RELIANCE’ as the label, and a specified figure size of 16×8.

Python3




# plotting Close price and simple
# moving average of 30 days using .plot() method
reliance[['Close', 'SMA30']].plot(label='RELIANCE',
                                  figsize=(16, 8))


Output:

o1

Cumulative Moving Average (CMA) Syntax

To calculate Cumulative Moving Average in Pandas Dataframe we will use dataframe.expanding() function. This method gives us the cumulative value of our aggregation function (mean in this case).

Syntax: DataFrame.expanding(min_periods=1, center=None, axis=0, method=’single’).mean()

Parameters:

  • min_periods : int, default 1 . Least number of observations in a window required to have a value (otherwise result is NA).
  • center : bool, default False . It is used to set the labels at the center of the window.
  • axis : int or str, default 0
  • method : str {‘single’, ‘table’}, default ‘single’

Cumulative Moving Average (CMA)

The Cumulative Moving Average is the mean of all the previous values up to the current value. CMA of dataPoints x1, x2 …..  at time t can be calculated as, 

f2

While calculating CMA we don’t have any fixed size of the window. The size of the window keeps on increasing as time passes. In Python, we can calculate CMA using .expanding() method. Now we will see an example, to calculate CMA for a period of 30 days.

Step 1: Importing Libraries

Here , the code imports essential data manipulation libraries: Pandas for handling data frames, NumPy for mathematical operations, and Matplotlib’s Pyplot for plotting graphs with a default style. The `%matplotlib inline` command ensures that plots are displayed within the Jupyter Notebook environment.

Python3




# importing Libraries
 
# importing pandas as pd
import pandas as pd
 
# importing numpy as np
# for Mathematical calculations
import numpy as np
 
# importing pyplot from matplotlib as plt
# for plotting graphs
import matplotlib.pyplot as plt
plt.style.use('default')
%matplotlib inline


Step 2: Importing Data 

To import data we will use pandas  .read_csv() function.

Python3




# importing time-series data
reliance = pd.read_csv('RELIANCE.NS.csv',
                       index_col='Date',
                       parse_dates=True)
 
# Printing dataFrame
reliance.head()


Step 3:Transform Dataframe by Columns

In this example the below code first transforms the ‘reliance’ DataFrame to include only the ‘Close’ column, converting it into a DataFrame. Then, it computes the Cumulative Moving Average (CMA) with a window size of 30 for the ‘Close’ column. Finally, the resulting DataFrame, including the CMA values, is printed.

Python3




# Extract and isolate 'Close' column, converting to DataFrame
reliance = reliance['Close'].to_frame()
 
# Calculate Cumulative Moving Average (CMA) with a window of 30
reliance['CMA30'] = reliance['Close'].expanding().mean()
 
# Print DataFrame
reliance


Output:

c4

Step 4: Plotting Cumulative Moving Averages

In this example code uses the `.plot()` method to visualize the ‘Close’ price and 30-day Cumulative Moving Average (CMA30) of Reliance stock, with the specified label and figure size.

Python3




# plotting Close price and cumulative moving
# average of 30 days using .plot() method
reliance[['Close', 'CMA30']].plot(label='RELIANCE',
                                  figsize=(16, 8))


Output

o2

Exponential Moving Average (EMA) Syntax

To calculate Exponential moving average in Pandas Dataframe use dataframe.ewm() function. It provides us exponentially weighted functions. We will be using .mean() function to calculate EMA.

Syntax: DataFrame.ewm(com=None, span=None, halflife=None, alpha=None, min_periods=0, adjust=True, ignore_na=False, axis=0, times=None).mean()

Parameters:

  • com : float, optional . It is the decay in terms of centre of mass.
  • span : float, optional . It is the decay in terms of span.
  • halflife : float, str, timedelta, optional . It is the decay in terms of halflife.
  • alpha : float, optional . It is the smoothing factor having value between 0 and 1 , 1 inclusive .
  • min_periods : int, default 0. Least number of observations in a window required to have a value (otherwise result is NA).
  • adjust : bool, default True . Divide by decaying adjustment factor in beginning periods to account for imbalance in relative weightings (viewing EWMA as a moving average)
  • ignore_na : Ignore missing values when calculating weights; specify True to reproduce pre-0.15.0 behavior.
  • axis : The axis to use. The value 0 identifies the rows, and 1 identifies the columns.

Exponential Moving Average

Exponential moving average (EMA) tells us the weighted mean of the previous K data points. EMA places a greater weight and significance on the most recent data points. The formula to calculate EMA at the time period t is:

f3

where xt is the value of observation at time t & α is the smoothing factor. In Python, EMA is calculated using .ewm() method. We can pass span or window as a parameter to .ewm(span = ) method. Now we will be looking at an example to calculate EMA for a period of 30 days.

Step 1: Importing Libraries

In below code imports the Pandas library as ‘pd’ for data manipulation, NumPy as ‘np’ for mathematical calculations, and Matplotlib’s pyplot module as ‘plt’ for creating graphs. Additionally, `%matplotlib inline` ensures that plots are displayed inline in Jupyter notebooks.

Python3




# importing Libraries
 
# importing pandas as pd
import pandas as pd
 
# importing numpy as np
# for Mathematical calculations
import numpy as np
 
# importing pyplot from matplotlib as plt
# for plotting graphs
import matplotlib.pyplot as plt
plt.style.use('default')
%matplotlib inline


Step 2: Importing Data

To import data we will use pandas .read_csv() function.

Python3




# importing time-series data
reliance = pd.read_csv('RELIANCE.NS.csv',
                       index_col='Date',
                       parse_dates=True)
 
# Printing dataFrame
reliance.head()


Output :

c5

Step 3: Isolates Column by Dataframe

In this example the below code isolates the ‘Close’ column in the ‘reliance’ DataFrame, converts it into a DataFrame, computes the Exponential Moving Average (EWMA) with a span of 30 for the ‘Close’ column, and prints the resulting DataFrame containing the EWMA values.

Python3




# Extract and isolate 'Close' column, converting to DataFrame
reliance = reliance['Close'].to_frame()
 
# Calculate Exponential Moving Average (EWMA) with a span of 30
reliance['EWMA30'] = reliance['Close'].ewm(span=30).mean()
 
# Print DataFrame
reliance


Output :

c6

Step 4: Plotting Exponential Moving Averages 

Here, code uses the `plot()` method to visualize the Close price and a 30-day Exponential Moving Average (EWMA) of the RELIANCE stock, displaying them on the same plot with a specified label and figure size.

Python3




# plotting Close price and exponential
# moving averages of 30 days
# using .plot() method
reliance[['Close', 'EWMA30']].plot(label='RELIANCE',
                                   figsize=(16, 8))


Output :

ol



Previous Article
Next Article

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 Averages 2 are very popular. Simple Moving AverageExpo
3 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): val = dataframe[value] wt = dataframe[weight] ret
3 min read
How to Calculate Moving Averages in Python?
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 i
11 min read
Difference Between Spark DataFrame and Pandas DataFrame
Dataframe represents a table of data with rows and columns, Dataframe concepts never change in any Programming language, however, Spark Dataframe and Pandas Dataframe are quite different. In this article, we are going to see the difference between Spark dataframe and Pandas Dataframe. Pandas DataFrame Pandas is an open-source Python library based o
3 min read
Pandas Dataframe.to_numpy() - Convert dataframe to Numpy array
Pandas DataFrame is a two-dimensional size-mutable, potentially heterogeneous tabular data structure with labeled axes (rows and columns). This data structure can be converted to NumPy ndarray with the help of the DataFrame.to_numpy() method. In this article we will see how to convert dataframe to numpy array. Syntax of Pandas DataFrame.to_numpy()
3 min read
Convert given Pandas series into a dataframe with its index as another column on the dataframe
First of all, let we understand that what are pandas series. Pandas Series are the type of array data structure. It is one dimensional data structure. It is capable of holding data of any type such as string, integer, float etc. A Series can be created using Series constructor. Syntax: pandas.Series(data, index, dtype, copy) Return: Series object.
1 min read
How to Convert Wide Dataframe to Tidy Dataframe with Pandas stack()?
We might sometimes need a tidy/long-form of data for data analysis. So, in python's library Pandas there are a few ways to reshape a dataframe which is in wide form into a dataframe in long/tidy form. Here, we will discuss converting data from a wide form into a long-form using the pandas function stack(). stack() mainly stacks the specified index
4 min read
Replace values of a DataFrame with the value of another DataFrame in Pandas
In this article, we will learn how we can replace values of a DataFrame with the value of another DataFrame using pandas. It can be done using the DataFrame.replace() method. It is used to replace a regex, string, list, series, number, dictionary, etc. from a DataFrame, Values of the DataFrame method are get replaced with another value dynamically.
4 min read
Converting Pandas Dataframe To Dask Dataframe
In this article, we will delve into the process of converting a Pandas DataFrame to a Dask DataFrame in Python through several straightforward methods. This conversion is particularly crucial when dealing with large datasets, as Dask provides parallel and distributed computing capabilities, allowing for efficient handling of substantial data volume
3 min read
Pandas Dataframe rank() | Rank DataFrame Entries
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas DataFrame rank() method returns a rank of every respective entry (1 through n) along an axis of the DataFrame passed. The rank is retu
3 min read
Pandas DataFrame to_dict() Method | Convert DataFrame to Dictionary
Python is a great language for doing data analysis because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Pandas .to_dict() method is used to convert a DataFrame into a dictionary of series or list-like data type depending on the orient parameter. Exam
3 min read
Pandas DataFrame assign() Method | Create new Columns in DataFrame
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages, making importing and analyzing data much easier. The Dataframe.assign() method assigns new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original one
4 min read
Python | Pandas DataFrame.fillna() to replace Null values in dataframe
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Sometimes csv file has null values, which are later displayed as NaN in Data Frame. Just like the pandas dropna() method manages and rem
5 min read
Pandas DataFrame hist() Method | Create Histogram in Pandas
A histogram is a graphical representation of the numerical data. Sometimes you'll want to share data insights with someone, and using graphical representations has become the industry standard. Pandas.DataFrame.hist() function plots the histogram of a given Data frame. It is useful in understanding the distribution of numeric variables. This functi
4 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
Calculate average values of two given NumPy arrays
Finding average of NumPy arrays is quite similar to finding average of given numbers. We just have to get the sum of corresponding array elements and then divide that sum with the total number of arrays. Let's see an example: Example 1: Calculate average values of two given NumPy 1d-arrays C/C++ Code # import library import numpy as np # create a n
1 min read
Calculate Average Street Circuity Using OSMnx stats Module
Circuity is defined as a lack of straightforwardness and it is a result of a circulation network configuration. It impacts how we use urban space for settlement and travel. Calculating the average circuity of a city provides insights about direct routes in a transportation network. In this article, we will see how to calculate average street circui
2 min read
Find Minimum, Maximum, and Average Value of PySpark Dataframe column
In this article, we are going to find the Maximum, Minimum, and Average of particular column in PySpark dataframe. For this, we will use agg() function. This function Compute aggregates and returns the result as DataFrame. Syntax: dataframe.agg({'column_name': 'avg/'max/min}) Where, dataframe is the input dataframecolumn_name is the column in the d
2 min read
How to select the rows of a dataframe using the indices of another dataframe?
Prerequisites: PandasRandom Using Pandas module it is possible to select rows from a data frame using indices from another data frame. This article discusses that in detail. It is advised to implement all the codes in jupyter notebook for easy implementation. Approach:Import moduleCreate first data frame. In the example given below choice(), randin
2 min read
How to slice a PySpark dataframe in two row-wise dataframe?
In this article, we are going to learn how to slice a PySpark DataFrame into two row-wise. Slicing a DataFrame is getting a subset containing all rows from one index to another. Method 1: Using limit() and subtract() functions In this method, we first make a PySpark DataFrame with precoded data using createDataFrame(). We then use limit() function
4 min read
How to Transform Spark DataFrame to Polars DataFrame?
Apache Spark and Polars are powerful data processing libraries that cater to different needs. Spark excels in distributed computing and is widely used for big data processing, while Polars, a newer library, is designed for fast, single-machine data processing, leveraging Rust for performance. Sometimes, you might want to transform a Spark DataFrame
3 min read
How to add moving platforms in PyGame
Prerequisite: Drawing in Pygame In this article, we will learn how we can add moving platforms to our game using PyGame in Python. Creating a Platform We can easily create any type of platform in pygame using the draw( ) method. For this, we will create react with specific width and height using the draw.rect() function. Syntax: pygame.draw.rect(su
5 min read
Python Tkinter | Moving objects using Canvas.move() method
The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x
2 min read
Python - Moving an object in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this tutorial, we are going to lear
3 min read
PyQt5 QCalendarWidget - Moving it to the bottom of the parent stack
In this article we will see how we can make the QCalendarWidget lowers to the parent stack. After making the QCalendarWidget lower at the stack, QCalendarWidgert will be visually behind (and therefore obscured by) any overlapping sibling widgets. In order to do this we will use lower method with the QCalendarWidget object.Syntax : calendar.lower()A
1 min read
PyQt5 QCalendarWidget - Moving it to the top of the parent stack
In this article we will see how we can make the QCalendarWidget at the top of the parent stack. After making the QCalendarWidget lower at the stack, QCalendarWidgert will be visually in front of any overlapping sibling widgets. In order to do this we will use raise_ method with the QCalendarWidget object.Syntax : calendar.raise_()Argument : It take
2 min read
MoviePy – Text with moving Letters
In this article we will see how we can move the letters of the text clip MoviePy. MoviePy is a Python module for video editing, which can be used for basic operations on videos and GIF’s. Video is formed by the frames, combination of frames creates a video each frame is an individual image. VideoClip is the base class for all the other video clips
4 min read
PYGLET – Moving Caret to nearest point
In this article we will see how we can move caret to nearest point in PYGLET module in python. Pyglet is easy to use but powerful library for developing visually rich GUI applications like games, multimedia etc. A window is a "heavyweight" object occupying operating system resources. Windows may appear as floating regions or can be set to fill an e
3 min read