Optimize function function from r

I would like to minimize the standard error ( mse() in the hydroGOF package can be used) between the simulated and observed spreads. The function is defined as:

  KV_CDS <- function(Lambda, s, sigma_S){ KV_CDS = (Lambda * (1 + s)) / exp(-s * sigma_S) - Lambda^2) } 

The goal is to minimize mse between KV_CDS and C, leaving the lambda free parameter in the KV_CDS function.

 df <- data.frame(C=c(1,1,1,2,2,3,4), Lambda=c(0.5),s=c(1:7), sigma_S=c(0.5,0.4,0.3,0.7,0.4,0.5,0.8), d=c(20,30,40,50,60,70,80), sigma_B=0.3, t=5, Rec=0.5, r=0.05) 
+6
source share
2 answers

Thanks to you, Simon, I have come to a decision:

  d <- df TestMSE <- function(LR) { D <- KV_CDS(LR, d$s, d$sigma_s, d$D, d$sigma_B, d$t, d$Rec, d$r) mse(d$C, D) } optimize(TestMSE,lower = 0.1, upper =1.5) 

or:

 TestMSE2 <- function(LR) { D <- KV_CDS(LR, d$s, d$sigma_s, d$D, d$sigma_B, d$t, d$Rec, d$r) mean((d$C- D)^2) } optimize(TestMSE2,lower = 0.1, upper =1.5) 

Thanks for the help guys!

+1
source

You need to write a function to minimize that calculates the root mean square error for this particular case, for example:

 calcMSE <- function (Lambda) { d <- df # best not to use -df- as a variable because of confusion with # degrees of freedom err <- d$C - KV_CDS(Lambda, d$s, d$sigma_S, d$d, d$sigma_B, d$t, d$Rec, d$r) sum(err^2) / length(err) } 

... and then you can use optimize() , for example, this (you need to specify a range of possible values ​​for Lambda - by the way, this is not an ideal name because it means that it can be a function when it is actually just a variable):

 optimize(calcMSE,c(0,1)) 

I could not complete the full test because I did not have pbivnorm installed, but this should do it for you.

+2
source

All Articles