Skip to Content

Costs and capacity

Estimate trading costs from your own trades, stress them, find the cost that erases the edge, and see how performance changes as capital grows.

A backtest’s gross profit is the profit if every trade filled at the reference price for free. Real trades pay commission, cross a spread, move the price, and sometimes borrow stock. Costs are rarely known precisely, and they grow with size, so one cost estimate is a weak answer. The useful questions are how much of the edge each assumption removes, how large a cost the strategy can absorb, and how much capital it can take before impact consumes it.

lacuna.costs answers those from a table of trades you supply. It estimates costs with explicit models, evaluates grids of cost scenarios, solves for the break-even cost, and traces net performance over capital. Every result records the assumptions it used. Where evidence is missing, borrow rates and liquidity data for example, the result says UNKNOWN instead of substituting zero. Other missing inputs, such as a null volume or volatility passed to an impact model, are rejected with a DataContractError; the sections below say which is which.

These are path-independent estimates computed from your fills and market fields. They are not an order-book simulation.

A first example

Four trades, each with the market fields the models need. The price and reference_price are equal here, which means no cost is yet embedded in the price: the models add the costs.

from datetime import date, timedelta

import lacuna as lc
import numpy as np
import polars as pl

fills = pl.DataFrame(
    {
        "decision_time": [date(2025, 3, 3)] * 4,
        "execution_time": [date(2025, 3, 4)] * 4,
        "instrument": ["AAA", "BBB", "CCC", "DDD"],
        "side": ["buy", "sell", "buy", "sell"],
        "quantity": [1000.0, -400.0, 5000.0, -250.0],
        "price": [50.0, 20.0, 10.0, 80.0],
        "reference_price": [50.0, 20.0, 10.0, 80.0],
        "adv": [100_000.0, 50_000.0, 2_000_000.0, 10_000.0],
        "volatility": [0.02, 0.03, 0.01, 0.04],
    }
)

model = lc.costs.CompositeCostModel(
    (
        lc.costs.CommissionModel(fixed_per_trade=1.0, per_unit=0.005, notional_bps=1.0, minimum=2.0),
        lc.costs.SpreadModel(quoted_spread_bps=4.0),
        lc.costs.SquareRootImpactModel(coefficient=0.8, max_participation=0.02, impact_cap=0.005),
    )
)
estimate = model.estimate(fills)
per_trade = pl.DataFrame(estimate.to_result().table("per_trade_costs"))
print(per_trade.select("row", "commission", "spread", "square_root_impact", "total_cost"))
print(estimate.total_cost)
print([(f.code, f.state.value) for f in estimate.findings])
shape: (4, 5)
┌─────┬────────────┬────────┬────────────────────┬────────────┐
│ row ┆ commission ┆ spread ┆ square_root_impact ┆ total_cost │
│ --- ┆ ---        ┆ ---    ┆ ---                ┆ ---        │
│ i64 ┆ f64        ┆ f64    ┆ f64                ┆ f64        │
╞═════╪════════════╪════════╪════════════════════╪════════════╡
│ 0   ┆ 11.0       ┆ 10.0   ┆ 80.0               ┆ 101.0      │
│ 1   ┆ 3.8        ┆ 1.6    ┆ 17.173002          ┆ 22.573002  │
│ 2   ┆ 31.0       ┆ 10.0   ┆ 20.0               ┆ 61.0       │
│ 3   ┆ 4.25       ┆ 4.0    ┆ 100.0              ┆ 108.25     │
└─────┴────────────┴────────┴────────────────────┴────────────┘
292.8230020671984
[('COST_PARTICIPATION_LIMIT_EXCEEDED', 'FAIL'), ('COST_IMPACT_CAP_APPLIED', 'WARN')]

Each model returns a CostEstimate with one named component per trade, in currency. Check the first row by hand: commission is 1.0 + 0.005 × 1000 + 1 bp × 50,000 = 11.0, the spread is half of 4 bps of 50,000 = 10.0, and the square-root impact is 50,000 × 0.8 × 0.02 × sqrt(1000 / 100,000) = 80.0. The composite keeps the components separate so you can see which assumption dominates.

The findings are part of the answer. The fourth trade sells 250 shares of a stock trading 10,000 a day, a 2.5% participation that exceeds the declared 2% limit (COST_PARTICIPATION_LIMIT_EXCEEDED), and its impact was truncated by the 0.5% cap (COST_IMPACT_CAP_APPLIED). The limit only raises a finding. It does not change the cost.

The trade table

Every function takes a table with one row per executed trade. The default column names are in TradeColumns; pass your own TradeColumns to rename them.

ColumnMeaning
decision_timeWhen the strategy decided to trade.
execution_timeWhen the trade was executed. Must not be earlier than decision_time, and must have the same dtype.
instrumentThe stable instrument identifier.
side"buy" or "sell", case-insensitive; string, categorical or enum dtype.
quantityThe traded amount, in the units of any volume column you supply (shares, contracts).
priceThe price the trade is costed at.
reference_priceThe benchmark price before costs, such as the arrival mid.

All seven are required, with no nulls. Quantity, price and reference price must be finite, and both prices must be positive.

columns = lc.costs.TradeColumns(quantity="qty", reference_price="arrival_mid")
print(columns.required())
('decision_time', 'execution_time', 'instrument', 'side', 'qty', 'price', 'arrival_mid')

Quantity conventions

quantity_convention says how quantity encodes direction, and every model, stress, break_even_cost, liquidity_diagnostics and capacity_curve take it.

ValueMeaning
"signed"Default. Buys are non-negative and sells are non-positive. A sell with a positive quantity raises a DataContractError.
"absolute"Quantity is non-negative for every row and side supplies the direction.

Every cost is computed from the absolute quantity, with notional |quantity| × price. The sign matters only to borrow cost, which treats a negative signed quantity as a short. Lacuna has no contract multiplier; for futures or options, fold the multiplier into quantity or price yourself.

Prices that already contain costs

If price is a realised fill that already includes slippage or spread, charging those costs again counts them twice. The spread, slippage and volatility-slippage models, and stress, refuse a trade table in which any price differs from reference_price:

tainted = fills.with_columns(price=pl.col("price") * 1.001)
lc.costs.SlippageModel(slippage_bps=1.0).estimate(tainted)
MethodContractError: slippage may already be present in observed execution prices; set allow_on_observed_execution=True only for an intentional incremental stress

If you want the extra cost on top of an observed fill, say so with allow_on_observed_execution=True. Commission, impact and borrow do not check this, because they are not embedded in a fill price. A trades column already named commission, spread, slippage or borrow also raises for the model of that name unless you pass allow_existing=True; stress has no override for its three component names.

Market fields and timing

None of the built-in models takes a separate market table. Join volume, volatility, bid and ask, or borrow fields onto the trades first, using an as-of join so they are what you could have known. Passing a non-None market argument raises.

The models that read market fields can also take an available_time column (market_available_time, volatility_available_time, borrow_available_time). The check is available_time <= execution_time: a field must be known by the moment of execution. That is the right test for costing a trade. It is not a decision-time guarantee. A volume figure published between the decision and the execution passes this check although the strategy could not have used it to decide, so use an as-of join against decision_time if the field feeds the decision itself. A null availability time counts as unavailable, and an availability column whose dtype differs from execution_time raises a DataContractError. A value that is unavailable raises for volatility slippage and impact, and counts as missing for borrow, liquidity and capacity.

Missing market data is handled differently by each function. The commission, spread, slippage, volatility-slippage and impact models raise a DataContractError on a null, NaN or infinite volatility, volume, bid or ask, and on a volume that is not positive. Only borrow (under missing="unknown"), liquidity_diagnostics, capacity_curve, and stress through its base_models turn missing evidence into UNKNOWN. The labels volume_horizon, volatility_horizon and estimator are recorded in the result’s assumptions and not checked: they are your statement of how the field was measured.

Cost models

Write Ni=∣qi∣ piN_i = \lvert q_i \rvert\, p_i for the notional of trade ii, with qiq_i the quantity and pip_i the price. All costs are non-negative amounts in the model’s currency, a label that is never converted (CostUnit.CURRENCY is the unit of every estimate).

ClassWhat it charges
CommissionModelFixed, per-unit and notional-proportional fees with a minimum.
SpreadModelHalf or full quoted spread, assumed or from bid and ask.
SlippageModelA fixed amount per unit plus a proportion of notional.
VolatilitySlippageModelNotional times a coefficient times a supplied volatility.
ParticipationImpactModelPower-law impact in participation (share of volume).
SquareRootImpactModelThe same, with the exponent fixed at one half.
BorrowCostModelAn annualised borrow rate over a holding period, for short trades.
CompositeCostModelThe sum of other models, with components kept separate.

Commission

ci=max⁡(F+u ∣qi∣+b104Ni,  m)if ∣qi∣>0,ci=0 otherwisec_i = \max\bigl(F + u\,\lvert q_i \rvert + \tfrac{b}{10^4} N_i,\; m\bigr) \quad \text{if } \lvert q_i \rvert > 0, \qquad c_i = 0 \text{ otherwise}

with FF = fixed_per_trade, uu = per_unit, bb = notional_bps and mm = minimum. A zero-quantity row pays nothing, not even the minimum.

Spread

ci=Ni⋅k⋅si,k=12 for half mode, k=1 for full modec_i = N_i \cdot k \cdot s_i, \qquad k = \tfrac12 \text{ for half mode},\ k = 1 \text{ for full mode}

With quoted_spread_bps set, sis_i is that value divided by 10410^4, a full quoted spread, so mode="half" (the default) charges half of it. Without it, si=(aski−bidi)/ris_i = (\text{ask}_i - \text{bid}_i) / r_i from the bid and ask columns, where rir_i is the reference_price. Observed quotes need a positive bid and an ask at or above it. Half a spread is the cost of crossing from the mid to one side. If reference_price is not the mid, the observed charge is only approximately that.

Slippage

ci=f ∣qi∣+β104Nic_i = f\,\lvert q_i \rvert + \tfrac{\beta}{10^4} N_i

with ff = fixed_per_unit and β\beta = slippage_bps. It is a magnitude: it is a cost on both buys and sells.

Volatility slippage

ci=Ni⋅κ⋅σic_i = N_i \cdot \kappa \cdot \sigma_i

with κ\kappa = coefficient and σi\sigma_i the value of the volatility column for the trade. It must be finite and non-negative. Lacuna does not compute volatility; the volatility_horizon label records what yours means (for example daily).

Participation and square-root impact

ci=Ni⋅min⁡ ⁣(κ σi (∣qi∣/Vi)γ,  cap)c_i = N_i \cdot \min\!\Bigl(\kappa\, \sigma_i \,\bigl(\lvert q_i \rvert / V_i\bigr)^{\gamma},\; \text{cap}\Bigr)

ViV_i is the volume column, in the same units as quantity, and must be positive. The exponent γ\gamma is exponent for ParticipationImpactModel, default 1 (linear), and fixed at 0.5 for SquareRootImpactModel. The participation model’s volatility is optional, and σi=1\sigma_i = 1 without it; the square-root model requires it. The impact_cap is a ceiling on the fractional impact. Leave it None for no cap. The default volume column is "volume" for participation impact and "adv" (average daily volume) for square-root impact, so name it explicitly.

max_participation never changes a cost. It adds a COST_PARTICIPATION_LIMIT_EXCEEDED finding, FAIL, if any trade’s ∣qi∣/Vi\lvert q_i \rvert / V_i exceeds it. The impact is modeled as temporary; there is no permanent-impact term. The square-root form is a scenario assumption, not a law of markets.

Borrow

ci=Ni⋅ri diDif qi<0,ci=0 otherwisec_i = N_i \cdot \frac{r_i\, d_i}{D} \quad \text{if } q_i < 0, \qquad c_i = 0 \text{ otherwise}

rir_i is the annualised rate as a decimal (0.03 for 3%), did_i the holding_days and DD the day_count (365 by default). The model is stateless: it holds no position history. It treats every row with a negative signed quantity as a short, so a sell that closes a long is charged borrow too. holding_days must be the short exposure interval that row opens: give holding_days=0 (or a zero rate) to a sell that closes or reduces a long. Without it the row is charged as a short sale.

missing governs only the rate. A short row whose rate is null, NaN, infinite, negative, or not available by execution_time is the case it handles. A short row whose holding_days is null, NaN, infinite or negative always raises a DataContractError, under every policy. Rows that are not short are not checked for either field.

MissingBorrowPolicyBehaviour
"unknown"Default. The cost of that row is None, and the estimate has a COST_BORROW_UNKNOWN finding, UNKNOWN.
"conservative"Uses conservative_rate, which is then required, and adds a COST_BORROW_CONSERVATIVE_ASSUMPTION warning.
"raise"Raises a DataContractError.
borrowing = fills.with_columns(
    borrow_rate=pl.Series([0.02, 0.05, 0.01, None]),
    holding_days=pl.Series([5.0, 5.0, 5.0, 5.0]),
)
unknown = lc.costs.BorrowCostModel().estimate(borrowing)
print(unknown.per_trade_costs, unknown.total_cost, unknown.known_total_cost)
safe = lc.costs.BorrowCostModel(missing="conservative", conservative_rate=0.10).estimate(borrowing)
print([round(value, 2) for value in safe.per_trade_costs], round(safe.total_cost, 2))
(0.0, 5.47945205479452, 0.0, None) None 5.47945205479452
[0.0, 5.48, 0.0, 27.4] 32.88

BBB, a sell, is charged because it is a negative quantity; the two buys are not. DDD has no borrow rate. Under the default policy its cost is unknown, so the total is None while known_total_cost sums what is known. Under the conservative policy it is priced at 10% and flagged.

CostEstimate and composing models

Every model’s estimate(trades) returns a CostEstimate:

MemberMeaning
componentsA mapping from component name to one cost per trade; None marks an unknown cost.
per_trade_costsThe sum of components for each trade, None if any component is unknown.
total_cost, known_total_costThe total, or None if any trade is unknown; and the sum over known trades.
unknown_rows, trade_countHow many trades have no all-in cost, and how many there are.
component_totalsThe total of each component, None if that component has unknown rows.
assumptions, findings, input_fingerprintThe parameters used, what the model noticed, and an identity for the trades and parameters.
to_result()The same as an AnalysisResult, with a per_trade_costs table.

A composite needs unique component names and one currency; combining currencies raises, because conversion is never implicit. Any object with name, version, required_fields() and estimate(trades, market=None) that returns a CostEstimate satisfies the CostModel protocol and can be used in a composite or as a stress base model.

Stress

stress evaluates the net result of a trade table under many linear cost scenarios at once. It needs a gross_pnl column: the profit of each trade before costs.

A small book of synthetic trades with gross profit, market fields and a borrow rate:

rng = np.random.default_rng(21)
days = (date(2025, 1, 6) + timedelta(days=k) for k in range(100))
sessions = [day for day in days if day.weekday() < 5][:61]
rows = []
for index in range(60):
    for name in ("AAA", "BBB", "CCC", "DDD"):
        if rng.random() < 0.5:
            continue
        quantity = float(rng.integers(100, 2000))
        sell = bool(rng.random() < 0.5)
        price = float(round(rng.uniform(20, 120), 2))
        rows.append(
            {
                "decision_time": sessions[index],
                "execution_time": sessions[index + 1],
                "instrument": name,
                "side": "sell" if sell else "buy",
                "quantity": -quantity if sell else quantity,
                "price": price,
                "reference_price": price,
                "gross_pnl": float(rng.normal(0.0008, 0.01) * quantity * price),
                "adv": float(rng.integers(40_000, 200_000)),
                "volatility": float(rng.uniform(0.01, 0.03)),
                "adv_available_time": sessions[index],
                "borrow_rate": None if name == "DDD" else 0.03,
                "holding_days": 5.0,
            }
        )
trades = pl.DataFrame(rows)
print(trades.height, round(trades["gross_pnl"].sum(), 1))
139 20775.8

By default stress builds the Cartesian grid of spread_bps, slippage_bps and commission_bps. The defaults are (0, 2, 5, 10, 20) for spread, (0, 2, 5, 10) for slippage and (0,) for commission, which is 20 scenarios. The spread value is a full quoted spread, and the surface charges half of it.

surface = lc.costs.stress(
    trades,
    spread_bps=[0, 4, 10],
    slippage_bps=[0, 5],
    capital=5_000_000,
    annualization=252,
)
table = pl.DataFrame(surface.table("stress_surface")).select(
    "spread_bps", "slippage_bps", "total_cost", "net_pnl", "net_return", "net_sharpe"
)
print(table.with_columns(pl.col("total_cost", "net_pnl").round(0), pl.col("net_return", "net_sharpe").round(4)))
print(surface.metrics["worst_net_pnl"], surface.metrics["complete_scenarios"])
shape: (6, 6)
┌────────────┬──────────────┬────────────┬─────────┬────────────┬────────────┐
│ spread_bps ┆ slippage_bps ┆ total_cost ┆ net_pnl ┆ net_return ┆ net_sharpe │
│ ---        ┆ ---          ┆ ---        ┆ ---     ┆ ---        ┆ ---        │
│ f64        ┆ f64          ┆ f64        ┆ f64     ┆ f64        ┆ f64        │
╞════════════╪══════════════╪════════════╪═════════╪════════════╪════════════╡
│ 0.0        ┆ 0.0          ┆ 0.0        ┆ 20776.0 ┆ 0.0042     ┆ 3.6865     │
│ 0.0        ┆ 5.0          ┆ 4943.0     ┆ 15832.0 ┆ 0.0032     ┆ 2.8266     │
│ 4.0        ┆ 0.0          ┆ 1977.0     ┆ 18798.0 ┆ 0.0038     ┆ 3.3442     │
│ 4.0        ┆ 5.0          ┆ 6921.0     ┆ 13855.0 ┆ 0.0028     ┆ 2.4788     │
│ 10.0       ┆ 0.0          ┆ 4943.0     ┆ 15832.0 ┆ 0.0032     ┆ 2.8266     │
│ 10.0       ┆ 5.0          ┆ 9887.0     ┆ 10889.0 ┆ 0.0022     ┆ 1.9537     │
└────────────┴──────────────┴────────────┴─────────┴────────────┴────────────┘
10888.83360928415 6

Each row is a scenario. net_pnl is gross profit minus total cost. A 10 bps quoted spread costs the same as 5 bps of slippage, because the surface charges half the spread: rows two and five are identical. The keys net_return, net_sharpe and turnover are present in every row and are None unless you supply what they need: net_return and turnover need capital, and net_sharpe needs annualization, the number of periods per year. Turnover is total traded notional, the sum of |quantity| × price, divided by capital over the whole sample. It is not annualised. The surface shows how steeply performance falls as costs rise, and which cost type the strategy is most exposed to.

Correlated scenarios

A grid combines every spread with every slippage, including combinations that never occur: a calm spread with a stressed slippage. Pass scenarios to evaluate named, hand-picked combinations instead.

named = lc.costs.stress(
    trades,
    scenarios=[
        lc.costs.CostScenario("calm", spread_bps=2.0, slippage_bps=1.0),
        lc.costs.CostScenario("stressed", spread_bps=12.0, slippage_bps=8.0, commission_bps=1.0),
    ],
    capital=5_000_000,
)
print([(row["scenario"], round(row["net_pnl"], 0)) for row in named.table("stress_surface")])
[('calm', 18798.0), ('stressed', 5945.0)]

scenarios cannot be combined with the grid arguments, and scenario names must be unique.

Unknown costs stay unknown

base_models adds other cost models to every scenario: a borrow cost, impact, or any CostModel that is not named commission, spread or slippage, since the grid already supplies those. If any base model has an unknown row, no scenario has a complete answer.

incomplete = lc.costs.stress(
    trades,
    spread_bps=[0, 4],
    slippage_bps=[0],
    base_models=[lc.costs.BorrowCostModel()],
    capital=5_000_000,
)
row = incomplete.table("stress_surface")[1]
print(row["status"], row["net_pnl"], round(row["known_total_cost"], 1))
print([(f.code, f.state.value) for f in incomplete.findings])
unknown_cost None 2854.7
[('COST_BORROW_UNKNOWN', 'UNKNOWN'), ('COST_STRESS_INCOMPLETE', 'UNKNOWN')]

The scenario’s net_pnl is None and its status is "unknown_cost". The result carries COST_STRESS_INCOMPLETE. Without a policy for the missing rate, there is no net performance to report, and Lacuna does not substitute zero. Resolve it with BorrowCostModel(missing="conservative", conservative_rate=...) or supply the data.

How net Sharpe is computed

Total cost for a scenario is ∑iNi (M+S/2+L)/104\sum_i N_i\,(M + S/2 + L)/10^4 plus any base-model costs, with MM, SS and LL the commission, spread and slippage in bps. For net_sharpe, trades are grouped by the period column, "execution_time" by default, and each group’s net profit is xt=Gt−Bt−R Ntx_t = G_t - B_t - R\,N_t, with GtG_t the gross profit, BtB_t the base-model cost, NtN_t the notional and RR the linear rate. Then:

net Sharpe=xˉsxA\text{net Sharpe} = \frac{\bar{x}}{s_x}\sqrt{A}

where sxs_x is the sample standard deviation (ddof 1) and AA is annualization. It is None with fewer than two periods or zero variance.

Read this as a Sharpe of summed trade profits, not of a portfolio return series. The inputs are the per-trade gross_pnl values summed over each distinct period value, not a mark-to-market series. Nothing is subtracted for a risk-free rate, and capital does not enter the stress Sharpe (it does in break_even_cost, but the ratio is scale-free either way). Periods are the groups present in the table: a session with no trades is absent, not a zero-profit observation. Because of that, stress, break_even_cost and capacity_curve add a result warning whenever you pass annualization, saying that Sharpe and CAGR use only periods containing at least one trade. With an annualization that counts every calendar period (252 for daily), a sparse trade ledger can overstate the statistic. If period holds intraday datetimes, every distinct timestamp is its own period. The factor A\sqrt{A} assumes the periods are independent and of equal length, so choose period and annualization consistently, for example daily dates with annualization=252.

Break-even cost

break_even_cost finds the all-in cost, in basis points of traded notional, at which a metric crosses a threshold. It answers “how expensive can trading get before the strategy stops working?”, which is the margin of safety against your cost estimate.

breakeven = lc.costs.break_even_cost(trades)
print(breakeven.metrics["status"], round(breakeven.metrics["solution_bps"], 2))
converged 21.01

The default metric is net_pnl and the default threshold is 0, so this is the cost at which net profit reaches zero. It is also the gross edge per unit of notional traded.

To compare it with a modelled cost, remember what it is: one flat all-in rate in bps applied to total traded notional. Convert a cost estimate to the same basis before comparing, as total_cost / total_notional × 10_000, where total_notional is surface.metrics["total_notional"] from stress. If that rate exceeds the break-even, the strategy loses money after costs. The default upper_bps is 1000, so a gross edge above 1000 bps of notional returns "no_crossing"; raise upper_bps if you expect one. The other metrics need capital, and the path-dependent ones need annualization too.

BreakEvenMetricEvaluated as
"net_pnl"Total gross profit minus total cost.
"net_return"Net profit divided by capital.
"net_sharpe"The annualised Sharpe of per-period net profit divided by capital.
"cagr"The compounded growth of the per-period returns (the product of one plus each period’s net profit over capital), raised to the power annualisation divided by the number of periods, minus one. It raises if any period loses 100% or more.

The solver needs the metric to fall as cost rises. It first evaluates a 33-point grid over [lower_bps, upper_bps] and checks that the values never increase. If they do, it stops with status "non_monotonic" and an UNKNOWN finding. If not, it brackets the crossing and bisects until the bracket is narrower than tolerance_bps, or max_iterations is reached.

statusMeaning
"converged"solution_bps is the crossing, within tolerance_bps.
"crossed_at_lower_bound"The metric is already at or below the threshold at lower_bps, which is returned.
"no_crossing"The metric is still above the threshold at upper_bps. There is no solution in the bracket, and solution_bps is None.
"non_monotonic"The metric is not non-increasing over the bracket.
"iteration_limit"max_iterations was reached first; the answer is still reported with a warning.

Net Sharpe is the metric most likely to be non-monotonic. Far beyond break-even the net profit series is dominated by the cost term, so Sharpe levels off and can drift back up toward a limit. A very wide bracket can then report "non_monotonic" although the crossing you want is well inside it. Narrow the bracket to the region you care about.

wide = lc.costs.break_even_cost(
    trades, metric="net_sharpe", threshold=1.0, capital=5_000_000, annualization=252, upper_bps=5000.0
)
narrow = lc.costs.break_even_cost(
    trades, metric="net_sharpe", threshold=1.0, capital=5_000_000, annualization=252, upper_bps=100.0
)
print(wide.metrics["status"], narrow.metrics["status"], round(narrow.metrics["solution_bps"], 2))
non_monotonic converged 15.4

Two cases raise instead of returning a status. net_sharpe raises a DataContractError if the Sharpe is undefined at any point the solver evaluates (fewer than two periods, or zero variance). cagr raises if any period return reaches -100% or worse at any evaluated cost, which a wide bracket can cause even when the crossing you want is far smaller. Narrowing the bracket avoids both.

The solution is valid only inside the bracket. Nothing is extrapolated. The solver trace, with every point it evaluated, is in the solver_trace table.

Liquidity diagnostics

liquidity_diagnostics measures participation: each trade’s share of the volume it traded against, ∣qi∣/Vi\lvert q_i \rvert / V_i.

liquidity = lc.costs.liquidity_diagnostics(
    trades,
    volume="adv",
    available_time="adv_available_time",
    classification_mode="point_in_time",
    max_participation=0.01,
)
print(liquidity.metrics["coverage"], liquidity.metrics["breach_rows"], round(liquidity.metrics["p95_participation"], 4))
print([(f.code, f.state.value) for f in liquidity.findings])
1.0 63 0.0289
[('COST_LIQUIDITY_CONSTRAINT_BREACH', 'FAIL')]

Each trade is "pass", "breach" (participation above max_participation) or "unknown" (volume missing, not positive, or not available by execution_time). Unknown rows are not assumed liquid; they are counted in coverage and give COST_LIQUIDITY_UNKNOWN. The per-trade table is liquidity.table("liquidity").

classification_mode is a required, explicit choice.

LiquidityModeMeaning
"point_in_time"The volume figure was known by execution. Requires available_time; rows whose value became available after execution_time count as unknown.
"retrospective"Volume may include data from after the trade, such as the execution day’s own volume. Allowed, but flagged with COST_LIQUIDITY_RETROSPECTIVE, WARN. If you also pass available_time, rows with a later or null value are still marked unknown, so omit it in this mode.

Using the same day’s volume to judge a trade decided before that day is look-ahead. Prefer a prior-period average.

Capacity

Capacity is not one number. It depends on the cost you will tolerate, so capacity_curve returns net performance across a range of capital instead. It takes the trades as run at base_capital and rescales them to each capital in capital, under each CapacityScenario.

curve = lc.costs.capacity_curve(
    trades,
    capital=[2_000_000, 5_000_000, 10_000_000, 20_000_000],
    base_capital=5_000_000,
    scenarios=[
        lc.costs.CapacityScenario("low", impact_coefficient=0.3, spread_bps=2.0),
        lc.costs.CapacityScenario("high", impact_coefficient=1.0, spread_bps=6.0, slippage_bps=2.0),
    ],
    volume="adv",
    volatility="volatility",
    available_time="adv_available_time",
    classification_mode="point_in_time",
    max_participation=0.02,
    annualization=252,
)
points = pl.DataFrame(curve.table("capacity_curve")).select(
    "scenario", "capital", "net_pnl", "net_return", "net_sharpe", "participation_breach_rows", "status"
)
print(points.with_columns(pl.col("net_pnl").round(0), pl.col("net_return", "net_sharpe").round(4)))
shape: (8, 7)
┌──────────┬─────────┬───────────┬────────────┬────────────┬───────────────────┬───────────────────┐
│ scenario ┆ capital ┆ net_pnl   ┆ net_return ┆ net_sharpe ┆ participation_bre ┆ status            │
│ ---      ┆ ---     ┆ ---       ┆ ---        ┆ ---        ┆ ach_rows          ┆ ---               │
│ str      ┆ f64     ┆ f64       ┆ f64        ┆ f64        ┆ ---               ┆ str               │
│          ┆         ┆           ┆            ┆            ┆ i64               ┆                   │
╞══════════╪═════════╪═══════════╪════════════╪════════════╪═══════════════════╪═══════════════════╡
│ low      ┆ 2e6     ┆ 6277.0    ┆ 0.0031     ┆ 2.7877     ┆ 0                 ┆ ok                │
│ low      ┆ 5e6     ┆ 13312.0   ┆ 0.0027     ┆ 2.3633     ┆ 15                ┆ constraint_breach │
│ low      ┆ 1e7     ┆ 21260.0   ┆ 0.0021     ┆ 1.8847     ┆ 63                ┆ constraint_breach │
│ low      ┆ 2e7     ┆ 27347.0   ┆ 0.0014     ┆ 1.2088     ┆ 106               ┆ constraint_breach │
│ high     ┆ 2e6     ┆ 873.0     ┆ 0.0004     ┆ 0.3862     ┆ 0                 ┆ ok                │
│ high     ┆ 5e6     ┆ -5752.0   ┆ -0.0012    ┆ -1.0066    ┆ 15                ┆ constraint_breach │
│ high     ┆ 1e7     ┆ -29384.0  ┆ -0.0029    ┆ -2.5251    ┆ 63                ┆ constraint_breach │
│ high     ┆ 2e7     ┆ -109342.0 ┆ -0.0055    ┆ -4.5414    ┆ 106               ┆ constraint_breach │
└──────────┴─────────┴───────────┴────────────┴────────────┴───────────────────┴───────────────────┘

Read each scenario’s rows from the smallest capital upward. In the low scenario net profit keeps rising with capital, but net return and Sharpe fall because impact grows faster than profit. In the high scenario net profit is already negative at 5,000,000. participation_breach_rows counts the trades whose scaled participation exceeds max_participation; in both scenarios breaches begin by the base capital. A point with a breach has status "constraint_breach": its net numbers are still computed, using the uncapped impact formula, but you could not actually trade that way. Pick the largest capital that is "ok" and still has a net return you would accept.

Capacity is "unknown_liquidity" for every point if any trade has unusable volume or volatility, unless the trade has zero quantity. Missing liquidity is not assumed away.

How capacity is computed

capacity_curve charges exactly three things: square-root impact (with no impact_cap), half the quoted spread, and slippage. It adds no commission, no borrow and no base_models, and it skips the price != reference_price check that stress applies. stress charges impact only if you pass an impact model as a base model. If commission or borrow matter at your size, they are not in the curve.

For capital CC and base capital C0C_0 the scale is s=C/C0s = C / C_0. The trades are assumed to scale proportionally: the same instruments, the same relative sizes, and gross profit that grows linearly with ss. Under that assumption, with scenario spread SS, slippage LL and impact coefficient κ\kappa:

net(s)=s G  −  s ∑iNi(S2⋅104+L104)  −  κ s3/2∑iNi σi∣qi∣Vi\text{net}(s) = s\,G \;-\; s\,\sum_i N_i \Bigl(\frac{S}{2 \cdot 10^4} + \frac{L}{10^4}\Bigr) \;-\; \kappa\, s^{3/2} \sum_i N_i\, \sigma_i \sqrt{\frac{\lvert q_i \rvert}{V_i}}

Notional and participation both scale with ss, so square-root impact, which is notional times the square root of participation, scales with s3/2s^{3/2}. Gross profit, spread and slippage scale with ss. Gross turnover is constant. The assumption that gross profit does not decay as size grows is strong: it is a statement about your strategy that Lacuna takes as given, and it makes the curve optimistic for strategies whose alpha is capacity-limited.

The same classification_mode choice applies as for liquidity: "point_in_time" requires available_time, and "retrospective" adds COST_CAPACITY_RETROSPECTIVE. As there, supplying available_time in retrospective mode still marks later or null rows unknown, so omit it. Capacity results always carry a warning that square-root impact is a declared scenario model.

Reading the results

QuestionWhere to look
Is the edge larger than plausible costs?break_even_cost, compared with your all-in estimate.
Which cost assumption matters most?stress, comparing rows that differ in one parameter.
Is any cost unmeasured?UNKNOWN findings, unknown_rows, and status values other than "ok".
Could the trades be executed at all?liquidity_diagnostics breaches and unknown rows.
How does net return decay with size?capacity_curve rows per scenario.

Parameters

stress

ParameterMeaning
tradesThe trade table. Polars, pandas, Arrow or anything to_polars accepts.
gross_pnlThe column of per-trade profit before costs.
spread_bpsFull quoted spreads to try, in bps. The surface charges half. Values must be non-negative and unique. Default (0, 2, 5, 10, 20).
slippage_bpsSlippage values to try, in bps of notional. Default (0, 2, 5, 10).
commission_bpsCommission values to try, in bps of notional. Default (0,).
scenariosExplicit CostScenario values. Replaces the grid; cannot be combined with it.
base_modelsOther cost models added to every scenario. They may not produce commission, spread or slippage components.
capitalOptional positive capital. Enables net_return and turnover.
periodThe column that groups trades into periods for the Sharpe. Default "execution_time".
annualizationPeriods per year. Enables net_sharpe.
currencyThe currency label. Base models must use the same one.
columnsA TradeColumns if your column names differ.
quantity_convention"signed" or "absolute".
allow_on_observed_executionPermit costing a table in which price differs from reference_price.

break_even_cost

ParameterMeaning
tradesThe trade table.
gross_pnlThe column of per-trade profit before costs.
metric"net_pnl", "net_return", "net_sharpe" or "cagr".
thresholdThe value of the metric at which to solve. Default 0.
lower_bps, upper_bpsThe search bracket in all-in bps of notional.
tolerance_bpsStop when the bracket is narrower than this. Must be smaller than the bracket.
max_iterationsBisection step limit.
capitalRequired for every metric except "net_pnl".
periodThe grouping column for "net_sharpe" and "cagr".
annualizationPeriods per year, required for "net_sharpe" and "cagr".
columnsA TradeColumns if your column names differ.
quantity_convention"signed" or "absolute".

liquidity_diagnostics

ParameterMeaning
tradesThe trade table with a volume column.
volumeThe volume column, in the units of quantity. Default "adv".
available_timeWhen each volume figure became available. Required for "point_in_time".
classification_mode"point_in_time" or "retrospective". Required, with no default.
max_participationThe participation limit as a fraction of volume. Default 0.1, unlike the impact models, where the default is None (no limit). Raises findings; changes no cost.
volume_horizonA label for the volume’s window, such as "daily". Recorded, not checked.
estimation_lagA label for how stale the estimate is. Recorded, not checked.
columnsA TradeColumns if your column names differ.
quantity_convention"signed" or "absolute".

capacity_curve

ParameterMeaning
tradesThe trades as run at base_capital, with gross profit, volume and volatility.
capitalThe capital points to evaluate: positive, strictly increasing.
base_capitalThe capital the trades were run at.
scenariosCapacityScenario values; names must be unique.
gross_pnlThe per-trade gross profit column.
volumeThe volume column. Default "adv".
volatilityThe volatility column. Default "volatility".
available_timeWhen the market fields became available. Required for "point_in_time".
classification_mode"point_in_time" or "retrospective". Required.
max_participationParticipation limit used to flag breaches at each capital. Default 0.1, unlike the impact models, where the default is None.
volume_horizon, volatility_horizon, estimation_lagLabels recorded in the result, not checked.
periodThe grouping column for the Sharpe.
annualizationPeriods per year. Enables net_sharpe.
columnsA TradeColumns if your column names differ.
quantity_convention"signed" or "absolute".

Scenarios and columns

ParameterMeaning
nameA unique label for the scenario.
spread_bpsThe full quoted spread; half is charged.
slippage_bpsSlippage in bps of notional.
commission_bpsCommission in bps of notional.
ParameterMeaning
nameA unique label for the scenario.
impact_coefficientThe square-root impact coefficient, as for SquareRootImpactModel.
spread_bpsThe full quoted spread; half is charged.
slippage_bpsSlippage in bps of notional.
ParameterMeaning
decision_timeColumn holding the decision time.
execution_timeColumn holding the execution time.
instrumentColumn holding the instrument identifier.
sideColumn holding "buy" or "sell".
quantityColumn holding the traded amount.
priceColumn holding the price the trade is costed at.
reference_priceColumn holding the benchmark price before costs.

Cost models

All models also take currency, columns (a TradeColumns) and quantity_convention.

ParameterMeaning
fixed_per_tradeA fixed fee per trade.
per_unitA fee per unit of quantity, such as per share.
notional_bpsA fee in bps of notional.
minimumThe smallest fee per non-empty trade.
allow_existingPermit a trades column already named commission.
ParameterMeaning
quoted_spread_bpsAn assumed full quoted spread. None reads observed bid and ask instead.
mode"half" (default) or "full": how much of the spread each trade pays.
bid, askThe quote columns used when quoted_spread_bps is None.
allow_on_observed_executionPermit costing when price differs from reference_price.
allow_existingPermit a trades column already named spread.
ParameterMeaning
fixed_per_unitA fixed amount per unit of quantity.
slippage_bpsSlippage in bps of notional.
allow_on_observed_executionPermit costing when price differs from reference_price.
allow_existingPermit a trades column already named slippage.
ParameterMeaning
coefficientThe multiplier on volatility. Required.
volatilityThe volatility column.
volatility_available_timeWhen the volatility figure became available; later than execution raises.
volatility_horizon, estimatorLabels describing the volatility; recorded, not checked.
allow_on_observed_executionPermit costing when price differs from reference_price.
ParameterMeaning
coefficientThe impact coefficient. Required.
exponentThe participation exponent. Default 1, which is linear.
volumeThe volume column, in the units of quantity. Default "volume".
volatilityOptional volatility column. Without it, volatility is taken as 1.
market_available_timeWhen the market fields became available; later than execution raises.
volume_horizon, volatility_horizonLabels recorded in the assumptions, not checked.
max_participationA limit that raises a finding when exceeded.
impact_capA ceiling on the fractional impact.
ParameterMeaning
coefficientThe impact coefficient. Required.
volumeThe volume column. Default "adv".
volatilityThe volatility column. Required for this model.
market_available_timeWhen the market fields became available; later than execution raises.
volume_horizon, volatility_horizonLabels recorded in the assumptions, not checked.
max_participationA limit that raises a finding when exceeded.
impact_capA ceiling on the fractional impact.
ParameterMeaning
borrow_rateThe annualised borrow rate column, as a decimal.
holding_daysThe column of days each short is held.
borrow_available_timeWhen the rate became available; a rate available after execution counts as missing.
day_countDays in the year used to scale the rate. Default 365.
missing"unknown", "conservative" or "raise".
conservative_rateThe rate used under "conservative"; invalid otherwise.
allow_existingPermit a trades column already named borrow.
ParameterMeaning
modelsThe models to add, with unique component names and one currency.
nameThe composite’s name. Default "composite".
versionThe composite’s version. Default 1.

The full signatures are in the API reference.