Merge branch 'worktree-agent-ad9ede16'

# Conflicts:
#	shared/strategies/__init__.py
#	shared/strategies/base.py
#	shared/strategies/mean_reversion.py
#	shared/strategies/momentum.py
#	shared/strategies/news_driven.py
This commit is contained in:
Viktor Barzin 2026-02-22 15:37:25 +00:00
commit 1d9900838d
No known key found for this signature in database
GPG key ID: 0EB088298288D958
11 changed files with 1532 additions and 0 deletions

View file

@ -0,0 +1,359 @@
"""Tests for the Signal Generator service.
Covers MarketDataManager (SMA, RSI, snapshot) and WeightedEnsemble
(signal combination, threshold filtering, strategy source tagging).
"""
from __future__ import annotations
from datetime import datetime, timezone
import pytest
from services.signal_generator.ensemble import WeightedEnsemble
from services.signal_generator.market_data import MarketDataManager
from shared.schemas.trading import (
MarketSnapshot,
OHLCVBar,
SentimentContext,
SignalDirection,
TradeSignal,
)
from shared.strategies.base import BaseStrategy
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_bar(close: float, *, ts_offset: int = 0) -> OHLCVBar:
"""Create an ``OHLCVBar`` with the given close price."""
return OHLCVBar(
timestamp=datetime(2026, 1, 1, 10, ts_offset, tzinfo=timezone.utc),
open=close - 0.5,
high=close + 1.0,
low=close - 1.0,
close=close,
volume=1000.0,
)
class _StubStrategy(BaseStrategy):
"""Test helper that returns a preconfigured signal."""
def __init__(self, name: str, signal: TradeSignal | None) -> None:
self.name = name
self._signal = signal
async def evaluate(self, ticker, market, sentiment=None):
return self._signal
def _make_signal(
direction: SignalDirection = SignalDirection.LONG,
strength: float = 0.8,
sources: list[str] | None = None,
) -> TradeSignal:
return TradeSignal(
ticker="AAPL",
direction=direction,
strength=strength,
strategy_sources=sources or ["test"],
timestamp=datetime.now(timezone.utc),
)
# ---------------------------------------------------------------------------
# MarketDataManager — SMA
# ---------------------------------------------------------------------------
class TestMarketDataManagerSMA:
"""Tests for SMA computation inside MarketDataManager."""
def test_sma_basic(self):
"""SMA-20 should equal the mean of the last 20 close prices."""
mgr = MarketDataManager()
closes = list(range(1, 21)) # 1, 2, ..., 20
for i, c in enumerate(closes):
mgr.add_bar("AAPL", _make_bar(float(c), ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
expected_sma_20 = sum(closes) / 20
assert snap.sma_20 == pytest.approx(expected_sma_20)
def test_sma_returns_none_insufficient_data(self):
"""SMA-20 should be None when fewer than 20 bars exist."""
mgr = MarketDataManager()
for i in range(10):
mgr.add_bar("AAPL", _make_bar(100.0, ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.sma_20 is None
def test_sma_50_requires_50_bars(self):
"""SMA-50 should be None with only 30 bars, present with 50."""
mgr = MarketDataManager()
for i in range(30):
mgr.add_bar("AAPL", _make_bar(float(i + 1), ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.sma_50 is None
# Add 20 more
for i in range(30, 50):
mgr.add_bar("AAPL", _make_bar(float(i + 1), ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.sma_50 is not None
expected = sum(range(1, 51)) / 50
assert snap.sma_50 == pytest.approx(expected)
# ---------------------------------------------------------------------------
# MarketDataManager — RSI
# ---------------------------------------------------------------------------
class TestMarketDataManagerRSI:
"""Tests for RSI computation inside MarketDataManager."""
def test_rsi_all_gains(self):
"""RSI should be 100 when all price changes are positive."""
mgr = MarketDataManager()
for i in range(20):
mgr.add_bar("AAPL", _make_bar(100.0 + i, ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.rsi == pytest.approx(100.0)
def test_rsi_all_losses(self):
"""RSI should be 0 when all price changes are negative."""
mgr = MarketDataManager()
for i in range(20):
mgr.add_bar("AAPL", _make_bar(200.0 - i, ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.rsi == pytest.approx(0.0)
def test_rsi_mixed(self):
"""RSI should be between 0 and 100 with mixed gains and losses."""
mgr = MarketDataManager()
prices = [44, 44.34, 44.09, 43.61, 44.33, 44.83, 45.10, 45.42,
45.84, 46.08, 45.89, 46.03, 45.61, 46.28, 46.28, 46.00]
for i, p in enumerate(prices):
mgr.add_bar("AAPL", _make_bar(p, ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.rsi is not None
assert 0 < snap.rsi < 100
def test_rsi_returns_none_insufficient_data(self):
"""RSI should be None when fewer than 15 bars exist (need 14+1)."""
mgr = MarketDataManager()
for i in range(10):
mgr.add_bar("AAPL", _make_bar(100.0, ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.rsi is None
# ---------------------------------------------------------------------------
# MarketDataManager — snapshot
# ---------------------------------------------------------------------------
class TestMarketDataManagerSnapshot:
"""Tests for get_snapshot behaviour."""
def test_snapshot_returns_none_for_unknown_ticker(self):
mgr = MarketDataManager()
assert mgr.get_snapshot("UNKNOWN") is None
def test_snapshot_uses_latest_bar_for_price(self):
mgr = MarketDataManager()
mgr.add_bar("AAPL", _make_bar(100.0, ts_offset=0))
mgr.add_bar("AAPL", _make_bar(105.0, ts_offset=1))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert snap.current_price == 105.0
def test_snapshot_contains_bars(self):
mgr = MarketDataManager()
for i in range(5):
mgr.add_bar("AAPL", _make_bar(100.0 + i, ts_offset=i))
snap = mgr.get_snapshot("AAPL")
assert snap is not None
assert len(snap.bars) == 5
# ---------------------------------------------------------------------------
# WeightedEnsemble — combines signals
# ---------------------------------------------------------------------------
class TestEnsembleCombinesSignals:
"""Test that the ensemble correctly combines strategy signals."""
@pytest.mark.asyncio
async def test_combines_two_long_signals(self):
"""Two LONG signals should produce a combined LONG signal."""
s1 = _StubStrategy("alpha", _make_signal(SignalDirection.LONG, 0.8))
s2 = _StubStrategy("beta", _make_signal(SignalDirection.LONG, 0.6))
ensemble = WeightedEnsemble([s1, s2], threshold=0.0)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"alpha": 0.5, "beta": 0.5}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is not None
assert signal.direction == SignalDirection.LONG
# Weighted average = (0.8*0.5 + 0.6*0.5) / (0.5+0.5) = 0.7
assert signal.strength == pytest.approx(0.7, abs=0.01)
@pytest.mark.asyncio
async def test_opposing_signals_net_direction(self):
"""When strategies disagree, direction follows the stronger weighted side."""
s1 = _StubStrategy("alpha", _make_signal(SignalDirection.LONG, 0.9))
s2 = _StubStrategy("beta", _make_signal(SignalDirection.SHORT, 0.3))
ensemble = WeightedEnsemble([s1, s2], threshold=0.0)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"alpha": 0.5, "beta": 0.5}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is not None
# Net direction should be LONG since alpha is stronger
assert signal.direction == SignalDirection.LONG
# ---------------------------------------------------------------------------
# WeightedEnsemble — threshold filtering
# ---------------------------------------------------------------------------
class TestEnsembleThresholdFiltering:
"""Test that weak combined signals are filtered out by the threshold."""
@pytest.mark.asyncio
async def test_below_threshold_returns_none(self):
"""Combined strength below threshold should yield None."""
# Two opposing signals of similar strength will nearly cancel out
s1 = _StubStrategy("alpha", _make_signal(SignalDirection.LONG, 0.5))
s2 = _StubStrategy("beta", _make_signal(SignalDirection.SHORT, 0.45))
ensemble = WeightedEnsemble([s1, s2], threshold=0.5)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"alpha": 0.5, "beta": 0.5}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is None
@pytest.mark.asyncio
async def test_above_threshold_returns_signal(self):
"""Strong combined signal above threshold should yield a signal."""
s1 = _StubStrategy("alpha", _make_signal(SignalDirection.LONG, 0.9))
ensemble = WeightedEnsemble([s1], threshold=0.3)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"alpha": 1.0}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is not None
assert signal.strength >= 0.3
# ---------------------------------------------------------------------------
# WeightedEnsemble — no signals returns None
# ---------------------------------------------------------------------------
class TestEnsembleNoSignals:
"""Test that the ensemble returns None when no strategy fires."""
@pytest.mark.asyncio
async def test_all_strategies_return_none(self):
s1 = _StubStrategy("alpha", None)
s2 = _StubStrategy("beta", None)
ensemble = WeightedEnsemble([s1, s2], threshold=0.3)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"alpha": 0.5, "beta": 0.5}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is None
# ---------------------------------------------------------------------------
# WeightedEnsemble — tags strategy sources
# ---------------------------------------------------------------------------
class TestEnsembleTagsStrategySources:
"""Verify that the output signal records which strategies contributed."""
@pytest.mark.asyncio
async def test_strategy_sources_contains_all_contributors(self):
s1 = _StubStrategy("momentum", _make_signal(SignalDirection.LONG, 0.7, ["momentum"]))
s2 = _StubStrategy("news_driven", _make_signal(SignalDirection.LONG, 0.6, ["news_driven"]))
s3 = _StubStrategy("mean_reversion", None) # does not contribute
ensemble = WeightedEnsemble([s1, s2, s3], threshold=0.0)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"momentum": 0.5, "news_driven": 0.3, "mean_reversion": 0.2}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is not None
# Should have exactly 2 sources
assert len(signal.strategy_sources) == 2
source_names = [s.split(":")[0] for s in signal.strategy_sources]
assert "momentum" in source_names
assert "news_driven" in source_names
# mean_reversion should NOT be present
assert "mean_reversion" not in source_names
@pytest.mark.asyncio
async def test_strategy_sources_contain_direction_and_strength(self):
"""Each source tag should be formatted as name:DIRECTION:strength."""
s1 = _StubStrategy("alpha", _make_signal(SignalDirection.LONG, 0.75))
ensemble = WeightedEnsemble([s1], threshold=0.0)
market = MarketSnapshot(
ticker="AAPL", current_price=150.0,
open=149.0, high=151.0, low=148.0, close=150.0, volume=1000,
)
weights = {"alpha": 1.0}
signal = await ensemble.evaluate("AAPL", market, None, weights)
assert signal is not None
assert len(signal.strategy_sources) == 1
parts = signal.strategy_sources[0].split(":")
assert parts[0] == "alpha"
assert parts[1] == "LONG"
assert float(parts[2]) == pytest.approx(0.75, abs=0.01)

View file

@ -0,0 +1,403 @@
"""Tests for the Trade Executor service.
Covers RiskManager (market hours, positions, exposure, cooldown,
position sizing) and the end-to-end executor flow with a mocked broker.
"""
from __future__ import annotations
from datetime import datetime, timedelta, timezone
from unittest.mock import AsyncMock, MagicMock, patch
from zoneinfo import ZoneInfo
import pytest
from services.trade_executor.config import TradeExecutorConfig
from services.trade_executor.main import process_signal
from services.trade_executor.risk_manager import RiskManager
from shared.schemas.trading import (
AccountInfo,
OrderResult,
OrderSide,
OrderStatus,
PositionInfo,
SignalDirection,
TradeSignal,
)
_ET = ZoneInfo("America/New_York")
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _make_config(**overrides) -> TradeExecutorConfig:
defaults = dict(
max_position_pct=0.05,
max_total_exposure_pct=0.80,
max_positions=20,
default_stop_loss_pct=0.03,
cooldown_minutes=30,
alpaca_api_key="test",
alpaca_secret_key="test",
paper_trading=True,
)
defaults.update(overrides)
return TradeExecutorConfig(**defaults)
def _make_signal(
ticker: str = "AAPL",
direction: SignalDirection = SignalDirection.LONG,
strength: float = 0.8,
current_price: float = 150.0,
) -> TradeSignal:
return TradeSignal(
ticker=ticker,
direction=direction,
strength=strength,
strategy_sources=["test"],
sentiment_context={"current_price": current_price},
timestamp=datetime.now(timezone.utc),
)
def _make_account(equity: float = 100_000.0) -> AccountInfo:
return AccountInfo(
equity=equity,
cash=equity,
buying_power=equity * 2,
portfolio_value=equity,
)
def _make_position(ticker: str = "AAPL", market_value: float = 5000.0) -> PositionInfo:
return PositionInfo(
ticker=ticker,
qty=10.0,
avg_entry=150.0,
current_price=150.0,
unrealized_pnl=0.0,
market_value=market_value,
)
def _mock_broker(positions: list[PositionInfo] | None = None, account: AccountInfo | None = None):
"""Create an AsyncMock broker with configurable positions and account."""
broker = AsyncMock()
broker.get_positions = AsyncMock(return_value=positions or [])
broker.get_account = AsyncMock(return_value=account or _make_account())
broker.submit_order = AsyncMock(
return_value=OrderResult(
order_id="ord-123",
ticker="AAPL",
side=OrderSide.BUY,
qty=10.0,
filled_price=150.0,
status=OrderStatus.FILLED,
timestamp=datetime.now(timezone.utc),
)
)
return broker
# ---------------------------------------------------------------------------
# RiskManager — risk check passes
# ---------------------------------------------------------------------------
class TestRiskCheckPasses:
"""All conditions met -> risk check passes."""
@pytest.mark.asyncio
async def test_all_conditions_met(self):
config = _make_config()
broker = _mock_broker(positions=[], account=_make_account(100_000))
rm = RiskManager(config, broker)
signal = _make_signal()
# Patch _is_market_hours to return True
with patch.object(RiskManager, "_is_market_hours", return_value=True):
approved, reason = await rm.check_risk(signal)
assert approved is True
assert reason == "approved"
# ---------------------------------------------------------------------------
# RiskManager — max positions exceeded
# ---------------------------------------------------------------------------
class TestRiskCheckMaxPositions:
"""Risk check fails when max_positions is already reached."""
@pytest.mark.asyncio
async def test_max_positions_exceeded(self):
config = _make_config(max_positions=2)
# Already have 2 positions
positions = [_make_position("AAPL"), _make_position("MSFT")]
broker = _mock_broker(positions=positions, account=_make_account())
rm = RiskManager(config, broker)
signal = _make_signal(ticker="GOOG")
with patch.object(RiskManager, "_is_market_hours", return_value=True):
approved, reason = await rm.check_risk(signal)
assert approved is False
assert "max_positions" in reason
# ---------------------------------------------------------------------------
# RiskManager — max exposure exceeded
# ---------------------------------------------------------------------------
class TestRiskCheckMaxExposure:
"""Risk check fails when total exposure exceeds the limit."""
@pytest.mark.asyncio
async def test_max_exposure_exceeded(self):
config = _make_config(max_total_exposure_pct=0.50)
account = _make_account(equity=100_000)
# Single position worth $60k = 60% of equity, limit is 50%
positions = [_make_position("AAPL", market_value=60_000)]
broker = _mock_broker(positions=positions, account=account)
rm = RiskManager(config, broker)
signal = _make_signal(ticker="MSFT")
with patch.object(RiskManager, "_is_market_hours", return_value=True):
approved, reason = await rm.check_risk(signal)
assert approved is False
assert "max_exposure" in reason
# ---------------------------------------------------------------------------
# RiskManager — cooldown active
# ---------------------------------------------------------------------------
class TestRiskCheckCooldown:
"""Risk check fails when a ticker is in cooldown."""
@pytest.mark.asyncio
async def test_cooldown_active(self):
config = _make_config(cooldown_minutes=30)
broker = _mock_broker()
rm = RiskManager(config, broker)
# Record an exit 10 minutes ago
now_et = datetime.now(tz=_ET)
rm.record_exit("AAPL", now_et - timedelta(minutes=10))
signal = _make_signal(ticker="AAPL")
with patch.object(RiskManager, "_is_market_hours", return_value=True):
approved, reason = await rm.check_risk(signal)
assert approved is False
assert "cooldown" in reason
@pytest.mark.asyncio
async def test_cooldown_expired(self):
"""After cooldown period expires the trade should be approved."""
config = _make_config(cooldown_minutes=30)
broker = _mock_broker()
rm = RiskManager(config, broker)
# Record an exit 45 minutes ago
now_et = datetime.now(tz=_ET)
rm.record_exit("AAPL", now_et - timedelta(minutes=45))
signal = _make_signal(ticker="AAPL")
with patch.object(RiskManager, "_is_market_hours", return_value=True):
approved, reason = await rm.check_risk(signal)
assert approved is True
# ---------------------------------------------------------------------------
# RiskManager — outside market hours
# ---------------------------------------------------------------------------
class TestRiskCheckMarketHours:
"""Risk check fails outside regular market hours."""
@pytest.mark.asyncio
async def test_outside_market_hours(self):
config = _make_config()
broker = _mock_broker()
rm = RiskManager(config, broker)
signal = _make_signal()
# Force market hours check to fail (no patching — use the real check
# with a time that is definitely outside market hours)
with patch.object(RiskManager, "_is_market_hours", return_value=False):
approved, reason = await rm.check_risk(signal)
assert approved is False
assert "market_hours" in reason
def test_market_hours_weekday(self):
"""A weekday at 10:00 AM ET should be within market hours."""
# Tuesday 10:00 AM ET
t = datetime(2026, 2, 24, 10, 0, 0, tzinfo=_ET)
assert RiskManager._is_market_hours(t) is True
def test_market_hours_weekend(self):
"""Saturday should always be outside market hours."""
t = datetime(2026, 2, 21, 10, 0, 0, tzinfo=_ET) # Saturday
assert RiskManager._is_market_hours(t) is False
def test_market_hours_before_open(self):
"""8:00 AM ET on a weekday is before market open."""
t = datetime(2026, 2, 24, 8, 0, 0, tzinfo=_ET) # Tuesday 8 AM
assert RiskManager._is_market_hours(t) is False
def test_market_hours_after_close(self):
"""5:00 PM ET on a weekday is after market close."""
t = datetime(2026, 2, 24, 17, 0, 0, tzinfo=_ET) # Tuesday 5 PM
assert RiskManager._is_market_hours(t) is False
# ---------------------------------------------------------------------------
# Position sizing — scales by strength
# ---------------------------------------------------------------------------
class TestPositionSizingScalesByStrength:
"""Position size should scale proportionally with signal strength."""
def test_full_strength(self):
config = _make_config(max_position_pct=0.05)
broker = _mock_broker()
rm = RiskManager(config, broker)
signal = _make_signal(strength=1.0, current_price=100.0)
account = _make_account(equity=100_000)
qty = rm.calculate_position_size(signal, account)
# position_value = 100k * 0.05 * 1.0 = 5000 / 100 = 50 shares
assert qty == 50
def test_half_strength(self):
config = _make_config(max_position_pct=0.05)
broker = _mock_broker()
rm = RiskManager(config, broker)
signal = _make_signal(strength=0.5, current_price=100.0)
account = _make_account(equity=100_000)
qty = rm.calculate_position_size(signal, account)
# position_value = 100k * 0.05 * 0.5 = 2500 / 100 = 25 shares
assert qty == 25
# ---------------------------------------------------------------------------
# Position sizing — respects max_position_pct
# ---------------------------------------------------------------------------
class TestPositionSizingRespectsMaxPct:
"""Position size should respect the max_position_pct cap."""
def test_respects_max_pct(self):
config = _make_config(max_position_pct=0.02)
broker = _mock_broker()
rm = RiskManager(config, broker)
signal = _make_signal(strength=1.0, current_price=50.0)
account = _make_account(equity=100_000)
qty = rm.calculate_position_size(signal, account)
# position_value = 100k * 0.02 * 1.0 = 2000 / 50 = 40 shares
assert qty == 40
def test_zero_price_returns_zero(self):
config = _make_config()
broker = _mock_broker()
rm = RiskManager(config, broker)
signal = _make_signal(strength=0.8, current_price=0.0)
account = _make_account(equity=100_000)
qty = rm.calculate_position_size(signal, account)
assert qty == 0
# ---------------------------------------------------------------------------
# Executor flow — approved signal
# ---------------------------------------------------------------------------
class TestExecutorFlowApproved:
"""End-to-end: approved signal -> order submitted -> trade published."""
@pytest.mark.asyncio
async def test_approved_signal_flow(self):
config = _make_config()
broker = _mock_broker(positions=[], account=_make_account(100_000))
publisher = AsyncMock()
publisher.publish = AsyncMock(return_value=b"1-0")
counters = {
"trades_executed": MagicMock(),
"rejections": MagicMock(),
"fill_latency": MagicMock(),
}
signal = _make_signal(ticker="AAPL", strength=0.8, current_price=150.0)
# Patch risk check to approve
with patch.object(RiskManager, "check_risk", return_value=(True, "approved")):
await process_signal(signal, RiskManager(config, broker), broker, publisher, counters)
# Verify order was submitted
broker.submit_order.assert_called_once()
order_arg = broker.submit_order.call_args[0][0]
assert order_arg.ticker == "AAPL"
assert order_arg.side == OrderSide.BUY
# Verify trade was published
publisher.publish.assert_called_once()
counters["trades_executed"].add.assert_called_once_with(1)
# ---------------------------------------------------------------------------
# Executor flow — rejected signal
# ---------------------------------------------------------------------------
class TestExecutorFlowRejected:
"""End-to-end: rejected signal -> no order, rejection logged."""
@pytest.mark.asyncio
async def test_rejected_signal_flow(self):
config = _make_config()
broker = _mock_broker()
publisher = AsyncMock()
counters = {
"trades_executed": MagicMock(),
"rejections": MagicMock(),
"fill_latency": MagicMock(),
}
signal = _make_signal(ticker="AAPL")
with patch.object(
RiskManager, "check_risk", return_value=(False, "outside_market_hours")
):
await process_signal(signal, RiskManager(config, broker), broker, publisher, counters)
# No order should have been submitted
broker.submit_order.assert_not_called()
# No trade should have been published
publisher.publish.assert_not_called()
# Rejection counter should have been incremented
counters["rejections"].add.assert_called_once()