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
stk <- read_csv("~/GOVT8002/Spring 2023/Lab VII/stocks2020.csv",  col_names = TRUE)

## Reading in presidential market data
pres_mkt <- read_excel("~/GOVT8002/Spring 2023/Lab VII/USPres_2020_Price History By Market -Bulk.xlsx", 
                       col_names = TRUE) %>%   
  dplyr::rename("date" = "Date (ET)", 
         "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
trump2020 <- pres_mkt %>%
  filter(year(date) > 2019 & name == "Donald Trump") %>%
  dplyr::select(c(date, "Trump" = price))

7.3 Merge the stock price and Trump price data

## Joining the two datasets
stk_pres <- left_join(stk, trump2020, by = "date")

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
stk_num <- length(stk_tickers)

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
pct_change <- function(x){
  
(x - dplyr::lag(x))/dplyr::lag(x)
  
}

## Daily Change Dataset
daily_df <- stk_pres %>% 
  dplyr::mutate_at(c("DJI", "Trump", stk_tickers), pct_change) %>% 
  dplyr::select(c(date, c("DJI", "Trump", stk_tickers)))

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
ols_results <- data.frame("row" = 1:stk_num,
                         "ticker" = NA, 
                         "coef" = NA, 
                         "se" = NA,
                         "tStat" = NA)

## Looping Though Regressions
for(i in 1:stk_num){
  daily_df$temp <- unlist(daily_df[, i + 3])
  ols.1 <- lm(temp ~ DJI + Trump, data = daily_df)
  ols_results[i, "ticker"] <- stk_tickers[i]
  ols_results[i, 3:5] <- round(summary(ols.1)$coefficients["Trump", 1:3], 3)
}

## 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()
ols_results2 <- lapply(stk_tickers, function(x){
  daily_df$temp = unlist(daily_df[, which(names(daily_df) == x)])
  ols.1 <- lm(temp ~ DJI + Trump, data = daily_df)
})

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