How to calculate MOVING AVERAGE in a Pandas DataFrame? (original) (raw)

Last Updated : 14 Feb, 2026

Moving averages in a Pandas DataFrame are used to smooth time series data and identify overall trends by reducing short-term fluctuations. They help in making patterns more visible and easier to analyze.

In Pandas, we commonly calculate moving averages using:

types_of_moving_averages

Types of Moving Average

Here we create a dataset of stock prices over 15 days and applies different moving average techniques to smooth daily fluctuations and identify trends.

**It calculates:

import pandas as pd import numpy as np import matplotlib.pyplot as plt

data = {'Date': pd.date_range(start='2024-01-01', periods=15, freq='D'), 'Stock Price': [100, 102, 101, 105, 107, 110, 108, 112, 114, 116, 115, 117, 120, 123, 125]}

df = pd.DataFrame(data)

df['SMA'] = df['Stock Price'].rolling(window=5).mean()
df['EMA'] = df['Stock Price'].ewm(span=5).mean()
df['CMA'] = df['Stock Price'].expanding().mean()

`

Now, we visualize three subplots to compare the trends. The SMA smooths prices over a 5 day window, the EMA reacts faster to recent changes and the CMA shows the overall average trend over time.

Python `

fig, axes = plt.subplots(3, 1, figsize=(10, 12), sharex=True)

axes[0].plot(df['Date'], df['Stock Price'], label='Original Stock Price', marker='o') axes[0].plot(df['Date'], df['SMA'], label='SMA (5 days)', marker='o', color='blue') axes[0].set_title("Simple Moving Average (SMA)") axes[0].set_ylabel("Stock Price") axes[0].legend() axes[0].grid(True)

axes[1].plot(df['Date'], df['Stock Price'], label='Original Stock Price', marker='o') axes[1].plot(df['Date'], df['EMA'], label='EMA (span=5)', marker='o', color='orange') axes[1].set_title("Exponential Moving Average (EMA)") axes[1].set_ylabel("Stock Price") axes[1].legend() axes[1].grid(True)

axes[2].plot(df['Date'], df['Stock Price'], label='Original Stock Price', marker='o') axes[2].plot(df['Date'], df['CMA'], label='CMA', marker='o', color='green') axes[2].set_title("Cumulative Moving Average (CMA)") axes[2].set_ylabel("Stock Price") axes[2].set_xlabel("Date") axes[2].legend() axes[2].grid(True) plt.tight_layout() plt.show()

`

**Output:

calculate-MOVING-AVERAGE-in-a-Pandas-DataFrame

Stock Trends

The stock price appears to be trending upwards over the given period.

**1. Simple Moving Average (SMA):

**2. Exponential Moving Average (EMA):

**3. Cumulative Moving Average (CMA):

Types of Moving averages

1. Simple Moving Average (SMA) Using rolling()

To calculate a Simple Moving Average (SMA) in a Pandas DataFrame, we use the rolling() function to create a fixed window and apply .mean() to compute the average. SMA represents the unweighted average of the last K data points. A larger K smooths the curve more but reduces responsiveness to recent changes.

If the data points are p_1,p_2,...,p_n the SMA at any point is simply the average of the last K values.

SMA_k = \frac{p_{n-k+1} + p_{n-k+2} + \cdots + p_n}{k}= \frac{1}{k} \sum_{i=n-k+1}^{n} p_i

In Python, we can calculate a moving average using the .rolling() method in Pandas.

Now let's see an example of how to calculate a simple rolling mean over a period of 30 days for a real world dataset:

The link to the data we will use in the article is RELIANCE.NS

**Step 1: Importing Libraries

Python `

import pandas as pd import numpy as np 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.

Python `

reliance = pd.read_csv('RELIANCE.NS.csv', index_col='Date', parse_dates=True)

reliance.head()

`

**Output:

c1

**Step 3: Calculating Simple Moving Average from DataFrame Columns

In this example, the code extracts the ‘Close’ column from the reliance DataFrame, calculates a 30 day Simple Moving Average (SMA) and then prints the refined DataFrame. This is a common step in financial analysis for computing technical indicators and identifying trends.

Python `

reliance = reliance['Close'].to_frame() reliance['SMA30'] = reliance['Close'].rolling(30).mean() reliance.dropna(inplace=True)

print(reliance)

`

**Output:

SMA30

SMA

**Step 4: Plotting Simple Moving Averages

In this example, the code uses the plot() method to visualize the Close price along with the 30 day Simple Moving Average (SMA) from the reliance DataFrame.

Python `

reliance[['Close', 'SMA30']].plot(label='RELIANCE', figsize=(16, 8))

`

**Output:

o1

**2. Exponential Moving Average (EMA) Using ewm()

The Exponential Moving Average (EMA) gives more weight to recent data points, making it more responsive to new changes compared to SMA. This makes EMA useful when recent movements are more important for analysis.

EMA places a greater weight and significance on the most recent data points. The formula to calculate EMA at the time period t is:

EMA_t =\begin{cases}x_0 & t = 0 \\\alpha x_t + (1 - \alpha) EMA_{t-1} & t > 0\end{cases}

where x_t is the value of observation at time t \space and \space \alpha 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 and Step 2 will remain same.

**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.

Python `

reliance = reliance['Close'].to_frame()

reliance['EWMA30'] = reliance['Close'].ewm(span=30).mean()

reliance

`

**Output :

SMA30

EWMA

**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.

Python `

reliance[['Close', 'EWMA30']].plot(label='RELIANCE', figsize=(16, 8))

`

**Output :

ol

**3. Cumulative Moving Average (CMA) Using expanding()

To calculate the Cumulative Moving Average (CMA) in a Pandas DataFrame, we use the .expanding() function. This method computes the cumulative value of an aggregation function (such as .mean()) from the beginning up to the current point. CMA represents the average of all previous values up to time 𝑡. For data points x_1, x_2.... at time t can be calculated as:

CMA_t = \frac{x_1 + x_2 + x_3 + \cdots + x_t}{t}

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 and Step 2 will remain same.

**Step 3: Transform Dataframe by Columns

In this example, the code first extracts the ‘Close’ column from the reliance DataFrame and ensures it is in DataFrame format. It then calculates the Cumulative Moving Average (CMA) for the ‘Close’ prices using the expanding method. Finally, it prints the updated DataFrame containing the computed CMA values.

Python `

reliance = reliance['Close'].to_frame()

reliance['CMA30'] = reliance['Close'].expanding().mean() reliance

`

**Output:

CMA30

CMA

**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.

Python `

reliance[['Close', 'CMA30']].plot(label='RELIANCE', figsize=(16, 8))

`

**Output

o2