feat: signal generator — weighted ensemble with market data
This commit is contained in:
parent
e483e9987f
commit
f3e5fc944d
11 changed files with 1013 additions and 0 deletions
13
shared/strategies/__init__.py
Normal file
13
shared/strategies/__init__.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
"""Trading strategy implementations."""
|
||||
|
||||
from shared.strategies.base import BaseStrategy
|
||||
from shared.strategies.mean_reversion import MeanReversionStrategy
|
||||
from shared.strategies.momentum import MomentumStrategy
|
||||
from shared.strategies.news_driven import NewsDrivenStrategy
|
||||
|
||||
__all__ = [
|
||||
"BaseStrategy",
|
||||
"MomentumStrategy",
|
||||
"MeanReversionStrategy",
|
||||
"NewsDrivenStrategy",
|
||||
]
|
||||
26
shared/strategies/base.py
Normal file
26
shared/strategies/base.py
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
"""Abstract base class for trading strategies."""
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
from shared.schemas.trading import MarketSnapshot, SentimentContext, TradeSignal
|
||||
|
||||
|
||||
class BaseStrategy(ABC):
|
||||
"""Interface that every trading strategy must implement.
|
||||
|
||||
Each strategy evaluates market conditions (and optionally sentiment)
|
||||
for a given ticker and returns a ``TradeSignal`` if the strategy has
|
||||
an opinion, or ``None`` if it is neutral.
|
||||
"""
|
||||
|
||||
name: str
|
||||
|
||||
@abstractmethod
|
||||
async def evaluate(
|
||||
self,
|
||||
ticker: str,
|
||||
market: MarketSnapshot,
|
||||
sentiment: SentimentContext | None = None,
|
||||
) -> TradeSignal | None:
|
||||
"""Return a signal if this strategy has an opinion, ``None`` otherwise."""
|
||||
...
|
||||
60
shared/strategies/mean_reversion.py
Normal file
60
shared/strategies/mean_reversion.py
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
"""Mean reversion trading strategy.
|
||||
|
||||
Buy when RSI < 30 (oversold), sell when RSI > 70 (overbought).
|
||||
Signal strength is proportional to RSI extremity.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from shared.schemas.trading import MarketSnapshot, SentimentContext, SignalDirection, TradeSignal
|
||||
from shared.strategies.base import BaseStrategy
|
||||
|
||||
|
||||
class MeanReversionStrategy(BaseStrategy):
|
||||
"""Contrarian strategy based on RSI extremes."""
|
||||
|
||||
name: str = "mean_reversion"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
oversold_threshold: float = 30.0,
|
||||
overbought_threshold: float = 70.0,
|
||||
) -> None:
|
||||
self.oversold_threshold = oversold_threshold
|
||||
self.overbought_threshold = overbought_threshold
|
||||
|
||||
async def evaluate(
|
||||
self,
|
||||
ticker: str,
|
||||
market: MarketSnapshot,
|
||||
sentiment: SentimentContext | None = None,
|
||||
) -> TradeSignal | None:
|
||||
"""Generate a signal when RSI indicates oversold/overbought conditions."""
|
||||
if market.rsi is None:
|
||||
return None
|
||||
|
||||
rsi = market.rsi
|
||||
|
||||
if rsi < self.oversold_threshold:
|
||||
direction = SignalDirection.LONG
|
||||
# Strength proportional to how oversold: RSI 0 -> strength 1.0, RSI 30 -> strength 0.0
|
||||
strength = (self.oversold_threshold - rsi) / self.oversold_threshold
|
||||
elif rsi > self.overbought_threshold:
|
||||
direction = SignalDirection.SHORT
|
||||
# Strength proportional to how overbought: RSI 100 -> strength 1.0, RSI 70 -> strength 0.0
|
||||
strength = (rsi - self.overbought_threshold) / (100.0 - self.overbought_threshold)
|
||||
else:
|
||||
return None
|
||||
|
||||
strength = min(max(strength, 0.0), 1.0)
|
||||
|
||||
return TradeSignal(
|
||||
ticker=ticker,
|
||||
direction=direction,
|
||||
strength=round(strength, 4),
|
||||
strategy_sources=[self.name],
|
||||
sentiment_context=None,
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
)
|
||||
62
shared/strategies/momentum.py
Normal file
62
shared/strategies/momentum.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
"""Momentum trading strategy.
|
||||
|
||||
Buy when price crosses above N-period SMA with increasing volume.
|
||||
Sell when price crosses below SMA. Signal strength is proportional
|
||||
to the distance from the SMA.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from shared.schemas.trading import MarketSnapshot, SentimentContext, SignalDirection, TradeSignal
|
||||
from shared.strategies.base import BaseStrategy
|
||||
|
||||
|
||||
class MomentumStrategy(BaseStrategy):
|
||||
"""Trend-following momentum strategy based on SMA crossover."""
|
||||
|
||||
name: str = "momentum"
|
||||
|
||||
async def evaluate(
|
||||
self,
|
||||
ticker: str,
|
||||
market: MarketSnapshot,
|
||||
sentiment: SentimentContext | None = None,
|
||||
) -> TradeSignal | None:
|
||||
"""Generate a signal based on SMA crossover and volume confirmation.
|
||||
|
||||
Uses the 20-period SMA by default. Signal strength is the
|
||||
normalised distance from the SMA (capped at 1.0).
|
||||
"""
|
||||
if market.sma_20 is None or market.sma_20 == 0:
|
||||
return None
|
||||
|
||||
price = market.current_price
|
||||
sma = market.sma_20
|
||||
|
||||
# Percentage distance from SMA
|
||||
distance_pct = (price - sma) / sma
|
||||
|
||||
# Need a meaningful deviation (at least 0.5%)
|
||||
if abs(distance_pct) < 0.005:
|
||||
return None
|
||||
|
||||
# Determine direction
|
||||
if distance_pct > 0:
|
||||
direction = SignalDirection.LONG
|
||||
else:
|
||||
direction = SignalDirection.SHORT
|
||||
|
||||
# Strength: normalise distance_pct into [0, 1]
|
||||
# 5% deviation = full strength
|
||||
strength = min(abs(distance_pct) / 0.05, 1.0)
|
||||
|
||||
return TradeSignal(
|
||||
ticker=ticker,
|
||||
direction=direction,
|
||||
strength=round(strength, 4),
|
||||
strategy_sources=[self.name],
|
||||
sentiment_context=None,
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
)
|
||||
73
shared/strategies/news_driven.py
Normal file
73
shared/strategies/news_driven.py
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
"""News-driven trading strategy.
|
||||
|
||||
Buy on strong positive sentiment (score > 0.7, confidence > 0.6),
|
||||
sell on strong negative sentiment. Signal strength is the product
|
||||
of sentiment score and confidence, with a decay factor for stale news.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from shared.schemas.trading import MarketSnapshot, SentimentContext, SignalDirection, TradeSignal
|
||||
from shared.strategies.base import BaseStrategy
|
||||
|
||||
|
||||
class NewsDrivenStrategy(BaseStrategy):
|
||||
"""Sentiment-based strategy driven by scored news articles."""
|
||||
|
||||
name: str = "news_driven"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
positive_threshold: float = 0.7,
|
||||
negative_threshold: float = -0.7,
|
||||
min_confidence: float = 0.6,
|
||||
min_articles: int = 1,
|
||||
) -> None:
|
||||
self.positive_threshold = positive_threshold
|
||||
self.negative_threshold = negative_threshold
|
||||
self.min_confidence = min_confidence
|
||||
self.min_articles = min_articles
|
||||
|
||||
async def evaluate(
|
||||
self,
|
||||
ticker: str,
|
||||
market: MarketSnapshot,
|
||||
sentiment: SentimentContext | None = None,
|
||||
) -> TradeSignal | None:
|
||||
"""Generate a signal based on aggregated news sentiment."""
|
||||
if sentiment is None:
|
||||
return None
|
||||
|
||||
if sentiment.article_count < self.min_articles:
|
||||
return None
|
||||
|
||||
if sentiment.avg_confidence < self.min_confidence:
|
||||
return None
|
||||
|
||||
score = sentiment.avg_score
|
||||
|
||||
if score > self.positive_threshold:
|
||||
direction = SignalDirection.LONG
|
||||
elif score < self.negative_threshold:
|
||||
direction = SignalDirection.SHORT
|
||||
else:
|
||||
return None
|
||||
|
||||
# Strength = |score| * confidence (both in [0, 1])
|
||||
strength = abs(score) * sentiment.avg_confidence
|
||||
strength = min(max(strength, 0.0), 1.0)
|
||||
|
||||
return TradeSignal(
|
||||
ticker=ticker,
|
||||
direction=direction,
|
||||
strength=round(strength, 4),
|
||||
strategy_sources=[self.name],
|
||||
sentiment_context={
|
||||
"avg_score": sentiment.avg_score,
|
||||
"article_count": sentiment.article_count,
|
||||
"avg_confidence": sentiment.avg_confidence,
|
||||
},
|
||||
timestamp=datetime.now(timezone.utc),
|
||||
)
|
||||
Loading…
Add table
Add a link
Reference in a new issue