Stock Price Predictor in java

               It is mathematical model which describes the relationship between variables. One is dependent variable and another one is independent variable.

For eg: stock price predictor. Here, dependent variable is stock price. Independent variables are time, trade data and volume.

The formula for predicted stock price is given by,

Y= beta1+beta2*X+error term

Where,

Y = predicted stock price

X = predictor value

‘beta1’ = intercept

‘beta2’ = slope

Error term

The java implementation is given below…

public class StockPricePredictor {

    private double slope1;

    private double intercept1;

    // Train simple regression model

    public void fit(double[] x, double[] y) {

        if (x.length != y.length) {

            throw new IllegalArgumentException("Two Arrays must have the same length");

        }

        int n = x.length;

        double sumX = 0, sumY = 0, sumXY = 0, sumXX = 0;

        for (int i = 0; i < n; i++) {

            sumX += x[i];

            sumY += y[i];

            sumXY += x[i] * y[i];

            sumXX += x[i] * x[i];

        }

        double meanX = sumX / n;

        double meanY = sumY / n;

        slope1 = (sumXY - n * meanX * meanY) / (sumXX - n * meanX * meanX);

        intercept1 = meanY - slope1 * meanX;

    }

    // Predict value

    public double predictIt(double x) {

        return slope1 * x + intercept1;

    }

    // Get methods

    public double getSlope() { return slope1; }

    public double getIntercept() { return intercept1; }

    // main() fucntion

    public static void main(String[] args) {

        double[] days = {1,2,3,4,5,6,7,8,9,10,11,12};

        double[] prices = {90,102,110,207,80,125,320,20,110,125,12,245};

        StockPricePredictor p1 = new StockPricePredictor();

        p1.fit(days, prices);

        double predictedPrice = p1.predictIt(11);

        System.out.println("Predicted price on day 16: " + predictedPrice);

        System.out.println("Slope: " + p1.getSlope());

        System.out.println("Intercept: " + p1.getIntercept());

    }

}

Output:

Predicted price on day 16: 137.17249417249417

Slope: 1.8531468531468531

Intercept: 116.7878787878788

That’s all. The Java Program to implement Stock Price Predictor was done successfully. Hope, this code gives you the clear view. Keep Coding!!

Comments