Skip to content

ENH: more work on copula (deriv, classes) - #5076

Merged
josef-pkt merged 1 commit into
statsmodels:masterfrom
josef-pkt:copula_update
Aug 31, 2018
Merged

josef-pkt merged 1 commit into
statsmodels:masterfrom
josef-pkt:copula_update

Conversation

@josef-pkt

@josef-pkt josef-pkt commented Aug 30, 2018 •

Copy link
Copy Markdown
Member

resurrecting copulas see #4046

the first commit is from 2011 and was never included in the statsmodels.sandbox version

@josef-pkt

Copy link
Copy Markdown
Member Author

example that was in the __main__ of my version of copula.py

# -*- coding: utf-8 -*-
"""

Author: Josef Perktold
"""



import numpy as np
from statsmodels.sandbox.distributions.copula import (copulanamesbv,
                                                      CopulaArchimedean,
                                                      TransfClayton,
                                                      TransfFrank,
                                                      TransfGumbel,
                                                      )

copula_examples = [
                   ('indep', ()),
                   ('min', ()),
                   ('max', ()),
                   ('clayton', (0.5,)),
                   ('clayton', (1.1,)),
                   ('clayton', (2.,)),
                   ('frank', (0.5,)),
                   ('frank', (2.,)),
                   ('frank', (10.,)),
                   ('gumbel', (2.,))
                   ]

doplot = 1
if doplot:
    eps = 0.1 #1e-4
    import matplotlib.pyplot as plt
    u = np.linspace(0+eps,1-eps,51)[:,None]
    for c, a in copula_examples[-2:]:
        cdfvalues = copulanamesbv[c](u, u.T, *a)
        plt.figure()
        plt.contour(cdfvalues)
        plt.title(c + repr(a))

    uvec = np.column_stack(map(np.ravel, np.broadcast_arrays(u, u.T)))
    clayton = CopulaArchimedean(TransfClayton())
    cdfv = clayton.cdf(uvec, args=(0.9,), axis=1)
    plt.figure()
    #plt.contour(uvec[:,0], uvec[:,1], cdfv)
    plt.contour(cdfv.reshape(51, 51))
    plt.title('clayton 0.5 class cdf')
    pdfv = clayton.pdf(uvec, args=(0.99,), axis=1)
    plt.figure()
    #plt.contour(uvec[:,0], uvec[:,1], cdfv)
    plt.contour(pdfv.reshape(51, 51))
    plt.title('clayton 0.99 class pdf')

    frank = CopulaArchimedean(TransfFrank())
    pdfv = frank.pdf(uvec, args=(0.5,), axis=1)
    plt.figure()
    #plt.contour(uvec[:,0], uvec[:,1], cdfv)
    plt.contour(pdfv.reshape(51, 51))
    plt.title('frank 0.99 class pdf')

    gumbel = CopulaArchimedean(TransfGumbel())
    pdfv = gumbel.pdf(uvec, args=(2.,), axis=1)
    cdfv = gumbel.cdf(uvec, args=(2,), axis=1)
    print(pdfv.shape, cdfv.shape)
    plt.figure()
    #plt.contour(uvec[:,0], uvec[:,1], cdfv)
    plt.contour(cdfv.reshape(51, 51))
    plt.title('gumbel 2 class cdf')

    plt.show()

@josef-pkt

Copy link
Copy Markdown
Member Author

Right now I only added the commit, I don't really know what the status is.
Looks like working towards multivariate version with dimension larger than bivariate and a class for it.

@coveralls

Copy link
Copy Markdown

Coverage Status

Coverage decreased (-0.07%) to 83.904% when pulling 2fd12a7 on josef-pkt:copula_update into a9bb76a on statsmodels:master.

@josef-pkt

josef-pkt commented Aug 31, 2018 •

Copy link
Copy Markdown
Member Author

2 travis fail because of an unrelated XPASS

The derivatives of the archimedean transforms are used to compute the pdf in CopulaArchimedean.pdf

extreme value copulas don't have a full class with pdf yet.
It looks like the cdf can be computed for the EV

>>> import statsmodels.sandbox.distributions.copula as cop
>>> cd = cop.copula_bv_ev(u, u.T, cop.transform_tawn, args=(0.5,0.5,0.5))
>>> cd.shape
(51, 51)
>>> plt.contour(cd)

same pattern as using the archimedean in example script: cdfvalues = copulanamesbv[c](u, u.T, *a)

trying out a few cases for tawn:
with these args the shape of the cdf looks strange
cd = cop.copula_bv_ev(u, u.T, cop.transform_tawn, args=(0.9,0.9,0.001))
maybe not enough points for good contour interpolation

this one looks closer to min (Leontief in economics)
cd = cop.copula_bv_ev(u, u.T, cop.transform_tawn, args=(0.9,0.9,0.01))

The EV copula transforms are functions without derivatives, while the Archimedean transforms are classes with methods to compute inverse transform and derivatives.
Code for either explicit or generic pdf for EV copulas is missing. Maybe something similar to CopulaArchimedean.pdf can be used for EV copulas.

@josef-pkt

josef-pkt commented Aug 31, 2018 •

Copy link
Copy Markdown
Member Author

multivariate > 2:
I don't see an example for the case with more than 2 marginals, e.g. for copula_mv_archimedean, copula_power_mv_archimedean
CopulaArchimedean looks like it's designed for arbitrary multivariate dimension (uses sum and product), but I'm not sure all terms in the pdf do this.
example/test case ?

a guess based on reading the code:
CopulaDistribution is designed for multivariate >= 2, but the cdf has not been fully adjusted yet, and might need a mv (not bv) copula function. Currently it uses two marginals and not an arbitrary number >=2.

another guess: It might be possible to create nested copulas in a similar way that wraps the current bivariate copula functions in loops.

@josef-pkt

Copy link
Copy Markdown
Member Author

3 times the same functionality:
cdf for Archimedean copulas can currently be computed in 3 ways:

  • explicit formulas: copula_bv_indep, ... used in copulanamesbv
  • copula_bv_archimedean or copula_mv_archimedean with using transform
  • CopulaArchimedean class with using transform

It looks like those define only the copula, using given (uniform) marginal values

CopulaDistributionBivariate, CopulaDistribution combine the Copula class with the marginal distributions to get the distribution for the observed variables.
Marginal distribution is provided currently by cdf functions, and we don't have other method besides cdf yet.

@josef-pkt

josef-pkt commented Aug 31, 2018 •

Copy link
Copy Markdown
Member Author

generic idea (I don't know about the details, and didn't read up on fit methods)
The classes for copula and distribution are designed in a similar way to scipy distributions, i.e. args are provided like params to each method and are not attributes of the instance (i.e. are not frozen distributions).
This means that one fit method could be to use Generic MLE, i.e. we could wrap the distribution in a estimation class, possibly using link functions to impose the limits on the parameters (e.g. (0,1) or [0, inf), or (-inf, 0))

There are no params/args yet for the marginal distributions in the CopulaDistribution classes. We will need those if we want to estimate parametric marginal and parametric copula at the same time.

If we use edf/empirical marginal distribution to estimate the copula parameters, then we only need the copula class and not a Distribution class.

@josef-pkt

Copy link
Copy Markdown
Member Author

some quick browsing/search:

the copula density is C12 (F1(·),F2(·))f1(·)f2(·)
page 54 equ 4.1 in
Pravin K. Trivedi and David M. Zimmer (2007), "Copula Modeling: An Introduction for Practitioners", Foundations and Trends® in Econometrics: Vol. 1: No. 1, pp 1-111. http://dx.doi.org/10.1561/0800000005

C12 is the second cross derivative of the copula
C12((F1|x1;β1), (F2|x2;β2);θ) = ∂C((F1|x1;β1), (F2|x2;β2);θ)/∂F1∂F2

f1, f2 are pdf of marginal distributions, so the CopulaDistribution classes need a marginal distribution instances that have both cdf and pdf methods.

(edf is not a continuous distribution, so that will not work for getting a copula distribution density)

@josef-pkt

Copy link
Copy Markdown
Member Author

a notebook based on the old script with addition of plots of extreme value copulas:
https://gist.github.com/josef-pkt/ac83ac2a414424cc384b3a94570a9f8a

(time to stop and go back to the scheduled program)

@josef-pkt

Copy link
Copy Markdown
Member Author

This is essentially backwards compatible with the current master version.
It's still in the sandbox, so I don't see a problem with merging this.

@josef-pkt

josef-pkt commented Aug 31, 2018 •

Copy link
Copy Markdown
Member Author

a reference in one of my old folders, survey for quickly checking some parts, with finance application
http://www.thierry-roncalli.com/download/copula-survey.pdf working paper from 2000
e.g. has section on MLE, including two-step (first marginal, then copula parameters) and using EDF marginals.

to make a link to a different literature and PR:
canonical MLE (CML) in terminology of Roncalli et al for gaussian copula

  1. transform original data into gaussian data
    a) estimate edf (order statistic)
    b) use norm.ppf (inverse cdf) to transform edf
  2. compute correlation of transformed data

This is identical to one of the covariance/correlation estimators in (outlier) robust
https://github.com/statsmodels/statsmodels/pull/3230/files#diff-0999b4a53db162f8a6150dbeecb638d7R143

@josef-pkt
josef-pkt merged commit f324895 into statsmodels:master Aug 31, 2018
@jbrockmendel

Copy link
Copy Markdown
Contributor

Adding more half-finished stuff to the sandbox makes it harder it harder to identify the actually finished pieces that nom-sandbox relies on. Please let us institute a meaningful separation.

@josef-pkt

josef-pkt commented Aug 31, 2018 •

Copy link
Copy Markdown
Member Author

If someone volunteers to work on code, then I help.
I care a lot more about getting new functionality in than about being pretty.

Once we have unit tests, it can move out of the sandbox, after adding docstring and a bit of cleanup.
(not sure if we need to privatize functions with leading underscore, or rename transform to generator)

@jbrockmendel

Copy link
Copy Markdown
Contributor

This obviously doesn’t belong outside of the sandbox. Stats.diagnostic and multicomp code that is used outside sandbox belongs outside.

We all know you don’t care about “prettiness” (AKA “bug prevention”) but you could avoid actively hampering the process and just empower Kevin to handle stuff you don’t care about.

@josef-pkt

Copy link
Copy Markdown
Member Author

prettiness is only marginally related to bug prevention, unit tests are the main tool for that.

(I would have given Kevin commit rights a long time ago because he is one of the main maintainers of statsmodels, but I worry that in combination with you after one month I will not recognize nor find my way around the code base anymore.)

@jbrockmendel

Copy link
Copy Markdown
Contributor

unit tests are the main tool for that.

And I look forward to the day when the test suite is reliable (#4966). Even then, the best tool is the Mark I Eyeball, and for that readability counts.

I would have given Kevin commit rights a long time ago

I'll consider it a win that this suggestion finally got a response.

but I worry that in combination with you after one month I will not recognize

Consider agreeing to reasonable limits on what a new committer is allowed to handle solo. e.g. CI, or Build, or docstrings, or tests, or "non-namespace-changing readability improvements that I don't want to bother with", or only modules with names containing the letter "r", or ...

nor find my way around the code base anymore

If done correctly, the code layout would be self-explanatory (#4992). Regardless, the vast majority of recent PRs wouldn't change layout, and those that do are for the very good reason of isolating sandbox from non-sandbox (#4887).

jbrockmendel added a commit to jbrockmendel/statsmodels that referenced this pull request Sep 1, 2018
rgommers added a commit that referenced this pull request Sep 2, 2018
@josef-pkt josef-pkt added this to the 0.10 milestone Sep 16, 2018
@josef-pkt
josef-pkt deleted the copula_update branch February 21, 2021 02:52
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.

3 participants