File size: 6,197 Bytes
d53dc44 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 | """
tests/test_risk.py — Risk check pipeline tests.
Covers:
- Safe mode blocking
- Daily loss limit
- Max positions limit
- 3 consecutive losses → pause + half size
- Profit lock after daily target
- Position sizing with ATR
"""
from __future__ import annotations
import datetime
from unittest.mock import patch
import pytest
import config
from contracts import FinalScore
from execution import risk as risk_module
@pytest.fixture(autouse=True)
def reset_risk_state():
"""Reset risk module state before each test."""
risk_module._last_reset_date = None # force reset
risk_module.reset_daily_state(equity=100_000.0)
yield
def _make_final(symbol: str, decision: str = "BUY", score: float = 0.7) -> FinalScore:
return FinalScore(
symbol=symbol,
timestamp=datetime.datetime.now(datetime.timezone.utc),
technical=score,
sentiment=0.5,
final=score,
decision=decision,
)
class TestDailyLossLimit:
@patch("execution.broker.safe_mode_active", False)
@patch("execution.broker.cancel_all_orders")
@patch("execution.broker.close_all_positions")
def test_blocks_after_max_loss(self, mock_close, mock_cancel):
"""After exceeding daily loss limit, all trades should be blocked."""
risk_module.update_pnl(realized=-(config.MAX_DAILY_LOSS_USD + 5.0), unrealized=0.0)
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=0,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert not allowed
assert "daily_loss" in reason.lower() or "loss" in reason.lower()
@patch("execution.broker.safe_mode_active", False)
def test_allows_within_limit(self):
risk_module.update_pnl(realized=-10.0, unrealized=0.0)
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=0,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert allowed
class TestMaxPositions:
@patch("execution.broker.safe_mode_active", False)
def test_blocks_at_max(self):
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=config.MAX_OPEN_POSITIONS,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert not allowed
@patch("execution.broker.safe_mode_active", False)
def test_allows_below_max(self):
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=2,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert allowed
class TestConsecutiveLosses:
@patch("execution.broker.safe_mode_active", False)
def test_pause_after_3_losses(self):
"""3 consecutive losses → 30 min pause."""
for _ in range(3):
risk_module.record_trade_result(-100.0)
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=0,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert not allowed
def test_half_size_after_3_losses(self):
"""After 3 losses, half_size_mode should be True."""
for _ in range(3):
risk_module.record_trade_result(-100.0)
# Trigger the risk check which sets half_size_mode
with patch("execution.broker.safe_mode_active", False):
risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=0,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert risk_module.half_size_mode
class TestProfitLock:
@patch("execution.broker.safe_mode_active", False)
def test_locks_after_target(self):
"""After hitting the configured daily target, lock profits."""
risk_module.update_pnl(realized=config.TARGET_DAILY_PROFIT_USD + 5.0, unrealized=0.0)
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=0,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert not allowed
assert "profit" in reason.lower() or "target" in reason.lower()
class TestPositionSizing:
@patch("execution.broker.is_fractionable", return_value=True)
def test_size_within_risk_budget(self, mock_frac):
qty, stop_dist, is_frac = risk_module.compute_position_size(
equity=100_000.0,
atr_value=2.0,
symbol="AAPL",
)
# Risk per trade = 1% of $100k = $1000
# With ATR stop = 2.0 * 1.0 = $2.0
# Qty = 1000 / 2.0 = 500
assert qty > 0
assert stop_dist > 0
@patch("execution.broker.is_fractionable", return_value=True)
def test_fractional_flag(self, mock_frac):
qty, _, is_frac = risk_module.compute_position_size(
equity=100.0, # tiny account → fractional
atr_value=2.0,
symbol="AAPL",
)
if qty > 0 and qty < 1:
assert is_frac
class TestSafeMode:
@patch("execution.broker.safe_mode_active", True)
def test_safe_mode_blocks(self):
allowed, reason = risk_module.run_risk_checks(
symbol="AAPL",
final_score=_make_final("AAPL"),
open_position_count=0,
open_positions={},
alert_callback=lambda *a, **kw: None,
)
assert not allowed
assert "safe" in reason.lower()
|