均值方差优化

Lau*_*sly 5 math optimization finance r matrix

我正在进行均值方差优化来解决投资组合优化问题.我想要做的是尽量减少两个约束的方差:

  1. x1m1 + x2m2 + ... + xnmn =米
  2. X1 + X2 + ... + XN = 1

所以这就是我做的代码:

################ Simulation for n=3 ################
################ Parameters ################
mu<-50  ## Mean of the portfolio
n<-3    ## Number of asset
m1<-30000  ## Size of the simulation
########### 3 Assets ############
x<- rnorm(m1,2,1)
y<- rnorm(m1,0.5,1.5)
z<- rnorm(m1,3.75,1)
d<-data.frame(x,y,z)

################ Solution Directe  ################
Sol<-function(m1) {
A = matrix(nrow=n+2, ncol=n+2)
    for (i in 1:n){
    for (j in 1:n)
        if(i==j) {
              A[i,j] <-  (2*var(d[,i]))
                } else { 
              A[i,j] <-  cov(d[,i],d[,j]) 
    }
    }

   for (i in 1:n){
             A[i,n+1] <-  -mean(d[,i])   
             A[i,n+2] <-  -1     
    }
   for (j in 1:n){
             A[n+1,j] <-  mean(d[,j])  
             A[n+2,j] <-   1    
    }

  for (i in 2:n+2){
    for (j in 2:n+2)
        if(i==j) {
              A[i,j] <-  0   
                } else { 
              A[i,j] <-  0  
    }
    }
A
Inv=solve(A)
Sol=Inv%*%c(0,0,0,m1,1)
result=list(x=Sol,A=A,Inv=Inv)
return(result) 
}
Sol(mu)
Sol(mu)$x  ## The solution 
Sol(mu)$A
Run Code Online (Sandbox Code Playgroud)

我知道,我为R使用了很多不好的东西,但我找不到更好的解决方案.所以我的问题是正确的吗?

任何纠正和建议,以改善这一过程!请随意在R中分享您现有的代码

非常感谢!

J.R*_*.R. 4

一种方法是solnp()Rsolnp包中最小化数字。这还提供了一种添加更多限制(杠杆约束等)的方法:

muVec <- colMeans(d) #mean-vector of assets
Sigma <- cov(d) #covariance-matrix
fmin <- function(x) as.numeric(t(x) %*% Sigma %*% x) #variance of portfolio to min.
eqn <- function(x) c(t(x) %*% muVec, sum(x)) #equality restriction
sol <- function(mu) Rsolnp::solnp(rep(0.5, 3), fun=fmin, eqfun=eqn, eqB=c(mu,1))
x <- sol(50)
Run Code Online (Sandbox Code Playgroud)

求解后,我们现在可以打印参数和投资组合方差:

> x$par
[1]  -5.490106 -11.270906  17.761012
> x$vscale[1]
[1] 630.4916
Run Code Online (Sandbox Code Playgroud)

在您的简单情况下,存在一个封闭的解决方案,可以归结为:

S <- solve(Sigma)
A <- matrix( c(t(muVec) %*% S %*% muVec, 
    rep( t(muVec) %*% S %*% rep(1,3), 2),
    t(rep(1,3)) %*% S %*% rep(1,3)), ncol=2
)
sol2 <- function(mu) S %*% cbind(muVec,1) %*% solve(A) %*% c(mu,1)
Run Code Online (Sandbox Code Playgroud)

“幸运的是”给出了相同的结果:

> sol2(50)
        [,1]
x  -5.490106
y -11.270906
z  17.761012
> fmin(sol2(50))
[1] 630.4916
Run Code Online (Sandbox Code Playgroud)