Automatic Synthesis of Financial Modeling Codes - CiteSeerX

0 downloads 0 Views 392KB Size Report
option value variable from the default V to Cval. ... they are also easy to write, and they provide a convenient way to store and reuse speci cations. In fact, usersĀ ...
Automatic Synthesis of Financial Modeling Codes Curt Randall and Elaine Kant SciComp Incy , 5806 Mesa Drive, Suite 250, Austin, TX 78731 Sergio Kostek Morgan Stanley & Co., 1585 Broadway New York, NY 10036

Abstract

This paper describes the automatic generation of nite di erence codes for solving the Black-Scholes and related equations for options valuation. Codes in several target languages (currently C, Fortran, and Fortran90) are produced from high-level speci cations using the SciNapse program synthesis system, under development at SciComp Inc. Speci cations include the de nition of solution domains, equations, boundary and initial conditions, numerical algorithms, input and output formats, and other programming considerations. SciNapse can synthesize modeling codes for many scienti c and engineering applications. A typical options model can be speci ed in a half page. From such concise input, validated and well-documented codes of several hundred lines of target code can be automatically generated in minutes; codes of several thousands of lines in about an hour. SciNapse encourages exploration of alternative methods because changing equations, discretization methods, solvers, etc., is typically a matter of modifying only a line or two of the speci cation and re-synthesizing. We have used SciNapse to automatically generate nite di erence codes for many types of options models, including vanilla European and American options, compound options, barrier options, convertible bonds, and options with non-standard payouts. Here, we describe how some of these option models are speci ed to SciNapse and display numerical results from the generated codes, comparing to analytic results where possible. The exibility of the system is demonstrated by generating codes that employ high-order di erencing, generalized coordinate transformations for non-uniform grids, and di erent solvers. Our goal in this paper is not to advocate a speci c numerical technique, but rather to demonstrate how modeling productivity leverage can be obtained with automatic program synthesis.

Introduction

New types of derivative securities continue to proliferate. This is old news for anyone working in the nancial sector. Just as any catalog of options becomes quickly obsolete, so does any library of numerical option modeling codes. New models must be generated rapidly and inexpensively. Copyright 1996 by SciComp Inc. This was work supported in part by National Institute of Standards and Technology Advanced Technology Program Cooperative Agreement #70NANB5H1017. y e-mail: [email protected], WWW: http://www.sig.net/scicomp/ 

1

Yet, currently scienti c and nancial modeling software is quite costly. Why is this so? Computer hardware costs have decreased by six orders of magnitude over thirty years, measured in dollars/MFLOP [1]. During this same period the cost of selected types of software has decreased by similar factors, as development is amortized over a few million users instead of a few. For example, the price of a database management system (bundled with other oce products) has decreased by about six orders of magnitude. Unfortunately, scienti c computing software is not mass-market. Scienti c software users typically need code customized to particular applications, so cost is driven by productivity gures for the generation of new software. Process improvements and techniques such as object-oriented programming, code re-use, domain analysis, and specialized language use (e.g., Fortran90) have improved new-program productivity somewhat. However, the experience of many large organizations [2, 3] is that the investment of millions of dollars in software process improvements yields factors of about three in metrics such as lines of code produced per day and defects per thousand lines of code. While such improvements are signi cant, order of magnitude software productivity gains will require more radical solutions such as the automation of the software production process itself. This automation is known as program synthesis. When producing modeling codes, scientists, engineers, and analysts begin with an abstract speci cation for the problem to be solved and the techniques to be applied. While they can often describe it to a colleague in a ve-minute conversation, this speci cation is sucient to completely de ne the desired code. Taking a very simple example, suppose we wish to generate a nite di erence model of simple European call options (though an analytic result, of course, exists [4]) Figure 1 shows an example abstract speci cation. Many details have been left out, to be lled in by mathematics knowledge and common modeling practice. Yet two skilled practitioners can translate this speci cation into functionally identical codes. \Solve the Black-Scholes equation in a region with one space dimension, S the underlying stock price, and one time dimension, t backward time. At the low price boundary the option value is zero, and at the high price boundary the value is linear. The initial condition is the standard payo function. Use Crank-Nicholson di erencing for stability, and a tridiagonal solver to invert the resulting matrix. Write the code in C."

Figure 1: Abstract Speci cation for a European Call Option Although such translation is routine, the process is neither simple nor ecient. Days or weeks may be expended in a cycle of coding, debugging, and recoding for a simple problem, while several months and more may be required for very complex ones. The process is tedious, error-fraught, and begs for automation. The SciNapse program synthesis system under development at SciComp Inc. automates this process for nite di erence and nite volume modeling codes. SciNapse is currently in an advanced prototype stage. It produced the option modeling codes discussed in this paper, and numerous others. Plans call for limited testing of SciNapse by interested parties by year end with commercial versions to follow. We begin our discussion of the synthesis of nancial models with some simple vanilla option examples and then move to a compound option example. Next we use the vanilla option to illustrate some of SciNapse's more powerful features for improving model accuracy, including truncation

2

error analysis, high-order di erencing schemes, and generalized coordinate transformations. We resume our discussion of specifying option models with several multi-dimensional examples, including bivariate cash or nothing spreads and convertible bonds with stochastic interest rates. The list of examples presented is by no means exhaustive, but rather is intended to be illustrative of the system's capabilities. SciNapse can produce nite di erence code for most any option that can be described by a PDE or system of PDE's.

Vanilla Options (* European Call Option *) Cartesian[{S},t]; When[Interior, der[V,t]==1/2 sigma^2 S^2 der[V,{S,2}] + (r-D0) S der[V,S] - r V]; When[min[S], V==0]; When[max[S], der[V,S]==1]; When[min[t], V==Max[S-K,0]]; CrankNicholson; TriDiagonal; TargetLanguage[C];

Figure 2: SciNapse Speci cation for a European Call Option. A SciNapse speci cation le for a simple European call problem, shown in Figure 2, is just a slightly formalized version of our hypothetical verbal speci cation. (In this and all SciNapse speci cations, comments appear as text delimited by (* *).) The rst non-comment line speci es the coordinate system and coordinate names, including the time variable. The second gives the equation being solved in the interior (the non-boundary part of the region.) All equations are speci ed in SciNapse's notation where der[V,fS,ng] means @ n V=@ Sn , and der[V,S] is shorthand for der[V,fS,1g]. The When["region-descriptor",...] statement is used to set a context for a speci cation statement or statements. Thus the \interior" equation is the Black-Scholes equation in backward time @V 2 2 @ 2 V = 2 S @S 2 + (r ? D0 )S @V ? rV : (1) @t @S Following this are the left and right boundary conditions and the initial condition. Finally, the time di erencing method CrankNicholson, the linear solver TriDiagonal, and the target language C are speci ed. V is the value of the option, r is the risk-free interest rate, K is the strike price, sigma is the volatility, etc. From this short le, SciNapse synthesizes a several-hundred-line nite di erence code for the European call, including informative comments. The process takes about ten minutes on a PC or mid-range workstation. SciNapse allows us to be so economical in our speci cation because it has a built-in knowledge base of mathematical and numerical methods; it uses intelligent defaults and heuristics for many programming details such as variable names and input and output methods. For example, the minimum and maximum values of S will be SMin and SMax. Values of these and other variables not de ned by speci c equations will be input from the terminal. The default spatial di erencing is second-order central on a uniform grid, and the default time di erencing, overridden here by our speci cation CrankNicholson, is rst-order explicit.

3

(* Simple European Call Option Model in Log-Price Coordinates *) Region[xMinCval, D0->0, Keywords->{LogPriceCoordinates,BackwardTime}]; CentralSpaceDifference[4]]; When[min[x], Cval==0]; When[max[x], der[Cval,x]==S0 Exp[x]; OneSidedDifference[3]]; ...

Figure 12: SciNapse Speci cation for European call option with higher-order di erencing. fourth-order di erence operator speci ed for the interior grid is ve grid points wide, and cannot be used there, since it would reference non-existent data. SciNapse recognizes this and by default creates a special shifted ve-point operator there. Because this shifted operator is not centered, its accuracy drops by one order to Ord[dx^3]. Consequently, we have speci ed a third-order accurate operator for the boundary condition itself. Alternatively, we could have de ned a wider operator and maintained fourth-order accuracy. Automatic handling of these \special cases" for higher-order di erencing methods is especially helpful in higher dimensions, where special cases can proliferate exponentially. Finite di erence operators of arbitrary order accuracy can be speci ed. After generating the nite di erence equations, the analysis of the truncation error yields Ord[dt^2]+Ord[dx^3]+Ord[dx^4].

The measured RMS error for the call option problem is shown in Figure 11b as the dotted line. Given the preceeding discussion on initial conditions, it is not particularly surprising to see that the absolute accuracy is slightly better than before but still scales as Ord[dx^2]. The algorithm is fourth-order only for suciently smooth functions. (The truncation error analysis assumes, as is customary, that all derivatives are continuous.) If we use a smooth initial value (a Gaussian, which has an easily derivable analytic solution) to verify the code, we obtain the error shown in Figure 11b as the dashed line. It scales as Ord[dx^4]. The Ord[dx^3] errors occur only near the boundaries and have an insigni cant e ect on global error for the chosen parameters. While higher-order methods are routinely used with excellent results for many problems in computational physics, discontinuities in initial conditions and discontinuities imposed by American features makes their value for options models less clear. The important point however, is that using code synthesis one can make such an evaluation in several hours instead of several days. Another approach for improving accuracy, clustering of grid points in critical regions, is considered next.

Generalized Coordinates - Grid Point Clustering

General coordinate transformations are used in the numerical solution of PDE's to increase the density of grid points in critical regions and to allow coordinate systems to conform to complex boundaries. Adaptive grids are generated by time-dependent general coordinate transformations that adapt to the evolving solution. SciNapse currently provides for generalized coordinate transformations speci ed by analytic functions. Automatic numerical generation of grids with various smoothness and orthogonality properties is under development. In options problems, one can con-

11

centrate grid points in critical regions near strike and barrier prices, or even explore the use of adaptive grids. We have already used a coordinate transformation in previous examples: specifying log-price coordinates via a Keyword choice in the BS1D equation generator. Alternatively, we can achieve the same result using SciNapse's facilities for general coordinate transformations, as shown in Figure 13. Because we specify the coordinate transformation explicitly, BS1D is invoked without the LogPriceCoordinates keyword and generates the Black-Scholes equation in price coordinates, as in Eq. (1). The boundary and initial conditions are also given in price coordinates. The new spatial coordinate x is uniformly sampled on the interval xmin  x  xmax . The analytic equations given in the CoordinateTransformation[..] command de ne the transformation, S (x) = S0 exp(x) and t =  (a simple time-independent transformation.) SciNapse transforms all the equations, interior, boundary, and initial, to the new coordinates. For example the BlackScholes equation becomes  1 @V  S (x) @V @V 2 S 2 (x) @ = 2 J (x) @x J (x) @x + r J (x) @x ? rV ; (6) @t where J (x) = @S (x)=@x is the Jacobian. The transformation of this one-dimensional equation is a fairly simple matter, and doesn't fully exploit SciNapse's abilities. In higher dimensionality however, manipulations such as transforming the Navier-Stokes equations of uid dynamics to time-dependent generalized coordinates become exceedingly complex. The ability to make such transformations is built into SciNapse. Numerical results of the code with log-price coordinates speci ed as a CoordinateTransformation as in Figure 13 are very similar, although not identical, to those from the earlier code with LogPriceCoordinates speci ed as a Keyword (see Figure 15.) The di erences arise because SciNapse, by default, discretizes equations in conservative form, and does not expand the chained derivatives in Eq. (6). This is the preference of most experts. It is appropriate if the coordinate transformation is not known analytically, as in this case, but only in tabular form as passed from a numerical grid generator, for example. If SciNapse is forced to use non-conservative form, then using the chain rule, Eq. (6) becomes Eq. (2) and the numerical results are identical. (* European Call Option Model in Generalized Coordinates*) Region[xMin=nShares S0 Exp[x]]; CrankNicholson; SOR; TargetLanguage[C]; Double; Default[ReadFile["cnvbinit.dat"]]; Output[CB, "cnvbnd.out.out", OneFile, Labelled]; * optional variable declarations *) Variable[rMin, Scalar, 1/Time, "minimum r value"]; Variable[rMax, Scalar, 1/Time, "maximum r value"]; ... Variable[Z, Scalar, Dollars, "Bond face value"]; Variable[alpha,Scalar, 1/Time^2,"r coeff in w"]; Variable[beta, Scalar, 1/Time^3,"const coeff in w"]; Variable[delta,Scalar, 1/Time^2,"const coeff in u"]; Variable[gamma,Scalar, 1/Time, "r coeff in u"];

Figure 19: SciNapse Speci cation for Convertible Bond with Stochastic Interest Rate. where u =  ? r. A speci cation le to produce code for the convertible bond model is given in Figure 19. CNVBND2D is an equation generator that produces a general form of Eq. (11). The list of Keywords and the substitutions, e.g. D0->0, specialize the results to the particular interest rate model and other features we need. The mathematically ideal boundary conditions speci ed for r ! 0 and r ! 1 given below Eq. (10) are dicult to implement numerically, and have been replaced with practical conditions that yield the expected behavior. They simply specify that at the r grid boundaries, the value of the bond is exponential in r. We have not attempted to be rigorous here. One of the advantages of code synthesis is that it encourages such experimentation. Users can simply change several lines in the speci cation le and re-synthesize. The numerical results from the code generated by SciNapse from our speci cation are shown in Figure 20.

17

(b)

(a)

2.5 2 1.5 1 V 0.5 0 2

1 0.8 1

1.5

0.6 r 0.4

S

0.5

0.2

1 0.8

1.5

0.6 r 0.4

2.5 2 1.5 1 V 0.5 0 2 1

0 0

S

0.5

0.2 0 0

Figure 20: Initial (a) and nal (b) value of the Convertible Bond using a Cox-Ingersoll-Ross interest rate model. Parameters used: sigma=.4, nShares=1, T=10., alpha=.01, gamma=.15, delta=.01, rho=.4, S0=1., xMin=-2., xMax=2., rMin=0., rMax=1.,

beta=0., iMax=61,

jMax=61, nMax=21.

Other Options

SciNapse can handle quite general systems of partial di erential equations, including non-linear

ones. Therefore, to the extent that any new option model can be practically posed as a system of PDEs, SciNapse can generate nite di erence code to model it. User-extensibility is a key element of this capability. New solvers and program control structures can be added as pseudocode templates and new discretization methods built up from existing primitives or even as pattern replacement rules. By the term \practically posed" as PDE's, we mean models which result in a practical dimensionality. The highest \practical" number of dimensions for the nite di erence solution of a PDE depends on the computer which will run the generated code. Options models with one hundred stochastic variables are solved via Monte Carlo techniques which SciNapse does not currently support. However, there exists a very large number of options which involve two or three such variables. Examples include (but are certainly not limited to) binaries, compounds, choosers, inside barriers, outside barriers, Asians, lookbacks, and convertible bonds with deterministic or stochastic interest rates. With advanced algorithms, problems with up to ve or six dimensions may become practical. Other possibilities include options models governed by equations other than Black-Scholes or its immediate extensions.

18

Inside SciNapse

This section is provided for those readers wishing a deeper understanding of SciNapse's program synthesis process. It describes some general characteristics of the system, including its knowledge base, reasoning processes, and validation mechanisms. We also discuss the various directions in which the knowledge base can be extended, both by users and system developers. More detailed information may be found in [7]. SciNapse employs an extensive knowledge base of mathematical entities, numerical methods, and their relationships. Equations, algorithms and programming constructs are representated by objects capturing their generic form. Symbolic mathematics rules embody numerical approximation techniques, and generic program transformation rules assist with data structure selection and program optimization. Speci cations are successively re ned through a series of levels that approximate users' problem-solving processes. An agenda-based goal mechanism guides the re nement and facilitates a mixed user/system decision-making process.

Knowledge Base Overview

To synthesize codes for a wide variety of applications, SciNapse has a comprehensive knowledge base of rules that implements many design choices. For example, users can specify equations in vector notation with arbitrary spatial dimensionality and let SciNapse automatically re ne the equations into a particular coordinate system. Alternatively, they can specify equations in a component-speci c form, as done here with the Black-Scholes equation and its variants. SciNapse can discretize equations in space using arbitrary order spatial di erencing with staggered grids, and in time using standard methods such as Crank-Nicholson, ADI, Splitting, or Runge-Kutta. Solver algorithms include SOR, Conjugate Gradient, PQMR, tridiagonal, Gaussian, and others listed in Appendix B. In addition to basic time-evolution algorithms, SciNapse also includes a convergencerate test algorithm to validate that a code actually achieves its predicted accuracy. Data structures include dense arrays, restricted-time arrays, diagonal arrays, and specialized stencil representations. SciNapse also applies optimizing transformations such as expression and subroutine in-lining, constant subexpression elimination, loop merging, and loop unrolling as needed. Input values can be speci ed by arrays, functions, subroutines, or passed parameters. Among available output styles are snapshots in single or multiple les and trace les. Future additions will allow for input from geometric modelers, output to visualization systems, and interfaces to numerical libraries (all via a generic interface language with speci c packages for common systems and libraries). A large knowledge base would not be very useful unless it were well organized. SciNapse uses levels of re nement and object representation to promote factoring of implementation concerns. Objects explicitly represent each design choice. Associated sets of rules describe how to carry out the possible design re nements and how to decide among alternatives. The objects mirror standard modeling practice so that design choices can be presented in appropriate terms and in a logical order. For example, SciNapse uses objects to represent equation systems, individual equations, terms of equations and variables, templates, discretization methods, and types of solvers. Attributes of objects represent relationships between these entities and their properties and store the design choices made for speci c problems{for example, the solver to be used with an equation system. Associated with attributes are methods (rules) for computing their values, such as rules for computing the nite di erence formula of a term. Elaboration rules re ne the choices made such as

19

specializing a conjugate gradient solver to a problem's particular matrix structure. Transformation rules carry out most of the generic program synthesis tasks.

Symbolic Mathematics

SciNapse is implemented in Mathematica [8], augmented with SciComp's own object system, tools for simpli cation of inequalities, and tools for simpli cation of expressions mixing loops, conditionals, and algebraic operators. This implementation gives SciNapse direct access to a symbolic algebra and a good facility for for writing pattern-based transformation rules. Computer algebra is used to implement such features as arbitrary order discretizations, truncation error analysis, and coordinate transformations. Other potential uses of computer algebra are numerical stability computations and sensitivity analysis.

Extensibility

SciNapse is a fairly comprehensive system, but because of the large volume of mathematical

knowledge needed for e ective scienti c computing, it must also be easily extensible, both by system developers and end users. SciNapse is extensible in several ways.

 The speci cation language includes parameterizable macros. The use of macros for equation

generators is one example. Another is placing speci cations in macro les as described near the compound option example. Thus users can build up libraries of speci cation les for easy construction of very complex models. Equation speci cation les can be combined with each other and with problem-oriented speci cations such as discretization methods and solvers.  Users and developers can add discretization methods to the system via compositions of existing techniques or with lower-level, continuous-to-discrete pattern replacement rules.  Users and developers can write pseudo-code templates to add new solvers or time-stepping methods.

Customization is streamlined because the user interface, on-line documentation, and system control respond directly to the object representations and are updated automatically when new knowledge is added. The system also contains a number of knowledge-base consistency checks that simplify integrating new knowledge.

Re nement-Based Synthesis

SciNapse successively re nes a problem speci cation through a series of levels that attempt to du-

plicate \best-practice" steps in the problem solving and programming process. The levels progress from requirements (mathematical, then algorithm, then computational) through implementations. Each speci cation statement encapsulates a design choice. Ideally a speci cation is expressed at the most abstract level, but realistically users often need to make lower-level choices for reasons beyond the system's understanding, so speci cations can include choices from a variety of levels. Following the speci cations and system-supplied knowledge, SciNapse re nes a set of equations from coordinate free form to component form, and then discretizes. Next, it combines all the equations into a pseudo-code algorithm via a set of templates for solvers and time-stepping loops.

20

Characteristics of the speci c problem then guide the choice of data structures and access functions. Finally, SciNapse optimizes the resulting pseudo-code and generates the nal program in the chosen target language. A bene t of the re nement approach is the ease of adding new target languages. Because all templates are represented in a pseudo-code (that includes constructs for parallelism) new target languages can be made available simply by constructing a pseudo-code-to-target-language translator.

Built-In Reasoning and Validation of Design Choices

SciNapse guides the synthesis process with a goal and agenda mechanism that allows a mixed

user/system decision-making process. The speci cation le is treated as a set of user suggestions. As the system steps through the set of decisions to be made, it consults both the speci cation and its own knowledge. Associated with each decision are constraints (not to be confused with the Constraint command) and heuristic rules. Constraints are de nite requirements on the legal values of the alternatives; they can be based on choices made previously. Constraints cannot be ignored because violated constraints lead to incorrect codes. If the user has speci ed something that violates a constraint, e.g., specifying a conjugate gradient solver for an asymmetric matrix, the system warns of the inconsistent design choice. If the user has not speci ed a choice, either explicitly (e.g., read variable S0 interactively from the terminal) or with defaults (e.g., always read Fortran inputs from a NameList), then SciNapse invokes its heuristics, which can also be based on previous choices.

Summary

The speci cation of a model to SciNapse begins with the de nition of the solution domain. For options on a single underlying asset, this typically consists of an appropriate interval in asset price and (backward) time. With multiple underlying assets, the domain is multi-dimensional. Users can specify arbitrary coordinate transformations to simplify equations or to concentrate grid points near speci c points such as strike or barrier prices. Next users tell SciNapse which partial di erential equation (PDE) or system of PDEs to solve. The Black-Scholes equation and its most common variants are prede ned and users may select them via keywords. However, most mathematically sensible PDEs are allowed, including nonlinear ones. Coordinate transformations are automatically applied to the selected PDEs. Boundary and initial conditions are speci ed similarly, with the most common selectable via keywords. Tensor order checking and dimensional analysis of user supplied equations eliminates most typographical entry errors. Users can specify discretization techniques, e.g. high-order di erencing for equations or individual terms of equations. Most numerical algorithms for Black-Scholes and related equations involve implicit di erencing for stability, so that a linear solver is required. Solvers may be called from a static library of the user's choosing, or better, may be selected from about a dozen prede ned solvers known to SciNapse. These prede ned solvers are implemented as pseudo-code templates that are expanded in line as the system builds code, taking advantage of knowledge of the speci ed data representations and any special properties of associated matrices such as de niteness and symmetry. Various preconditioners are also provided. The system can use its knowledge to choose

21

an appropriate solver if one is not speci ed by the user. Finally, input and output preferences, target language, and other programming choices may be speci ed. For example, input les may be speci ed as Fortran NameList, while output formats may be appropriate to a favorite data visualization package. Software synthesis is an exciting new technique for scienti c computing in general and for nancial modeling in particular because it:  Encourages users to explore new techniques and to experiment with novel algorithms. Modi cations are made to speci cations instead of to code. For example, the change from a second-order to a fourth-order nite di erence scheme can be e ected by modifying one character in the speci cation le.  Easily produces high quality programs because the algebraic and clerical errors inevitable in manual coding are avoided. Accuracy and stability analyses and convergence rate tests can be automated.  Frees users from having to learn optimizations for new architectures. Such knowledge resides in the synthesis system, which can suggest algorithms based on both the problem and the hardware of interest.

Acknowledgements

We wish to thank Robert Akers, Paul Ba es, Stanly Steinberg, Robert Young, and Michael Ekstrom for critical contributions to the work reported here and suggestions for improving the manuscript.

References [1] T. Guldimann, \Beyond the Year 2000," Risk, 6, June pp. 17-19, 1996. [2] V. Basili, M. Zelkowitz, F. McGarry, J. Page, S. Waligora, and R. Pajerski, \SEL's Software Process Improvement Program," IEEE Software, November 1995, pp.83-87. [3] H. Saiedian and R. Kuzara, \SEI's Capability Maturity Model's Impact on Contractors," IEEE Computer, January 1995, pp.17-26. [4] P. Wilmott, J. Dewynne, and S. Howison, Option Pricing, 1st Edition, Oxford Financial Press, Oxford UK, 1993. [5] J. Hull, Option, Futures, and Other Derivative Securities, 2nd Edition, Prentice Hall, Englewood Cli s, NJ, 1993. [6] R. Heynen and H Kat, \Brick by Brick," Risk, 6, June pp. 58-61, 1996. [7] E. Kant, \Synthesis of Mathematical Modeling Software," IEEE Software, June 1993 pp. 30-41. [8] S. Wolfram, Mathematica: A System for Doing Mathematics by Computer, 2nd Edition, Addison-Wesley, Reading, MA, 1991.

22

[9] R. Barrett, M. Berry, T. Chan, J. Demmel, J. Danato, J. Dongarra, V. Eijkhout, R. Pozo, C. Romine, H. van der Vorst, Templates for the Solution of Linear Systems: Building Blocks for Iterative Methods, SIAM, 1994.

Appendix A: Transformation of Equations

Equations in SciNapse are re ned through a series of levels, from speci cation through code. Here we display the rst few levels of re nement for the Black-Scholes equation in log-price coordinates and backward time.

Speci cation

May appear in a speci cation le or be created by an equation generator le. der[V; t] == (1=2)sigma^2 (der[V; fx; 2g] + (k1 ? 1)der[V; x]) ? r V

Component Level

Normally, SciNapse translates the speci cation into a Coordinate-Free (vector notation) form and then expands that to a system of component form equations in the appropriate coordinate system, including generalized coordinates. However, in this case we have speci ed the single equation in component form and no translation is necessary. ! @V 2 @ 2 V @V = 2 @x2 + (k1 ? 1) @x ? rV @t

Discrete Level

SciNapse uses the user speci ed discretization methods or its own defaults to discretize the equa-

tion. Here the user has speci ed Crank-Nicholson time di erencing and defaulted to second order central space di erencing. V (x + x; t + t) ? 2V (x; t + t) + V (x ? x; t + t) V (x; t + t) ? V (x; t) = 2 t 4x2 + 2 V (x + x; t) ? 2V4(x;x2t) + V (x ? x; t) ? V (x ? x; t + t) + 2 (k1 ? 1) V (x + x; t + t)8 x V (x + x; t) ? V (x ? x; t) 2 +  (k1 ? 1) 8x V (x; t + t) + V (x; t) ? r 2

Staggered grids are allowed. A variable may be de ned anywhere on a grid. SciNapse uses various averaging rules, also user speci able, to generate average values of variables if required. For example, in the call option example with generalized coordinates, J = @S=@x is de ned at half-integer grid locations J (x + x=2). Values of J at whole integer locations are generated automatically via J (x) = (J (x + x=2) + J (x ? x=2))=2.

23

Indexed Level

Using the grid locations of each variable, SciNapse converts the Discrete equation into an Indexed equation. n n n V n+1 ? 2Vin+1 + Vin?+1 Vin+1 ? Vin 1 + Vi+1 ? 2Vi + Vi?1 = 2 i+1 t 4x2 n +1 n +1 Vi+1 ? Vi?1 + Vin+1 ? Vin?1 V n+1 + Vin 2 ? r i +  (k1 ? 1) 8x 2

where, Vin = V (xi ; tn ) = V (xmin + ix; tmin + nt).

Appendix B: Solvers and Preconditioners

By default, SciNapse builds code for solvers from templates rather than calling static solver subroutine libraries. This allows it to make use of knowledge it has about the properties of the matrix and data structures. For example, it can choose a solver based on the matrix properties of such as symmetry, diagonal dominance, or positive de niteness. SciNapse also uses information about the sparsity of the matrix such as being diagonal, tridiagonal, or banded. Templates are provided for many solvers including all of those discussed in the Templates book [9]. A partial list of the available solvers is given in Figure 21.

Type Direct

Name Gauss TriDiagonal Diagonal Stationary Jacobi Iterative SOR SSOR Non-Stationary PCG Iterative PCGS PBCG PBCGST PGMRES PQMR

Description Gaussian Elimination with Partial Pivoting Gaussian Elimination for Three-Banded Matrices Divide by the Diagonal Jacobi Iterative Solver Successive Over Relaxation Symmetric Successive Over Relaxation Conjugate Gradient Conjugate Gradient Squared BiConjugate Gradient BiConjugate Gradient Stabilized Generalized Minimal Residual Quasi Minimal Residual Without Look-Ahead Figure 21: Solvers

24

Appendix C: C Code for European call

Below we reproduce portions of the C code that SciNapse generates from the Vanilla call option speci cation le in Figure 3. The selected code segments illustrate important features of the code without reproducing it in its entirety. To make the series of code segments more readable, annotations have been inserted. These annotations are clearly marked with a \*" in the rst column. They appear here for exposition only, and are not part of the code generated by SciNapse. Some annotation lines end in a number, e.g. (2), which refers to further explanatory notes following the code. \..." denotes deleted code lines. # include # include # include main() { * TYPE DECLARATIONS int i; double xMin; double xMax; double SA[3][3]; void SOR2(); FILE * Stream; ... * GENERAL PROGRAM COMMENTS (1) /* Key to program variables: */ /* Cval: value */ /* eps: machine epsilon */ /* K: strike price */ /* sigma: volatility */ /* S0: normalizing price */ /* temp4: common subexpression temporary */ /* temp3: common subexpression temporary */ ... * INPUT /* Read file callinit.dat */ Stream = fopen("callinit.dat","r"); fscanf(Stream,"%i",&iMax); fscanf(Stream,"%lg",&K); ... * INITIALIZATIONS /* Initial value for Cval */ for (i=0; i0) { Cval[i] = S0*exp(dx*i + xMin) - K; } else { Cval[i] = 0; } } /* Initialize time */ t = 0; ... * CREATING COMMON SUBEXPRESSION TEMPS (2) temp4 = pow(dx,(float)(-2)); temp3 = pow(sigma,2.); ... * SETTING UP "STENCIL ARRAY" SA[][] (3) /* Interior discretization is {CrankNicholson}. */ ... /* Total error is bounded by C*(dt^2 + dx^2). */ /* set up stencils */ /* Computing Cval on dimension x (Minimum); formula is Cval == 0; error is 0; BEq1 */ SA[0][1] = 1.;

25

/* Computing Cval on dimension x (Maximum); formula is -(E^x*S0) + der[Cval, {x,1}] == 0; error is Ord[dx^2]; BEq2 */ SA[1][0] = -(1/dx); SA[1][1] = 1/dx; /* Computing Cval on dimension x (Interior); formula is -(Cval*r) - der[Cval, {t, 1}] + ((k1-1)*sigma^2*der[Cval, {x, 1}])/2 + (sigma^2*der[Cval, {x, 2}])/2 == 0; error is Ord[dt^2] + Ord[dx^2]; BlackScholes1D */ SA[2][0] = temp1 + temp2 - temp; SA[2][1] = -(1/dt) - 0.5*r - 2*temp1; SA[2][2] = temp + temp1 - temp2; ... * MAIN TIME LOOP (4) while (n

Suggest Documents