position-sizer 0.1.0
Precise position size calculator for traders - CLI tool for risk management
License: MIT
Requires Python: >=3.10
Keywords: trading, risk-management, position-sizing, cli, crypto, stocks

# Position Sizer

[![Ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/brody4321)

[![Buy Me A Coffee](https://img.shields.io/badge/Buy%20Me%20A%20Coffee-support-yellow?logo=buymeacoffee)](https://buymeacoffee.com/brody4321)

A precise command-line tool for calculating proper position sizes based on account risk percentage, entry price, stop loss, and current portfolio value.

## Features

- **Position Sizing** - Calculate exact position size based on risk tolerance
- **Long & Short** - Support for both directions
- **Risk/Reward** - Calculate R:R ratios and break-even win rates
- **Kelly Criterion** - Optimal bet sizing based on historical performance
- **Drawdown Simulator** - See impact of consecutive losses
- **Commission Aware** - Factor in trading fees
- **High Precision** - Uses Decimal math for accuracy (important for crypto)
- **Zero Dependencies** - No external API calls, works completely offline

## Installation

```bash
pip install position-sizer
```

## Quick Start

```bash
# Basic position sizing - risk 1% of $10,000 account
position-sizer calc --account 10000 --entry 100 --stop 95 --risk-pct 1.0

# Short position with fixed dollar risk
position-sizer calc --account 10000 --entry 100 --stop 110 --risk-usd 500 --side short

# Include commission in calculation
position-sizer calc --account 10000 --entry 100 --stop 95 --risk-pct 1.0 --commission 0.04

# Calculate with R:R target
position-sizer calc --account 10000 --entry 100 --stop 95 --risk-pct 1.0 --target 115
```

## Commands

### `calc` - Position Size Calculator

The main command for calculating position sizes.

```bash
position-sizer calc \
  --account 48250.75 \
  --entry 4231.40 \
  --stop 4187.90 \
  --risk-pct 1.0
```

Output:
```
╭─────────────────────────────╮
│ Position Size Calculator    │
╰─────────────────────────────╯
Account size       $48,250.75
Risk %             1.00%
Risk amount        $482.51
Side               LONG
Entry price        4231.4
Stop price         4187.9
Distance to stop   43.5 (1.03%)

Position Size: 11.09195402 units
Position Value: $46,928.07
```

Options:
- `--account, -a` - Account size in USD (required)
- `--entry, -e` - Entry price (required)
- `--stop, -s` - Stop loss price (required)
- `--risk-pct, -r` - Risk as percentage (e.g., 1.0 for 1%)
- `--risk-usd, -u` - Risk as fixed USD amount
- `--side` - Trade direction: `long` or `short` (default: long)
- `--commission, -c` - Commission per unit traded
- `--target, -t` - Take profit target (calculates R:R)

### `rr` - Risk/Reward Calculator

Calculate risk/reward ratio and required win rate.

```bash
position-sizer rr --entry 100 --stop 95 --target 115
```

Output:
```
╭─────────────────────────────╮
│ Risk/Reward Calculator      │
╰─────────────────────────────╯
Side               LONG
Entry              100
Stop               95
Target             115
Risk               5
Reward             15

Risk/Reward Ratio: 1:3.00
Break-even win rate needed: 25.0%
```

### `kelly` - Kelly Criterion

Calculate optimal position sizing based on your historical performance.

```bash
position-sizer kelly \
  --account 10000 \
  --win-rate 0.55 \
  --avg-win 150 \
  --avg-loss 100
```

Output:
```
╭─────────────────────────────╮
│ Kelly Criterion Calculator  │
╰─────────────────────────────╯
Win rate           55.0%
Avg winner         $150.00
Avg loser          $100.00
Win/Loss ratio     1.50

Full Kelly: 18.3% of account
Half Kelly (safer): 9.2%
Quarter Kelly (conservative): 4.6%

For $10,000.00 account:
  Full Kelly risk: $1,833.33
  Half Kelly risk: $916.67
```

### `drawdown` - Drawdown Simulator

See what happens after a streak of losses.

```bash
position-sizer drawdown --account 10000 --risk-pct 2.0 --trades 10
```

Output:
```
╭─────────────────────────────╮
│ Drawdown Simulator          │
╰─────────────────────────────╯
┏━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━━━━┓
┃ Trade # ┃ Loss       ┃ Balance    ┃ Total DD ┃
┡━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━━━━┩
│ 1       │ -$200.00   │ $9,800.00  │ -2.0%    │
│ 2       │ -$196.00   │ $9,604.00  │ -4.0%    │
│ 3       │ -$192.08   │ $9,411.92  │ -5.9%    │
│ ...     │ ...        │ ...        │ ...      │
│ 10      │ -$166.77   │ $8,171.02  │ -18.3%   │
└─────────┴────────────┴────────────┴──────────┘

After 10 consecutive losses at 2.0% risk:
  Starting: $10,000.00
  Ending: $8,171.02
  Total Drawdown: -18.3%
  Gain needed to recover: +22.4%
```

## Use as Library

```python
from position_sizer import PositionCalculator

calc = PositionCalculator()

# Calculate position size
result = calc.calculate(
    account_size=10000,
    entry_price=100,
    stop_price=95,
    risk_percent=1.0,
    side="long",
)

print(f"Position size: {result.position_size} units")
print(f"Position value: ${result.position_value}")
print(f"Risk amount: ${result.risk_amount}")

# Calculate risk/reward
rr = calc.calculate_risk_reward(
    entry_price=100,
    stop_price=95,
    target_price=115,
    side="long",
)
print(f"Risk/Reward: 1:{rr}")

# Kelly Criterion
kelly = calc.kelly_criterion(
    win_rate=0.55,
    avg_win=150,
    avg_loss=100,
)
print(f"Kelly optimal: {kelly * 100:.1f}%")
```

## The Math

### Position Size Formula

```
Position Size = Risk Amount / Risk Per Unit

Where:
- Risk Amount = Account Size × Risk Percentage
- Risk Per Unit = |Entry Price - Stop Price| + (2 × Commission)
```

### Kelly Criterion Formula

```
f* = (p × b - q) / b

Where:
- f* = fraction of account to risk
- p = probability of winning
- q = probability of losing (1 - p)
- b = win/loss ratio (avg_win / avg_loss)
```

### Why Use Half-Kelly?

Full Kelly maximizes long-term growth but causes large drawdowns. Most traders use:
- **Half Kelly** - Good balance of growth and drawdown
- **Quarter Kelly** - Conservative, smoother equity curve

## Tips

1. **Never risk more than you can afford to lose** - The calculator doesn't know your situation
2. **Account for slippage** - Your actual stop might execute worse than planned
3. **Use Half-Kelly or less** - Full Kelly is mathematically optimal but emotionally brutal
4. **Round down** - The calculator rounds position sizes down, never up
5. **Test with paper trading** - Verify the math matches your broker's calculations

## License

MIT License