Skip to content

fix(portfolio): stop dropping a lot when flooring to size_granularity - #894

Merged
polakowo merged 5 commits into
polakowo:masterfrom
stooq1:fix-size-granularity-float
Nov 8, 2026
Merged

polakowo merged 5 commits into
polakowo:masterfrom
stooq1:fix-size-granularity-float

Conversation

@stooq1

@stooq1 stooq1 commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

With a fractional size_granularity, the Numba engine fills one lot less than asked whenever the size is an exact multiple of the lot. The Rust engine fills the full size, so the same call gives different trades depending on whether vectorbt-rust is installed. vectorbt 1.2.0 / master @ 8e30b8c, from_orders at price 10, init_cash=100:

case Numba Rust
buy 1.0, lot 0.1 0.9 1.0
buy 1.0, lot 0.001 0.999 1.0
buy 0.9 then sell 0.9, lot 0.1 0.8, 0.8 0.9, 0.9
buy all cash (size=np.inf), lot 0.1 9.9 10.0
buy 1.0, lot 0.1, allow_partial=False rejected 1.0

from_signals with size=1.0, lot 0.1, fees 0.1%, prices 100, 120, 130, 150 (enter, exit, enter, exit): Numba buys 0.9, sells 0.8, keeps 0.1 open and skips the second entry, total profit 20.81; Rust trades 1.0 four times, total profit 39.50.

The cause is adj_size // size_granularity * size_granularity (nb.py#L145, #L170, #L294). Float // is computed from fmod, and 1.0 // 0.1 == 9.0. The Rust engine uses (adj_size / size_granularity).floor() (portfolio.rs#L850, #L876, #L1042).

Both engines now floor through one helper (floor_to_granularity_nb in nb.py, floor_to_granularity in portfolio.rs). A lot count within 4 machine epsilons of a whole number (relative, about 8.9e-16, so only floating-point rounding) counts as that number, anything further below is floored, and the result is capped at the input size. The script below then prints the Rust column for both engines.

The cases above are in test_size_granularity_fractional (tests/test_portfolio.py, runs in the job without vectorbt-rust) and test_from_orders_fractional_size_granularity_parity (tests/test_engine.py, Numba against Rust for lots 0.1, 0.01, 0.001). Lot boundaries: test_size_granularity_lot_boundary (4.3 and 8.1 at 0.1, 0.29 and 0.58 at 0.01, exact closes, allow_partial=False, all cash) and test_from_orders_size_granularity_lot_boundary_parity (k lots for k = 1..1000 at 0.1, 0.01 and 0.001, bought and closed in both engines). Rounding bound: test_size_granularity_rounding_bound and test_from_orders_size_granularity_rounding_bound_parity (1.0000000006 at a lot of 1e-9 fills 1.0, sub-lot sizes at lots of 0.001, 0.1 and 1000 do not trade, a size one ulp short of a lot still fills).

Sizes that are a lot multiple but land just under it after the division (4.3 / 0.1 == 42.99999999999999) used to lose a lot in both engines. The second commit keeps them on the lot, and 9dcbd1b bounds that snap to rounding error so a fraction of a lot is floored at any lot count (numbers in the comments below).

Script
import numpy as np, pandas as pd
import vectorbt as vbt

close = pd.Series([10.0, 10.0])
cases = {
    'buy 1.0, lot 0.1': dict(size=pd.Series([1.0, np.nan]), size_granularity=0.1),
    'buy 1.0, lot 0.001': dict(size=pd.Series([1.0, np.nan]), size_granularity=0.001),
    'buy 0.9 then sell 0.9, lot 0.1': dict(size=pd.Series([0.9, -0.9]), size_granularity=0.1),
    'buy all cash (100 at 10), lot 0.1': dict(size=pd.Series([np.inf, np.nan]), size_granularity=0.1),
    'buy 1.0, lot 0.1, allow_partial=False': dict(size=pd.Series([1.0, np.nan]), size_granularity=0.1, allow_partial=False),
}
for name, kwargs in cases.items():
    for engine in ('numba', 'rust'):
        pf = vbt.Portfolio.from_orders(close, engine=engine, **kwargs)
        print(f'{name:40} {engine:5} filled {pf.order_records["size"].round(6).tolist()}')

price = pd.Series([100.0, 120.0, 130.0, 150.0])
entries, exits = pd.Series([True, False, True, False]), pd.Series([False, True, False, True])
for engine in ('numba', 'rust'):
    pf = vbt.Portfolio.from_signals(price, entries, exits, size=1.0, size_granularity=0.1, fees=0.001,
                                    init_cash=1000, engine=engine)
    print(f'from_signals {engine:5} orders {pf.order_records["size"].round(6).tolist()} '
          f'profit {pf.total_profit():.2f} left in position {pf.assets().iloc[-1]:.1f}')
buy 1.0, lot 0.1                         numba filled [0.9]
buy 1.0, lot 0.1                         rust  filled [1.0]
buy 1.0, lot 0.001                       numba filled [0.999]
buy 1.0, lot 0.001                       rust  filled [1.0]
buy 0.9 then sell 0.9, lot 0.1           numba filled [0.8, 0.8]
buy 0.9 then sell 0.9, lot 0.1           rust  filled [0.9, 0.9]
buy all cash (100 at 10), lot 0.1        numba filled [9.9]
buy all cash (100 at 10), lot 0.1        rust  filled [10.0]
buy 1.0, lot 0.1, allow_partial=False    numba filled []
buy 1.0, lot 0.1, allow_partial=False    rust  filled [1.0]
from_signals numba orders [0.9, 0.8] profit 20.81 left in position 0.1
from_signals rust  orders [1.0, 1.0, 1.0, 1.0] profit 39.50 left in position 0.0

…ust engine

Float floor division (1.0 // 0.1 == 9.0) dropped one lot from exact multiples
of a fractional size_granularity in the Numba engine: 1.0 at a 0.1 lot filled
0.9, a 0.9 position closed as 0.8, and allow_partial=False rejected the order.
Use np.floor(size / size_granularity), which the Rust engine already does.
@arhancanli

Copy link
Copy Markdown

The patch fixes the exact-multiple case from the description, but sizes that are a multiple of the lot and still land one lot short remain, because x / g itself can come out just under the integer.

I checked out the PR head (0a572c3, Python 3.12, numpy 2.4, pandas 3, numba 0.66) and ran from_orders at price 10, init_cash=1000, one buy of size:

size size_granularity filled
1.0 0.1 1.0
4.3 0.1 4.2
8.1 0.1 8.0
0.29 0.01 0.28
0.58 0.01 0.57
4.3 0.001 4.3

The cause is 4.3 / 0.1 == 42.99999999999999, so np.floor gives 42. Counting over k * g for k = 1..1000 in plain Python: floor((k*g)/g) != k for 47 values of k at g = 0.1 and 68 at g = 0.01, against 493 and 495 for the old //. So the PR removes about 90% of the dropped lots, but not all of them. At g = 0.001 none of the first 1000 multiples are affected, which is why the new test only covers 0.1, 0.01 and 0.001 with sizes that happen to work.

If the Rust engine uses (adj_size / size_granularity).floor() as the description says, it has the same remaining gap, so parity would hold while both are off by one lot for these sizes. A tolerance would close it in both, for example:

q = adj_size / size_granularity
r = np.round(q)
lots = r if abs(q - r) <= 1e-9 * max(1.0, abs(q)) else np.floor(q)
adj_size = lots * size_granularity

A regression test with size=4.3, size_granularity=0.1 (expect 4.3, not 4.2) would pin it. I did not run the Rust engine, only the Numba path.

@polakowo polakowo left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! This improves parity, but size 4.3 with granularity 0.1 still fills 4.2 in both engines. Closing 4.3 leaves 0.1 open. Please include robust lot-boundary rounding in both engines here, with regression tests for exact closes and allow_partial=False.

…anularity

Both engines floor through one helper that treats a size within the
is_close tolerance of a lot multiple as that multiple, so 4.3 at a lot
of 0.1 fills 4.3 instead of 4.2 and closing such a position leaves it
flat. The result is capped at the input size.
@stooq1 stooq1 changed the title fix(portfolio): stop dropping a lot when flooring to size_granularity in Numba fix(portfolio): stop dropping a lot when flooring to size_granularity Oct 28, 2026
@stooq1

stooq1 commented Oct 28, 2026

Copy link
Copy Markdown
Contributor Author

Done in fb6852c. Both engines now round through one helper (floor_to_granularity_nb in nb.py, floor_to_granularity in portfolio.rs): if size / size_granularity is within the existing is_close tolerance (rel 1e-9) of an integer, that integer is used, otherwise it floors. The result is capped at the size it was given, so a fill never exceeds the request or the position.

Price 10, same numbers from Numba and from Rust built from the branch:

case before after
buy 4.3, lot 0.1 4.2 4.3
buy 4.3 (no lot), then sell 4.3 with lot 0.1 sells 4.2, 0.1 left open sells 4.3, flat
same with direction="longonly" and sell -np.inf sells 4.2, 0.1 left open sells 4.3, flat
buy 4.3 then sell 4.3, lot 0.1, allow_partial=False rejected 4.3, 4.3
all cash (43 at price 10), lot 0.1 4.2 4.3
buy 4.35, lot 0.1 4.3 4.3
buy k·lot for k = 1..1000, lot 0.1 / 0.01 / 0.001 47 / 68 / 0 one lot short 0 / 0 / 0

Tests: test_size_granularity_lot_boundary in tests/test_portfolio.py (the rows above; runs in both CI jobs) and test_from_orders_size_granularity_lot_boundary_parity in tests/test_engine.py (k = 1..1000 for the three lots: Numba equals Rust, every buy and every full close fills k·lot, all positions end flat).

Locally tests/test_portfolio.py passes with Numba only (191) and with Rust (191), tests/test_engine.py 165.

@arhancanli

Copy link
Copy Markdown

That covers it. Reading the diff: both paths snap to the nearest lot inside the is_close tolerance, otherwise floor, and the min(lots * size_granularity, size) cap handles the case where 43 * 0.1 lands a hair above 4.3. The parity test over k = 1..1000 for three lot sizes is the right shape, because that is where the 47 / 68 misses came from. I only read the diff and your table here; I did not re-run either engine.

One edge I would pin with a test: because the snap uses a relative tolerance, a size a hair under a lot, such as 0.0999999999 with size_granularity=0.1, snaps up to one lot and the cap then fills 0.0999999999. That is a fill that is not an exact multiple of the lot, by about 1e-10 lots. It is harmless numerically, but it means "fills are always multiples of the lot" is true only up to the tolerance. Is that the behaviour you want to document, or should sizes that only reach the lot through the tolerance fill the capped size, as now?

… a test

A size within the is_close tolerance of a lot multiple counts as that
multiple and the fill is capped at the requested size, so fills are lot
multiples up to that tolerance. The parity test checks both engines:
0.1 * (1 - 1e-10) at a lot of 0.1 fills the requested size, 0.0999
does not trade.
@stooq1

stooq1 commented Oct 29, 2026

Copy link
Copy Markdown
Contributor Author

Yes, that is deliberate, and it is now written down.

The cap is the invariant I kept: a fill never exceeds the size that was asked for, and never exceeds the position being closed. A size that only reaches a lot through the tolerance therefore fills what was asked instead of being floored to zero, which is what it did before the patch. Rejecting it would turn a size that is one lot for every practical purpose into no trade at all, which is the same class of surprise as the dropped lot.

One detail from running it: 0.0999999999 itself lands just outside the tolerance (0.0999999999 / 0.1 is 0.9999999989999999, about 1.00000008e-9 from 1), so it floors to zero and does not trade in either engine. 0.1 * (1 - 1e-10) is inside and fills 0.09999999999.

Done in 38ed377: the Order.size_granularity docstring now says that fills are multiples of the granularity up to the is_close_nb tolerance and never larger than the requested size, and test_from_orders_size_granularity_tolerance_parity pins both sides in both engines: 0.1 * (1 - 1e-10) at a lot of 0.1 fills the requested size, 0.0999 does not trade. tests/test_engine.py: 166 passed (numba 0.68.0, numpy 2.5.4, pandas 3.1.0).

@arhancanli

Copy link
Copy Markdown

Thanks, the wording in the docstring is what I wanted: "up to the tolerance, never larger than requested" covers both of the cases I was unsure about. I re-ran the two numbers: 0.0999999999 / 0.1 is 0.9999999989999999, 1.0000000827e-09 from 1, and 0.1 * (1 - 1e-10) gives 1.0000000827e-10, so a decade apart and on opposite sides of a relative tolerance of 1e-9. That makes the boundary easy to pin from both sides.

One related thing worth a test if it is not there yet: a relative tolerance means the absolute slack grows with the lot size. At a lot of 1000 the same 1e-9 relative band is about 1e-6 shares wide, so a size that clears the tolerance at one lot size is a different absolute amount at another. Do you parametrize the tolerance test over lot sizes (0.001, 0.1, 1000), or only 0.1?

@polakowo polakowo left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update! The original cases are fixed, but the tolerance grows with the lot count: size 1.0000000006 with granularity 1e-9 fills 1,000,000,000.6 lots. Please bound the snap to floating-point rounding error and add large-lot-count and genuinely sub-lot regression cases in both engines.

The snap to the next lot used is_close (relative 1e-9) on the number of
lots, so the window grew with the lot count: 1.0000000006 with a
granularity of 1e-9 filled 1,000,000,000.6 lots. Both engines now count
a lot number as whole only within 4 machine epsilons (about 8.9e-16
relative), which covers the rounding of the size, the granularity and
their quotient, and floor anything further below a multiple.

0.1 * (1 - 1e-10) with a lot of 0.1 is now a real shortfall and does not
trade, so the tolerance test from the previous commit is replaced by
cases at 1e9 and 1e12 lots, sub-lot sizes at lots of 0.001, 0.1 and
1000, and sizes one ulp short of a lot, in both engines.
@stooq1

stooq1 commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Done in 9dcbd1b. The snap is now bounded by rounding error in both engines: a lot count within 4 machine epsilons of a whole number (relative, about 8.9e-16) counts as that number, anything further below is floored. Before it was is_close with rel 1e-9, a whole lot at 1e9 lots.

Price 10, the same output from Numba and from Rust built from the branch:

size lot before after
1.0000000006 1e-9 1.0000000006 1.0
0.9999999996 1e-9 0.9999999996 0.999999999
0.1 * (1 - 1e-10) 0.1 0.09999999999 no trade
1000 * (1 - 1e-10) 1000 999.9999999 no trade
one ulp under 0.1 0.1 0.09999999999999999 0.09999999999999999
4.3 0.1 4.3 4.3

The third row reverses what I wrote above on 29.10: 1e-10 of a lot is a real shortfall, so it no longer trades, and the size_granularity note now says fills are multiples up to rounding error.

Why 4 eps: for a size of k lots, size / granularity lands within 1 eps of k (k up to 20,000, lots from 1e-9 to 1000), and sizes the engine derives first (value / price, all cash after fees) stay within 2.4 eps.

One limit remains. A position summed from many fills of one lot drifts further than that: 1000 buys of 0.1 add up to 99.9999999999986, and closing it sells 99.9 and leaves 0.1 open, as master does. Keeping closes flat up to about 9,000 fills would take about 1000 eps, a 0.2-lot window at 1e12 lots, so the bound stays at 4 eps.

The new cases are test_size_granularity_rounding_bound in tests/test_portfolio.py and test_from_orders_size_granularity_rounding_bound_parity in tests/test_engine.py, which replaces the tolerance test from 38ed377: your case, 0.4 and 0.2 lot short at 1e9 and 1e12 lots, sub-lot sizes at lots of 0.001, 0.1 and 1000, and sizes one ulp short of a lot, which still fill.

@polakowo polakowo left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the update! The bounded rounding passes the large-lot and sub-lot checks in both engines. The accumulated-position drift also occurs on master and can be handled separately. Please include #907 before final CI.

@polakowo
polakowo merged commit 337e201 into polakowo:master Nov 8, 2026
25 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants