Live D3.JS Stock Chart

copied from: https://leanpub.com/D3-Tips-and-Tricks/read#leanpub-auto-starting-with-a-basic-graph

by Scott Vandervort

HTML

<body></body>

CSS

body {
    font: 12px Arial;
}
path {
    stroke: steelblue;
    stroke-width: 2;
    fill: none;
}
.axis path, .axis line {
    fill: none;
    stroke: grey;
    stroke-width: 1;
    shape-rendering: crispEdges;
}

JavaScript

/* 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...