Return simulated pricing result - r
I am quite new to R and try to do a pricing simulation. The goal is to have a vector with length n, that gives a percentage for the coupon that will be received. When I use print, I get exactly the result I want. However, for my subsequent calculations I cannot proceed with results in print format. I tried replacing it with return but this just gives me one result.
Any input is appreciated.
(package used for rgpd is POT)
bond_coupon <- function(n, l) {
events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
for (i in 1:length(events)){
cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
if(events[i]>1){
coupon <- prod(1-((cat-1000)/cat))
} else if(events[i]==1){
coupon<- 1-((cat-1000)/cat)
} else{
coupon<- 1.00
}
print(coupon)
}
}
Your coupon is overwritten at each iteration of loop, hence return only returns the last one.
You could create a vector coupon and fill it at each iteration:
bond_coupon <- function(n, l) {
events <- rpois(n, l) #simulates the rate of arrival according to a Poisson process
coupon = numeric(length(events))
for (i in 1:length(events)){
cat <- rgpd(events[i], loc=1000, scale=100, shape=1) #simulates the severance of each event
if(events[i]>1){
coupon[i] <- prod(1-((cat-1000)/cat))
} else if(events[i]==1){
coupon[i]<- 1-((cat-1000)/cat)
} else{
coupon[i]<- 1.00
}
}
return(coupon)
}
Alternatively you could delegate creation and looping to apply family of functions:
bond_coupon <- function(n, l) {
#simulates the rate of arrival according to a Poisson process
events <- rpois(n, l)
coupon <- sapply(X = seq_along(events), FUN = function(i) {
#simulates the severance of each event
cat <- rgpd(events[i], loc = 1000, scale = 100, shape = 1)
if (events[i] > 1) {
prod(1 - ((cat - 1000) / cat))
} else if (events[i] == 1) {
1 - ((cat - 1000) / cat)
} else {
1.00
}
}
)
return(coupon)
}
Related
How can I find the observations associated with rank j in this code?
I have been trying to find the observations associated with rank j in Ranked Set Sampling method. The problem is I don't know how to use the simulations to find the Xj values I'm supposed to work with further. Please help! #The rankedsets function selects ranked sets from a target population. The selection of units in a set is without replacement, but the sets are selecting with replacement. rankedsets<-function(X,m,s=m){ if(s==m){ x=sample(X,(m^2),replace=F) n=matrix(x,ncol=m,nrow=m,byrow=T) ms=matrix(0,ncol=m,nrow=m) for (i in 1:m){ ms[i,]=sort(n[i,]) } }else { x=sample(X,(m*s),replace=F) n=matrix(x,ncol=m,nrow=s,byrow=T) ms=matrix(0,ncol=m,nrow=s) for (i in 1:s){ ms[i,]=sort(n[i,]) } } return(ms) } #The rss function samples from a target population by using ranked set sampling method rss<-function(X,m,r=1,sets=FALSE){ rss=numeric() set=matrix(0,ncol=m,nrow=(m*r)) if (is.vector(X)){ a=0 for (j in 1:r){ ms=rankedsets(X,m) for (i in 1:(m)){ set[i+a,]=ms[i,] rss[i+a]=ms[i,i] } a=a+m } rss=matrix(rss,ncol=m,nrow=r,byrow=T) cn=rn=numeric() for (i in 1:r){ rn[i]=paste("r","=",i) } for (i in 1:m){ cn[i]=paste("m","=",i) } rownames(rss)=rn colnames(rss)=cn if (sets){ s=list(sets=set,sample=rss) return(s) } else { return(rss)} }else stop(" X must be a vector!",call.=F) } #RSS Data Generation data=rnorm(10000,1,3) rss(data,m=5,r=3,sets=TRUE) I was trying using simulations but the code doesn't return Xj values: sims = 1000 Xj = rep(NA, sims) because I don't really know where I should put my for loop.
Likelihood for First order censored autoregressive process with covariate(see Jung Wook Park1 , Marc G. Genton2 and Sujit K. Ghosh3)
library(mvtnorm) set.seed(14) n=10000 sigmatrue<-1 rhotrue<-0.3 b1=0.05 b0=0 y<-arima.sim(model=list(ar=c(0.3)),n=10000 ,sd=sigmatrue)#kataskevi #xronoseiras x=rep(0,n) for(i in 1:n){ x[i]=i } for(t in 1:n) { y[t]=y[t]+b0+b1*x[t] } est=arima(y,order=c(1,0,0),xreg=x,include.mean=TRUE,method="ML",kappa=1e+06) cens<-rep(0, n) c=(9/10)*(n*b1+b0) for (i in 1:n) { if(y[i]>c){ y[i]<-c cens[i]<-1 } } ll<-function(p){ sigma=matrix(c(p[2]^2/(1-p[3]^2), p[2]^2*p[3]/(1-p[3]^2),p[2]^2*p[3]/(1-p[3]^2),p[2]^2/(1-p[3]^2)),ncol=2,nrow=2,byrow=TRUE) likelihood<-rep(0,n) for(t in 2 :n){ if(cens[t]==0 & cens[t-1]==0){ likelihood[t]<-dnorm(((y[t]-(p[1]+p[4]*t)-p[3]*(y[t-1]-(p[1]+p[4]*(t-1)))/p[2]) )/p[2]) } else if(cens[t]==0 & cens[t-1]==1){ likelihood[t]<-(1/(1-pnorm((c-(p[1]+p[4]*t)*sqrt(1-p[3]^2)/p[2]))*sqrt(1-p[3]^2)/p[2]*dnorm(((y[t]-(p[1]+p[4]*t)*sqrt(1-p[3]^2))/p[2])*(1-pnorm(((c-(p[1]+p[4]*(t))-p[3]*(y[t]-(p[1]+p[4]*(t-1)))/p[2]))))))) } else if(cens[t]==1 & cens[t-1]==0){ likelihood[t]<-1-pnorm(((c-(p[1]+p[4]*t)-p[3]*(y[t-1]-(p[1]+p[4]*(t-1)))/p[2]))) } else { likelihood[t]<-(((pmvnorm(lower=c, upper=Inf , mean=c(p[1]+p[4]*(t-1),p[1]+p[4]*t),sigma=sigma))/(1-pnorm((c-(p[1]+p[4]*(t-1))*sqrt(1-p[3]^2)/p[2]))))) } } f0=(sqrt(1-p[3])/p[2]*dnorm(((y[1]-p[1]-p[4])*sqrt(1-p[3]^2))/p[2])) likelihood[1]=f0 #Ta prosthesa if (any(likelihood==0)){ likelihood[likelihood==0] = 0.000001 #poly mikros arithmos } if (any(likelihood==Inf)){ likelihood[likelihood==Inf] = 1 #poly megalos h 1, an milame gia pi8anothta } if (any(is.nan(likelihood))){ likelihood[is.nan(likelihood)] = 0.000001 } minusloglike=-sum(log(likelihood)) #l1=list(Minusloglike=minusloglike,Loglikelihood=log(likelihood)) return(minusloglike) } fit<-optim(c(0,1,0.3,0.05),ll,method="L-BFGS-B",lower=c(-Inf,0.001,-0.999,-Inf),upper = c(Inf,Inf,0.999,Inf),hessian=TRUE) fisher.info<-solve(fit$hessian) fisher.info prop.sigma<-sqrt(diag(fisher.info)) sigmas<-diag(prop.sigma) upper<-fit$par+1.96*sigmas lower<-fit$par-1.96*sigmas interval<-data.frame(value=fit$par, lower=diag(lower),upper=diag(upper)) interval I run this code(it is for censored first order autogressive process with covariate , i have 4 cases for x(t) ,x(t-1) either is censored or non-censored and i dont want the likelihood to go near zero and inf).I get error Error in if (any(likelihood == Inf)) { : missing value where TRUE/FALSE needed Called from: fn(par, ...) The program is working for n=100 but when n is larger than 100 i have this error. I think this error causes bad estimattes of the four parameters(b1,rho,sigma,b0).Does anyone know what can i do? Thank you for your help.
Dealing with recursion depth limitation in R
The algorithm is from https://www.math.upenn.edu/~wilf/eastwest.pdf page 16 RandomKSubsets RandomKSubsets = function(n, k){ if (n<0 | k<0 | k<n){ return() } else { if (n==0 && k==0){ return(c()) } else { rno = runif(1) if (rno < n/k){ east = RandomKSubsets(n-1,k-1) return (c(east, k)) } else{ west = RandomKSubsets(n,k-1) return(west) } } } } Running the program with k=4000 and n=1200 I run into recursion depth limit. I tried options(expressions=500000) but it's not enough for the algorithm. How can I run this code for my variables?
This is close to tail recursion: the only recursive calls are in the return statements. This blog: http://blog.moertel.com/posts/2013-05-11-recursive-to-iterative.html describes how to change such functions into loops. I followed the mostly mechanical process described there, and came up with this version: RandomKSubsetsLoop = function(n, k) { acc <- NULL while (TRUE) { if (n<0 | k<0 | k<n){ return(acc) } else { if (n==0 && k==0){ return(acc) } else { rno = runif(1) if (rno < n/k){ acc <- c(k, acc) k <- k - 1 n <- n - 1 next } else{ k <- k - 1 next } } } break } } I haven't tested it extensively, but it produces the same result as the original in this test: set.seed(1) RandomKSubsets(5, 10) # [1] 1 3 6 9 10 set.seed(1) RandomKSubsetsLoop(5, 10) # [1] 1 3 6 9 10 You'll probably want to do more extensive testing, and read the blog to make sure I've done things as it describes. By the way, there are other algorithms to do this sampling, e.g. the one described in AUTHOR="McLeod, A.I. and Bellhouse, D.R. ", YEAR = 1983, TITLE="A convenient algorithm for drawing a simple random sample", JOURNAL="Applied Statistics", VOLUME="32", PAGES="182-184" That one is based on a loop by design, and has the advantage that you don't need to know the population size (k in your notation) in advance: you just keep updating your sample until there are no more items to process.
How can I define a constant variable inside a recursive function in R?
I want to create functions that compute the Simple Moving Average (SMA) and the Exponential Moving Average (EMA). My problem is in the EMA implementation. I would like to set a constant variable inside the recursive function that is equal to one of its argument. Here is my code: #SMA sma <- function(P,t,n) { return(sum(P[(t-n):(t-1)])/n) } #EMA recursive.ema <- function(P,t,n) { # Here I want to create a constant variable that keeps in memory the first # value of t, i.e. the value of t before the first recursion, so I can use # it as argument of sma function. # Something similar to this: tmp <- t (t given from outside the function) b <- 2/(n+1) if (t == 1) { return(b*P[1] + (1-b)*sma(P,tmp,n)) } return (b*P[t] + (1-b)*recursive.ema(P,t-1,n)) } Here P is a vector, time series of prices, t is the index of the vector, the time in my model, and n is any positive number, corresponding to n lagged periods at time t.
Would this work ? e <-new.env() test<-TRUE assign("test",test,e) recursive.ema <- function(P,t,n) { test <-get("test",envir=e) if (test) { assign("t",t,envir=e) assign("test",FALSE,envir=e) } else { t=get("t",envir=e) } b <- 2/(n+1) if (t == 1) { return(b*P[1] + (1-b)*sma(P,tmp,n)) } return (b*P[t] + (1-b)*recursive.ema(P,t-1,n)) }
0 vector result in R after running function
After I finished running my function, I kept on getting 0s as my answer: niv_density <- function(returns, mu, delta, alpha, beta, t) { t <- 1/t gamma <- sqrt(alpha^2 - beta^2) result <- rep(0, (1/t)) for(i in 1:(1/t)) { term3 <- exp(delta*gamma*t + beta*(returns[i] - mu*t)) term1 <- alpha*delta*t/pi term2_1 <- besselY(alpha*sqrt(delta^2*t^2 + (returns[i] - mu*t)^2), 1) term2_2 <- sqrt(delta^2*t^2 + (returns[i] - mu*t)^2) term2 <- term2_1/term2_2 result[i] <- (term1*term2*term3) } } niv_density(returns, 0, 2, 50, 0, 10) result After executing the last part, I get a vector of 0s. I think I'm having a problem with global vs. local scopes, but I'm not sure how to fix it. dput(returns) structure(c(-0.003859212, 0.011873365, -0.004826217, -0.004006846, -0.004527209, -0.005597606, -0.001446292, 0.004890173, 0.001260653, -0.005469839, 0.001715495, 0.00776223, -6.79514e-05, -0.002405413, -0.00344927, 0.013203733, 0.009007395, -0.002918161, -0.000682757, 0.003600917, -0.001584568, 0.001778635, 0.003881849, -0.003228443, 0.00809855, -0.003407655, 0.006570117, -0.001629285, -0.001479157, -0.000683758, 0.007489741, 0.007807378, 0.001399056, -0.000578823, -0.002437511, -0.000593349, -0.004020762, 0.004744014, -0.001815119, 0.007757796, -0.002401808, -0.00225831, -0.005162853, -0.002256747, 0.032891919, 0.005882631, -0.011822966, -0.005744899, -0.004359233, 0.00405189, 0.017035644, 0.001079738, 0.001845759, -0.004758891, 0.006067706, -0.006027932, -0.00224155, -0.010844493, 0, -0.003861616, -0.004698823, 0.000397524, 0.001840917, 0.013599978, -0.008376557, 1.92494e-05, 0.010797502, -0.004105023, 0.003119424, -0.004797368, -0.001962367, 0.002663974, 0.008489008, 0.007827146, -0.000566674, -0.003404669, -0.000160508, -0.003953786, -0.000635631, 0.0023086, 0.008931147, -0.002761431, 0.013046559, -0.009673618, 0.007572105, -0.011309217, 0.003777911, -0.004767721, -0.004096769, 0.003915212, -0.005571037, 0.008566323, -0.009063831, -0.011191246, -0.000639167, 0.002834983, -0.009156367, 0.00189252, 0.007166451, -0.001788182, -0.002437146, 0.00226261, -0.010459432, -0.001511577, 0.00039628, -0.00349739, 0.009561965, 0.063504871, 0.003492974, 0.009233691, 0.004795333, -0.003995969, -0.002552804, 6.81834e-05, 0.006134657, 0.006713932, -0.006875273, -0.005108732, 0.006239377, 0.002293386, -0.01121192, -0.005666844, 0.000894577, -0.012511724, 0.00351622, -0.009671627, -0.004480382, 0.007385228, -0.009143379, 0.005467177, 0.017094141, 0.005918621, 0.001514995, -0.001356959, 0.015656296, 0.001101646, 0.001457523, 0.0051402, -0.005516804, 0.002832519, -0.002196811, -0.007752963, 0.009050809, 0.006380147, 0.001995102, 0.002319077, -0.001788715, 0.000845096, -0.009821598, 0.012634302, -0.001457121, 0.000582262, -0.004083585, -0.004021717, -0.000571503, 0.006159289, -0.010822168, -0.015789222, -0.000657867, 0.013935285, 0.001312777, -0.001172312, 0.003031039, 0.002482838, -0.010634785, 0.014015267, 0.005435065, -0.034817949, 0.005145224, -0.007217488, 0.00458109, 0.012581199, 0.001853981, 0.002118571, -0.011151137, -0.007933775, 0.011336262, 0.018212375, 0.007815775, 0.006103632, -0.007270438, -0.001066825, 0.001892988, -0.009740379, 0.012057142, 0.00024459, -0.003702988, 0.014628744, -0.001902607, -7.49322e-05, -0.005903797, -0.002481339, -0.004266069, 0.01150386, -0.019888508, 0.007657512, -0.004649027, 0, 0.002523089, -0.00072238, -0.021153782, -0.007969763, 0.005775428, -0.010897333, 0.007468107, -0.009508927, 0.000464995, -0.002430182, 0.010796022, 0.008898853, -0.013079549, 0.027112561, -0.015413991, -0.007630787, 0.007033724, -0.017738864, -0.015961032, -0.015579591, -0.011802317, -0.002187586, 0.003065715, 0.013389559, -0.000885034, -0.013701533, 0.001976838, 0.001041955, -0.003616062, 0.005344799, 0.007148373, -0.002877552, -0.007681476, 0.021591165, 0.017966863, -0.058771073, -0.019551973, 0.005203616, 0.002169669, 0.003884158, -0.022568915, 0.002769004, -0.007779571, 0.018998803, -0.001212088, 0.002446011, 0.007740844, 0.012532807, 0.006287039, 0.003958813, 0.01407559, 0.001064047, -0.00862106, -0.012296938, -0.013967015, 0.010524923, -0.010789529, 0.011953286, 0.000738662, -0.016492003, -0.00257709, -0.015437029, 0.004315983, 0.023337948, 0.008138125, 0.005972748, 0.005915635, 0.010493804, -0.011895336, -0.005245454, 0.007409717, 0.012596218, -0.005221382, -0.005462129, 0.008785043, 0.009134618, 0.015541224, 0.016072839, -0.003827797, 0.000403703, 0.03749696, -0.003386946, -0.008627298, -0.030790478, -0.003861794, -0.011426323, 0.001393173, 0.008541783, 0.009361445, -0.023851831, 0.024814864, -0.019724128, 0.002621807, -0.017904622, -0.003584294, -0.019299804, -0.00234839, -0.002685042, 0.002685042, 0.016590137, 0.001401377, -0.006120481, 0.006690448, -0.004740457, -0.005027981, 0.013204038, -0.002742491, 0.005110009, -0.006393429, 0.00464228, -0.00270551, -0.011552836, 0.003074876, 0.005139878, 0.002032361, 0.007603533, 0.010491222, 0.000658875, 0.003909991, 0.00236732, 0.019192366, -0.00361624, 0.005696264, -0.005852811, 0.014805765, 0.00313454, 0.006385073, -0.005475311, -0.009195918, 0.008472618, -0.000559148, -0.007272851, 0.003748203, 0.001156269, 0.004328552, -0.006107929, -0.012121056, 0.002812434, -0.009577213, 0.005689626, -0.001941957, 0.006145673, -0.002275509, -0.006578825, -0.005345298, -0.000327811, 0.003751791, 0.005053343, 0.005157952, -0.022100394, -0.007461083, 0.003576376, 0.00093598, 0.006738706, 0.006976768, 0.001078282, -0.006256189, 0.003313743, -0.005955287, 0.011771523, 0.001644383, -0.003459295, 0.032863111, -0.007369908, -0.001099451, 0.004745151, 0.012094786, 0.001167328, -0.00404787, -0.004345022, -0.001121192, 0.004333763, -0.008483142, -0.001578184, -0.00046999, 0.005079249, -0.005970832, 0.005543307, 0.006722626, 0, 0.001715197, 0.011776868, 0.013308783, -0.004160112, -0.000304697, 0.014924613, 0.007204855, -0.00509816, 0.007186504, 0.002287253, -0.009948655, -0.001000861, -0.00431929, -0.00347645, 0.005015994, -0.007540969, 0.00558486, -0.005661924, -0.006602168, -0.002824197, 0.001939661, 0.006563001, -0.009757559, -0.00978824, -0.001247868, 0.002622219, -0.009097288, -0.014394158, -0.00292424, 0.002644891, -0.005572549, -0.003181826, 0.002676673, 0.007032888, 0.002127581, 0.005281961, 0.016021024, 0.001232531, 0.005515082, 0.000450254, 0.003568462, 0.006277841, -0.003823264, -0.032527132, 0.021873831, -0.003231721, -0.000368515, -0.001397511, -0.010973353, -0.011563657, -0.010061858, 0.005714484, 0.007472816, 0.003407539, -0.000612977, -0.000800283, -0.001900635, -0.000865432, -0.003630001, 0.00562073, 0.001858425, 0.010064273, -0.006584881, -0.001470899, 0.005433816, -0.002510864, -0.001071656, -0.005130965, 2.35065e-05, 0.003445676, 0.01374472, -0.001123534, 0.006067276, 0.004050843, -0.000773321, -0.003401186, 0.001908336, -0.003562041, -0.001180884, -0.003133416, 0.005819655, -0.002096198, -4.92007e-05, 0.002838133, -0.010010669, 0.00557654, -0.000122526, 0.022760252, -0.005618111, 0.014434193, 0.001716112, 0.01567573, 0.001566116, -0.003071945, -0.018146189, -0.012123038, -0.007480614, 0.007735601, -0.00436506, 0.003091618, 0.004704796, 0.001184206, 0.010066361, 0.005389096, -0.007021784, -0.004211278, -0.001740557, -0.00628043, 0.002434464, -0.000333944, 0.010815674, 0.016910153, 0, -0.01318228, -0.002858256, 0.024721185, 0.001006412, -0.003651077, 0.009682259, -0.007093437, -0.002005597, 0.002424598, -0.015024047, 0.015051995, 0.004720944 ), na.action = structure(504L, class = "omit"))
Your version is not working because result is local to the function's body and it is lost as you exit the function. I suspect you have another result object in your global environment (a vector of zeroes) and that's what you always get when you try to check your result. Instead, make your function explicitly return result by adding a return statement at the end: niv_density <- function(returns, mu, delta, alpha, beta, n) { t <- 1/n gamma <- sqrt(alpha^2 - beta^2) result <- rep(0, n) for(i in seq_len(n)) { term3 <- exp(delta*gamma*t + beta*(returns[i] - mu*t)) term1 <- alpha*delta*t/pi term2_1 <- besselY(alpha*sqrt(delta^2*t^2 + (returns[i] - mu*t)^2), 1) term2_2 <- sqrt(delta^2*t^2 + (returns[i] - mu*t)^2) term2 <- term2_1/term2_2 result[i] <- (term1*term2*term3) } return(result) } And when calling the function, assign the result as follows: result <- niv_density(returns, 0, 2, 50, 0, 10) (and maybe you should avoid calling a variable result, I'm sure you can find a more descriptive name from the context.)