S.O.S Capstone Analyzing Financial Data with Python ,ValueError: Rank(A) < p or Rank([P; A; G]) < n

Hello, I have had an error that I have been trying to solve for a couple days with no luck. If anyone could help, I would really appreciate it.

This is the error:
(It is way over my head in terms of my programming knowledge)

site-packages/cvxopt/coneprog.py", line 2067, in coneqp
raise ValueError(“Rank(A) < p or Rank([P; A; G]) < n”)
ValueError: Rank(A) < p or Rank([P; A; G]) < n

The issue arises from the ‘optimal_portfolio’ function. I actually copy and pasted someone elses completed code, and it still wouldn’t work. Could it just be my computer?

Here is the function:

def optimal_portfolio(returns):
n = returns.shape[1]
returns = np.transpose(returns.to_numpy()) # originally as_matrix changed to values

N = 100
mus = [10**(5.0 * t/N - 1.0) for t in range(N)]

# Convert to cvxopt matrices
S = opt.matrix(np.cov(returns))
pbar = opt.matrix(np.mean(returns, axis=1))

# Create constraint matrices
G = -opt.matrix(np.eye(n))   # negative n x n identity matrix
h = opt.matrix(0.0, (n ,1))
A = opt.matrix(1.0, (1, n))
b = opt.matrix(1.0)

# Calculate efficient frontier weights using quadratic programming
portfolios = [solvers.qp(mu*S, -pbar, G, h, A, b)['x']
              for mu in mus]
## CALCULATE RISKS AND RETURNS FOR FRONTIER
returns = [blas.dot(pbar, x) for x in portfolios]
risks = [np.sqrt(blas.dot(x, S*x)) for x in portfolios]
## CALCULATE THE 2ND DEGREE POLYNOMIAL OF THE FRONTIER CURVE
m1 = np.polyfit(returns, risks, 2)
x1 = np.sqrt(m1[2] / m1[0])
# CALCULATE THE OPTIMAL PORTFOLIO
wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x']
return np.asarray(wt), returns, risks

Please let me know if you can help in anyway :slight_smile:

I figured it out!
The problem lies in what you are passing into the function.

i was passing in some non-numbers

I hope this helps

1 Like