R:加速集成功能

时间:2017-11-21 11:20:29

标签: r performance integral

我需要加快功能。特别是积分的一部分。就像你可以看到我每次都必须从0到Inf集成不同的参数。 我已经对该函数进行了矢量化。但它仍然运行得很慢。我已经尝试过并行for循环,但矢量化仍然是最快的。我还使用编译器包中的cmpfun编译了该函数。 数据大约有6十亿行。有没有人知道如何加快速度?

功能:

HM_Call2 <- function (Prices_Para,ATM=1,q=0,ttm) 
{
  cfHeston <- function(om,S,tau,r,q,v0,vT,rho,k,sigma) {
    d <- sqrt((rho * sigma * (0+1i) * om - k)^2 + sigma^2 *((0+1i) * om + om^2))
    g <- (k - rho * sigma * (0+1i) * om - d)/(k - rho * sigma *(0+1i) * om + d)
    cf1 <- (0+1i) * om * (log(S) + (r - q) * tau)
    cf2 <- vT * k/(sigma^2) * ((k - rho * sigma * (0+1i) *  om - d)*tau-2*log((1-g*exp(-d*tau))/(1-g)))
    cf3 <- v0/sigma^2 * (k - rho * sigma * (0+1i) * om - d) * (1 - exp(-d * tau))/(1 - g * exp(-d * tau))
    cf <- exp(cf1 + cf2 + cf3)
    cf
  }
  P1 <- function(om,S,X,tau,r,q,v0,vT,rho,k,sigma) Re(exp(-(0+1i)*log(X)*om)*cfHeston(om-(0+1i),S,tau,r,q,v0,vT,rho,k,sigma)/((0+1i)*om*S*exp((r-q)*tau)))
  P2 <- function(om,S,X,tau,r,q,v0,vT,rho,k,sigma) Re(exp(-(0+1i)*log(X)*om)*cfHeston(om,S,tau,r,q,v0,vT,rho,k,sigma)/((0+1i)*om))
  vP1 <- function(S,X,tau,r,q,v0,vT,rho,k,sigma)  integrate(f=P1,lower=0,upper=Inf,S=S,X=X,tau=tau,r=r,q=q,v0=v0,vT=vT,rho=rho,k=k,sigma=sigma, stop.on.error =F)$value
  vP1 <- Vectorize(vP1)
  vP2 <- function(S,X,tau,r,q,v0,vT,rho,k,sigma)  integrate(f=P2,lower=0,upper=Inf,S=S,X=X,tau=tau,r=r,q=q,v0=v0,vT=vT,rho=rho,k=k,sigma=sigma, stop.on.error =F)$value
  vP2 <- Vectorize(vP2)
  nvP1 <- 0.5+1/pi*vP1(S=Prices_Para[,1],X=Prices_Para[,1]*ATM,tau=ttm,
               r=Prices_Para[,7],q=q,v0=Prices_Para[,2],vT=Prices_Para[,3],rho=Prices_Para[,4],
               k=Prices_Para[,5],sigma=Prices_Para[,6])
  nvP2 <- 0.5+1/pi*vP2(S=Prices_Para[,1],X=Prices_Para[,1]*ATM,tau=ttm,
                       r=Prices_Para[,7],q=q,v0=Prices_Para[,2],vT=Prices_Para[,3],rho=Prices_Para[,4],
                       k=Prices_Para[,5],sigma=Prices_Para[,6])
  result <- exp(-q*ttm)*Prices_Para[,1]*nvP1-exp(-Prices_Para[,7]*ttm)*Prices_Para[,1]*ATM*nvP2
  return(result)
}
HM_Call2 <- compiler::cmpfun(HM_Call2)

采样数据:

ttm <- 63/252

Prices_Para <- data.frame( c(10.085,9.925,9.862,9.715,9.817,9.804,9.625,9.683,9.663,9.548),
                           c(0.04732137,0.04732137,0.04605786,0.05112859,0.04725873,0.04350297,0.04350297,0.04001722,0.03750331,0.03865721),
                           c(0.002221575,0.002787169,0.002970667,0.003174367,0.003362648,0.003535967,0.004055923,0.004215354,0.004364770,0.004518782),
                           c(0.1520490,0.1526177,0.1522709,0.1415566,0.1418355,0.1416145,0.1439227,0.1524284,0.1656090,0.1795288),
                           rep(2,10),
                           c(0.01844871,0.01984709,0.02023645,0.02071596,0.02108624,0.02136627,0.02211971,0.02229061,0.02241744,0.02255033),
                           c(0.0395067,0.0395733,0.0399867,0.0400000,0.0400000,0.0400000,0.0400000,0.0400167,0.0400000,0.0399792))

0 个答案:

没有答案