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:
https://www.codecademy.com/paths/finance-python/tracks/analyze-financial-data-with-python-capstone/modules/analyze-financial-data-with-python-capstone/informationals/analyze-financial-data-with-python-capstone

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

https://www.codecademy.com/paths/finance-python/tracks/visualizing-finance-data/modules/portfolio-optimization/lessons/mv-portfolio-optimization/exercises/efficient-frontier-iii

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]
  ## 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!