Automated AVG plotLine, min and max labels using annotations

by Black Label

HTML

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

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

CSS

#container {
    max-width: 800px;
    margin: 0 auto;
    height: 400px;
    margin-top: 1em;
}

JavaScript

(async () => {

    const data = await fetch(
        'https://demo-live-data.highcharts.com/aapl-c.json'
    ).then(response => response.json());

    let minMax = {};

    function getMinMax(chart) {
        const yMin = Math.min.apply(
                null,
                chart.series[0].processedYData.slice(1, -1)
            ),
            yMax = Math.max.apply(
                null,
                chart.series[0].processedYData.slice(1, -1)
            ),
            maxIndex = chart.series[0].processedYData.indexOf(yMax),
            minIndex = chart.series[0].processedYData.indexOf(yMin);

        minMax = {
            xMin: chart.series[0].processedXData[minIndex],
            xMax: chart.series[0].processedXData[maxIndex],
            yMin,
            yMax
        };
    }

    Highcharts.stockChart('container', {
        chart: {
            zooming: {
                type: 'x'
            }
        },

        xAxis: {
            type: 'datetime'
        },
        yAxis: {
        	min: 30,
            max: 400
        },

        annotations: [{
            draggable: '',
            shapes: [{
                type: 'path',
                points: [
                    annotation => {
                        // Calculate once
                        getMinMax(annotation.chart);

                        return {
                            x: annotation.chart.xAxis[0].min,
                            xAxis: 0,
                            y: (minMax.yMin + minMax.yMax) / 2,
                            yAxis: 0
                        };
                    },
                    annotation => ({
                        x: annotation.chart.xAxis[0].max,
                        xAxis: 0,
                        y: (minMax.yMin + minMax.yMax) / 2,
                        yAxis: 0
                    })
                ]
            }],
            labels: [{
                point: () => ({
                    x: minMax.xMax,
                   ...