Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate the Area under a Curve

I would like to calculate the area under a curve to do integration without defining a function such as in integrate().

My data looks as this:

Date          Strike     Volatility 2003-01-01    20         0.2 2003-01-01    30         0.3 2003-01-01    40         0.4 etc. 

I plotted plot(strike, volatility) to look at the volatility smile. Is there a way to integrate this plotted "curve"?

like image 582
Dani Avatar asked Feb 10 '11 07:02

Dani


People also ask

Why do we calculate area under the curve?

Definite integrals and areas found under the curve are essential in physics, statistics, engineering, and other applied fields. Learning about areas under the curve also makes you appreciate what you've learned so far and makes you see how amazing integral calculus is.


2 Answers

The AUC is approximated pretty easily by looking at a lot of trapezium figures, each time bound between x_i, x_{i+1}, y{i+1} and y_i. Using the rollmean of the zoo package, you can do:

library(zoo)  x <- 1:10 y <- 3*x+25 id <- order(x)  AUC <- sum(diff(x[id])*rollmean(y[id],2)) 

Make sure you order the x values, or your outcome won't make sense. If you have negative values somewhere along the y axis, you'd have to figure out how exactly you want to define the area under the curve, and adjust accordingly (e.g. using abs() )

Regarding your follow-up : if you don't have a formal function, how would you plot it? So if you only have values, the only thing you can approximate is a definite integral. Even if you have the function in R, you can only calculate definite integrals using integrate(). Plotting the formal function is only possible if you can also define it.

like image 180
Joris Meys Avatar answered Sep 24 '22 01:09

Joris Meys


Just add the following to your program and you will get the area under the curve:

require(pracma) AUC = trapz(strike,volatility) 

From ?trapz:

This approach matches exactly the approximation for integrating the function using the trapezoidal rule with basepoints x.

like image 29
simon Avatar answered Sep 21 '22 01:09

simon