create stock chart real time input is stock code company code
- User
create stock chart real time input is stock code company code
Assistant
create stock chart real time input is stock code company code
Here's a solution to create a real-time stock chart based on user input of a company stock code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Real-Time Stock Chart</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<style>
body {
font-family: Arial, sans-serif;
max-width: 1000px;
margin: 0 auto;
padding: 20px;
}
.input-container {
margin-bottom: 20px;
}
input {
padding: 8px;
width: 200px;
}
button {
padding: 8px 16px;
background-color: #4CAF50;
color: white;
border: none;
cursor: pointer;
}
.chart-container {
position: relative;
height: 500px;
width: 100%;
}
</style>
</head>
<body>
<h1>Real-Time Stock Chart</h1>
<div class="input-container">
<label for="stockCode">Enter Stock Code (e.g., AAPL, MSFT, TSLA):</label>
<input type="text" id="stockCode" placeholder="e.g., AAPL">
<button onclick="fetchStockData()">Get Chart</button>
</div>
<div class="chart-container">
<canvas id="stockChart"></canvas>
</div>
<script>
let stockChart = null;
let updateInterval = null;
// Initialize chart with empty data
function initChart() {
const ctx = document.getElementById('stockChart').getContext('2d');
stockChart = new Chart(ctx, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'Stock Price',
data: [],
borderColor: 'rgb(75, 192, 192)',
tension: 0.1,
fill: false
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: false
}
}
}
});
}
// Fetch stock data from API
async function fetchStockData() {
const stockCode = document.getElementById('stockCode').value.trim();
if (!stockCode) {
alert('Please enter a stock code');
return;
}
try {
// First clear any existing interval
if (updateInterval) {
clearInterval(updateInterval);
}
// Initial fetch
await updateChartData(stockCode);
// Set up periodic updates (every 5 seconds)
updateInterval = setInterval(async () => {
await updateChartData(stockCode);
}, 5000);
} catch (error) {
console.error('Error fetching stock data:', error);
alert('Error fetching data. Please check the stock code and try again.');
}
}
// Update chart with new data
async function updateChartData(stockCode) {
try {
// Using Alpha Vantage API (you'll need your own API key)
const response = await axios.get(
`https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${stockCode}&interval=5min&apikey=demo`
);
const timeSeries = response.data['Time Series (5min)'];
if (!timeSeries) {
throw new Error('Invalid stock code or API limit reached');
}
const timestamps = Object.keys(timeSeries).reverse();
const prices = timestamps.map(ts => parseFloat(timeSeries[ts]['1. open']));
// Update chart
stockChart.data.labels = timestamps;
stockChart.data.datasets[0].data = prices;
stockChart.data.datasets[0].label = `${stockCode} Stock Price`;
stockChart.update();
} catch (error) {
console.error('Error updating chart:', error);
throw error;
}
}
// Initialize chart when page loads
window.onload = initChart;
</script>
</body>
</html>
API Key: The example uses Alpha Vantage's demo API key which has limited requests. For production use:
demo with your actual API keyAlternative APIs: You can also use:
Rate Limits: Most free APIs have rate limits. For higher frequency updates, consider:
Error Handling: The code includes basic error handling but you may want to expand it for production use.
Customization: You can easily modify the chart appearance by changing the Chart.js configuration options.
To use this, simply save the code as an HTML file and open it in a browser. Enter a stock symbol (like AAPL for Apple) and click "Get Chart" to see real-time updates.