Learn how to build a real-time stock price tracker using HTML, CSS, and JavaScript with Alpha Vantage API. Follow this easy step-by-step guide to create your own stock tracking app.
Table of Contents
Building a Real-Time Stock Price Tracker is an exciting way to enhance your web development skills while learning how to integrate live data into your website. In this blog, we will show you how to create a simple yet powerful stock price tracker using HTML, CSS, and JavaScript. By using the Alpha Vantage API, you can fetch real-time stock prices and display them on your website.
Prerequisites
Before we get started, ensure you have the following:
- Basic understanding of HTML, CSS, and JavaScript.
- A code editor like Visual Studio Code or Sublime Text.
- A web browser to test your project.
- An Alpha Vantage API key (You can get a free API key by signing up at Alpha Vantage).
Let’s dive into the steps!
Source Code
Step 1 (HTML Code):
First, create the basic structure of your webpage. In this step, we will add the HTML elements needed for the stock price tracker, such as an input field for entering the stock symbol and a button to fetch data. Here's a detailed explanation of each part:
1. Document Type Declaration
<!DOCTYPE html>
- Declares the document as an HTML5 document.
2. <html>
Tag
<html lang="en">
- Defines the root element of the HTML document.
- The
lang="en"
attribute specifies the language as English for accessibility and SEO.
3. <head>
Section
Contains metadata and resources for the document.
a. Charset Declaration
<meta charset="UTF-8">
- Specifies the character encoding as UTF-8, supporting most characters and symbols.
b. Viewport Meta Tag
<meta name="viewport" content="width=device-width, initial-scale=1.0">
- Ensures the page is responsive on all devices, adjusting layout based on screen size.
c. Title
<title>Stock Price Tracker</title>
- Sets the title displayed in the browser tab.
d. Google Fonts
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap">
- Loads the Poppins font from Google Fonts for styling text.
e. External Stylesheet
<link rel="stylesheet" href="styles.css">
- Links an external CSS file (
styles.css
) to style the page.
4. <body>
Section
Contains the visible content and structure of the application.
a. App Container
<div class="app-container">
- A wrapper element for the entire app, styled using the
app-container
class.
5. Header Section
<header class="header">
<h1>📊 Stock Price Tracker</h1>
<div class="input-container">
<input type="text" id="stock-input" placeholder="Enter Stock Symbol (e.g., TSLA)">
<button id="search-btn">Search</button>
</div>
</header>
- Header:
- Displays the app title with an emoji 📊.
- Includes an input field (
<input>
) for entering the stock symbol. - A button (
<button>
) with the IDsearch-btn
triggers the stock search.
6. Main Content
<main class="main-content">
<div class="stock-card">
<h2 id="stock-name">Stock Name</h2>
<p id="stock-price">Price: $0.00</p>
<p id="stock-change">Change: 0.00%</p>
</div>
<div class="chart-container">
<canvas id="stock-chart"></canvas>
</div>
</main>
- Stock Card:
- Displays the stock name (
<h2>
), current price (<p>
), and percentage change (<p>
). - IDs (
stock-name
,stock-price
,stock-change
) are used to dynamically update values with JavaScript.
- Displays the stock name (
- Chart Container:
- Contains a
<canvas>
element with the IDstock-chart
for rendering the stock price chart using the Chart.js library.
- Contains a
7. Footer
<footer class="footer">
<p>Powered by Alpha Vantage</p>
</footer>
- Displays a footer with a credit line to Alpha Vantage, the data provider.
8. Scripts
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="script.js"></script>
- Chart.js: A library for creating charts.
- script.js: The custom JavaScript file that handles stock data fetching, UI updates, and chart rendering.
9. Styling and Color Scheme
- The layout and design are defined in the
styles.css
file. - The code uses a modern UI with clean fonts (Poppins) and a color scheme that can be customized further.
Step 2 (CSS Code):
Next, we will style the stock tracker app using CSS. The design will be clean and modern, with a focus on user experience. Here's a breakdown of each section:
1. General Body Styling
body {
margin: 0;
font-family: 'Poppins', sans-serif;
background-color: #f0f4f8;
color: #333;
}
margin: 0;
: Removes default margin around the body.font-family: 'Poppins', sans-serif;
: Sets the font to Poppins (with sans-serif as a fallback).background-color: #f0f4f8;
: Applies a light grayish-blue background color for a clean look.color: #333;
: Sets the default text color to dark gray for readability.
2. App Container
.app-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
max-width: 800px;
: Restricts the app width to 800px for better readability.margin: 0 auto;
: Centers the container horizontally.padding: 20px;
: Adds spacing inside the container.
3. Header Section
.header {
text-align: center;
margin-bottom: 20px;
}
.header h1 {
color: #825CFF;
font-size: 2rem;
margin-bottom: 10px;
}
- Header Container:
text-align: center;
: Centers the header content.margin-bottom: 20px;
: Adds spacing below the header.
- Header Title:
color: #825CFF;
: Sets the title color to a vibrant purple.font-size: 2rem;
: Makes the title large and prominent.margin-bottom: 10px;
: Adds spacing below the title.
4. Input Container
.input-container {
display: flex;
justify-content: center;
gap: 10px;
}
display: flex;
: Aligns the input and button in a horizontal row.justify-content: center;
: Centers the input and button horizontally.gap: 10px;
: Adds spacing between the input and button.
5. Input Field
input#stock-input {
font-family: 'Poppins', sans-serif;
padding: 10px;
width: 200px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 1rem;
}
- Font and Size:
font-family: 'Poppins', sans-serif;
: Matches the app's font style.font-size: 1rem;
: Sets a readable font size.
- Styling:
padding: 10px;
: Adds internal spacing for better usability.width: 200px;
: Fixes the input width.border: 1px solid #ccc;
: Adds a light gray border.border-radius: 5px;
: Rounds the corners.
6. Search Button
button#search-btn {
font-family: 'Poppins', sans-serif;
padding: 10px 15px;
background-color: #825CFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
}
button#search-btn:hover {
background-color: #6b4ae8;
}
- Default Styling:
background-color: #825CFF;
: Sets a vibrant purple background.color: white;
: Ensures text is readable.border: none;
: Removes the default border.border-radius: 5px;
: Rounds the corners.cursor: pointer;
: Changes the cursor to a pointer on hover.
- Hover Effect:
background-color: #6b4ae8;
: Darkens the button color on hover for interactivity.
7. Main Content
.main-content {
display: flex;
flex-direction: column;
align-items: center;
}
display: flex;
: Defines a flexible layout.flex-direction: column;
: Stacks child elements vertically.align-items: center;
: Centers the content horizontally.
8. Stock Card
.stock-card {
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
margin-bottom: 20px;
width: 100%;
}
.stock-card h2 {
color: #825CFF;
font-size: 1.5rem;
margin-bottom: 10px;
}
- Card Styling:
background-color: white;
: Sets a clean white background.padding: 20px;
: Adds internal spacing.border-radius: 10px;
: Rounds the corners.box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
: Adds a subtle shadow for depth.
- Stock Name:
color: #825CFF;
: Uses a purple color for emphasis.font-size: 1.5rem;
: Makes the text larger and noticeable.
9. Chart Container
.chart-container {
width: 100%;
max-width: 700px;
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
width: 100%; max-width: 700px;
: Ensures the chart fits within a maximum width.background-color: white;
: Keeps a clean background.padding: 20px;
: Adds spacing around the chart.border-radius: 10px;
: Rounds the corners.box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
: Adds depth with a subtle shadow.
10. Footer
.footer {
text-align: center;
margin-top: 20px;
font-size: 0.9rem;
color: #555;
}
text-align: center;
: Centers the text.margin-top: 20px;
: Adds spacing above the footer.font-size: 0.9rem;
: Makes the text slightly smaller.color: #555;
: Uses a medium gray for subtlety.
body {
margin: 0;
font-family: 'Poppins', sans-serif;
background-color: #f0f4f8;
color: #333;
}
.app-container {
max-width: 800px;
margin: 0 auto;
padding: 20px;
}
.header {
text-align: center;
margin-bottom: 20px;
}
.header h1 {
color: #825CFF;
font-size: 2rem;
margin-bottom: 10px;
}
.input-container {
display: flex;
justify-content: center;
gap: 10px;
}
input#stock-input {
font-family: 'Poppins', sans-serif;
padding: 10px;
width: 200px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 1rem;
}
button#search-btn {
font-family: 'Poppins', sans-serif;
padding: 10px 15px;
background-color: #825CFF;
color: white;
border: none;
border-radius: 5px;
cursor: pointer;
font-size: 1rem;
}
button#search-btn:hover {
background-color: #6b4ae8;
}
.main-content {
display: flex;
flex-direction: column;
align-items: center;
}
.stock-card {
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
text-align: center;
margin-bottom: 20px;
width: 100%;
}
.stock-card h2 {
color: #825CFF;
font-size: 1.5rem;
margin-bottom: 10px;
}
.chart-container {
width: 100%;
max-width: 700px;
background-color: white;
padding: 20px;
border-radius: 10px;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}
.footer {
text-align: center;
margin-top: 20px;
font-size: 0.9rem;
color: #555;
}
Step 3 (JavaScript Code):
Now, we will write the JavaScript code to fetch stock data using the Alpha Vantage API. We will use fetch() to get the stock data and display it on the webpage. Here's a breakdown of the code:
Variables:
- stockInput: References the input field where the user enters the stock symbol.
- searchBtn: References the button that the user clicks to search for a stock.
- stockName: A DOM element where the stock's name (symbol) will be displayed.
- stockPrice: A DOM element where the current stock price will be displayed.
- stockChange: A DOM element where the percentage change in stock price will be displayed.
- stockChart: The canvas element for drawing the chart (using the Chart.js library).
- chart: A variable used to store the current chart object (for updating or destroying it).
Constants:
- API_KEY: Stores the API key for fetching stock data from the Alpha Vantage API. It’s set to
'demo'
in this example.
fetchStockData(symbol)
:
This asynchronous function fetches stock data from the Alpha Vantage API. It:
- Builds a URL using the stock symbol (
symbol
). - Sends a fetch request to the API.
- If successful, it checks if the stock data is available (
data['Time Series (Daily)']
). - If the stock data is found, it calls
updateUI(symbol, data['Time Series (Daily)'])
to update the webpage with stock information. - If not found or there is an error, it displays an alert indicating failure.
updateUI(symbol, timeSeries)
:
This function updates the webpage with the stock's data:
- Dates: It extracts the last 15 days of stock data from the
timeSeries
object. - Prices: It collects the closing prices for those 15 days.
- Change Calculation: It calculates the percentage change between the latest and previous day’s closing prices.
- It then updates the stock name, price, and change in the DOM, and calls
updateChart(dates, prices)
to update the chart.
updateChart(dates, prices)
:
This function updates the chart displayed on the webpage:
- Chart Update: If a chart already exists (
chart
), it is destroyed usingchart.destroy()
to prevent multiple charts from stacking. - Chart Creation: It creates a new
Chart.js
line chart with:- The dates as labels on the x-axis.
- The closing prices as data on the y-axis.
- Custom styling for the line, points, and hover effects.
- Chart Options: Includes settings like:
- Responsive: Ensures the chart resizes properly.
- Animation: Defines how the chart will animate (duration and easing).
- Tooltip: Customizes the appearance of tooltips.
- Scales: Customizes grid lines and tick marks for the axes.
Event Listener:
- searchBtn.addEventListener('click', ...): Adds a click event listener to the search button. When clicked, it:
- Retrieves the stock symbol from the input field (
stockInput.value
). - If a symbol is entered, it calls
fetchStockData(symbol)
to fetch the stock data. - If no symbol is entered, it shows an alert asking the user to enter a stock symbol.
- Retrieves the stock symbol from the input field (
const stockInput = document.getElementById('stock-input');
const searchBtn = document.getElementById('search-btn');
const stockName = document.getElementById('stock-name');
const stockPrice = document.getElementById('stock-price');
const stockChange = document.getElementById('stock-change');
const stockChart = document.getElementById('stock-chart').getContext('2d');
let chart;
const API_KEY = 'demo';
async function fetchStockData(symbol) {
try {
const url = `https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=${symbol}&apikey=${API_KEY}`;
const response = await fetch(url);
const data = await response.json();
if (data['Time Series (Daily)']) {
updateUI(symbol, data['Time Series (Daily)']);
} else {
alert('Stock not found! Please check the symbol and try again.');
}
} catch (error) {
console.error('Error fetching stock data:', error);
alert('Failed to fetch stock data. Please try again later.');
}
}
function updateUI(symbol, timeSeries) {
const dates = Object.keys(timeSeries).slice(0, 15); // Last 15 days
const prices = dates.map(date => parseFloat(timeSeries[date]['4. close']));
const latestPrice = prices[0];
const previousPrice = prices[1];
const changePercent = (((latestPrice - previousPrice) / previousPrice) * 100).toFixed(2);
stockName.textContent = symbol.toUpperCase();
stockPrice.textContent = `Price: $${latestPrice.toFixed(2)}`;
stockChange.textContent = `Change: ${changePercent}%`;
updateChart(dates.reverse(), prices.reverse());
}
function updateChart(dates, prices) {
if (chart) {
chart.destroy();
}
chart = new Chart(stockChart, {
type: 'line',
data: {
labels: dates,
datasets: [
{
label: 'Stock Price (USD)',
data: prices,
backgroundColor: 'rgba(130, 92, 255, 0.2)',
borderColor: '#825CFF',
borderWidth: 3,
tension: 0.4,
pointRadius: 5,
pointBackgroundColor: '#ffffff',
pointBorderColor: '#825CFF',
pointHoverRadius: 8,
pointHoverBackgroundColor: '#6b4ae8',
},
],
},
options: {
responsive: true,
animation: {
duration: 2000,
easing: 'easeInOutCubic',
},
plugins: {
legend: {
display: true,
position: 'top',
labels: {
color: '#333',
font: {
size: 14,
},
},
},
tooltip: {
enabled: true,
backgroundColor: '#825CFF',
titleColor: '#fff',
bodyColor: '#fff',
cornerRadius: 5,
},
},
scales: {
x: {
grid: {
display: false,
},
ticks: {
color: '#333',
},
},
y: {
grid: {
color: 'rgba(130, 92, 255, 0.1)',
},
ticks: {
color: '#333',
},
},
},
},
});
}
searchBtn.addEventListener('click', () => {
const symbol = stockInput.value.trim();
if (symbol) {
fetchStockData(symbol);
} else {
alert('Please enter a stock symbol!');
}
});
Final Output:
Conclusion:
In this tutorial, we learned how to create a Real-Time Stock Price Tracker using HTML, CSS, and JavaScript. By integrating the Alpha Vantage API, we fetched live stock data and displayed it in a user-friendly format. This project is perfect for beginners looking to practice their web development skills and learn how to work with APIs.
You can further enhance this project by adding more features like tracking multiple stocks, displaying historical data, or adding real-time price updates.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊