This is an R Markdown document. Markdown is a simple formatting syntax for authoring HTML, PDF, and MS Word documents. For more details on using R Markdown see http://rmarkdown.rstudio.com.
When you click the Knit button a document will be generated that includes both content as well as the output of any embedded R code chunks within the document. You can embed an R code chunk like this:
summary(cars)
## speed dist
## Min. : 4.0 Min. : 2.00
## 1st Qu.:12.0 1st Qu.: 26.00
## Median :15.0 Median : 36.00
## Mean :15.4 Mean : 42.98
## 3rd Qu.:19.0 3rd Qu.: 56.00
## Max. :25.0 Max. :120.00
You can also embed plots, for example:
Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.
#========================================
# multifactor model
#========================================
rm(list=ls())
#setwd("D:/亞洲大學上課資料/Portfolio management 2016 Fall")
retdata = read.csv('berndt.csv')
t = dim(retdata)[1]
t
## [1] 120
market = retdata[,10]
riskfree = retdata[,17]
market = market - riskfree
retdata1 = retdata[,c(-10, -17)]
retdata1 = as.matrix(retdata1)
n = dim(retdata1)[2]
n
## [1] 15
riskfree_mtx = matrix(rep(riskfree,n), ncol=n)
retdata1<-retdata1 - riskfree_mtx
ones = rep(1,t)
X = cbind(ones,market)
b_hat = solve(t(X)%*%X)%*%t(X)%*%retdata1
E_hat = retdata1 - X%*%b_hat
diagD_hat = diag(t(E_hat)%*%E_hat)/(t-2)
#R-square
retvar = apply(retdata1,2,var)
R_2 = 1 - diag(t(E_hat)%*%E_hat)/((t-1)*retvar)
res_std = sqrt(diagD_hat)
cov_factor = var(market)*t(b_hat)%*%b_hat + diag(diagD_hat)
sd = sqrt(diag(cov_factor));
cor_factor = cov_factor/(sd%*%t(sd));
# sample variance and correlation matrix
cov_sample = cov(retdata1);
cor_sample = cor(retdata1);
# use factor covariance matrix to compute global minimum variance portfolio
one.vec = rep(1,15)
a = solve(cov_factor)%*%one.vec
b = t(one.vec)%*%a
mvp.w =a / as.numeric(b)
as.vector(mvp.w)
## [1] 0.0441958555 0.3784362193 0.0057086517 -0.0240242882 -0.0054729231
## [6] 0.0527807083 0.1822287491 0.0427075778 0.1849916457 0.0333480876
## [11] 0.0074189426 0.0666131371 -0.0268521162 0.0581325010 -0.0002127482
barplot(as.vector(mvp.w), ylim = c(-0.01, 0.4), names.arg = rownames(mvp.w), cex.names = 0.5)