Skip to content

Instantly share code, notes, and snippets.

@joshbode
Last active October 11, 2015 19:08
Show Gist options
  • Save joshbode/3905422 to your computer and use it in GitHub Desktop.
Save joshbode/3905422 to your computer and use it in GitHub Desktop.
Robust Non-Linear Regression
library(robustbase)
# black-scholes LGR function
LGR = function (x, LGR_0, sigma) {
d_1 = (log(x) + sigma ^ 2 / 2.0) / sigma
d_2 = d_1 - sigma
return(LGR_0 * ifelse(x > 0, pnorm(-d_2) - x * pnorm(-d_1), 1.0))
}
# fake data
d = data.frame(x=seq(0, 2, 0.1))
d$y = LGR(d$x, 0.5, 0.9) + 0.1 * runif(length(d$x), -1, 1)
# fit least-squares and robust regressions
initial = c(LGR_0=1.0, sigma=1.0)
fit = nls(y ~ LGR(x, LGR_0, sigma), d, initial, trace=TRUE)
fit_rr = nlrob(y ~ LGR(x, LGR_0, sigma), d, initial, trace=TRUE)
plot(d$x, d$y)
lines(d$x, predict(fit))
lines(d$x, predict(fit_rr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment