ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing
ApX logoApX logo
ModelsCalculatorHardwareCoursesPricing

All Courses

Time Series Analysis and Forecasting
Chapter 1: Introduction to Time Series Data
Characteristics of Time Series Data
Components: Trend, Seasonality, Cyclical, Irregular
Loading and Handling Time Series in Pandas
Time Shifting, Lagging, and Rolling Windows
Visualizing Time Series Data
Hands-on Practice: Loading and Plotting Data
Quiz for Chapter 1
Chapter 2: Time Series Decomposition and Stationarity
Understanding Stationarity
Methods for Time Series Decomposition
Implementing Decomposition in Python
Testing for Stationarity: Visual Inspection
Statistical Tests for Stationarity (ADF Test)
Achieving Stationarity: Differencing
Hands-on Practice: Decomposition and Stationarity Tests
Quiz for Chapter 2
Chapter 3: Autocorrelation and Model Identification
Autocorrelation Function (ACF)
Partial Autocorrelation Function (PACF)
Plotting ACF and PACF in Python
Interpreting ACF/PACF for Model Selection
Hands-on Practice: ACF/PACF Plotting and Interpretation
Quiz for Chapter 3
Chapter 4: ARIMA Models for Forecasting
Autoregressive (AR) Models
Moving Average (MA) Models
Combining AR and MA: ARMA Models
Introducing Integration: ARIMA Models
Selecting ARIMA Order (p, d, q)
Fitting ARIMA Models in Python (statsmodels)
Model Diagnostics and Residual Analysis
Forecasting with ARIMA Models
Hands-on Practice: Building an ARIMA Model
Quiz for Chapter 4
Chapter 5: Handling Seasonality with SARIMA
Limitations of ARIMA with Seasonal Data
Introduction to Seasonal ARIMA (SARIMA)
Identifying Seasonal Components (ACF/PACF)
Selecting SARIMA Order (p, d, q)(P, D, Q)m
Fitting SARIMA Models in Python
Diagnosing SARIMA Models
Forecasting with SARIMA
Hands-on Practice: Building a SARIMA Model
Quiz for Chapter 5
Chapter 6: Model Evaluation and Selection
Need for Model Evaluation
Train-Test Split for Time Series
Common Evaluation Metrics (MAE, MSE, RMSE, MAPE)
Information Criteria (AIC, BIC)
Comparing Forecasts from Different Models
Visualizing Forecast Performance
Hands-on Practice: Evaluating Forecasts
Quiz for Chapter 6
Forecasting Future Trends in a Selected Domain

Plotting ACF and PACF in Python

Generating and visualizing Autocorrelation (ACF) and Partial Autocorrelation (PACF) functions in Python is a fundamental step for time series analysis. These plots are primary tools for visually inspecting the correlation structure of time series data, which aids in identifying potential model parameters. The statsmodels library is primarily used for this purpose.

Remember, ACF and PACF analysis is typically performed on stationary time series data. If your data exhibits trends or seasonality, you should apply transformations like differencing (as discussed in Chapter 2) to achieve stationarity before generating these plots. Operating on non-stationary data can lead to misleading ACF/PACF plots where the underlying correlations are obscured by the trend or seasonality.

Generating the Autocorrelation Function (ACF) Plot

The statsmodels library provides a convenient function, plot_acf, within its graphics.tsaplots module to compute and plot the ACF.

Let's assume you have a stationary time series stored in a Pandas Series object called stationary_series. Here's how you can generate the ACF plot:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.tsa.arima_process import ArmaProcess # To generate sample data

# --- Generate Sample Stationary Data (e.g., AR(1) process) ---
# This simulates data you might have after differencing
np.random.seed(42)
ar_coeffs = np.array([1, -0.7]) # AR parameter = 0.7
ma_coeffs = np.array([1])      # No MA part
ar_process = ArmaProcess(ar_coeffs, ma_coeffs)
sample_data = ar_process.generate_sample(nsample=500)
stationary_series = pd.Series(sample_data)
# ------------------------------------------------------------

# Plot the ACF
fig, ax = plt.subplots(figsize=(10, 5))
plot_acf(stationary_series, lags=20, ax=ax) # Plot first 20 lags
ax.set_xlabel("Lag")
ax.set_ylabel("Autocorrelation")
ax.set_title("Autocorrelation Function (ACF)")
plt.show() # Display the plot

This code snippet first generates some sample stationary data (simulating an AR(1) process for demonstration). The core part is the call to plot_acf(stationary_series, lags=20, ax=ax).

  • The first argument is your stationary time series data (a Pandas Series or NumPy array).
  • The lags parameter specifies how many lags of autocorrelation to calculate and display. Choosing an appropriate number depends on your data's frequency and expected correlation length, but 20-40 lags is often a reasonable starting point.
  • We pass a Matplotlib Axes object (ax) for better control over the plot appearance, though plot_acf can generate its own figure if needed.

The resulting plot typically looks something like this:

The ACF plot shows the correlation coefficient on the y-axis for different time lags on the x-axis. The shaded blue area represents the confidence interval (typically 95%). Correlations extending outside this band are statistically significant. Note that the ACF at lag 0 is always 1, as any series is perfectly correlated with itself. This example shows a typical pattern for an AR process: correlations decay exponentially towards zero.

Generating the Partial Autocorrelation Function (PACF) Plot

Similarly, statsmodels provides the plot_pacf function to compute and plot the PACF. Remember, the PACF measures the correlation between the series and its lag kkk, after removing the linear effects of the intermediate lags (1,2,...,k−11, 2, ..., k-11,2,...,k−1).

The usage is analogous to plot_acf:

# Assuming 'stationary_series' holds your stationary data
from statsmodels.graphics.tsaplots import plot_pacf

# Plot the PACF
fig, ax = plt.subplots(figsize=(10, 5))
plot_pacf(stationary_series, lags=20, ax=ax, method='ywm') # Plot first 20 lags
ax.set_xlabel("Lag")
ax.set_ylabel("Partial Autocorrelation")
ax.set_title("Partial Autocorrelation Function (PACF)")
plt.show() # Display the plot

We use stationary_series again. The lags parameter works the same way. The method parameter specifies how the PACF is estimated; 'ywm' (Yule-Walker Modified) is a common and often default method.

The resulting plot provides insight into the direct relationship between an observation and its lag, removing indirect correlations:

The PACF plot structure is similar to the ACF plot, with lags on the x-axis, partial correlation on the y-axis, and a confidence interval band. Again, values outside the band are statistically significant. This example PACF plot shows a sharp cutoff after lag 1, which is characteristic of an AR(1) process. All partial autocorrelations for lags greater than 1 are close to zero and within the confidence band.

A First Look at Interpretation

Generating these plots is the first step. The real value comes from interpreting the patterns of significant spikes:

  • Autoregressive (AR) processes typically show an ACF plot with correlations that decay gradually (often exponentially or sinusoidally) towards zero and a PACF plot that cuts off sharply after a certain lag ppp. The lag where the PACF cuts off suggests the order ppp for an AR(ppp) model.
  • Moving Average (MA) processes typically show the opposite: an ACF plot that cuts off sharply after a certain lag qqq and a PACF plot with correlations that decay gradually towards zero. The lag where the ACF cuts off suggests the order qqq for an MA(qqq) model.
  • Autoregressive Moving Average (ARMA) processes exhibit gradual decay in both the ACF and PACF plots.

The plots generated above, based on simulated AR(1) data (yt=0.7yt−1+ϵty_t = 0.7 y_{t-1} + \epsilon_tyt​=0.7yt−1​+ϵt​), clearly show this AR pattern: the ACF decays exponentially, while the PACF has a significant spike only at lag 1 and then cuts off (falls within the confidence bands).

By generating and examining these plots for your stationary time series, you gain valuable clues about the underlying data generating process. This visual inspection, combined with quantitative measures discussed later, helps guide the selection of appropriate ppp and qqq orders for ARIMA models, which we will cover in the next chapter. The next section details how to use these patterns for model identification more systematically.

  • Time Series Analysis: Forecasting and Control, George E. P. Box, Gwilym M. Jenkins, Gregory C. Reinsel, Greta M. Ljung, 2015 (Wiley) - A foundational text providing a comprehensive theoretical and practical treatment of ARIMA models, including detailed explanations of autocorrelation and partial autocorrelation functions for model identification.
  • Forecasting: Principles and Practice, Rob J Hyndman, George Athanasopoulos, 2021 (OTexts) - An accessible online textbook covering fundamental time series analysis concepts, including stationarity, ACF, and PACF, with practical examples and clear explanations.
  • statsmodels.graphics.tsaplots.plot_acf Documentation, statsmodels Developers, 2024 - Official documentation for the plot_acf function in the statsmodels Python library, detailing its usage for generating autocorrelation plots. The plot_pacf function works similarly.

© 2026 ApX Machine Learning