Actual source code: blackscholes.c
petsc-3.5.4 2015-05-23
1: /**********************************************************************
2: American Put Options Pricing using the Black-Scholes Equation
4: Background (European Options):
5: The standard European option is a contract where the holder has the right
6: to either buy (call option) or sell (put option) an underlying asset at
7: a designated future time and price.
9: The classic Black-Scholes model begins with an assumption that the
10: price of the underlying asset behaves as a lognormal random walk.
11: Using this assumption and a no-arbitrage argument, the following
12: linear parabolic partial differential equation for the value of the
13: option results:
15: dV/dt + 0.5(sigma**2)(S**alpha)(d2V/dS2) + (r - D)S(dV/dS) - rV = 0.
17: Here, sigma is the volatility of the underling asset, alpha is a
18: measure of elasticity (typically two), D measures the dividend payments
19: on the underling asset, and r is the interest rate.
21: To completely specify the problem, we need to impose some boundary
22: conditions. These are as follows:
24: V(S, T) = max(E - S, 0)
25: V(0, t) = E for all 0 <= t <= T
26: V(s, t) = 0 for all 0 <= t <= T and s->infinity
28: where T is the exercise time time and E the strike price (price paid
29: for the contract).
31: An explicit formula for the value of an European option can be
32: found. See the references for examples.
34: Background (American Options):
35: The American option is similar to its European counterpart. The
36: difference is that the holder of the American option can excercise
37: their right to buy or sell the asset at any time prior to the
38: expiration. This additional ability introduce a free boundary into
39: the Black-Scholes equation which can be modeled as a linear
40: complementarity problem.
42: 0 <= -(dV/dt + 0.5(sigma**2)(S**alpha)(d2V/dS2) + (r - D)S(dV/dS) - rV)
43: complements
44: V(S,T) >= max(E-S,0)
46: where the variables are the same as before and we have the same boundary
47: conditions.
49: There is not explicit formula for calculating the value of an American
50: option. Therefore, we discretize the above problem and solve the
51: resulting linear complementarity problem.
53: We will use backward differences for the time variables and central
54: differences for the space variables. Crank-Nicholson averaging will
55: also be used in the discretization. The algorithm used by the code
56: solves for V(S,t) for a fixed t and then uses this value in the
57: calculation of V(S,t - dt). The method stops when V(S,0) has been
58: found.
60: References:
61: Huang and Pang, "Options Pricing and Linear Complementarity,"
62: Journal of Computational Finance, volume 2, number 3, 1998.
63: Wilmott, "Derivatives: The Theory and Practice of Financial Engineering,"
64: John Wiley and Sons, New York, 1998.
65: ***************************************************************************/
67: /*
68: Include "petsctao.h" so we can use TAO solvers.
69: Include "petscdmda.h" so that we can use distributed meshes (DMs) for managing
70: the parallel mesh.
71: */
73: #include <petscdmda.h>
74: #include <petsctao.h>
76: static char help[] =
77: "This example demonstrates use of the TAO package to\n\
78: solve a linear complementarity problem for pricing American put options.\n\
79: The code uses backward differences in time and central differences in\n\
80: space. The command line options are:\n\
81: -rate <r>, where <r> = interest rate\n\
82: -sigma <s>, where <s> = volatility of the underlying\n\
83: -alpha <a>, where <a> = elasticity of the underlying\n\
84: -delta <d>, where <d> = dividend rate\n\
85: -strike <e>, where <e> = strike price\n\
86: -expiry <t>, where <t> = the expiration date\n\
87: -mt <tg>, where <tg> = number of grid points in time\n\
88: -ms <sg>, where <sg> = number of grid points in space\n\
89: -es <se>, where <se> = ending point of the space discretization\n\n";
91: /*T
92: Concepts: TAO^Solving a complementarity problem
93: Routines: TaoCreate(); TaoDestroy();
94: Routines: TaoSetJacobianRoutine(); TaoAppSetConstraintRoutine();
95: Routines: TaoSetFromOptions();
96: Routines: TaoSolveApplication();
97: Routines: TaoSetVariableBoundsRoutine(); TaoSetInitialSolutionVec();
98: Processors: 1
99: T*/
102: /*
103: User-defined application context - contains data needed by the
104: application-provided call-back routines, FormFunction(), and FormJacobian().
105: */
107: typedef struct {
108: PetscReal *Vt1; /* Value of the option at time T + dt */
109: PetscReal *c; /* Constant -- (r - D)S */
110: PetscReal *d; /* Constant -- -0.5(sigma**2)(S**alpha) */
112: PetscReal rate; /* Interest rate */
113: PetscReal sigma, alpha, delta; /* Underlying asset properties */
114: PetscReal strike, expiry; /* Option contract properties */
116: PetscReal es; /* Finite value used for maximum asset value */
117: PetscReal ds, dt; /* Discretization properties */
118: PetscInt ms, mt; /* Number of elements */
120: DM dm;
121: } AppCtx;
123: /* -------- User-defined Routines --------- */
125: PetscErrorCode FormConstraints(Tao, Vec, Vec, void *);
126: PetscErrorCode FormJacobian(Tao, Vec, Mat, Mat, void *);
127: PetscErrorCode ComputeVariableBounds(Tao, Vec, Vec, void*);
131: int main(int argc, char **argv)
132: {
134: Vec x; /* solution vector */
135: Vec c; /* Constraints function vector */
136: Mat J; /* jacobian matrix */
137: PetscBool flg; /* A return variable when checking for user options */
138: Tao tao; /* Tao solver context */
139: AppCtx user; /* user-defined work context */
140: PetscInt i, j;
141: PetscInt xs,xm,gxs,gxm;
142: PetscReal sval = 0;
143: PetscReal *x_array;
144: Vec localX;
146: /* Initialize PETSc, TAO */
147: PetscInitialize(&argc, &argv, (char *)0, help);
149: /*
150: Initialize the user-defined application context with reasonable
151: values for the American option to price
152: */
153: user.rate = 0.04;
154: user.sigma = 0.40;
155: user.alpha = 2.00;
156: user.delta = 0.01;
157: user.strike = 10.0;
158: user.expiry = 1.0;
159: user.mt = 10;
160: user.ms = 150;
161: user.es = 100.0;
163: /* Read in alternative values for the American option to price */
164: PetscOptionsGetReal(NULL, "-alpha", &user.alpha, &flg);
165: PetscOptionsGetReal(NULL, "-delta", &user.delta, &flg);
166: PetscOptionsGetReal(NULL, "-es", &user.es, &flg);
167: PetscOptionsGetReal(NULL, "-expiry", &user.expiry, &flg);
168: PetscOptionsGetInt(NULL, "-ms", &user.ms, &flg);
169: PetscOptionsGetInt(NULL, "-mt", &user.mt, &flg);
170: PetscOptionsGetReal(NULL, "-rate", &user.rate, &flg);
171: PetscOptionsGetReal(NULL, "-sigma", &user.sigma, &flg);
172: PetscOptionsGetReal(NULL, "-strike", &user.strike, &flg);
174: /* Check that the options set are allowable (needs to be done) */
176: user.ms++;
177: DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,user.ms,1,1,NULL,&user.dm);
178: /* Create appropriate vectors and matrices */
180: DMDAGetCorners(user.dm,&xs,NULL,NULL,&xm,NULL,NULL);
181: DMDAGetGhostCorners(user.dm,&gxs,NULL,NULL,&gxm,NULL,NULL);
183: DMCreateGlobalVector(user.dm,&x);
184: /*
185: Finish filling in the user-defined context with the values for
186: dS, dt, and allocating space for the constants
187: */
188: user.ds = user.es / (user.ms-1);
189: user.dt = user.expiry / user.mt;
191: PetscMalloc1(gxm,&(user.Vt1));
192: PetscMalloc1(gxm,&(user.c));
193: PetscMalloc1(gxm,&(user.d));
195: /*
196: Calculate the values for the constant. Vt1 begins with the ending
197: boundary condition.
198: */
199: for (i=0; i<gxm; i++) {
200: sval = (gxs+i)*user.ds;
201: user.Vt1[i] = PetscMax(user.strike - sval, 0);
202: user.c[i] = (user.delta - user.rate)*sval;
203: user.d[i] = -0.5*user.sigma*user.sigma*PetscPowReal(sval, user.alpha);
204: }
205: if (gxs+gxm==user.ms){
206: user.Vt1[gxm-1] = 0;
207: }
208: VecDuplicate(x, &c);
210: /*
211: Allocate the matrix used by TAO for the Jacobian. Each row of
212: the Jacobian matrix will have at most three elements.
213: */
214: DMCreateMatrix(user.dm,&J);
216: /* The TAO code begins here */
218: /* Create TAO solver and set desired solution method */
219: TaoCreate(PETSC_COMM_WORLD, &tao);
220: TaoSetType(tao,TAOSSILS);
222: /* Set routines for constraints function and Jacobian evaluation */
223: TaoSetConstraintsRoutine(tao, c, FormConstraints, (void *)&user);
224: TaoSetJacobianRoutine(tao, J, J, FormJacobian, (void *)&user);
226: /* Set the variable bounds */
227: TaoSetVariableBoundsRoutine(tao,ComputeVariableBounds,(void*)&user);
229: /* Set initial solution guess */
230: VecGetArray(x,&x_array);
231: for (i=0; i< xm; i++)
232: x_array[i] = user.Vt1[i-gxs+xs];
233: VecRestoreArray(x,&x_array);
234: /* Set data structure */
235: TaoSetInitialVector(tao, x);
237: /* Set routines for function and Jacobian evaluation */
238: TaoSetFromOptions(tao);
240: /* Iteratively solve the linear complementarity problems */
241: for (i = 1; i < user.mt; i++) {
243: /* Solve the current version */
244: TaoSolve(tao);
246: /* Update Vt1 with the solution */
247: DMGetLocalVector(user.dm,&localX);
248: DMGlobalToLocalBegin(user.dm,x,INSERT_VALUES,localX);
249: DMGlobalToLocalEnd(user.dm,x,INSERT_VALUES,localX);
250: VecGetArray(localX,&x_array);
251: for (j = 0; j < gxm; j++) {
252: user.Vt1[j] = x_array[j];
253: }
254: VecRestoreArray(x,&x_array);
255: DMRestoreLocalVector(user.dm,&localX);
256: }
258: /* Free TAO data structures */
259: TaoDestroy(&tao);
261: /* Free PETSc data structures */
262: VecDestroy(&x);
263: VecDestroy(&c);
264: MatDestroy(&J);
265: DMDestroy(&user.dm);
266: /* Free user-defined workspace */
267: PetscFree(user.Vt1);
268: PetscFree(user.c);
269: PetscFree(user.d);
271: PetscFinalize();
272: return 0;
273: }
275: /* -------------------------------------------------------------------- */
278: PetscErrorCode ComputeVariableBounds(Tao tao, Vec xl, Vec xu, void*ctx)
279: {
280: AppCtx *user = (AppCtx *) ctx;
282: PetscInt i;
283: PetscInt xs,xm;
284: PetscInt ms = user->ms;
285: PetscReal sval=0.0,*xl_array,ub= PETSC_INFINITY;
287: /* Set the variable bounds */
288: VecSet(xu, ub);
289: DMDAGetCorners(user->dm,&xs,NULL,NULL,&xm,NULL,NULL);
291: VecGetArray(xl,&xl_array);
292: for (i = 0; i < xm; i++){
293: sval = (xs+i)*user->ds;
294: xl_array[i] = PetscMax(user->strike - sval, 0);
295: }
296: VecRestoreArray(xl,&xl_array);
298: if (xs==0){
299: VecGetArray(xu,&xl_array);
300: xl_array[0] = PetscMax(user->strike, 0);
301: VecRestoreArray(xu,&xl_array);
302: }
303: if (xs+xm==ms){
304: VecGetArray(xu,&xl_array);
305: xl_array[xm-1] = 0;
306: VecRestoreArray(xu,&xl_array);
307: }
309: return 0;
310: }
311: /* -------------------------------------------------------------------- */
315: /*
316: FormFunction - Evaluates gradient of f.
318: Input Parameters:
319: . tao - the Tao context
320: . X - input vector
321: . ptr - optional user-defined context, as set by TaoAppSetConstraintRoutine()
323: Output Parameters:
324: . F - vector containing the newly evaluated gradient
325: */
326: PetscErrorCode FormConstraints(Tao tao, Vec X, Vec F, void *ptr)
327: {
328: AppCtx *user = (AppCtx *) ptr;
329: PetscReal *x, *f;
330: PetscReal *Vt1 = user->Vt1, *c = user->c, *d = user->d;
331: PetscReal rate = user->rate;
332: PetscReal dt = user->dt, ds = user->ds;
333: PetscInt ms = user->ms;
335: PetscInt i, xs,xm,gxs,gxm;
336: Vec localX,localF;
337: PetscReal zero=0.0;
339: DMGetLocalVector(user->dm,&localX);
340: DMGetLocalVector(user->dm,&localF);
341: DMGlobalToLocalBegin(user->dm,X,INSERT_VALUES,localX);
342: DMGlobalToLocalEnd(user->dm,X,INSERT_VALUES,localX);
343: DMDAGetCorners(user->dm,&xs,NULL,NULL,&xm,NULL,NULL);
344: DMDAGetGhostCorners(user->dm,&gxs,NULL,NULL,&gxm,NULL,NULL);
345: VecSet(F, zero);
346: /*
347: The problem size is smaller than the discretization because of the
348: two fixed elements (V(0,T) = E and V(Send,T) = 0.
349: */
351: /* Get pointers to the vector data */
352: VecGetArray(localX, &x);
353: VecGetArray(localF, &f);
355: /* Left Boundary */
356: if (gxs==0){
357: f[0] = x[0]-user->strike;
358: } else {
359: f[0] = 0;
360: }
362: /* All points in the interior */
363: /* for (i=gxs+1;i<gxm-1;i++){ */
364: for (i=1;i<gxm-1;i++){
365: f[i] = (1.0/dt + rate)*x[i] - Vt1[i]/dt + (c[i]/(4*ds))*(x[i+1] - x[i-1] + Vt1[i+1] - Vt1[i-1]) +
366: (d[i]/(2*ds*ds))*(x[i+1] -2*x[i] + x[i-1] + Vt1[i+1] - 2*Vt1[i] + Vt1[i-1]);
367: }
369: /* Right boundary */
370: if (gxs+gxm==ms){
371: f[xm-1]=x[gxm-1];
372: } else {
373: f[xm-1]=0;
374: }
376: /* Restore vectors */
377: VecRestoreArray(localX, &x);
378: VecRestoreArray(localF, &f);
379: DMLocalToGlobalBegin(user->dm,localF,INSERT_VALUES,F);
380: DMLocalToGlobalEnd(user->dm,localF,INSERT_VALUES,F);
381: DMRestoreLocalVector(user->dm,&localX);
382: DMRestoreLocalVector(user->dm,&localF);
383: PetscLogFlops(24*(gxm-2));
384: /*
385: info=VecView(F,PETSC_VIEWER_STDOUT_WORLD);
386: */
387: return 0;
388: }
390: /* ------------------------------------------------------------------- */
393: /*
394: FormJacobian - Evaluates Jacobian matrix.
396: Input Parameters:
397: . tao - the Tao context
398: . X - input vector
399: . ptr - optional user-defined context, as set by TaoSetJacobian()
401: Output Parameters:
402: . J - Jacobian matrix
403: */
404: PetscErrorCode FormJacobian(Tao tao, Vec X, Mat J, Mat tJPre, void *ptr)
405: {
406: AppCtx *user = (AppCtx *) ptr;
407: PetscReal *c = user->c, *d = user->d;
408: PetscReal rate = user->rate;
409: PetscReal dt = user->dt, ds = user->ds;
410: PetscInt ms = user->ms;
411: PetscReal val[3];
413: PetscInt col[3];
414: PetscInt i;
415: PetscInt gxs,gxm;
416: PetscBool assembled;
418: /* Set various matrix options */
419: MatSetOption(J,MAT_IGNORE_OFF_PROC_ENTRIES,PETSC_TRUE);
420: MatAssembled(J,&assembled);
421: if (assembled){MatZeroEntries(J); }
423: DMDAGetGhostCorners(user->dm,&gxs,NULL,NULL,&gxm,NULL,NULL);
425: if (gxs==0){
426: i = 0;
427: col[0] = 0;
428: val[0]=1.0;
429: MatSetValues(J,1,&i,1,col,val,INSERT_VALUES);
430: }
431: for (i=1; i < gxm-1; i++) {
432: col[0] = gxs + i - 1;
433: col[1] = gxs + i;
434: col[2] = gxs + i + 1;
435: val[0] = -c[i]/(4*ds) + d[i]/(2*ds*ds);
436: val[1] = 1.0/dt + rate - d[i]/(ds*ds);
437: val[2] = c[i]/(4*ds) + d[i]/(2*ds*ds);
438: MatSetValues(J,1,&col[1],3,col,val,INSERT_VALUES);
439: }
440: if (gxs+gxm==ms){
441: i = ms-1;
442: col[0] = i;
443: val[0]=1.0;
444: MatSetValues(J,1,&i,1,col,val,INSERT_VALUES);
445: }
447: /* Assemble the Jacobian matrix */
448: MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
449: MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
450: PetscLogFlops(18*(gxm)+5);
451: return 0;
452: }