Sizing API¶
Position sizing strategies.
Fixed Sizing¶
fixed_quantity¶
fixed_notional¶
fixed_notional ¶
Size by notional value at a given price.
Percentage Sizing¶
percent_of_equity¶
percent_of_equity ¶
Calculate position size as a percentage of equity.
A simple sizing method that allocates a fixed percentage of account equity to each position.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
equity
|
Money
|
Total account equity |
required |
percent
|
Decimal
|
Percentage to allocate (e.g., 0.02 for 2%) |
required |
price
|
Price
|
Current asset price |
required |
Returns:
| Type | Description |
|---|---|
Quantity
|
Quantity to buy/sell |
Raises:
| Type | Description |
|---|---|
ZeroDivisionError
|
If price is zero |
Example
from decimal import Decimal
Allocate 2% of $10,000 equity at $100/share¶
qty = percent_of_equity(Decimal("10000"), Decimal("0.02"), Decimal("100")) float(qty) 2.0
Allocate 5% of $50,000 equity at $250/share¶
qty = percent_of_equity(Decimal("50000"), Decimal("0.05"), Decimal("250")) float(qty) 10.0
Risk-Based Sizing¶
risk_per_trade¶
risk_per_trade ¶
Size so that loss to stop_distance equals a fraction of equity.
Volatility Sizing¶
atr_position_size¶
atr_position_size ¶
Size inversely proportional to ATR (higher volatility -> smaller size).
Kelly Criterion¶
kelly_fraction¶
kelly_fraction ¶
Calculate the Kelly fraction of bankroll to risk per trade.
The Kelly criterion determines the optimal bet size to maximize long-term growth rate. The result can be negative (don't bet), or > 1 (use leverage).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
win_rate
|
Decimal
|
Probability of winning (0 to 1) |
required |
win_loss_ratio
|
Decimal
|
Average win / average loss ratio |
required |
Returns:
| Type | Description |
|---|---|
Decimal
|
Fraction of bankroll to risk (can be negative or > 1) |
Raises:
| Type | Description |
|---|---|
ValueError
|
If win_loss_ratio is not positive |
Example
from decimal import Decimal
60% win rate, 1.5:1 reward/risk¶
kelly = kelly_fraction(Decimal("0.6"), Decimal("1.5")) float(kelly) # ~33% of bankroll 0.33...
50% win rate, 2:1 reward/risk¶
kelly = kelly_fraction(Decimal("0.5"), Decimal("2")) float(kelly) # 25% of bankroll 0.25
Use half-Kelly for reduced volatility¶
half_kelly = kelly / 2
Constraints¶
apply_position_limits¶
apply_position_limits ¶
apply_position_limits(
desired_qty: Quantity,
max_position: Quantity | None = None,
max_notional: Decimal | None = None,
price: Decimal | None = None,
) -> Quantity