Критерий льюнга бокса python

Как выполнить тест Ljung-Box в Python

Тест Льюнга-Бокса — это статистический тест, который проверяет наличие автокорреляции во временном ряду.

Он использует следующие гипотезы:

H 0 : Остатки распределяются независимо.

H A : остатки не распределяются независимо; они демонстрируют серийную корреляцию.

В идеале мы хотели бы не отвергнуть нулевую гипотезу. То есть мы хотели бы, чтобы p-значение теста было больше 0,05, потому что это означает, что остатки для нашей модели временных рядов независимы, что часто является предположением, которое мы делаем при создании модели.

В этом руководстве объясняется, как выполнить тест Ljung-Box в Python.

Пример: тест Льюнга-Бокса в Python

Чтобы выполнить тест Ljung-Box для серии данных в Python, мы можем использовать функцию acorr_ljungbox() из библиотеки statsmodels , которая использует следующий синтаксис:

acorr_ljungbox(x, задержки=нет)

Эта функция возвращает тестовую статистику и соответствующее p-значение. Если p-значение меньше некоторого порога (например, α = 0,05), вы можете отклонить нулевую гипотезу и сделать вывод, что остатки не распределены независимо.

В следующем коде показано, как использовать эту функцию для выполнения теста Льюнга-Бокса на встроенном наборе данных statsmodels под названием «SUNACTIVITY»:

import statsmodels.api as sm #load data series data = sm.datasets.sunspots.load_pandas().data #view first ten rows of data series data[:5] YEAR SUNACTIVITY 0 1700.0 5.0 1 1701.0 11.0 2 1702.0 16.0 3 1703.0 23.0 4 1704.0 36.0 #fit ARMA model to dataset res = sm. tsa.ARMA (data[" SUNACTIVITY "], (1,1)). fit (disp=-1) #perform Ljung-Box test on residuals with lag=5 sm. stats.acorr_ljungbox (res. resid , lags=[5], return_df= True ) lb_stat lb_pvalue 5 107.86488 1.157710e-21 

Тестовая статистика теста составляет 107,86488 , а p-значение теста составляет 1,157710e-21 , что намного меньше 0,05. Таким образом, мы отвергаем нулевую гипотезу теста и заключаем, что остатки не являются независимыми.

Обратите внимание, что в этом примере мы решили использовать значение задержки 5, но вы можете выбрать любое значение, которое хотите использовать для задержки. Например, вместо этого мы могли бы использовать значение 20:

#perform Ljung-Box test on residuals with lag=20 sm. stats.acorr_ljungbox (res. resid , lags=[20], return_df= True ) lb_stat lb_pvalue 20 343.634016 9.117477e-61 

Тестовая статистика теста составляет 343,634016 , а p-значение теста составляет 9,117477e-61 , что намного меньше 0,05. Таким образом, мы еще раз отвергаем нулевую гипотезу теста и заключаем, что остатки не являются независимыми.

Читайте также:  Php format date with timezone

В зависимости от конкретной ситуации вы можете выбрать более низкое или более высокое значение задержки.

Источник

statsmodels.stats.diagnostic.acorr_ljungbox¶

The data series. The data is demeaned before the test statistic is computed.

lags , default None

If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is min(10, nobs // 5). The default number of lags changes if period is set.

boxpierce bool , default False

If true, then additional to the results of the Ljung-Box test also the Box-Pierce test results are returned.

model_df int , default 0

Number of degrees of freedom consumed by the model. In an ARMA model, this value is usually p+q where p is the AR order and q is the MA order. This value is subtracted from the degrees-of-freedom used in the test so that the adjusted dof for the statistics are lags — model_df. If lags — model_df

period int , default None

The period of a Seasonal time series. Used to compute the max lag for seasonal data which uses min(2*period, nobs // 5) if set. If None, then the default rule is used to set the number of lags. When set, must be >= 2.

auto_lag bool , default False

Flag indicating whether to automatically determine the optimal lag length based on threshold of maximum correlation value.

  • lb_stat — The Ljung-Box test statistic.
  • lb_pvalue — The p-value based on chi-square distribution. The p-value is computed as 1 — chi2.cdf(lb_stat, dof) where dof is lag — model_df. If lag — model_df
  • bp_stat — The Box-Pierce test statistic.
  • bp_pvalue — The p-value based for Box-Pierce test on chi-square distribution. The p-value is computed as 1 — chi2.cdf(bp_stat, dof) where dof is lag — model_df. If lag — model_df

Results from linear regression models.

Ljung-Box test statistic computed from estimated autocorrelations.

Ljung-Box and Box-Pierce statistic differ in their scaling of the autocorrelation function. Ljung-Box test is has better finite-sample properties.

Green, W. “Econometric Analysis,” 5th ed., Pearson, 2003.

J. Carlos Escanciano, Ignacio N. Lobato “An automatic Portmanteau test for serial correlation”., Volume 151, 2009.

>>> import statsmodels.api as sm >>> data = sm.datasets.sunspots.load_pandas().data >>> res = sm.tsa.ARMA(data["SUNACTIVITY"], (1,1)).fit(disp=-1) >>> sm.stats.acorr_ljungbox(res.resid, lags=[10], return_df=True) lb_stat lb_pvalue 10 214.106992 1.827374e-40 

Источник

statsmodels.stats.diagnostic.acorr_ljungbox¶

The data series. The data is demeaned before the test statistic is computed.

lags , default None

If lags is an integer then this is taken to be the largest lag that is included, the test result is reported for all smaller lag length. If lags is a list or array, then all lags are included up to the largest lag in the list, however only the tests for the lags in the list are reported. If lags is None, then the default maxlag is min(10, nobs // 5). The default number of lags changes if period is set.

boxpierce bool , default False

If true, then additional to the results of the Ljung-Box test also the Box-Pierce test results are returned.

model_df int , default 0

Number of degrees of freedom consumed by the model. In an ARMA model, this value is usually p+q where p is the AR order and q is the MA order. This value is subtracted from the degrees-of-freedom used in the test so that the adjusted dof for the statistics are lags — model_df. If lags — model_df

period int , default None

The period of a Seasonal time series. Used to compute the max lag for seasonal data which uses min(2*period, nobs // 5) if set. If None, then the default rule is used to set the number of lags. When set, must be >= 2.

auto_lag bool , default False

Flag indicating whether to automatically determine the optimal lag length based on threshold of maximum correlation value.

  • lb_stat — The Ljung-Box test statistic.
  • lb_pvalue — The p-value based on chi-square distribution. The p-value is computed as 1 — chi2.cdf(lb_stat, dof) where dof is lag — model_df. If lag — model_df
  • bp_stat — The Box-Pierce test statistic.
  • bp_pvalue — The p-value based for Box-Pierce test on chi-square distribution. The p-value is computed as 1 — chi2.cdf(bp_stat, dof) where dof is lag — model_df. If lag — model_df

Results from linear regression models.

Ljung-Box test statistic computed from estimated autocorrelations.

Ljung-Box and Box-Pierce statistic differ in their scaling of the autocorrelation function. Ljung-Box test is has better finite-sample properties.

Green, W. “Econometric Analysis,” 5th ed., Pearson, 2003.

J. Carlos Escanciano, Ignacio N. Lobato “An automatic Portmanteau test for serial correlation”., Volume 151, 2009.

>>> import statsmodels.api as sm >>> data = sm.datasets.sunspots.load_pandas().data >>> res = sm.tsa.ARMA(data["SUNACTIVITY"], (1,1)).fit(disp=-1) >>> sm.stats.acorr_ljungbox(res.resid, lags=[10], return_df=True) lb_stat lb_pvalue 10 214.106992 1.827374e-40 

Источник

Оцените статью