0

Quick and hopefully easy question. Let's say I'm looking to invest some money in stocks and I've got 5 I want in total, of these 5 I want to invest equally in all of them, 20% of the total capital weight each.

the problem being of course that each stock price has a different cost, so it's going to be unlikely that I can buy a combination of shares which will give me exactly 20% in each stock.

So the question is, is there a fast way to, or function, for solving non-linear problems like this, so that I can input the stock price and then the desired weight and get the solution for the least total difference?

Cheers fo the help!

DavimusPrime
  • 368
  • 4
  • 17

1 Answers1

0

May be use a MIP (Mixed Integer Programming) solver. The problem can be formulated as:

 min sum(i, abs(target(i) - price(i)*purchase(i)))
 subject to 
     sum(i, price(i)*purchase(i)) <= budget 
 purchase(i): integer variable

The absolute value can be linearized:

 min sum(i,z(i))
 -z(i) <= target(i) - price(i)*purchase(i) <= z(i)

Alternatively you can use a quadratic objective:

 min sum(i, (target(i) - price(i)*purchase(i))^2 )
 subject to 
     sum(i, price(i)*purchase(i)) <= budget 
 purchase(i): integer variable

This would require a MIQP solver.

Erwin Kalvelagen
  • 15,677
  • 2
  • 14
  • 39