Error in quadratic programing in R using portfolio.optim function
<p>I’m trying to create the realized efficient frontier from a quarter period, with the daily closing prices of a hundred stocks, no short positions allowed. </p>

<p>The first step is to calculate the daily return for the period for each stock:</p>

<pre><code>setwd("/Users/ClariceLoureiro/Desktop/COPPEAD/5th Term/Introducao ao Pacote estatistico em R/db")
getwd()
library(tseries)
Quarter &lt;- read.csv2("20153Q.csv",header=T,dec=".")
assets &lt;- Quarter
n &lt;- nrow(assets)
returns &lt;- (assets[2:n,])/(assets[1:n-1,])-1
</code></pre>

<p>Then I used the portfolio.optim() function from the {tseries} to perform the quadratic programing and create the an optimum portfolio:</p>

<pre><code>w2 &lt;-portfolio.optim(as.matrix(returns),shorts=FALSE,riskless=FALSE)
</code></pre>

<p>But, when I run this function the following message appears: </p>

<pre><code>Error in solve.QP(Dmat, dvec, Amat, bvec = b0, meq = 2) : 
matrix D in quadratic function is not positive definite!
</code></pre>

<p>When I run the same code for fewer stocks, It seems to work well:</p>

<pre><code># Choosing just 70 stocks out of 100
Quarter &lt;- read.csv2("20153Q.csv",header=T,dec=".")
assets &lt;- Quarter[,1:70]

#Calculating the returns
n &lt;- nrow(assets)
returns &lt;- (assets[2:n,])/(assets[1:n-1,])-1

#Portfolio optimization 
w2 &lt;-portfolio.optim(as.matrix(returns),shorts=FALSE,riskless=FALSE)

#Weights 
w2$pw

[1] -3.644189e-19  2.390930e-18  1.156864e-01 -3.918512e-16  2.676315e-17 -3.136607e-16
[7]  3.158552e-16  3.901110e-16 -1.112018e-17 -1.927371e-16  1.264102e-19  9.040602e-17
[13]  4.881587e-02  2.291796e-17 -6.328846e-17  8.224983e-02  1.210207e-16  1.329818e-16
[19]  3.460248e-17  8.966350e-02 -4.929045e-17  1.689343e-17 -9.573418e-17  0.000000e+00
[25] -1.323861e-18  1.133006e-01 -1.896390e-17 -1.386383e-17  1.525087e-16  4.805648e-02
[31] -4.695605e-18  6.110056e-02  6.128005e-17 -1.042136e-17  9.100962e-03  1.846112e-17
[37]  5.128598e-17 -3.981178e-16 -4.379979e-16  1.936907e-17  4.694298e-02  2.676847e-18
[43]  8.752091e-18  4.121872e-02  2.970893e-17  6.871426e-03  3.612246e-17  4.217859e-17
[49] -4.834692e-18  3.071602e-17 -7.301697e-19 -1.309647e-17  2.034399e-02  4.689105e-03
[55] -6.014390e-19  6.389368e-02  7.511315e-02 -4.338530e-17  1.551683e-18 -6.838667e-20
[61]  1.445453e-18  4.783709e-17  4.803861e-17  1.866350e-02 -1.471388e-17  1.100957e-01
[67]  1.809216e-02  2.610136e-02 -2.751673e-17  1.393180e-18

# It must sum 1

sum(w2$pw)
[1] 1
</code></pre>

<p>Anybody knows why I’m facing this problem?
Thank you very much!</p>