0
$\begingroup$

I'm writing an algorithm that outputs the number of stocks I have to buy for each product in order to get as close as possible to my target weights.

I was thinking at this minimization problem:

$$\min_{x_i}\sum_{i=0}^n (x_i - \frac{T * W_i}{P_i})^2$$

with costraint:

  • $\sum_{i=0}^n x_i * P_i < T $
  • $x_0, x_1, ...,x_n$ are non negative Integers

where:

  • there are $n$ different products
  • $x_i$ are (non negative) integers that indicate the quantity to hold (fractional stocks not allowed)
  • $T$ is the (non negative) total amount of money I can invest at this time
  • $W_i$ is my (non negative) target weight for each product
  • $P_i$ is the (non negative) last closing price for the product

I would like to know if there is a closed formula to solve problems such as this, or what kind of numerical techniques should I look into.

For now I'm not considering brute-force solutions.

(Bonus points if you mention a lightweight C++ library that could help here)

$\endgroup$
3
  • $\begingroup$ Something like this? quant.stackexchange.com/q/59966/31263 $\endgroup$ Commented Jan 18, 2022 at 21:56
  • $\begingroup$ By the way; how do you award bonus points? $\endgroup$ Commented Jan 18, 2022 at 21:57
  • $\begingroup$ The algorithm in the accepted answer is order dependent and is far away from an optimal solution, as for the bonus points, I LIED $\endgroup$
    – AathakA
    Commented Jan 18, 2022 at 22:27

1 Answer 1

1
$\begingroup$

The problem that you have suggested minimizes the difference in the number of shares. If the share prices of the products that you are considering are very different, this could lead to undesirable outcomes. I would suggest that instead you minimize the difference in the dollars invested, which will give you the closest possible portfolio to your target.

So the objective function would become:

$x_i * P_i - T * W_i$

This is a mixed integer optimization problem. You could use:

$\endgroup$
1
  • $\begingroup$ Thank you for the answer, I struggle to understand this point, may you elaborate "If the share prices of the products that you are considering are very different, this could lead to undesirable outcomes" with an example? $\endgroup$
    – AathakA
    Commented Jan 18, 2022 at 22:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.