与create an OHLC data from Date, time, price using C#类似,如何将基本贸易数据转换为OHLC(或开放,高,低,关闭)并将其应用于这种独特的案例?
var data = [{
"tid": 283945,
"date": 1384934366,
"amount": "0.08180000",
"price": "501.30"
}, {
"tid": 283947,
"date": 1384934066,
"amount": "0.06110000",
"price": "490.66"
},
...
];
function convertToOHLC(data) {
// What goes here?
}
convertToOHLC(data);
答案 0 :(得分:5)
这是一个将数据转换为OHLC的工作函数:
function convertToOHLC(data) {
data.sort((a, b) => d3.ascending(a.date, b.date));
var result = [];
var format = d3.timeFormat("%Y-%m-%d");
data.forEach(d => d.date = format(new Date(d.date * 1000)));
var allDates = [...new Set(data.map(d => d.date))];
allDates.forEach(d => {
var tempObject = {};
var filteredData = data.filter(e => e.date === d);
tempObject.date = d;
tempObject.open = filteredData[0].price;
tempObject.close = filteredData[filteredData.length - 1].price;
tempObject.high = d3.max(filteredData, e => e.price);
tempObject.low = d3.min(filteredData, e => e.price);
result.push(tempObject);
});
return result;
};
这是您更新的小提琴:https://jsfiddle.net/mg9v89r2/
首先,我们按日期对原始数据数组进行排序:
data.sort((a, b) => d3.ascending(a.date, b.date));
这是我们稍后处理open
和close
时的重要一步。
之后,我们将毫秒转换为日期,作为字符串:
var format = d3.timeFormat("%Y-%m-%d");
data.forEach(d => d.date = format(new Date(d.date * 1000)));
这样做,我们可以过滤属于给定日期的所有对象。首先,我们创建一个包含数据中所有不同日期的数组:
var allDates = [...new Set(data.map(d => d.date))];
对于该数组的每一天,我们将调用一个函数来填充一个名为results
的空数组:
allDates.forEach(d => {
var tempObject = {};
var filteredData = data.filter(e => e.date === d);
tempObject.date = d;
tempObject.open = filteredData[0].price;
tempObject.close = filteredData[filteredData.length - 1].price;
tempObject.high = d3.max(filteredData, e => e.price);
tempObject.low = d3.min(filteredData, e => e.price);
result.push(tempObject);
});
在上面的forEach
中,我们创建了一个空对象,并且对于allDates
数组中的每一天,我们都会过滤数据:
var filteredData = data.filter(e => e.date === d);
用它填充一个临时对象:
var tempObject = {};
tempObject.date = d;
tempObject.open = filteredData[0].price;
tempObject.close = filteredData[filteredData.length - 1].price;
tempObject.high = d3.max(filteredData, e => e.price);
tempObject.low = d3.min(filteredData, e => e.price);
每次迭代后,我们将该临时对象推送到results
:
result.push(tempObject);
最后,我们返回results
。
令人惊讶的是,您的小提琴中的巨大数据阵列只有2天的数据。