-
Notifications
You must be signed in to change notification settings - Fork 8
/
utils.js
101 lines (83 loc) · 2.54 KB
/
utils.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
const cloneDeep = require('lodash/cloneDeep')
const filter = require('lodash/filter')
const find = require('lodash/find')
const keyBy = require('lodash/keyBy')
const Big = require('big.js')
const {
format,
eachDayOfInterval,
parse, isAfter
} = require('date-fns')
function applySplitMultiplier (activities) {
activities = cloneDeep(activities)
const splits = filter(
filter(activities, a => a.type === 'split'),
a => !isAfter(new Date(a.date), new Date())
)
// multiply all shares from activities <= split date with the split multiplier
splits.forEach(s => {
const activitiesBeforeSplit = filter(
activities,
(a) =>
['Buy', 'Sell'].includes(a.type) &&
isAfter(new Date(s.date), new Date(a.date))
)
activitiesBeforeSplit.forEach(a => {
a.shares = +Big(a.shares).times(Big(s.multiplier))
a.price = +Big(a.price).div(Big(s.multiplier))
})
})
return activities
}
function getDateArr (interval) {
const startDate = new Date(parse(interval.start, 'yyyy-MM-dd', new Date()))
const endDate = new Date(parse(interval.end, 'yyyy-MM-dd', new Date()))
const eachDay = eachDayOfInterval({ start: startDate, end: endDate })
const dateArr = eachDay.map((d, i) => format(d, 'yyyy-MM-dd'))
return dateArr
}
// iterate all dates verifing if it have a price in the quotes
// we save the last founded price to fill the next dates without price
// if a date dont have price it will be filled with the previous price we save
// when the first price was found, if exists, we fill the firsts empty elements
// the output will be the dates array and every day will have a price
function normalizeQuotes (quotes = [], dates) {
quotes = keyBy(quotes, 'date')
let price = 0
let priceFound = false
const quotesPerDay = []
for (let i = 0; i < dates.length; i++) {
const t = dates[i]
const q = quotes[t]
if (q && q.price) {
price = q.price
// Fills empty starting values by take the first empty elements of the array and fill in the first price that was found.
if (!priceFound) {
quotesPerDay.slice(0, i).map(q => q.price = price);
priceFound = true
}
}
quotesPerDay.push({
date: t,
price
})
}
return quotesPerDay
}
function getPreviousValue (arr, i) {
if (i === 0) {
return arr.find(x => x != null)
}
const prev = arr[i - 1]
if (prev === null) {
return getPreviousValue(arr, i - 1)
} else {
return prev
}
}
module.exports = {
applySplitMultiplier,
getDateArr,
normalizeQuotes,
getPreviousValue
}