r - 如何绕过使用不同日期的重复函数?
问题描述
我需要我的函数在股票的某个时期工作,在示例中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
我如何在每次接近一年的情况下重复所有这些功能?
解决方案
如果日期数量有限,我们可以手动创建日期向量
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
, for
loop 等)
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
推荐阅读
- java - 在 2 个映射之间获取具有 2 个键的值
- javascript - 在 React 中安装组件时包含谷歌地图脚本
- c - MPI Scatter / 向进程发送数据
- ios - 保存在文档库中的图像文件无法在计算机 Objective-C 中打开
- c# - 指定格式时 DateTime 解析不起作用
- google-sheets - 每隔 n 行着色一次
- javascript - 将变量作为具有相同字符串的索引传递将不起作用
- php - PHP / Laravel Firebase 实时数据库更新特定字段
- laravel - 为什么在验证空字符串时 laravel 验证不正确?
- android - 在 Android 设备中使用 ADB shell 删除非系统应用程序