eddelbuettel / rquantlib

R interface to the QuantLib library
119 stars 50 forks source link

Vectorization of Functions #58

Closed alitiffany closed 8 years ago

alitiffany commented 8 years ago

I am using the package to do some derivative pricing and meet a problem. Maybe all the pricing functions like "EuropeanOption" are not vectorized?

When I type: EuropeanOption(c("call", "put"), c(100, 100), c(100, 100), c(0.01, 0.01), c(0.03, 0.03), c(0.5, 0.5), c(0.4, 0.4)), the screen prints that:Error in europeanOptionEngine(type, underlying, strike, dividendYield, : expecting a single value.

I want to do pricing for several deravatives at one time so that I am concerned about this topic. For instance, I storred information of several derivatives in a data.table and I want to add a column to do pricing for all these derivatives. The code maybe like this : table[, price := EuropeanOption(type, underlying, strike, dividendYield, riskFreeRate, maturity, volatility = vol)]. And of course this does not work.

I do hope that you can help me to use these pricing functions like vectorized functions. Thank you in advance!

eddelbuettel commented 8 years ago

I found it hard to do this 'generically'. Different folks may want different vector argument for different 'greek' sensitivities. I have not been able to think of a way to do this nicely for all interesting cases. Can you?

When I needed something like this at work once (for the related task of implied vol calculation across vectors of deltas etc), I just wrote a custom function. It helped a lot in terms of speed for that case, but again I did not find it generalized. I did write a blog post though. Maybe that helps.

Better ideas welcome.

tleitch commented 8 years ago

I've vectorized black scholes on a gpu. The key vector inputs that make sense are either strike, spot, time, volatility, or rate. One input, but not more than one, could logically be a vectorized for a given call. The call above would produce a hypercube.

eddelbuettel commented 8 years ago

Yes, sure. I also did something similar in EuropeanOptionArrays at the R level. We could pull this down to C++ for efficiency, and then rearranging things neatly in R.

alitiffany commented 8 years ago

Thank you so much for your sharing! Your blog post maked me more clear about how functions work in your package and motivated me to start learning Rcpp. Maybe it is necessary to define my own functions using Rcpp everytime when I meet such vectorized problems.