/* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise */
/* https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch */
/* https://leanpub.com/D3-Tips-and-Tricks/read#leanpub-auto-starting-with-a-basic-graph*/
/* https://www.alphavantage.co/documentation/#monthly */
const apikey='demo'; // Need to register your own key at : https://www.alphavantage.co/
const dateFormat="%Y-%m-%d";
// Fetches (GET) stock data for the specified symbol from www.alphavantage.co - a free RESTful API for stock info.
function getData (symbol) {
let url = 'https://www.alphavantage.co/query?function=TIME_SERIES_MONTHLY&symbol=' + symbol + '&apikey=' + apikey;
return new Promise((resolve, reject) => {
fetch( url, { mode: "cors"})
.then(function(response) {
return response.json();
})
.catch(error => reject(error))
.then(json => {
// The web service will throw a fit ( but not an exception ) if you try to use their demo key.
// Need to capture the "error".
if (typeof json.Information != 'undefined') {
reject(json.Information);
}
else {
let result = [];
// Need to reformat the data from the web service ( it uses strings w/ spaces for JSON keys amongst other things).
for (const [key, value] of Object.entries(json["Monthly Time Series"])) {
result.push({ "date" : key,
"close" : value["4. close"]});
}
resolve(result);
}
});
});
}
getData("msft")
.then(data => showChart(data))
.catch(error => alert(error));
/*
Displays a simple D3.js line chart given the specified data.
Data must be in the format :
[ { date: "1998-02-27", close: "84.7500" },
{ date: "1998-03-31", close: "89.5000" },
...
]
*/
function showChart( data ) {
// set the dimensions and margins of...
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.