Changed around line 1
+ document.addEventListener('DOMContentLoaded', function() {
+ const calculateBtn = document.getElementById('calculate');
+ const forecastStats = document.getElementById('forecast-stats');
+ const canvas = document.getElementById('forecast-chart');
+ const ctx = canvas.getContext('2d');
+
+ function calculateForecast() {
+ const baseline = parseFloat(document.getElementById('baseline').value);
+ const growth = parseFloat(document.getElementById('growth').value) / 100;
+ const confidence = parseFloat(document.getElementById('confidence').value) / 100;
+
+ if (isNaN(baseline) || isNaN(growth) || isNaN(confidence)) {
+ alert('Please enter valid numbers');
+ return;
+ }
+
+ // Calculate forecast with Monte Carlo simulation
+ const iterations = 1000;
+ const results = [];
+
+ for (let i = 0; i < iterations; i++) {
+ const randomGrowth = growth + (Math.random() - 0.5) * 0.2; // Add randomness
+ results.push(baseline * (1 + randomGrowth));
+ }
+
+ results.sort((a, b) => a - b);
+
+ const mean = results.reduce((a, b) => a + b) / results.length;
+ const lower = results[Math.floor(results.length * (1 - confidence))];
+ const upper = results[Math.floor(results.length * confidence)];
+
+ // Display results
+ forecastStats.innerHTML = `
+
Forecast Results
+
Expected Sales: ${mean.toFixed(2)}
+
${confidence * 100}% Confidence Interval:
+
Lower: ${lower.toFixed(2)}
+
Upper: ${upper.toFixed(2)}
+ `;
+
+ // Draw chart
+ drawChart(results);
+ }
+
+ function drawChart(data) {
+ const width = canvas.width;
+ const height = canvas.height;
+
+ ctx.clearRect(0, 0, width, height);
+ ctx.beginPath();
+ ctx.strokeStyle = '#3498db';
+ ctx.lineWidth = 2;
+
+ const buckets = 50;
+ const bucketSize = (Math.max(...data) - Math.min(...data)) / buckets;
+ const histogram = new Array(buckets).fill(0);
+
+ data.forEach(value => {
+ const bucketIndex = Math.floor((value - Math.min(...data)) / bucketSize);
+ histogram[bucketIndex]++;
+ });
+
+ const maxCount = Math.max(...histogram);
+
+ histogram.forEach((count, i) => {
+ const x = (i / buckets) * width;
+ const y = height - (count / maxCount) * height;
+
+ if (i === 0) {
+ ctx.moveTo(x, y);
+ } else {
+ ctx.lineTo(x, y);
+ }
+ });
+
+ ctx.stroke();
+ }
+
+ calculateBtn.addEventListener('click', calculateForecast);
+
+ // Initialize canvas size
+ function resizeCanvas() {
+ const container = canvas.parentElement;
+ canvas.width = container.clientWidth;
+ canvas.height = container.clientWidth * 0.5;
+ }
+
+ window.addEventListener('resize', resizeCanvas);
+ resizeCanvas();
+ });