Derivatives pricing models have been widely applied in the financial industry for building software systems for pricing derivative instruments.
However, most of the research work on financial … Expand. Components: a valuable investment for financial engineering, why derivative contracts should be active documents. PPPJ ' Factory Pattern In my project, I use an abstract factory to call the calculate function that is required by the facade pattern, which is passed on to each concrete factory of specific pricing engines … Expand.
View 1 excerpt, cites methods. This research paper tries to evaluate different variance reduction strategies used for pricing financial options using Monte Carlo simulations. Within the field of finance and theoretical pricing of … Expand. View 1 excerpt, cites background. Robust calibration of the Libor market model and pricing of derivative products. The Libor market model has established itself as the benchmark model for interest rate derivatives. If the observed correlation and volatility surfaces cannot be reproduced by a model, we cannot hope … Expand.
High Dimensional American Options. Pricing single asset American options is a hard problem in mathematical finance. There are no closed form solutions available apart from in the case of the perpetual option , so many approximations … Expand.
View 2 excerpts, cites background. Active Documents Taking advantage of component-orientation beyond pure reuse. Since its introduction, the component-oriented paradigm has exerted strong influence on the development process of software.
Second generation component technologies like. NET or Java provide a … Expand. Related Papers. Its main data member is a ParkMiller generator object. It also remembers the initial seed, and the reciprocal of the maximum value plus one, to save time then turning the output of the inner generator into uniforms. Our pattern here is an example of the adapter pattern. We have a random generator which works and is effective, however its interface is not what the rest of the code expects.
We therefore write a class around it which adapts its interface into what we want. Whenever we use old code or import libraries, it is rare for the interfaces to fit precisely with what we have been using, and the adapter pattern is then necessary. To use the adapter pattern simply means to use an intermediary class which transforms one interface into another. It is the coding equivalent of a plug adapter. The implementation of these classes is straightforward.
The generator relies on modular arithmetic. The basic idea is that if you repeatedly multiply a number by a large number, and then take the modulus with respect to another number, then the successive remainders are effectively random. We refer the reader to [28] for discussion of the mathematics and the choice of the constants.
If it is we change it to 1. The reason is that a zero seed yields a chain of zeros. Note the advantage of a class-based implementation here. The seed is only inputted in the constructor and the set seed method, which are called only rarely, so we can put in extra tests to make sure the seed is correct with no real overhead. If the seed had to be checked every time the random number generator was called, then the overhead would be substantial indeed. The implementation of the adapter class is quite straightforward.
Note that we divide the outputs of the inner class by the maximum plus 1, and so ensure that we obtain random numbers on the open interval 0, 1 rather than the closed one; this means that we will have no trouble with the inverse cumulative normal function.
This means that if we draw a vector X 1 ,. This method guarantees that, for any even number of paths drawn, all the odd moments of the sample of Gaussian variates drawn are zero, and in particular the mean is correct. This generally, but not always, causes simulations to converge faster.
See [11] for discussion of the pros and cons of anti-thetic sampling. We wish to implement anti-thetic sampling in such a way that it can be used with any random number generator and with any Monte Carlo simulation in such a way that we only have to implement it once. The natural way to do this is the decorator pattern. The decoration can be applied to any generator so it fulfills the first criterion, and the fact that the interface is unchanged means that we can plug the decorated class into any socket which the original class fitted.
We implement such a decorator class in AntiThetic. It has an array as a data member to store the last vector drawn, and a boolean to indicate whether the next draw should be drawn from the inner generator, or be the anti-thetic of the last draw. A copy of the generator we are using is stored using the Wrapper template class and cloning, as usual.
Note that we are actually taking a copy of the generator here so that the sequence of draws from the original generator will not be affected by drawing from the anti-thetic generator.
Most of the methods consist of simply forwarding the request to the inner class, together with bookkeeping for odd and even paths. However, we can always treat any inherited class object as a base class object so the call to RandomBase invokes the base class copy constructor, copying the base class data in innerGenerator, and thus ensuring that the new object has the correct dimensionality stored.
We give an adapted vanilla option pricer in SimpleMC8. The header file declares the new function. It cannot be a const reference as the act of drawing a random number changes the generator and is therefore implemented by a non-const method.
The effect of this is that any random numbers drawn inside the function will not be produced outside the function, but instead the generator will continue where the function left off. If we wanted the generator to be totally unaffected by what happened inside the function, we would change the function to take in the object by value instead.
Or alternatively, we could copy the object and pass in the copy to the function, which 98 A random numbers class would have the same net effect. As usual, we use a reference to the base class in order to allow the caller to decide how to implement the generator. The implementation is as follows: Listing 6. OptionPayOff thisSpot ; gatherer.
We set up the array in which to store the variate before we set up the main loop, once and for all. This avoids any difficulties with speed in the allocation of dynamically sized arrays. The GetGaussians method of the generator is used to write the variates in this case just one variate, of course into the array. This variate is then used as before to compute the final value of spot.
We give an example of using this routine with anti-thetic sampling in RandomMain3. The paths will be an array of spot values at the times specified by the product.
We allow the possibility of variable interest rates and dividend rates, as well as variable but deterministic volatility. To simulate this process at times t0 , t1 ,.
Listing 7. Integral 0. Integral Times[j-1],Times[j] - 0. The constructor therefore gets the times from the product, and uses them to compute the integrals of the drifts and the standard deviations which are stored as data members. Note that the class does not bother to store the times as it is only the constructor which needs to know what they are.
In any case, the product is passed up to the base class and it could be retrieved from there if it were necessary. The generation will of course require a random number generator and we pass in a wrapped RandomBase object to allow us to plug in any one we want without having to do any explicit memory handling. We have a data member Variates so that the array can be defined once and for all at the beginning: once again this is with the objective of avoiding unnecessary creation and deletion of objects.
We store the log of the initial value of spot as this is the most convenient for carrying out the path generation. As we have done a lot of precomputation in the constructor, the routine to actually generate a path is fairly simple. We simply get the variates from the generator and loop through the times. For each time, we add the integrated drift to the log, and then add the product of the random number and the standard deviation. To minimize the number of calls to log and exp, we keep track of the log of the spot at all times, and convert into spot values as necessary.
We thus have NumberOfTimes calls to exp each path and no calls to log. As we will have to exponentiate to change our Gaussian into a log-normal variate at some point, this appears to be optimal for this design. If we were really worried that too much time was being spent on computing exponentials, one solution would be to change the design and pass the log of the values of spot back, and then pass these log values into the product. The product would then have the obligation to exponentiate them if necessary.
For certain products such as a geometric Asian option this might well be faster as it would only involve one exponentiation instead of many. The main downside would be that for 7. One simple example is an arithmetic Asian option.
Rather than define a different class for each sort of pay-off, we use the already developed PayOff class as a data member. The header file for the class is quite simple: Listing 7. We pass in the averaging times as an array and we provide a separate delivery time to allow for the possibility that the pay-off occurs at some time after the last averaging date. Note An exotics engine and the template pattern that the use of PayOffBridge class means that the memory handling is handled internally, and this class does not need to worry about assignment, copying and destruction.
The source file is fairly simple too. It only ever generates cash-flows at the delivery time so the PossibleCashFlowTimes method is straightforward too. The CashFlows method takes the spot values, sums them, divides by the number of them and calls ThePayOff to find out what the pay-off is. The answer is then written into the GeneratedFlows array and we are done. We give an example of a simple interface program in EquityFXMain. We have three functions for manipulating strings.
Note the use of the transform algorithm from the standard template library which is neater than looping through the elements of the string. The two ConvertToString functions take in numbers and spit out strings. This is acheived by using the sstream class. This works similarly to iostreams. The difference being that the objective is to create a string rather than an in-out buffer. We include these functions since they will be useful when creating error messages that say that a certain element of a CellMatrix is incorrect, which is very useful when debugging spreadsheets.
We have an add method for each argument type. Almost all of these do the same things: add the argument name and type to ArgumentNames, insert the name and value into the map for this argument type, and call RegisterName.
The method addList takes the same form. The one add method that is different is the one for adding lists. This converts the input ArgumentList into a CellMatrix and calls the addList method, thus avoiding the issue of having ArgumentList data members.
For each one, we copy the input string, convert it to lower case, and look up the map to see if it is present. If it is not present, we throw, and if it is, we store the fact that it has been used, and return the value. Once again it is the list method that has an additional step. Here we get a CellMatrix from the map and convert it to an ArgumentList on final return. A subtlety worth mentioning is that with the current design, it is only at this point that the CellMatrix is checked for validity.
So if the CellMatrix contains errors, then a throw will occur. We also include the GetIfPresent methods to make it easy for the user to deal with optional arguments.
These simply test if the argument is present and if it is, overwrite the parameter passed by value. A bool is returned indicating if the argument was found. These were included to save the user from having to repeatedly write code to test if an argument were present and then do one thing it it was and another if it was not. The remaining methods are self-explanatory and we do not comment on the implementation further.
The most general form of input will be a table of values from the sheet. The object of the CellMatrix is to abstractize this concept. The class is presented in Listing We therefore discuss the CellValue class first. This is intended to represent the possible values a cell can hold. Note that a CellValue can be of at most one type and attempting to use it as another will yield a throw. Note that we also have the methods operator operator operator operator std::string const; bool const; double const; unsigned long const; which may appear a little confusing to the reader.
These are implicit conversion operators. For example, suppose a routine, f, expects a double and we have a CellValue called x holding a double. We can use our original methods to code f x. NumericValue ; but it would be nice if we could just put f x ; Implicit conversion operators allow us to do this. The declaration operator double const; says that the CellValue can be treated as a double and, when this is done, the method Templatizing the factory CellValue::operator double const is called to give the requisite value.
Note that with conversion to user-defined classes an alternative is simply to write a new constructor that takes in a CellValue, but this is not an option for inbuilt types such as doubles.
We also provide constructors for various types to make it easy to create CellValues. In addition, we provide a method for clearing the value: clear. The implementation of this class is straightforward and the details can be found in the file CellMatrix. The CellMatrix class itself is just a table of values implemented as a vector of vectors for simplicity. Note that using a vector of vectors is not recommended for numerical code for efficiency reasons — it may result in data in the same matrix being in rather different parts of the memory and switching memory locations is time consuming.
Here, however, we are purely interested in convenience and the design is adequate. The main thing to remark on in the class is the number of constructors. This is because we will want to write functions returning lots of different types to the spreadsheet. By making the CellMatrix constructors take in all of these, we can simply write routines that return them and convert to a CellMatrix automatically and via that to a spreadsheet data-type.
Otherwise the user will be perpetually writing code at the end of routines to convert data to the correct type. Note we include a couple of routines for merging CellMatrix objects. PushBottom simply adds some new rows to the bottom of the CellMatrix, widening the object if necessary.
MergeCellMatrices does essentially the same thing but with a non-member function interface. The implementation of this class is straightforward and can be found in CellMatrix. The most important of these is the constructor that takes in a CellMatrix ArgumentList CellMatrix cells, std::string ErrorIdentifier ; The idea is that the user in a spreadsheet enters a table of values and these are then used to construct an argument list, which can then be used to create on object from the factory.
The constructor takes in an additional string to make it easy to identify where the problem occurred in the event of an error being thrown. The implementation is fairly straightforward and we only comment on the unusual parts.
ColumnsInStructure cells. StringValueLowerCase ; RowsInStructure , extracted. After studying how to do generic singletons at the start of the chapter, you will note that this is not how the factory has been done. The reason is that the curiously recurring template pattern singleton is too smart for some compilers e. Instead, we therefore work with a friend function called FactoryInstance which can access the private constructor. This has a static variable of type ArgListFactory, and so plays the same role as the static member function Instance in our previous factory.
The rest of the template class is very similar to our non-template factory. Note that we make the names lower case to avoid confusion, and we store a list of all names registered to make it easy to guide the user when an invalid name is passed in.
We also need the helper class to register classes inherited from T with the factory. The derived class will be the class being registered and the base class will specify the factory to be registered with. Otherwise, our helper class is very much the same as the non-template one. Note that we have written our class to only work with the ArgumentList; we could go further and templatize on the argument type, then having two template parameters for the factory and three for the helper class.
However, the ArgumentList class is sufficiently general that the extra flexibility would seem to gain us little at the cost of opaque syntax. We return to our original motivating example: coding a factory for a pay-off class that takes in multiple arguments.
The PayOff class there is very simple Listing Inherited from this class, we have three examples given in PayOffConcrete. Listing In all three cases, the sole constructor takes an ArgumentList, so the factory is directly usable. The class PayOffSpread can be viewed as an example of the composite pattern, which is similar to decorator; the difference being that more than one underlying class is involved.
The classes are implemented in PayOffConcrete. GetStringArgumentValue "name"! GetDoubleArgumentValue "strike" ; args. Spot-Strike Strike-Spot GetStringArgumentValue "name" ; GetArgumentListArgumentValue "optiontwo" ; args. We get the strike by calling GetDoubleArgumentValue "strike" and put it into the relevant data member. Finally, we make sure that the user has not supplied extra irrelevant arguments using the CheckAllUsed method.
The constructor for PayOffSpread is more interesting. The first part is the same as before. We then check to see if the notionals of the two underlying options have been specified and otherwise set default values. To get the underlying options themselves, we use list arguments from the ArgumentList passed in and call the same factory. Note that the factory returns raw pointers, but these are immediately taken over by the Wrapper class, which ensures that they are properly memory managed.
Note the important synergies here between the composite pattern and the ArgumentList class. We are able to bring our composite into the factory because Templatizing the factory it is legitimate to have data stored in the ArgumentList class, which is of the same type, and can therefore be used to create more objects from the factory.
Note that we could even specify the inner class to be another PayOffSpread. The process has to end somewhere, since the number of cells used to make each successive CellMatrix gets smaller each time.
We still have to register these classes with the factory, this is done in PayOffRegistration. The reason is that if we decide to place the PayOff classes in a static library, then we cannot put the registrations in the library. The reason is that if we do, then they will be ignored!
Material in a static library is only included when linking if it is referenced somewhere; a global variable declaration not mentioned anywhere will not be referenced and so not included. Include anti-thetic sampling and moment matching with arbitrary underlying classes amongst the classes to register.
Exercise An xll is a dynamic link library dll that contains some special functions that allow the user to register functions with EXCEL. Once the xll has been created we simply open it from EXCEL, and some new functions appear that can be used just like ordinary inbuilt functions. Our focus in this chapter is on how to use xlw. We do not address how it works. Indeed the philosophy of the current version is that using it should be similar to using a compiler — we wish to understand how to use all the features, but not how it works internally.
The source code is fully available for those who are curious, however. In this chapter, we will restrict our discussion to xlw 2. The package can be obtain from xlw. There is also an xlw-users mailing list which you can subscribe to for further discussion. The essential difference between the series 2 releases of xlw, which the author of this book wrote, and previous releases due to Jerome Lecomte and Ferdinando Ametrano is that the interfacing code is written automatically, so the user needs to know nothing about special data types or registration code.
The xlw 2. The user first has to build the InterfaceGenerator and xlwLib. Interfacing is A project then has to be built that links against xlwLib and includes the new source file. The main trickinesses in the use of xlw are to do with how to set up projects and build for the first time; no actual interface coding is done by the user.
This project should be built and will produce a console application called InterfaceGenerator. Note that we can use the version of this application built with any one compiler with any other compiler without trouble. Second we need to build the xlw 2. The project files are in the same place as for the console application. The built libraries are xlwLib-Debug. For each compiler, an example project is given of functions to be exported to the xll. These are called: DevCppXll.
Some files for payoffs can also be found there, and example spreadsheets. It is the interface file xlwTest. To re-generate it, simply ensure that InterfaceGenerator. The functions to be exported to EXCEL should be contained in header files which contain nothing else. The InterfaceGenerator should then be applied to them. If the header file is called MyFile. The new file should then be added to the project. Note InterfaceGenerator will ignore any preprocessor commands, and will throw an error if the header file contains any classes or function definitions.
It will also protest if any unknown data types are found; we discuss what data types are acceptable in Section The information for the function wizard in EXCEL is taken from comments and the names of argument variables in the header file.
This means that arguments must be named. A comment should follow each argument name and this will appear in the function wizard when that argument is being entered. The general description of the function should be in a comment between the type of the function and its name. Arguments can be passed by reference or by value, and can be const or nonconst. In fact, these have no effect on the coding of the interface file. Once the interface file has been added to the project, we simply build the project and then the output xll file should be openable by EXCEL.
Note that we can have any number of interface files in the same xll project. If you wish to create a new xll project, this can be done. Create a dll project, remove the file created by DevCpp, and then add your files.
Note if you are working with Visual Studio 8. This is not an option when creating new projects from new code. These are divisible into basic data types and extended types. This is a polymorphic data type with two numeric data types that are essentially short and double, so other numeric types go via double. The class MyMatrix is defined via a typedef in MyContainers. You can change this to your favourite matrix type. The matrix class must support the following: it should have.
The class NEMatrix is a typedef for MyMatrix, but if you declare an argument to be of this type, then the function will not be called unless the argument is a nonempty matrix of numbers. If you are working with very large matrices, it should be more stable as the data type is much simpler and Interfacing with EXCEL uses a different mechanism for transmitting the data to and from EXCEL.
The default is to typedef to std::vector. It must have. We discussed the CellMatrix class at length in Section The fact that this class allows a table of cells of arbitrary values including errors means that the conversion of EXCEL data to it should virtually never fail, since it allows error codes. The types std::string and string are both allowed.
These are the same class and the difference is simply in whether the namespace std has already been declared via using. The only constraint is that a function or method must exist that takes in a data type that is already constructible from basic types and creates the new type. We require the construction to be from a single previous type: argument specification would get rather complicated if multiple types were allowed.
For this purpose, a constructor is equivalent to a function. To add in extra types, we have to modify the InterfaceGenerator project. We simply add a declaration in the file TypeRegistrations. The type to convert from is specified by the second argument. The third is the function or method used to construct the new type from the old one.
The first bool is to specify whether the conversion function is a method of the old class, or simply a function or constructor that takes in an object of the old class. The second bool indicates whether the converter method or function takes in a second argument that is a string expressing an identifier in case of error — this is very handy when trying to work out which argument in your complicated function is dubious. For the curious only, the key is to tell EXCEL the type, this is generally only used when defining a basic type.
The last argument allows the forcing of extra includes in our. This allows us to ensure that the conversion function is available. We can define new types from other new types. The maximum depth is 26, at which point the parser concludes that we have accidentally created a loop. The ArgumentList we discussed at length in Chapter The DoubleOrNothing class allows us distinguish between a number passed in or an empty argument. We can therefore choose between a number passed in, and a default value if the argument is empty.
The factory returns a raw pointer to the base class, so this should be immediately converted to a smart pointer as we discussed in Section Our new data type is therefore Wrapper which takes ownership and ensures deletion at the appropriate time.
Note the point Interfacing with EXCEL here that although the factory returns a raw pointer, the registration simply specifies the Wrapper, which silently takes ownership of the pointer. We discuss briefly how this is implemented in the InterfaceGenerator project. The mechanism here is similar to that used for the factory. This class is implemented using a singleton defined via the curiously recurring template pattern from Section ValuesPtr, original.
0コメント