Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting Historical Cointegration Values between two pairs

Here is the sample ADF test in python to check for Cointegration between two pairs. However the final result gives only the numeric value for co-integration. How to get the historical results of Co-integration.

Taken from http://www.leinenbock.com/adf-test-in-python/

import numpy as np
import statsmodels.api as stat
import statsmodels.tsa.stattools as ts

x = np.random.normal(0,1, 1000)
y = np.random.normal(0,1, 1000)

def cointegration_test(y, x):
    result = stat.OLS(y, x).fit()    
    return ts.adfuller(result.resid)
like image 298
Rajandran R Avatar asked Mar 19 '23 19:03

Rajandran R


1 Answers

I assume you want to test for expanding cointegration? Note that you should use sm.tsa.coint to test for cointegration. You could test for historical cointegrating relationship between realgdp and realdpi using pandas like so

import pandas as pd
import statsmodels.api as sm

data = sm.datasets.macrodata.load_pandas().data

def rolling_coint(x, y):
    yy = y[:len(x)]
    # returns only the p-value
    return sm.tsa.coint(x, yy)[1]

historical_coint = pd.expanding_apply(data.realgdp, rolling_coint, 
                                      min_periods=36, 
                                      args=(data.realdpi,))
like image 157
jseabold Avatar answered Apr 06 '23 13:04

jseabold