Stochastic Simulation With Copulas in R

You know we do! A friend of mine gave me a call last week and was wondering if I had a little R code that could illustrate how to do a Cholesky decomposition. He ultimately wanted to build a Monte Carlo model with correlated variables. I pointed him to a number of packages that do Cholesky decomp but then I recommended he consider just using a Gaussian Copula and R for the whole simulation. For most of my copula needs in R, I use the QRMlib package which is a code companion to the book Quantitative Risk Management: Concepts, Techniques and Tools by Alexander J. McNeil, Rudiger Frey and Paul Embrechts. The book is only loosely coupled (pun intended) with the code in the QRMlib package. I really wish the book had been written with code examples and tight linkage between the book and the code. Of course I’m the type of guy who prefers code snip-its to mathematical notation.

I had some code where I used the QRMlib package, but it was really messy and fairly specific to my use case. So I whipped up very simple example of how to create correlated random draws from a multivariate distribution. In this example I used normally distributed marginals and Gaussian correlation to keep things simple and easy to follow. Rather than blogging through the code, I added a shit load (metric ass ton, if you’re in Canada) of comments. The code is designed to be stepped through. So don’t just run the whole blob and wonder what happened.

Walk through the code and if you find any errors be sure and let me know.

The code is embedded in a Github gist below, but if you are reading this in an aggregator (shout out to R-Bloggers) you’ll need to manually go to the gist.


  1. Awesome post! A perfect mix of education and entertainment… edutainment… entercation? Anyway, I’ve wanted to learn more about copulas for quite awhile but I seem to learn better with code than formulas (for whatever reason). Thanks for the primer.

  2. [...] after yesterday’s post on Simple Simulation using Copulas I got a very nice email that basically begged the question, “Dude, why are you making this so [...]

  3. gappy says:

    Sorry, but the way mensches do multivariate (log)normal variates is via Cholesky. It’s simple, instructive, and fast. If you have a covariance matrix S, get a Cholesky decomp S=A’*A, and then compute a random variate as x’*A, where x is a vector of independent standard gaussians. Done.

    N.B.: SVD works too, although everyone knows Cholesky is more efficient.

  4. [...] I did a brief post three days ago I had no plans on writing two more posts on correlated random number generation. But I’ve [...]

  5. maddy says:

    What if my correlation matrix is very large but I only need to generate 100 dependent random variables. Is there any efficient way to do it?? Thank you.

Leave a Reply