Skip to content

BUG/REF: fixing a few VAR problems - #4538

Merged
josef-pkt merged 9 commits into
statsmodels:masterfrom
josef-pkt:bug_var_vecm
Apr 26, 2018
Merged

josef-pkt merged 9 commits into
statsmodels:masterfrom
josef-pkt:bug_var_vecm

Conversation

@josef-pkt

Copy link
Copy Markdown
Member

WIP
trying to get a few fixes into 0.9

plot now return fig, rename test_whiteness methods closes #4537
(old test_whiteness is now plot_acorr)

I'm still thinking about #4535

@coveralls

coveralls commented Apr 23, 2018 •

Copy link
Copy Markdown

Coverage Status

Coverage increased (+0.07%) to 82.836% when pulling 50c0235 on josef-pkt:bug_var_vecm into 7cbaa2e on statsmodels:master.

@codecov-io

codecov-io commented Apr 23, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #4538 into master will increase coverage by 0.06%.
The diff coverage is 90.47%.

Impacted file tree graph

@@            Coverage Diff             @@
##           master    #4538      +/-   ##
==========================================
+ Coverage   80.15%   80.22%   +0.06%     
==========================================
  Files         563      563              
  Lines       85238    85412     +174     
  Branches     9656     9672      +16     
==========================================
+ Hits        68326    68525     +199     
+ Misses      14685    14658      -27     
- Partials     2227     2229       +2
Impacted Files Coverage Δ
statsmodels/tsa/vector_ar/tests/test_vecm.py 90.4% <ø> (ø) ⬆️
statsmodels/tsa/vector_ar/tests/test_var_jmulti.py 78.74% <100%> (ø) ⬆️
statsmodels/tsa/vector_ar/irf.py 54.22% <100%> (+2.25%) ⬆️
statsmodels/tsa/vector_ar/svar_model.py 62.03% <100%> (+0.12%) ⬆️
statsmodels/tsa/vector_ar/plotting.py 90.34% <100%> (+6.42%) ⬆️
statsmodels/tsa/vector_ar/util.py 84.21% <42.85%> (-2.83%) ⬇️
statsmodels/tsa/vector_ar/var_model.py 86.64% <85.22%> (+3.1%) ⬆️
statsmodels/tsa/vector_ar/tests/test_var.py 93.58% <97.11%> (+1.37%) ⬆️
statsmodels/genmod/tests/test_bayes_mixed_glm.py 99.5% <0%> (ø) ⬆️
statsmodels/tsa/vector_ar/dynamic.py 15.38% <0%> (+0.23%) ⬆️
... and 4 more

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 7cbaa2e...50c0235. Read the comment docs.

@josef-pkt

Copy link
Copy Markdown
Member Author

This includes now part of a solution for exog, based on notes in #4535

fix and unit test for varsim/simulate_var and VARProcess.mean (maybe rename to intercept_longrun)
docstrings not updated yet.
not checked yet: simulation irf_xxx
unit tests added only for backwards case, trend='c' and no exog
smoketests for plots with fig return

@josef-pkt

Copy link
Copy Markdown
Member Author

The irf plots in BaseIRAnalysis also don't return the fig.

@josef-pkt

josef-pkt commented Apr 24, 2018 •

Copy link
Copy Markdown
Member Author

ci tests are all red
While fixing VAR and test_var, I broke VECM and test_var_jmulti. (I didn't run those locally)

@josef-pkt

josef-pkt commented Apr 24, 2018 •

Copy link
Copy Markdown
Member Author

conflicting definitions between VARProcess and VARResults. (double assignment of attributes in both classes makes this fragile)

VARResults defined k_trend as k_exog_all, i.e. self.k_trend = self.coefs_exog.shape[1]. I changed it in VARProcess to use the original k_trend = trend order

changed in last commit by replacing k_trend with k_exog (meaning trend + exog_user).
I needed to add defaults for the params_info attributes to make VECM and VAR happy.
no more local test failures in any vector_ar/tests

@josef-pkt

Copy link
Copy Markdown
Member Author

this should be fine now, except for updating the docstrings and maybe some cleanup, as far as it is unit tested.

FEVD works, but I have no intuition to interpret plot or guess whether it's ok. There are only smoke tests for it (as pointed out by @jbrockmendel in some (?) issue)

IRF has unit test, in test_var, test_var_jmulti and test_vecm.
Asymptotic standard errors are tested in test_var, but no error bands like 'mc' are unit tested.

SVAR has only some basic tests for the estimation (that I had added against Stata) but not test for postestimation extras.

@jbrockmendel

Copy link
Copy Markdown
Contributor

conflicting definitions between VARProcess and VARResults. (double assignment of attributes in both classes makes this fragile)

+1 for addressing this. I'll give this a review later this afternoon.

assert_equal(res0.k_ar, 2)

# SMOKE test
if have_matplotlib:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

separate test


obtained = results_sm[ds][dt].test_whiteness_new(nlags=lags,
obtained = results_sm[ds][dt].test_whiteness(nlags=lags,
adjusted=True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

indentation

coefs = results_sm[ds][dt].var_rep
intercept = np.zeros(len(sigma_u))
# Note: _params_info k_trend, k_exog, ... is inferred with defaults
var = VARProcess(coefs, intercept, sigma_u)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is intercept right here? I thought it now wants exog (which is problematic for other reasons)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's fine
it wants now coefs_exog in this PR (not exog data as after VECM),
intercept params are a special case of coefs_exog.

Comment thread statsmodels/tsa/vector_ar/util.py Outdated
if not len(intercept) == len(ugen):
raise ValueError('1-D intercept needs to have length `steps`')
# if np.ndim(intercept) == 1:
# intercept = intercept[:, None]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please delete instead of commenting-out.

**Attributes**:
"""
def __init__(self, coefs, exog, sigma_u, names=None):
def __init__(self, coefs, coefs_exog, sigma_u, names=None, _params_info=None):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is _params_info the best name for an argument? private arg names seem kinda weird

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

VARProcess is mostly an internal class.
private _params_info is weird but the best I managed to come up with for this not so fast quickfix.
(It might become public, official but only after seeing how it works for a while. I still don't like several parts in the separation and duplication between process and results class.)

.. math:: \mu = (I - A_1 - \dots - A_p)^{-1} \alpha
"""
return np.linalg.solve(self._char_mat, self.exog)
return np.linalg.solve(self._char_mat, self.intercept)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Possibly a warning that this method is only correct in the no-exog case?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I will change the docstring to long run intercept.
I'm not sure yet about deprecating this method.

Comment thread statsmodels/tsa/vector_ar/var_model.py Outdated

# print(coefs.round(3))
super(VARResults, self).__init__(coefs, exog, sigma_u, names=names)
#self.k_trend = self.coefs_exog.shape[1]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please delete

self.k_exog = self.coefs_exog.shape[1]
self.k_exog_user = k_exog_user

# maybe change to params class, distinguish exog_all versus exog_user

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add "TODO: " to the beginning of this comment?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW VARParams class here isn't quite what I think you're referring to (which I think is more analogous to MixedLMParams), but may still be useful.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

similar but more focused on just holding the parameters and parameter info.
i.e. the meaning and characteristics in terms of the stochastic process, like stationarity, stay in the Process class.

The parameterization should be defined by the model class, so we don't have to fiddle with the values for k_exog, k_trend, const_idx, k_endog, k_ar, ... in the results and process classes.

test="inst", method="wald")

def test_whiteness_new(self, nlags=10, signif=0.05, adjusted=False):
def test_whiteness(self, nlags=10, signif=0.05, adjusted=False):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

YES!

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, finally
I will clean up tonight, one more commit with adding fig return to irf will be coming.

@jbrockmendel
If you still see things that are broken and that I missed, then I could still try to fix them.
I'm not trying to finish full support for exog in all the extras, that part stays experimental/incomplete for 0.9, but I think we managed to resurrect the pre-VECM usecases for intercept or trend without exog (with partial support for exog_user).

@josef-pkt

Copy link
Copy Markdown
Member Author

I just remembered:
I haven't put the parameter uncertainty back into the forecast_interval.
I'm not sure yet. my initital thought was to add it as and option to the interval method but ignore it in the plot. Default might not be backwards compatible, but difference is small unless df_resid is small.

@josef-pkt

Copy link
Copy Markdown
Member Author

I think simulate_var has a bug if exog is not None. It uses self.exog which does not (yet) include trend.
i.e. we need to column_stack trend and exog in this case.
Do we ever store an trend array, or is it always computed directly ?

I included a unit test for offset but not for exog already in VAR.

data = np.diff(np.log(data), axis=0) * 400
cls.res0 = sm.tsa.VAR(data).fit(maxlags=2)

def test_process(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should be split into method-specific tests.

def test_process(self):
res0 = self.res0
k_ar = res0.k_ar
fc20 = res0.forecast(res0.endog[-k_ar:], 20)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC this should return a DataFrame. Assert that?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The unit tests that I added use only numpy arrays. So, in this test class there are no pandas objects.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, my bad. I missed the data = mdata.values line in setup_class. Carry on.

Comment thread statsmodels/tsa/vector_ar/var_model.py Outdated
self.params = params
self.exog = exog
# print(params.shape)
# print(params.round(3))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

delete

observations to start the autoregressive process.
If offset is not None, then exog of the model are used if they were
provided in the model
offset : None or ndarray (steps, neqs)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure I understand what this represents? It looks a little bit like optional realizations for shocks(?)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not for shocks directly, those are still added with random draws.
The term offset is in analogy to GLM.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OK. Consider fleshing out the docstring. I'm more-than-averagely familiar with this code and still don't find this arg obvious.

y = self.simulate_var(steps=steps, offset=offset, seed=seed)
return plotting.plot_mts(y)

def intercept_longrun(self):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Points for explicitness.

r"""Long run intercept of stable VAR process

Warning: trend and exog except for intercept are ignored for this.
This might change in future versions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure how I feel about this, will give it some thought...

There seem to be a lot of methods/attributes that are conceptually (and implementation-ally) cleaner when restricting to no-trend no-exog cases. Part of me wants to separate that (common) nice case from the VARX model/process this is turning into.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Splitting out any of the constant-only cases will make it more difficult to add more trend/exog support later.
E.g. IRF only depends on the estimated lag polynomial, but simulated confidence intervals might require support for exog,
currently irf_errband_mc is only for intercept case (trend in ['nc', 'c']), AFAIU.
same for FEVD if/when we get simulated or bootstrap standard errors or confidence intervals.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Splitting out any of the constant-only cases will make it more difficult to add more trend/exog support later

False. Drawing the lines between classes such that they are internally coherent and represent meaningful abstractions (e.g, VARProcess could represent a "VAR Process") makes things easier to understand and therefore harder to screw up.

If you want to make it easier to do X later, we should be talking about improving internal consistency across the board.

@josef-pkt

Copy link
Copy Markdown
Member Author

problem with matplotlib 1.4.3 on Travis

>               a = fig_asym.axes[1].get_children()[k].get_ydata()
E               AttributeError: 'XAxis' object has no attribute 'get_ydata'

I'm currently using 1.5.3, and don't have any failures/errors, also travis is green with matplotlib 1.5.
So, these unit tests require matplotlib >= 1.5

@josef-pkt

Copy link
Copy Markdown
Member Author

all green, I don't remember enough of the VECM implementation to make changes there,
So I think this is a good place to stop, and merge.

@jbrockmendel

Copy link
Copy Markdown
Contributor

There are some spots I haven't reviewed yet. Mind holding off for a few hours?

import matplotlib
have_matplotlib = True
import matplotlib.pyplot as plt
plt.switch_backend('Agg') # otherwise segfault on windows

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good to know about the windows segfault. Also prevents exceptions (I forget which kind) on headless Linux.

import pytest

have_matplotlib = False
try:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This block is pretty common, may merit putting in something like sm.tools._testing, especially since it has now grown past 2-3 lines.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(not necessarily for this PR)

k_ex = self.coefs_exog.shape[0] if self.coefs_exog.ndim != 1 else 1
k_c = k_ex - self.k_exog_user
else:
k_c = 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not just call this k_trend?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because this is just a temporary variable, and I didn't want to confuse it with the provided k_trend, if provided.

k_c = k_ex - self.k_exog_user
else:
k_c = 0
self.k_trend = _params_info.get('k_trend', k_c)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like "k_trend" and "k_exog_user" are the only keys that are relevant here. Why not just make those optional kwargs to __init__? It's clearer and doesn't risk silently ignoring anything.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

because adding k_trend explicitly is not future proof. We would have to change the signature again if or when we add seasonal, k_seasonal or other deterministic or exog with explicit built in support.

@jbrockmendel jbrockmendel Apr 26, 2018 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nothing is future proof, and it's OK to change the signature when behavior changes. Better to do that than to de-facto change the signature in an opaque and error-prone way.

self.k_exog_user = _params_info.get('k_exog_user', 0)
if self.coefs_exog is not None:
k_ex = self.coefs_exog.shape[0] if self.coefs_exog.ndim != 1 else 1
k_c = k_ex - self.k_exog_user

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Restriction k_c >= 0?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That has to hold, unless there is a bug somewhere else, or the class got the wrong k_exog_user in _params_info (which we control because VARProcess is mainly an internal class)

@jbrockmendel

Copy link
Copy Markdown
Contributor

This isn't my favorite but seems OK-given-decisions-I-dislike. Pending small requested edits, LGTM.

@josef-pkt

Copy link
Copy Markdown
Member Author

on last commit here, I will merge when green

I added parameter uncertainty as option back into VARResults.forecast_cov, but did not add it to forecast_interval because that is more generic in VARProcess.
I think it might be better to remove inference, including forecast_interval from VARProcess (otherwise all sublcasses need to accept, and possibly ignore, additional keywords, like method in this case.)

unit test for forecast_cov with parameter uncertainty:
no verified numbers for now,
is within 5% of the mse forecast_cov in the example for 3 steps forecasting.

@josef-pkt

Copy link
Copy Markdown
Member Author

Nothing is future proof, and it's OK to change the signature when behavior changes. Better to do that than to de-facto change the signature in an opaque and error-prone way.

There is still a fundamental difference in your and my approach to designing the code.
I don't just want a pretty status-quo and change it (possibly in a backwards incompatible way) whenever enhancements come in.
I would like to have a design that makes it easy to add future enhancement and requires only minimal future changes (especially backwards incompatible changes), if and when I can anticipate what those future changes may roughly look like. (e.g. adding seasonal dummies should require only a few lines of changes in VARProcess and VARResults.)
(There are enough parts across statsmodels where I don't have a good idea about future changes, and there "future proofing" the design does not work so well.)

@josef-pkt
josef-pkt merged commit 1c68681 into statsmodels:master Apr 26, 2018
@jbrockmendel

Copy link
Copy Markdown
Contributor

There is still a fundamental difference in your and my approach to designing the code. I don't just want a pretty status-quo and change it

[Comment about the status quo being awful omitted]

This isn't that big a deal; carry on. Thanks for addressing the commented-out code requests.

@jbrockmendel

Copy link
Copy Markdown
Contributor

Some but not all occurrences of self.k_trend have been replaced by self.k_exog. reordered is where I noticed this. Is this intentional?

@josef-pkt

Copy link
Copy Markdown
Member Author

Most likely reordered only handles the trend='c' case and no exog.
I skipped it in my renaming because it looked suspicious and I didn't want to figure out how to change or extend it. It's not used by any other code.

Checking again, I see that it shows up in unit tests, but only one with default trend.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

BUG: VAR test_whiteness is a plot function but uses sample_acorr

4 participants