-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtasks.js
212 lines (191 loc) · 6.02 KB
/
tasks.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
const request = require("request");
// const fetch = require('node-fetch');
const superagent = require("superagent");
const { parse_csv_to_json, normalize_data } = require("./utils");
const {
SYMBOLS,
OLD_SYMBOLS,
COMPANIES,
PNGX_DATA_URL,
PNGX_URL,
LOCAL_TIMEZONE,
LOCAL_TIMEZONE_FORMAT,
} = require("./constants");
const { Stock } = require("./models");
exports.fetch_data_from_pngx = function fetch_data_from_pngx(url) {
return "fetching data from: " + url;
};
/**
* Hello
*/
function make_async_request(url, options) {
Object.assign(options, {
method: "GET",
redirect: "follow",
// "headers": {
// 'Content-Type': 'text/csv'
// }
});
return new Promise(function (resolve, reject) {
fetch(url, options)
// .retry(2)
// .on('progress', event => {
// /* the event is:
// {
// direction: "upload" or "download"
// percent: 0 to 100 // may be missing if file size is unknown
// total: // total file size, may be missing
// loaded: // bytes downloaded or uploaded so far
// } */
// console.log(event)
// })
// .withCredentials()
// .redirects(2)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return response.text();
})
.then((csv) => {
return parse_csv_to_json(csv);
})
.then((json) => {
resolve(json);
})
.catch((error) => {
reject(error);
});
});
}
exports.make_async_request = make_async_request;
/**
* hello
*/
function get_quotes_from_pngx(code) {
var options = {};
return new Promise(function (resolve, reject) {
if (undefined !== typeof code) {
let url = PNGX_DATA_URL + code + ".csv";
make_async_request(url, options)
.then(function (response) {
// resolve(typeof callback == 'function' ? new callback(response) : response);
resolve(response);
})
.catch(function (error) {
reject(error);
});
} else {
for (var j = 0; j < SYMBOLS.length; j++) {
options["url"] = PNGX_DATA_URL + SYMBOLS[j] + ".csv";
make_async_request(options)
.then(function (response) {
// resolve(typeof callback == 'function' ? new callback(response) : response);
resolve(response);
})
.catch(function (error) {
reject(error);
});
}
}
});
}
exports.get_quotes_from_pngx = get_quotes_from_pngx;
/**
* Fetches Quotes from PNGX.com.pg
*/
async function data_fetcher() {
console.log(`Fetching csv data from ${PNGX_URL}\n`);
console.time("timer"); //start time with name = timer
const startTime = new Date();
let reqTimes = 0; // number of times the loop runs to fetch data
for (var i = 0; i < SYMBOLS.length; i++) {
reqTimes++;
let symbol = SYMBOLS[i];
console.log("Fetching quotes for " + symbol + " ...");
/**
* insert new data from pngx into the local database
* get csv data from pngx.com
* parse the csv to json
* for each quote compare its date against the date of the ones that exist in the database
* if the date compared does not match any existing quote then insert that quote into the database
* else continue to next quote until all quotes are compared then exit the program
*/
await get_quotes_from_pngx(symbol)
.then((quotes) => {
console.log("Fetched quotes for " + symbol);
let totalCount = quotes.length,
totalAdded = 0,
index = totalCount - 1,
recordExist = false;
// iterate through the dataset and add each data element to the db
do {
let quote = normalize_data(quotes[index]); // latest quote
console.log(`Querying db for existing quote for ${symbol} on ${quote.date.toLocaleDateString()} ...`);
// check if the quote for that particular company at that particular date already exists
Stock
.findOne({
date: quote.date,
code: quote.code,
})
.then((result) => {
if (result) {
recordExist = true;
console.log("Results found");
console.log("Skip ...");
} else {
recordExist = false;
console.log("Results not found");
console.log("Adding quote for " + symbol + " ...");
let stock = new Stock(quote);
stock
.save()
.then(() => {
console.log(`Added quote for ${quote.date.toLocaleDateString()} \n`);
totalAdded++;
})
.catch((error) => {
console.log(error + "\n");
});
}
})
.catch((error) => {
throw new Error(error);
});
index--;
} while (recordExist && index >= 0);
console.log(`${totalAdded}/${totalCount} quotes were added.`);
console.log("stop\n");
})
.catch((error) => {
// throw new Error(error);
console.error(error);
});
}
console.log("Date Request Summary");
console.log(`Data fetched from ${PNGX_DATA_URL}\n`);
console.timeEnd("timer"); // end timer and log time difference
const endTime = new Date();
const timeDiff = parseInt((Math.abs(endTime.getTime() - startTime.getTime()) / 1000) % 60);
console.log("Start time " + startTime);
console.log("End time " + timeDiff + " secs\n");
console.log("Time difference " + timeDiff + " secs\n");
console.log("Total request time: " + reqTimes);
}
exports.data_fetcher = data_fetcher;
async function checkIfExistInDatabase(code, date) {
let result = await Stock
.findOne({
date: date,
code: code,
})
return result > 0;
}
async function stock_fetcher() {
let result = await Stock.find();
return result;
}
exports.stock_fetcher = stock_fetcher;
/**
* reverse run down
*/