I'm desperately trying to avoid for loops to calculate custom financial indicators (multiple stocks, 5,000 rows per stock). I'm trying to use purrr::map2
, and it is fine when doing math on existing vectors, but I need to reference the lag (previous) value of the vector I'm trying to create. Without referencing a previous value, purrr::map2
works fine:
some_function <- function(a, b) { (a * b) + ((1 - a) * b) }
a <- c(0.019, 0.026, 0.012, 0.022) # some indicator
b <- c(15.5, 16.7, 14.8, 13.1) # close price
purrr::map2(a, b, some_function)
which just results in the original close values
15.5, 16.7, 14.8, 13.1
But what I'm really trying to do is create a new vector (c), that looks back on itself (lag) as part of the calculation. If it is the first row, c == b, otherwise:
desired_function <- function(a, b, c) { (a * b) + ((1 - a) * lag(c)) }
So I create a vector c
and populate and try:
c <- c(15.5, 0, 0, 0)
purrr::map2(a, b, c, desired_function)
And get all NULL values, obviously.
Values for c should be: 15.50, 15.53, 15.52, 15.47
Referencing a previous value is a common thing among indicators, and it forces me to go to clunky, slow 'for loops'. Any suggestions are greatly appreciated.