循环将年份分为两部分

时间:2018-08-25 08:51:52

标签: r xts tidyverse quantmod performanceanalytics

我正在寻找一种创建循环的方法,该循环将多年分为开始部分和结束部分,并给出以发生切割年份的百分比为单位的数值。在更详细地描述之前,最容易向您展示我想要获得的产品:

循环的第一次迭代将在下一次迭代开始之前为我提供以下输出:

beginning_section = c("2003-01-01/2003-02-01","2004-01-01/2004-02-01","2005-01-01/2005-02-01")
ending_section = c("2003-02-02/2003-12-31","2004-02-02/2004-12-31","2005-02-02/2005-12-31")
time_scale = c(0.169,0.169,0.169)

循环的第二次迭代将在下一次迭代开始之前为我提供以下输出:

beginning_section = c("2003-01-01/2003-02-02","2004-01-01/2004-02-02","2005-01-01/2005-02-02")
ending_section = c("2003-02-03/2003-12-31","2004-02-03/2004-12-31","2005-02-03/2005-12-31")
time_scale = c(0.172,0.172,0.172)

循环的最后一次迭代将使我在循环结束之前可以使用以下输出:

beginning_section = c("2003-01-01/2003-11-30","2004-01-01/2004-11-30","2005-01-01/2005-11-30")
ending_section = c("2003-02-03/2003-12-31","2004-02-03/2004-12-31","2005-02-03/2005-12-31")
time_scale = c(0.915,0.915,0.915)

#do some calculations with beginning_section, ending section, and time scaled 

基本上,它应该将一个特定的月-日点处的所有年份都分为两个字符向量(一个用于所有开始部分,一个用于所有结束部分),并给出一个整数向量,该百分比表示一年的削减。例如,如果削减恰好发生在年中,则截止值为0.5。然后,循环应该向前移动一天,然后再次执行相同的操作,依此类推。

到目前为止,我已经尝试过(但经历了惨败):

library(tidyverse)   

days <- 1:30 %>% as.character()
months <- 2:11 %>% as.character()
years <- 2003:2017 %>% as.character()

beg_section <- NULL
end_section <- NULL
time_scaled <- NULL

for (m in months) {
  for (d in days) {
    for (y in years) {
      temp_beg <- paste(y, "-1-1/", y, "-", m, "-", d, sep = "")
      beg_section <- rbind(beg_section,temp_beg)
      temp_end <- paste(y, "-", m, "-", d, "/", y, "-12-31", sep = "")
      end_section <- rbind(end_section,temp_end)
      temp_scale <- (as.numeric(m) + as.numeric(d)/30 - 1) / 12
      time_scaled <- rbind(time_scaled,temp_scale)
    }
  }
} 

beg_section <- beg_section %>% as.vector()
end_section <- end_section %>% as.vector()
time_scaled <- time_scaled %>% as.vector()

n <- 1
m <- length(years) %>% as.numeric()

while (m < length(beg_section)) {
  lead_up_period <- beg_section[n:m]
  end_period <- end_section[n:m]
  vol_adjustment <- time_scaled[n]
  print(lead_up_period)
  print(end_period)
  print(vol_adjustment)
  n <- m + 1
  m <- m + length(years)
    }
#end

我还想指出,解决方案不必绝对完美。例如,如果所有月份仅处理30天,那将不胜感激。

0 个答案:

没有答案