######################################################
# QQR Approach for Adrian
# Date: 03/26/2016
#######################################################

# set working directory for interactive run
dirname(getwd())

# load libraries
library(quantreg)
#Get the data
data = read.csv(file = "Data.csv")
S<-data$Stock
B<-data$Bond

# Apply QR and get the coefficents
taus<-seq(from = .05, to = .95, by = 0.05)
QR.coef <- coef(rq(S~B,tau=taus))
#Save estimates
write.table(QR.coef, file = "QR.csv", sep = ",", col.names = NA, qmethod = "double")

# Add QQR Function
lprq <-  function(x, y, h, m=19 , tau=.5)
  {
    xx <- seq(min(x),max(x),length=m)
    fv <- xx
    dv <- xx
    for(i in 1:length(xx)) {
      z <- x - xx[i]
      wx <- dnorm(z/h)
      r <- rq(y~z, weights=wx, tau=tau, ci=FALSE)
      fv[i] <- r$coef[1.]
      dv[i] <- r$coef[2.]
    }
    data.frame(dv = dv)
}

#Create a matrix to save the QQR estimates
QQR.coef <- as.data.frame(matrix(0, ncol = 19, nrow = 19))

# Run QQR in a loop and save estimates in matrix "QQR.coef"
#Note: 0.05 in below loop is the bandwidth that can be adjusted
for (i in 1:19){
  x<-lprq(B,S,0.05,tau=taus[i])
  QQR.coef[,i]<-x
}  

#Save the results
write.table(QQR.coef, file = "QQR.csv", sep = ",", col.names = NA, qmethod = "double")
