Search code examples
pythonnumpymathscipyfinance

Compute a list of rounded proportions


Required:

[10,20,-30] -> [1,2,-3]
[19,-14,15] -> [2,-1,2]
[-1.09,-0.92,0.02] -> [-109,-92,2]
[501.6545,-1857.1,897.543] -> [5,-19,9]

The number closest to zero in each input set should be a single digit number in the output. The proportions must be kept approximately constant, rounding errors accepted.

Context: Converting the number of shares of securities to buy from a model to round lots of 100 using the smallest orders possible.

I can brute force this in a non-pythonic way but I'm looking for pointers on Python functions to use. My background is Java.


Solution

  • In Python you would use numpy for such calculations. I would suggest an algorithm like this:

    def process(array):
        order_of_magnitude = np.floor(np.log10(np.min(np.abs(array))))
        return np.round(array*10**(-order_of_magnitude))
    

    Explanation:

    1. Find the order of magnitude of the smallest element in the array (regardless of sign).
    2. Scale every element (or up) according to this.
    3. Round the result

    You will need to install numpy for this. For example with pip or via your linux distribution.

    Turn your lists into numpy arrays like this:

    array = np.array(your_list)