NAG Technical Report 2/2009

Calling NAG Library Routines from Java


Start of report   Skip to Example 1   Skip to Example 2   Skip to Example 3   Skip to Example 4   Skip to Example 6

4.5. Example 5

Black–Scholes–Merton option pricing formula, function s30aac

Here we show how to call one of the new NAG C Library option pricing functions which require input Nag_PutType and input/output array arguments: the function s30aac. We also show how to pass data back from C to Java properties.

Contents

  1. Function prototype from the NAG C Library Manual
  2. Declaring the native function in our Java program
  3. Compiling the Java program
  4. Generating a header file for use by C
  5. Implementing the native function in C code
  6. Building the shareable library or DLL
  7. Running the program
  8. Quick summary of how to build the option pricing example

  1. Function prototype from the NAG C Library Manual
  2. According to the C Library Manual, the prototype for function s30aac looks like this:

      #include <nag.h>
      #include <nags.h>
    
      void s30aac(Nag_OrderType order, Nag_PutType iput, Integer m,
    	      Integer n, const double x[], double s, const double t[],
    	      double sigma, double r, double q, double p[],
    	      NagError *fail)
    
    
    The function s30aac is designed to compute the price of a European call or put (determined by iput) option for constant volatility, sigma, and risk-free interest rate, r, with a possible dividend yield, q, using the Black–Scholes–Merton formula.

    The computing option prices are returned via array argument p.

    For full description of the roles of all routine arguments consult the s30aac routine document in the NAG C Library Manual.

  3. Declaring the native function in our Java program
  4. As with Example 1, Example 2 and Example 3, we will not attempt to pass the contents of the NagError structure back to Java. In our Java program, we will declare the function like this:

      // Declaration of the Native (C) function
      private native int s30aac(char calput, int m, int n, double[] x, double s,
                                double[] t, double sigma, double r, double q,
                                double[] p);
    
    i.e. a method with return type int.

    Note that we choose not to pass all possible arguments - the order is missing. We could include this argument if we wanted the information it contains to be returned to Java; here we don't. Also the argument iput is replaced with an argument of type char. Later on we will convert it into Nag_PutType argument. Since we are also not using the ifail argument, we will use the int return value to send back any error code.

  5. Compiling the Java program
  6. Here is the complete source code of our Java program EuropeanOptPrice.java.
    public class EuropeanOptPrice
    {
    
      // Declaration of the Native (C) function
      private native int s30aac(char calput, int m, int n, double[] x, double s,
                                double[] t, double sigma, double r, double q,
                                double[] p);
    
      static
        {
          // The runtime system executes a class's static
          // initializer when it loads the class.
          System.loadLibrary("nagCJavaInterface");
        }
    
      // The main program
      public static void main(String[] args)
        {
          double x[], t[], p[];
          double s, sigma, r, q;
          int i, j, m, n, retCode;
          char calput;
    
          // Create an object of class EuropeanOptPrice
          EuropeanOptPrice price = new EuropeanOptPrice();
    
          calput = 'C';
          s = 55.0;
          sigma = 0.3;
          r = 0.1;
          q = 0.0;
          m = 3;
          n = 2;
    
          p = new double[m*n];
          x = new double[m];
          t = new double[n];
    
          for (i = 0; i < m*n; i++)
            p[i] = 0.0;
    
          x[0] = 58.0;
          x[1] = 60.0;
          x[2] = 62.0;
    
          t[0] = 0.7;
          t[1] = 0.8;
    
          System.out.println();
          System.out.println("Call of NAG Black-Scholes-Merton option pricing routine s30aac");
          System.out.println();
    
          // Call method s30aac of object price
          retCode = price.s30aac(calput, m, n, x, s, t, sigma, r, q, p);
    
          System.out.print("Return code from s30aac = ");
          System.out.println(retCode);
          System.out.println();
    
          if (retCode == 0)
            {
              // Print the input values
              System.out.println("European Call:");
              System.out.println("Spot " + s);
              System.out.println("Volatility " + sigma);
              System.out.println("Rate " + r);
              System.out.println("Dividend " + q);
              System.out.println();
    
              // Print the solution
              System.out.println(" Strike      Expiry     Option Price");
              for (i = 0; i < m; i++)
                {
                  for (j = 0; j < n; j++)
                    System.out.format("%8.4f   %8.4f   %8.4f%n",x[i],t[j],p[i*n + j]);
                }
              System.out.println();
            }
        }
    }
    
    The main program simply assigns values of the arguments, and calls the native method using those arguments.

    We can compile our Java program with the following command:

      % javac EuropeanOptPrice.java
    

  7. Generating a header file for use by C
  8. Having compiled EuropeanOptPrice.java, we can use javah to create a C header file:

      % javah -jni EuropeanOptPrice
    
    The generated header file, EuropeanOptPrice.h, contains this function prototype:
      JNIEXPORT jint JNICALL Java_EuropeanOptPrice_s30aac
      (JNIEnv *, jobject, jchar, jint, jint, jdoubleArray, jdouble, jdoubleArray, jdouble, jdouble, jdouble, jdoubleArray);
    

  9. Implementing the native function in C code
  10. Now that we have created the header file EuropeanOptPrice.h, we can write our C code implementation of Java_EuropeanOptPrice_s30aac. Here is the C source code, from file EuropeanOptPriceImp.c:

    #include <jni.h>         /* Java Native Interface headers */
    #include "EuropeanOptPrice.h"  /* Auto-generated header created by javah -jni */
    #include <nag.h>      /* NAG C Library headers */
    #include <nags.h>
    
    /* Our C definition of the function s30aac declared in EuropeanOptPrice.java */
    JNIEXPORT jint JNICALL Java_EuropeanOptPrice_s30aac
      (JNIEnv *env, jobject obj, jchar calput, jint m, jint n, jdoubleArray x,
       jdouble s, jdoubleArray t, jdouble sigma, jdouble r, jdouble q,
       jdoubleArray p)
    {
      static NagError fail;
      Nag_PutType iput;
      Nag_OrderType order;
    
      /* First extract the arrays from Java */
      jdouble *xpt, *tpt, *ppt;
      jboolean isCopy;
    
      xpt = (*env)->GetDoubleArrayElements(env, x, &isCopy);
      tpt = (*env)->GetDoubleArrayElements(env, t, &isCopy);
      ppt = (*env)->GetDoubleArrayElements(env, p, &isCopy);
    
      /* Java stores arrays in row order */
      order = Nag_RowMajor;
    
      /* Convert calput into Nag_PutType */
      if (calput == 'P')
        {
          iput = Nag_Put;
        }
      else if (calput == 'C')
        {
          iput = Nag_Call;
        }
    
      /* Call s30aac */
      fail.print = Nag_FALSE;
      s30aac(order, iput, m, n, xpt, s, tpt, sigma, r, q, ppt, &fail);
    
      /* Release the array elements back to Java */
      (*env)->ReleaseDoubleArrayElements(env, x, xpt, 0);
      (*env)->ReleaseDoubleArrayElements(env, t, tpt, 0);
      (*env)->ReleaseDoubleArrayElements(env, p, ppt, 0);
    
      /* Return any fail code that the nagc.dll function s30aac returned. */
      return fail.code;
    }
    
    Points to note:

  • Building the shareable library or DLL
  • This step is operating-system dependent.

    The compiler flags used were described in Section 7 of Example 1.

  • Running the program
  • Assuming that all has gone well, we can run the program using the command

      % java EuropeanOptPrice
    
    The expected output looks like this:

    Call of NAG Black-Scholes-Merton option pricing routine s30aac
    
    Return code from s30aac = 0
    
    European Call:
    Spot 55.0
    Volatility 0.3
    Rate 0.1
    Dividend 0.0
    
     Strike      Expiry     Option Price
     58.0000     0.7000     5.9198
     58.0000     0.8000     6.5506
     60.0000     0.7000     5.0809
     60.0000     0.8000     5.6992
     62.0000     0.7000     4.3389
     62.0000     0.8000     4.9379
    

    (If you get an error message saying that a library cannot be located, see the tip given in Example 1).

  • Quick summary of how to build the option pricing example
  • Given the two source files EuropeanOptPrice.java and EuropeanOptPriceImp.c, issue the following commands:
    Start of report   Skip to Example 1   Skip to Example 2   Skip to Example 3   Skip to Example 4   Skip to Example 6
    Copyright 2009 Numerical Algorithms Group
    Page last updated 2011-01-25 annak
    [NP3671]