# Monte Carlo simulation for VaR estimation using R

As I am not very experienced in financial econometrics I need help in writing R code for MC simulation for VaR estimation. Namely, reading some books and reference manuals for R packages, I ended up with the following code:

-constructing hypothetical portfolio consisting of x1 and x2

p<-matrix(c(rnorm(1000,50,4),rnorm(1000,5,0.5)),ncol=2);
colnames(p)<-c("x1","x2")


-x1 and x2 weights

weights<-c(100,100)


-calculated means and covariance matrix

mu<-apply(p,2,mean);
sigma<-cov(p)


-generate 10000 scenarios for x1 and x2 with given covariance matrix sigma

library(MASS);
MC<-mvrnorm(10000,mu,sigma)


-calculate portfolio value for simulated x1 and x2

MCportfolio<-MC%*%t(weights)


-find VaR for 95%

quantile(MCportfolio,p=0.05)


Could someone tell me if this is the right way or not to perform MC simulation for VaR? Thanks in advance for any help or guidelines.

MCportfolio<-MC%*%t(weights)


should probably be

Mcportfolio <- MC%*%as.matrix(weights)


because

dim(weights)
dim(as.matrix(weights))


I'm at work, seems alright to me. One fairly major potential issue is with the line:

-x1 and x2 weights

weights<-c(100,100)

Those weights should be adding to parity, weights of 100 don't make sense. Your results will be nonsense.

An example would be c(0.6,0.4).

This would represent a portfolio with 60% of your NAV/value/allocation in x1 and 40% in x2, which combined is 100% of your portfolio.