mercredi 22 avril 2020

Writing a conditional If-statement for portfolio analysis

I am new to R and I am currently trying to create equal-weighted portfolios based on ESG Scores, but I am having some trouble with parts of the code. Specifically, I would like to write an if function that allows me to specify that if the Market Value > 0 in the previous month, then I want my return column to be multiplied with the corresponding weights column. I have this problem as some of the companies in my dataset are delisted during the year, and the weights then need to be redistributed to the remaining companies for the remaining months of the year. Various websites have been of great help (especially this one: https://www.codingfinance.com/post/2018-04-05-portfolio-returns/), but I cannot seem to find a solution to my above-mentioned problem. All help is appreciated and I apologise if the code is messy, thank you.

  returnhigh <- highport %>%
    group_by(Company) %>%
    # Trying to add the weight constraint 
    if(all$`Market Value` > 0) {
      # This is the part where I struggle to specify the market value of the previous month 
      returnhigh$Weight <- 1/length(highport$Company)
    }

  returnhigh <- returnhigh %>% mutate(wt_return = Weight * Return)
  porthigh <- returnhigh %>% group_by(Date) %>% summarise(port_ret = sum(wt_return))
  returnlow <- lowport %>%
    group_by(Company) %>%
    if(all$`Market Value` > 0) {
      # Same problem as above 
      returnlow$Weight <- 1/length(lowport$Company)
    }
  returnlow <- returnlow %>% mutate(wt_return = Weight * Return)
  portlow <- returnlow %>% group_by(Date) %>% summarise(port_ret = sum(wt_return))
  result <- porthigh - portlow
  return(result)
}


Aucun commentaire:

Enregistrer un commentaire