Time Series Analysis and Forecasting
Time series data is recorded over time, like daily sales or monthly website visits. This topic shows how to understand its patterns and make simple forecasts.
a. Trend, Seasonality, and Noise
Most time series are made of three parts. The trend is the long-term direction, such as steady growth. Seasonality is a repeating pattern, such as higher sales every December. Noise is the random ups and downs that remain.
Seeing these parts separately makes data easier to understand. A sales rise might be due to real growth, or just the festival season. The difference matters for planning.
Some series also have cycles, which are longer and less regular than seasons. Before any forecast, plot your data and look for these patterns with your own eyes.
b. Decomposing a Time Series
Decomposition splits a series into trend, seasonality, and residual noise. The statsmodels library provides a simple function for this.
from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(df["sales"], model="additive", period=12)
result.plot()
plt.show()The period is the number of steps in one seasonal cycle. For monthly data with a yearly pattern, use 12. Use the additive model when the seasonal swings stay about the same size. Use the multiplicative model when they grow as the trend grows.
The chart shows four panels: the original data, the trend, the seasonal pattern, and the residuals. This is a strong way to explain what is driving the numbers.
c. Moving Average and Exponential Smoothing
A moving average smooths the series by averaging recent values. It is simple and good for spotting the trend.
df["ma_3"] = df["sales"].rolling(window=3).mean()Exponential smoothing also averages past values, but gives more weight to recent ones. This lets it react faster to change. In Pandas, you can use ewm() for a quick version.
df["ema"] = df["sales"].ewm(span=3).mean()For forecasting with trend and seasonality, statsmodels offers ExponentialSmoothing. It is a good first model because it is easy to explain and often works well.
d. Introduction to ARIMA Forecasting
ARIMA is a popular forecasting model. It stands for AutoRegressive Integrated Moving Average. It uses past values and past errors to predict future values.
It has three settings, written as (p, d, q). The p is the number of past values used, d is how many times the data is differenced to remove trend, and q is the number of past errors used.
from statsmodels.tsa.arima.model import ARIMA
model = ARIMA(df["sales"], order=(1, 1, 1))
fitted = model.fit()
forecast = fitted.forecast(steps=6)The code above predicts the next 6 periods. To check accuracy, hold out the last few points, forecast them, and compare. Start with simple settings and increase complexity only if the results improve.
Data Analysis with Python Handbook
Wesline Rinisha








