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.

For your reference this is the link to the project:

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 :slight_smile:

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]
  returns = [blas.dot(pbar, x) for x in portfolios]
  risks = [np.sqrt(blas.dot(x, S*x)) for x in portfolios]
  m1 = np.polyfit(returns, risks, 2)
  x1 = np.sqrt(m1[2] / m1[0])
  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 :slightly_smiling_face:

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!