Stock Data Analysis

This report presents a comprehensive analysis of stock data for Apple, Nvidia, and Tesla from 2010 to 2024.

Required Libraries

Loading necessary R libraries for the analysis.

library(quantmod)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(dplyr)
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:xts':
## 
##     first, last
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(xts)
library(fredr)
library(TTR)

Fetching Stock Data

Retrieving stock data from Yahoo Finance.

# Apple, Nvidia, and Tesla stock data from Yahoo Finance
getSymbols("AAPL", src = "yahoo", from = "2010-01-01", to = "2024-01-01")
## [1] "AAPL"
getSymbols("NVDA", src = "yahoo", from = "2010-01-01", to = "2024-01-01")
## [1] "NVDA"
getSymbols("TSLA", src = "yahoo", from = "2010-01-01", to = "2024-01-01")
## [1] "TSLA"
stock_data_Apple <- AAPL
stock_data_nvda <- NVDA
stock_data_tsla <- TSLA

Preview of Stock Data

Displaying the first few rows of the fetched stock data for Apple, Nvidia, and Tesla.

head(stock_data_Apple)
##            AAPL.Open AAPL.High AAPL.Low AAPL.Close AAPL.Volume AAPL.Adjusted
## 2010-01-04  7.622500  7.660714 7.585000   7.643214   493729600      6.470741
## 2010-01-05  7.664286  7.699643 7.616071   7.656429   601904800      6.481928
## 2010-01-06  7.656429  7.686786 7.526786   7.534643   552160000      6.378825
## 2010-01-07  7.562500  7.571429 7.466071   7.520714   477131200      6.367033
## 2010-01-08  7.510714  7.571429 7.466429   7.570714   447610800      6.409362
## 2010-01-11  7.600000  7.607143 7.444643   7.503929   462229600      6.352822
head(stock_data_nvda)
##            NVDA.Open NVDA.High NVDA.Low NVDA.Close NVDA.Volume NVDA.Adjusted
## 2010-01-04    4.6275    4.6550   4.5275     4.6225    80020400      4.240230
## 2010-01-05    4.6050    4.7400   4.6050     4.6900    72864800      4.302147
## 2010-01-06    4.6875    4.7300   4.6425     4.7200    64916800      4.329666
## 2010-01-07    4.6950    4.7150   4.5925     4.6275    54779200      4.244816
## 2010-01-08    4.5900    4.6700   4.5625     4.6375    47816800      4.253990
## 2010-01-11    4.6625    4.6825   4.5075     4.5725    55661200      4.194364
head(stock_data_tsla)
##            TSLA.Open TSLA.High TSLA.Low TSLA.Close TSLA.Volume TSLA.Adjusted
## 2010-06-29  1.266667  1.666667 1.169333   1.592667   281494500      1.592667
## 2010-06-30  1.719333  2.028000 1.553333   1.588667   257806500      1.588667
## 2010-07-01  1.666667  1.728000 1.351333   1.464000   123282000      1.464000
## 2010-07-02  1.533333  1.540000 1.247333   1.280000    77097000      1.280000
## 2010-07-06  1.333333  1.333333 1.055333   1.074000   103003500      1.074000
## 2010-07-07  1.093333  1.108667 0.998667   1.053333   103825500      1.053333

Analysis of Apple Stock

Detailed analysis of financial indicators for Apple stock using the TTR library.

Computing Financial Indicators for Apple

sma <- SMA(Cl(stock_data_Apple), n=20)
ema <- EMA(Cl(stock_data_Apple), n=20)
rsi <- RSI(Cl(stock_data_Apple), n=14)
macd <- MACD(Cl(stock_data_Apple), nFast=12, nSlow=26, nSig=9)
obv <- OBV(Cl(stock_data_Apple), Vo(stock_data_Apple))
combined_data_Apple <- merge(stock_data_Apple, sma, ema, rsi, macd, obv)
combined_data_Apple_df <- data.frame(date=index(combined_data_Apple), coredata(combined_data_Apple))
combined_data_Apple_df$AAPL.High <- NULL
combined_data_Apple_df$AAPL.Low <- NULL
combined_data_Apple_df$AAPL.Open <- NULL
combined_data_Apple_df$AAPL.Adjusted <- NULL
head(combined_data_Apple_df)
##         date AAPL.Close AAPL.Volume SMA EMA rsi macd signal        obv
## 1 2010-01-04   7.643214   493729600  NA  NA  NA   NA     NA  493729600
## 2 2010-01-05   7.656429   601904800  NA  NA  NA   NA     NA 1095634400
## 3 2010-01-06   7.534643   552160000  NA  NA  NA   NA     NA  543474400
## 4 2010-01-07   7.520714   477131200  NA  NA  NA   NA     NA   66343200
## 5 2010-01-08   7.570714   447610800  NA  NA  NA   NA     NA  513954000
## 6 2010-01-11   7.503929   462229600  NA  NA  NA   NA     NA   51724400

Preparing Data for Modeling-Apple

Creating the target variable Price_Movement and preprocessing data for Apple stock.

combined_data_Apple_df <- combined_data_Apple_df %>%
  mutate(Next_Close = lead(AAPL.Close),
         Price_Movement = ifelse(Next_Close > AAPL.Close, 1, 0))
combined_data_Apple_df <- na.omit(combined_data_Apple_df)

Analysis of Nividia Stock

Repeating the analysis process for Nvidia stock.

Computing Financial Indicators for Apple

sma <- SMA(Cl(stock_data_nvda), n=20)
ema <- EMA(Cl(stock_data_nvda), n=20)
rsi <- RSI(Cl(stock_data_nvda), n=14)
macd <- MACD(Cl(stock_data_nvda), nFast=12, nSlow=26, nSig=9)
obv <- OBV(Cl(stock_data_nvda), Vo(stock_data_nvda))
combined_data_nvda <- merge(stock_data_nvda, sma, ema, rsi, macd, obv)

combined_data_nvda_df <- data.frame(date=index(combined_data_nvda), coredata(combined_data_nvda))
combined_data_nvda_df$NVDA.High <- NULL
combined_data_nvda_df$NVDA.Low <- NULL
combined_data_nvda_df$NVDA.Open <- NULL
combined_data_nvda_df$NVDA.Adjusted <- NULL
head(combined_data_nvda_df)
##         date NVDA.Close NVDA.Volume SMA EMA rsi macd signal       obv
## 1 2010-01-04     4.6225    80020400  NA  NA  NA   NA     NA  80020400
## 2 2010-01-05     4.6900    72864800  NA  NA  NA   NA     NA 152885200
## 3 2010-01-06     4.7200    64916800  NA  NA  NA   NA     NA 217802000
## 4 2010-01-07     4.6275    54779200  NA  NA  NA   NA     NA 163022800
## 5 2010-01-08     4.6375    47816800  NA  NA  NA   NA     NA 210839600
## 6 2010-01-11     4.5725    55661200  NA  NA  NA   NA     NA 155178400

Preparing Data for Modeling-Nividia

Creating the target variable Price_Movement and preprocessing data for Nividia stock.

combined_data_nvda_df <- combined_data_nvda_df %>%
  mutate(Next_Close = lead(NVDA.Close),
         Price_Movement = ifelse(Next_Close > NVDA.Close, 1, 0))

combined_data_nvda_df <- na.omit(combined_data_nvda_df)

Analysis of Tesla Stock

Conducting similar analysis for Tesla stock.

Computing Financial Indicators for Tesla

sma <- SMA(Cl(stock_data_tsla), n=20)
ema <- EMA(Cl(stock_data_tsla), n=20)
rsi <- RSI(Cl(stock_data_tsla), n=14)
macd <- MACD(Cl(stock_data_tsla), nFast=12, nSlow=26, nSig=9)
obv <- OBV(Cl(stock_data_tsla), Vo(stock_data_tsla))
combined_data_tsla <- merge(stock_data_tsla, sma, ema, rsi, macd, obv)

combined_data_tsla_df <- data.frame(date=index(combined_data_tsla), coredata(combined_data_tsla))
combined_data_tsla_df$TSLA.High <- NULL
combined_data_tsla_df$TSLA.Low <- NULL
combined_data_tsla_df$TSLA.Open <- NULL
combined_data_tsla_df$TSLA.Adjusted <- NULL
head(combined_data_tsla_df)
##         date TSLA.Close TSLA.Volume SMA EMA rsi macd signal        obv
## 1 2010-06-29   1.592667   281494500  NA  NA  NA   NA     NA  281494500
## 2 2010-06-30   1.588667   257806500  NA  NA  NA   NA     NA   23688000
## 3 2010-07-01   1.464000   123282000  NA  NA  NA   NA     NA  -99594000
## 4 2010-07-02   1.280000    77097000  NA  NA  NA   NA     NA -176691000
## 5 2010-07-06   1.074000   103003500  NA  NA  NA   NA     NA -279694500
## 6 2010-07-07   1.053333   103825500  NA  NA  NA   NA     NA -383520000

Preparing Data for Modeling-Tesla

Creating the target variable Price_Movement and preprocessing data for Tesla stock.

combined_data_tsla_df <- combined_data_tsla_df %>%
  mutate(Next_Close = lead(TSLA.Close),
         Price_Movement = ifelse(Next_Close > TSLA.Close, 1, 0))

combined_data_tsla_df <- na.omit(combined_data_tsla_df)

Viewing the Prepared Datasets

After processing and merging the financial indicators, the datasets for each company are now ready for analysis.

Apple Stock Combined Dataset

Preview of the processed data for Apple stock:

head(combined_data_Apple_df)
##          date AAPL.Close AAPL.Volume      SMA      EMA      rsi       macd
## 34 2010-02-22   7.157857   390563600 7.108964 7.190744 46.78058 -1.2198023
## 35 2010-02-23   7.037857   575094800 7.098232 7.176183 42.66471 -1.2600488
## 36 2010-02-24   7.166429   460566400 7.088804 7.175254 47.94888 -1.1340106
## 37 2010-02-25   7.214286   665126000 7.078304 7.178971 49.80332 -0.9689520
## 38 2010-02-26   7.307857   507460800 7.087821 7.191246 53.30619 -0.7245216
## 39 2010-03-01   7.463929   550093600 7.118054 7.217216 58.50723 -0.3523378
##       signal        obv Next_Close Price_Movement
## 34 -2.126551 2770454400   7.037857              0
## 35 -1.953251 2195359600   7.166429              1
## 36 -1.789403 2655926000   7.214286              1
## 37 -1.625312 3321052000   7.307857              1
## 38 -1.445154 3828512800   7.463929              1
## 39 -1.226591 4378606400   7.458929              0

Nividia Stock Combined Dataset

Preview of the processed data for Nividia stock:

head(combined_data_nvda_df)
##          date NVDA.Close NVDA.Volume      SMA      EMA      rsi      macd
## 34 2010-02-22     4.1525    45808400 4.148125 4.237807 44.89034 -1.441962
## 35 2010-02-23     4.0525    48976400 4.141500 4.220159 41.48619 -1.633046
## 36 2010-02-24     4.1375    44586800 4.145750 4.212287 45.28432 -1.603728
## 37 2010-02-25     4.1000    57697200 4.142625 4.201593 43.92956 -1.634490
## 38 2010-02-26     4.0500    39339600 4.144000 4.187155 42.12018 -1.736565
## 39 2010-03-01     4.2125    55586800 4.162250 4.189569 49.41278 -1.485715
##       signal       obv Next_Close Price_Movement
## 34 -2.348939   2028000     4.0525              0
## 35 -2.205760 -46948400     4.1375              1
## 36 -2.085354  -2361600     4.1000              0
## 37 -1.995181 -60058800     4.0500              0
## 38 -1.943458 -99398400     4.2125              1
## 39 -1.851909 -43811600     4.2100              0

Tesla Stock Combined Dataset

Preview of the processed data for Tesla stock:

head(combined_data_tsla_df)
##          date TSLA.Close TSLA.Volume      SMA      EMA      rsi      macd
## 34 2010-08-16   1.252000     7287000 1.335733 1.298357 40.26706 -1.374697
## 35 2010-08-17   1.276667     6718500 1.331900 1.296291 42.51617 -1.307812
## 36 2010-08-18   1.251333     9019500 1.327067 1.292009 40.81635 -1.398487
## 37 2010-08-19   1.252667     8686500 1.319700 1.288262 40.95022 -1.446106
## 38 2010-08-20   1.273333     4440000 1.312400 1.286840 43.09764 -1.338059
## 39 2010-08-23   1.342000    16321500 1.309667 1.292094 49.64971 -0.810026
##         signal        obv Next_Close Price_Movement
## 34  0.89942866 -199660500   1.276667              1
## 35  0.45798046 -192942000   1.251333              0
## 36  0.08668695 -201961500   1.252667              1
## 37 -0.21987158 -193275000   1.273333              1
## 38 -0.44350912 -188835000   1.342000              1
## 39 -0.51681250 -172513500   1.280000              0

Feature Selection for Predictive Modeling

Identifying which features in the datasets have predictive power for the price movement.

Apple Stock: Correlation Matrix and Feature Selection

Visualizing the correlations between different features in the Apple stock dataset:

# Installing and loading corrplot if not already installed
if (!require(corrplot)) install.packages("corrplot")
## Loading required package: corrplot
## corrplot 0.92 loaded
library(corrplot)

# Computing and plotting correlations
correlations <- cor(combined_data_Apple_df[, -c(1, ncol(combined_data_Apple_df))])
corrplot(correlations, method = "circle")

Building a logistic regression model for Apple stock:

# exclude the Next_close variable since it is a variable contains future data, not be availiable in the prediction stage
combined_data_Apple_df <- combined_data_Apple_df[, -which(names(combined_data_Apple_df) == "Next_Close")]
head(combined_data_Apple_df)
##          date AAPL.Close AAPL.Volume      SMA      EMA      rsi       macd
## 34 2010-02-22   7.157857   390563600 7.108964 7.190744 46.78058 -1.2198023
## 35 2010-02-23   7.037857   575094800 7.098232 7.176183 42.66471 -1.2600488
## 36 2010-02-24   7.166429   460566400 7.088804 7.175254 47.94888 -1.1340106
## 37 2010-02-25   7.214286   665126000 7.078304 7.178971 49.80332 -0.9689520
## 38 2010-02-26   7.307857   507460800 7.087821 7.191246 53.30619 -0.7245216
## 39 2010-03-01   7.463929   550093600 7.118054 7.217216 58.50723 -0.3523378
##       signal        obv Price_Movement
## 34 -2.126551 2770454400              0
## 35 -1.953251 2195359600              1
## 36 -1.789403 2655926000              1
## 37 -1.625312 3321052000              1
## 38 -1.445154 3828512800              1
## 39 -1.226591 4378606400              0
glm_model_apple <- glm(Price_Movement ~ ., data = combined_data_Apple_df, family = binomial())
summary(glm_model_apple)
## 
## Call:
## glm(formula = Price_Movement ~ ., family = binomial(), data = combined_data_Apple_df)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)   
## (Intercept) -8.892e-01  1.183e+00  -0.752  0.45210   
## date         6.841e-05  6.851e-05   0.999  0.31803   
## AAPL.Close  -5.532e-02  1.843e-02  -3.002  0.00268 **
## AAPL.Volume  1.526e-10  2.573e-10   0.593  0.55314   
## SMA         -6.247e-02  6.584e-02  -0.949  0.34273   
## EMA          1.181e-01  7.558e-02   1.562  0.11823   
## rsi          6.644e-03  6.264e-03   1.061  0.28881   
## macd         8.563e-02  1.208e-01   0.709  0.47858   
## signal      -5.271e-02  1.037e-01  -0.508  0.61141   
## obv         -4.497e-11  1.475e-11  -3.049  0.00229 **
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 4824.6  on 3487  degrees of freedom
## Residual deviance: 4805.0  on 3478  degrees of freedom
## AIC: 4825
## 
## Number of Fisher Scoring iterations: 3

Evaluating feature importance using Random Forest for Apple stock:

# Installing and loading randomForest if not already installed
if (!require(randomForest)) install.packages("randomForest")
## Loading required package: randomForest
## randomForest 4.7-1.1
## Type rfNews() to see new features/changes/bug fixes.
## 
## Attaching package: 'randomForest'
## The following object is masked from 'package:dplyr':
## 
##     combine
library(randomForest)

rf_model_apple <- randomForest(Price_Movement ~ ., data = combined_data_Apple_df)
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
varImpPlot(rf_model_apple)

Nividia Stock: Correlation Matrix and Feature Selection

Visualizing the correlations between different features in the Nividia stock dataset:

# Computing and plotting correlations
correlations <- cor(combined_data_nvda_df[, -c(1, ncol(combined_data_nvda_df))])
corrplot::corrplot(correlations, method = "circle")

Building a logistic regression model for Nividia stock:

combined_data_nvda_df <- combined_data_nvda_df[, -which(names(combined_data_nvda_df) == "Next_Close")]
head(combined_data_nvda_df)
##          date NVDA.Close NVDA.Volume      SMA      EMA      rsi      macd
## 34 2010-02-22     4.1525    45808400 4.148125 4.237807 44.89034 -1.441962
## 35 2010-02-23     4.0525    48976400 4.141500 4.220159 41.48619 -1.633046
## 36 2010-02-24     4.1375    44586800 4.145750 4.212287 45.28432 -1.603728
## 37 2010-02-25     4.1000    57697200 4.142625 4.201593 43.92956 -1.634490
## 38 2010-02-26     4.0500    39339600 4.144000 4.187155 42.12018 -1.736565
## 39 2010-03-01     4.2125    55586800 4.162250 4.189569 49.41278 -1.485715
##       signal       obv Price_Movement
## 34 -2.348939   2028000              0
## 35 -2.205760 -46948400              1
## 36 -2.085354  -2361600              0
## 37 -1.995181 -60058800              0
## 38 -1.943458 -99398400              1
## 39 -1.851909 -43811600              0
glm_model_nvda <- glm(Price_Movement ~ ., data = combined_data_nvda_df, family = binomial())
summary(glm_model_nvda)
## 
## Call:
## glm(formula = Price_Movement ~ ., family = binomial(), data = combined_data_nvda_df)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)   
## (Intercept) -3.819e+00  1.293e+00  -2.952  0.00315 **
## date         2.582e-04  7.968e-05   3.240  0.00119 **
## NVDA.Close  -2.452e-03  6.022e-03  -0.407  0.68390   
## NVDA.Volume  1.222e-09  1.223e-09   0.999  0.31794   
## SMA         -2.220e-03  2.134e-02  -0.104  0.91712   
## EMA          4.307e-03  2.501e-02   0.172  0.86327   
## rsi         -4.859e-03  6.032e-03  -0.806  0.42046   
## macd         8.047e-03  6.853e-02   0.117  0.90653   
## signal       2.747e-03  5.834e-02   0.047  0.96244   
## obv         -8.326e-11  3.898e-11  -2.136  0.03269 * 
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 4825.9  on 3487  degrees of freedom
## Residual deviance: 4811.1  on 3478  degrees of freedom
## AIC: 4831.1
## 
## Number of Fisher Scoring iterations: 3

Evaluating feature importance using Random Forest for Nividia stock:

library(randomForest)
rf_model <- randomForest(Price_Movement ~ ., data = combined_data_nvda_df)
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
varImpPlot(rf_model)

Tesla Stock: Correlation Matrix and Feature Selection

Visualizing the correlations between different features in the Tesla stock dataset:

# Computing and plotting correlations
correlations <- cor(combined_data_tsla_df[, -c(1, ncol(combined_data_tsla_df))])
corrplot::corrplot(correlations, method = "circle")

Building a logistic regression model for Tesla stock:

combined_data_tsla_df <- combined_data_tsla_df[, -which(names(combined_data_tsla_df) == "Next_Close")]
head(combined_data_tsla_df)
##          date TSLA.Close TSLA.Volume      SMA      EMA      rsi      macd
## 34 2010-08-16   1.252000     7287000 1.335733 1.298357 40.26706 -1.374697
## 35 2010-08-17   1.276667     6718500 1.331900 1.296291 42.51617 -1.307812
## 36 2010-08-18   1.251333     9019500 1.327067 1.292009 40.81635 -1.398487
## 37 2010-08-19   1.252667     8686500 1.319700 1.288262 40.95022 -1.446106
## 38 2010-08-20   1.273333     4440000 1.312400 1.286840 43.09764 -1.338059
## 39 2010-08-23   1.342000    16321500 1.309667 1.292094 49.64971 -0.810026
##         signal        obv Price_Movement
## 34  0.89942866 -199660500              1
## 35  0.45798046 -192942000              0
## 36  0.08668695 -201961500              1
## 37 -0.21987158 -193275000              1
## 38 -0.44350912 -188835000              1
## 39 -0.51681250 -172513500              0
glm_model_tsla <- glm(Price_Movement ~ ., data = combined_data_tsla_df, family = binomial())
summary(glm_model_tsla)
## 
## Call:
## glm(formula = Price_Movement ~ ., family = binomial(), data = combined_data_tsla_df)
## 
## Coefficients:
##               Estimate Std. Error z value Pr(>|z|)  
## (Intercept) -5.224e-01  9.519e-01  -0.549   0.5831  
## date         4.839e-05  5.830e-05   0.830   0.4065  
## TSLA.Close  -1.645e-03  5.010e-03  -0.328   0.7426  
## TSLA.Volume  2.250e-10  5.340e-10   0.421   0.6735  
## SMA         -3.185e-02  1.815e-02  -1.754   0.0794 .
## EMA          3.379e-02  2.125e-02   1.590   0.1118  
## rsi         -3.963e-03  5.896e-03  -0.672   0.5015  
## macd        -2.449e-03  5.148e-02  -0.048   0.9621  
## signal       1.975e-02  4.416e-02   0.447   0.6547  
## obv         -1.237e-11  2.132e-11  -0.580   0.5619  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 4661.4  on 3365  degrees of freedom
## Residual deviance: 4654.6  on 3356  degrees of freedom
## AIC: 4674.6
## 
## Number of Fisher Scoring iterations: 3

Evaluating feature importance using Random Forest for Tesla stock:

library(randomForest)
rf_model <- randomForest(Price_Movement ~ ., data = combined_data_tsla_df)
## Warning in randomForest.default(m, y, ...): The response has five or fewer
## unique values.  Are you sure you want to do regression?
varImpPlot(rf_model)

Predictors Selection

Based on our analysis, OBV (On-Balance Volume) and RSI (Relative Strength Index) are selected as predictors for Apple, Nvidia, and Tesla stocks.

Splitting Data into Training and Testing Sets

To validate our models, we split the data into training and testing datasets.

Apple Stock

training_apple <- combined_data_Apple_df[combined_data_Apple_df$date < as.Date("2020-01-01"),]
test_apple <- combined_data_Apple_df[combined_data_Apple_df$date >= as.Date("2020-01-01"),]
training_apple.Price_Movement <- training_apple$Price_Movement
test_apple.Price_Movement <- test_apple$Price_Movement
tail(training_apple)
##            date AAPL.Close AAPL.Volume      SMA      EMA      rsi     macd
## 2511 2019-12-23    71.0000    98572000 67.79550 68.11368 74.20847 2.396842
## 2512 2019-12-24    71.0675    48478800 68.01925 68.39500 74.43659 2.446472
## 2513 2019-12-26    72.4775    93121200 68.33950 68.78381 78.67899 2.617382
## 2514 2019-12-27    72.4500   146266000 68.61400 69.13297 78.40566 2.715221
## 2515 2019-12-30    72.8800   144114400 68.91737 69.48983 79.59896 2.807176
## 2516 2019-12-31    73.4125   100805600 69.28600 69.86341 80.99926 2.904653
##        signal         obv Price_Movement
## 2511 2.198160 14658823600              1
## 2512 2.247822 14707302400              1
## 2513 2.321734 14800423600              0
## 2514 2.400431 14654157600              1
## 2515 2.481780 14798272000              1
## 2516 2.566355 14899077600              1
head(test_apple)
##            date AAPL.Close AAPL.Volume      SMA      EMA      rsi     macd
## 2517 2020-01-02    75.0875   135480400 69.79725 70.36095 84.58374 3.132220
## 2518 2020-01-03    74.3575   146322800 70.24337 70.74157 77.70370 3.189191
## 2519 2020-01-06    74.9500   118387200 70.67112 71.14237 79.18367 3.260179
## 2520 2020-01-07    74.5975   108872000 71.01712 71.47143 75.95355 3.237152
## 2521 2020-01-08    75.7975   132079200 71.47050 71.88344 79.08193 3.311355
## 2522 2020-01-09    77.4075   170108400 71.98487 72.40954 82.39181 3.503001
##        signal         obv Price_Movement
## 2517 2.679528 15034558000              0
## 2518 2.781461 14888235200              1
## 2519 2.877204 15006622400              0
## 2520 2.949194 14897750400              1
## 2521 3.021626 15029829600              1
## 2522 3.117901 15199938000              1

Nividia Stock

training_nvda <- combined_data_nvda_df[combined_data_nvda_df$date < as.Date("2020-01-01"),]
test_nvda <- combined_data_nvda_df[combined_data_nvda_df$date >= as.Date("2020-01-01"),]
training_nvda.Price_Movement <- training_nvda$Price_Movement
test_nvda.Price_Movement <- test_nvda$Price_Movement
tail(training_nvda)
##            date NVDA.Close NVDA.Volume      SMA      EMA      rsi     macd
## 2511 2019-12-23    59.7050    35506000 55.10725 55.64577 77.17063 3.535595
## 2512 2019-12-24    59.6550    13886400 55.32488 56.02760 76.74387 3.654571
## 2513 2019-12-26    59.7975    18285200 55.60225 56.38664 77.13200 3.721711
## 2514 2019-12-27    59.2175    25464400 55.83512 56.65624 71.87416 3.648428
## 2515 2019-12-30    58.0800    25805600 56.02987 56.79184 62.82860 3.391097
## 2516 2019-12-31    58.8250    23100400 56.35550 56.98547 65.85919 3.253231
##        signal        obv Price_Movement
## 2511 2.688921 5749557200              0
## 2512 2.882051 5735670800              1
## 2513 3.049983 5753956000              0
## 2514 3.169672 5728491600              0
## 2515 3.213957 5702686000              1
## 2516 3.221812 5725786400              1
head(test_nvda)
##            date NVDA.Close NVDA.Volume      SMA      EMA      rsi     macd
## 2517 2020-01-02    59.9775    23753600 56.75863 57.27043 69.94190 3.265288
## 2518 2020-01-03    59.0175    20538400 57.09175 57.43682 63.16592 3.104359
## 2519 2020-01-06    59.2650    26263600 57.44575 57.61093 64.13073 2.976108
## 2520 2020-01-07    59.9825    31485600 57.79275 57.83679 66.84225 2.938597
## 2521 2020-01-08    60.0950    27710800 58.14538 58.05186 67.26017 2.889633
## 2522 2020-01-09    60.7550    25511200 58.50838 58.30930 69.67493 2.906181
##        signal        obv Price_Movement
## 2517 3.230507 5749540000              0
## 2518 3.205278 5729001600              1
## 2519 3.159444 5755265200              1
## 2520 3.115274 5786750800              1
## 2521 3.070146 5814461600              1
## 2522 3.037353 5839972800              1

Tesla stock

training_tsla <- combined_data_tsla_df[combined_data_tsla_df$date < as.Date("2020-01-01"),]
test_tsla <- combined_data_tsla_df[combined_data_tsla_df$date >= as.Date("2020-01-01"),]
training_tsla.Price_Movement <- training_tsla$Price_Movement
test_tsla.Price_Movement <- test_tsla$Price_Movement
tail(training_tsla)
##            date TSLA.Close TSLA.Volume      SMA      EMA      rsi     macd
## 2389 2019-12-23   27.94800   199794000 23.79493 24.46941 83.32686 5.976415
## 2390 2019-12-24   28.35000   120820500 24.09130 24.83899 84.35260 6.437638
## 2391 2019-12-26   28.72933   159508500 24.43137 25.20950 85.27327 6.820456
## 2392 2019-12-27   28.69200   149185500 24.76167 25.54116 84.74477 7.011882
## 2393 2019-12-30   27.64667   188796000 25.04420 25.74169 71.40126 6.756993
## 2394 2019-12-31   27.88867   154285500 25.32240 25.94616 72.48151 6.547900
##        signal        obv Price_Movement
## 2389 4.462256 4633287000              1
## 2390 4.857332 4754107500              1
## 2391 5.249957 4913616000              0
## 2392 5.602342 4764430500              0
## 2393 5.833272 4575634500              1
## 2394 5.976198 4729920000              1
head(test_tsla)
##            date TSLA.Close TSLA.Volume      SMA      EMA      rsi     macd
## 2395 2020-01-02   28.68400   142981500 25.63593 26.20691 75.72662 6.538703
## 2396 2020-01-03   29.53400   266677500 26.00253 26.52377 78.62741 6.695306
## 2397 2020-01-06   30.10267   151995000 26.40643 26.86462 80.32174 6.891604
## 2398 2020-01-07   31.27067   268231500 26.85033 27.28424 83.25755 7.280835
## 2399 2020-01-08   32.80933   467164500 27.35903 27.81044 86.18216 7.903911
## 2400 2020-01-09   32.08933   426606000 27.80070 28.21796 79.20948 8.074886
##        signal        obv Price_Movement
## 2395 6.088699 4872901500              1
## 2396 6.210020 5139579000              1
## 2397 6.346337 5291574000              1
## 2398 6.533236 5559805500              1
## 2399 6.807371 6026970000              0
## 2400 7.060874 5600364000              0

Building Classification Models

We use the LDA (Linear Discriminant Analysis) model to classify stock price movements.

LDA Model for Apple Stock

library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:dplyr':
## 
##     select
lda_model_apple <- lda(Price_Movement ~ rsi + obv, data = training_apple)
lda_pred_apple <- predict(lda_model_apple, test_apple)$class
confusion_matrix_apple <- table(Predicted = lda_pred_apple, Actual = test_apple$Price_Movement)
accuracy_fraction_apple <- sum(diag(confusion_matrix_apple)) / sum(confusion_matrix_apple)

LDA Model for Nvidia Stock

lda_model_nvda <- lda(Price_Movement ~ rsi + obv, data = training_nvda)
lda_pred_nvda <- predict(lda_model_nvda, test_nvda)$class
confusion_matrix_nvda <- table(Predicted = lda_pred_nvda, Actual = test_nvda$Price_Movement)
accuracy_fraction_nvda <- sum(diag(confusion_matrix_nvda)) / sum(confusion_matrix_nvda)

LDA Model for Tesla Stock

lda_model_tsla <- lda(Price_Movement ~ rsi + obv, data = training_tsla)
lda_pred_tsla <- predict(lda_model_tsla, test_tsla)$class
confusion_matrix_tsla <- table(Predicted = lda_pred_tsla, Actual = test_tsla$Price_Movement)
accuracy_fraction_tsla <- sum(diag(confusion_matrix_tsla)) / sum(confusion_matrix_tsla)

Outputs

Apple Stock LDA Model Results

print(confusion_matrix_apple)
##          Actual
## Predicted   0   1
##         0 305 339
##         1 173 188
print(accuracy_fraction_apple)
## [1] 0.4905473

Nvidia Stock LDA Model Results

print(confusion_matrix_nvda)
##          Actual
## Predicted   0   1
##         0   0   0
##         1 460 545
print(accuracy_fraction_nvda)
## [1] 0.5422886

Tesla Stock LDA Model Results

print(confusion_matrix_tsla)
##          Actual
## Predicted   0   1
##         0 462 536
##         1   3   4
print(accuracy_fraction_tsla)
## [1] 0.4636816

Building Classification Models

In addition to LDA, we will also use the QDA (Quadratic Discriminant Analysis) model for classifying stock price movements.

QDA Model for Apple Stock

library(MASS)
qda_fit_apple <- qda(Price_Movement ~ obv + rsi, data = training_apple)
qda_pred_apple <- predict(qda_fit_apple, newdata = test_apple)
qda_table_apple <- table(Predicted = qda_pred_apple$class, Actual = test_apple$Price_Movement)
qda_correct_apple <- sum(diag(qda_table_apple))
qda_accuracy_apple <- qda_correct_apple / sum(qda_table_apple)

QDA Model for Nividia Stock

qda_fit_nvda <- qda(Price_Movement ~ obv + rsi, data = training_nvda)
qda_pred_nvda <- predict(qda_fit_nvda, newdata = test_nvda)
qda_table_nvda <- table(Predicted = qda_pred_nvda$class, Actual = test_nvda$Price_Movement)
qda_correct_nvda <- sum(diag(qda_table_nvda))
qda_accuracy_nvda <- qda_correct_nvda / sum(qda_table_nvda)

QDA Model for Tesla Stock

qda_fit_tsla <- qda(Price_Movement ~ obv + rsi, data = training_tsla)
qda_pred_tsla <- predict(qda_fit_tsla, newdata = test_tsla)
qda_table_tsla <- table(Predicted = qda_pred_tsla$class, Actual = test_tsla$Price_Movement)
qda_correct_tsla <- sum(diag(qda_table_tsla))
qda_accuracy_tsla <- qda_correct_tsla / sum(qda_table_tsla)

Outputs

Apple Stock QDA Model Results

print(qda_table_apple)
##          Actual
## Predicted   0   1
##         0 328 385
##         1 150 142
print(qda_accuracy_apple)
## [1] 0.4676617

Nividia Stock QDA Model Results

print(qda_table_nvda)
##          Actual
## Predicted   0   1
##         0   0   0
##         1 460 545
print(qda_accuracy_nvda)
## [1] 0.5422886

Tesla Stock QDA Model Results

print(qda_table_tsla)
##          Actual
## Predicted   0   1
##         0 465 540
##         1   0   0
print(qda_accuracy_tsla)
## [1] 0.4626866

Building Classification Models Using KNN

The KNN (k-Nearest Neighbors) model is another approach we use to classify stock price movements. Here, we find the best value for ‘k’ and build the KNN model.

KNN Model for Apple Stock

Finding the optimal ‘k’ and building the model:

library(class)
training_apple_X <- as.matrix(training_apple[, c("obv", "rsi")])
test_apple_X <- as.matrix(test_apple[, c("obv", "rsi")])

best_k_apple <- 1
best_accuracy_apple <- 0

for (k in 1:20) {
  set.seed(1)
  knn_pred <- knn(training_apple_X, test_apple_X, cl=training_apple$Price_Movement, k=k)
  knn_table <- table(Predicted=knn_pred, Actual=test_apple$Price_Movement)
  knn_accuracy <- sum(diag(knn_table)) / sum(knn_table)
  if (knn_accuracy > best_accuracy_apple) {
    best_k_apple <- k
    best_accuracy_apple <- knn_accuracy
  }
}
print(paste("Best K for Apple:", best_k_apple))
## [1] "Best K for Apple: 6"

Building the KNN model for Apple stock using the optimal ‘k’:

knn_pred_apple <- knn(training_apple_X, test_apple_X, cl=training_apple$Price_Movement, k=best_k_apple)
knn_table_apple <- table(Predicted = knn_pred_apple, Actual = test_apple$Price_Movement)
knn_accuracy_apple <- sum(diag(knn_table_apple)) / sum(knn_table_apple)

KNN Model for Nvidia Stock

Finding the optimal ‘k’ and building the model:

training_nvda_X <- as.matrix(training_nvda[, c("obv", "rsi")])
test_nvda_X <- as.matrix(test_nvda[, c("obv", "rsi")])

best_k_nvda <- 1
best_accuracy_nvda <- 0

for (k in 1:20) {
  set.seed(1)
  knn_pred <- knn(training_nvda_X, test_nvda_X, cl=training_nvda$Price_Movement, k=k)
  knn_table <- table(Predicted=knn_pred, Actual=test_nvda$Price_Movement)
  knn_accuracy <- sum(diag(knn_table)) / sum(knn_table)
  if (knn_accuracy > best_accuracy_nvda) {
    best_k_nvda <- k
    best_accuracy_nvda <- knn_accuracy
  }
}
print(paste("Best K for Nvidia:", best_k_nvda))
## [1] "Best K for Nvidia: 9"

Building the KNN model for Nvidia stock using the optimal ‘k’:

knn_pred_nvda <- knn(training_nvda_X, test_nvda_X, cl=training_nvda$Price_Movement, k=best_k_nvda)
knn_table_nvda <- table(Predicted = knn_pred_nvda, Actual = test_nvda$Price_Movement)
knn_accuracy_nvda <- sum(diag(knn_table_nvda)) / sum(knn_table_nvda)

KNN Model for Tesla Stock

Finding the optimal ‘k’ and building the model:

training_tsla_X <- as.matrix(training_tsla[, c("obv", "rsi")])
test_tsla_X <- as.matrix(test_tsla[, c("obv", "rsi")])

best_k_tsla <- 1
best_accuracy_tsla <- 0

for (k in 1:20) {
  set.seed(1)
  knn_pred <- knn(training_tsla_X, test_tsla_X, cl=training_tsla$Price_Movement, k=k)
  knn_table <- table(Predicted=knn_pred, Actual=test_tsla$Price_Movement)
  knn_accuracy <- sum(diag(knn_table)) / sum(knn_table)
  if (knn_accuracy > best_accuracy_tsla) {
    best_k_tsla <- k
    best_accuracy_tsla <- knn_accuracy
  }
}
print(paste("Best K for Tesla:", best_k_tsla))
## [1] "Best K for Tesla: 11"

Building the KNN model for Tesla stock using the optimal ‘k’:

knn_pred_tsla <- knn(training_tsla_X, test_tsla_X, cl=training_tsla$Price_Movement, k=best_k_tsla)
knn_table_tsla <- table(Predicted = knn_pred_tsla, Actual = test_tsla$Price_Movement)
knn_accuracy_tsla <- sum(diag(knn_table_tsla)) / sum(knn_table_tsla)

Outputs

Apple Stock KNN Model Results

print(knn_table_apple)
##          Actual
## Predicted   0   1
##         0 208 226
##         1 270 301
print(knn_accuracy_apple)
## [1] 0.5064677

Nvidia Stock KNN Model Results

print(knn_table_nvda)
##          Actual
## Predicted   0   1
##         0   0   0
##         1 460 545
print(knn_accuracy_nvda)
## [1] 0.5422886

Tesla Stock KNN Model Results

print(knn_table_tsla)
##          Actual
## Predicted   0   1
##         0 464 532
##         1   1   8
print(knn_accuracy_tsla)
## [1] 0.4696517

Building Classification Models Using Naive Bayes

We also apply the Naive Bayes model for classifying stock price movements.

Naive Bayes Model for Apple Stock

Building and evaluating the Naive Bayes model for Apple stock:

library(e1071)
nb_fit_apple <- naiveBayes(Price_Movement ~ obv + rsi, data = training_apple)
nb_pred_apple <- predict(nb_fit_apple, newdata = test_apple)
nb_table_apple <- table(Predicted = nb_pred_apple, Actual = test_apple$Price_Movement)
nb_accuracy_apple <- sum(diag(nb_table_apple)) / sum(nb_table_apple)

Naive Bayes Model for Nividia Stock

Building and evaluating the Naive Bayes model for Nividia stock:

nb_fit_nvda <- naiveBayes(Price_Movement ~ obv + rsi, data = training_nvda)
nb_pred_nvda <- predict(nb_fit_nvda, newdata = test_nvda)
nb_table_nvda <- table(Predicted = nb_pred_nvda, Actual = test_nvda$Price_Movement)
nb_accuracy_nvda <- sum(diag(nb_table_nvda)) / sum(nb_table_nvda)

Naive Bayes Model for Tesla Stock

Building and evaluating the Naive Bayes model for Tesla stock:

nb_fit_tsla <- naiveBayes(Price_Movement ~ obv + rsi, data = training_tsla)
nb_pred_tsla <- predict(nb_fit_tsla, newdata = test_tsla)
nb_table_tsla <- table(Predicted = nb_pred_tsla, Actual = test_tsla$Price_Movement)
nb_accuracy_tsla <- sum(diag(nb_table_tsla)) / sum(nb_table_tsla)

Results and Evaluation

Apple Stock Naive Bayes Model Results

print(nb_table_apple)
##          Actual
## Predicted   0   1
##         0 313 350
##         1 165 177
print(nb_accuracy_apple)
## [1] 0.4875622

Nvidia Stock Naive Bayes Model Results

print(nb_table_nvda)
##          Actual
## Predicted   0   1
##         0   0   0
##         1 460 545
print(nb_accuracy_nvda)
## [1] 0.5422886

Tesla Stock Naive Bayes Model Results

print(nb_table_tsla)
##          Actual
## Predicted   0   1
##         0 465 539
##         1   0   1
print(nb_accuracy_tsla)
## [1] 0.4636816

Model Comparison

In this section, we compare the performance of different models for stocks using ROC (Receiver Operating Characteristic) curves and calculating the AUC (Area Under the Curve).

Apple

ROC Curve for Logistic Regression Model

library(pROC)
## Type 'citation("pROC")' for a citation.
## 
## Attaching package: 'pROC'
## The following objects are masked from 'package:stats':
## 
##     cov, smooth, var
log_prob <- predict(glm_model_apple, newdata=test_apple, type="response")
roc_obj <- roc(test_apple$Price_Movement, log_prob)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_obj, main="ROC Curve for Logistic Regression Model")

print(paste("AUC:", auc(roc_obj)))
## [1] "AUC: 0.557112573737822"
plot(roc_obj, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for LDA Model

library(MASS)
lda_probs_apple <- predict(lda_model_apple, newdata = test_apple)$posterior[,2]
roc_apple <- roc(test_apple$Price_Movement, lda_probs_apple)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_apple, main="ROC Curve for LDA Model")

print(paste("AUC for LDA Model:", auc(roc_apple)))
## [1] "AUC for LDA Model: 0.495788111438393"
plot(roc_apple, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for QDA Model

qda_probs_apple <- predict(qda_fit_apple, newdata = test_apple)$posterior[,2]
roc_qda_apple <- roc(test_apple$Price_Movement, qda_probs_apple)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_qda_apple, main="ROC Curve for QDA Model")

print(paste("AUC for QDA Model:", auc(roc_qda_apple)))
## [1] "AUC for QDA Model: 0.496911546370471"
plot(roc_qda_apple, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for Naive Bayes Model

nb_probs_apple <- predict(nb_fit_apple, newdata = test_apple, type = "raw")[,2]
roc_nb_apple <- roc(test_apple$Price_Movement, nb_probs_apple)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
plot(roc_nb_apple, main="ROC Curve for Naive Bayes Model")

print(paste("AUC for Naive Bayes Model:", auc(roc_nb_apple)))
## [1] "AUC for Naive Bayes Model: 0.489500051606552"
plot(roc_nb_apple, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

Nividia

ROC Curve for Logistic Regression Model (Nvidia)

log_prob_nvda <- predict(glm_model_nvda, newdata=test_nvda, type="response")
roc_obj_nvda <- roc(test_nvda$Price_Movement, log_prob_nvda)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_obj_nvda, main="ROC Curve for Logistic Regression Model")

print(paste("AUC for Logistic Regression (Nvidia):", auc(roc_obj_nvda)))
## [1] "AUC for Logistic Regression (Nvidia): 0.526521739130435"
plot(roc_obj, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for LDA Model (Nvidia)

lda_probs_nvda <- predict(lda_model_nvda, newdata = test_nvda)$posterior[,2]
roc_nvda <- roc(test_nvda$Price_Movement, lda_probs_nvda)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_nvda, main="ROC Curve for LDA Model")

print(paste("AUC for LDA Model (Nvidia):", auc(roc_nvda)))
## [1] "AUC for LDA Model (Nvidia): 0.501531711208616"
plot(roc_nvda, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for QDA Model (Nvidia)

qda_probs_nvda <- predict(qda_fit_nvda, newdata = test_nvda)$posterior[,2]
roc_qda_nvda <- roc(test_nvda$Price_Movement, qda_probs_nvda)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
plot(roc_qda_nvda, main="ROC Curve for QDA Model")

print(paste("AUC for QDA Model (Nvidia):", auc(roc_qda_nvda)))
## [1] "AUC for QDA Model (Nvidia): 0.53176705225369"
plot(roc_qda_nvda, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for Naive Bayes Model (Nvidia)

nb_probs_nvda <- predict(nb_fit_nvda, newdata = test_nvda, type = "raw")[,2]
roc_nb_nvda <- roc(test_nvda$Price_Movement, nb_probs_nvda)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
plot(roc_nb_nvda, main="ROC Curve for Naive Bayes Model")

print(paste("AUC for Naive Bayes Model (Nvidia):", auc(roc_nb_nvda)))
## [1] "AUC for Naive Bayes Model (Nvidia): 0.518213003589948"
plot(roc_nb_nvda, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

Tesla

ROC Curve for Logistic Regression Model (Tesla)

log_prob_tsla <- predict(glm_model_tsla, newdata=test_tsla, type="response")
roc_obj_tsla <- roc(test_tsla$Price_Movement, log_prob_tsla)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_obj_tsla, main="ROC Curve for Logistic Regression Model")

print(paste("AUC for Logistic Regression (Tesla):", auc(roc_obj_tsla)))
## [1] "AUC for Logistic Regression (Tesla): 0.53557546794106"
plot(roc_obj, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for LDA Model (Tesla)

lda_probs_tsla <- predict(lda_model_tsla, newdata = test_tsla)$posterior[,2]
roc_tsla <- roc(test_tsla$Price_Movement, lda_probs_tsla)
## Setting levels: control = 0, case = 1
## Setting direction: controls > cases
plot(roc_tsla, main="ROC Curve for LDA Model")

print(paste("AUC for LDA Model (Tesla):", auc(roc_tsla)))
## [1] "AUC for LDA Model (Tesla): 0.494064117881322"
plot(roc_tsla, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for QDA Model (Tesla)

qda_probs_tsla <- predict(qda_fit_tsla, newdata = test_tsla)$posterior[,2]
roc_qda_tsla <- roc(test_tsla$Price_Movement, qda_probs_tsla)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_qda_tsla, main="ROC Curve for QDA Model")

print(paste("AUC for QDA Model (Tesla):", auc(roc_qda_tsla)))
## [1] "AUC for QDA Model (Tesla): 0.538285543608125"
plot(roc_qda_tsla, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

ROC Curve for Naive Bayes Model (Tesla)

nb_probs_tsla <- predict(nb_fit_tsla, newdata = test_tsla, type = "raw")[,2]
roc_nb_tsla <- roc(test_tsla$Price_Movement, nb_probs_tsla)
## Setting levels: control = 0, case = 1
## Setting direction: controls < cases
plot(roc_nb_tsla, main="ROC Curve for Naive Bayes Model")

print(paste("AUC for Naive Bayes Model (Tesla):", auc(roc_nb_tsla)))
## [1] "AUC for Naive Bayes Model (Tesla): 0.52578853046595"
plot(roc_nb_tsla, print.auc=TRUE, print.auc.x=0.5, print.auc.y=.2, auc.polygon=TRUE, max.auc.polygon=TRUE, grid=TRUE)

Weekly Returns Analysis

This part of the report extends our previous analysis to include weekly returns for Apple, Nvidia, Tesla, and the S&P 500 index.

Required Libraries

Loading necessary R libraries for computing weekly returns and visualization.

library(quantmod)
library(PerformanceAnalytics)
## 
## Attaching package: 'PerformanceAnalytics'
## The following objects are masked from 'package:e1071':
## 
##     kurtosis, skewness
## The following object is masked from 'package:graphics':
## 
##     legend
library(dygraphs)
library(tseries)

Calculate weekly returns for the individual stocks

Fetching stock data and calculating log weekly returns.

weekly_returns_AAPL <- periodReturn(AAPL, period = "weekly", type = "log")
weekly_returns_NVDA <- periodReturn(NVDA, period = "weekly", type = "log")
weekly_returns_TSLA <- periodReturn(TSLA, period = "weekly", type = "log")

Get S&P 500 data for the same period for benchmark comparison

getSymbols("SPY", src = "yahoo", from = "2010-01-01", to = "2024-01-01")
## [1] "SPY"
weekly_returns_SPY <- periodReturn(SPY, period = "weekly", type = "log")

Combining and Visualizing Weekly Returns

Combining weekly returns of all stocks into one dataset and visualizing them.

combined_weekly_returns <- merge(weekly_returns_AAPL, weekly_returns_NVDA, weekly_returns_TSLA, weekly_returns_SPY)
colnames(combined_weekly_returns) <- c("AAPL", "NVDA", "TSLA", "SPY")

Visualization of Weekly Returns

Visualizing the weekly returns using dygraphs.

dygraph(combined_weekly_returns, main = "Weekly Returns Comparison") %>%
  dyOptions(colors = RColorBrewer::brewer.pal(4, "Dark2")) %>%
  dyRangeSelector()

2 methods for finding the optimal weight to different stocks

Finding the optimal ratio for each stock in the portfolio.

Sharpe Ratio Calculation

Calculating Mean Returns and Risks

# Calculate mean returns and risk for each stock
mean_returns <- apply(combined_weekly_returns, 2, mean)
risks <- apply(combined_weekly_returns, 2, sd)

# Display mean returns and risks
print(mean_returns)
##        AAPL        NVDA        TSLA         SPY 
## 0.004423490 0.006401350          NA 0.001975576
print(risks)
##       AAPL       NVDA       TSLA        SPY 
## 0.03857035 0.05840647         NA 0.02297077

Calculating the Sharpe Ratio for each stock and the S&P 500 index using a risk-free rate.

# Setting the risk-free rate
risk_free_rate <- 0.01 / 252  # Daily rate if annual rate is 1%

# Calculating Sharpe Ratios
sharpe_ratios <- apply(combined_weekly_returns, 2, function(x) SharpeRatio.annualized(x, Rf = risk_free_rate))
print(sharpe_ratios)
##      AAPL      NVDA      TSLA       SPY 
## 0.7469659 0.6513537 0.4934061 0.5468982

Optimal Portfolio Weight Calculation Using Mean-Variance Optimization

Finding the optimal weights for each stock in the portfolio based on the mean-variance optimization method.

# Calculating mean returns and covariance matrix
mean_returns <- colMeans(combined_weekly_returns[, c("AAPL", "NVDA", "TSLA")], na.rm = TRUE)
cov_matrix <- cov(combined_weekly_returns[, c("AAPL", "NVDA", "TSLA")], use = "pairwise.complete.obs")

# Convert mean returns to a matrix with one row
mean_returns_matrix <- matrix(mean_returns, nrow = 1)

# Running mean-variance optimization
opt_results <- portfolio.optim(x = mean_returns_matrix, covmat = cov_matrix, rf = risk_free_rate, shorts = FALSE)

# Extracting and displaying the optimal weights
opt_weights <- opt_results$pw
print(opt_weights)
## [1] 0.3135874 0.3890227 0.2973898
weights <- c(157/500, 389/1000, 297/1000)
portfolio_returns <- Return.portfolio(R = combined_weekly_returns[,1:3], weights = weights, wealth.index = TRUE)
## Warning in Return.portfolio(R = combined_weekly_returns[, 1:3], weights =
## weights, : NA's detected: filling NA's with zeros

Portfolio vs. S&P 500 Benchmark Analysis

This report compares the performance of a custom portfolio with the S&P 500 benchmark.

Data Preparation

First, we isolate the benchmark returns from the S&P 500 data and combine them with the portfolio returns for comparison.

# Assuming 'combined_weekly_returns' and 'portfolio_returns' are already calculated
benchmark_returns <- Return.portfolio(R = combined_weekly_returns[, 4], wealth.index = TRUE)

# Merging portfolio and benchmark returns
comparison <- merge.xts(portfolio_returns, benchmark_returns)
colnames(comparison) <- c("Portfolio", "SPY")

Visualization

Now, we’ll visualize the performance of the portfolio compared to the S&P 500 benchmark using interactive ‘dygraphs’.

Portfolio Analysis

Assuming an equally weighted portfolio of AAPL, NVDA, and TSLA, we analyze the portfolio returns.

# Setting weights
weights <- c(157/500, 389/1000, 297/1000)

# Calculating portfolio returns
portfolio_returns <- Return.portfolio(R = combined_weekly_returns[,1:3], weights = weights, wealth.index = TRUE)
## Warning in Return.portfolio(R = combined_weekly_returns[, 1:3], weights =
## weights, : NA's detected: filling NA's with zeros
# Benchmark returns isolated from the S&P 500 data
combined_weekly_returns
##                    AAPL         NVDA         TSLA          SPY
## 2010-01-08 -0.006817010  0.002158609           NA  0.019388965
## 2010-01-15 -0.028955586 -0.080806624           NA -0.008150436
## 2010-01-22 -0.040532700 -0.038729984           NA -0.039762926
## 2010-01-29 -0.029195766 -0.067215169           NA -0.016805564
## 2010-02-05  0.017547851  0.052527036           NA -0.006820823
## 2010-02-12  0.024859906  0.067347522           NA  0.012855298
## 2010-02-19  0.006417082 -0.045395383           NA  0.028289125
## 2010-02-26  0.014521906 -0.023185856           NA -0.003605570
## 2010-03-05  0.067688828  0.058152390           NA  0.031203938
## 2010-03-12  0.034342961  0.004648464           NA  0.010535112
##        ...                                                    
## 2023-10-27 -0.027325087 -0.021664836 -0.022372095 -0.025269739
## 2023-11-03  0.048897685  0.105471593  0.059278708  0.056818834
## 2023-11-10  0.053724530  0.071382381 -0.024436976  0.013526958
## 2023-11-17  0.017496304  0.019727586  0.087593592  0.022841521
## 2023-11-24  0.001474998 -0.031360093  0.004896205  0.009954897
## 2023-12-01  0.006663041 -0.021388395  0.014253446  0.008311549
## 2023-12-08  0.023104794  0.015720967  0.020760248  0.002393140
## 2023-12-15  0.009458983  0.028716850  0.038851566  0.019644913
## 2023-12-22 -0.020298783 -0.001228011 -0.003794198  0.009162522
## 2023-12-29 -0.005542227  0.014072165 -0.016207283  0.003498578
benchmark_returns <- Return.portfolio(R = combined_weekly_returns[, 4], wealth.index = TRUE)

# Merge portfolio and benchmark returns for comparison
comparison <- merge.xts(portfolio_returns, benchmark_returns)
colnames(comparison) <- c("Portfolio", "SPY")

# Visualize portfolio vs. benchmark
dygraph(comparison, main = "Portfolio Performance vs. S&P 500 Benchmark") %>%
  dyAxis("y", label = "Performance") %>%
  dyOptions(colors = c("blue", "red")) %>%
  dyLegend(show = "always") %>%
  dyRangeSelector()

In this analysis, we explored the weekly returns of Apple, Nvidia, and Tesla stocks compared with the S&P 500 index. We calculated the Sharpe Ratios for each and determined the optimal portfolio weights using mean-variance optimization. This report provides insights into stock performance and portfolio management strategies.

Conclusion

In this comprehensive study, we delved into the stock performances of Apple, Nvidia, and Tesla over the period from 2010 to 2024. Utilizing a variety of statistical models and techniques, we were able to unearth valuable insights about the market behavior and trends of these tech giants. The analysis commenced with the acquisition of historical data, followed by calculating weekly returns and key financial indicators such as the Simple Moving Average (SMA), Exponential Moving Average (EMA), Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), and On-Balance Volume (OBV). This approach shed light on the historical performance and trends of each stock, laying the groundwork for more nuanced analyses.

Subsequently, we explored several predictive models, including Linear Discriminant Analysis (LDA), Quadratic Discriminant Analysis (QDA), k-Nearest Neighbors (KNN), and Naive Bayes, to forecast stock price movements. We thoroughly assessed these models using various metrics, focusing particularly on their predictive accuracy and efficiency. Furthermore, we examined an equally weighted portfolio comprising Apple, Nvidia, and Tesla stocks, benchmarking its performance against the S&P 500. This comparison provided us with insights into the potential advantages and risks associated with this specific combination of stocks. Moreover, we delved into portfolio optimization using mean-variance optimization techniques and the Sharpe Ratio to determine the ideal stock allocation aimed at maximizing risk-adjusted returns.

The detailed analysis offers a comprehensive view of the performances and interrelationships of Apple, Nvidia, and Tesla stocks. The insights derived are invaluable for investors interested in the technology sector, providing a nuanced perspective for informed investment decisions. However, it’s imperative to remember that past performances are not definitive indicators of future results. Investment strategies should be formulated considering current market conditions, individual investment goals, and risk appetites. This report serves as an in-depth guide to understanding the dynamics of tech stocks and should be supplemented with up-to-date market analyses and professional financial advice.