Use of Fetch API - weekly oil price
In this tutorial, I am going to use the data of oil price since 1987 from Fred Economic Research via a .csv and then, use Fetch API do extract data and display on a chart. The code is as follows:
Data Source: EIA
// HTML canvas element
<canvas id="myChart" width="600" height="450"></canvas>
<p style="text-align:right;color:grey;">Vivax Solutions</p>
// script for charting
<script>
const xlabels=[];
const yvalues=[];
const r=4;
drawChart();
async function drawChart(){
await GetData();
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels:xlabels,
datasets: [{
label: 'Weekly Oil Price Fluctuations during the Lockdown',
data:yvalues,
hoverBackgroundColor:'rgba(0,255,0,0.4)',
backgroundColor:'rgba(255, 99, 132, 0.2)',
borderColor:'rgba(255, 99, 132, 1)',
borderWidth: 2,
fill:true,
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
};
// Getting data from the .csv
async function GetData(){
const res = await fetch('oil-price.csv');
const data = await res.text();
//Checking that data has loaded properly
console.log(data);
// removing the line breaks and breaking into blocks
const table=data.split('\n').slice(200);
console.log(table.length);
table.forEach(row => {
// removing commas
const columns =row.split(',');
// getting data into two columns
const date=columns[0];
xlabels.push(date);
const price=Math.floor(columns[1]*1000)/1000;
yvalues.push(price)
// checking new format of data
console.log(date , price);
});
}
</script>
In this project, the data in the form of oil price and the week are taken from the given source in a .csv file, using the Fetch() function. It comes as a promise. The promise is then turned into a human-readable format, text, using slice() and split() functions.
From text data, oil price and the week are extracted with the aid of two JavaScript functions, as mentioned above.
In addition, Chart.js is used to plot the data on a canvas.
U.S. Energy Information Administration, Crude Oil Prices: West Texas Intermediate (WTI) - Cushing, Oklahoma [WCOILWTICO], retrieved from FRED, Federal Reserve Bank of St. Louis; https://fred.stlouisfed.org/series/WCOILWTICO, May 9, 2020.