Actual source code: blackscholes.c
petsc-3.8.4 2018-03-24
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*);
129: int main(int argc, char **argv)
130: {
132: Vec x; /* solution vector */
133: Vec c; /* Constraints function vector */
134: Mat J; /* jacobian matrix */
135: PetscBool flg; /* A return variable when checking for user options */
136: Tao tao; /* Tao solver context */
137: AppCtx user; /* user-defined work context */
138: PetscInt i, j;
139: PetscInt xs,xm,gxs,gxm;
140: PetscReal sval = 0;
141: PetscReal *x_array;
142: Vec localX;
144: /* Initialize PETSc, TAO */
145: PetscInitialize(&argc, &argv, (char *)0, help);
147: /*
148: Initialize the user-defined application context with reasonable
149: values for the American option to price
150: */
151: user.rate = 0.04;
152: user.sigma = 0.40;
153: user.alpha = 2.00;
154: user.delta = 0.01;
155: user.strike = 10.0;
156: user.expiry = 1.0;
157: user.mt = 10;
158: user.ms = 150;
159: user.es = 100.0;
161: /* Read in alternative values for the American option to price */
162: PetscOptionsGetReal(NULL,NULL, "-alpha", &user.alpha, &flg);
163: PetscOptionsGetReal(NULL,NULL, "-delta", &user.delta, &flg);
164: PetscOptionsGetReal(NULL,NULL, "-es", &user.es, &flg);
165: PetscOptionsGetReal(NULL,NULL, "-expiry", &user.expiry, &flg);
166: PetscOptionsGetInt(NULL,NULL, "-ms", &user.ms, &flg);
167: PetscOptionsGetInt(NULL,NULL, "-mt", &user.mt, &flg);
168: PetscOptionsGetReal(NULL,NULL, "-rate", &user.rate, &flg);
169: PetscOptionsGetReal(NULL,NULL, "-sigma", &user.sigma, &flg);
170: PetscOptionsGetReal(NULL,NULL, "-strike", &user.strike, &flg);
172: /* Check that the options set are allowable (needs to be done) */
174: user.ms++;
175: DMDACreate1d(PETSC_COMM_WORLD,DM_BOUNDARY_NONE,user.ms,1,1,NULL,&user.dm);
176: DMSetFromOptions(user.dm);
177: DMSetUp(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 ierr;
273: }
275: /* -------------------------------------------------------------------- */
276: PetscErrorCode ComputeVariableBounds(Tao tao, Vec xl, Vec xu, void*ctx)
277: {
278: AppCtx *user = (AppCtx *) ctx;
280: PetscInt i;
281: PetscInt xs,xm;
282: PetscInt ms = user->ms;
283: PetscReal sval=0.0,*xl_array,ub= PETSC_INFINITY;
285: /* Set the variable bounds */
286: VecSet(xu, ub);
287: DMDAGetCorners(user->dm,&xs,NULL,NULL,&xm,NULL,NULL);
289: VecGetArray(xl,&xl_array);
290: for (i = 0; i < xm; i++){
291: sval = (xs+i)*user->ds;
292: xl_array[i] = PetscMax(user->strike - sval, 0);
293: }
294: VecRestoreArray(xl,&xl_array);
296: if (xs==0){
297: VecGetArray(xu,&xl_array);
298: xl_array[0] = PetscMax(user->strike, 0);
299: VecRestoreArray(xu,&xl_array);
300: }
301: if (xs+xm==ms){
302: VecGetArray(xu,&xl_array);
303: xl_array[xm-1] = 0;
304: VecRestoreArray(xu,&xl_array);
305: }
307: return 0;
308: }
309: /* -------------------------------------------------------------------- */
311: /*
312: FormFunction - Evaluates gradient of f.
314: Input Parameters:
315: . tao - the Tao context
316: . X - input vector
317: . ptr - optional user-defined context, as set by TaoAppSetConstraintRoutine()
319: Output Parameters:
320: . F - vector containing the newly evaluated gradient
321: */
322: PetscErrorCode FormConstraints(Tao tao, Vec X, Vec F, void *ptr)
323: {
324: AppCtx *user = (AppCtx *) ptr;
325: PetscReal *x, *f;
326: PetscReal *Vt1 = user->Vt1, *c = user->c, *d = user->d;
327: PetscReal rate = user->rate;
328: PetscReal dt = user->dt, ds = user->ds;
329: PetscInt ms = user->ms;
331: PetscInt i, xs,xm,gxs,gxm;
332: Vec localX,localF;
333: PetscReal zero=0.0;
335: DMGetLocalVector(user->dm,&localX);
336: DMGetLocalVector(user->dm,&localF);
337: DMGlobalToLocalBegin(user->dm,X,INSERT_VALUES,localX);
338: DMGlobalToLocalEnd(user->dm,X,INSERT_VALUES,localX);
339: DMDAGetCorners(user->dm,&xs,NULL,NULL,&xm,NULL,NULL);
340: DMDAGetGhostCorners(user->dm,&gxs,NULL,NULL,&gxm,NULL,NULL);
341: VecSet(F, zero);
342: /*
343: The problem size is smaller than the discretization because of the
344: two fixed elements (V(0,T) = E and V(Send,T) = 0.
345: */
347: /* Get pointers to the vector data */
348: VecGetArray(localX, &x);
349: VecGetArray(localF, &f);
351: /* Left Boundary */
352: if (gxs==0){
353: f[0] = x[0]-user->strike;
354: } else {
355: f[0] = 0;
356: }
358: /* All points in the interior */
359: /* for (i=gxs+1;i<gxm-1;i++){ */
360: for (i=1;i<gxm-1;i++){
361: 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]) +
362: (d[i]/(2*ds*ds))*(x[i+1] -2*x[i] + x[i-1] + Vt1[i+1] - 2*Vt1[i] + Vt1[i-1]);
363: }
365: /* Right boundary */
366: if (gxs+gxm==ms){
367: f[xm-1]=x[gxm-1];
368: } else {
369: f[xm-1]=0;
370: }
372: /* Restore vectors */
373: VecRestoreArray(localX, &x);
374: VecRestoreArray(localF, &f);
375: DMLocalToGlobalBegin(user->dm,localF,INSERT_VALUES,F);
376: DMLocalToGlobalEnd(user->dm,localF,INSERT_VALUES,F);
377: DMRestoreLocalVector(user->dm,&localX);
378: DMRestoreLocalVector(user->dm,&localF);
379: PetscLogFlops(24*(gxm-2));
380: /*
381: info=VecView(F,PETSC_VIEWER_STDOUT_WORLD);
382: */
383: return 0;
384: }
386: /* ------------------------------------------------------------------- */
387: /*
388: FormJacobian - Evaluates Jacobian matrix.
390: Input Parameters:
391: . tao - the Tao context
392: . X - input vector
393: . ptr - optional user-defined context, as set by TaoSetJacobian()
395: Output Parameters:
396: . J - Jacobian matrix
397: */
398: PetscErrorCode FormJacobian(Tao tao, Vec X, Mat J, Mat tJPre, void *ptr)
399: {
400: AppCtx *user = (AppCtx *) ptr;
401: PetscReal *c = user->c, *d = user->d;
402: PetscReal rate = user->rate;
403: PetscReal dt = user->dt, ds = user->ds;
404: PetscInt ms = user->ms;
405: PetscReal val[3];
407: PetscInt col[3];
408: PetscInt i;
409: PetscInt gxs,gxm;
410: PetscBool assembled;
412: /* Set various matrix options */
413: MatSetOption(J,MAT_IGNORE_OFF_PROC_ENTRIES,PETSC_TRUE);
414: MatAssembled(J,&assembled);
415: if (assembled){MatZeroEntries(J); }
417: DMDAGetGhostCorners(user->dm,&gxs,NULL,NULL,&gxm,NULL,NULL);
419: if (gxs==0){
420: i = 0;
421: col[0] = 0;
422: val[0]=1.0;
423: MatSetValues(J,1,&i,1,col,val,INSERT_VALUES);
424: }
425: for (i=1; i < gxm-1; i++) {
426: col[0] = gxs + i - 1;
427: col[1] = gxs + i;
428: col[2] = gxs + i + 1;
429: val[0] = -c[i]/(4*ds) + d[i]/(2*ds*ds);
430: val[1] = 1.0/dt + rate - d[i]/(ds*ds);
431: val[2] = c[i]/(4*ds) + d[i]/(2*ds*ds);
432: MatSetValues(J,1,&col[1],3,col,val,INSERT_VALUES);
433: }
434: if (gxs+gxm==ms){
435: i = ms-1;
436: col[0] = i;
437: val[0]=1.0;
438: MatSetValues(J,1,&i,1,col,val,INSERT_VALUES);
439: }
441: /* Assemble the Jacobian matrix */
442: MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
443: MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
444: PetscLogFlops(18*(gxm)+5);
445: return 0;
446: }