Skip to content

BUG/ENH VECM follow-up #3775

Open
Open

Description

@josef-pkt

An issue for open issues after merging VECM, to look at or decide before a release
extensions are separate issues #3135 #3133

  • ???
  • check api.py and doc additions
  • why does HypothesisTestResults and subclasses implement __eq__ (LGTM warning)
  • check behavior for not supported cases in coint test, e.g. LGTM Warning "Local variable 'jc' may be used before it is initialized." in coint_table.py
  • standard pattern in plots (add ax), VECM follows VAR in some parts which does not have the "modern" statsmodels pattern and conventions in some parts
  • unit tests are yield based, which might require adjustments when we switch to pytest and they deprecate/remove yield support.
  • backwards compatibility? new methods test_whiteness_new, deprecate replace old methods?

other LGTM warnings seem mostly irrelevant (e.g. we circular import warnings with api.py which I think don't apply.)
https://lgtm.com/projects/g/statsmodels/statsmodels/rev/pr-8201a3203c0ae4914ad5563d67ab9b2fe56ddd2c
https://coveralls.io/builds/12153518/source?filename=%2Fhome%2Ftravis%2Fbuild%2Fstatsmodels%2Fstatsmodels%2Fstatsmodels%2Ftsa%2Fvector_ar%2Fvecm.py

edit/update still open (partial check)

  • summary top table missing
  • missing or incomplete docstrings, e.g. what is cov_params_default? class docstring has non-existing cov_params instead
  • related to cov_params_default, the corresponding bse is stderr_params. There is no params attribute itself. What should be used for Wald tests? i.e. separate or joint components of all parameters. There is no joint params array in the fit method, and no joint Hessian.
  • ...

Activity

  1. josef-pkt commented on Jul 2, 2017

    @josef-pkt
    MemberAuthor

    possible bug-wrong: in the forecast plot in the VECM notebook the seasonal timing looks wrong or shifted, when I use default lag 1, instead of k_ar_diff=lag_order.aic, # =3 (updated keyword).
    parameters for season dummies differ by a large amount from those with k_ar=3.
    with k_ar_diff=3, the results are the same as in the gist

    I'm trying out (and updating) @yogabonito's notebook from the gist (inflation and interest rate)
    https://gist.github.com/yogabonito/b532e20b64587c19198f1aacb5ddfca2

  2. josef-pkt commented on Jul 2, 2017

    @josef-pkt
    MemberAuthor

    about season dummies, AFAICS from browsing parts of the code
    In _endog_matrices the time series are truncated for initial conditions, e.g. y_1_T = y[:, p:]. However, first_season is not adjusted and consequently the first season index refers to the truncated arrays and will depend on k_ar_diff. So coefficients for seasonal dummies are not comparable across different k_ar_diff.

    my guess is that we need something like (first_season + p) modulo season_length.

  3. josef-pkt commented on Jul 2, 2017

    @josef-pkt
    MemberAuthor

    in predict
    first_future_season = (self.first_season + nobs_tot) % self.seasons
    where nobs_tot = self.nobs + self.k_ar

    AFAIU, this assumes first_season is the first period of the untruncated array.

  4. josef-pkt commented on Jul 13, 2017

    @josef-pkt
    MemberAuthor

    cointegration test:
    The display of results does not show an "obvious" test result. I.e. I don't know how to interpret the output of select_coint_rank and coint_johansen without reading again the background of the tests.
    coint_johansen does not have a summary. select_coint_rank is a wrapper around coint_johansen that returns a CointRankResults instance.

    partial correction: select_coint_rank has a rank attribute with the estimated cointegrating rank, the summary table stops at the first not rejected rank.

    edit: deterministic/trend option: replace or alias numbers by deterministic option used in VECM.__init__, e.g. lico

    (question: I have 4 series with cointegrating rank two. I'd like to know if they form two pairs of series or if there is a common cointegrating relationship across all 4.
    (example housing price indices of US regions with 2 pairs of similar regions.))

  5. josef-pkt commented on Jul 13, 2017

    @josef-pkt
    MemberAuthor

    (continued)
    normalization of cointegrating vector depends on order of variables, If there are separate groups of series that are cointegrated within group but not cointegrated across groups, then reordering looks better to get one of each group to be normalized to 1.
    (still just experimenting)

    edit
    I am looking at the size and significance of the coefficients in the adjustment matrix alpha to see which cointegrating vector affects the different endog.
    Also beta after reordering have 1 cointegration vector that is almost (0, 1, 0, -1)

    >>> res.beta.T
    array([[ 1.        ,  0.        , -0.71819192, -0.39092398],
           [ 0.        ,  1.        , -0.09991324, -0.94083385]])
    
  6. josef-pkt commented on Jul 14, 2017

    @josef-pkt
    MemberAuthor
    In [88]: res.predict(steps=12,alpha=0.1)
    
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-88-ca098260f243> in <module>()
    ----> 1 res.predict(steps=12,alpha=0.1)
    
    E:\Josef_new\eclipsews\statsmodels_py34_pr\statsmodels\tsa\vector_ar\vecm.py in predict(self, steps, alpha, exog_fc, exog_coint_fc)
       1693                                      trend_coefs, self.sigma_u, steps,
       1694                                      alpha=alpha,
    -> 1695                                      exog=exog)
       1696         else:
       1697             return forecast(last_observations, self.var_rep, trend_coefs,
    
    E:\Josef_new\eclipsews\statsmodels_py34_pr\statsmodels\tsa\vector_ar\var_model.py in forecast_interval(y, coefs, trend_coefs, sig_u, steps, alpha, exog)
        307     point_forecast = forecast(y, coefs, trend_coefs, steps, exog)
        308     ma_coefs = ma_rep(coefs, 10)
    --> 309     sigma = np.sqrt(_forecast_vars(steps, ma_coefs, sig_u))
        310 
        311     forc_lower = point_forecast - q * sigma
    
    E:\Josef_new\eclipsews\statsmodels_py34_pr\statsmodels\tsa\vector_ar\var_model.py in _forecast_vars(steps, ma_coefs, sig_u)
        293 
        294     """
    --> 295     covs = mse(ma_coefs, sig_u, steps)
        296     # Take diagonal for each cov
        297     neqs = len(sig_u)
    
    E:\Josef_new\eclipsews\statsmodels_py34_pr\statsmodels\tsa\vector_ar\var_model.py in mse(ma_coefs, sigma_u, steps)
        192     for h in range(steps):
        193         # Sigma(h) = Sigma(h-1) + Phi Sig_u Phi'
    --> 194         phi = ma_coefs[h]
        195         var = chain_dot(phi, sigma_u, phi.T)
        196         forc_covs[h] = prior = prior + var
    
    IndexError: index 11 is out of bounds for axis 0 with size 11
    

    plot_forecast fails in the same way
    predict without specifying alpha works

    edit
    steps=11 or smaller works, steps=12 or larger raises above exception,
    the data is monthly data without seasonal deterministic terms
    res.plot_forecast(steps=11, alpha=0.1)

  7. josef-pkt commented on Jul 14, 2017

    @josef-pkt
    MemberAuthor

    res.plot_forecast(steps=11, alpha=0.1, n_last_obs=2*12)
    does not use date index for x-labels

    predict is actually the forecast method (misnomer compared to other tsa model) and does only out-of-sample forecasting.

  8. josef-pkt commented on Jul 14, 2017

    @josef-pkt
    MemberAuthor

    summary() does not contain a top table with model description and overall fit results.

  9. josef-pkt commented on Jul 15, 2017

    @josef-pkt
    MemberAuthor

    cosmetic, print style: could get small improvements
    (notebook don't allow copy paste over several cells)

    line breaks, __repr__, raw %s

    test_gc = res_t.test_granger_causality(1)
    test_gc.summary()
    
    Granger causality F-test. H_0: %s do not Granger-cause East South Central. Conclusion: reject H_0 at 5% significance level.
    Test statistic	Critical value	p-value	df
    8.221	1.676	0.000	(15, 1092)
    
    vars(test_gc)
    
    {'caused': ['East South Central'],
     'causing': ['New England', 'Pacific', 'West South Central'],
     'conclusion': 'reject',
     'conclusion_str': 'Conclusion: reject H_0',
     'crit_value': 1.6755481361219347,
     'df': (15, 1092),
     'h0': 'H_0: %s do not Granger-cause East South Central',
     'method': 'F',
     'pvalue': 5.701613328228913e-18,
     'signif': 0.05,
     'signif_str': ' at 5% significance level',
     'test': 'granger',
     'test_statistic': 8.2213386515454339,
     'title': 'Granger causality F-test'}
    
  10. josef-pkt commented on Jul 15, 2017

    @josef-pkt
    MemberAuthor

    terminology, argument names:
    VECM uses signif instead of the usual alpha, e,g, signif=0.05
    alpha is the matrix of adjustment coefficients

  11. josef-pkt commented on Jul 15, 2017

    @josef-pkt
    MemberAuthor

    not clear to me: Is there a way to get the corresponding VAR models (now that VAR allows exog)?
    get_var_model method?
    AFAICS: the VECMResult uses the VAR representation directly, i.e. var_rep computes A lag-polynomial (?) matrices.

    internal: The data matrices for the regression are attached to the results instance and not to the model instance. Should this change? That's not important at the current stage, given that it's internal (leading underscore attributes)

    edit
    test_granger_causality and test_inst_causality create a VAR model internally

            y, k, t, p = self.y_all, self.neqs, self.nobs - 1, self.k_ar + 1
            exog = _deterministic_to_exog(self.deterministic, self.seasons,
                                          nobs_tot=self.nobs + self.k_ar,
                                          first_season=self.first_season,
                                          seasons_centered=True, exog=self.exog,
                                          exog_coint=self.exog_coint)
            var_results = VAR(y.T, exog).fit(maxlags=p, trend="nc")
    
  12. josef-pkt commented on Jul 15, 2017

    @josef-pkt
    MemberAuthor

    design comment, docs?
    VECM uses the row representation used by Luetkepohl (non-standard for statsmodels, but internal

    arr_list = ['_chol_sigma_u', '_cov_sigma', '_delta_x', '_delta_y_1_T', '_y_lag1']
    [getattr(res_t, i).shape for i in arr_list]
    
    [(4, 4), (10, 10), (28, 311), (4, 311), (5, 311)]
    

    in model
    res_t = VECM(dta_h3, coint_rank=2, deterministic="lico", k_ar_diff=4, seasons=12).fit()

  13. josef-pkt commented on Jul 15, 2017

    @josef-pkt
    MemberAuthor

    can we obtain and plot the stochastic trends? 4 endog, coint_rank=2, should have two stochastic trends
    (I don't remember how that goes.)

  14. josef-pkt commented on Jul 15, 2017

    @josef-pkt
    MemberAuthor

    forecast longer horizon
    BUG fix: forecast_interval in var_model.py limits the ma_rep to 10.
    After changing it to steps, the forecast works also for larger number of steps

    i.e. this should be an existing bug in VAR and is not VECM specific

  15. jbrockmendel commented on Oct 16, 2017

    @jbrockmendel
    Contributor

    Not a big deal, but I'd like to register a preference against the non-standard attributes stderr_endog_lagged, stderr_dt, tvalues_endog_lagged, tvalues_dt, pvalues_endog_lagged, pvalues_dt, stderr_alpha, stderr_gamma, tvalues_det_coef_coint, conf_int_alpha, ...

    Is there a reason why VECMResults a) doesn't inherit from the Results hierarchy and B) doesn't have a VECMResultsWrapper?

    vecm is a huge piece of very nice work.

  16. josef-pkt commented on Oct 16, 2017

    @josef-pkt
    MemberAuthor

    @jbrockmendel
    IIRC you asked a similar question in another issue, where I didn't reply.

    VECMResults a) doesn't inherit from the Results hierarchy

    The problem is that the results hierarchy currently doesn't help in the multivariate endog case. VAR/VECM implement all the special methods that work, while MNLogit inherits things that don't work, e.g. Wald inference, t_test, confint, ....
    The same might be true for the VECMResultsWrapper, but most likely this is partially following the pattern of VAR and partially not having enough time to look into it.

    One problem with VECM is the large number of intermediate arrays or results, and the large number of pieces for the final results. Essentially, I gave up coming up with names or a structure for all the specific things that are needed in VECM. What might be possible is to add more leading underscores if the results are private.

    At least most names are a bit more informative in VECM than in VAR. Names like pvalues_endog_lagged should be pretty mnenomic instead of looking at a slice of the full params and pvalues. Coming up with good names is a lot of work.
    I'm sure there are ways to improve this or organize this better, but I came up empty or it didn't bother me enough given the limited amount of time.

  17. jbrockmendel commented on Oct 16, 2017

    @jbrockmendel
    Contributor

    How long do we have until the next release (i.e. this is set in semi-stone)? I'm pretty slammed in the upcoming week, but may be able to look it over carefully later this month.

  18. josef-pkt commented on Oct 16, 2017

    @josef-pkt
    MemberAuthor

    Nothing is set in stone or semi-stone (my older son had surgery last week and will be at home almost the entire week).

    Bug-fixing and maintenance is a never ending story and at some point we have to pull the plug and release. It will have to be fairly soon, because I start to get impatient and want to do something more fun (either penalized or treatment effects).
    There will always be a next release and some things will have to wait for it.

  19. added this to the 0.9 milestone on Apr 22, 2018
  20. josef-pkt commented on Jan 3, 2019

    @josef-pkt
    MemberAuthor

    this needs an update to list what's still open

    for example I just saw that summary still doesn't have the top table which I mentioned already in a comment above

    Some of the BUGy things and the worst misnamings mentioned above are already fixed, AFAIR.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions