montecarlo - Cannot figure out Reduce and Monte Carlo Simulations in R, calculating VaR -
apologies title. not think of how title this...
(also, know shite question, hoping out there can help.)
i have following mean vector , covariance matrix:
> mu0 msft aapl 0.001250251 0.001060690 > sig0 msft aapl msft 1.275625e-04 3.334225e-05 aapl 3.334225e-05 1.484212e-04
i have following chunk of code (i know 500 simulations. brevity's sake. ramp when figure out code.):
wta = 0.562546911; wtm = 0.437453089; ct = -1000000*c(wtm,wta); lambda = .97; k = 20; m = 500; l1 = 0.0; l1 = rep(0,m); mu1 = mu0; sig1 = sig0; l1=0.0; rando = rmvnorm(m, mu1, sig1) for(i in 1:m){ xtd = t(rando[i,]) mu1 = lambda*mu1+(1-lambda)*xtd sig1 = lambda*sig0+(1-lambda)*t(xtd)%*%xtd; l1 = l1+t(ct)%*%t(xtd) l1=l1+t(ct)%*%t(xtd) for(j in 2:k){ xtd=rmvnorm(1,mu1, sig1) mu1=lambda*mu1+(1-lambda)*xtd sig1=lambda*sig0+(1-lambda)*t(xtd)%*%xtd l1=l1+t(ct)%*%t(xtd) } l1[i]=l1 }
i hate code. slow, , perhaps more importantly, ugly. feel ripe sort of optimization using reduce or do.call or something. cannot figure out how write functional reduce function. honest, not understand reduce. have been trying read through this, struggling apply here.
the problem seems have several value must 'accumulate' through pulls of random numbers, 'x' reduce list instead of vector, doesn't seem make sense. tried writing this:
runstuff <- function(theprev, thenext, thelam, thect, thesig){ xtd=rmvnorm(1, theprev[1], theprev[2]) thenext[3]=theprev[3]+t(thect)%*%t(xtd) thenext[1]=thelam*theprev[1]+(1-thelam)*xtd thenext[2]=thelam*thesig+(1-lambda)*t(xtd)%*%xtd thenext }
and using (which expected not work), , not work:
reduce(x=list(mu1, sig1, l1), f=runstuff, thelam = lambda, thect = ct, thesig = sig0, accumulate=true)
any how use functional in scenario?
Comments
Post a Comment