# Qiskit sample - Portfolio optimization

I've recently tried to run this sample from Qiskit (Portfolio Optimization)

I was able to change RandomDataProvider to YahooDataProvider and able to run it on real stock prices.

However, there is one peculiar challenge I'm facing - I'm not sure if it is my lack of understanding. At this particular code

budget = num_assets // 2  # set budget
penalty = num_assets      # set parameter to scale the budget penalty term
qubitOp, offset = portfolio.get_operator(mu, sigma, q, budget, penalty)


No matter what budget or penalty I set this to, I always receive portfolio with about half of the total number of assets. For example, if my total number of assets is 5, then my budget is 2 (from above code). The result always contains 2 assets [0 0 1 1 0]

If I change my budget to

budget = num_assets // 3


and my total assets are 5, then I expect to see only 1 asset in the resulting portfolio. However, I see 2

If I increase my num_assets to 10 and make

budget = num_assets


I still get a portfolio of 5 or 6 stocks (close to half of 10) and not a portfolio of 10.

Note - I'm running on qasm_simulator

Is there a gap in my understanding? What role do these variables - budget and penalty - play while building the portfolio?

• As @tsgeorgios pointed out, the constraint is added as a penalty term. If you change the data source, you may need to adjust the penalty factor and increase it. The penalty factor must be large enough to enforce the constraint. – Stefan Woerner Sep 6 '20 at 10:57

The budget constraint is only added as a penalty term (multiplied by ‘penalty’ coefficient) in the Hamiltonian and does not enforce equality. This means the objective function is $$\text{min}_{x\in\{0,1\}^n} \hspace{0.5em} q x^T \Sigma x - \mu^T x + \text{penalty} \cdot (B - 1^T x)^2$$