Forecasting with simple stats

by sberube

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Time Series Forecasting</title>
<script src='https://unpkg.com/[email protected]/dist/simple-statistics.min.js'>
</script>
</head>

<body>
    <script>
        // Your array of numbers
        const data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

        // Define the window size (Y) for moving average
        const windowSize = 5;

        // Define the number of periods (X) into the future to forecast
        const forecastPeriods = 3;

        // Function to calculate moving average
        function movingAverage(data, windowSize) {
            const output = [];
            for (let i = windowSize - 1; i < data.length; i++) {
                const windowData = data.slice(i - windowSize + 1, i + 1);
                output.push(window.ss.mean(windowData));
            }
            return output;
        }

        // Forecast X periods into the future
        let forecastData = data.slice();
        for (let i = 1; i <= forecastPeriods; i++) {
            let ma = movingAverage(forecastData.slice(-windowSize), windowSize);
            let nextValue = ma[ma.length - 1];
            forecastData.push(nextValue);
            console.log(`Forecast period ${i}: ${nextValue}`);
        }
    </script>
</body>

</html>