-
Notifications
You must be signed in to change notification settings - Fork 3
/
exercise2.R
67 lines (54 loc) · 2.07 KB
/
exercise2.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#install.packages("data.table", "lubridate", "dplyr", ggplot2", "matrixStats")
# load the data.table package
library(data.table)
# load the lubridate package
library(lubridate)
# load the dplyr package to enable use of the pipe operator
library(dplyr)
# load the ggplot library to enable plotting
library(ggplot2)
# load the matrixStats library to enable use of the rowProds operation
library(matrixStats)
# load results of exercise 1
load("wksp/exercise1.RData")
# delete columns containing top and bottom returns plus existing RF column (will be added through the merge again)
portfolios<-portfolios[, !c("return_bottom", "return_top", "RF")]
portfolios
# read Fama-French data
ffdata<-fread("./data/F-F_Research_Data_Factors.csv")
ffdata
# convert date strings to actual dates
ffdata[,date:=as.Date(paste(year, month, "01", sep="-"))]
day(ffdata$date)<-days_in_month(ffdata$date)
ffdata
# delete date columns not needed anymore
ffdata<-ffdata[, !c("V1", "year", "month"), with=FALSE]
ffdata
setnames(ffdata,c("mktrf", "smb", "hml", "rf", "date"))
ffdata$rf<-ffdata$rf/100 # convert from percentage values to actual values
ffdata$mktrf<-ffdata$mktrf/100
ffdata$smb<-ffdata$smb/100
ffdata$hml<-ffdata$hml/100
ffdata
# merge ffdata with portfolio data
portfolios<-merge(portfolios, ffdata, by.x="date", by.y="date")
portfolios
# calculate excess return for the regression
portfolios$return_wml_exc<-portfolios$return_wml - portfolios$rf
portfolios
# regress the excess returns on the Fama-French factors
ffreg<-lm(return_wml_exc ~ mktrf + smb + hml, data=portfolios)
summary(ffreg)
portfolios
# calculate the beta of the WML portfolio
beta = cov(portfolios$return_wml, portfolios$return_mkt)/var(portfolios$return_mkt)
# calculate the alpha for each date
portfolios$alpha<-portfolios$return_wml - portfolios$rf - beta * (portfolios$return_mkt - portfolios$rf)
# plot the alphas
ggplot(data=portfolios,aes(x=date)) + geom_line(aes(y=alpha, color="alpha"),colour="#009682")+
xlab("Date")+
ylab("Alpha")
# calculate the mean alpha
mean(portfolios$alpha)
count(portfolios$alpha > 0)
count(portfolios$alpha < 0)