1

I am working on boyd MOOC, CVX101, I am trying to do the third homework in Python and I am encoutering a few problems

We have to solve the following program

enter image description here

We generate the data with:

# ---- Data Generation ---- # np.random.seed(5) n = 20 # Covariance matrix S = np.random.rand(n,n) S = S.T.dot(S) S = S/np.max(np.abs(np.diag(S)))*.2 S[:,-1] = 0 S[-1,:] = 0 # Uniform weight vector x_unif = np.ones((n,1)) / n # Price vector pbar = np.ones((n,1))*.03 + np.array(np.append(np.random.rand(n-1,1),0)).reshape((-1,1))*.12 

And what I did

from cvxpy import quad_form from cvxpy import sum as cvxsum x_unconstrained = cp.Variable(n) constraints = [cvxsum(x_unconstrained) == 1, pbar.T * x_unconstrained == x_unif.T * pbar ] obj_3 = cp.Minimize(quad_form(x_unconstrained, S)) prob = cp.Problem(obj_3, constraints) prob.solve() print("status:", prob.status) print("optimal value", prob.value) print("optimal var", x_unconstrained.value) 

This is the result I got

status: infeasible optimal value inf optimal var None 

As a side note I have the solution in matlab

simple_portfolio_data; %% part i %minimum-risk unconstrained portfolio %with same expected return as uniform %allocation cvx_begin cvx_quiet(true) variable x_unconstrained(n) minimize(quad_form(x_unconstrained,S)) subject to sum(x_unconstrained)==1; pbar’*x_unconstrained==x_unif’*pbar; cvx_end 

1 Answer 1

2

I think you intended to do a matrix multiply with x_unif' and pbar. Confusingly, since these are both numpy arrays, using the * operator will try to do element-wise multiplication, broadcasting when it can. Therefore the shape of

(x_unif.T * pbar).shape 

is (20, 20). So you just need to replace this with a matrix multiply. If you are using Python 3.5 or newer you can do:

x_unif.T @ pbar 

otherwise this will work everywhere:

np.dot(x_unif.T, pbar) 

Then you should get a feasible result:

status: optimal optimal value 6.593319112947055e-06 optimal var [-0.04367061 0.14013956 -0.165039 0.11715289 0.26894204 0.19991486 -0.18222916 -0.06746431 -0.28428226 -0.1740003 0.14624092 -0.29178846 0.0979433 0.02320117 -0.29351406 0.06030019 0.13121461 0.14653953 0.24223093 0.92816817] 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.