Building a Stock Market Tracker Using an API with HTML, CSS, and JavaScript
March 31, 20255 min read

Building a Stock Market Tracker Using an API with HTML, CSS, and JavaScript

Web developmentJavaScriptCSS3JavaScript Projects
share this article on

Introduction

Stock market data is essential for traders, investors, and financial enthusiasts. With APIs like Alpha Vantage or Twelve Data, we can retrieve real-time stock market information and display it on a webpage.

In this tutorial, we’ll create a simple stock market tracker that fetches and displays stock prices, trading volume, 52-week high/low, market capitalization, P/E ratio, and dividend yield using HTML, CSS, and JavaScript. We will also integrate Chart.js to visualize historical stock data.

Prerequisites

Before we begin, ensure you have:

Setting Up the Project

We’ll create three files:

Step 1: HTML Structure

We’ll build a simple layout with an input field to enter a stock symbol, a button to fetch data, and sections to display stock details

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Stock Market Dashboard</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h2>Stock Market Data</h2>
        <div class="input-group">
            <input type="text" id="stockSymbol" placeholder="Enter Stock Symbol">
            <button onclick="fetchStockData()">Get Stock Data</button>
        </div>
    
        <div class="company-info">
            <p class="company-name" id="companyName">-</p>
            <p class="stock-price-info">
                <span class="stock-price" id="stockPrice">-</span>
                <span class="stock-change" id="stockChange">-</span>
            </p>
            <p class="company-description" id="companyDescription">-</p>
        </div>
    
        <div class="tables">
            <table>
                <tr><th>Sector</th><td id="sector">-</td></tr>
                <tr><th>Previous Close</th><td id="previousClose">-</td></tr>
                <tr><th>Open</th><td id="stockOpen">-</td></tr>
                <tr><th>High</th><td id="stockHigh">-</td></tr>
                <tr><th>Low</th><td id="stockLow">-</td></tr>
                <tr><th>Volume</th><td id="stockVolume">-</td></tr>
                <tr><th>52-Week High</th><td id="stock52WeekHigh">-</td></tr>
                <tr><th>52-Week Low</th><td id="stock52WeekLow">-</td></tr>
         </table>
        <table>
                <tr><th>Market Cap</th><td id="marketCap">-</td></tr>
                <tr><th>Book Value</th><td id="bookValue">-</td></tr>
                <tr><th>EPS</th><td id="eps">-</td></tr>
                <tr><th>Beta</th><td id="beta">-</td></tr>
                <tr><th>EBITDA</th><td id="ebitda">-</td></tr>
                <tr><th>P/E Ratio</th><td id="peRatio">-</td></tr>
                <tr><th>Dividend Yield</th><td id="dividendYield">-</td></tr>
                <tr><th>200 DMA</th><td id="dayMovingAverage">-</td></tr>
        </table>
    </div>
        <div class="button-group">
            <button class="buy-btn">Buy</button>
            <button class="sell-btn">Sell</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

Step 2: Styling with CSS

Now, let’s add some styling to make our tracker visually appealing.

body {
    font-family: Arial, sans-serif;
    background-color: #161a20;
    color: white;
    text-align: center;
    padding: 20px;
}

.container {
    max-width: 800px;
    margin: auto;
}

input,
button {
    padding: 10px;
    margin: 10px;
    font-size: 16px;
}

button {
    cursor: pointer;
    background-color: #28a745;
    color: white;
    border: none;
}

.company-info {
    margin-bottom: 20px;
}

.company-name {
    font-size: 36px;
    font-weight: bold;
    color: #fff;
    text-align: justify;
    margin-bottom: 10px;
}

.stock-price-info {
    text-align: justify;
}

.stock-price {
    font-size: 32px;
    font-weight: bold;
    color: white;
    background: #161a20;
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
    margin-top: 5px;
}

.stock-change {
    font-size: 18px;
    font-weight: bold;
    margin-left: 10px;
}

.company-description {
    font-size: 14px;
    color: #aca8a8;
    margin-top: 10px;
    text-align: justify;
}

.tables {
    display: flex;
    justify-content: center;
    gap: 20px;
}

table {
    width: 45%;
    border-collapse: collapse;
    background: white;
    box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
}

th,
td {
    padding: 10px;
    border: 1px solid #ddd;
    text-align: left;
    color: #161a20;
}

th {
    background: #161a20;
    color: white;
}

.button-group {
    margin-top: 20px;
}

.buy-btn, .sell-btn {
    width: 100px;
    color: white;
}

.sell-btn {
    background-color: red;

}

Step 3: JavaScript to Fetch Stock Data

We will now use JavaScript to fetch stock data from the API and display it on the page.

const apiKey = "Alpha Vantage API Key";   //Replace with your Alpha Vantage API Key
const apiUrl = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=";
const overviewUrl = "https://www.alphavantage.co/query?function=OVERVIEW&symbol=";
const timeSeriesUrl = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=";

async function fetchStockData() {
    const symbol = document.getElementById("stockSymbol").value.toUpperCase();
    if (!symbol) {
        alert("Please enter a stock symbol.");
        return;
    }

    try {
        // Fetch Real-Time Stock Data
        const stockUrl = `https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=${symbol}&apikey=${apiKey}`;
        const stockResponse = await fetch(stockUrl);
        const stockData = await stockResponse.json();

        if (!stockData["Global Quote"]) {
            alert("Invalid stock symbol or API limit exceeded.");
            return;
        }

        const stock = stockData["Global Quote"];
        const change = parseFloat(stock["09. change"]).toFixed(2);
    
        document.getElementById("stockPrice").innerText = `$${parseFloat(stock["05. price"]).toFixed(2)}`;
        document.getElementById("stockChange").innerText = `${stock["09. change"]} (${stock["10. change percent"]})`;
        document.getElementById("stockChange").style.color = change >= 0 ? "green" : "red";
        document.getElementById("stockOpen").innerText = `$${parseFloat(stock["02. open"]).toFixed(2)}`;
        document.getElementById("stockHigh").innerText = `$${parseFloat(stock["03. high"]).toFixed(2)}`;
        document.getElementById("stockLow").innerText = `$${parseFloat(stock["04. low"]).toFixed(2)}`;
        document.getElementById("stockVolume").innerText = `${stock["06. volume"]}`;
        document.getElementById("previousClose").innerText = parseFloat(stock["08. previous close"]).toFixed(2);

        // Fetch Additional Company Information
        const overviewUrl = `https://www.alphavantage.co/query?function=OVERVIEW&symbol=${symbol}&apikey=${apiKey}`;
        const overviewResponse = await fetch(overviewUrl);
        const overviewData = await overviewResponse.json();

        if (overviewData) {
            document.getElementById("companyName").innerText = overviewData["Name"] || "Company Name Not Available";
            document.getElementById("companyDescription").innerText = overviewData["Description"] || "No description available.";
            document.getElementById("stock52WeekHigh").innerText = `$${overviewData["52WeekHigh"]}`;
            document.getElementById("stock52WeekLow").innerText = `$${overviewData["52WeekLow"]}`;
            document.getElementById("marketCap").innerText = `$${(overviewData["MarketCapitalization"] / 1e9).toFixed(2)}B`;
            document.getElementById("peRatio").innerText = overviewData["PERatio"];
            document.getElementById("dividendYield").innerText = `${(overviewData["DividendYield"] * 100).toFixed(2)}%`;
            document.getElementById("sector").innerText = `${overviewData["Sector"]}`;
            document.getElementById("bookValue").innerText = `${overviewData["BookValue"]}`;
            document.getElementById("eps").innerText = `${overviewData["EPS"]}`;
            document.getElementById("ebitda").innerText = `${(overviewData["EBITDA"] / 1e9).toFixed(2)}B`;
            document.getElementById("beta").innerText = `${overviewData["Beta"]}`;
            document.getElementById("dayMovingAverage").innerText = `${overviewData["200DayMovingAverage"]}`;
        }

    } catch (error) {
        console.error("Error fetching stock data:", error);
        alert("Error fetching stock data. Please try again later");
    }
}

Explanation

  1. Fetch stock data from Alpha Vantage API using the stock symbol entered by the user.
  2. Extract latest stock price, open, high, low, and volume from the JSON response.
  3. Display stock information dynamically in the stockInfo div.
  4. Handle errors when fetching stock data or entering an invalid symbol.

Conclusion

We have successfully built a stock market tracker that fetches real-time data. You can expand this project by:

By following this tutorial, you now have a solid foundation for working with stock market APIs using JavaScript. Happy coding!


Back to Articles