cJc cJc - 4 years ago 219
Python Question

How to calculate expanding cointegration using latest pandas version?

Using this post answer as template for the calculation, I get a depreciation warning: FutureWarning: pd.expanding_apply is deprecated for Series and will be removed in a future version, replace with Series.expanding(min_periods=36).apply(args=,func=,kwargs=)

Old code:

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,

How can I write the last line of code using Pandas 0.19.2?

I tried:
hist_coint = pd.DataFrame.expanding(min_periods=20).apply(data.realgdp, rolling_coint, args = (data.realdpi,))

with the following error: TypeError: unbound method expanding() must be called with DataFrame instance as first argument (got nothing instead)

Any ideas how to get this right?

Answer Source

The syntax for Series.expanding().apply() has been modified starting with v0.18.0 as follows:

data.realgdp.expanding(min_periods=36).apply(rolling_coint, args=(data.realdpi,))
# <-SERIES->.expanding(..............).apply(<FUNC>, args=())
#                                                   / passed \ 
#                                                  / as tuple \
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download