繪製股價走勢圖
from book 9–13
(1)讀取外部檔案,用openFile將文字檔傳入程式中
(2)strtary將openFile傳回來的文字轉為陣列
(3)將陣列傳入drawplot繪製k線圖
<!DOCTYPE html>
<html>
<head>
<meta charset=”UTF-8">
<script src=”https://cdn.plot.ly/plotly-latest.min.js"></script>
<script type=”text/javascript” src=”E_9_4.js”></script>
</head>
<body>
<input type=’file’ accept=’text/plain’ onchange=’openFile(event)’><br> #
<div id=’output’>
…
</div>
</body>
</html>
window.addEventListener(“load”, function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
//alert(“Great success! All the File APIs are supported.”);
openFile();#
} else {
alert(‘The File APIs are not fully supported in this browser.’);
}
})
function openFile(event) {#
var input = event.target;#
var reader = new FileReader();#
var numary;
reader.onload = function(){#
var text = [];
var node = document.getElementById(‘output’);#
text = reader.result;#
numary = strtary(text);#call
drawplot(numary);#call
}
reader.readAsText(input.files[0]);#
}
function strtary(rawdata) {
var sizeary = rawdata.length;#
console.log(“size = “ + sizeary);
var strbyline = rawdata.split(‘\n’);#
var row = strbyline.length-1;#
var col = 90;#
num = new Array(row);#
for (i = 0; i < row; i++) {
if (i == 0) {#處理日期
strbyline[i]=strbyline[i].replace(/\//g,”-”);#reg
num[i] = new Array(col);#
num[i] = strbyline[i].split(“\t”);#
} else {#處理資料
num[i] = new Array(col);
num[i] = strbyline[i].split(“\t”);
}
console.log(“num = “ + num[i]);
}
return num;
}
function drawplot(numary) {
var trace1 = {
x: numary[0],
open: numary[1],
high: numary[2],
low: numary[3],
close: numary[4],
decreasing: {line: {color: ‘#7F7F7F’}},
increasing: {line: {color: ‘#17BECF’}},
line: {color: ‘rgba(31,119,180,1)’},
type: ‘candlestick’,
xaxis: ‘x’,
yaxis: ‘y’
};
var data = [trace1];
var layout = {
dragmode: ‘zoom’,
margin: {
r: 10,
t: 25,
b: 40,
l: 60
},
showlegend: false,
xaxis: {
autorange: true,
domain: [0, 1],
range: [‘2017–01–02’, ‘2017–05–05’],
rangeslider: {range: [‘2017–01–02’, ‘2017–05–05’]},
title: ‘Date’,
type: ‘date’
},
yaxis: {
autorange: true,
domain: [0, 1],
range: [150, 200],
type: ‘linear’
},
height: “auto”,
width: “auto”
};
Plotly.plot(‘output’, data, layout);
}
因为 ‘/’ 符号 和上面的规则冲突了
所以需要用 ‘\’ 转义