How to calculate the hedge ratio between two securities using the Least Squares model in Java

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):
model = sm.OLS(Y, X).fit()
return model.params[1]

• I'm voting to close this question at it has no direct link with quantitative finance. It would be better suites to stackoverflow. – Quantuple Oct 23 '16 at 10:02
• Indeed not really suited here and this should be googleable: commons.apache.org/proper/commons-math/userguide/… – Bob Jansen Oct 23 '16 at 13:58
• 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? – Bob Jansen Oct 23 '16 at 15:11
• 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". – LocalVolatility Nov 3 '16 at 12:06

    final boolean includeIntercept = false;