Reputation: 93
I would like to minimize the mean squared error (the mse()
in the hydroGOF
Package might be used) between modeled 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 by leaving Lambda a 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)
Upvotes: 6
Views: 1836
Reputation: 10841
You'll need to write a function to minimise that calculates the mean squared error for this particular case, e.g.:
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()
, like this for instance (you need to specify the range of possible values for Lambda
-- incidentally not an ideal name because it implies that it could be a function when it is actually just a variable):
optimize(calcMSE,c(0,1))
I couldn't do the complete test because I didn't have pbivnorm
installed but this ought to do it for you.
Upvotes: 2
Reputation: 93
Thanks to you Simon, I came to a solution:
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 your help guys!
Upvotes: 1