Aka*_*all 17 python linear-regression pandas
我想知道是否有更好的方法来测试两个变量是否是协整的,而不是以下方法:
import numpy as np
import statsmodels.api as sm
import statsmodels.tsa.stattools as ts
y = np.random.normal(0,1, 250)
x = np.random.normal(0,1, 250)
def cointegration_test(y, x):
# Step 1: regress on variable on the other
ols_result = sm.OLS(y, x).fit()
# Step 2: obtain the residual (ols_resuld.resid)
# Step 3: apply Augmented Dickey-Fuller test to see whether
# the residual is unit root
return ts.adfuller(ols_result.resid)
Run Code Online (Sandbox Code Playgroud)
以上方法有效; 但是,效率不高.当我跑步时sm.OLS,会计算很多东西,而不仅仅是残差,这当然会增加运行时间.我当然可以编写自己的代码来计算残差,但我认为这也不会非常有效.
我正在寻找一种直接测试协整的内置测试.我在想Pandas,但似乎找不到任何东西.或者也许有一个聪明的人来测试协整而不运行回归或一些有效的方法.
我必须进行大量的协整测试,并且很好地改进我当前的方法.
您可以尝试以下方法:
import statsmodels.tsa.stattools as ts
result=ts.coint(x, y)
Run Code Online (Sandbox Code Playgroud)
编辑:
import statsmodels.tsa.stattools as ts
import numpy as np
import pandas as pd
import pandas.io.data as web
data1 = web.DataReader('FB', data_source='yahoo',start='4/4/2015', end='4/4/2016')
data2 = web.DataReader('AAPL', data_source='yahoo',start='4/4/2015', end='4/4/2016')
data1['key']=data1.index
data2['key']=data2.index
result = pd.merge(data1, data2, on='key')
x1=result['Close_x']
y1=result['Close_y']
coin_result = ts.coint(x1, y1)
Run Code Online (Sandbox Code Playgroud)
代码是自解释的: - 1)导入必要的包2)获取Facebook和Apple股票的数据一年持续时间3)根据日期列合并数据4)选择收盘价5)进行协整检验6)变量coin_result具有协整检验的统计
| 归档时间: |
|
| 查看次数: |
16956 次 |
| 最近记录: |