R Markdown

# Load required libraries
library(ISLR)

# Load the Smarket dataset
data(Smarket)

## Examining the data

# View variable names and data types
str(Smarket)
## 'data.frame':    1250 obs. of  9 variables:
##  $ Year     : num  2001 2001 2001 2001 2001 ...
##  $ Lag1     : num  0.381 0.959 1.032 -0.623 0.614 ...
##  $ Lag2     : num  -0.192 0.381 0.959 1.032 -0.623 ...
##  $ Lag3     : num  -2.624 -0.192 0.381 0.959 1.032 ...
##  $ Lag4     : num  -1.055 -2.624 -0.192 0.381 0.959 ...
##  $ Lag5     : num  5.01 -1.055 -2.624 -0.192 0.381 ...
##  $ Volume   : num  1.19 1.3 1.41 1.28 1.21 ...
##  $ Today    : num  0.959 1.032 -0.623 0.614 0.213 ...
##  $ Direction: Factor w/ 2 levels "Down","Up": 2 2 1 2 2 2 1 2 2 2 ...
# Display number of objects and data type for each variable
summary(Smarket)
##       Year           Lag1                Lag2                Lag3          
##  Min.   :2001   Min.   :-4.922000   Min.   :-4.922000   Min.   :-4.922000  
##  1st Qu.:2002   1st Qu.:-0.639500   1st Qu.:-0.639500   1st Qu.:-0.640000  
##  Median :2003   Median : 0.039000   Median : 0.039000   Median : 0.038500  
##  Mean   :2003   Mean   : 0.003834   Mean   : 0.003919   Mean   : 0.001716  
##  3rd Qu.:2004   3rd Qu.: 0.596750   3rd Qu.: 0.596750   3rd Qu.: 0.596750  
##  Max.   :2005   Max.   : 5.733000   Max.   : 5.733000   Max.   : 5.733000  
##       Lag4                Lag5              Volume           Today          
##  Min.   :-4.922000   Min.   :-4.92200   Min.   :0.3561   Min.   :-4.922000  
##  1st Qu.:-0.640000   1st Qu.:-0.64000   1st Qu.:1.2574   1st Qu.:-0.639500  
##  Median : 0.038500   Median : 0.03850   Median :1.4229   Median : 0.038500  
##  Mean   : 0.001636   Mean   : 0.00561   Mean   :1.4783   Mean   : 0.003138  
##  3rd Qu.: 0.596750   3rd Qu.: 0.59700   3rd Qu.:1.6417   3rd Qu.: 0.596750  
##  Max.   : 5.733000   Max.   : 5.73300   Max.   :3.1525   Max.   : 5.733000  
##  Direction 
##  Down:602  
##  Up  :648  
##            
##            
##            
## 
# Calculate and display five-number summary for numeric variables
summary(Smarket[, -9])
##       Year           Lag1                Lag2                Lag3          
##  Min.   :2001   Min.   :-4.922000   Min.   :-4.922000   Min.   :-4.922000  
##  1st Qu.:2002   1st Qu.:-0.639500   1st Qu.:-0.639500   1st Qu.:-0.640000  
##  Median :2003   Median : 0.039000   Median : 0.039000   Median : 0.038500  
##  Mean   :2003   Mean   : 0.003834   Mean   : 0.003919   Mean   : 0.001716  
##  3rd Qu.:2004   3rd Qu.: 0.596750   3rd Qu.: 0.596750   3rd Qu.: 0.596750  
##  Max.   :2005   Max.   : 5.733000   Max.   : 5.733000   Max.   : 5.733000  
##       Lag4                Lag5              Volume           Today          
##  Min.   :-4.922000   Min.   :-4.92200   Min.   :0.3561   Min.   :-4.922000  
##  1st Qu.:-0.640000   1st Qu.:-0.64000   1st Qu.:1.2574   1st Qu.:-0.639500  
##  Median : 0.038500   Median : 0.03850   Median :1.4229   Median : 0.038500  
##  Mean   : 0.001636   Mean   : 0.00561   Mean   :1.4783   Mean   : 0.003138  
##  3rd Qu.: 0.596750   3rd Qu.: 0.59700   3rd Qu.:1.6417   3rd Qu.: 0.596750  
##  Max.   : 5.733000   Max.   : 5.73300   Max.   :3.1525   Max.   : 5.733000
# Calculate correlation coefficients for all pairs of variables
cor(Smarket[,-9])
##              Year         Lag1         Lag2         Lag3         Lag4
## Year   1.00000000  0.029699649  0.030596422  0.033194581  0.035688718
## Lag1   0.02969965  1.000000000 -0.026294328 -0.010803402 -0.002985911
## Lag2   0.03059642 -0.026294328  1.000000000 -0.025896670 -0.010853533
## Lag3   0.03319458 -0.010803402 -0.025896670  1.000000000 -0.024051036
## Lag4   0.03568872 -0.002985911 -0.010853533 -0.024051036  1.000000000
## Lag5   0.02978799 -0.005674606 -0.003557949 -0.018808338 -0.027083641
## Volume 0.53900647  0.040909908 -0.043383215 -0.041823686 -0.048414246
## Today  0.03009523 -0.026155045 -0.010250033 -0.002447647 -0.006899527
##                Lag5      Volume        Today
## Year    0.029787995  0.53900647  0.030095229
## Lag1   -0.005674606  0.04090991 -0.026155045
## Lag2   -0.003557949 -0.04338321 -0.010250033
## Lag3   -0.018808338 -0.04182369 -0.002447647
## Lag4   -0.027083641 -0.04841425 -0.006899527
## Lag5    1.000000000 -0.02200231 -0.034860083
## Volume -0.022002315  1.00000000  0.014591823
## Today  -0.034860083  0.01459182  1.000000000
# Plot volume over time
plot(Smarket$Year, Smarket$Volume)

## Logistic regression model (Scenario 1: Same data for training and testing)

# Fit the logistic regression model
glm.fit1 <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,
                data = Smarket, family = binomial)

# Display model summary
summary(glm.fit1)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Smarket)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.126000   0.240736  -0.523    0.601
## Lag1        -0.073074   0.050167  -1.457    0.145
## Lag2        -0.042301   0.050086  -0.845    0.398
## Lag3         0.011085   0.049939   0.222    0.824
## Lag4         0.009359   0.049974   0.187    0.851
## Lag5         0.010313   0.049511   0.208    0.835
## Volume       0.135441   0.158360   0.855    0.392
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1731.2  on 1249  degrees of freedom
## Residual deviance: 1727.6  on 1243  degrees of freedom
## AIC: 1741.6
## 
## Number of Fisher Scoring iterations: 3
# Predict probabilities of the market going up
glm.probs1 <- predict(glm.fit1, type = "response")

# Convert probabilities to class labels
glm.pred1 <- rep("Down", 1250)
glm.pred1[glm.probs1 > 0.5] <- "Up"

# Create and display confusion matrix
cm1 <- table(glm.pred1, Smarket$Direction)
print(cm1)
##          
## glm.pred1 Down  Up
##      Down  145 141
##      Up    457 507
# Calculate accuracy and error rate
correct1 <- (cm1[1,1] + cm1[2,2]) / sum(cm1)
error1 <- 1 - correct1

## Logistic regression model - Scenario 1 (Same data for training and testing)

# Fit the logistic regression model
glm.fit1 <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,
                data = Smarket, family = binomial)

# Display model summary
summary(glm.fit1)
## 
## Call:
## glm(formula = Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + 
##     Volume, family = binomial, data = Smarket)
## 
## Coefficients:
##              Estimate Std. Error z value Pr(>|z|)
## (Intercept) -0.126000   0.240736  -0.523    0.601
## Lag1        -0.073074   0.050167  -1.457    0.145
## Lag2        -0.042301   0.050086  -0.845    0.398
## Lag3         0.011085   0.049939   0.222    0.824
## Lag4         0.009359   0.049974   0.187    0.851
## Lag5         0.010313   0.049511   0.208    0.835
## Volume       0.135441   0.158360   0.855    0.392
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 1731.2  on 1249  degrees of freedom
## Residual deviance: 1727.6  on 1243  degrees of freedom
## AIC: 1741.6
## 
## Number of Fisher Scoring iterations: 3
# Predict probabilities of the market going up
glm.probs1 <- predict(glm.fit1, type = "response")

# Convert probabilities to class labels
glm.pred1 <- rep("Down", 1250)
glm.pred1[glm.probs1 > 0.5] <- "Up"

# Create and display confusion matrix
cm1 <- table(glm.pred1, Smarket$Direction)
print(cm1)
##          
## glm.pred1 Down  Up
##      Down  145 141
##      Up    457 507
# Calculate accuracy and error rate
correct1 <- (cm1[1,1] + cm1[2,2]) / sum(cm1)
error1 <- 1 - correct1

# Display coefficients
coef(glm.fit1)
##  (Intercept)         Lag1         Lag2         Lag3         Lag4         Lag5 
## -0.126000257 -0.073073746 -0.042301344  0.011085108  0.009358938  0.010313068 
##       Volume 
##  0.135440659
## Logistic regression model - Scenario 2 (Separate training and testing sets)

# Define year range for training data
train <- (Smarket$Year < 2005)

# Split data into training and testing sets
Smarket.2005 <- Smarket[!train,]

# Fit the model using training data
glm.fit2 <- glm(Direction ~ Lag1 + Lag2 + Lag3 + Lag4 + Lag5 + Volume,
                data = Smarket, family = binomial, subset = train)

# Predict probabilities for testing data
glm.probs2 <- predict(glm.fit2, Smarket.2005, type = "response")

# Convert probabilities to class labels for testing data
glm.pred2 <- rep("Down", 252)
glm.pred2[glm.probs2 > 0.5] <- "Up"

# Create and display confusion matrix for testing data
cm2 <- table(glm.pred2, Smarket.2005$Direction)
print(cm2)
##          
## glm.pred2 Down Up
##      Down   77 97
##      Up     34 44
# Calculate accuracy and error rate for testing data
correct2 <- (cm2[1,1] + cm2[2,2]) / sum(cm2)
error2 <- 1 - correct2

## Display results

# Print accuracy and error rates for both scenarios
cat("Scenario 1 Accuracy:", correct1, "\n")
## Scenario 1 Accuracy: 0.5216
cat("Scenario 1 Error Rate:", error1, "\n\n")
## Scenario 1 Error Rate: 0.4784
cat("Scenario 2 Accuracy:", correct2, "\n")
## Scenario 2 Accuracy: 0.4801587
cat("Scenario 2 Error Rate:", error2, "\n")
## Scenario 2 Error Rate: 0.5198413
# Print model coefficients for both scenarios
print("Coefficients for Scenario 1:")
## [1] "Coefficients for Scenario 1:"
coef(glm.fit1)
##  (Intercept)         Lag1         Lag2         Lag3         Lag4         Lag5 
## -0.126000257 -0.073073746 -0.042301344  0.011085108  0.009358938  0.010313068 
##       Volume 
##  0.135440659
print("Coefficients for Scenario 2:")
## [1] "Coefficients for Scenario 2:"
coef(glm.fit2)
##  (Intercept)         Lag1         Lag2         Lag3         Lag4         Lag5 
##  0.191212621 -0.054178292 -0.045805334  0.007200118  0.006440875 -0.004222672 
##       Volume 
## -0.116256960