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

Hello, I could really use some help with my capstone project. The problem I have is way over my head.

My problem lies with a function I am using. (optimal_portfolio)
I got the function from a previous lesson on codeacademy:

Initially the function wouldnâ€™t work because as_matrix() is no longer used or something?
So, I replaced it with to_numpy().

However, now I get an error that is way over my head:

opt/miniconda3/lib/python3.7/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

If someone could help me I would really appreciate it

Here is the optimal_portfolio 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``````

Just figured it out! If anyone is struggling, the problem lies in what is being passed into the function.

I found out, I was passing in some-non numbers.

Hope this helps!

1 Like

Hi Oleksiy,

I am having the exact same problem and Iâ€™m not exactly sure what you mean by non-numbers. Do you mean NaN values? If so, how do I avoid passing these numbers into the function?

I would really appreciate your help on this

Hi Logan,

By â€śnon-numbersâ€ť I mean anything but a number. If i remember correctly the function only takes numbers, what is being passed in is something else. Check the value you are passing into the function.

Hi Oleksiy,
Thanks! I did that and I got it to work. On a sort of unrelated note, when you call the optimal_portfolio function with the code
â€śweights, returns, risks = optimal_portfolio(returns)â€ť,
is there a piece of code I can write to select the weight and return of a portfolio with a given value for volatility? Right now, I have the efficient frontier graph plotted out, but Iâ€™m struggling with how to pull out the information I need from the graph.
Thanks again!