document.getElementById('stockForm').addEventListener('submit', function(event) {
event.preventDefault();
const stockSymbol = document.getElementById('stockSymbol').value.toUpperCase().trim();
const url = `https://query1.finance.yahoo.com/v8/finance/chart/${stockSymbol}?interval=1d&range=1y`;
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`Failed to fetch data for ${stockSymbol}.`);
}
return response.json();
})
.then(data => {
console.log('Data fetched successfully:', data);
if (!data.chart || !data.chart.result || !data.chart.result[0] || !data.chart.result[0].timestamp || !data.chart.result[0].indicators || !data.chart.result[0].indicators.quote || !data.chart.result[0].indicators.quote[0].close) {
throw new Error(`Data format error for ${stockSymbol}.`);
}
const dates = data.chart.result[0].timestamp.map(ts => new Date(ts * 1000));
const prices = data.chart.result[0].indicators.quote[0].close;
// Calculate EMAs
const ema20 = calculateEMA(prices, 20);
const ema50 = calculateEMA(prices, 50);
// Plotting with Chart.js
const ctx = document.getElementById('myChart').getContext('2d');
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dates,
datasets: [
{
label: 'Closing Price',
data: prices,
borderColor: 'blue',
backgroundColor: 'rgba(0, 0, 255, 0.1)',
borderWidth: 1,
fill: false
},
{
label: '20-day EMA',
data: ema20,
borderColor: 'green',
backgroundColor: 'rgba(0, 255, 0, 0.1)',
borderWidth: 1,
fill: false
},
{
label: '50-day EMA',
data: ema50,
borderColor: 'purple',
backgroundColor: 'rgba(128, 0, 128, 0.1)',
borderWidth: 1,
fill: false
}
]
},
options: {
responsive: true,
scales: {
x: {
type: 'time',
time: {
unit: 'month'
}
},
y: {
title: {
display: true,
text: 'Price'
}
}
}
}
});
})
.catch(error => {
console.error('Error fetching data:', error);
alert(`Failed to fetch data for ${stockSymbol}. Please check the stock symbol and try again.`);
});
});
function calculateEMA(prices, period) {
const alpha = 2 / (period + 1);
const ema = [prices[0]];
for (let i = 1; i < prices.length; i++) {
ema[i] = alpha * prices[i] + (1 - alpha) * ema[i - 1];
}
return ema;
}