How does one, having two lists of prices Y and X and wishing to fit the Least Squares model, perform this in Java?

The fit is required to calculate the hedge ratio in a pairs trading strategy.

For every period, the spread is calculated as follows:

symbol1.close - hedgeRatio * symbol2

We intend to compare the performance of this formula versus using normalized moving averages.

The below Python code uses the statsmodels library and the Ordinary Least Squares (OLS) method.

import statsmodels.api as sm

def hedge_ratio(Y, X):
    X = sm.add_constant(X)
    model = sm.OLS(Y, X).fit()
    return model.params[1]
  • 1
    $\begingroup$ I'm voting to close this question at it has no direct link with quantitative finance. It would be better suites to stackoverflow. $\endgroup$ – Quantuple Oct 23 '16 at 10:02
  • $\begingroup$ Indeed not really suited here and this should be googleable: commons.apache.org/proper/commons-math/userguide/… $\endgroup$ – Bob Jansen Oct 23 '16 at 13:58
  • $\begingroup$ In view of this topic on Meta this question can probably be on-topic but please explain more about what have you tried and what inputs and expected outputs are. Where do you stuck when you follow the docs? $\endgroup$ – Bob Jansen Oct 23 '16 at 15:11
  • $\begingroup$ Not a Java programmer myself but don't you just need a linear algebra library and compute $b = \left( X^T X \right)^{-1} X^T y$, where $X$ is your design matrix with first column all ones? See e.g. Chapter 3 in Greene "Econometric Analysis". $\endgroup$ – LocalVolatility Nov 3 '16 at 12:06

The below code works for us:

    final boolean includeIntercept = false;
    SimpleRegression simpleRegression = new SimpleRegression(includeIntercept);

    for (int i = 0; i < symbol1Bars.size(); i++) {
        simpleRegression.addData(symbol1Bars.get(i).getClose(), symbol2Bars.get(i).getClose());

This uses the Apache Commons Math 3 library


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.