## 1. First, install the devtools package using the RStudio drop-down menu:
## RStudio > Tools > Install Packages > devtools.

## 2. Install all packages that are arguments of library(pkgName) below with:
## RStudio > Tools > Install Packages > pkgName.

# Unfortunately, almost every single plot or table in this chapter must be 
# generated manually, as the underlying data cannot be distributed with the
# PCRA package. Even so, the last code segment regenerates Figure 1.6 with
# the smaller PCRA dataset.

## Load all the packages needed for Chapter 1
library(PCRA)
library(data.table) 
library(RobStatTM)
library(tidyr)
library(xts)
library(hexbin)
library(lattice)
library(rstudioapi)

# NOTE:  When loading packages, you can safely ignore the various comments 
# that appear in the console in red after each package is loaded, including, 
# but not limited to: "method overwritten", "using 6 threads", 
# "object is masked", etc. etc.

## 3. Finally, in RStudio select:
## Session > Set Working Directory > To Source File Location
## This makes the folder where you saved the demo script the R working directory
##
## Later, when you have more experience with the demo, you can set the working
## directory automatically using the rstudioapi library and run the entire file
## file by clicking on the Source button at the top right of the Source pane. 
## To do so, first uncomment the two lines that obtain the current path and set 
## the working directory using rstudioapi::getActiveDocumentContext()$path, 
## as well as the lines before  the Functions section that start with 
## writelines(..., then click on Source at the top right of the active document pane


# You are now ready to run Ch 1 Introduction Demo.R

# Set the working directory automatically using the rstudioapi library
# when sourcing the entire file
# current_path <- rstudioapi::getActiveDocumentContext()$path 
# setwd(dirname(current_path ))

# Figures 1.1 - 1.5 and Tables 1.1 - 1.3
## writeLines("Data needed to reproduce Figures 1.1 - 1.5 and Tables 1.1 - 1.3")
## writeLines("must be downloaded manually from various sources.")
## writeLines("Instruction are provided in Section 1.10 of Chapter 1\n\n")

# Figure 1.6
## writeLines("Least Squares vs. Robust Estimates of a Beta Coefficient for OFG Using Weekly Returns, 2009-2010")
PCRA::plotLSandRobustSFM(retOFG)

## writeLines("Figure 1.7 was generated by the authors using a CRSP dataset")
## writeLines("that they are not permitted to distribute. However, we can")
## writeLines("generate a simpler version of Figure 1.7 using the data in PCRA")
## 1. You will see Returns * 100 in multiple places, as returns are stored as decimals
##    but treated as percents. If you want returns as a decimal, remove * 100 everywhere
## 2. to adjust the location of the legend, change corner = c(0.95, 0.95)

############################ Functions #########################################
pltFunc_hexbin <- function(data, variable, efficiency = 0.95, cropping = list(),
                           pdf_fn = NULL, nbins = 25, ...) {
  
  upper <- lmrobdet.control(efficiency = efficiency)$tuning.psi[["upper"]]
  
  months_to_print = unique(stocksDat$Date)
  for (mth in months_to_print) {
    print(as.Date(mth))
    
    # Get the data for this month
    mth_data <- drop_na(stocksDat[stocksDat$Date == mth, ])
    
    # Do OLS and robust regressions for returns vs. Size. Returns are stored
    # as a decimal, so scale them by 100 to treat them as percentages
    OLSfit <- lm(formula = Return * 100 ~ Size, data = mth_data)
    ROBfit <- lmrobdetMM(formula = Return * 100 ~ Size, data = mth_data)
    
    # Extract the coefficients from the summary, then create a vector with 
    # intercept, t(intercept), slope, t(slope) and scale (for robust regression)
    # Do it this way not for any fundamental advantage, but to stay consistent 
    # with Dan Xia's estimates_size.rda which was used to generate Figure 1.6
    linear <- as.data.frame(summary(OLSfit)[4])
    linear <- c(linear[1, 1], linear[1, 3], linear[2, 1], linear[2, 3])
    
    robust <- as.data.frame(summary(ROBfit)[9])
    robust <- c(robust[1, 1], robust[1, 3], robust[2, 1], robust[2, 3], ROBfit$scale)
    
    # outlier boundaries and percent of observations rejected by lmrobdetMM
    ar <- upper * ROBfit$scale
    pct_rejected <- get_pct_rejected(mth_data, variable, ar,  robust[1], robust[3])
    
    # crop outliers on the x and y axes if desired
    cropped_data <- crop(mth_data, variable, cropping)
    mth_data     <- cropped_data$data
    
    # add a little space at the top for the legend
    ylim <- range(mth_data$Return * 100, finite=TRUE)
    ylim <- c(ylim[1], ylim[2] + (ylim[2] - ylim[1]) * 0.125)
    
    # create the hexbins and also the grayscale used to color them
    hb <-  hexbin(mth_data[[variable]], mth_data$Return * 100, xbins = nbins, shape = 1,
                  xbnds = range(mth_data[[variable]], finite=T), ybnds = ylim)
    countF  <- as.factor(hb@count)
    lvl     <- length(levels(countF))
    palette <- grey(seq(0.7,0.1,length=lvl))[as.numeric(countF)]
    
    # create and position the legend and title
    key <-  list(corner = c(0.95, 0.95), # background = "gray97", #space = "right", 
                 lines = list(col = c(4, 2, 1), lty = c(1, 2, 3), lwd = 1.5) ,
                 text  = list(c(paste("Robust (lmrobdetMM) Slope:  ", round(robust[3], 2), 
                                      paste("(", round(robust[4], 2), ")", sep = "")),
                                paste("Classical (OLS) Slope:         ", round(linear[3], 2), 
                                      paste("(", round(linear[4], 2),")",  sep = "")),
                                paste("Rejected Outliers:  ", 
                                      round(pct_rejected$pos, 2), "% (+)  / ", 
                                      round(pct_rejected$neg, 2), "% (-)", sep = "") ), cex=1), 
                 padding.text=2.5 )
    
    main <- paste("Return vs. ln(Market Capitalization)", 
                  "\n Robust mOpt", efficiency * 100, " vs LS: ", as.Date(mth))
    
    # Now create the hexbin plot and print it to the pdf file
    hex <- hexbinplot(as.formula(paste("Return * 100 ~", "Size")), data=mth_data,
                      aspect="1", xbins=nbins, style = "centroids", 
                      minarea = 0.1, maxarea = 0.9,
                      pen = palette, 
                      border = rgb(1,1,1),
                      # ylim = ylim,
                      # maxcnt = max(hb@count),
                      
                      prepanel = function(x, y, type = character(0),...) {
                        if('tmd'%in%type){
                          tmp <- x
                          x   <- (y + x) / sqrt(2)
                          y   <- (y - tmp) / sqrt(2)
                        }
                        ans <-list(xlim = range(x, finite = TRUE),
                                   ylim = ylim,
                                   dx = IQR(x,na.rm=TRUE),
                                   dy = IQR(y,na.rm=TRUE))
                      },
                      
                      panel = function(x, y, ...){
                        panel.hexbinplot(x, y, ...)
                        
                        # linear and robust regression lines
                        panel.abline(a = linear[1], b = linear[3], col=2, lwd = 2, lty=2)
                        panel.abline(a = robust[1], b = robust[3], col=4, lwd = 2)
                        
                        # outliers boundaries 
                        panel.abline(a = robust[1] + ar, b = robust[3], lty = 3, lwd = 2.5)
                        panel.abline(a = robust[1] - ar, b = robust[3], lty = 3, lwd = 2.5)
                        
                        # Add a horizontal line if required
                        #panel.abline(h = 0, lty = 1, col = gray(0.3))
                      },
                      
                      main = main, key = key,
                      xlab = "Size = ln(Market Capitalization)", ylab = "Return(%)", colorkey = FALSE, ...)
    print(hex)
  }
}

crop <- function(data, variable, cropping) {
  # Cropping type = h for X axis, v for Y axis, hv for both axes
  type  <- cropping$type
  xcrop <- cropping$xcrop
  ycrop <- cropping$ycrop
  if (is.null(type)) {
    type <- ""
  }
  qx <- NULL
  
  if (grepl("h", type)) {
    if (length(xcrop) == 1) {
      qx <- quantile(data[[variable]], c(xcrop, 1-xcrop), na.rm = TRUE)
    } else if (length(xcrop) == 2) {
      qx <- xcrop
    } else {
      stop("xcrop must be length of 1 or 2")
    }
  }
  
  if (grepl("v", type)) {
    if (length(ycrop) == 1) {
      qy <- quantile(data$Return, c(ycrop, 1-ycrop), na.rm = TRUE)
    } else if (length(xcrop) == 2) {
      qy <- ycrop
    } else {
      stop("ycrop must be length of 1 or 2")
    }
  }
  
  if (grepl("h", type)) {
    data <- data[ data[[variable]] > qx[[1]] & data[[variable]] < qx[[2]] ,]
  }
  if (grepl("v", type)) {
    data <- data[ data$Return > qy[[1]] & data$Return < qy[[2]] ,]
  }
  
  cropped_data <- list(data = data, qx = qx)
  return(cropped_data)
}


get_pct_rejected <- function(data, variable, ar, intercept, slope) {
  # Find the fraction of points rejected by lmrobdetMM
  pos_pct_rejected <- sum(data$Return * 100 > intercept + slope * data[[variable]] + ar) / dim(data)[1]
  neg_pct_rejected <- sum(data$Return * 100 < intercept + slope * data[[variable]] - ar) / dim(data)[1]
  pct_rejected     <- list(pos = pos_pct_rejected * 100, neg = neg_pct_rejected * 100)
  
  return(pct_rejected)
}


############################Main Section#######################################
# Print the arguments for the PCRA function selectCRSPandSPGMI along with its defaults
# args(selectCRSPandSPGMI)

# Endpoints of range of months we want to plot. 
# c(1, 276) plots them all, c(200, 200) plots August 2009
BEGIN_END <- c(200, 200)

# Get Tickers, Returns and Size = Log Market Cap from the CRSP and SPGMI databases
stockItems  <- c("Date", "TickerLast", "Return")
factorItems <- c("LogMktCap")
dateRange   <- unique(stocksCRSPmonthly[ , Date])[BEGIN_END]

stocksDat   <- selectCRSPandSPGMI("monthly",
                                  dateRange   = dateRange, 
                                  stockItems  = stockItems, 
                                  factorItems = factorItems,
                                  outputType  = "data.table")

# Rename LogMktCap to Size
data.table::setnames(stocksDat, old = c("LogMktCap"),
                                new = c("Size"))

# Finally generate a pdf file with the hexbin plot(s)
pltFunc_hexbin(stocksDat, "Size", pdf_fn = OUT_FN, nbins = 30, 
               cropping = list(type = "hv", xcrop = 0.000, ycrop = 0.000))



