I have a portfolio or $N$ assets in $t=10$ days.

import numpy as np
import pandas as pd
n= 10
A = pd.DataFrame([np.random.randn(5) for i in range(n)],columns=['a', 'b', 'c', 'd', 'e'])

T = A.shape[0]
k = A.shape[1]

The covariance matrix

Σ = A.cov().to_numpy()
Sigma = Σ

I want to minimize the variance with convex optimization in Python.

Actually I want to solve the

$$\min \quad (1/2) w^T \Sigma w$$ s.t $$w_{i}\geq 0,\sum_{i=1}^{n}w_{I} =1$$

So I do :

import cvxpy as cp
w = cp.Variable(n)

# Defining risk objective
risk = cp.quad_form(w,Sigma)
objective = cp.Minimize((1/2)*risk)

# Budget and weights constraints
constraints = [cp.sum(w) == 1, 
                w >= 0]
# Solver 
prob = cp.Problem(objective, constraints)

but I receive an error:

Exception: Invalid dimensions for arguments.

what is my mistake here ? Anybody ?

  • $\begingroup$ Be careful in terms of 1. how many assets you want to trade 2. how many observations of returns you have for said assets to estimate the covaraince matrix. $\endgroup$ Dec 30, 2021 at 18:45

1 Answer 1


your Sigma matrix is 5x5 and not 10x10, try this

A = pd.DataFrame(
      [np.random.randn(n) for i in range(5*n)],
      columns=[chr(65+i) for i in range(n)]

it will work.

[ADDITION following a remark] I assumed that you expected the portfolio to be of dimension 10 (because you write n=10;w = cp.Variable(n)), hence your covariance matrix should have the dimension of the portfolio, ie 10.

  • $\begingroup$ it worked but I wonder:the variance covariance matrix is $n \times n$, so it must be $5 \times 5$.Why $10 \times 10$?(is $X^T X/(n-1) $ in dimensions calculations there are $5 \times 10 @ 10 \times 5 = 5 \times 5 $) $\endgroup$
    – user57440
    Dec 30, 2021 at 17:01
  • $\begingroup$ @HungryHomer my answer in ly answer ;{)} $\endgroup$
    – lehalle
    Dec 30, 2021 at 17:55
  • $\begingroup$ thanks a lot. I didn't notice that $\endgroup$
    – user57440
    Dec 30, 2021 at 18:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy