# Minimum variance portfolio in Python

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'])
A

T = A.shape[0]
k = A.shape[1]
print(T,k)


The covariance matrix

Σ = A.cov().to_numpy()
Sigma = Σ
print(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
objective = cp.Minimize((1/2)*risk)

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



but I receive an error:

Exception: Invalid dimensions for arguments.


what is my mistake here ? Anybody ?

• 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. Dec 30, 2021 at 18:45

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.

• 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$)
– user57440
Dec 30, 2021 at 17:01
• @HungryHomer my answer in ly answer ;{)} Dec 30, 2021 at 17:55
• thanks a lot. I didn't notice that
– user57440
Dec 30, 2021 at 18:44