# Optimization algorithm for maintaning portfolio weights

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)

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

$$x_i * P_i - T * W_i$$