-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
498 lines (397 loc) · 16.1 KB
/
index.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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// var Promise = require('es6-promise').Promise;
var async = require('asyncawait/async');
var await = require('asyncawait/await');
var Promise = require('bluebird');
var _ = require('lodash');
var moment = require('moment');
var express = require('express'); // call express
var app = express(); // define our app using express
var bodyParser = require('body-parser');
var fs = require('fs');
var fetch = require('node-fetch');
var schedule = require('node-schedule');
var utf8 = require('utf8');
var EtfModel = require('./models/EtfModel');
var StockModel = require('./models/StockModel');
var dataFileName = 'd.json';
var data = [];
// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8080; // set our port
// ROUTES FOR OUR API
// =============================================================================
var router = express.Router(); // get an instance of the express Router
// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/test', (req, res) => {
res.json(data);
});
router.get('/strategies', (req, res) => {
var r = res;
fs.readFile('data.json', 'utf8', (err, d) => {
if(!err)
r.json(JSON.parse(d))
})
});
router.get('/stock/:id', (req, res) => {
var r = res;
getStockData(req.params.id)
.then((res) => { r.json(res) })
.catch((err) => { r.json({error: err}); });
});
router.get('/etf/:id', (req, res) => {
var r = res;
getETFData(req.params.id)
.then((res) => { r.json(res); })
.catch((err) => { r.json('ERROR' + err) });
});
router.get('/stock13f/:symbol/:id', (req, res) => {
var r = res;
var stockData = {};
var holdingsData = {};
getStock13F(req.params.id, req.params.symbol)
.then((res) => {r.json(res);})
.catch((err) => { r.json({error: err}); });
/*
getStockData(req.params.symbol)
.then((res) => {
stockData = res;
get13F(req.params.id)
.then((res) => {
var sectorsIndustries = [];
sectorsIndustries = res.holdings.map((item) => {
return {name: item.industry, raw: item.current_percent_of_portfolio, fmt: item.current_percent_of_portfolio};
});
stockData.sectorsIndustries = sectorsIndustries;
r.json(stockData);
})
.catch((err) => { r.json({error: err}); });
})
.catch((err) => { r.json({error: err}); });
*/
});
router.get('/history/:id/:period', (req, res) => {
var r = res;
var date = {};
switch(req.params.period) {
case '1D':
date.startDate = moment().subtract(1, 'days').format('YYYY-MM-DD');
break;
case '5D':
date.startDate = moment().subtract(5, 'days').format('YYYY-MM-DD');
break;
case '1W':
date.startDate = moment().subtract(7, 'days').format('YYYY-MM-DD');
break;
case '1M':
date.startDate = moment().subtract(30, 'days').format('YYYY-MM-DD');
break;
case '3M':
date.startDate = moment().subtract(3, 'months').format('YYYY-MM-DD');
break;
case '6M':
date.startDate = moment().subtract(6, 'months').format('YYYY-MM-DD');
break;
case '1Y':
date.startDate = moment().subtract(12, 'months').format('YYYY-MM-DD');
break;
case '2Y':
date.startDate = moment().subtract(2, 'years').format('YYYY-MM-DD');
break;
case '5Y':
date.startDate = moment().subtract(5, 'years').format('YYYY-MM-DD');
break;
}
date.endDate = moment().format('YYYY-MM-DD');
getHistoricalData(req.params.id, date)
.then((res) => {
r.json(res);
})
.catch((err) => {r.json('ERROR' + err)});
});
router.get('/13f/:id', (req, res) => {
var r = res;
get13F(req.params.id)
.then((res) => { r.json(res); })
.catch((err) => { r.json('ERROR ' + err)});
});
// more routes for our API will happen here
// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);
// START THE SERVER
// =============================================================================
app.listen(port);
console.log('Running server on port ' + port);
// Excecute cron job every day at 00 hs.
var cronJob = schedule.scheduleJob('0 0 0 * * *', function(){
});
function getAllData() {
console.log('GETTING DATA');
return;
var data = {};
fs.readFile('data.json', 'utf8', (err, d) => {
if(!err) {
data = JSON.parse(d);
data.map((item) => {
if(item.wid)
console.log(item.wid);
})
}
})
// setTimeout(readDataFromFile , 1000);
}
var getETFData = async((symbol) => {
var data = {};
var etf = await(
fetch('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'+symbol+'?formatted=true&crumb=pFqE0Ejwwqf&lang=en-US&modules=topHoldings%2CdefaultKeyStatistics%2CassetProfile%2CfinancialData%2CincomeStatementHistory%2CbalanceSheetHistory')
.then((res) => {return res.json();})
.then((json) => {
return json.quoteSummary.result[0];
})
);
var etfFinance = await(
fetch('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22'+symbol+'%22)&format=json&env=http://datatables.org/alltables.env')
.then((res) => {return res.json()})
.then((json) => {return json.query.results.quote;})
);
// Top holdings
var topHoldings = _.map(etf.topHoldings.holdings, (h) => {return {symbol:h.symbol, name: h.holdingName, percent: h.holdingPercent}});
for(var holding of topHoldings) {
var holdingData2 = await(
fetch('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22'+holding.symbol+'%22)&format=json&env=http://datatables.org/alltables.env')
.then((res) => {return res.json()})
.then((json) => {return json.query.results.quote;})
);
holding.ask = holdingData2.Ask;
holding.bid = holdingData2.Bid;
// console.log(holdingData);
}
var sectorsIndustries = [];
for(var industries in etf.topHoldings.sectorWeightings) {
for(var industry in etf.topHoldings.sectorWeightings[industries]) {
sectorsIndustries.push({
name: industry,
raw: etf.topHoldings.sectorWeightings[industries][industry].raw,
fmt: etf.topHoldings.sectorWeightings[industries][industry].fmt
});
}
}
data.finance = {};
data.profile = {};
data.profile.name = etfFinance.Name;
data.profile.symbol = etfFinance.Symbol;
data.profile.summery = utf8.decode(etf.assetProfile.longBusinessSummary.replace("\n ", "\n\n"));
data.finance.ask = etfFinance.Ask;
data.finance.bid = etfFinance.Bid;
data.finance.category = etf.defaultKeyStatistics.category;
data.finance.foundFamily = etf.defaultKeyStatistics.foundFamily;
data.finance.legalType = etf.defaultKeyStatistics.legalType;
data.finance.ytdReturn = etf.defaultKeyStatistics.ytdReturn;
data.finance.totalAssets = etf.defaultKeyStatistics.totalAssets;
data.finance.yield = etf.defaultKeyStatistics.yield;
data.finance.fundInceptionDate = etf.defaultKeyStatistics.fundInceptionDate;
data.finance.threeYearAverageReturn = etf.defaultKeyStatistics.threeYearAverageReturn;
data.finance.fiveYearAverageReturn = etf.defaultKeyStatistics.fiveYearAverageReturn;
data.sectorsIndustries = sectorsIndustries;
data.topHoldings = topHoldings;
return data;
});
var getStockData = async((id) => {
var data = {};
var stockInfo = await(
fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22'+id+'%22)&format=json&env=http://datatables.org/alltables.env')
.then((res) => {return res.json()})
.then((json) => {return json.query.results.quote;})
);
var stockFinance = await(
fetch('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'+id+'?f=y&formatted=true&crumb=n&lang=en-US&modules=topHoldings%2CdefaultKeyStatistics%2CassetProfile%2CfinancialData%2CincomeStatementHistory%2CbalanceSheetHistory')
.then((res) => {return res.json();})
.then((json) => {return json.quoteSummary.result[0];})
);
data.profile = {};
data.finance = {};
data.profile.name = stockInfo.Name;
data.profile.symbol = stockInfo.Symbol;
data.profile.industry = stockFinance['assetProfile'].industry;
data.profile.sector = stockFinance['assetProfile'].sector;
data.profile.summery = stockFinance['assetProfile'].longBusinessSummary;
data.finance.ask = stockInfo.Ask;
data.finance.bid = stockInfo.Bid;
data.finance.yield = stockInfo.DividendYield;
data.finance.marketCap = stockInfo.MarketCapitalization;
data.finance.sharesOutstanding = stockFinance.defaultKeyStatistics.sharesOutstanding;
data.finance.peRatio = stockInfo.PERatio;
data.finance.pegRatio = stockFinance.defaultKeyStatistics.pegRatio;
data.finance.enterpriseValue = stockFinance.defaultKeyStatistics.enterpriseValue;
data.finance.forwardPE = stockFinance.defaultKeyStatistics.forwardPE;
data.finance.totalCash = stockFinance.financialData.totalCash;
data.finance.totalRevenue = stockFinance.financialData.totalRevenue;
data.finance.revenueGrowth = stockFinance.financialData.revenueGrowth;
data.finance.currentPrice = stockFinance.financialData.currentPrice;
data.finance.targetHighPrice = stockFinance.financialData.targetHighPrice;
data.finance.targetLowPrice = stockFinance.financialData.targetLowPrice;
data.finance.returnOnAssets = stockFinance.financialData.returnOnAssets;
return data;
});
var get13F = async((id) => {
var api_key = 'IzHSnnbUgHWxBgwNeEKg';
var auth = 'Basic ' + new Buffer('[email protected]:Lyon280314').toString('base64');
var url = 'https://whalewisdom.com/shell/command.json?args=';
var options = {
method: 'GET',
headers: { 'Authorization': auth },
};
//349 - BERKSHIRE HATHAWAY INC
var getId = await(
// fetch(url + JSON.stringify(command), options)
// .then((res) => {return res.json()})
// .then((json) => {return json})
);
var command = {
"command": "holdings",
"filer_ids": [id],
"columns": [3,4,8,10,18,19,20],
"sort": "current_ranking",
"include_13d": 1
};
var whaleApi = await(
fetch(url + JSON.stringify(command), options)
.then((res) => {return res.json()})
.then((json) => {return json.results[0].records[0]})
);
var totalPercent = 0;
// for(var holding in whaleApi) {
// if(whaleApi[holding].current_percent_of_portfolio != null)
// totalPercent += whaleApi[holding].current_percent_of_portfolio
// console.log(whaleApi[holding]);
// }
// totalPercent = Math.round(totalPercent);
return whaleApi;
});
var getStock13F = async((id, symbol) => {
var data = {};
var sectorsIndustries = [];
var stockInfo = await(
fetch('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22'+symbol+'%22)&format=json&env=http://datatables.org/alltables.env')
.then((res) => {return res.json()})
.then((json) => {return json.query.results.quote;})
);
var stockFinance = await(
fetch('https://query2.finance.yahoo.com/v10/finance/quoteSummary/'+symbol+'?f=y&formatted=true&crumb=n&lang=en-US&modules=topHoldings%2CdefaultKeyStatistics%2CassetProfile%2CfinancialData%2CincomeStatementHistory%2CbalanceSheetHistory')
.then((res) => {return res.json();})
.then((json) => {return json.quoteSummary.result[0];})
);
data.profile = {};
data.finance = {};
var get13fData = await(
get13F(id)
.then((res) => {return res})
.catch((err) => { return err })
);
// Top holdings
var topHoldings = _.map(get13fData.holdings, (h) => {return {symbol:h.stock_ticker, name: h.stock_name, percent: h.current_percent_of_portfolio}});
sectorsIndustries = get13fData.holdings.map((item) => {
return {name: item.industry, raw: item.current_percent_of_portfolio, fmt: item.current_percent_of_portfolio};
});
// console.log(get13fData.holdings);
/*
stock_name": "General Electric Co",
"stock_ticker": "GE",
"current_ranking": 33,
"current_percent_of_portfolio": 0.2435,
"sector": "INDUSTRIALS",
"industry": "CONGLOMERATES",
"percent_ownership": "0.1128604"
*/
// for(var holding of topHoldings) {
// var holdingData2 = await(
// fetch('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22'+holding.symbol+'%22)&format=json&env=http://datatables.org/alltables.env')
// .then((res) => {return res.json()})
// .then((json) => {return json.query.results.quote;})
// );
// holding.ask = holdingData2.Ask;
// holding.bid = holdingData2.Bid;
// // console.log(holdingData);
// }
data.finance = {};
data.profile = {};
data.profile.name = stockInfo.Name;
data.profile.symbol = stockInfo.Symbol;
data.profile.summery = stockFinance['assetProfile'].longBusinessSummary;//utf8.decode(etf.assetProfile.longBusinessSummary.replace("\n ", "\n\n"));
data.finance.ask = stockInfo.Ask;
data.finance.bid = stockInfo.Bid;
data.finance.yield = stockInfo.DividendYield;
data.finance.marketCap = stockInfo.MarketCapitalization;
data.finance.sharesOutstanding = stockFinance.defaultKeyStatistics.sharesOutstanding;
data.finance.peRatio = stockInfo.PERatio;
data.finance.pegRatio = stockFinance.defaultKeyStatistics.pegRatio;
data.finance.enterpriseValue = stockFinance.defaultKeyStatistics.enterpriseValue;
data.finance.forwardPE = stockFinance.defaultKeyStatistics.forwardPE;
data.finance.totalCash = stockFinance.financialData.totalCash;
data.finance.totalRevenue = stockFinance.financialData.totalRevenue;
data.finance.revenueGrowth = stockFinance.financialData.revenueGrowth;
data.finance.currentPrice = stockFinance.financialData.currentPrice;
data.finance.targetHighPrice = stockFinance.financialData.targetHighPrice;
data.finance.targetLowPrice = stockFinance.financialData.targetLowPrice;
data.finance.returnOnAssets = stockFinance.financialData.returnOnAssets;
data.sectorsIndustries = sectorsIndustries;
data.topHoldings = topHoldings;
return data;
});
var getHistoricalData = async((id, date) => {
var data = {};
histData = [];
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.historicaldata%20where%20symbol%20%3D%20%22'+id+'%22%20and%20startDate%20%3D%20%22'+date.startDate+'%22%20and%20endDate%20%3D%20%22'+date.endDate+'%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys';//&callback=';
var historicalData = await(
fetch(url)
.then((res) => {return res.json()})
.then((json) => {return json.query.results.quote;})
);
for(var i = 0; i < historicalData.length; i++) {
var period = [];
period.push(Number(historicalData[i].Open));
period.push(Number(historicalData[i].Close));
histData.push(period);
}
data.data = histData;
return data;
});
var getHistoricalData2 = async((opts, type) => {
// function getStockFinanceData(opts, type) {
var defs = {
baseURL: 'http://query.yahooapis.com/v1/public/yql?q=',
query: {
quotes: 'select * from yahoo.finance.quotes where symbol in ("{stock}")',
historicaldata: 'select * from yahoo.finance.historicaldata where symbol = "{stock}" and startDate = "{startDate}" and endDate = "{endDate}"',
},
suffixURL: {
quotes: '&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys',
historicaldata: '&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys',
}
};
opts = opts || {};
if (!opts.stock) {
console.log('No stock defined');
return;
}
if (opts.stock instanceof Array) {
opts.stock = opts.stock.join("', '");
}
console.log(opts.stock);
var query = defs.query[type]
.replace('{stock}', opts.stock)
.replace('{startDate}', opts.startDate)
.replace('{endDate}', opts.endDate);
var url = defs.baseURL + query + (defs.suffixURL[type] || '');
console.log('URLURL',url);
return fetch(url);
});
function readDataFromFile() {
fs.readFile(dataFileName, 'utf8', (err, d) => {
if(!err)
data = JSON.parse(d);
})
}
setTimeout(getAllData, 1000);