I wrote a code inspired by Rod's answer to this question. It is supposed to find the minimum variance portfolio of stocks and allows for arbitrary constraints on the weights of each stock:

weights = wtsV /. MV[[2]];
Print["Expected return is"];
Print[Sum[weights[[i]]*expR[[i]], {i, 1, Length[weights]}]];
Print["Expected standard deviation is"];

expR is a list containing expected returns, sd a list containing expected standard deviations, corr is the correlation matrix,reqR the required return and cons the constraints on the weights of individual stocks. wtsV is then the vector containing weights of each stock and pret and pvar are the portfolio return and variance, respectively. Now, if the weights are not restricted, i.e. one can short any stock(s), everything works well. But if I use constraints on the weights, the code returns unevaluated, i.e. only e.g. MV$10261 appears (for the Print[MV] line of code) along with the corresponding unevaluated expected return and standard deviation. If I run the code step by step outside the optP function, it seems to work. Any ideas on what the problem might be?

  • $\begingroup$ the MV$10261 is indicating MV was never assigned in the module. Hard to say more without seeing the input. $\endgroup$
    – george2079
    Oct 16 '15 at 20:00
  • $\begingroup$ note if cons is a list then cons==0 is neither true nor false and neither expression inside the If block is evaluated. You might want that to be If[TrueQ[cons==0] , .. $\endgroup$
    – george2079
    Oct 16 '15 at 20:03
  • $\begingroup$ @george2079 You are right, changing the condition to TrueQ[cons==0] solved the problem. However, I thought that the two were equivalent...? $\endgroup$
    – Skumin
    Oct 16 '15 at 20:08
  • $\begingroup$ Equal can return True or False or remain unevaluated. If you do for example {0}==0 it remains unevaluated. Wrapping in TrueQ forces any undetermined case to be False (more like you'd expect in a traditional language) $\endgroup$
    – george2079
    Oct 16 '15 at 20:57