library(xts)
## Loading required package: zoo
##
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
##
## as.Date, as.Date.numeric
library(quantmod)
## Loading required package: TTR
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
library(lubridate)
##
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
##
## date, intersect, setdiff, union
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
# Set date range
begin_date <- "2013-01-01"
end_date <- "2015-12-31"
# Valid tickers only (AEZS removed)
stock_namelist <- c("AAPL", "AMD", "ADI", "ABBV", "A", "APD", "AA", "CF")
# Safely get adjusted close prices
data_set <- xts()
for (symbol in stock_namelist) {
tryCatch({
stock_data <- Ad(getSymbols(symbol, from = begin_date, to = end_date, auto.assign = FALSE))
data_set <- cbind(data_set, stock_data)
}, error = function(e) {
message(paste("Skipping:", symbol, "— not available."))
})
}
# Rename columns to match tickers
colnames(data_set) <- stock_namelist
# Calculate log returns
X <- diff(log(data_set), na.pad = FALSE)
print(head(X))
## AAPL AMD ADI ABBV A
## 2013-01-03 -0.012702938 -0.015936577 -0.016267757 -0.008291405 0.003575422
## 2013-01-04 -0.028249542 0.039375128 -0.017947523 -0.012713820 0.019555223
## 2013-01-07 -0.005899345 0.030420658 0.003052831 0.002033667 -0.007259162
## 2013-01-08 0.002687468 0.000000000 -0.010370255 -0.022004529 -0.008022628
## 2013-01-09 -0.015752318 -0.015094611 -0.002609039 0.005620058 0.026649317
## 2013-01-10 0.012319894 -0.003809616 0.012041188 0.002945649 0.007354819
## APD AA CF
## 2013-01-03 -0.0035005091 0.008858913 -0.004740656
## 2013-01-04 0.0133513147 0.020732178 0.022152126
## 2013-01-07 -0.0009229190 -0.017429680 -0.003753372
## 2013-01-08 0.0018453717 0.000000000 -0.014768762
## 2013-01-09 0.0133906906 -0.002200167 0.034376496
## 2013-01-10 -0.0009099872 -0.012188554 0.014916930