How to generate multivariate random numbers with different marginal distributions?
If you have Statistics Toolbox you can generate random numbers from copulas using the function copularnd
. There are several examples in the documentation. To convert between using Kendall's tau and Pearson's rho, take a look at copulaparam
and copulastat
.
Generate copula-correlated samples with specified marginals in Python
The following code implements the Clayton and AMH copulas. Page 4 of this paper shows how other kinds of copulas can be implemented.
import random
import math
import scipy.stats as st
def clayton(theta, n):
v=random.gammavariate(1/theta,1)
uf=[random.expovariate(1)/v for _ in range(n)]
return [(k+1)**(-1.0/theta) for k in uf]
def amh(theta, n):
# NOTE: Use SciPy RNG for convenience here
v=st.geom(1-theta).rvs()
uf=[random.expovariate(1)/v for _ in range(n)]
return [(1-theta)/(math.exp(k)-theta) for k in uf]
scipy - generate random variables with correlations
If you just want correlation through a Gaussian Copula (*), then it can be calculated in a few steps with numpy and scipy.
create multivariate random variables with desired covariance,
numpy.random.multivariate_normal
, and creating a (nobs by k_variables) arrayapply
scipy.stats.norm.cdf
to transform normal to uniform random variables, for each column/variable to get uniform marginal distributionsapply
dist.ppf
to transform uniform margin to the desired distribution, wheredist
can be one of the distributions inscipy.stats
(*) Gaussian copula is only one choice and it is not the best when we are interested in tail behavior, but it is the easiest to work with
for example http://archive.wired.com/techbiz/it/magazine/17-03/wp_quant?currentPage=all
two references
https://stats.stackexchange.com/questions/37424/how-to-simulate-from-a-gaussian-copula
http://www.mathworks.com/products/demos/statistics/copulademo.html
(I might have done this a while ago in python, but don't have any scripts or function right now.)
Related Topics
Recursive Function Using Dplyr
Summing Multiple Columns in an R Data-Frame Quickly
Same Seed, Different Os, Different Random Numbers in R
How to Make UI Respond to Reactive Values in for Loop
Ggplot2: Shape, Color and Linestyle into One Legend
Return Rows Establishing a "Closest Value To" in R
Margins Between Plots in Grid.Arrange
Change Plot Panel in Multipanel Plot in R
In R, Merge Two Data Frames, Fill Down The Blanks
Data.Table Join (Multiple) Selected Columns with New Names
How to Format Kable Table When Knit from .Rmd to Word (With Bookdown)
Character Extraction from String
Extract Coefficients from Ggplot2-Created Nls Fit
How to Use Custom Cross Validation Folds with Xgboost