Dmitry Beresnev
commited on
Commit
Β·
de2e885
1
Parent(s):
e98f030
add a risk management module
Browse files- .env.example +1 -0
- requirements.txt +6 -2
- src/core/risk_management/__init__.py +0 -0
- src/core/risk_management/risk_analyzer.py +376 -0
- src/telegram_bot/config.py +1 -0
- src/telegram_bot/telegram_bot_service.py +186 -9
.env.example
CHANGED
|
@@ -3,6 +3,7 @@ FINNHUB_API_TOKEN=
|
|
| 3 |
SPACE_ID=
|
| 4 |
GEMINI_API_TOKEN=
|
| 5 |
OPENROUTER_API_TOKEN=
|
|
|
|
| 6 |
GOOGLE_APPS_SCRIPT_URL=
|
| 7 |
WEBHOOK_SECRET=
|
| 8 |
SPACE_URL=
|
|
|
|
| 3 |
SPACE_ID=
|
| 4 |
GEMINI_API_TOKEN=
|
| 5 |
OPENROUTER_API_TOKEN=
|
| 6 |
+
OPENROUTER_API_TOKEN_2=
|
| 7 |
GOOGLE_APPS_SCRIPT_URL=
|
| 8 |
WEBHOOK_SECRET=
|
| 9 |
SPACE_URL=
|
requirements.txt
CHANGED
|
@@ -4,9 +4,13 @@ fastapi==0.104.1
|
|
| 4 |
uvicorn[standard]==0.24.0
|
| 5 |
httpx>=0.25.0
|
| 6 |
python-dotenv==1.0.0
|
| 7 |
-
pydantic==2.
|
| 8 |
typing-extensions==4.8.0
|
| 9 |
pytz==2025.2
|
| 10 |
datasets
|
| 11 |
huggingface_hub
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
uvicorn[standard]==0.24.0
|
| 5 |
httpx>=0.25.0
|
| 6 |
python-dotenv==1.0.0
|
| 7 |
+
pydantic==2.11.7
|
| 8 |
typing-extensions==4.8.0
|
| 9 |
pytz==2025.2
|
| 10 |
datasets
|
| 11 |
huggingface_hub
|
| 12 |
+
numpy==1.24.3
|
| 13 |
+
pandas==2.0.3
|
| 14 |
+
yfinance==0.2.65
|
| 15 |
+
google-genai==1.29.0
|
| 16 |
+
TA-Lib==0.6.5
|
src/core/risk_management/__init__.py
ADDED
|
File without changes
|
src/core/risk_management/risk_analyzer.py
ADDED
|
@@ -0,0 +1,376 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from datetime import datetime, timedelta
|
| 2 |
+
import os
|
| 3 |
+
from typing import Any
|
| 4 |
+
import warnings
|
| 5 |
+
import asyncio
|
| 6 |
+
|
| 7 |
+
import yfinance as yf
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
from google import genai
|
| 11 |
+
from google.genai import types
|
| 12 |
+
import talib
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
warnings.filterwarnings('ignore')
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class RiskAnalyzer:
|
| 19 |
+
def __init__(self, gemini_api_key: str):
|
| 20 |
+
self._model_name = 'gemini-2.0-flash-001'
|
| 21 |
+
self.client = genai.Client(
|
| 22 |
+
api_key=gemini_api_key,
|
| 23 |
+
http_options=types.HttpOptions(api_version='v1')
|
| 24 |
+
)
|
| 25 |
+
|
| 26 |
+
def get_stock_data(self, ticker: str, period: str = "3mo") -> pd.DataFrame:
|
| 27 |
+
try:
|
| 28 |
+
stock = yf.Ticker(ticker)
|
| 29 |
+
data = stock.history(period=period)
|
| 30 |
+
return data
|
| 31 |
+
except Exception as e:
|
| 32 |
+
raise Exception(f"Error retrieving data for {ticker}: {str(e)}")
|
| 33 |
+
|
| 34 |
+
def calculate_basic_metrics(self, data: pd.DataFrame) -> dict[str, float]:
|
| 35 |
+
"""
|
| 36 |
+
Calculate basic risk metrics for the stock data.
|
| 37 |
+
|
| 38 |
+
Args:
|
| 39 |
+
data (pd.DataFrame): DataFrame with stock prices including 'Close' column.
|
| 40 |
+
Returns:
|
| 41 |
+
dict[str, float]: Dictionary with calculated risk metrics.
|
| 42 |
+
"""
|
| 43 |
+
prices = data['Close']
|
| 44 |
+
returns = prices.pct_change().dropna()
|
| 45 |
+
|
| 46 |
+
# Calculate basic metrics
|
| 47 |
+
volatility = returns.std() * np.sqrt(252)
|
| 48 |
+
var_5 = np.percentile(returns, 5)
|
| 49 |
+
max_drawdown = self.calculate_max_drawdown(prices)
|
| 50 |
+
sharpe_ratio = self.calculate_sharpe_ratio(returns)
|
| 51 |
+
sortino_ratio = self.calculate_sortino_ratio(returns)
|
| 52 |
+
beta = self.calculate_beta(prices)
|
| 53 |
+
|
| 54 |
+
return {
|
| 55 |
+
'volatility': volatility,
|
| 56 |
+
'var_5': var_5,
|
| 57 |
+
'max_drawdown': max_drawdown,
|
| 58 |
+
'sharpe_ratio': sharpe_ratio,
|
| 59 |
+
'sortino_ratio': sortino_ratio,
|
| 60 |
+
'beta': beta
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
def calculate_technical_indicators(self, data: pd.DataFrame) -> dict[str, Any]:
|
| 64 |
+
"""
|
| 65 |
+
Calculate technical indicators for the stock data.
|
| 66 |
+
|
| 67 |
+
Args:
|
| 68 |
+
data (pd.DataFrame): DataFrame with stock prices including 'High', 'Low', 'Close', and 'Volume' columns.
|
| 69 |
+
Returns:
|
| 70 |
+
dict[str, Any]: Dictionary with calculated technical indicators.
|
| 71 |
+
"""
|
| 72 |
+
high = data['High'].values
|
| 73 |
+
low = data['Low'].values
|
| 74 |
+
close = data['Close'].values
|
| 75 |
+
volume = data['Volume'].values
|
| 76 |
+
|
| 77 |
+
# Calculate moving averages
|
| 78 |
+
ema_20 = talib.EMA(close, timeperiod=20)
|
| 79 |
+
ema_50 = talib.EMA(close, timeperiod=50)
|
| 80 |
+
ema_200 = talib.EMA(close, timeperiod=200)
|
| 81 |
+
|
| 82 |
+
# ATR (Average True Range) is a measure of volatility
|
| 83 |
+
atr = talib.ATR(high, low, close, timeperiod=14)
|
| 84 |
+
|
| 85 |
+
# RSI and Stochastic. RSI (Relative Strength Index) is a momentum oscillator that measures the speed and change of price movements.
|
| 86 |
+
# Stochastic Oscillator is a momentum indicator comparing a particular closing price of a security to a range of its prices over a certain period.
|
| 87 |
+
rsi = talib.RSI(close, timeperiod=14)
|
| 88 |
+
slowk, slowd = talib.STOCH(high, low, close)
|
| 89 |
+
|
| 90 |
+
# Bollinger Bands. Bollinger Bands consist of a middle band (SMA) and two outer bands (standard deviations).
|
| 91 |
+
upper_bb, middle_bb, lower_bb = talib.BBANDS(close)
|
| 92 |
+
|
| 93 |
+
# Volume indicators. On-Balance Volume (OBV) is a cumulative volume-based indicator that uses volume flow to predict changes in stock price.
|
| 94 |
+
obv = talib.OBV(close, volume)
|
| 95 |
+
vol_sma = talib.SMA(volume, timeperiod=20)
|
| 96 |
+
|
| 97 |
+
return {
|
| 98 |
+
'ema_20': ema_20[-1],
|
| 99 |
+
'ema_50': ema_50[-1],
|
| 100 |
+
'ema_200': ema_200[-1],
|
| 101 |
+
'atr': atr[-1],
|
| 102 |
+
'rsi': rsi[-1],
|
| 103 |
+
'stoch_k': slowk[-1],
|
| 104 |
+
'stoch_d': slowd[-1],
|
| 105 |
+
'bb_upper': upper_bb[-1],
|
| 106 |
+
'bb_lower': lower_bb[-1],
|
| 107 |
+
'obv': obv[-1],
|
| 108 |
+
'volume_ratio': volume[-1] / vol_sma[-1] if vol_sma[-1] > 0 else 1,
|
| 109 |
+
'current_price': close[-1]
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
def calculate_position_sizing(self, price: float, atr: float, account_capital: float = 10000,
|
| 113 |
+
risk_pct: float = 0.02, atr_multiplier: float = 2.0) -> dict[str, float]:
|
| 114 |
+
"""
|
| 115 |
+
Calculate position sizing based on ATR and account capital.
|
| 116 |
+
|
| 117 |
+
Args:
|
| 118 |
+
price (float): Current stock price.
|
| 119 |
+
atr (float): Average True Range (ATR) of the stock.
|
| 120 |
+
account_capital (float): Total capital available for trading.
|
| 121 |
+
risk_pct (float): Percentage of capital to risk on a single trade.
|
| 122 |
+
atr_multiplier (float): Multiplier for ATR to determine stop distance.
|
| 123 |
+
Returns:
|
| 124 |
+
dict[str, float]: Dictionary with recommended shares, position value, stop loss price, actual risk in USD and percentage.
|
| 125 |
+
"""
|
| 126 |
+
stop_distance = atr_multiplier * atr
|
| 127 |
+
risk_amount = account_capital * risk_pct
|
| 128 |
+
position_size = risk_amount / stop_distance
|
| 129 |
+
|
| 130 |
+
# Calculate shares and actual position value
|
| 131 |
+
shares = int(position_size / price)
|
| 132 |
+
actual_position_value = shares * price
|
| 133 |
+
actual_risk = shares * stop_distance
|
| 134 |
+
|
| 135 |
+
return {
|
| 136 |
+
'recommended_shares': shares,
|
| 137 |
+
'position_value': actual_position_value,
|
| 138 |
+
'stop_loss_price': price - stop_distance,
|
| 139 |
+
'actual_risk_usd': actual_risk,
|
| 140 |
+
'actual_risk_pct': (actual_risk / account_capital) * 100,
|
| 141 |
+
'atr_stop_distance': stop_distance
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def calculate_risk_reward_levels(self, price: float, atr: float,
|
| 145 |
+
min_rr: float = 2.0) -> dict[str, float]:
|
| 146 |
+
"""
|
| 147 |
+
Calculate risk/reward levels based on ATR and price.
|
| 148 |
+
|
| 149 |
+
Args:
|
| 150 |
+
price (float): Current stock price.
|
| 151 |
+
atr (float): Average True Range (ATR) of the stock.
|
| 152 |
+
min_rr (float): Minimum risk/reward ratio for the first take profit level.
|
| 153 |
+
Returns:
|
| 154 |
+
dict[str, float]: Dictionary with stop loss, take profit levels and risk/reward ratios.
|
| 155 |
+
"""
|
| 156 |
+
stop_distance = 2 * atr
|
| 157 |
+
stop_loss = price - stop_distance
|
| 158 |
+
take_profit_1 = price + (stop_distance * min_rr)
|
| 159 |
+
take_profit_2 = price + (stop_distance * 3.0)
|
| 160 |
+
|
| 161 |
+
return {
|
| 162 |
+
'stop_loss': stop_loss,
|
| 163 |
+
'take_profit_1': take_profit_1,
|
| 164 |
+
'take_profit_2': take_profit_2,
|
| 165 |
+
'risk_reward_1': min_rr,
|
| 166 |
+
'risk_reward_2': 3.0
|
| 167 |
+
}
|
| 168 |
+
|
| 169 |
+
def analyze_trend_context(self, indicators: dict[str, Any]) -> dict[str, Any]:
|
| 170 |
+
"""
|
| 171 |
+
Analyze the trend context based on technical indicators.
|
| 172 |
+
|
| 173 |
+
Args:
|
| 174 |
+
indicators (dict[str, Any]): Dictionary with technical indicators including current price, EMAs, and Bollinger Bands.
|
| 175 |
+
Returns:
|
| 176 |
+
dict[str, Any]: Dictionary with trend analysis and Bollinger Bands position.
|
| 177 |
+
"""
|
| 178 |
+
price = indicators['current_price']
|
| 179 |
+
ema20 = indicators['ema_20']
|
| 180 |
+
ema50 = indicators['ema_50']
|
| 181 |
+
ema200 = indicators['ema_200']
|
| 182 |
+
|
| 183 |
+
# Determine trend based on EMAs
|
| 184 |
+
if price > ema20 > ema50 > ema200:
|
| 185 |
+
trend = "Strong uptrend"
|
| 186 |
+
elif price > ema20 > ema50:
|
| 187 |
+
trend = "Uptrend"
|
| 188 |
+
elif price < ema20 < ema50 < ema200:
|
| 189 |
+
trend = "Strong downtrend"
|
| 190 |
+
elif price < ema20 < ema50:
|
| 191 |
+
trend = "Downtrend"
|
| 192 |
+
else:
|
| 193 |
+
trend = "Sideways"
|
| 194 |
+
|
| 195 |
+
# Position in Bollinger Bands
|
| 196 |
+
bb_position = "Middle"
|
| 197 |
+
if price > indicators['bb_upper']:
|
| 198 |
+
bb_position = "Above upper band"
|
| 199 |
+
elif price < indicators['bb_lower']:
|
| 200 |
+
bb_position = "Below lower band"
|
| 201 |
+
|
| 202 |
+
return {
|
| 203 |
+
'trend': trend,
|
| 204 |
+
'bb_position': bb_position,
|
| 205 |
+
'price_vs_ema20': ((price / ema20) - 1) * 100,
|
| 206 |
+
'ema20_vs_ema50': ((ema20 / ema50) - 1) * 100
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
def calculate_max_drawdown(self, prices: pd.Series) -> float:
|
| 210 |
+
"""
|
| 211 |
+
Calculate the maximum drawdown of a stock's price series.
|
| 212 |
+
|
| 213 |
+
Args:
|
| 214 |
+
prices (pd.Series): Series of stock prices.
|
| 215 |
+
Returns:
|
| 216 |
+
float: Maximum drawdown as a percentage.
|
| 217 |
+
"""
|
| 218 |
+
cumulative = (1 + prices.pct_change()).cumprod()
|
| 219 |
+
running_max = cumulative.expanding().max()
|
| 220 |
+
drawdown = (cumulative - running_max) / running_max
|
| 221 |
+
return drawdown.min()
|
| 222 |
+
|
| 223 |
+
def calculate_sharpe_ratio(self, returns: pd.Series, risk_free_rate: float = 0.02) -> float:
|
| 224 |
+
"""
|
| 225 |
+
Calculate the Sharpe ratio of a stock's returns.
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
returns (pd.Series): Series of stock returns.
|
| 229 |
+
risk_free_rate (float): Risk-free rate, default is 2%.
|
| 230 |
+
Returns:
|
| 231 |
+
float: Sharpe ratio.
|
| 232 |
+
"""
|
| 233 |
+
excess_returns = returns.mean() * 252 - risk_free_rate
|
| 234 |
+
volatility = returns.std() * np.sqrt(252)
|
| 235 |
+
return excess_returns / volatility if volatility != 0 else 0
|
| 236 |
+
|
| 237 |
+
def calculate_sortino_ratio(self, returns: pd.Series, risk_free_rate: float = 0.02) -> float:
|
| 238 |
+
"""
|
| 239 |
+
Calculate the Sortino ratio of a stock's returns.
|
| 240 |
+
Args:
|
| 241 |
+
returns (pd.Series): Series of stock returns.
|
| 242 |
+
risk_free_rate (float): Risk-free rate, default is 2%.
|
| 243 |
+
Returns:
|
| 244 |
+
float: Sortino ratio.
|
| 245 |
+
"""
|
| 246 |
+
excess_returns = returns.mean() * 252 - risk_free_rate
|
| 247 |
+
downside_returns = returns[returns < 0]
|
| 248 |
+
downside_deviation = downside_returns.std() * np.sqrt(252)
|
| 249 |
+
return excess_returns / downside_deviation if downside_deviation != 0 else 0
|
| 250 |
+
|
| 251 |
+
def calculate_beta(self, stock_prices: pd.Series, market_ticker: str = "^GSPC") -> float:
|
| 252 |
+
"""
|
| 253 |
+
Calculate the beta of a stock relative to a market index.
|
| 254 |
+
|
| 255 |
+
Args:
|
| 256 |
+
stock_prices (pd.Series): Series of stock prices.
|
| 257 |
+
market_ticker (str): Ticker symbol of the market index (default is S&P 500).
|
| 258 |
+
Returns:
|
| 259 |
+
float: Beta value of the stock.
|
| 260 |
+
"""
|
| 261 |
+
try:
|
| 262 |
+
market_data = yf.Ticker(market_ticker).history(period="1y")
|
| 263 |
+
stock_returns = stock_prices.pct_change().dropna()
|
| 264 |
+
market_returns = market_data['Close'].pct_change().dropna()
|
| 265 |
+
|
| 266 |
+
common_dates = stock_returns.index.intersection(market_returns.index)
|
| 267 |
+
stock_returns_aligned = stock_returns.loc[common_dates]
|
| 268 |
+
market_returns_aligned = market_returns.loc[common_dates]
|
| 269 |
+
|
| 270 |
+
covariance = np.cov(stock_returns_aligned, market_returns_aligned)[0][1]
|
| 271 |
+
market_variance = np.var(market_returns_aligned)
|
| 272 |
+
|
| 273 |
+
return covariance / market_variance if market_variance != 0 else 1
|
| 274 |
+
except:
|
| 275 |
+
return 1.0
|
| 276 |
+
|
| 277 |
+
def analyze_risks(self, ticker: str, account_capital: float = 10000) -> dict[str, Any]:
|
| 278 |
+
"""
|
| 279 |
+
Analyze risks for a given stock ticker and account capital.
|
| 280 |
+
|
| 281 |
+
Args:
|
| 282 |
+
ticker (str): Stock ticker symbol.
|
| 283 |
+
account_capital (float): Total capital available for trading, default is $10,000.
|
| 284 |
+
Returns:
|
| 285 |
+
Dict[str, Any]: Dictionary with analysis results including current price, price change, basic metrics,
|
| 286 |
+
technical indicators, trend analysis, position sizing, and risk/reward levels.
|
| 287 |
+
"""
|
| 288 |
+
try:
|
| 289 |
+
data = self.get_stock_data(ticker)
|
| 290 |
+
basic_metrics = self.calculate_basic_metrics(data)
|
| 291 |
+
technical_indicators = self.calculate_technical_indicators(data)
|
| 292 |
+
trend_analysis = self.analyze_trend_context(technical_indicators)
|
| 293 |
+
position_sizing = self.calculate_position_sizing(
|
| 294 |
+
technical_indicators['current_price'],
|
| 295 |
+
technical_indicators['atr'],
|
| 296 |
+
account_capital
|
| 297 |
+
)
|
| 298 |
+
risk_reward = self.calculate_risk_reward_levels(
|
| 299 |
+
technical_indicators['current_price'],
|
| 300 |
+
technical_indicators['atr']
|
| 301 |
+
)
|
| 302 |
+
current_price = technical_indicators['current_price']
|
| 303 |
+
prev_price = data['Close'].iloc[-2]
|
| 304 |
+
price_change = (current_price - prev_price) / prev_price * 100
|
| 305 |
+
|
| 306 |
+
return {
|
| 307 |
+
'ticker': ticker.upper(),
|
| 308 |
+
'success': True,
|
| 309 |
+
'current_price': current_price,
|
| 310 |
+
'price_change_pct': price_change,
|
| 311 |
+
'basic_metrics': basic_metrics,
|
| 312 |
+
'technical_indicators': technical_indicators,
|
| 313 |
+
'trend_analysis': trend_analysis,
|
| 314 |
+
'position_sizing': position_sizing,
|
| 315 |
+
'risk_reward': risk_reward
|
| 316 |
+
}
|
| 317 |
+
|
| 318 |
+
except Exception as e:
|
| 319 |
+
return {'success': False, 'error': str(e)}
|
| 320 |
+
|
| 321 |
+
async def generate_explanation(self, risk_data: dict[str, Any]) -> str:
|
| 322 |
+
"""
|
| 323 |
+
Generate a comprehensive risk management analysis explanation in Russian based on the provided risk data.
|
| 324 |
+
|
| 325 |
+
Args:
|
| 326 |
+
risk_data (dict[str, Any]): Dictionary containing risk analysis data including ticker, current price,
|
| 327 |
+
basic metrics, technical indicators, trend analysis, position sizing, and risk/reward levels.
|
| 328 |
+
"""
|
| 329 |
+
basic = risk_data['basic_metrics']
|
| 330 |
+
tech = risk_data['technical_indicators']
|
| 331 |
+
trend = risk_data['trend_analysis']
|
| 332 |
+
position = risk_data['position_sizing']
|
| 333 |
+
rr = risk_data['risk_reward']
|
| 334 |
+
|
| 335 |
+
prompt = f"""
|
| 336 |
+
Analyze the comprehensive risk management picture for the stock {risk_data['ticker']} in English.
|
| 337 |
+
|
| 338 |
+
Price: ${risk_data['current_price']:.2f} ({risk_data['price_change_pct']:+.2f}%)
|
| 339 |
+
|
| 340 |
+
RISK METRICS:
|
| 341 |
+
- Volatility: {basic['volatility'] * 100:.1f}%
|
| 342 |
+
- Sharpe: {basic['sharpe_ratio']:.2f}
|
| 343 |
+
- Sortino: {basic['sortino_ratio']:.2f}
|
| 344 |
+
- Max drawdown: {basic['max_drawdown'] * 100:.1f}%
|
| 345 |
+
- Beta: {basic['beta']:.2f}
|
| 346 |
+
|
| 347 |
+
TECHNICAL ANALYSIS:
|
| 348 |
+
- Trend: {trend['trend']}
|
| 349 |
+
- RSI: {tech['rsi']:.1f}
|
| 350 |
+
- ATR: ${tech['atr']:.2f}
|
| 351 |
+
- BB Position: {trend['bb_position']}
|
| 352 |
+
- Volume: {tech['volume_ratio']:.1f}x of average
|
| 353 |
+
|
| 354 |
+
TRADING PLAN:
|
| 355 |
+
- Recommended size: {position['recommended_shares']} shares (${position['position_value']:.0f})
|
| 356 |
+
- Stop-loss: ${position['stop_loss_price']:.2f}
|
| 357 |
+
- Take-profit 1: ${rr['take_profit_1']:.2f} (R/R 2:1)
|
| 358 |
+
- Risk: ${position['actual_risk_usd']:.0f} ({position['actual_risk_pct']:.1f}%)
|
| 359 |
+
|
| 360 |
+
Give a brief assessment:
|
| 361 |
+
1. Overall risk level (low/medium/high)
|
| 362 |
+
2. Is it a good time to enter now
|
| 363 |
+
3. What to pay attention to
|
| 364 |
+
|
| 365 |
+
Maximum 200 words, concise and to the point.
|
| 366 |
+
"""
|
| 367 |
+
|
| 368 |
+
try:
|
| 369 |
+
response = await asyncio.to_thread(
|
| 370 |
+
self.client.models.generate_content,
|
| 371 |
+
model=self._model_name,
|
| 372 |
+
contents=prompt
|
| 373 |
+
)
|
| 374 |
+
return response.text
|
| 375 |
+
except Exception as e:
|
| 376 |
+
return f"Failed to generate explanation: {str(e)}"
|
src/telegram_bot/config.py
CHANGED
|
@@ -15,6 +15,7 @@ class Config:
|
|
| 15 |
HF_TOKEN = os.getenv('HF_TOKEN', '')
|
| 16 |
HF_DATASET_REPO = os.getenv('HF_DATASET_REPO', '')
|
| 17 |
OPENROUTER_API_KEY_2 = os.getenv('OPENROUTER_API_TOKEN_2', '')
|
|
|
|
| 18 |
|
| 19 |
@classmethod
|
| 20 |
def validate(cls) -> bool:
|
|
|
|
| 15 |
HF_TOKEN = os.getenv('HF_TOKEN', '')
|
| 16 |
HF_DATASET_REPO = os.getenv('HF_DATASET_REPO', '')
|
| 17 |
OPENROUTER_API_KEY_2 = os.getenv('OPENROUTER_API_TOKEN_2', '')
|
| 18 |
+
GEMINI_API_KEY = os.getenv('GEMINI_API_TOKEN', '')
|
| 19 |
|
| 20 |
@classmethod
|
| 21 |
def validate(cls) -> bool:
|
src/telegram_bot/telegram_bot_service.py
CHANGED
|
@@ -15,6 +15,7 @@ from src.api.finnhub.financial_news_requester import fetch_comp_financial_news
|
|
| 15 |
from src.api.openrouter.openrouter_client import OpenRouterClient
|
| 16 |
from src.api.openrouter.prompt_generator import PromptGenerator
|
| 17 |
from src.services.news_pooling_service import NewsPollingService
|
|
|
|
| 18 |
|
| 19 |
|
| 20 |
class TelegramBotService:
|
|
@@ -125,9 +126,10 @@ class TelegramBotService:
|
|
| 125 |
|
| 126 |
async def _handle_command(self, chat_id: int, command: str, user_name: str) -> None:
|
| 127 |
"""Handle bot commands"""
|
| 128 |
-
|
|
|
|
| 129 |
|
| 130 |
-
if
|
| 131 |
response = f"π Hello, {user_name}! Welcome to the Financial News Bot!\n\n"
|
| 132 |
response += "Available commands:\n"
|
| 133 |
response += "/hello - Say hello\n"
|
|
@@ -135,9 +137,12 @@ class TelegramBotService:
|
|
| 135 |
response += "/status - Check bot status\n"
|
| 136 |
response += "/news - Show all today's news\n"
|
| 137 |
response += "/run - News feed analysis by ticker (NVDA)\n\n"
|
| 138 |
-
response += "/pooling - News feed pooling by ticker (NVDA)\n\n"
|
|
|
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
elif
|
| 141 |
response = "π€ <b>Financial News Bot Help</b>\n\n"
|
| 142 |
response += "<b>Commands:</b>\n"
|
| 143 |
response += "/start or /hello - Get started\n"
|
|
@@ -145,27 +150,41 @@ class TelegramBotService:
|
|
| 145 |
response += "/status - Check bot status\n\n"
|
| 146 |
response += "<b>About:</b>\n"
|
| 147 |
response += "This bot provides financial news and sentiment analysis."
|
| 148 |
-
|
| 149 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
response = "β
<b>Bot Status: Online</b>\n\n"
|
| 151 |
response += "π§ System: Running on HuggingFace Spaces\n"
|
| 152 |
response += "π Proxy: Google Apps Script\n"
|
| 153 |
response += "π Status: All systems operational"
|
| 154 |
|
| 155 |
-
elif
|
| 156 |
await self.news_feed_analysing(chat_id, command, user_name)
|
| 157 |
return
|
| 158 |
|
| 159 |
-
elif
|
| 160 |
await self.news_feed_analysing_by_ticker(ticker="NVDA", chat_id=chat_id,
|
| 161 |
text=None, user_name=user_name)
|
| 162 |
return
|
| 163 |
|
| 164 |
-
elif
|
| 165 |
await self.news_feed_pooling_by_ticker(ticker="NVDA", chat_id=chat_id,
|
| 166 |
text=None, user_name=user_name)
|
| 167 |
return
|
| 168 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 169 |
else:
|
| 170 |
response = f"β Unknown command: {command}\n\n"
|
| 171 |
response += "Type /help to see available commands."
|
|
@@ -293,3 +312,161 @@ class TelegramBotService:
|
|
| 293 |
except Exception as e:
|
| 294 |
main_logger.error(f"Error in news_feed_analysing_by_ticker: {e}")
|
| 295 |
await self.send_message_via_proxy(chat_id, f"Sorry, there was an error fetching news: {str(e)}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
from src.api.openrouter.openrouter_client import OpenRouterClient
|
| 16 |
from src.api.openrouter.prompt_generator import PromptGenerator
|
| 17 |
from src.services.news_pooling_service import NewsPollingService
|
| 18 |
+
from src.core.risk_management.risk_analyzer import RiskAnalyzer
|
| 19 |
|
| 20 |
|
| 21 |
class TelegramBotService:
|
|
|
|
| 126 |
|
| 127 |
async def _handle_command(self, chat_id: int, command: str, user_name: str) -> None:
|
| 128 |
"""Handle bot commands"""
|
| 129 |
+
command_parts = command.lower().strip().split()
|
| 130 |
+
base_command = command_parts[0]
|
| 131 |
|
| 132 |
+
if base_command in ["/start", "/hello"]:
|
| 133 |
response = f"π Hello, {user_name}! Welcome to the Financial News Bot!\n\n"
|
| 134 |
response += "Available commands:\n"
|
| 135 |
response += "/hello - Say hello\n"
|
|
|
|
| 137 |
response += "/status - Check bot status\n"
|
| 138 |
response += "/news - Show all today's news\n"
|
| 139 |
response += "/run - News feed analysis by ticker (NVDA)\n\n"
|
| 140 |
+
response += "/pooling - News feed pooling by ticker (NVDA) π§ͺ (not working properly, testing)\n\n"
|
| 141 |
+
response += "π <b>Risk Analysis Commands:</b> π§ͺ (testing)\n"
|
| 142 |
+
response += "/risk TICKER - Full risk analysis (e.g., /risk AAPL)\n"
|
| 143 |
+
response += "/risk TICKER 25000 - Risk analysis with custom capital\n"
|
| 144 |
|
| 145 |
+
elif base_command == "/help":
|
| 146 |
response = "π€ <b>Financial News Bot Help</b>\n\n"
|
| 147 |
response += "<b>Commands:</b>\n"
|
| 148 |
response += "/start or /hello - Get started\n"
|
|
|
|
| 150 |
response += "/status - Check bot status\n\n"
|
| 151 |
response += "<b>About:</b>\n"
|
| 152 |
response += "This bot provides financial news and sentiment analysis."
|
| 153 |
+
response += "<b>Risk Analysis Commands:</b>\n"
|
| 154 |
+
response += "/risk TICKER - Complete risk analysis\n"
|
| 155 |
+
response += "/risk AAPL - Apple analysis with $10,000 capital\n"
|
| 156 |
+
response += "/risk TSLA 50000 - Tesla analysis with $50,000 capital\n\n"
|
| 157 |
+
response += "<b>What Risk Analysis Includes:</b>\n"
|
| 158 |
+
response += "π Risk metrics (volatility, Sharpe, Sortino)\n"
|
| 159 |
+
response += "π Technical indicators (RSI, ATR, EMA, Bollinger)\n"
|
| 160 |
+
response += "π° Position sizing and trade plan\n"
|
| 161 |
+
response += "π― Stop-loss and take-profit levels\n"
|
| 162 |
+
response += "π€ AI-powered trading insights\n"
|
| 163 |
+
|
| 164 |
+
elif base_command == "/status":
|
| 165 |
response = "β
<b>Bot Status: Online</b>\n\n"
|
| 166 |
response += "π§ System: Running on HuggingFace Spaces\n"
|
| 167 |
response += "π Proxy: Google Apps Script\n"
|
| 168 |
response += "π Status: All systems operational"
|
| 169 |
|
| 170 |
+
elif base_command == "/news":
|
| 171 |
await self.news_feed_analysing(chat_id, command, user_name)
|
| 172 |
return
|
| 173 |
|
| 174 |
+
elif base_command == "/run":
|
| 175 |
await self.news_feed_analysing_by_ticker(ticker="NVDA", chat_id=chat_id,
|
| 176 |
text=None, user_name=user_name)
|
| 177 |
return
|
| 178 |
|
| 179 |
+
elif base_command == "/pooling":
|
| 180 |
await self.news_feed_pooling_by_ticker(ticker="NVDA", chat_id=chat_id,
|
| 181 |
text=None, user_name=user_name)
|
| 182 |
return
|
| 183 |
|
| 184 |
+
elif base_command == "/risk":
|
| 185 |
+
await self._handle_risk_command(chat_id, command_parts, user_name)
|
| 186 |
+
return
|
| 187 |
+
|
| 188 |
else:
|
| 189 |
response = f"β Unknown command: {command}\n\n"
|
| 190 |
response += "Type /help to see available commands."
|
|
|
|
| 312 |
except Exception as e:
|
| 313 |
main_logger.error(f"Error in news_feed_analysing_by_ticker: {e}")
|
| 314 |
await self.send_message_via_proxy(chat_id, f"Sorry, there was an error fetching news: {str(e)}")
|
| 315 |
+
|
| 316 |
+
async def get_risk_analysis(
|
| 317 |
+
self, ticker: str, chat_id: int, text: str | None, user_name: str
|
| 318 |
+
) -> None:
|
| 319 |
+
await self.send_message_via_proxy(chat_id, f"Fetching latest financial data for ticker {ticker} ...")
|
| 320 |
+
analyzer = RiskAnalyzer(self.config.GEMINI_API_KEY)
|
| 321 |
+
try:
|
| 322 |
+
risk_analysis = await analyzer.analyze_risk(ticker)
|
| 323 |
+
if risk_analysis:
|
| 324 |
+
response = f"Risk analysis for {ticker}:\n\n{risk_analysis}"
|
| 325 |
+
else:
|
| 326 |
+
response = f"No risk analysis available for {ticker}."
|
| 327 |
+
except Exception as e:
|
| 328 |
+
main_logger.error(f"Error in get_risk_analysis: {e}")
|
| 329 |
+
response = f"Sorry, there was an error fetching risk analysis: {str(e)}"
|
| 330 |
+
await self.send_message_via_proxy(chat_id, response)
|
| 331 |
+
|
| 332 |
+
async def _handle_risk_command(self, chat_id: int, command_parts: list[str],
|
| 333 |
+
user_name: str) -> None:
|
| 334 |
+
"""Handle risk analysis command"""
|
| 335 |
+
try:
|
| 336 |
+
risk_analyzer = RiskAnalyzer(self.config.GEMINI_API_KEY)
|
| 337 |
+
if not risk_analyzer:
|
| 338 |
+
await self.send_message_via_proxy(
|
| 339 |
+
chat_id,
|
| 340 |
+
"β Risk analysis is currently unavailable. Please try again later."
|
| 341 |
+
)
|
| 342 |
+
return
|
| 343 |
+
if len(command_parts) < 2:
|
| 344 |
+
await self.send_message_via_proxy(
|
| 345 |
+
chat_id,
|
| 346 |
+
"β Please specify a ticker: /risk AAPL [capital]\n\n"
|
| 347 |
+
"Examples:\nβ’ /risk AAPL\nβ’ /risk TSLA 25000"
|
| 348 |
+
)
|
| 349 |
+
return
|
| 350 |
+
ticker = command_parts[1].upper()
|
| 351 |
+
await self.send_message_via_proxy(chat_id, f"Fetching latest financial data for ticker {ticker} ...")
|
| 352 |
+
try:
|
| 353 |
+
capital = float(command_parts[2]) if len(command_parts) > 2 else 10000
|
| 354 |
+
except (ValueError, IndexError):
|
| 355 |
+
capital = 10000
|
| 356 |
+
|
| 357 |
+
if capital < 1000:
|
| 358 |
+
await self.send_message_via_proxy(
|
| 359 |
+
chat_id,
|
| 360 |
+
"β Minimum capital is $1,000"
|
| 361 |
+
)
|
| 362 |
+
return
|
| 363 |
+
|
| 364 |
+
# Send loading message
|
| 365 |
+
loading_message = f"β³ Analyzing {ticker} with ${capital:,.0f} capital...\n\n"
|
| 366 |
+
loading_message += "π Fetching market data...\n"
|
| 367 |
+
loading_message += "π’ Calculating risk metrics...\n"
|
| 368 |
+
loading_message += "π Analyzing technical indicators...\n"
|
| 369 |
+
loading_message += "πΌ Generating trade plan..."
|
| 370 |
+
|
| 371 |
+
await self.send_message_via_proxy(chat_id, loading_message)
|
| 372 |
+
|
| 373 |
+
# Perform analysis
|
| 374 |
+
risk_data = await risk_analyzer.analyze_risks(ticker, capital)
|
| 375 |
+
|
| 376 |
+
if not risk_data['success']:
|
| 377 |
+
await self.send_message_via_proxy(
|
| 378 |
+
chat_id,
|
| 379 |
+
f"β Analysis failed for {ticker}: {risk_data['error']}"
|
| 380 |
+
)
|
| 381 |
+
return
|
| 382 |
+
# Format and send main results
|
| 383 |
+
result_text = self._format_risk_analysis_results(risk_data)
|
| 384 |
+
await self.send_message_via_proxy(chat_id, result_text)
|
| 385 |
+
|
| 386 |
+
# Generate and send AI explanation
|
| 387 |
+
ai_loading = "π€ Generating AI analysis..."
|
| 388 |
+
await self.send_message_via_proxy(chat_id, ai_loading)
|
| 389 |
+
|
| 390 |
+
explanation = await risk_analyzer.generate_explanation(risk_data)
|
| 391 |
+
ai_response = f"π€ <b>AI Trading Analysis:</b>\n\n{explanation}"
|
| 392 |
+
|
| 393 |
+
await self.send_message_via_proxy(chat_id, ai_response)
|
| 394 |
+
|
| 395 |
+
except Exception as e:
|
| 396 |
+
main_logger.error(f"Error in risk command handler: {e}")
|
| 397 |
+
await self.send_message_via_proxy(
|
| 398 |
+
chat_id,
|
| 399 |
+
f"β An error occurred during analysis: {str(e)}"
|
| 400 |
+
)
|
| 401 |
+
|
| 402 |
+
def _format_risk_analysis_results(self, data: dict[str, Any]) -> str:
|
| 403 |
+
"""Format comprehensive risk analysis results"""
|
| 404 |
+
try:
|
| 405 |
+
basic = data['basic_metrics']
|
| 406 |
+
tech = data['technical_indicators']
|
| 407 |
+
trend = data['trend_analysis']
|
| 408 |
+
position = data['position_sizing']
|
| 409 |
+
rr = data['risk_reward']
|
| 410 |
+
|
| 411 |
+
change_emoji = "π" if data['price_change_pct'] >= 0 else "π"
|
| 412 |
+
|
| 413 |
+
# RSI signals
|
| 414 |
+
rsi_value = tech['rsi']
|
| 415 |
+
if rsi_value > 70:
|
| 416 |
+
rsi_emoji = "π΄"
|
| 417 |
+
rsi_signal = "Overbought"
|
| 418 |
+
elif rsi_value < 30:
|
| 419 |
+
rsi_emoji = "π’"
|
| 420 |
+
rsi_signal = "Oversold"
|
| 421 |
+
else:
|
| 422 |
+
rsi_emoji = "π‘"
|
| 423 |
+
rsi_signal = "Neutral"
|
| 424 |
+
|
| 425 |
+
# Volume signal
|
| 426 |
+
vol_emoji = "π₯" if tech['volume_ratio'] > 1.5 else "π"
|
| 427 |
+
|
| 428 |
+
# Risk level based on volatility
|
| 429 |
+
vol_pct = basic['volatility'] * 100
|
| 430 |
+
if vol_pct < 20:
|
| 431 |
+
risk_level = "π’ Low"
|
| 432 |
+
elif vol_pct < 40:
|
| 433 |
+
risk_level = "π‘ Medium"
|
| 434 |
+
else:
|
| 435 |
+
risk_level = "π΄ High"
|
| 436 |
+
|
| 437 |
+
return f"""
|
| 438 |
+
π <b>Risk Analysis: {data['ticker']}</b>
|
| 439 |
+
|
| 440 |
+
π° <b>Current Price:</b> ${data['current_price']:.2f} ({data['price_change_pct']:+.2f}%) {change_emoji}
|
| 441 |
+
|
| 442 |
+
π― <b>Risk Metrics:</b>
|
| 443 |
+
β’ Volatility: {vol_pct:.1f}% ({risk_level})
|
| 444 |
+
β’ Sharpe Ratio: {basic['sharpe_ratio']:.2f}
|
| 445 |
+
β’ Sortino Ratio: {basic['sortino_ratio']:.2f}
|
| 446 |
+
β’ VaR (5%): {basic['var_5'] * 100:.1f}%
|
| 447 |
+
β’ Max Drawdown: {basic['max_drawdown'] * 100:.1f}%
|
| 448 |
+
β’ Beta: {basic['beta']:.2f}
|
| 449 |
+
|
| 450 |
+
π <b>Technical Analysis:</b>
|
| 451 |
+
β’ Trend: <b>{trend['trend']}</b>
|
| 452 |
+
β’ RSI: {rsi_value:.0f} {rsi_emoji} ({rsi_signal})
|
| 453 |
+
β’ ATR: ${tech['atr']:.2f}
|
| 454 |
+
β’ Volume: {tech['volume_ratio']:.1f}x avg {vol_emoji}
|
| 455 |
+
β’ BB Position: {trend['bb_position']}
|
| 456 |
+
|
| 457 |
+
πΌ <b>Trading Plan:</b>
|
| 458 |
+
β’ Position Size: <b>{position['recommended_shares']} shares</b>
|
| 459 |
+
β’ Investment: ${position['position_value']:,.0f}
|
| 460 |
+
β’ Stop Loss: ${position['stop_loss_price']:.2f}
|
| 461 |
+
β’ Take Profit 1: ${rr['take_profit_1']:.2f} (R/R 2:1)
|
| 462 |
+
β’ Take Profit 2: ${rr['take_profit_2']:.2f} (R/R 3:1)
|
| 463 |
+
β’ Risk Amount: ${position['actual_risk_usd']:.0f} ({position['actual_risk_pct']:.1f}%)
|
| 464 |
+
|
| 465 |
+
π <b>Moving Averages:</b>
|
| 466 |
+
β’ EMA 20: ${tech['ema_20']:.2f}
|
| 467 |
+
β’ EMA 50: ${tech['ema_50']:.2f}
|
| 468 |
+
β’ EMA 200: ${tech['ema_200']:.2f}
|
| 469 |
+
"""
|
| 470 |
+
except Exception as e:
|
| 471 |
+
main_logger.error(f"Error formatting risk results: {e}")
|
| 472 |
+
return f"β Error formatting analysis results: {str(e)}"
|