library(ISLR2)
## Warning: package 'ISLR2' was built under R version 4.2.3
Weekly = na.omit(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
# Question a: The summary of the weekly data
# Numerical
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  
##            
##            
##            
## 
# Graphical
library(corrplot)
## Warning: package 'corrplot' was built under R version 4.2.3
## corrplot 0.92 loaded
corrplot(cor(Weekly[,-9]), method="square")
title("Summary")

# Training&testing

library(dplyr)    
## Warning: package 'dplyr' was built under R version 4.2.3
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(ggplot2)   
## Warning: package 'ggplot2' was built under R version 4.2.3
library(rsample)   
library(tidyverse)
## Warning: package 'tidyverse' was built under R version 4.2.3
## Warning: package 'tibble' was built under R version 4.2.3
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ forcats   1.0.0     ✔ stringr   1.5.0
## ✔ lubridate 1.9.2     ✔ tibble    3.2.1
## ✔ purrr     1.0.1     ✔ tidyr     1.3.0
## ✔ readr     2.1.4
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag()    masks stats::lag()
## ℹ Use the ]8;;http://conflicted.r-lib.org/conflicted package]8;; to force all conflicts to become errors
library(caret) 
## Warning: package 'caret' was built under R version 4.2.3
## Loading required package: lattice
## 
## Attaching package: 'caret'
## 
## The following object is masked from 'package:purrr':
## 
##     lift
library(vip)
## Warning: package 'vip' was built under R version 4.2.3
## 
## Attaching package: 'vip'
## 
## The following object is masked from 'package:utils':
## 
##     vi
library(kknn)
## Warning: package 'kknn' was built under R version 4.2.3
## 
## Attaching package: 'kknn'
## 
## The following object is masked from 'package:caret':
## 
##     contr.dummy
set.seed(123) 
week_split <- initial_split(Weekly, prop = .7, strata ="Direction")
week_train <- training(week_split)
head(week_train)
##    Year   Lag1   Lag2  Lag3   Lag4   Lag5   Volume  Today Direction
## 2  1990 -0.270  0.816 1.572 -3.936 -0.229 0.148574 -2.576      Down
## 10 1990  1.253  0.041 0.807 -1.372  1.178 0.133635 -2.678      Down
## 11 1990 -2.678  1.253 0.041  0.807 -1.372 0.149024 -1.793      Down
## 17 1990  2.420 -0.017 0.750  4.022  2.820 0.172625 -1.225      Down
## 24 1990 -1.552  2.480 0.112  0.729 -2.061 0.166956 -2.259      Down
## 25 1990 -2.259 -1.552 2.480  0.112  0.729 0.171718 -2.428      Down
week_test  <- testing(week_split) 
head(week_test)
##    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
## 3  1990 -2.576 -0.270  0.816  1.572 -3.936 0.1598375  3.514        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
## 8  1990  0.807 -1.372  1.178  0.712  3.514 0.1323100  0.041        Up
## 12 1990 -1.793 -2.678  1.253  0.041  0.807 0.1357900  2.820        Up

``{r} # Question 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. Use the summary() function to print the results. Do any of the predictors appear to be statistically significant? If so,which ones?

model1 <-glm(Direction~Lag1+Lag2+Lag3+Lag4+Lag5+Volume, data=week_train,family=binomial)
summary(model1)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = week_train)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -2.0820  -1.2486   0.9596   1.0805   1.5091  
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)   
## (Intercept)  0.305306   0.102934   2.966  0.00302 **
## Lag1        -0.043377   0.030582  -1.418  0.15608   
## Lag2         0.035335   0.030947   1.142  0.25354   
## Lag3         0.004343   0.032683   0.133  0.89428   
## Lag4        -0.002149   0.033088  -0.065  0.94822   
## Lag5        -0.080433   0.033615  -2.393  0.01672 * 
## Volume      -0.042205   0.044740  -0.943  0.34552   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1045.5  on 760  degrees of freedom
## Residual deviance: 1034.7  on 754  degrees of freedom
## AIC: 1048.7
## 
## Number of Fisher Scoring iterations: 4
# Question 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.
predicted1 <- predict(model1, week_train)
predicted2 <- if_else(predicted1 > 0.5, "Up", "Down")
cross.tab1 <-table(week_train$Direction, predicted2)
cross.tab1
##       predicted2
##        Down  Up
##   Down  312  26
##   Up    373  50
# Question d: (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).
names (Weekly)
## [1] "Year"      "Lag1"      "Lag2"      "Lag3"      "Lag4"      "Lag5"     
## [7] "Volume"    "Today"     "Direction"
summary(Weekly$Year)
##    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
##    1990    1995    2000    2000    2005    2010
train = (Weekly$Year<2009)
weekly_test = Weekly[!train,]
Dir_test= Weekly$Direction[!train]
model2 <- glm(Direction~Lag2, data = Weekly, family = "binomial", 
             subset = train)
predicted3 <- predict(model2,weekly_test, type="response")
predicted4 = rep("Down", nrow(weekly_test))
predicted4[predicted3 > .5] = "Up"
table(predicted4, Dir_test)
##           Dir_test
## predicted4 Down Up
##       Down    9  5
##       Up     34 56
# Question e: Repeat (d) using LDA
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
## The following object is masked from 'package:ISLR2':
## 
##     Boston
model3 <- lda(Direction~Lag2, data = Weekly, family = "binomial", 
              subset = train)
model3
## Call:
## lda(Direction ~ Lag2, data = Weekly, family = "binomial", 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
predicted5 <- predict(model3, weekly_test)
predicted6 = predicted5$class
table(predicted6, Dir_test)
##           Dir_test
## predicted6 Down Up
##       Down    9  5
##       Up     34 56
# Question f: Repeat (d) using QDA.
model4 <- qda(Direction~Lag2, data = Weekly, family = "binomial", 
              subset = train)
predicted7 <- predict(model4, weekly_test)
predicted8 = predicted7$class
table(predicted8, Dir_test)
##           Dir_test
## predicted8 Down Up
##       Down    0  0
##       Up     43 61
# Question g: Repeat (d) using KNN with K = 1

train.X = as.matrix(Weekly$Lag2[train])
test.X = as.matrix(Weekly$Lag2[!train])

train.Direction = Weekly$Direction[train]

summary(Weekly$Direction[train])
## Down   Up 
##  441  544
library("naivebayes")
## Warning: package 'naivebayes' was built under R version 4.2.3
## naivebayes 0.9.7 loaded
model6 <- naive_bayes(Direction ~ Lag1, data = Weekly, family = "binomial", 
                     subset = train)
predicted10 <- predict(model6, weekly_test)
## Warning: predict.naive_bayes(): more features in the newdata are provided as
## there are probability tables in the object. Calculation is performed based on
## features to be found in the tables.
predicted11 <- if_else(predicted10 > 0.5, "Up", "Down")
## Warning in Ops.factor(predicted10, 0.5): '>' not meaningful for factors
cross.tab6 <-table(weekly_test$Direction, predicted11)
cross.tab6
## < table of extent 2 x 0 >