Posted by
Luigi Ballabio on
URL: http://quantlib.414.s1.nabble.com/PayoffInterpreter-specify-new-pay-offs-and-price-them-without-code-recompilation-tp9776p9778.html
On Tue, 2007-09-25 at 00:00 -0400, Joseph Wang wrote:
> What would be nice is if there were some standard C++ interfaces which people
> could using to "hook in" function evaluation systems from any language.
This can be done already with a combination of polymorphism and the
scripting language API. In Python, for instance, it would be enough to
define a C++ class like the following one and export it to Python via
SWIG:
class PyPayoff : public Payoff {
PyObject payoff_; // The payoff defined in Python. It can be
// a function or function object.
public:
PyPayoff(PyObject* payoff)
: payoff_(payoff) { // Store it...
Py_XINCREF(function_); // ...and make sure Python doesn't
} // garbage-collect it.
~PyPayoff() {
Py_XDECREF(function_); // Release it when we're done.
}
Real operator()(Real price) const {
// Call the Python function using the API...
PyObject* pyResult = PyObject_CallFunction(payoff_,"d",price);
// ...convert the result from Python...
Real result = PyFloat_AsDouble(pyResult);
// ...clean up...
Py_XDECREF(pyResult);
// ...and return.
return result;
}
...
};
Once the above is exported (which can be done in a few lines of SWIG
interface) the payoff can be defined from Python and used, as in:
def my_payoff1(S): # a regular function
return sqrt(S)
class my_payoff2: # a function object
def __init__(self,K):
self.K = K
def __call__(self,S):
return (S-K)**2
option1 = SomeOption(process, PyPayoff(my_payoff1),
exercise, engine)
option2 = SomeOption(process, PyPayoff(my_payoff2(42.0)),
exercise, engine)
I'm sure the same can be done in other languages.
Later,
Luigi
--
Poets have been mysteriously silent on the subject of cheese.
-- Gilbert K. Chesterton
-------------------------------------------------------------------------
This SF.net email is sponsored by: Microsoft
Defy all challenges. Microsoft(R) Visual Studio 2005.
http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/_______________________________________________
QuantLib-dev mailing list
[hidden email]
https://lists.sourceforge.net/lists/listinfo/quantlib-dev