Calculate the Ljung-Box test for autocorrelation.

The test aggregates the squared Autocorrelation Function up to lag h into a single statistic that is chi-squared distributed with h degrees of freedom under the null hypothesis that the series exhibits no autocorrelation up to that lag. A significant result (low p-value) indicates that the series is autocorrelated, which is relevant both as a standalone diagnostic (e.g. to check whether a return series follows a random walk) and as a residual diagnostic after fitting a model (e.g. checking that GARCH residuals are no longer autocorrelated).

For more information about the method, see the following paper:

  • Ljung, G.M., & Box, G.E.P. (1978). “On a Measure of Lack of Fit in Time Series Models.” Biometrika, 65(2), 297-303.

Also known as: Ljung-Box Q test, portmanteau test.

No programming experience? With the Finance Toolkit MCP server, AI assistants such as Claude and ChatGPT can calculate the Ljung-Box Test for you. Just ask in plain English.

Calculate the Ljung-Box Test in Python

The Ljung-Box Test is available in the Econometrics module of the open-source Finance Toolkit. Install it with:

pip install financetoolkit -U

Then call get_ljung_box_test as shown below.

from financetoolkit import Toolkit

toolkit = Toolkit(["AMZN", "TSLA"], api_key="FINANCIAL_MODELING_PREP_KEY")

toolkit.econometrics.get_ljung_box_test(period="quarterly", within_period=False)

Which returns:

  AMZN TSLA
Ljung-Box Statistic 8.7703 7.1814
P-Value 0.554 0.7082

Parameters

get_ljung_box_test accepts the following parameters:

  • period (str, optional): The data frequency for returns (daily, weekly, monthly, quarterly, or yearly). Defaults to “daily”.
  • within_period (bool, optional): Whether to calculate the test within the specified period or for the entire period. Thus whether to look at the test within a specific year (if period = ‘yearly’) or look at the entirety of all years. Defaults to False.
  • lags (int, optional): The number of lags to test for autocorrelation up to. Defaults to 10.
  • include_benchmark (bool, optional): Whether to include “Benchmark” among the assets tested. Defaults to False.
  • rounding (int | None, optional): The number of decimals to round the results to. Defaults to None.

The Econometrics module page introduces the module, and the sidebar lists all of its functions.

Share