7 Lab VI: Lists, Loops, & Functions in R
7.0.1 Preperation
## Packages
library(plyr)
library(tidyverse)
library(readxl)
library(readr)
library(lubridate)
library(knitr)
7.1 Load data. Stock price data is in stocks2020.csv. Presidential prices are in USPres_2020_Price History By Market -Bulk.xlsx.
## Reading in stock data
<- read_csv("~/GOVT8002/Spring 2023/Lab VII/stocks2020.csv", col_names = TRUE)
stk
## Reading in presidential market data
<- read_excel("~/GOVT8002/Spring 2023/Lab VII/USPres_2020_Price History By Market -Bulk.xlsx",
pres_mkt col_names = TRUE) %>%
::rename("date" = "Date (ET)",
dplyr"name" = "Contract Name",
"price" = "Close Share Price")
7.2 Create data frame with daily price data for Trump in 2020
## Creating daily price data for Trump
<- pres_mkt %>%
trump2020 filter(year(date) > 2019 & name == "Donald Trump") %>%
::select(c(date, "Trump" = price)) dplyr
7.3 Merge the stock price and Trump price data
## Joining the two datasets
<- left_join(stk, trump2020, by = "date") stk_pres
7.4 Create a list of stock ticker names (do not include DJI as a ticker)
## Creating list of ticker names
<-
stk_tickers c(names(stk)[!names(stk) %in% c("date", "DJI")])
## Creating number of stocks
<- length(stk_tickers) stk_num
7.5 Create a function that calculates daily percent change.
- Use the
dplyr::lag()
function inside your function. - Apply the function to price data in your data frame using the
mutate_at()
function.
## Price Change Function
<- function(x){
pct_change
- dplyr::lag(x))/dplyr::lag(x)
(x
}
## Daily Change Dataset
<- stk_pres %>%
daily_df ::mutate_at(c("DJI", "Trump", stk_tickers), pct_change) %>%
dplyr::select(c(date, c("DJI", "Trump", stk_tickers))) dplyr
7.6 Check that your function worked
cbind(stk_pres$AAPL, daily_df$AAPL)[1:3,]
## [,1] [,2]
## [1,] 75 NA
## [2,] 74 -0.0097
## [3,] 75 0.0080
7.7 Loop thru list of tickers and run regressions in which daily change in stock price is a function of change in DJIA and change in Trump price. Create a data frame that stores the coefficient, standard error and t-stat for the Trump variable for each stock. Include a column that has the stock ticker in that data frame as well. Show the first six rows of the data frame with the ticker and coefficient information.
## Preparing Data Frame to store results
<- data.frame("row" = 1:stk_num,
ols_results "ticker" = NA,
"coef" = NA,
"se" = NA,
"tStat" = NA)
## Looping Though Regressions
for(i in 1:stk_num){
$temp <- unlist(daily_df[, i + 3])
daily_df.1 <- lm(temp ~ DJI + Trump, data = daily_df)
ols"ticker"] <- stk_tickers[i]
ols_results[i, 3:5] <- round(summary(ols.1)$coefficients["Trump", 1:3], 3)
ols_results[i,
}
## Showing results
head(ols_results)
## row ticker coef se tStat
## 1 1 AAPL -0.015 0.011 -1.304
## 2 2 NFLX -0.036 0.016 -2.208
## 3 3 AMZN -0.034 0.013 -2.643
## 4 4 K -0.003 0.011 -0.259
## 5 5 TSLA -0.004 0.031 -0.115
## 6 6 LMT 0.000 0.011 -0.026
7.7.1 IF INTERESTED IN DOING MORE (not required or for credit): Use lapply()
(list apply) to regress stock price on Trump and DJI for all stock tickers.
## Now with lapply()
<- lapply(stk_tickers, function(x){
ols_results2 $temp = unlist(daily_df[, which(names(daily_df) == x)])
daily_df.1 <- lm(temp ~ DJI + Trump, data = daily_df)
ols
})
head(ols_results2)
## [[1]]
##
## Call:
## lm(formula = temp ~ DJI + Trump, data = daily_df)
##
## Coefficients:
## (Intercept) DJI Trump
## 0.00189 0.98010 -0.01476
##
##
## [[2]]
##
## Call:
## lm(formula = temp ~ DJI + Trump, data = daily_df)
##
## Coefficients:
## (Intercept) DJI Trump
## 0.0019 0.5354 -0.0358
##
##
## [[3]]
##
## Call:
## lm(formula = temp ~ DJI + Trump, data = daily_df)
##
## Coefficients:
## (Intercept) DJI Trump
## 0.0021 0.5324 -0.0336
##
##
## [[4]]
##
## Call:
## lm(formula = temp ~ DJI + Trump, data = daily_df)
##
## Coefficients:
## (Intercept) DJI Trump
## -0.00033 0.41330 -0.00285
##
##
## [[5]]
##
## Call:
## lm(formula = temp ~ DJI + Trump, data = daily_df)
##
## Coefficients:
## (Intercept) DJI Trump
## 0.00954 1.04214 -0.00360
##
##
## [[6]]
##
## Call:
## lm(formula = temp ~ DJI + Trump, data = daily_df)
##
## Coefficients:
## (Intercept) DJI Trump
## -0.000279 0.833710 -0.000286