-
Notifications
You must be signed in to change notification settings - Fork 2
/
util.js
51 lines (41 loc) · 1.56 KB
/
util.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
const dateTime = require('date-and-time');
const getStrikeBlock = (symbol) => {
const lastSpace = symbol.lastIndexOf(' ');
return symbol.substring(lastSpace + 1);
}
const getStrikePriceOptions = (symbol) => {
return getStrikePriceFutures(symbol) / 1000
}
const getStrikePriceFutures = (symbol) => {
const strikeTextBlock = getStrikeBlock(symbol);
const optionType = getOptionType(symbol);
if (optionType === 'call') return Number(strikeTextBlock.substring(strikeTextBlock.lastIndexOf('C') + 1));
if (optionType === 'put') return Number(strikeTextBlock.substring(strikeTextBlock.lastIndexOf('P') + 1));
};
const getOptionType = (symbol) => {
const strikeTextBlock = getStrikeBlock(symbol);
const c = strikeTextBlock.lastIndexOf('C');
const p = strikeTextBlock.lastIndexOf('P');
if (c > -1) return 'call';
if (p > -1) return 'put';
throw new Error('invalid symbol');
};
const getExpirationInYears = (currentDate, symbol) => {
const strikeDateString = getStrikeBlock(symbol).slice(0, 6);
const strikeDate = dateTime.parse(strikeDateString, 'YYMMDD');
const differenceInMs = strikeDate.getTime() - currentDate.getTime();
return differenceInMs / 31536000000; // milliseconds in a year
};
const groupBy = function (xs, key) { // https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects
return xs.reduce(function (rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
module.exports = {
getStrikePriceOptions,
getStrikePriceFutures,
getExpirationInYears,
getOptionType,
groupBy
}