用R语言自动构建指定风险和收益的现代投资组合

用R实现,通过指定期望收益、风险、权重等条件,自动创建现代投资组合。

# 获得四只股票股价收盘价数据
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)

感谢阅读,欢迎关注和留言
量化投资与期货外汇散仙,基金保险水平也拿的出手

你可能感兴趣的:(人工智能,r,量化)