Skip to main content
LearnMLAcademy
Intermediate10 min read

ARIMA

Model non-stationary time series using ARIMA differencing and lag parameters, with Python code, architecture diagrams, worked examples, and interview quiz.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

ARIMA (AutoRegressive Integrated Moving Average)

ARIMA is a classical statistical model for forecasting a time series from its own history. Unlike a normal table where row order may not matter, time-series observations arrive in sequence, so yesterday, last week, or last month can contain useful information about what comes next.

ARIMA in Simple Words

1. Look Back

Use earlier values of the series.

2. Remove Trend

Difference the series when needed.

3. Learn Errors

Use patterns in earlier forecast errors.

4. Forecast

Combine the learned structure to predict future values.

A Tiny Example First

Suppose monthly demand is:

MonthDemand
January100
February108
March117

The level is rising, but the changes are only +8 and +9. ARIMA can model a series after differencing and combine that with lagged values and lagged errors.

Common time-series examples include sales, demand, traffic, sensor readings, financial quantities, website activity, and other measurements collected repeatedly over time. ARIMA is most appropriate when the series can be represented reasonably well by a linear non-seasonal ARIMA structure; strongly seasonal series usually need seasonal terms such as SARIMA.


What Does ARIMA(p, d, q) Mean?

p

AutoRegressive order

How many lagged values are included in the AR part.

d

Differencing order

How many rounds of differencing are used by the integrated part.

q

Moving-Average order

How many lagged error terms are included in the MA part.

Example: ARIMA(2, 1, 1)

Use an AR order of 2, difference once, and use an MA order of 1. This notation describes the model structure; it does not mean those values are automatically correct for every dataset.


The Three Parts of ARIMA

1. AR — AutoRegression

The AR part relates the current value to earlier values of the series. An AR(p) model can be written as:

Yt = c + ϕ1Yt-1 + ... + ϕpYt-p + εt

Worked AR example

Suppose c = 10, ϕ₁ = 0.6, ϕ₂ = 0.2, and the last two values are 50 and 46.

Forecast part = 10 + (0.6 × 50) + (0.2 × 46)

= 10 + 30 + 9.2

= 49.2

This isolates the lagged-value contribution for a simple teaching example; a full stochastic model also includes an innovation/error term.

2. I — Integrated / Differencing

Differencing replaces the original levels with changes between observations. First differencing is:

Y't = Yt − Yt-1

Original series

100 → 108 → 117

The level is trending upward.

First difference

108 − 100 = 8

117 − 108 = 9

If one round is used, then d = 1.

3. MA — Moving Average

In ARIMA, Moving Average does not mean a rolling average of recent observations. The MA part models the current value using previous innovation/error terms.

Yt = c + εt + θ1εt-1 + ... + θqεt-q

Simple one-step MA intuition

Suppose the baseline is 20, θ₁ = 0.5, and the previous error was −4.

Forecast contribution = 20 + (0.5 × −4)

= 18

For a one-step forecast, the unknown future innovation has expected value zero under the model.


Stationarity and Why d Matters

A stationary process has statistical behavior that does not systematically drift over time. In practical ARIMA modeling, we often difference a non-stationary level series so that the remaining process is more suitable for ARMA-style modeling.

More stationary-looking

Values fluctuate around a broadly stable level.

Clearly trending

The level changes systematically over time.

Avoid over-differencing

Differencing is not automatically better. Unnecessary extra differencing can introduce undesirable structure and make forecasts noisier. Choose d using diagnostics and validation rather than mechanically differencing until the graph looks flat.


A Practical ARIMA Workflow

1. Plot the series

Inspect trend, seasonality, missing periods, outliers, and structural changes.

2. Keep time order

Use an earlier training period and a later validation/test period. Do not randomly shuffle a forecasting series.

3. Examine stationarity

Use plots, domain knowledge, and tests such as ADF as supporting evidence.

4. Choose d

Difference when needed so the modeled process is more stable.

5. Explore p and q

ACF/PACF can provide clues; candidate models can then be compared.

6. Fit and diagnose

Check residuals and compare candidate models using criteria such as AIC plus forecasting performance.

7. Forecast

Generate forecasts from the end of the training period into future periods.

8. Evaluate chronologically

Use MAE, RMSE or a domain-specific metric on later observations that were not used to fit the model.

ADF Test — What the p-value Actually Means

The Augmented Dickey-Fuller test has a null hypothesis that the series contains a unit root. A small p-value, such as below a chosen 5% significance level, is evidence for rejecting that null under the test specification. It is better to say this than to say “p < 0.05 proves stationarity.”

ACF and PACF

ToolSimple meaningClassical clue
ACFCorrelation between the series and its lagged values.Can help suggest MA structure.
PACFLag relationship after accounting for shorter-lag linear effects.Can help suggest AR structure.

These are identification heuristics, not mechanical rules that always reveal the correct p and q for a mixed ARIMA model.

AIC — Useful, but Not a Forecast Guarantee

AIC balances model fit with model complexity. When several candidate models are fitted to the same data under comparable assumptions, a lower AIC is preferred by that criterion. But the lowest AIC does not guarantee the best future forecast, so chronological validation still matters.


Python: A Self-Contained ARIMA Example

This example creates a reproducible non-seasonal series, keeps the final 12 months as an untouched time-ordered test period, checks the effect of first differencing, compares a small set of ARIMA orders by AIC, and evaluates the forecast.

import itertools
import warnings
import numpy as np
import pandas as pd
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.stattools import adfuller

# 1. Create a reproducible non-seasonal time series
rng = np.random.default_rng(42)
n = 120
noise = rng.normal(0, 1.2, n)

values = np.zeros(n)
values[0] = 50
change = 0.0

for t in range(1, n):
    change = 0.55 * change + 0.25 + noise[t]
    values[t] = values[t - 1] + change

series = pd.Series(
    values,
    index=pd.date_range("2015-01-01", periods=n, freq="MS"),
    name="value"
)

# 2. Chronological split: last 12 months are test data
train = series.iloc[:-12]
test = series.iloc[-12:]

# 3. ADF before and after first differencing
adf_level = adfuller(train, autolag="AIC")
adf_diff = adfuller(train.diff().dropna(), autolag="AIC")

print("Level ADF p-value:", round(adf_level[1], 4))
print("Differenced ADF p-value:", round(adf_diff[1], 4))

# 4. Small teaching search over p and q, keeping d=1
candidates = list(itertools.product(range(3), [1], range(3)))

best_aic = np.inf
best_order = None

for order in candidates:
    try:
        # Some deliberately tested candidates may emit start-value/convergence warnings.
        # We compare the models that successfully fit.
        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            fitted = ARIMA(train, order=order).fit()

        if fitted.aic < best_aic:
            best_aic = fitted.aic
            best_order = order
    except Exception:
        pass

print("Best order by AIC:", best_order)
print("Best AIC:", round(best_aic, 2))

# 5. Fit selected model and forecast the test period
model = ARIMA(train, order=best_order).fit()
forecast = model.forecast(steps=len(test))

mae = np.mean(np.abs(test - forecast))
rmse = np.sqrt(np.mean((test - forecast) ** 2))

print("First 3 forecasts:", forecast.iloc[:3].round(2).tolist())
print("MAE:", round(mae, 2))
print("RMSE:", round(rmse, 2))

Level ADF p-value: 0.5364

Differenced ADF p-value: 0.0

Best order by AIC: (1, 1, 0)

Best AIC: 294.38

First 3 forecasts: [92.62, 92.36, 92.2]

MAE: 1.14

RMSE: 1.28

What this example teaches

The raw training series does not give strong ADF evidence against a unit root, while the first-differenced series does. Among this deliberately small candidate set, ARIMA(1,1,0) has the lowest AIC. We still evaluate its forecast on later unseen observations rather than trusting AIC alone.


ARIMA, SARIMA and Exogenous Variables

Model ideaUse it when...
ARIMA(p,d,q)You need a non-seasonal ARIMA structure based primarily on the series history.
SARIMAThere is repeating seasonal structure requiring seasonal AR, differencing, or MA terms.
ARIMA/SARIMAX with exogenous variablesExternal predictors such as price, promotions, temperature, or holidays should enter the forecasting model.

Seasonal example

If monthly sales show a pattern that repeats every 12 months, a plain non-seasonal ARIMA may miss that seasonal structure. A seasonal specification can add terms with period s = 12.


ARIMA vs Other Forecasting Approaches

Avoid treating one family as universally better. ARIMA is a useful interpretable baseline for many linear time-series problems, while other statistical or machine-learning approaches may be stronger when seasonality, nonlinear relationships, many external predictors, multiple related series, or large-scale data become central.

QuestionARIMA perspective
InterpretabilityExplicit lag, differencing, and error structure can be inspected.
NonlinearityStandard ARIMA is fundamentally a linear model.
SeasonalityUse seasonal extensions when seasonal structure is important.
Model choiceCompare against sensible baselines and alternatives using chronological validation.

Common ARIMA Mistakes

Randomly shuffling the series

Forecasting evaluation should respect time order.

Assuming p-value < 0.05 proves stationarity

ADF tests a unit-root null under a chosen specification; use it with plots and other diagnostics.

Choosing p and q mechanically from ACF/PACF

They are useful clues, especially in simpler AR/MA cases, but mixed models need broader diagnostics and validation.

Calling the lowest AIC the guaranteed best forecast

AIC is an in-sample model-selection criterion; later-period forecast performance still matters.

Using plain ARIMA for strong seasonality without checking it

Seasonal patterns may require seasonal differencing and seasonal AR/MA terms.

Confusing MA(q) with a rolling moving average

The MA in ARIMA refers to lagged model innovations/errors, not simply averaging recent observations.

Quick FAQ

Does ARIMA require the raw series itself to be stationary?

Not necessarily. The integrated part allows differencing. The goal is for the appropriately differenced process modeled by the ARMA terms to satisfy the model assumptions reasonably well.

Is ARIMA only for one-step-ahead forecasts?

No. Multi-step forecasts are possible, although uncertainty generally grows as the forecast horizon extends.

What should I learn next?

Continue with Moving Average, Exponential Smoothing, and Forecasting Basics.

Final Summary

Most Important Insight

ARIMA combines lagged values, differencing, and lagged errors. Choose p, d, and q using evidence rather than fixed rules, respect time order during evaluation, inspect residuals, and validate forecasts on later unseen observations. For strong seasonal structure, move to a seasonal extension rather than forcing plain ARIMA to explain everything.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "ARIMA"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Summary / Key Takeaways

  • ARIMA combines autoregression, differencing, and lagged forecast errors.
  • p, d, and q control those three parts.
  • Differencing can remove trend and improve stationarity.
  • ACF and PACF guide candidate lag orders.
  • Residuals should resemble uncorrelated noise.
  • Use chronological validation and compare with naive forecasts.

Knowledge Check

Progress: 0/4

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 4
What do p, d, q in ARIMA(p,d,q) control?
Question 2 of 4
What is stationarity and why does ARIMA require it?
Question 3 of 4
ACF cuts off sharply after lag 2, while PACF decays gradually. What ARIMA order does this suggest?
Question 4 of 4
How do you check if ARIMA residuals indicate a good fit?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What do p, d, q in ARIMA(p,d,q) control?▼

Correct Answer: p=past values used; d=differencing order for stationarity; q=past forecast errors used

AR(p) uses p lagged observations. I(d) differences d times to remove trends and achieve stationarity. MA(q) uses q past forecast errors to correct predictions.

2What is stationarity and why does ARIMA require it?▼

Correct Answer: A stationary series has constant mean, variance, and autocorrelation over time. ARIMA assumes these properties — trends and seasonality violate them, making model parameters unstable and forecasts unreliable

ARIMA's coefficients are estimated assuming the process doesn't change over time. A trending series makes the model learn different parameters in different time windows — unreliable forecasts.

3ACF cuts off sharply after lag 2, while PACF decays gradually. What ARIMA order does this suggest?▼

Correct Answer: ARIMA(0,d,2) — pure MA(2). Sharp ACF cutoff and gradual PACF decay is the MA signature

ACF cuts off at lag q → MA(q). PACF cuts off at lag p → AR(p). Gradual PACF and ACF cutting off at lag 2 → MA(2) process.

4How do you check if ARIMA residuals indicate a good fit?▼

Correct Answer: Good residuals should be white noise: ACF of residuals shows no significant autocorrelation at any lag, and Ljung-Box test p-value > 0.05

If residuals contain autocorrelation, the model hasn't fully captured the time series structure. White noise residuals confirm the model explains all systematic variation.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Optional Learning Resources

These resources may complement the lesson. They are optional and are not required to use ML Academy.

As an Amazon Associate I earn from qualifying purchases. Other links are identified separately when they are not affiliate links.

Next