我试图保存我从使用这行代码await yahooStockAPI.getHistoricalPrices(startDate, endDate, symbol, '1d');
的API收集的股票数据,并将其保存为名为newData
的数组,但是,我一直得到一个空数组。如果我执行console.log(newData);
,我可以看到输出是这样的(对于我在代码中定义的每个符号)…
{
error: false,
currency: 'USD',
response: [
{
date: 1627047000,
open: 147.5500030517578,
high: 148.72000122070312,
low: 146.9199981689453,
close: 148.55999755859375,
volume: 71447400,
adjclose: 148.33775329589844
},
{
date: 1626960600,
open: 145.94000244140625,
high: 148.1999969482422,
low: 145.80999755859375,
close: 146.8000030517578,
volume: 77338200,
adjclose: 146.58038330078125
},...
…但是,保存在我设置的目录中的CSV文件是空的,并且我得到一个错误The input to objects-to-csv must be an array of objects
。我想把上面的输出作为对象数组newData
,然后使用NPM包将其转换为CSV文件。本质上,数组应该是这样的(与const symbol
:
const newData = [
{date: '...', open: open price for apple, high: highest price for amazon, low:..., etc},
{date: '...', open: open price for amazon, high: highest price for google, low:..., etc},
];
我不介意如果数组中的每个对象没有每个股票的报价,因为我有const symbol
,这是有序的
这是代码:
const yahooStockAPI = require('yahoo-stock-api');
const ObjectsToCsv = require('objects-to-csv');
const symbol = ['AAPL','AMZN','GOOGL']
symbol.forEach(main);
let newData = [];
async function main(symbol) {
const startDate = new Date('01/01/2018');
const endDate = new Date('08/01/2021');
newData = await yahooStockAPI.getHistoricalPrices(startDate, endDate, symbol, '1d');
//console.log(newData);
(async () => {
const csv = new ObjectsToCsv(newData);
await csv.toDisk('C:/Users/Rafael Oliveira/Desktop/teste/test2.csv');
})();
};
main();
提前谢谢你
ObjectsToCsv
包期望传递给它一个对象数组,但是从您共享的日志数据来看,newData
是一个对象。您正在寻找的确切数据可以通过newData.response
访问。所以下面的代码行应该可以工作:
const csv = new ObjectsToCsv(newData.response);