packages=c("xts",
"quantmod",'tidyverse','glue','readxl','car','lmtest',"dplyr",
"tidyr",'lubridate','frenchdata','ggplot2','sandwich')
for(i in packages){
if(!require(i,character.only = TRUE)) install.packages(i)
library(i,character.only = TRUE)
}
options(warn=-1)
#********************************************************
#Parms Setting
#********************************************************
SD<-'2018-04-01'
ED<-'2019-12-31'
#***********************************************
#Download Data#***********************************************
Tickers <- c('AAPL','AMGN','AXP','BA','CAT','CRM','CSCO','CVX','DIS','GS','HD',
'HON','IBM','INTC','JNJ','JPM','KO','MCD','MMM','MRK','MSFT','NKE','PG',
'TRV','UNH','V','VZ','WBA','WMT')
Tickers <- sort(unique(c(Tickers)))
Names <- paste0(Tickers)
NoF = length(Tickers)
pb = txtProgressBar(title = "progress bar", min = 0,
max = NoF, width = 300)
RawSTK <- list()
Prices <- NULL
for (i in seq(1,length(Tickers))){
tem = loadSymbols(Tickers[i], from = as.Date(SD), to =as.Date(ED),
auto.assign = FALSE, return.class = 'xts')
RawSTK[[i]] <- adjustOHLC(tem,use.Adjusted=TRUE)
Prices <- cbind(Prices,tem[,6])
rm(tem)
Sys.sleep(0.01)
setTxtProgressBar(pb, i, title=paste( round(i/NoF*100, 0),
"% Download Data from Yahoo by hcLee"))
}
close(pb)
colnames(Prices) <- Tickers
Prices <- data.frame(Dates=index(Prices),
Prices)
prices_monthly <- to.monthly(Prices,
indexAt = 'lastof',
OHLC=FALSE)
prices_monthly[ ,1] <- NULL
prices.num <- as.numeric(unlist(prices_monthly))
prices.mon <- matrix(prices.num,ncol=29)
f <- function(x){
na.omit(diff(log(x),lag = 1))*1
}
mon.ret <- apply(prices.mon, 2, f)
colnames(mon.ret) <- paste(Tickers,'mon.ret')
dat.mon.ret <- data.frame(mon.ret)
###3 factors
data_sets <- get_french_data_list()
View(data_sets$files_list)
ff_3_factors <-
download_french_data("Fama/French 3 Factors")
ff_3_factors <-
download_french_data("Fama/French 3 Factors",
dir = ".",
dest_file = "ftp/F-F_Research_Data_Factors_CSV.zip")
a <- ff_3_factors$subsets$data
fac <- matrix(unlist(a[1]),ncol=5)
colnames(fac) <-c('date','mrk-rf','smb','hml','rf')
thr.fac <- fac[1103:1122,-1]
dat.fac <- data.frame(thr.fac)
mrk <- dat.fac[,1]/100
smb <- dat.fac[,2]/100
hml <- dat.fac[,3]/100
rf <- dat.fac[,4]/100
ri.rf <- list()
for (j in 1:ncol(dat.mon.ret)) {
ggg <-(dat.mon.ret[j]-rf)
ri.rf[j] <- ggg
}
ri.rf.mat <- matrix(unlist(ri.rf),ncol=29)
colnames(ri.rf.mat) <- paste(Tickers,'-rf')
g <- list()
for (l in 1:ncol(ri.rf.mat)) {
g [[l]]<- lm(ri.rf.mat[ ,l] ~ mrk+smb+hml)
}
lapply(g, function(x) summary(x)$coefficients )
lapply(g, function(x) summary(x)$r.squared )
lapply(g, function(x) summary(x)$adj.r.squared )