Skip to content

Instantly share code, notes, and snippets.

@pkgandhi
Last active August 9, 2020 17:27
Show Gist options
  • Save pkgandhi/ba07aa78547f5a23b4f11ffdbb2fb22d to your computer and use it in GitHub Desktop.
Save pkgandhi/ba07aa78547f5a23b4f11ffdbb2fb22d to your computer and use it in GitHub Desktop.
Using ADF test to check stationarity
# Loading the packages
import pandas as pd
import numpy as np
import statsmodels.tsa.stattools as sm
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
# Loading the dataset:
data = pd.read_csv('../AirPassengers.csv')
data = data.rename(columns = {'#Passengers':'Passengers'})
data = data.set_index('Month')
# Plotting the data (Figure A):
ax = data.plot(linewidth = 0.8)
ax.set_xlabel('Year')
ax.set_ylabel('Number of Passengers')
ax.set_title('Monthly Passengers')
# Applying ADF Test:
nonst_test = sm.adfuller(data)
# Printing the results (Table under Figure A):
output = pd.Series(nonst_test[0:4], index=['t-statistic','p-value','lags-used','no-of-observations'])
for key,value in nonst_test[4].items():
output['Critical Value (%s)'%key] = value
print(output)
# Apply transformation to make data stationary:
log_data = np.log(data) # Taking the log
ma_data = log_data.rolling(window=12).mean() # Taking moving average
log_minus_ma_data = log_data - ma_data
log_minus_ma_data.dropna(inplace=True)
# Plotting the data (Figure B):
ax = log_minus_ma_data.plot(linewidth = 0.8)
ax.set_xlabel('Year')
ax.set_ylabel('Number of Passengers')
ax.set_title('Monthly Passengers')
# Applying ADF Test after applying transformations:
st_test = sm.adfuller(log_minus_ma_data)
# Printing the results (Table under Figure B):
output = pd.Series(st_test[0:4], index=['t-statistic','p-value','lags-used','no-of-observations'])
for key,value in st_test[4].items():
output['Critical Value (%s)'%key] = value
print(output)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment