#Question 13 This question should be answered using the Weekly data set, which is part of the ISLR package. This data is similar in nature to the Smarket data from this chapter’s lab, except that it contains 1,089 weekly returns for 21 years, from the beginning of 1990 to the end of 2010.

library(pacman)
p_load(class, tidyverse,MASS, corrplot, kableExtra, ISLR2)
data("Weekly")
head(Weekly)
##   Year   Lag1   Lag2   Lag3   Lag4   Lag5    Volume  Today Direction
## 1 1990  0.816  1.572 -3.936 -0.229 -3.484 0.1549760 -0.270      Down
## 2 1990 -0.270  0.816  1.572 -3.936 -0.229 0.1485740 -2.576      Down
## 3 1990 -2.576 -0.270  0.816  1.572 -3.936 0.1598375  3.514        Up
## 4 1990  3.514 -2.576 -0.270  0.816  1.572 0.1616300  0.712        Up
## 5 1990  0.712  3.514 -2.576 -0.270  0.816 0.1537280  1.178        Up
## 6 1990  1.178  0.712  3.514 -2.576 -0.270 0.1544440 -1.372      Down

(a) Produce some numerical and graphical summaries of the Weekly data

summary(Weekly)
##       Year           Lag1               Lag2               Lag3         
##  Min.   :1990   Min.   :-18.1950   Min.   :-18.1950   Min.   :-18.1950  
##  1st Qu.:1995   1st Qu.: -1.1540   1st Qu.: -1.1540   1st Qu.: -1.1580  
##  Median :2000   Median :  0.2410   Median :  0.2410   Median :  0.2410  
##  Mean   :2000   Mean   :  0.1506   Mean   :  0.1511   Mean   :  0.1472  
##  3rd Qu.:2005   3rd Qu.:  1.4050   3rd Qu.:  1.4090   3rd Qu.:  1.4090  
##  Max.   :2010   Max.   : 12.0260   Max.   : 12.0260   Max.   : 12.0260  
##       Lag4               Lag5              Volume            Today         
##  Min.   :-18.1950   Min.   :-18.1950   Min.   :0.08747   Min.   :-18.1950  
##  1st Qu.: -1.1580   1st Qu.: -1.1660   1st Qu.:0.33202   1st Qu.: -1.1540  
##  Median :  0.2380   Median :  0.2340   Median :1.00268   Median :  0.2410  
##  Mean   :  0.1458   Mean   :  0.1399   Mean   :1.57462   Mean   :  0.1499  
##  3rd Qu.:  1.4090   3rd Qu.:  1.4050   3rd Qu.:2.05373   3rd Qu.:  1.4050  
##  Max.   : 12.0260   Max.   : 12.0260   Max.   :9.32821   Max.   : 12.0260  
##  Direction 
##  Down:484  
##  Up  :605  
##            
##            
##            
## 
corrplot(cor(Weekly[,-9]), method="square")

(b) Use the full data set to perform a logistic regression with Direction as the response and the five lag variables plus Volume as predictors.

attach(Weekly)
Weekly.fit<-glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data=Weekly,                       family=binomial)
summary(Weekly.fit)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Weekly)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -1.6949  -1.2565   0.9913   1.0849   1.4579  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.26686    0.08593   3.106   0.0019 **
## Lag1        -0.04127    0.02641  -1.563   0.1181   
## Lag2         0.05844    0.02686   2.175   0.0296 * 
## Lag3        -0.01606    0.02666  -0.602   0.5469   
## Lag4        -0.02779    0.02646  -1.050   0.2937   
## Lag5        -0.01447    0.02638  -0.549   0.5833   
## Volume      -0.02274    0.03690  -0.616   0.5377   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1496.2  on 1088  degrees of freedom
## Residual deviance: 1486.4  on 1082  degrees of freedom
## AIC: 1500.4
## 
## Number of Fisher Scoring iterations: 4

(c) Compute the confusion matrix and overall fraction of correct predictions. Explain what the confusion matrix is telling you about the types of mistakes made by logistic regression.

Wk.probs <- predict(Weekly.fit, type = "response")
Wk.probs[1:10]
##         1         2         3         4         5         6         7         8 
## 0.6086249 0.6010314 0.5875699 0.4816416 0.6169013 0.5684190 0.5786097 0.5151972 
##         9        10 
## 0.5715200 0.5554287
contrasts(Direction)
##      Up
## Down  0
## Up    1
Wk.pred <- rep("Down", length(Wk.probs))
Wk.pred[Wk.probs > .5] = "Up"
table(Wk.pred, Direction)
##        Direction
## Wk.pred Down  Up
##    Down   54  48
##    Up    430 557
(54 + 557) / length(Wk.probs)
## [1] 0.5610652
mean(Wk.pred == Direction)
## [1] 0.5610652

(d) Now fit the logistic regression model using a training data period from 1990 to 2008, with Lag2 as the only predictor. Compute the confusion matrix and the overall fraction of correct predictions for the held out data (that is, the data from 2009 and 2010).

train <- (Year < 2009)
Weekly.test <- Weekly[!train, ]
dim(Weekly.test)
## [1] 104   9
Direction.test <- Direction[!train]
Weekly.fit<-glm(Direction~Lag2, data=Weekly,family=binomial, subset=train)
logWeekly.prob= predict(Weekly.fit, Weekly.test, type = "response")
logWeekly.pred = rep("Down", length(logWeekly.prob))
logWeekly.pred[logWeekly.prob > 0.5] = "Up"
table(logWeekly.pred, Direction.test)
##               Direction.test
## logWeekly.pred Down Up
##           Down    9  5
##           Up     34 56
mean(logWeekly.pred == Direction.test)
## [1] 0.625

(e) Repeat (d) using LDA

library(MASS)
lda.fit <- lda(Direction ~ Lag2, data = Weekly,
               subset = train)
lda.fit
## Call:
## lda(Direction ~ Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
## 
## Coefficients of linear discriminants:
##            LD1
## Lag2 0.4414162
plot(lda.fit)

lda.pred <- predict(lda.fit, Weekly.test)
names(lda.pred)
## [1] "class"     "posterior" "x"
lda.class <- lda.pred$class
table(lda.class, Direction.test)
##          Direction.test
## lda.class Down Up
##      Down    9  5
##      Up     34 56
mean(lda.class == Direction.test)
## [1] 0.625

(f) Repeat (d) using QDA.

qda.fit <- qda(Direction ~ Lag2, data = Weekly,
               subset = train)
qda.fit
## Call:
## qda(Direction ~ Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##             Lag2
## Down -0.03568254
## Up    0.26036581
qda.class <- predict(qda.fit, Weekly.test)$class
table(qda.class, Direction.test)
##          Direction.test
## qda.class Down Up
##      Down    0  0
##      Up     43 61
mean(qda.class == Direction.test)
## [1] 0.5865385

(g) Repeat (d) using KNN with K = 1

Wk.train=as.matrix(Lag2[train])
Wk.test=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
knn.pred=knn(Wk.train,Wk.test,train.Direction,k=1)
table(knn.pred,Direction.test)
##         Direction.test
## knn.pred Down Up
##     Down   21 30
##     Up     22 31
mean(knn.pred == Direction.test)
## [1] 0.5

(h) Repeat (d) using naive Bayes

library(e1071)
nb.fit <- naiveBayes(Direction ~ Lag2, data = Weekly,
                     subset = train)
nb.fit
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Conditional probabilities:
##       Lag2
## Y             [,1]     [,2]
##   Down -0.03568254 2.199504
##   Up    0.26036581 2.317485
nb.class <- predict(nb.fit, Weekly.test)
table(nb.class, Direction.test)
##         Direction.test
## nb.class Down Up
##     Down    0  0
##     Up     43 61
mean(nb.class == Direction.test)
## [1] 0.5865385

(i) Which of these methods appears to provide the best results on this data?

print("The methods that have the highest accuracy rates are the Logistic Regression and Linear Discriminant Analysis; both having rates of 62.5%.")
## [1] "The methods that have the highest accuracy rates are the Logistic Regression and Linear Discriminant Analysis; both having rates of 62.5%."

(j) Experiment with different combinations of predictors, including possible transformations and interactions, for each of the methods. Report the variables, method, and associated confusion matrix that appears to provide the best results on the held out data. Note that you should also experiment with values for K in the KNN classifier.

We combine 2 variables: log 1 and log 2 to test

GLM method

Weekly.fit<-glm(Direction~ Lag1 + Lag2, data=Weekly,family=binomial, subset=train)
logWeekly.prob= predict(Weekly.fit, Weekly.test, type = "response")
logWeekly.pred = rep("Down", length(logWeekly.prob))
logWeekly.pred[logWeekly.prob > 0.5] = "Up"
table(logWeekly.pred, Direction.test)
##               Direction.test
## logWeekly.pred Down Up
##           Down    7  8
##           Up     36 53
mean(logWeekly.pred == Direction.test)
## [1] 0.5769231

lda

lda.fit <- lda(Direction ~ Lag1 + Lag2, data = Weekly,
               subset = train)
lda.fit
## Call:
## lda(Direction ~ Lag1 + Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##              Lag1        Lag2
## Down  0.289444444 -0.03568254
## Up   -0.009213235  0.26036581
## 
## Coefficients of linear discriminants:
##             LD1
## Lag1 -0.3013148
## Lag2  0.2982579
plot(lda.fit)

lda.pred <- predict(lda.fit, Weekly.test)
names(lda.pred)
## [1] "class"     "posterior" "x"
lda.class <- lda.pred$class
table(lda.class, Direction.test)
##          Direction.test
## lda.class Down Up
##      Down    7  8
##      Up     36 53
mean(lda.class == Direction.test)
## [1] 0.5769231

qda

qda.fit <- qda(Direction ~ Lag1 + Lag2, data = Weekly,
               subset = train)
qda.fit
## Call:
## qda(Direction ~ Lag1 + Lag2, data = Weekly, subset = train)
## 
## Prior probabilities of groups:
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Group means:
##              Lag1        Lag2
## Down  0.289444444 -0.03568254
## Up   -0.009213235  0.26036581
qda.class <- predict(qda.fit, Weekly.test)$class
table(qda.class, Direction.test)
##          Direction.test
## qda.class Down Up
##      Down    7 10
##      Up     36 51
mean(qda.class == Direction.test)
## [1] 0.5576923

knn (k=10)

Wk.train=as.matrix(Lag2[train])
Wk.test=as.matrix(Lag2[!train])
train.Direction =Direction[train]
set.seed(1)
knn.pred=knn(Wk.train,Wk.test,train.Direction,k=10)
table(knn.pred,Direction.test)
##         Direction.test
## knn.pred Down Up
##     Down   17 21
##     Up     26 40
mean(knn.pred == Direction.test)
## [1] 0.5480769

naive Bayes

nb.fit <- naiveBayes(Direction ~ Lag1 + Lag2, data = Weekly,
                     subset = train)
nb.fit
## 
## Naive Bayes Classifier for Discrete Predictors
## 
## Call:
## naiveBayes.default(x = X, y = Y, laplace = laplace)
## 
## A-priori probabilities:
## Y
##      Down        Up 
## 0.4477157 0.5522843 
## 
## Conditional probabilities:
##       Lag1
## Y              [,1]     [,2]
##   Down  0.289444444 2.211721
##   Up   -0.009213235 2.308387
## 
##       Lag2
## Y             [,1]     [,2]
##   Down -0.03568254 2.199504
##   Up    0.26036581 2.317485
nb.class <- predict(nb.fit, Weekly.test)
table(nb.class, Direction.test)
##         Direction.test
## nb.class Down Up
##     Down    3  8
##     Up     40 53
mean(nb.class == Direction.test)
## [1] 0.5384615