Cover Image for Calculate Moving Averages in Python
227 views

Calculate Moving Averages in Python

Moving averages are commonly used in time series analysis to smooth out fluctuations in data and identify trends or patterns. Python provides various libraries and methods for calculating moving averages, including NumPy and pandas. Below, I’ll demonstrate how to calculate different types of moving averages in Python:


Simple Moving Average (SMA):

The Simple Moving Average is the most basic type of moving average, calculated by taking the average of a fixed window of data points.

Python
import pandas as pd

# Sample time series data
data = {'Date': pd.date_range(start='2022-01-01', periods=10, freq='D'),
        'Value': [25, 30, 35, 40, 45, 50, 55, 60, 65, 70]}

df = pd.DataFrame(data)

# Calculate a 3-day Simple Moving Average (SMA)
window_size = 3
df['SMA'] = df['Value'].rolling(window=window_size).mean()

print(df)


Exponential Moving Average (EMA):

The Exponential Moving Average gives more weight to recent data points, making it more responsive to changes in the data.

Python
import pandas as pd

# Sample time series data
data = {'Date': pd.date_range(start='2022-01-01', periods=10, freq='D'),
        'Value': [25, 30, 35, 40, 45, 50, 55, 60, 65, 70]}

df = pd.DataFrame(data)

# Calculate a 3-day Exponential Moving Average (EMA)
span = 3
df['EMA'] = df['Value'].ewm(span=span, adjust=False).mean()

print(df)


Weighted Moving Average (WMA):

The Weighted Moving Average assigns different weights to each data point within the moving window.

Python
import pandas as pd

# Sample time series data
data = {'Date': pd.date_range(start='2022-01-01', periods=10, freq='D'),
        'Value': [25, 30, 35, 40, 45, 50, 55, 60, 65, 70]}

df = pd.DataFrame(data)

# Calculate a 3-day Weighted Moving Average (WMA)
window_size = 3
weights = [0.3, 0.4, 0.3]  # Customize the weights as needed
df['WMA'] = df['Value'].rolling(window=window_size).apply(lambda x: (x * weights).sum())

print(df)

These are basic examples of how to calculate different types of moving averages using pandas. You can adjust the window size and customize weights as needed for your specific analysis. Moving averages are commonly used in time series forecasting, anomaly detection, and trend analysis to gain insights from historical data.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS