lundi 12 août 2019

How to include the counting process in for loop in R studio?

I want to count how many positive and negative returns for each month in 10 years time and include them in the dtf. This is because I want to calculate the probability of getting positive and negative returns. I'm not sure how to include the counting process in my for loop, so I wish I could get help for this task.

For example: The average monthly returns for July in 10 years is 2.18%, and the number of positive returns are 8 out of 10 which is 80% and so the probability of obtaining negative returns will be 20%. Since the 10 years average monthly return for July is in positive, 2.18%, I would like the probability of positive return (80%) to be shown in dtf instead of negative one (20%).

Another example: Same thing goes to May. Since the average monthly return in 10 years time for May is negative (-1.23%), and the probability of getting positive returns in 10 years is 60% (6 out of 10) while for the negative one is 40% (4 out of 10), I would like the negative probability (40%) to be shown in dtf instead of the positive 60%.

Same thing goes to each and every month, and therefore, there will be a 3rd column in dtf showing the probability of getting positive/negative returns.

Please help me with this task as I figured the code for long time already but still can't get there. Thanks a lot!

I tried to include if loop in my for loop but it doesn't work. I attached my code below with the dtf with only 2 column (Month and 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)

I hope I can get help in this issue, it will help me a lot, appreciated!

Aucun commentaire:

Enregistrer un commentaire