Search code examples
javarrjava

Using RQuantLib in Java with RJava


i'm relatively new to using RJava and was getting a null pointer exception from a piece of code I was trying out. I suspect that this could be due to the data type I am using, but am a bit confused about how to solve this. Any help with this would be amazing.

    import org.rosuda.JRI.Rengine;



    public class RJava {

    public static void main(String a[]) {


        String javaVector = "c(put, 0.0425, 66.592, 66.00, 0, 0.068, 0.072, 0.1)";


        Rengine engine = new Rengine(new String[] { "--no-save" }, false, null);


        engine.eval("library(RQuantLib)");
        engine.eval("rVector=" + javaVector);
        engine.eval("Euvol=EuropeanOptionImpliedVolatility(rVector)");

        double vol = engine.eval("Euvol").asDouble();
        System.out.println("Vol=" + vol);

    }
}

       Exception in thread "main" java.lang.NullPointerException
       at co.karan.RJava.main(RJava.java:49)

Solution

  • You have a null exception and it happens in RJava, have you tried to use a debugger to figure out where exactly it crashes?

    Your code can't crash in javaVector and new Rengine because the Java runtime guarantees it'll throw an exception but it won't be a null exception. Your code also can't crash in your eval calls. So what else?

    Your code crashes in engine.eval("Euvol"). The function eval gives you a null and you try to cast to double, you can't do this.

    Now, you should think why your R engine gave you a null exception. There're several possibilities:

    1: You don't have QuantLib installed. RQuantLib won't work if your QuantLib is not properly installed. Worse, you might not even have RQuantLib installed.

    2: Your inputs to RQuanlib are not correct. Read the documentation:

    enter image description here

    The first argument is a STRING. In your code you gave put, this is a variable but not a string.

    The R vector c(put, 0.0425, 66.592, 66.00, 0, 0.068, 0.072, 0.1) is invalid. Try to copy it to your R and you'll get an error.