Skip to content

Instantly share code, notes, and snippets.

@bananaumai
Last active December 23, 2016 13:41
Show Gist options
  • Save bananaumai/c1b04fe32d3248947c7a1a45f9280b5b to your computer and use it in GitHub Desktop.
Save bananaumai/c1b04fe32d3248947c7a1a45f9280b5b to your computer and use it in GitHub Desktop.
Googleスプレッドシートで連続データをローソク足チャート描画用のデータに変換するGoogle Apps Script
function seq2candlestick(range, nDiv, noHeader) {
const vals = range.filter(function(val) { return val != "" }).map(function(val) { return Number(val) })
const res = _splitseq(vals, Number(nDiv)).map(function(ns) {
const min = Math.min.apply(null, ns)
const q1 = _q1(ns)
const q3 = _q3(ns)
const max = Math.max.apply(null, ns)
return [min, q1, q3, max]
})
if (noHeader) {
return res
}
return [['min', 'q1', 'q2', 'max']].concat(res)
}
function _splitseq(data, nDiv) {
const nSplit = Math.ceil(data.length / nDiv)
const res = []
for (i = 0; i < nSplit; i++) {
res.push(data.splice(0, nDiv))
}
return res
}
function _q1(ns) {
return _quartile(ns, 1)
}
function _q3(ns) {
return _quartile(ns, 3)
}
function _quartile(ns, pos) {
const len = ns.length
var m = 0
switch (pos) {
case 1:
m = (len + 3) / 4
break
case 3:
m = (3 * len + 1) / 4
break
default:
throw new Exception("")
}
ns = ns.slice().sort(function(a, b) { return a - b })
if (m == Math.floor(m)) {
return ns[m-1]
}
const l = Math.floor(m)
const h = Math.ceil(m)
return (h - m) * ns[l-1] + (m - l) * ns[h-1]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment