![]() |
VOOZH | about |
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:
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:
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.
Output:
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):
- Bullish Trend: All three moving averages are trending upwards, indicating a bullish trend in the stock price.
- EMA's Responsiveness: The EMA, being more responsive to recent price changes, provides a better indication of the current trend direction.
- CMA's Cumulative Nature: The CMA is useful for long term perspectives, but it's less helpful for short term trading decisions.
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 ,,..., the SMA at any point is simply the average of the last K values.
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
Step 2: Importing Data
To import data we will use pandas .read_csv() function.
Output:
👁 c1Step 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.
Output:
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.
Output:
👁 o1ewm()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:
where is the value of observation at time 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.
Output :
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.
Output :
👁 olexpanding()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 at time t can be calculated as:
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.
Output:
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.
Output
👁 o2