SOLVER FOR NON-LINEAR FUNCTIONS
The end result of this post will be a small, flexible and extendable design for a numerical procedure, which solves a root for a given non-linear function. Now, as you already know there are more than a lot of these root-finding algorithms available. In this post, we just use simple Bisection method. We will create a program design, which can be used to solve for option implied volatility or bond yield-to-maturity, for example.
WIN API DISPCALLFUNC FUNCTION
Let us start and go through Windows API function DispCallFunc, which enables us to implement our desired "function-pointer" mechanism. DispCallFunc belongs to a family of Automation objects (OleAut32.dll) which are written in C language. So, we need to be able to handle parameter exchanges between VBA and C interface. There are a lot of articles about this issue to be found in web. One particularly helpful and otherwise extremely comprehensive source for truly advanced VB stuff is a book written by Bruce McKinney called Hardcore Visual Basic. From the previous link, you have an access to online version of this awesome book. The issues concerning VBA/C interfacing are dealt within the chapter 2 (The Second Level of Basic Enlightenment).
Now, to be able to understand how to use DispCallFunc function in practice, let us first quickly go through its arguments. After this we create two simple example programs on the fly.
void *pvInstance is a special type of pointer that can be pointed at objects of any data type. However, since we are not dealing with any actual COM objects we can set this value to be 0.
ULONG_PTR oVft is a pointer to unsigned long variable. With this argument we will pass the address of a function. DispCallFunc must have a pointer to the callback function's address in memory. VBA supports the AddressOf operator, which makes it possible to pass the address of a VBA function to a DLL function.
CALLCONV cc is an argument for Calling convention to be used. In general, when we deal with C/C++ DLL functions in VBA, we have to use stdcall convention (4).
VARTYPE vtReturn defines a type for function return value. We will use VbVarType enumerated type that indicates the type of the function's return value. If the function does not return any value (Sub procedure in VBA), we will simply use VbVarType.vbEmpty.
UINT cActuals is an unsigned integer for setting the number of function arguments.
VARTYPE *prgvt is a pointer to an array of Integer type VbVarType enumerated values. DispCallFunc must have information on the type of the function arguments. How do we deal with this one in practice? First, we wrap all function argument variable types into an array one by one by using VarType function. Then, we just pass the address of the first item of array for DLL function. When dealing with arrays from VBA to C/C++ DLL functions, we always pass the first array item, not the whole array. If there is not any function arguments, we can simply use zero value.
VARIANTARG **prgpvarg is a pointer to an array of pointers. First, we need to convert all function arguments into new Variant data types. Then, we wrap the address of each variable into a Long data type array (address is Long data type) by using VarPtr function. Finally, we just pass the address of the first item of array. Again, if there is not any function arguments, we can simply use zero value.
VARIANT *pvargResult is a pointer to variant data type. We need to create a variant type variable and give its address by using VarPtr function again. The result value of a function what DispCallFunc is using, is then stored into this variable. The return value of the actual DispCallFunc is zero (assuming that a function call has been successful).
DispCallFunc - example 1.
First, we create a simple program using DispCallFunc. In this example, function to be called by DispCallFunc does not have any arguments or any return value. DispCallFunc will just call procedure someFunction, which then pops up a message. CopyPaste the following program into a new VBA standard module and run the program.
DispCallFunc - example 2.
Next, our function, which is going to get called by DispCallFunc, has two arguments (double) and a return value (double). CopyPaste the following program into a new VBA standard module and run the program.
DispCallFunc works as expected and it is enabling "function pointer mechanism" to be used. We should now be ready for implementing DispCallFunc function in our root solver design.
SOLVER DESIGN WITH DISPCALLFUNC
A couple of words about some of the design targets. We would like to be able to
- change our numerical algorithm for root-solving procedure at will.
- change target function (a function which root is going to be solved) used by root solver at will.
To change our numerical algorithm for root-solving procedure at will gives a strong indication for using VB interfaces. In this case, we will create a common IRootSolver interface, from which we can create any desired new root-solving algorithm implementation.
IRootSolver interface has only one public function (solve), which returns a double and takes in two arguments: "algorithm-related" parameters and "function-related" parameters. In a nutshell, we make a clear division for parameters which are "algorithm-related" and parameters which are "function-related".
When we create our IRootSolver interface and its function signature for this public solve method, we have to make a decision about what are the input arguments for this public solve method. After this, we are married with this function signature, come rain or come shine. Each and every new interface implementation must implement exactly the same interface function signature for this public solve method.
However, each new IRootSolver interface implementation can naturally have different amount of algorithm-related parameters. The most flexible way to have variable amount of input arguments, is to wrap all input parameters into a dictionary data structure. Similarly, target function related parameters are wrapped into a separate data structure. With this approach, public solve method now demands two separate dictionary data structures as its input arguments. One for "algorithm-related" parameters and another for "function-related" parameters. After this, the actual root solver implementation will then "unzip" both data structures to get all the parameters what it needs to perform its numerical procedures. I have been opening this "parameter wrapper" approach in one of my previous posting.
But why this kind of solution for feeding parameters? In some other languages you have constructors for all class member variables and those constructors does not need to have any homogenous signatures for arguments. With VBA we do not even have constructors (class initializers are not really constructors, since you can not have any access to class member variables from outside class itself). So, there is a lot of problems coming from the fact, that VBA does not have real constructors. I have been chewing this issue before in this posting under "constructor problem". Anyway, we can find a way out of this irritating problem just by wrapping all possible parameters inside a data structure and then define our public interface function so, that it is taking only data structure as an input argument.
To change target function used in root solver at will is now easy. First of all, the actual public functions are stored separately in a standard VBA module. A target function is one of those "algorithm-related" parameters and we will wrap its address into a Dictionary by using AddressOf function. As soon as any solver implementation will "unzip" the input algorithm-related data structure, it will have an address to our given target function what solver can use in DispCallFunc function. Function address is really all it knows. Now, we can give any function from our "function library" and solver implementation will then be using this given function with DispCallFunc function, assuming of course that we give all the other required parameters for it.
SOLVER DESIGN IMPLEMENTATION
Finally, we will now create a program, which solves zero-coupon bond yield-to-maturity and option implied volatility as an example. For solving a zero-coupon bond yield-to-maturity, there is no need for any numerical procedure since analytical formula exists. However, it is included here only for demonstration purposes.
Open a new Excel for this project and copyPaste all the following program parts and follow all the given instructions. At this point you could reference Microsoft Scripting Runtime library in your VB editor (Tools - References - Microsoft Scripting Runtime), since we are using Dictionary data structure in our program.
Function library (New standard VBA module, name=FuncLib)
IRootSolver interface (New VBA class module, name=IRootSolver)
IRootSolver implementation (New VBA class module, name=BisectionAlgorithm)
Enumerators for parameter wrappers (New standard VBA module, name=Enumerators)
Main program (New standard VBA module, name=MainProgram)
Note, that the order of parameters inside data structure (target function-related parameters) must correspond exactly the order of target function arguments found in the actual function signature (found in our function library module). Also, the variable what we are about to solve (implied volatility, yield) is also given in function-related parameter wrapper but with zero value. Then, in algorithm-related parameter wrapper we have information, what is the order of item in function-related wrapper, which is going to be solved.
PROS, CONS AND AFTERTHOUGHTS
DispCallFunc works as desired and it can enable cool callback mechanism to be used in VBA. With this design we can implement any new numerical algorithm from our generic IRootSolver. No matter what are the input arguments or how many input arguments there will be for any new solver implementation. We can always zip these input parameters inside a wrapper. In this way, we obey the requirement for "homogeneous public interface function signature" for any new IRootSolver interface implementation. Moreover, we can use any auxiliary function to be solved, since we are delivering the address of this auxiliary function to solver as one of its input parameters.
Of course we need to admit, that compared with the corresponding C/C# mechanism, there are "some additional twists" included, but nothing really too complicated or unmanageable.
Well, that's all for now. If you have been missing some proper callback mechanisms for your VBA programs, you might take a look at this DispCallFunc stuff. This time I need to give my deepest appreciations for Akihito Yamashiro, who has wonderfully and thoroughly opened this issue in his blog.
It has really been a while since my last posting. I have been more than busy with so many issues going on. Being otherwise "A Hard Working Family Man" these days, I additionally decided to go through Certificate in Quantitative Finance program, what I have been quietly woodshedding on my own for the last 6 months or so. During the program I have been learning a lot of interesting stuff and hopefully I could be able to share some of those things with you as well. After finishing CQF, I should be able to allocate some time again for this blog.
Thanks for reading, see you again and have a nice weekend!