作者:贰少爷闯天涯_964 | 来源:互联网 | 2023-02-12 19:08
类似于使用C#从日期,时间,价格创建OHLC数据,如何将基本贸易数据转换为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);
这是小提琴:https://jsfiddle.net/5dfjhnLw/
1> Gerardo Furt..:
这是将数据转换为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天的数据.