-
Notifications
You must be signed in to change notification settings - Fork 0
/
closingPriceAPI.js
104 lines (93 loc) · 2.82 KB
/
closingPriceAPI.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
98
99
100
101
102
103
104
import { chartDataStyling } from "../Utils/chart-settings";
const backendOrigin = process.env.REACT_APP_BACKEND;
export const callAPIGateway = async (stockSymbols, existingSymbolsWithDataset) => {
const stocksInfo = [];
const stocksSymbolsRequestQueue = [];
for (var i = 0; i < stockSymbols.length; i++) {
const isNewSymbol = existingSymbolsWithDataset.indexOf(stockSymbols[i]) === -1;
if (isNewSymbol) {
const response = await fetch(`${backendOrigin}/wrapper?symbol=${stockSymbols[i]}`, {
mode: 'cors',
headers: {
'Access-Control-Allow-Origin': backendOrigin
},
});
// eslint-disable-next-line
const { message, result } = await response.json();
// console.log(message);
// console.log(result);
stocksSymbolsRequestQueue.push(stockSymbols[i]);
stocksInfo.push(result);
}
}
return {
stocksInfo: stocksInfo,
stocksSymbolsRequestQueue: stocksSymbolsRequestQueue
};
};
const getDailyClosingPrice = json => {
const dates = [];
const closingPrices = [];
Object.entries(json["Time Series (Daily)"]).forEach(
(dailyData, index, json) => {
dates.push(dailyData[0]);
closingPrices.push(dailyData[1]["4. close"]);
return {
date: dailyData[0],
closingPrice: dailyData[1]["4. close"]
};
}
);
return {
label: json["Meta Data"]["2. Symbol"],
dates: dates.reverse(),
closingPrices: closingPrices.reverse()
};
};
const processErrorResponse = (symbols, index, response, errorArray) => {
const invalidStockSymbol = symbols[index];
console.log(`symbol: ${invalidStockSymbol} information: ${response}`);
errorArray.push(invalidStockSymbol);
};
export const formatStockData = (
rawJSONDataArray,
symbols,
totalExistingDataSets
) => {
const chartDataWrapper = {
labels: [],
datasets: [],
errors: []
};
rawJSONDataArray.forEach((rawJSONData, index) => {
if (rawJSONData["Error Message"] !== undefined) {
processErrorResponse(
symbols,
index,
JSON.stringify(rawJSONData),
chartDataWrapper.errors
);
return;
}
try {
const converted = getDailyClosingPrice(rawJSONData);
const indexInChart =
index - chartDataWrapper.errors.length + totalExistingDataSets;
const returnObject = {
...chartDataStyling[indexInChart]
};
if (chartDataWrapper.labels.length === 0) {
chartDataWrapper.labels = converted.dates;
}
// converted: label (stock symbol) & closing price
returnObject.label = converted.label;
returnObject.data = converted.closingPrices;
chartDataWrapper.datasets.push(returnObject);
} catch (error) {
processErrorResponse(symbols, index, error, chartDataWrapper.errors);
}
});
return {
...chartDataWrapper
};
};