我正在尝试使用Convert data to OHLC (Open, High, Low, Close) in JavaScript?中的脚本将某些图表数据转换为OHLC。唯一的问题是我的数据与原始数据略有不同(http://api.bitcoincharts.com/v1/csv/localbtcDKK.csv.gz - 显示丹麦曾进行的所有比特币交易),那么我将如何修改代码呢?
原始数据
p=0.5
my_data = pd.Series(np.random.binomial(1, p, input_length))
新数据
var data = [{"tid": 283945, "date": 1384934366, "amount": "0.08180000", "price": "501.30"}, {"tid": 283947, "date": 1384934066, "amount": "0.06110000", "price": "490.66"}, ...];
由于它是CSV,因此我将jquery-csv用于将数据转换为数组。这是我当前的代码(https://jsfiddle.net/askhflajsf/mg9v89r2/5/):
// CSV format: UNIX timestamp, price, amount traded
// http://api.bitcoincharts.com/v1/csv/localbtcDKK.csv.gz
var data = `1366383202,748.680000000000,1.000000000000
1366471506,777.440000000000,2.700000000000
1368121200,685.740000000000,2.187400000000
...`
答案 0 :(得分:1)
您必须做的最重要的事情是向该数据添加标题。像这样:
var data = `date,price,amount
1366383202,748.680000000000,1.000000000000
1366471506,777.440000000000,2.700000000000
//etc...
没有标题,这些属性都不起作用。
另外,你不需要jQuery。你可以简单地使用D3:
var parsedArray = d3.csvParse(data)
如果出于某种原因,您无法更改数据以添加标题,则可以在代码中添加:
var headers = ["date", "price", "amount"];
var parsedArray = d3.csvParse(headers + "\n" + data)
以下是包含这些更改的演示:
var csv = `date,price,amount
1366383202,748.680000000000,1.000000000000
1366471506,777.440000000000,2.700000000000
1368121200,685.740000000000,2.187400000000
1375783458,619.500000000000,1.000000000000`;
var originalData = d3.csvParse(csv)
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
}
console.log(convertToOHLC(originalData))

<script src="//d3js.org/d3.v4.min.js"></script>
&#13;