In the package quantreg
one can perform a penalized quantile regression. Selecting the variables that were deemed statistically significant is "easy". However, when I considered applying a restrain to the coefficients: i.e some to be strictly positive/negative (otherwise they will be zero), I just couldn't figure out how it was done! The code i have so far is this:
quant<-c(0.4,0.5,0.6)
for (t in 400:600){ #the first 400 rows are the trainset, the remaining the test set. In each iteration
x=X[1:399,] #we increase the trainset by 1row and use it to predict for the next.
y=Y[1:399]
for (i in 1:quant) {
eq=rqss(y~x,method="lasso",tau=quant[i],lambda=lambdas) #find the significant variable though a Lasso quantile.
s=summary(eq)
findsigPV=s$coef[2:28,4] #select the stat. significant coefficient/variable
selectedPV=findsigPV<=0.05
if (sum(selectedPV)==0){
SelectedPV=rank(findsigPV)==1
}
newx=as.matrix(subset(X[1:t,],select=which(selectedPV))) #new matrix with the selected variable
eq=rq(y~newx[1:(t-1),],tau=quant[i]) #applies the new q. regression with the selected coeff from the lasso
pr[t-400+1,i]=c(1,newx[t,])%*%eq$coef #saves the forecast
}
}
I fear that this problem is very obvious. I had considered using ifelse(eq$coef<0,0,eq$coef)
but given that a few variables are restrained either positive or negative that wasn't the ideal solution. Any ideas?
EDIT: Something I forgot to include, is that each iteration selects a (maybe) different variable(s) than the previous iteration!
Adding
j=2
for (k in 1:23){
if (II[k]){
if (k <=12){ #positive constraint to the first 12 variables lets say
if (eq$coeff[j] <0){
eq$coeff[j] =0}
j=j+1}
if (k > 12){ #negative constraint to the remaining ones
if (eq$coeff[j] >0){
eq$coeff[j] =0}
j=j+1}
}
}
print(eq$coeff)
right before the predictions are made, solves the issue.