如何在Python中创建循环(带pvalue检查的ADF测试)

2024-10-01 11:27:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中创建循环时,我需要一些帮助。以下是我正在使用的代码:

import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
from statsmodels.graphics.tsaplots import plot_acf
from statsmodels.graphics.tsaplots import plot_pacf
%matplotlib inline

df= pd.read_csv('original_data.csv', index_col='1')

from statsmodels.tsa.stattools import adfuller

def adf_test(timeseries):
    #Perform Dickey-Fuller test:
    test_types = ['nc','c','ct']
    for tests in test_types:
        print ('\n Results of Dickey-Fuller Test type =  {}:\n'.format(tests))
        dftest = adfuller(timeseries,regression=tests,autolag='AIC')
        dfoutput = pd.Series(dftest[0:4],index=['Test Statistic','p-value','#Lags used','#Observations used'])

       # for key, value in dftest[4].items():
       #     dfoutput['Critical value (%s)'%key] = value
        print(dfoutput)

    p_value = dftest[1]

    if p_value > 0.05:
        print('Unit root!')
    elif p_value < 0.05:
        print('No unit root!')


adf_test(df['2']) #2 is the number of the column in the cvs file

n = 1
df['rates_difference'] = df['2']-df['2'].shift(n)

adf_test(df['rates_difference'].dropna())

n = 1
df['rates_difference2'] = df['rates_difference']-df['rates_difference'].shift(n)

adf_test(df['rates_difference2'].dropna())

其思想是,代码使用3个版本的ADF测试来检查数据是否平稳(p值<;0.05)。如果不是,那么我们必须做第一个差分并再次检查。如果它不再是静止的,我们必须进行第二次差分并检查p值。所以这个过程必须循环,直到数据静止

提前谢谢


Tags: infromtestimportdfvalueastests