Problem Statement

start=Sys.time()
sigma=matrix(rep(1,100),nrow=10)
sigma[upper.tri(sigma)|lower.tri(sigma)]=0.2
c=chol(sigma)
#running the simulation
for(i in 1:N){ 
  Z<-rnorm(10,0,1) #generating standard normal random numbers
  X=c%*%Z #computing the default rates using the correlation matrix and RVs 
  t=-log(1-pnorm(X))/def #using the default rates to determine the default times
  sorted=sort(t) #sort the default times
  sum=0 
  #if the number of defaults before the maturity of the contract are 5,CDS called
  if(sum(sorted<Time)>=5){ 
    tau=sorted[5] #compute the time for the 5th default
    index=which(t==tau) #indexing the asset which was the 5th default  
    R=rec[index] #use the recovery rate of the 5th default as per the contract
    #using the recovery rate we compute the total payoff as 1-R
    value=value+(1-R)*exp(-r*tau)  #discounting it to the trigger time
    tj=floor(tau) #taking the time right before the trigger
    for(i in seq(1:tj)){ #adding the value of all insurance payments made 
      sum=sum+exp(-r*i)
    }
    sum=sum+exp(-r*tau)*(tau-tj)
    vp=vp+sum #summing the insurance payments for this simulation[CDS triggered]
  }
  else{ #when the CDS is not triggered
    
    for(i in 1:Time){ #computing the insurance in this case
      sum=sum+exp(-r*i)
        }
    vp=vp+sum #summing the insurance for this simulation [CDS not triggered]
  }
}
#value of the swap in bps as percentage of payoffs w.r.t insurance payments
swap_price=value/vp
print(swap_price)
## [1] 0.01308854
end=Sys.time()
cat('Total time taken for pricing = ',(end-start))
## Total time taken for pricing =  1.012198

```