How to do it...

Execute the following steps to test the given time series for stationarity.

  1. Import the libraries:
import pandas as pd
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import adfuller, kpss
  1. Define a function for running the ADF test:
def adf_test(x):

indices = ['Test Statistic', 'p-value',
'# of Lags Used', '# of Observations Used']
adf_test = adfuller(x, autolag='AIC')
results = pd.Series(adf_test[0:4], index=indices)
for key, value in adf_test[4].items():
results[f'Critical Value ({key})'] = value

return results

Now, we can run the test:

adf_test(df.price)

The code generates the following summary:

The null hypothesis of the ADF test states that the time series is not stationary. With a p-value of 1 (or equivalently, the test statistic larger than the critical value for the selected confidence level), we have no reason to reject the null hypothesis, meaning that we can conclude that the series is not stationary.

  1. Define a function for running the KPSS test:
def kpss_test(x, h0_type='c'):

indices = ['Test Statistic', 'p-value', '# of Lags']
kpss_test = kpss(x, regression=h0_type)
results = pd.Series(kpss_test[0:3], index=indices)
for key, value in kpss_test[3].items():
results[f'Critical Value ({key})'] = value

return results

Now, we can run the test:

kpss_test(df.price)

The code generates the following summary:

The null hypothesis of the KPSS test is that the time series is stationary. With a p-value of 0.01 (or test statistic greater than the selected critical value), we have reasons to reject the null hypothesis in favor of the alternative one, meaning that the series is not stationary.

  1. Generate the ACF/PACF plots:
N_LAGS = 40
SIGNIFICANCE_LEVEL = 0.05

fig, ax = plt.subplots(2, 1)
plot_acf(df.price, ax=ax[0], lags=N_LAGS,
alpha=SIGNIFICANCE_LEVEL)
plot_pacf(df.price, ax=ax[1], lags=N_LAGS,
alpha=SIGNIFICANCE_LEVEL)

The output is as follows:

In the ACF plot, we can see that there are significant autocorrelations (above the 95% confidence interval, corresponding to the selected 5% significance level). There are also some significant autocorrelations at lags 1 and 4 in the PACF plot.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.181.166