R/market_model.R

#' Market Model
#'
#' This function calculates the normal returns using the market model.
#' Returns either the residuals or the regressions.
#' @param return.data should be a data frame containing dates (Date) in the first column and returns in the rest.
#' @param market.data should be a data frame containing dates (Date) in the first column and market returns in the second.
#' @param residuals Do you want the residuals? Defaults to TRUE. If FALSE the regressions are returned.
#' @keywords Keywords
#' @export
#' @examples
#' MarketModel(return.data = ReturnData, market.data = MarketData, residuals = TRUE)
#' MarketModel(return.data = ReturnData, market.data = MarketData, residuals = FALSE)

# This function calculates the normal returns using the market model.
# Input:
# return.data should be a data frame containing dates (Date) in the first column and returns in the rest.
# market.data should be a data frame containing dates (Date) in the first column and market returns in the second.
# Output:
# If residuals = TRUE the residuals of the market model are returned. If FALSE the regressions are returned.

MarketModel <- function(return.data, market.data, residuals = TRUE){
  # Check if the data has the same number of observations.
  stopifnot(nrow(return.data) == nrow(market.data))

  # Set number of observations and assets in return.data and set date vector
  observations <- nrow(return.data)
  assets <- ncol(return.data) - 1
  returns <- return.data[,-1]
  market.returns <- market.data[,-1]

  # Construct result containers
  resids <- return.data

  # If only one asset is included in the study
  if (assets == 1) {
    reg <- list()
    merged.data <- as.data.frame(cbind(returns, market.returns))
    reg <- lm(returns ~ market.returns, data = merged.data, na.action = na.exclude) # na.exclude: NAs can be seen in prediction

    if (residuals == TRUE) {
      resids[,2] <- returns - predict(reg)
      result <- resids
    } else {
      result <- reg
    }
  } else {
    # If multiple assets are included in the study
    regs <- list()
    for (i in 1:assets) {
      merged.data <- as.data.frame(cbind(returns[,i], market.returns))
      colnames(merged.data)[1] <- "returns"
      regs[[i]] <- lm(returns ~ market.returns, data = merged.data, na.action = na.exclude)

      if (residuals == TRUE) {
        resids[,i+1] <- returns[,i] - predict(regs[[i]])
      }
    }
    names(regs) <- colnames(returns)

    if (residuals == TRUE) {
      result <- resids
    } else {
      result <- regs
    }
  }
  return(result)
}
wbach12/p9eventstudy documentation built on May 4, 2019, 7:43 p.m.