-
Notifications
You must be signed in to change notification settings - Fork 3
/
plots.js
80 lines (66 loc) · 1.78 KB
/
plots.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* Helper function to select stock data
* Returns an array of values
* @param {array} rows
* @param {integer} index
* index 0 - Date
* index 1 - Open
* index 2 - High
* index 3 - Low
* index 4 - Volume
*/
function unpack(rows, index) {
return rows.map(function(row) {
return row[index];
});
}
// Submit Button handler
function handleSubmit() {
// Prevent the page from refreshing
d3.event.preventDefault();
// Select the input value from the form
var stock = d3.select("#stockInput").node().value;
console.log(stock);
// clear the input value
d3.select("#stockInput").node().value = "";
// Build the plot with the new stock
buildPlot(stock);
}
function buildPlot(stock) {
var apiKey = "V2vzspYSYL8eenGuq8uF";
var url = `https://www.quandl.com/api/v3/datasets/WIKI/${stock}.json?start_date=2016-10-01&end_date=2017-10-01&api_key=${apiKey}`;
d3.json(url).then(function(data) {
// Grab values from the response json object to build the plots
var name = data.dataset.name;
var stock = data.dataset.dataset_code;
var startDate = data.dataset.start_date;
var endDate = data.dataset.end_date;
var dates = unpack(data.dataset.data, 0);
var closingPrices = unpack(data.dataset.data, 1);
var trace1 = {
type: "scatter",
mode: "lines",
name: name,
x: dates,
y: closingPrices,
line: {
color: "#17BECF"
}
};
var data = [trace1];
var layout = {
title: `${stock} closing prices`,
xaxis: {
range: [startDate, endDate],
type: "date"
},
yaxis: {
autorange: true,
type: "linear"
}
};
Plotly.newPlot("plot", data, layout);
});
}
// Add event listener for submit button
d3.select("#submit").on("click", handleSubmit);