# Calculate mean variance portfolio

I am trying to calculate the mean variance portfolio using the plug-in approach.

First I generate some artificial data:

x <- replicate(10,rnorm(1000))


Then I apply the plug-in principle:

#count number of columns in the datasets
N <- ncol(x)

#create vector of ones
In <- rep(1,N)

#calculate covariance
covariance <- cov(x)

#calculate mean returns
mu <- colMeans(x)
mu <- t(t(mu))

#use the plug-in principle

xt <- solve(covariance) %*% mu
mean.var <- as.vector(xt) / abs(In %*% xt)


I would like to know:

1. Is this the correct way to implement the mean variance strategy?

2. How can I incorporate a risk-aversion parameter in this framework?

There is one minor mistake: If you compute sum(mean.var) you'll obtain $-1$ instead of $1$. So it should be
 mean.var<-xt/sum(xt)

in order to ensure that the weights sum up to one. The remainder is correct. Incorporating a risk aversion parameter into the framework requires the solution to the minVar problem (See for example here). Therefore, dividing your result with the risk aversion parameter $\gamma$ is sufficient to solve your problem.