r - 如何在R Studio中的for循环中包含计数过程?

标签 r loops for-loop if-statement while-loop

我想计算 10 年内每个月有多少正返回和负返回,并将它们包含在 dtf 中。这是因为我想计算获得正 yield 和负 yield 的概率。我不知道如何将计数过程包含在我的 for 循环中。

例如:10年7月份的平均月返回率为2.18%,正返回的数量为10中有8个,即80%,因此获得负返回的概率为20%。由于 7 月份的 10 年平均月返回率为正数,即 2.18%,我希望在 dtf 中显示正返回率 (80%) 的概率,而不是负返回率 (20%)。

另一个例子:五月也是如此。由于5月份10年平均月返回率为负(-1.23%),10年获得正返回的概率为60%(十分之六),而获得负返回的概率为40%(十分之4) 10),我希望在 dtf 中显示负概率 (40%),而不是正概率 60%。

每个月都会发生同样的事情,因此,dtf 中会有第三列显示获得正/负返回的概率。

我尝试在 for 循环 中包含 if 循环,但它不起作用。我在下面附上了我的代码,其中 dtf 只有 2 列(Month 和 AverageMonthlyRet)。

library(quantmod)

#obtian the historical stock price
prices <- getSymbols("^GSPC", src = 'yahoo', from = "2009-07-01", to = "2019-08-01", 
                     periodicity = "monthly", auto.assign = FALSE, warnings = FALSE)[,4]

#calculate the log return and convert back to simple return
return <- diff(log(prices))
r <- na.omit(exp(return)-1)

monthlyRet <- as.numeric(r[,1])

#loop through all the months in 10 years
AverageMonthlyRet <- c()
for (j in 1:12){
  Group <- c()
  for (i in seq(j,length(monthlyRet),12)){
    Group[i] <- monthlyRet[i]
  }
  AverageMonthlyRet[j] <- mean(Group, na.rm=TRUE)
}
AverageMonthlyRet <- round(AverageMonthlyRet,4)

#create a data frame to store the result
Month <- c("Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul")
dtf <- data.frame(Month, AverageMonthlyRet)

最佳答案

根据我对您问题的理解,这是一个建议的解决方案。代码中给出了注释。

主要思想是添加一些计数器变量,根据一些 if/else 测试的结果在循环中递增这些变量。它们存储负收入或正收入的概率。然后通过额外的测试,您确定要保持正收入或负收入概率。

有多种方法可以将其写得更简洁,但这个较长的版本显示了所有细节和想法。如果您知道收入永远不会为空,您只需计算一个计数器,因为您知道一个概率,例如正数,始终为 100 - 其他概率。在我的版本中,零收入是可能的,因此您的正概率 + 负概率可能小于 100。

library(quantmod)

#obtian the historical stock price
prices <- getSymbols("^GSPC", src = 'yahoo', from = "2009-07-01", to = "2019-08-01", 
                     periodicity = "monthly", auto.assign = FALSE, warnings = FALSE)[,4]

#calculate the log return and convert back to simple return
return <- diff(log(prices))
r <- na.omit(exp(return)-1)

monthlyRet <- as.numeric(r[,1])

#loop through all the months in 10 years
AverageMonthlyRet <- c()
#Added: Array to store the probability for each month
Probability <- c()
for (j in 1:12){
  Group <- c()
  #Added: Counter, for each month, of positive or negative income
  connt_pos=0
  count_neg=0
  for (i in seq(j,length(monthlyRet),12)){
    Group[i] <- monthlyRet[i]
    #Added: Increment the counters based on the sign of monthlyRet[i]
    if(monthlyRet[i]>0){
      connt_pos <- connt_pos+1
    }
    else  if(monthlyRet[i]<0){
      count_neg <- count_neg+1
    }
  }
  AverageMonthlyRet[j] <- mean(Group, na.rm=TRUE)
  #Added: Depending if the average monthly retrn is positive or negative
  #compute the probability of positive or negative income (in %)
  prob=0
  if(AverageMonthlyRet[j]>0)
  {
    prob=connt_pos/(length(monthlyRet)/12)*100
  }
  else if (AverageMonthlyRet[j]<0){
    prob=count_neg/(length(monthlyRet)/12)*100
  }
  #Added: Store the result
  Probability[j] <- prob

}
AverageMonthlyRet <- round(AverageMonthlyRet,4)

#create a data frame to store the result
Month <- c("Aug","Sep","Oct","Nov","Dec","Jan","Feb","Mar","Apr","May","Jun","Jul")
#Added: Add the new probability column to the final data frame
dtf <- data.frame(Month, AverageMonthlyRet,Probability)

关于r - 如何在R Studio中的for循环中包含计数过程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57472489/

相关文章:

r - Highcharter 中的手动轴标签

regex - 正则表达式保留一些匹配,删除其他匹配

java - 将 While 循环与 g.drawPolygon 代码结合使用

php - 为什么代码进入无限循环? (

bash - 为什么for循环中有不同的输出

javascript - 我应该如何在javascript中循环遍历and "associative object"?

mysql - 使用来自服务器的 MySQL 数据更新 Shiny R 中的 selectInput

r - foreach dopar 循环内的绘图

r - R 中的循环 - 需要使用索引,无论如何要避免 'for' ?

java - 如何只返回一个公共(public)值?