Actual source code: blackscholes.c

petsc-master 2016-12-09
Report Typos and Errors
  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,NULL, "-alpha", &user.alpha, &flg);
165:   PetscOptionsGetReal(NULL,NULL, "-delta", &user.delta, &flg);
166:   PetscOptionsGetReal(NULL,NULL, "-es", &user.es, &flg);
167:   PetscOptionsGetReal(NULL,NULL, "-expiry", &user.expiry, &flg);
168:   PetscOptionsGetInt(NULL,NULL, "-ms", &user.ms, &flg);
169:   PetscOptionsGetInt(NULL,NULL, "-mt", &user.mt, &flg);
170:   PetscOptionsGetReal(NULL,NULL, "-rate", &user.rate, &flg);
171:   PetscOptionsGetReal(NULL,NULL, "-sigma", &user.sigma, &flg);
172:   PetscOptionsGetReal(NULL,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:   DMSetFromOptions(user.dm);
179:   DMSetUp(user.dm);
180:   /* Create appropriate vectors and matrices */

182:   DMDAGetCorners(user.dm,&xs,NULL,NULL,&xm,NULL,NULL);
183:   DMDAGetGhostCorners(user.dm,&gxs,NULL,NULL,&gxm,NULL,NULL);

185:   DMCreateGlobalVector(user.dm,&x);
186:   /*
187:      Finish filling in the user-defined context with the values for
188:      dS, dt, and allocating space for the constants
189:   */
190:   user.ds = user.es / (user.ms-1);
191:   user.dt = user.expiry / user.mt;

193:   PetscMalloc1(gxm,&(user.Vt1));
194:   PetscMalloc1(gxm,&(user.c));
195:   PetscMalloc1(gxm,&(user.d));

197:   /*
198:      Calculate the values for the constant.  Vt1 begins with the ending
199:      boundary condition.
200:   */
201:   for (i=0; i<gxm; i++) {
202:     sval = (gxs+i)*user.ds;
203:     user.Vt1[i] = PetscMax(user.strike - sval, 0);
204:     user.c[i] = (user.delta - user.rate)*sval;
205:     user.d[i] = -0.5*user.sigma*user.sigma*PetscPowReal(sval, user.alpha);
206:   }
207:   if (gxs+gxm==user.ms){
208:     user.Vt1[gxm-1] = 0;
209:   }
210:   VecDuplicate(x, &c);

212:   /*
213:      Allocate the matrix used by TAO for the Jacobian.  Each row of
214:      the Jacobian matrix will have at most three elements.
215:   */
216:   DMCreateMatrix(user.dm,&J);

218:   /* The TAO code begins here */

220:   /* Create TAO solver and set desired solution method  */
221:   TaoCreate(PETSC_COMM_WORLD, &tao);
222:   TaoSetType(tao,TAOSSILS);

224:   /* Set routines for constraints function and Jacobian evaluation */
225:   TaoSetConstraintsRoutine(tao, c, FormConstraints, (void *)&user);
226:   TaoSetJacobianRoutine(tao, J, J, FormJacobian, (void *)&user);

228:   /* Set the variable bounds */
229:   TaoSetVariableBoundsRoutine(tao,ComputeVariableBounds,(void*)&user);

231:   /* Set initial solution guess */
232:   VecGetArray(x,&x_array);
233:   for (i=0; i< xm; i++)
234:     x_array[i] = user.Vt1[i-gxs+xs];
235:   VecRestoreArray(x,&x_array);
236:   /* Set data structure */
237:   TaoSetInitialVector(tao, x);

239:   /* Set routines for function and Jacobian evaluation */
240:   TaoSetFromOptions(tao);

242:   /* Iteratively solve the linear complementarity problems  */
243:   for (i = 1; i < user.mt; i++) {

245:     /* Solve the current version */
246:     TaoSolve(tao);

248:     /* Update Vt1 with the solution */
249:     DMGetLocalVector(user.dm,&localX);
250:     DMGlobalToLocalBegin(user.dm,x,INSERT_VALUES,localX);
251:     DMGlobalToLocalEnd(user.dm,x,INSERT_VALUES,localX);
252:     VecGetArray(localX,&x_array);
253:     for (j = 0; j < gxm; j++) {
254:       user.Vt1[j] = x_array[j];
255:     }
256:     VecRestoreArray(x,&x_array);
257:     DMRestoreLocalVector(user.dm,&localX);
258:   }

260:   /* Free TAO data structures */
261:   TaoDestroy(&tao);

263:   /* Free PETSc data structures */
264:   VecDestroy(&x);
265:   VecDestroy(&c);
266:   MatDestroy(&J);
267:   DMDestroy(&user.dm);
268:   /* Free user-defined workspace */
269:   PetscFree(user.Vt1);
270:   PetscFree(user.c);
271:   PetscFree(user.d);

273:   PetscFinalize();
274:   return ierr;
275: }

277: /* -------------------------------------------------------------------- */
280: PetscErrorCode ComputeVariableBounds(Tao tao, Vec xl, Vec xu, void*ctx)
281: {
282:   AppCtx         *user = (AppCtx *) ctx;
284:   PetscInt       i;
285:   PetscInt       xs,xm;
286:   PetscInt       ms = user->ms;
287:   PetscReal      sval=0.0,*xl_array,ub= PETSC_INFINITY;

289:   /* Set the variable bounds */
290:   VecSet(xu, ub);
291:   DMDAGetCorners(user->dm,&xs,NULL,NULL,&xm,NULL,NULL);

293:   VecGetArray(xl,&xl_array);
294:   for (i = 0; i < xm; i++){
295:     sval = (xs+i)*user->ds;
296:     xl_array[i] = PetscMax(user->strike - sval, 0);
297:   }
298:   VecRestoreArray(xl,&xl_array);

300:   if (xs==0){
301:     VecGetArray(xu,&xl_array);
302:     xl_array[0] = PetscMax(user->strike, 0);
303:     VecRestoreArray(xu,&xl_array);
304:   }
305:   if (xs+xm==ms){
306:     VecGetArray(xu,&xl_array);
307:     xl_array[xm-1] = 0;
308:     VecRestoreArray(xu,&xl_array);
309:   }

311:   return 0;
312: }
313: /* -------------------------------------------------------------------- */

317: /*
318:     FormFunction - Evaluates gradient of f.

320:     Input Parameters:
321: .   tao  - the Tao context
322: .   X    - input vector
323: .   ptr  - optional user-defined context, as set by TaoAppSetConstraintRoutine()

325:     Output Parameters:
326: .   F - vector containing the newly evaluated gradient
327: */
328: PetscErrorCode FormConstraints(Tao tao, Vec X, Vec F, void *ptr)
329: {
330:   AppCtx         *user = (AppCtx *) ptr;
331:   PetscReal      *x, *f;
332:   PetscReal      *Vt1 = user->Vt1, *c = user->c, *d = user->d;
333:   PetscReal      rate = user->rate;
334:   PetscReal      dt = user->dt, ds = user->ds;
335:   PetscInt       ms = user->ms;
337:   PetscInt       i, xs,xm,gxs,gxm;
338:   Vec            localX,localF;
339:   PetscReal      zero=0.0;

341:   DMGetLocalVector(user->dm,&localX);
342:   DMGetLocalVector(user->dm,&localF);
343:   DMGlobalToLocalBegin(user->dm,X,INSERT_VALUES,localX);
344:   DMGlobalToLocalEnd(user->dm,X,INSERT_VALUES,localX);
345:   DMDAGetCorners(user->dm,&xs,NULL,NULL,&xm,NULL,NULL);
346:   DMDAGetGhostCorners(user->dm,&gxs,NULL,NULL,&gxm,NULL,NULL);
347:   VecSet(F, zero);
348:   /*
349:      The problem size is smaller than the discretization because of the
350:      two fixed elements (V(0,T) = E and V(Send,T) = 0.
351:   */

353:   /* Get pointers to the vector data */
354:   VecGetArray(localX, &x);
355:   VecGetArray(localF, &f);

357:   /* Left Boundary */
358:   if (gxs==0){
359:     f[0] = x[0]-user->strike;
360:   } else {
361:     f[0] = 0;
362:   }

364:   /* All points in the interior */
365:   /*  for (i=gxs+1;i<gxm-1;i++){ */
366:   for (i=1;i<gxm-1;i++){
367:     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]) +
368:            (d[i]/(2*ds*ds))*(x[i+1] -2*x[i] + x[i-1] + Vt1[i+1] - 2*Vt1[i] + Vt1[i-1]);
369:   }

371:   /* Right boundary */
372:   if (gxs+gxm==ms){
373:     f[xm-1]=x[gxm-1];
374:   } else {
375:     f[xm-1]=0;
376:   }

378:   /* Restore vectors */
379:   VecRestoreArray(localX, &x);
380:   VecRestoreArray(localF, &f);
381:   DMLocalToGlobalBegin(user->dm,localF,INSERT_VALUES,F);
382:   DMLocalToGlobalEnd(user->dm,localF,INSERT_VALUES,F);
383:   DMRestoreLocalVector(user->dm,&localX);
384:   DMRestoreLocalVector(user->dm,&localF);
385:   PetscLogFlops(24*(gxm-2));
386:   /*
387:   info=VecView(F,PETSC_VIEWER_STDOUT_WORLD);
388:   */
389:   return 0;
390: }

392: /* ------------------------------------------------------------------- */
395: /*
396:    FormJacobian - Evaluates Jacobian matrix.

398:    Input Parameters:
399: .  tao  - the Tao context
400: .  X    - input vector
401: .  ptr  - optional user-defined context, as set by TaoSetJacobian()

403:    Output Parameters:
404: .  J    - Jacobian matrix
405: */
406: PetscErrorCode FormJacobian(Tao tao, Vec X, Mat J, Mat tJPre, void *ptr)
407: {
408:   AppCtx         *user = (AppCtx *) ptr;
409:   PetscReal      *c = user->c, *d = user->d;
410:   PetscReal      rate = user->rate;
411:   PetscReal      dt = user->dt, ds = user->ds;
412:   PetscInt       ms = user->ms;
413:   PetscReal      val[3];
415:   PetscInt       col[3];
416:   PetscInt       i;
417:   PetscInt       gxs,gxm;
418:   PetscBool      assembled;

420:   /* Set various matrix options */
421:   MatSetOption(J,MAT_IGNORE_OFF_PROC_ENTRIES,PETSC_TRUE);
422:   MatAssembled(J,&assembled);
423:   if (assembled){MatZeroEntries(J); }

425:   DMDAGetGhostCorners(user->dm,&gxs,NULL,NULL,&gxm,NULL,NULL);

427:   if (gxs==0){
428:     i = 0;
429:     col[0] = 0;
430:     val[0]=1.0;
431:     MatSetValues(J,1,&i,1,col,val,INSERT_VALUES);
432:   }
433:   for (i=1; i < gxm-1; i++) {
434:     col[0] = gxs + i - 1;
435:     col[1] = gxs + i;
436:     col[2] = gxs + i + 1;
437:     val[0] = -c[i]/(4*ds) + d[i]/(2*ds*ds);
438:     val[1] = 1.0/dt + rate - d[i]/(ds*ds);
439:     val[2] =  c[i]/(4*ds) + d[i]/(2*ds*ds);
440:     MatSetValues(J,1,&col[1],3,col,val,INSERT_VALUES);
441:   }
442:   if (gxs+gxm==ms){
443:     i = ms-1;
444:     col[0] = i;
445:     val[0]=1.0;
446:     MatSetValues(J,1,&i,1,col,val,INSERT_VALUES);
447:   }

449:   /* Assemble the Jacobian matrix */
450:   MatAssemblyBegin(J,MAT_FINAL_ASSEMBLY);
451:   MatAssemblyEnd(J,MAT_FINAL_ASSEMBLY);
452:   PetscLogFlops(18*(gxm)+5);
453:   return 0;
454: }