用R語言自動構建指定風險和收益的現代投資組合

用R實現,經過指按期望收益、風險、權重等條件,自動建立現代投資組合。segmentfault

# 得到四隻股票股價收盤價數據
library(quantmod)

stockData <- new.env()
symbols <- c("MSFT","FB","GOOG","AAPL")
start_data <- as.Date("2014-01-01")
end_date <- as.Date("2017-12-31")
getSymbols(symbols,sec="yahoo",env=stockData,from=start_data,to=end_date)

# [1] "MSFT" "FB"   "GOOG" "AAPL"

x<-list()
for (i in 1:length(symbols)) {
  x[[i]] <- get(symbols[i],pos=stockData)
  if(i==1){
    data <- Ad(x[[i]])
  }
  else {
    data <- cbind(data,Ad(x[[i]]))
  }
}

# 計算收益率、平均收益率、協方差

data_ret <- apply(data, 2, Delt)
avg_ret <- apply(data_ret, 2, mean,na.rm=TRUE)
Covariance_mat <- cov(data_ret,use="na.or.complete")

# 初始權重

# 源代碼位置:http://faculty.washington.edu/ezivot/econ424/portfolio.r

source("portfolio.r")

weights <-c(0.2,0.3,0.35,0.15)

# 指望收益率、標準差和權重

weightsport <- getPortfolio(avg_ret,Covariance_mat,weights)
weightsport

# Call:
#   getPortfolio(er = avg_ret, cov.mat = Covariance_mat, weights = weights)
# 
# Portfolio expected return:     0.0009934422 
# Portfolio standard deviation:  0.01189354 
# Portfolio weights:
#   MSFT.Adjusted   FB.Adjusted GOOG.Adjusted AAPL.Adjusted 
# 0.20          0.30          0.35          0.15 

# 最小方差組合,藍點

minvar_port <- globalMin.portfolio(avg_ret,Covariance_mat)
minvar_port

# Call:
#   globalMin.portfolio(er = avg_ret, cov.mat = Covariance_mat)
# 
# Portfolio expected return:     0.0009279438 
# Portfolio standard deviation:  0.01112518 
# Portfolio weights:
#   MSFT.Adjusted   FB.Adjusted GOOG.Adjusted AAPL.Adjusted 
# 0.3036        0.0671        0.2850        0.3443 

# 給定日收益率,求風險最小的有效投資組合

rf <- 0.0002
effcient_port <- efficient.portfolio(avg_ret,Covariance_mat,rf)
effcient_port

# Call:
#   efficient.portfolio(er = avg_ret, cov.mat = Covariance_mat, target.return = rf)
# 
# Portfolio expected return:     2e-04 
# Portfolio standard deviation:  0.02025839 
# Portfolio weights:
#   MSFT.Adjusted   FB.Adjusted GOOG.Adjusted AAPL.Adjusted 
# -0.2155       -0.9749        1.6681        0.5222 

# 最大化夏普比率的投資組合,切線,紅點

tangency_port <- tangency.portfolio(avg_ret,Covariance_mat,rf)
tangency_port

# Call:
#   tangency.portfolio(er = avg_ret, cov.mat = Covariance_mat, risk.free = rf)
# 
# Portfolio expected return:     0.001242274 
# Portfolio standard deviation:  0.01331219 
# Portfolio weights:
#   MSFT.Adjusted   FB.Adjusted GOOG.Adjusted AAPL.Adjusted 
# 0.5277        0.5170       -0.3122        0.2675 

# 畫出的投資組合的有效邊界、藍點最小方差組合,紅點最大化夏普比率(切線)的投資組合

efficient_frontier <- efficient.frontier(
  avg_ret,Covariance_mat,alpha.min = -2,alpha.max = 2,nport = 50
)

plot(efficient_frontier,plot.assets = TRUE,pch=20)
points(minvar_port$sd,minvar_port$er,pch=13,col="blue")
points(tangency_port$sd,tangency_port$er,pch=13,col="red")
tangent_sharpe_ratio <- (tangency_port$er -rf)/tangency_port$sd
abline(a=rf,b=tangent_sharpe_ratio)

file

感謝閱讀,歡迎關注和留言 量化投資與期貨外匯散仙,基金保險水平也拿的出手
相關文章
相關標籤/搜索