Highcharts Stock Demo

author(s): Paweł Fus

HTML

<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/indicators/indicators.js"></script>

<div id="container"></div>

CSS

#container {
    height: 400px;
    min-width: 310px;
}

JavaScript

function getLinearRegression(xData, yData) {
    let sumX = 0,
        sumY = 0,
        sumXY = 0,
        sumX2 = 0,
        x,
        y;

    const linearData = [],
        linearXData = [],
        linearYData = [],
        n = xData.length;

    // Get sums:
    for (let i = 0; i < n; i++) {
        x = xData[i];
        y = yData[i];
        sumX += x;
        sumY += y;
        sumXY += x * y;
        sumX2 += x * x;
    }

    // Get slope and offset:
    let alpha = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);

    if (isNaN(alpha)) {
        alpha = 0;
    }

    const beta = (sumY - alpha * sumX) / n;

    // Calculate linear regression:
    for (let i = 0; i < n; i++) {
        x = xData[i];
        y = alpha * x + beta;

        // Prepare arrays required for getValues() method
        linearData[i] = [x, y];
        linearXData[i] = x;
        linearYData[i] = y;
    }

    return {
        xData: linearXData,
        yData: linearYData,
        values: linearData
    };
}

Highcharts.seriesType(
    'linearregression',
    'sma', {
        name: 'Linear Regression',
        enableMouseTracking: false,
        marker: {
            enabled: false
        },
        params: {} // linear regression doesn’t need params
    }, {
        getValues: function (series) {
            return this.getLinearRegression(series.xData, series.yData);
        },
        getLinearRegression: getLinearRegression
    }
);

Highcharts.chart('container', {
    chart: {
        type: 'scatter',
        zooming: {
            type: 'xy'
        }
    },
    title: {
        text: 'Height Versus Weight of 507 Individuals by Gender'
    },
    subtitle: {
        text: 'Source: Heinz  2003'
    },
    xAxis: {
        title: {
            enabled: true,
            text: 'Height (cm)'
        },
        startOnTick: true,
        endOnTick: true,
        showLastLabel: true
    },
    yAxis: {
        title: {
            text: 'Weight (kg)'
        }
    },
   ...