请 [注册] 或 [登录]  | 返回主站

量化交易吧 /  源码分享 帖子:3151961 新帖:17

带P值ADF

asadadsa发表于:6 月 24 日 00:00回复(1)
from pandas import *
import numpy as np
import jqdata
import matplotlib.pyplot as plt
matplotlib.rcParams['axes.unicode_minus']=False # 解决负号显示异常的问题
import pandas as pd
from scipy import stats
import statsmodels.api as sm
IndexData = get_price('000002.XSHG', start_date='2017-01-01',
                      end_date='2018-01-01', frequency='daily', fields=['close']) # 取得上证指数2016年的收盘价格
IndexData.head()
close
2017-01-03 3283.45
2017-01-04 3307.45
2017-01-05 3314.39
2017-01-06 3302.79
2017-01-09 3320.53
IndexData['changepct'] =''
for i in range(0,len(IndexData['close'])-1):
    IndexData.iloc[i, 1] = 100*(IndexData['close'][i+1] - IndexData['close'][i])/IndexData['close'][i] # 计算每日收益率
IndexData['changepct'] = IndexData['changepct'][0:-1] 
IndexData['closeDif_1'] = IndexData['close'].diff(1)
IndexData['closeDif_2'] = IndexData['closeDif_1'].diff(1)
IndexData = IndexData[0:-1] # 由于changepct值最后一行缺失,因此去除最后一行

IndexData['changepct'] = float64(IndexData['changepct']) #使changepct数据类型和其他三列保持一致
IndexData.tail()
close changepct closeDif_1 closeDif_2
2017-12-22 3452.99 -0.503621 -3.15 -16.20
2017-12-25 3435.60 0.782978 -17.39 -14.24
2017-12-26 3462.50 -0.920722 26.90 44.29
2017-12-27 3430.62 0.628749 -31.88 -58.78
2017-12-28 3452.19 0.327039 21.57 53.45
len(IndexData['changepct']) # 数据量
243
IndexData.plot(subplots=True,figsize=(18,12))
array([Axes(0.125,0.732174;0.775x0.147826),
       Axes(0.125,0.554783;0.775x0.147826),
       Axes(0.125,0.377391;0.775x0.147826), Axes(0.125,0.2;0.775x0.147826)], dtype=object)
closedata = IndexData['close'] # 取得上证指数2016年收盘价
closedata.plot(figsize = (15,5))
<matplotlib.axes._subplots.AxesSubplot at 0x7fe43b896a90>
closedata = np.array(closedata) # 收盘价的ADF检验
adftest = sm.tsa.stattools.adfuller(closedata)
dif1closedata = IndexData['closeDif_1'] #收盘价一阶差分的ADF检验
dif1closedata = dif1closedata[1:] # 去除第一行的NaN值
dif1closedata = np.array(dif1closedata)
adftestdif1 = sm.tsa.stattools.adfuller(dif1closedata)
dif2closedata = IndexData['closeDif_2'] #收盘价二阶差分的ADF检验
dif2closedata = dif2closedata[2:] # 去除前两行的NaN值
dif2closedata = np.array(dif2closedata)
adftestdif2 = sm.tsa.stattools.adfuller(dif2closedata)
output=pd.DataFrame(index=["p-value"],columns=["original", "dif1", "dif2"])
output.loc["p-value"]["original", "dif1", "dif2"] = adftest[1], adftestdif1[1], adftestdif2[1]
output
original dif1 dif2
p-value 0.4814242 6.826172e-29 3.326064e-11
 

全部回复

0/140

量化课程

    移动端课程