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.
| Column | Meaning |
|---|---|
decision_time | When the strategy decided to trade. |
execution_time | When the trade was executed. Must not be earlier than decision_time, and must have the same dtype. |
instrument | The stable instrument identifier. |
side | "buy" or "sell", case-insensitive; string, categorical or enum dtype. |
quantity | The traded amount, in the units of any volume column you supply (shares, contracts). |
price | The price the trade is costed at. |
reference_price | The 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.
| Value | Meaning |
|---|---|
"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 for the notional of trade , with the quantity and 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).
| Class | What it charges |
|---|---|
CommissionModel | Fixed, per-unit and notional-proportional fees with a minimum. |
SpreadModel | Half or full quoted spread, assumed or from bid and ask. |
SlippageModel | A fixed amount per unit plus a proportion of notional. |
VolatilitySlippageModel | Notional times a coefficient times a supplied volatility. |
ParticipationImpactModel | Power-law impact in participation (share of volume). |
SquareRootImpactModel | The same, with the exponent fixed at one half. |
BorrowCostModel | An annualised borrow rate over a holding period, for short trades. |
CompositeCostModel | The sum of other models, with components kept separate. |
Commission
with = fixed_per_trade, = per_unit, = notional_bps and = minimum. A zero-quantity row pays nothing, not even the minimum.
Spread
With quoted_spread_bps set, is that value divided by , a full quoted spread, so mode="half" (the default) charges half of it. Without it, from the bid and ask columns, where 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
with = fixed_per_unit and = slippage_bps. It is a magnitude: it is a cost on both buys and sells.
Volatility slippage
with = coefficient and 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
is the volume column, in the same units as quantity, and must be positive. The exponent is exponent for ParticipationImpactModel, default 1 (linear), and fixed at 0.5 for SquareRootImpactModel. The participation model’s volatility is optional, and 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 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
is the annualised rate as a decimal (0.03 for 3%), the holding_days and 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.
MissingBorrowPolicy | Behaviour |
|---|---|
"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:
| Member | Meaning |
|---|---|
components | A mapping from component name to one cost per trade; None marks an unknown cost. |
per_trade_costs | The sum of components for each trade, None if any component is unknown. |
total_cost, known_total_cost | The total, or None if any trade is unknown; and the sum over known trades. |
unknown_rows, trade_count | How many trades have no all-in cost, and how many there are. |
component_totals | The total of each component, None if that component has unknown rows. |
assumptions, findings, input_fingerprint | The 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 plus any base-model costs, with , and 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 , with the gross profit, the base-model cost, the notional and the linear rate. Then:
where is the sample standard deviation (ddof 1) and 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 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.
BreakEvenMetric | Evaluated 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.
status | Meaning |
|---|---|
"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, .
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.
LiquidityMode | Meaning |
|---|---|
"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 and base capital the scale is . The trades are assumed to scale proportionally: the same instruments, the same relative sizes, and gross profit that grows linearly with . Under that assumption, with scenario spread , slippage and impact coefficient :
Notional and participation both scale with , so square-root impact, which is notional times the square root of participation, scales with . Gross profit, spread and slippage scale with . 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
| Question | Where 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
| Parameter | Meaning |
|---|---|
trades | The trade table. Polars, pandas, Arrow or anything to_polars accepts. |
gross_pnl | The column of per-trade profit before costs. |
spread_bps | Full quoted spreads to try, in bps. The surface charges half. Values must be non-negative and unique. Default (0, 2, 5, 10, 20). |
slippage_bps | Slippage values to try, in bps of notional. Default (0, 2, 5, 10). |
commission_bps | Commission values to try, in bps of notional. Default (0,). |
scenarios | Explicit CostScenario values. Replaces the grid; cannot be combined with it. |
base_models | Other cost models added to every scenario. They may not produce commission, spread or slippage components. |
capital | Optional positive capital. Enables net_return and turnover. |
period | The column that groups trades into periods for the Sharpe. Default "execution_time". |
annualization | Periods per year. Enables net_sharpe. |
currency | The currency label. Base models must use the same one. |
columns | A TradeColumns if your column names differ. |
quantity_convention | "signed" or "absolute". |
allow_on_observed_execution | Permit costing a table in which price differs from reference_price. |
break_even_cost
| Parameter | Meaning |
|---|---|
trades | The trade table. |
gross_pnl | The column of per-trade profit before costs. |
metric | "net_pnl", "net_return", "net_sharpe" or "cagr". |
threshold | The value of the metric at which to solve. Default 0. |
lower_bps, upper_bps | The search bracket in all-in bps of notional. |
tolerance_bps | Stop when the bracket is narrower than this. Must be smaller than the bracket. |
max_iterations | Bisection step limit. |
capital | Required for every metric except "net_pnl". |
period | The grouping column for "net_sharpe" and "cagr". |
annualization | Periods per year, required for "net_sharpe" and "cagr". |
columns | A TradeColumns if your column names differ. |
quantity_convention | "signed" or "absolute". |
liquidity_diagnostics
| Parameter | Meaning |
|---|---|
trades | The trade table with a volume column. |
volume | The volume column, in the units of quantity. Default "adv". |
available_time | When each volume figure became available. Required for "point_in_time". |
classification_mode | "point_in_time" or "retrospective". Required, with no default. |
max_participation | The 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_horizon | A label for the volume’s window, such as "daily". Recorded, not checked. |
estimation_lag | A label for how stale the estimate is. Recorded, not checked. |
columns | A TradeColumns if your column names differ. |
quantity_convention | "signed" or "absolute". |
capacity_curve
| Parameter | Meaning |
|---|---|
trades | The trades as run at base_capital, with gross profit, volume and volatility. |
capital | The capital points to evaluate: positive, strictly increasing. |
base_capital | The capital the trades were run at. |
scenarios | CapacityScenario values; names must be unique. |
gross_pnl | The per-trade gross profit column. |
volume | The volume column. Default "adv". |
volatility | The volatility column. Default "volatility". |
available_time | When the market fields became available. Required for "point_in_time". |
classification_mode | "point_in_time" or "retrospective". Required. |
max_participation | Participation 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_lag | Labels recorded in the result, not checked. |
period | The grouping column for the Sharpe. |
annualization | Periods per year. Enables net_sharpe. |
columns | A TradeColumns if your column names differ. |
quantity_convention | "signed" or "absolute". |
Scenarios and columns
| Parameter | Meaning |
|---|---|
name | A unique label for the scenario. |
spread_bps | The full quoted spread; half is charged. |
slippage_bps | Slippage in bps of notional. |
commission_bps | Commission in bps of notional. |
| Parameter | Meaning |
|---|---|
name | A unique label for the scenario. |
impact_coefficient | The square-root impact coefficient, as for SquareRootImpactModel. |
spread_bps | The full quoted spread; half is charged. |
slippage_bps | Slippage in bps of notional. |
| Parameter | Meaning |
|---|---|
decision_time | Column holding the decision time. |
execution_time | Column holding the execution time. |
instrument | Column holding the instrument identifier. |
side | Column holding "buy" or "sell". |
quantity | Column holding the traded amount. |
price | Column holding the price the trade is costed at. |
reference_price | Column holding the benchmark price before costs. |
Cost models
All models also take currency, columns (a TradeColumns) and quantity_convention.
| Parameter | Meaning |
|---|---|
fixed_per_trade | A fixed fee per trade. |
per_unit | A fee per unit of quantity, such as per share. |
notional_bps | A fee in bps of notional. |
minimum | The smallest fee per non-empty trade. |
allow_existing | Permit a trades column already named commission. |
| Parameter | Meaning |
|---|---|
quoted_spread_bps | An 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, ask | The quote columns used when quoted_spread_bps is None. |
allow_on_observed_execution | Permit costing when price differs from reference_price. |
allow_existing | Permit a trades column already named spread. |
| Parameter | Meaning |
|---|---|
fixed_per_unit | A fixed amount per unit of quantity. |
slippage_bps | Slippage in bps of notional. |
allow_on_observed_execution | Permit costing when price differs from reference_price. |
allow_existing | Permit a trades column already named slippage. |
| Parameter | Meaning |
|---|---|
coefficient | The multiplier on volatility. Required. |
volatility | The volatility column. |
volatility_available_time | When the volatility figure became available; later than execution raises. |
volatility_horizon, estimator | Labels describing the volatility; recorded, not checked. |
allow_on_observed_execution | Permit costing when price differs from reference_price. |
| Parameter | Meaning |
|---|---|
coefficient | The impact coefficient. Required. |
exponent | The participation exponent. Default 1, which is linear. |
volume | The volume column, in the units of quantity. Default "volume". |
volatility | Optional volatility column. Without it, volatility is taken as 1. |
market_available_time | When the market fields became available; later than execution raises. |
volume_horizon, volatility_horizon | Labels recorded in the assumptions, not checked. |
max_participation | A limit that raises a finding when exceeded. |
impact_cap | A ceiling on the fractional impact. |
| Parameter | Meaning |
|---|---|
coefficient | The impact coefficient. Required. |
volume | The volume column. Default "adv". |
volatility | The volatility column. Required for this model. |
market_available_time | When the market fields became available; later than execution raises. |
volume_horizon, volatility_horizon | Labels recorded in the assumptions, not checked. |
max_participation | A limit that raises a finding when exceeded. |
impact_cap | A ceiling on the fractional impact. |
| Parameter | Meaning |
|---|---|
borrow_rate | The annualised borrow rate column, as a decimal. |
holding_days | The column of days each short is held. |
borrow_available_time | When the rate became available; a rate available after execution counts as missing. |
day_count | Days in the year used to scale the rate. Default 365. |
missing | "unknown", "conservative" or "raise". |
conservative_rate | The rate used under "conservative"; invalid otherwise. |
allow_existing | Permit a trades column already named borrow. |
| Parameter | Meaning |
|---|---|
models | The models to add, with unique component names and one currency. |
name | The composite’s name. Default "composite". |
version | The composite’s version. Default 1. |
The full signatures are in the API reference.