generated from alexk111/store-of-something
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
data-collector-stocks.js
97 lines (82 loc) · 2.66 KB
/
data-collector-stocks.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
const csv = require("csv-parser");
const fse = require("fs-extra");
const path = require("path");
const yahooFinance = require('yahoo-finance2').default;
const pathSrc = path.join(".", "src");
const pathData = path.join(pathSrc, "data");
const pathCollected = path.join(pathData, "_collected");
const pathCollectedStocks = path.join(pathCollected, "stocks");
const stocksInfo = {};
async function loadStocksInfoFromCSV() {
return new Promise((resolve, reject) => {
fse
.createReadStream(path.join(pathData, "stocks.csv"))
.pipe(csv({}))
.on("data", (data) => {
const {symbol,name,filename} = data;
stocksInfo[symbol] = { name, filename };
})
.on("end", () => {
resolve();
})
.on("error", (err) => {
reject(err);
});
});
}
async function loadStockHistoryFromRemoteAPI(symbol, from, to, period) {
return await yahooFinance.historical(symbol, {
period1: from,
period2: to,
interval: period
})
}
function dateToYYYYMMDD(d) {
let month = '' + (d.getUTCMonth() + 1);
let date = '' + d.getUTCDate();
const year = d.getUTCFullYear();
if (month.length < 2) {
month = '0' + month;
}
if (date.length < 2) {
date = '0' + date;
}
return [year, month, date].join('-');
}
async function build() {
console.info("Collecting Stocks data...");
await loadStocksInfoFromCSV();
const stockSymbols = Object.keys(stocksInfo);
const dFrom = new Date(Date.UTC(2013,3,1,0,0,0,0));
const dNow = new Date();
const strYYYYMMDDFrom = dateToYYYYMMDD(dFrom);
const strYYYYMMDDNow = dateToYYYYMMDD(dNow);
for (const symbol of stockSymbols) {
console.log(symbol);
const symbolHistory = await loadStockHistoryFromRemoteAPI(symbol, strYYYYMMDDFrom, strYYYYMMDDNow, "1mo");
console.log(symbolHistory);
symbolHistory.sort((v1,v2) => ((new Date(v1.date)).getTime() > (new Date(v2.date)).getTime()) ? 1 : -1);
let lastClose;
let symbolData;
for (let itemIdx=0; itemIdx<symbolHistory.length; itemIdx++) {
const { open, close, date } = symbolHistory[itemIdx];
lastClose=close;
const d = new Date(date);
const strYYYYMMDD = dateToYYYYMMDD(d);
if (!symbolData) {
symbolData = [];
}
if (d.getUTCDate() === 1) {
symbolData.push([strYYYYMMDD, open]);
}
}
if (dNow.getUTCDate() > 1) {
symbolData.push([strYYYYMMDDNow, lastClose]);
}
const stockFilename = stocksInfo[symbol].filename;
const outFile = path.join(pathCollectedStocks, stockFilename + ".json");
await fse.writeFile(outFile, JSON.stringify(symbolData, null, 2));
console.info(`${symbol} saved as ${stockFilename}`);
}
}
build();