I’m just writing up some support code to do something I thought would be simple, but turns out to be trickier than I expected.

Basically, if my process generates target weights for a portfolio, but I am constrained by integer share or contract sizes, I want to find the combination of integer shares that fits my budget constraint (long only in this case) and optimizes some value (say Sharpe ratio).

I figured that I’d find the non-integer share/contract counts at the optimal, based on my system criteria, then expand a search sphere (technically a hypersphere) around that point until I find the first point inside that consists of only integers. But I discover that I still need to find a way to compute the nearest all-integer points to sample, and it’s possible that a point farther away might actually have a better objective value (if the optimal falls away faster in one direction than the other).

Alternately, I figured I’d take some sphere around the theoretically optimal point and search all integer-only point, then compute the objective function (e.g. sharpe ratio) for each and then select the best one. Again, finding the nearest all-integer points is the hang-up.

Apparently I am too dumb to figure out how to do either. Have any of you MFE or CQF types done this?

I’m thinking that maybe what I need to do is to take the highest priced share or contract, find the integer that is just above and below the non-integer target number, then expand that number by one to either side (so if the target calls for 8.1 contracts, it will take 8 and 9 as the next-door integers, and expand by one each way to get 7 through 10). Then I look at the smaller cost contracts and figure out what integer spreads * contract price cover the same price range. Repeat for each asset. Then go through each combination and compute the objective function, skipping the calculation for each set of points that doesn’t fit the budget constraint. – this is a brute force solution, but it seems highly inefficient. Surely there is something more elegant.

In practice, I’d been approximating manually, and that’s been ok, but I figured that it’d be nice to get the machine to do it for me, and I thought I would ask the quantsters here if they have a solution (either a description of an algorithm, a reference, or even a code library that does this).

Any ideas? maratikus? jmh? ohai? anyone else?