Alice — an open-source AI trading bot covering equities, crypto, commodities, forex, and macro
| 1 | """Tests for position sizing and risk management.""" |
| 2 | |
| 3 | import pytest |
| 4 | |
| 5 | from open_alice.risk.position_sizing import PositionSizer |
| 6 | |
| 7 | |
| 8 | def test_calculate_size_basic() -> None: |
| 9 | sizer = PositionSizer(risk_per_trade=0.02) |
| 10 | # $100k capital, risk 2% = $2000, risk $5/share => 400 shares |
| 11 | size = sizer.calculate_size(capital=100_000, entry_price=100, stop_price=95) |
| 12 | assert size == 400 |
| 13 | |
| 14 | |
| 15 | def test_calculate_size_zero_risk_per_share() -> None: |
| 16 | sizer = PositionSizer(risk_per_trade=0.02) |
| 17 | size = sizer.calculate_size(capital=100_000, entry_price=100, stop_price=100) |
| 18 | assert size == 0 |
| 19 | |
| 20 | |
| 21 | def test_should_exit_stop_loss() -> None: |
| 22 | sizer = PositionSizer(stop_loss_pct=0.05) |
| 23 | # Long position, price dropped 6% — should exit |
| 24 | assert sizer.should_exit(entry_price=100, current_price=94, position=1) is True |
| 25 | |
| 26 | |
| 27 | def test_should_exit_take_profit() -> None: |
| 28 | sizer = PositionSizer(take_profit_pct=0.10) |
| 29 | # Long position, price rose 12% — should exit |
| 30 | assert sizer.should_exit(entry_price=100, current_price=112, position=1) is True |
| 31 | |
| 32 | |
| 33 | def test_should_not_exit() -> None: |
| 34 | sizer = PositionSizer(stop_loss_pct=0.05, take_profit_pct=0.10) |
| 35 | # Long position, price moved 2% — within bounds |
| 36 | assert sizer.should_exit(entry_price=100, current_price=102, position=1) is False |
| 37 | |
| 38 | |
| 39 | def test_invalid_risk_per_trade() -> None: |
| 40 | with pytest.raises(ValueError): |
| 41 | PositionSizer(risk_per_trade=1.5) |