I need my function to work on some period on the stock, in the example, AKER["2013-11-19/2018-11-19"]
, from oct of 2013 to oct of 2018. And then work again BUT this time with one year closer to the date that I set, like this AKER["2014-11-19/2018-11-19"]
. And then again. And again.
That's what I got:
resistence_line_by_volume <- function(x) {
open_prices <- x[,1]
close_prices <- x[,4]
volume_amount <- x[,5]
average_open_and_close <- (open_prices + close_prices)/2
weighet_price_volume <- (average_open_and_close*volume_amount)/sum(volume_amount)
result <- sum(weighet_price_volume)
result
}
getSymbols("AKER")
[1] "AKER"
resistence_line_by_volume(AKER["2013-11-19/2018-11-19")
[1] 3.353938
resistence_line_by_volume(AKER["2014-11-19/2018-11-19")
[1] 3.319899
resistence_line_by_volume(AKER["2015-11-19/2018-11-19")
[1] 3.290728
resistence_line_by_volume(AKER["2016-11-19/2018-11-19")
[1] 3.256264
resistence_line_by_volume(AKER["2017-11-19/2018-11-19")
[1] 3.191081
And that's what I need (some version of that):
resistence_line_by_volume(AKER["2013-11-19/2018-11-19")
[1] 3.353938
[2] 3.319899
[3] 3.290728
[4] 3.256264
[5] 3.191081
How do I repete all this functions with one year closer every time?
If there are limited number of dates, we can manually create a vector of dates
library(quantmod)
dates <- c("2013-11-19/2018-11-19","2014-11-19/2018-11-19","2015-11-19/2018-11-19",
"2016-11-19/2018-11-19", "2017-11-19/2018-11-19")
and then use any looping technique to loop over dates
(sapply
, lapply
, map
, for
loop etc.)
sapply(dates, function(x) resistence_line_by_volume(AKER[x]), USE.NAMES = FALSE)
#[1] 3.327881 3.294591 3.266057 3.232329 3.168454
Or we can also generate the dates programatically using seq
dates <- paste(seq(as.Date("2013-11-19"), length.out = 5, by = "year"),
"2018-11-19", sep = "/")
sapply(dates, function(x) resistence_line_by_volume(AKER[x]), USE.NAMES = FALSE)
#[1] 3.327881 3.294591 3.266057 3.232329 3.168454