Loading...
Loading...
Compute Simple (SMA), Exponential (EMA), and Weighted (WMA) moving averages. Compare smoothing methods with interactive charts and Python pandas code.
Moving averages smooth time series data to reveal underlying trends. SMA averages all values equally in a window. EMA weights recent values exponentially higher for faster trend detection. WMA uses linearly increasing weights as a middle ground.
| Type | MAE | RMSE |
|---|---|---|
| SMA | 2.45 | 2.78 |
| EMA | 2.45 | 2.73 |
| WMA | 1.78 | 2.04 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# Data
data = [100, 102, 104, 103, 105, 108, 110, 107, 109, 112, 115, 113, 116, 118, 120, 117, 119, 122, 125, 123, 126, 128, 130, 127, 129]
df = pd.DataFrame({'value': data})
# Simple Moving Average (SMA)
df['SMA_5'] = df['value'].rolling(window=5).mean()
# Exponential Moving Average (EMA)
df['EMA_5'] = df['value'].ewm(span=5, adjust=False).mean()
# Weighted Moving Average (WMA)
weights = np.arange(1, 5 + 1)
df['WMA_5'] = df['value'].rolling(window=5).apply(
lambda x: np.dot(x, weights) / weights.sum(), raw=True
)
print(df.to_string())
# Error metrics
for col in ['SMA_5', 'EMA_5', 'WMA_5']:
valid = df.dropna(subset=[col])
mae = (valid['value'] - valid[col]).abs().mean()
rmse = np.sqrt(((valid['value'] - valid[col]) ** 2).mean())
print(f"\n{col}: MAE={mae:.4f}, RMSE={rmse:.4f}")
# Plot
plt.figure(figsize=(12, 6))
plt.plot(df['value'], 'k-', label='Original', alpha=0.5)
plt.plot(df['SMA_5'], 'b-', label='SMA(5)', linewidth=2)
plt.plot(df['EMA_5'], 'r-', label='EMA(5)', linewidth=2)
plt.plot(df['WMA_5'], 'g-', label='WMA(5)', linewidth=2)
plt.legend()
plt.title('Moving Averages Comparison')
plt.xlabel('Time Period')
plt.ylabel('Value')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()SMA gives equal weight to all values in the window. EMA gives exponentially more weight to recent values using a decay factor α = 2/(n+1). WMA assigns linearly increasing weights (1, 2, ..., n). EMA reacts fastest to changes, SMA is smoothest, WMA is in between.
Larger windows produce smoother curves but lag more behind the data. Common choices: 5-day and 20-day for stock trading, 7-day for weekly patterns, 12-month for annual seasonality. Use MAE/RMSE to compare different window sizes.
A golden cross occurs when a short-term MA (e.g., 50-day) crosses above a long-term MA (e.g., 200-day), signaling a potential uptrend. A death cross is the opposite, signaling a potential downtrend.
Moving averages are lagging indicators - they smooth past data and reveal trends but don't predict future values. For forecasting, combine with methods like exponential smoothing (Holt-Winters) or ARIMA.
EMA assigns exponentially decaying weights - the most recent value gets weight α = 2/(n+1), the next gets α(1-α), then α(1-α)², etc. Recent data points have much more influence, making EMA more responsive.
SMA gives equal weight to all values in the window. EMA gives exponentially more weight to recent values using a decay factor α = 2/(n+1). WMA assigns linearly increasing weights (1, 2, 3, ..., n). EMA reacts fastest to changes, SMA is smoothest, WMA is in between.
Larger windows produce smoother curves but lag more behind the data. Common choices: 5-day and 20-day for stock trading, 7-day for weekly patterns, 12-month for annual seasonality. Use MAE/RMSE to compare different window sizes for forecasting accuracy.
A golden cross occurs when the short-term MA (e.g., 50-day) crosses above the long-term MA (e.g., 200-day), signaling a potential uptrend. A death cross is the opposite - short-term crosses below long-term, signaling a potential downtrend.
Moving averages are lagging indicators - they smooth past data and reveal trends, but they don't predict future values. For forecasting, use the last MA value as a simple forecast, or combine with other methods like exponential smoothing (Holt-Winters) or ARIMA.
EMA assigns exponentially decaying weights - the most recent value gets weight α = 2/(n+1), the next gets α(1-α), then α(1-α)², etc. This means recent data points have much more influence than older ones, making EMA more responsive to changes compared to SMA where all points are equally weighted.