Skip to content

Instantly share code, notes, and snippets.

@jaradc
Created November 8, 2017 23:19
Show Gist options
  • Save jaradc/9316cf33f66758ead3bfe734b7159845 to your computer and use it in GitHub Desktop.
Save jaradc/9316cf33f66758ead3bfe734b7159845 to your computer and use it in GitHub Desktop.
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller
def test_stationarity(timeseries):
'''
timeseries has a date index and a single column of numeric values
'''
#Determing rolling statistics
rolmean = timeseries.rolling(window=52,center=False).mean()
rolstd = timeseries.rolling(window=52,center=False).std()
#Plot rolling statistics:
orig = plt.plot(timeseries, color='blue',label='Original')
mean = plt.plot(rolmean, color='red', label='Rolling Mean')
std = plt.plot(rolstd, color='black', label = 'Rolling Std')
plt.legend(loc='best')
plt.title('Rolling Mean & Standard Deviation')
plt.show(block=False)
#Perform Dickey-Fuller test:
print('Results of Dickey-Fuller Test:')
dftest = adfuller(timeseries.iloc[:, 0].values, autolag='AIC')
dfoutput = pd.Series(dftest[0:4], index=['Test Statistic','p-value','#Lags Used','Number of Observations Used'])
for key,value in dftest[4].items():
dfoutput['Critical Value (%s)'%key] = value
print(dfoutput)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment