%%HTML

<html>

<body>

  <div>
    <!-- Input for the stock symbol -->
    <label for="stockInput">Enter Stock Symbol: </label>
    <input type="text" id="stockInput" placeholder="e.g. MSFT">
    <button onclick="fetchData()">Generate Graph</button>
  </div>
  
  <!-- Canvas element for the graph -->
  <canvas></canvas>

  <div class="prediction-wrapper" style="display:none">
    <!-- Input for user to enter a date for prediction -->
    <label for="predictionInput">Enter a Month to Predict your Selected Stock Price (YYYY-MM): </label>
    <input type="text" id="predictionInput" placeholder="e.g. 2023-09">
    <button onclick="predictPrice()">Predict Price</button>
    <!-- Display the prediction result -->
    <h1 id="prediction"></h1>
  </div>

  <script>

    // Global variables to store regression data and x-value
    let regression = {}
    let x = 0

    // Function to fetch stock data
    async function fetchData() {
      const stockSymbol = document.getElementById('stockInput').value;
      const url = `https://alpha-vantage.p.rapidapi.com/query?function=TIME_SERIES_MONTHLY_ADJUSTED&symbol=${stockSymbol}&datatype=json`;
      const options = {
        method: 'GET',
        headers: {
          'X-RapidAPI-Key': '115318933dmsh6d4dd26b9c05b57p138eb6jsn5766c7fe61da',
          'X-RapidAPI-Host': 'alpha-vantage.p.rapidapi.com'
        }
      };

      try {
        // Fetch stock data from the API
        const response = await fetch(url, options);
        const result = await response.json();

        // Extract dates and adjusted closing prices from the API response
        const weeklyData = result['Monthly Adjusted Time Series'];
        const dates = Object.keys(weeklyData);

        // Parse prices as floats
        const prices = dates.map((date) => parseFloat(weeklyData[date]['5. adjusted close']));

        // Generate the graph using the data
        generateGraph(dates, prices)

      } catch (error) {
        console.error(error);
      }
    }

    // Function to generate the graph
    function generateGraph(dates, prices) {
      // Get canvas element and context
      const canvas = document.getElementsByTagName('canvas')[0];
      const ctx = canvas.getContext('2d');

      // Define canvas dimensions
      canvas.width = 700;
      canvas.height = 400;

      // Define data points and chart dimensions
      const dataPoints = prices.length;
      const margin = 40;
      const chartWidth = canvas.width - 2 * margin;
      const chartHeight = canvas.height - 2 * margin;

      // Calculate scaling factors
      const maxPrice = Math.max(...prices);
      const minPrice = Math.min(...prices);
      const priceRange = maxPrice - minPrice;
      const xStep = chartWidth / (dataPoints - 1);
      const yStep = chartHeight / priceRange;

      // Draw x and y axes
      ctx.beginPath();
      ctx.moveTo(margin, margin);
      ctx.lineTo(margin, canvas.height - margin);
      ctx.lineTo(canvas.width - margin, canvas.height - margin);
      ctx.stroke();

      // Plot stock prices
      ctx.beginPath();
      ctx.strokeStyle = 'blue';
      ctx.lineWidth = 2;
      for (let i = dataPoints; i > 0; i--) {
        const x = canvas.width - 40 - i * xStep;
        const y = canvas.height - margin - (prices[i] - minPrice) * yStep;
        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      }
      ctx.stroke();

      // Calculate linear regression
      const xValues = [...Array(dataPoints).keys()];
      const yValues = prices;
      regression = linearRegression(xValues, yValues);

      // Plot linear regression line
      ctx.beginPath();
      ctx.strokeStyle = 'red';
      ctx.lineWidth = 2;
      for (let i = 0; i < dataPoints; i++) {
        const x = canvas.width - 40 - i * xStep;
        const y = canvas.height - margin - (regression.slope * i + regression.intercept - minPrice) * yStep;
        if (i === 0) {
          ctx.moveTo(x, y);
        } else {
          ctx.lineTo(x, y);
        }
      }
      ctx.stroke();

      // Label axes
      ctx.fillStyle = 'black';
      ctx.fillText('Date', canvas.width - margin - 20, canvas.height - 10);
      ctx.fillText('Stock Price', margin - 10, margin - 10);

      // Display the prediction input section
      document.getElementsByClassName("prediction-wrapper")[0].style.display = "block"
    }

    // Function to calculate linear regression
    function linearRegression(x, y) {
      const n = x.length;
      let sumX = 0;
      let sumY = 0;
      let sumXY = 0;
      let sumX2 = 0;

      for (let i = 0; i < n; i++) {
        sumX += x[i];
        sumY += y[i];
        sumXY += x[i] * y[i];
        sumX2 += x[i] * x[i];
      }

      const slope = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
      const intercept = (sumY - slope * sumX) / n;

      return {
        slope,
        intercept
      };
    }

    // Function to calculate the index based on user input
    function calculateIndex(userInput) {
      // Split the user input into year and month
      const [year, month] = userInput.split('-');
    
      // Calculate the index based on the year and month, assuming January 2000 as the starting point
      const startIndex = (parseInt(year) - 2000) * 12 + (parseInt(month) + 1);
    
      return startIndex;
    }    

    // Function to predict the stock price
    function predictPrice() {
      const prediction = document.getElementById("predictionInput").value;

      // Calculate the x-value based on user input
      let xValue = calculateIndex(prediction)

      // Predict the stock price using linear regression formula
      const predictedPrice = (-regression.slope * xValue + regression.intercept);

      // Display the predicted price
      document.getElementById("prediction").textContent = "$" + predictedPrice.toFixed(2);
    }
  </script>

  <style>
    .prediction-wrapper {
      display: none;
    }
  </style>

</body>

</html>