首页 > 解决方案 > 如何绕过使用不同日期的重复函数?

问题描述

我需要我的函数在股票的某个时期工作,在示例中AKER["2013-11-19/2018-11-19"],从 2013 年 10 月到 2018 年 10 月。然后再次工作,但这次离我设定的日期更近一年,就像这样AKER["2014-11-19/2018-11-19"]。然后再一次。然后再次。

这就是我得到的:

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

这就是我需要的(某些版本):

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

我如何在每次接近一年的情况下重复所有这些功能?

标签: rdatexts

解决方案


如果日期数量有限,我们可以手动创建日期向量

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")

然后使用任何循环技术循环dates( sapply, lapply, map, forloop 等)

sapply(dates, function(x) resistence_line_by_volume(AKER[x]), USE.NAMES = FALSE)
#[1] 3.327881 3.294591 3.266057 3.232329 3.168454

或者我们也可以使用编程方式生成日期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

推荐阅读