
Moving average smoothing helps make time series data clearer by reducing noise. In this article, you’ll learn to smooth time series data using moving averages in Python.
What is Moving Average Smoothing?
Moving average smoothing reduces short-term fluctuations. It averages data points over a set period. This method helps minimize noise and highlights the overall trend.
Imagine daily temperature readings for a month. Each day, temperatures change slightly. Use moving average smoothing to see the trend. Average temperatures over 7 days. This creates a smoother line, It reveals the trend and reduces daily fluctuations.
Load data
Let’s create a sample time series dataset.
import numpy as np import pandas as pd # Generate a time series with noise dates = pd.date_range(start='2024-01-01', periods=100) data = np.sin(np.linspace(0, 10, 100)) + np.random.normal(0, 0.5, 100) # Create a DataFrame df = pd.DataFrame(data, index=dates, columns=['Value']) # Print the DataFrame print(df)

Simple Moving Average (SMA)
The Simple Moving Average (SMA) smooths data by averaging recent points. To apply SMA, use the ‘.rolling()’ method to create a moving window and then calculate the mean.
# Define window size
window_size = 7
# Calculate SMA
df['SMA'] = df['Value'].rolling(window=window_size).mean()
# Plot the results
plt.figure(figsize=(12, 6))
plt.plot(df['Value'], label='Original Data', color='blue')
plt.plot(df['SMA'], label=f'SMA (window={window_size})', color='red')
plt.title('Simple Moving Average Smoothing')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

The plot shows the original data in blue and the Simple Moving Average (SMA) in red. The SMA line smooths the fluctuations by averaging data over 7 days. However, the SMA lags behind the original data because it uses past values. This technique reduces short-term noise and highlights the overall direction.
Weighted Moving Average (WMA)
The Weighted Moving Average (WMA) smooths time series data by giving more importance to recent points. For WMA, you must manually assign weights to each data point and calculate the weighted average. The ‘.apply()’ method with a lambda function calculates the weighted average. This method makes recent changes stand out more.
# Define weights
weights = np.arange(1, window_size + 1)
# Calculate WMA
df['WMA'] = df['Value'].rolling(window=window_size).apply(lambda x: np.dot(x, weights)/weights.sum(), raw=True)
# Plot the results
plt.figure(figsize=(12, 6))
plt.plot(df['Value'], label='Original Data', color='blue')
plt.plot(df['WMA'], label=f'WMA (window={window_size})', color='green')
plt.title('Weighted Moving Average Smoothing')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

The plot displays the original data in blue and the Weighted Moving Average (WMA) in green. The WMA line smooths the fluctuations by giving more weight to recent data points. This makes the WMA line react faster to recent changes. The WMA highlights recent trends and reduces the impact of older data. This results in a smooth curve that responds better to recent changes.
Exponential Moving Average (EMA)
The Exponential Moving Average (EMA) smooths time series data by giving more weight to recent points. It reacts faster to changes than the Simple Moving Average (SMA). To calculate EMA, use the ‘.ewm()’ method. It includes a parameter for the smoothing factor. This makes the average respond quickly to recent trends.
# Define span for EMA
span = 10
# Calculate EMA
df['EMA'] = df['Value'].ewm(span=span, adjust=False).mean()
# Plot the results
plt.figure(figsize=(12, 6))
plt.plot(df['Value'], label='Original Data', color='blue')
plt.plot(df['EMA'], label=f'EMA (span={span})', color='orange')
plt.title('Exponential Moving Average Smoothing')
plt.xlabel('Date')
plt.ylabel('Value')
plt.legend()
plt.show()

The plot shows the original data in blue and the Exponential Moving Average (EMA) in orange. The EMA line smooths the data by giving more weight to recent values. This helps the EMA react faster to recent changes. The EMA makes the trend smoother and highlights recent changes better. It also reduces the effect of older data.
Conclusion
Moving average smoothing is a useful tool for analyzing time series data. It helps reduce noise and reveal trends. We showed how to use Python for these techniques. You can adjust the window sizes and spans to fit your data and analysis needs.
Image created by Editor with Midjourney.
