So, a couple of comments:
-
The original error you cited simply comes from looping over 10 values when the number of rows in that dataset is 9. The proper way to define
j
would bej <- nrow(df_data)
, if that is indeed what you were trying to do. However, that's not the only problem. -
You don't need to define
v0, vT, rho, k, sig
inside each loop, since their values are always the same once you call thefunc_optim
function. -
func_optim
hasreturn(...)
inside a loop. This means that, when the function reaches thatreturn(...)
in the first loop, it will stop, returning one single value corresponding toi = 1
. -
Even if you place
return(mserr)
outside of the loop, it will still only return one single value, in that case corresponding to the last iteration of the loop. I don't think this is what you want, but I'm not sure.
R functions return a single object, so you should think beforehand what you want this object to be. If you need multiple values, you will need to define a vector, a list, or a similar object which lets you store more than one value.
- Finally, and this is just a suggestion, try to avoid repeating names from objects inside functions, to avoid mix-ups. So in this case,
var
could be the function parameter, andvar0
could be the vector with your values:
library(NMOF)
j <- nrow(df_data) # To loop over the number of rows in the dataset
func_optim <- function(var){ # var is the function parameter
# These values are defined outside the loop:
v0 <- var[1]
vT <- var[2]
rho <- var[3]
k <- var[4]
sig <- var[5]
for(i in 1:j){
prices <- df_data$call_price[i]
mserr <- (callHestoncf(S=df_data$S[i], X=df_data$K[i], tau=df_data$T[i], r=df_data$r[i], q=0, v0, vT, rho, k, sig)-prices)^2
# Store each mserr value somewhere if that is what you need
}
#return(wherever you stored mserr values)
}
var0 <- c(0.2, 0.2, 0.5, 0.2, 0.05) # var0 contains the actual v0, vT, rho, k, sig values
optim(var0, func_optim)
Hope this helps!