Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -82,13 +82,10 @@ def parse_market_data(text):
|
|
| 82 |
return None
|
| 83 |
|
| 84 |
def analyze_sentiment_with_bert(market_data):
|
| 85 |
-
"""Analisa o sentimento usando o sistema de IA BERT"""
|
| 86 |
if not TRANSFORMERS_AVAILABLE or not trading_bot or not hasattr(trading_bot, 'hf_api'):
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
'confidence': 0.5,
|
| 90 |
-
'label': 'NEUTRO'
|
| 91 |
-
}
|
| 92 |
|
| 93 |
try:
|
| 94 |
# Preparar dados para análise de IA
|
|
@@ -114,6 +111,12 @@ def analyze_sentiment_with_bert(market_data):
|
|
| 114 |
# Parse da resposta
|
| 115 |
ai_sentiment, ai_confidence, ai_analysis = trading_bot.hf_api.parse_ai_response(ai_response)
|
| 116 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
# Mapear para o formato esperado
|
| 118 |
sentiment_mapping = {
|
| 119 |
'BULLISH': 'POSITIVO',
|
|
@@ -135,20 +138,120 @@ def analyze_sentiment_with_bert(market_data):
|
|
| 135 |
'analysis': ai_analysis
|
| 136 |
}
|
| 137 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
return {
|
| 139 |
-
'sentiment':
|
| 140 |
-
'confidence':
|
| 141 |
-
'label':
|
| 142 |
-
'analysis': 'Análise
|
|
|
|
|
|
|
| 143 |
}
|
| 144 |
|
| 145 |
except Exception as e:
|
| 146 |
-
print(f"Erro na análise
|
| 147 |
return {
|
| 148 |
'sentiment': 'neutral',
|
| 149 |
'confidence': 0.5,
|
| 150 |
'label': 'NEUTRO',
|
| 151 |
-
'analysis': f'Erro na análise: {e}'
|
|
|
|
|
|
|
| 152 |
}
|
| 153 |
|
| 154 |
def analyze_scalping_signals(market_data, original_text=""):
|
|
@@ -793,7 +896,7 @@ with gr.Blocks(css=custom_css, title="🤖 Serviço de Análise BERT - BotCS", t
|
|
| 793 |
<div class="row">
|
| 794 |
<div class="col-12">
|
| 795 |
<p class="lead text-light mb-3 text-center" style="color: #ffffff !important;">
|
| 796 |
-
<strong style="color: #ffffff !important;">Insira os indicadores técnicos
|
| 797 |
</p>
|
| 798 |
</div>
|
| 799 |
</div>
|
|
@@ -815,7 +918,7 @@ with gr.Blocks(css=custom_css, title="🤖 Serviço de Análise BERT - BotCS", t
|
|
| 815 |
<div class="col-12 col-md-6">
|
| 816 |
<div class="d-flex align-items-center mb-2">
|
| 817 |
<span class="badge bg-success me-2">✅</span>
|
| 818 |
-
<span class="text-light" style="color: #ffffff !important;"><strong style="color: #ffffff !important;">Análise de sentimento FinBERT</strong>
|
| 819 |
</div>
|
| 820 |
<div class="d-flex align-items-center mb-2">
|
| 821 |
<span class="badge bg-success me-2">✅</span>
|
|
@@ -833,6 +936,7 @@ with gr.Blocks(css=custom_css, title="🤖 Serviço de Análise BERT - BotCS", t
|
|
| 833 |
<span class="badge bg-primary me-1">Volume</span>
|
| 834 |
<span class="badge bg-primary me-1">Momentum</span>
|
| 835 |
<span class="badge bg-success">🤖 FinBERT AI</span>
|
|
|
|
| 836 |
</p>
|
| 837 |
</div>
|
| 838 |
</div>
|
|
|
|
| 82 |
return None
|
| 83 |
|
| 84 |
def analyze_sentiment_with_bert(market_data):
|
| 85 |
+
"""Analisa o sentimento usando o sistema de IA BERT com fallback robusto"""
|
| 86 |
if not TRANSFORMERS_AVAILABLE or not trading_bot or not hasattr(trading_bot, 'hf_api'):
|
| 87 |
+
print("⚠️ BERT não disponível - usando sistema robusto")
|
| 88 |
+
return analyze_sentiment_robust(market_data)
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
try:
|
| 91 |
# Preparar dados para análise de IA
|
|
|
|
| 111 |
# Parse da resposta
|
| 112 |
ai_sentiment, ai_confidence, ai_analysis = trading_bot.hf_api.parse_ai_response(ai_response)
|
| 113 |
|
| 114 |
+
# Verificar se o BERT retornou dados estáticos (problema conhecido)
|
| 115 |
+
if ("$0.00" in ai_analysis or "RSI: 50" in ai_analysis or
|
| 116 |
+
"0.00%" in ai_analysis or "Volume: 0.0x" in ai_analysis):
|
| 117 |
+
print("⚠️ BERT retornou dados estáticos - usando sistema robusto")
|
| 118 |
+
return analyze_sentiment_robust(market_data)
|
| 119 |
+
|
| 120 |
# Mapear para o formato esperado
|
| 121 |
sentiment_mapping = {
|
| 122 |
'BULLISH': 'POSITIVO',
|
|
|
|
| 138 |
'analysis': ai_analysis
|
| 139 |
}
|
| 140 |
|
| 141 |
+
print("⚠️ BERT não respondeu - usando sistema robusto")
|
| 142 |
+
return analyze_sentiment_robust(market_data)
|
| 143 |
+
|
| 144 |
+
except Exception as e:
|
| 145 |
+
print(f"⚠️ Erro na análise BERT: {e} - usando sistema robusto")
|
| 146 |
+
return analyze_sentiment_robust(market_data)
|
| 147 |
+
|
| 148 |
+
def analyze_sentiment_robust(market_data):
|
| 149 |
+
"""Sistema de análise robusto que funciona quando o BERT falha"""
|
| 150 |
+
try:
|
| 151 |
+
# Extrair dados
|
| 152 |
+
price = market_data.get('price', 0)
|
| 153 |
+
rsi = market_data.get('rsi', 50)
|
| 154 |
+
ema_trend = market_data.get('ema_trend', 'NEUTRO')
|
| 155 |
+
volume_ratio = market_data.get('volume', 1.0)
|
| 156 |
+
price_change_pct = market_data.get('variation', 0)
|
| 157 |
+
symbol = market_data.get('symbol', 'BTCUSD')
|
| 158 |
+
|
| 159 |
+
print(f"📊 Análise Robusta {symbol}: Preço={price}, RSI={rsi}, Trend={ema_trend}")
|
| 160 |
+
|
| 161 |
+
# Análise de sentimento baseada em indicadores
|
| 162 |
+
sentiment_score = 0
|
| 163 |
+
confidence_score = 0
|
| 164 |
+
signals = []
|
| 165 |
+
|
| 166 |
+
# === ANÁLISE RSI ===
|
| 167 |
+
if rsi <= 30:
|
| 168 |
+
sentiment_score += 30 # Muito bullish
|
| 169 |
+
confidence_score += 25
|
| 170 |
+
signals.append(f"RSI {rsi} - Zona de sobrevenda (COMPRA)")
|
| 171 |
+
elif rsi >= 70:
|
| 172 |
+
sentiment_score -= 30 # Muito bearish
|
| 173 |
+
confidence_score += 25
|
| 174 |
+
signals.append(f"RSI {rsi} - Zona de sobrecompra (VENDA)")
|
| 175 |
+
elif 40 <= rsi <= 60:
|
| 176 |
+
sentiment_score += 5 # Neutro
|
| 177 |
+
confidence_score += 10
|
| 178 |
+
signals.append(f"RSI {rsi} - Zona neutra")
|
| 179 |
+
|
| 180 |
+
# === ANÁLISE EMA ===
|
| 181 |
+
if ema_trend == 'ALTA':
|
| 182 |
+
sentiment_score += 20
|
| 183 |
+
confidence_score += 15
|
| 184 |
+
signals.append("EMA em tendência de ALTA")
|
| 185 |
+
elif ema_trend == 'BAIXA':
|
| 186 |
+
sentiment_score -= 20
|
| 187 |
+
confidence_score += 15
|
| 188 |
+
signals.append("EMA em tendência de BAIXA")
|
| 189 |
+
|
| 190 |
+
# === ANÁLISE DE VOLUME ===
|
| 191 |
+
if volume_ratio > 1.5:
|
| 192 |
+
sentiment_score += 15
|
| 193 |
+
confidence_score += 10
|
| 194 |
+
signals.append(f"Volume alto ({volume_ratio:.1f}x) - Confirma movimento")
|
| 195 |
+
elif volume_ratio < 0.8:
|
| 196 |
+
sentiment_score -= 5
|
| 197 |
+
confidence_score += 5
|
| 198 |
+
signals.append(f"Volume baixo ({volume_ratio:.1f}x) - Cuidado")
|
| 199 |
+
|
| 200 |
+
# === ANÁLISE DE MOMENTUM ===
|
| 201 |
+
if price_change_pct > 0.1:
|
| 202 |
+
sentiment_score += 10
|
| 203 |
+
confidence_score += 10
|
| 204 |
+
signals.append(f"Momentum positivo (+{price_change_pct:.2f}%)")
|
| 205 |
+
elif price_change_pct < -0.1:
|
| 206 |
+
sentiment_score -= 10
|
| 207 |
+
confidence_score += 10
|
| 208 |
+
signals.append(f"Momentum negativo ({price_change_pct:.2f}%)")
|
| 209 |
+
|
| 210 |
+
# === ANÁLISE DE BOLLINGER BANDS ===
|
| 211 |
+
bb_position = market_data.get('bb_position', 'DENTRO')
|
| 212 |
+
if bb_position == 'ABAIXO':
|
| 213 |
+
sentiment_score += 25
|
| 214 |
+
confidence_score += 20
|
| 215 |
+
signals.append("Preço abaixo da banda inferior - Reversão esperada")
|
| 216 |
+
elif bb_position == 'ACIMA':
|
| 217 |
+
sentiment_score -= 25
|
| 218 |
+
confidence_score += 20
|
| 219 |
+
signals.append("Preço acima da banda superior - Reversão esperada")
|
| 220 |
+
|
| 221 |
+
# Determinar sentimento final
|
| 222 |
+
if sentiment_score >= 30:
|
| 223 |
+
sentiment = 'BULLISH'
|
| 224 |
+
sentiment_label = 'POSITIVO'
|
| 225 |
+
elif sentiment_score <= -30:
|
| 226 |
+
sentiment = 'BEARISH'
|
| 227 |
+
sentiment_label = 'NEGATIVO'
|
| 228 |
+
else:
|
| 229 |
+
sentiment = 'NEUTRAL'
|
| 230 |
+
sentiment_label = 'NEUTRO'
|
| 231 |
+
|
| 232 |
+
# Calcular confiança final
|
| 233 |
+
confidence = min(95, max(15, confidence_score))
|
| 234 |
+
|
| 235 |
+
print(f"✅ Análise Robusta: {sentiment} ({confidence:.1f}%)")
|
| 236 |
+
|
| 237 |
return {
|
| 238 |
+
'sentiment': sentiment.lower(),
|
| 239 |
+
'confidence': confidence / 100.0,
|
| 240 |
+
'label': sentiment_label,
|
| 241 |
+
'analysis': f'Análise robusta: {sentiment} ({confidence:.1f}%) - {len(signals)} sinais',
|
| 242 |
+
'signals': signals,
|
| 243 |
+
'sentiment_score': sentiment_score
|
| 244 |
}
|
| 245 |
|
| 246 |
except Exception as e:
|
| 247 |
+
print(f"❌ Erro na análise robusta: {e}")
|
| 248 |
return {
|
| 249 |
'sentiment': 'neutral',
|
| 250 |
'confidence': 0.5,
|
| 251 |
'label': 'NEUTRO',
|
| 252 |
+
'analysis': f'Erro na análise: {e}',
|
| 253 |
+
'signals': [],
|
| 254 |
+
'sentiment_score': 0
|
| 255 |
}
|
| 256 |
|
| 257 |
def analyze_scalping_signals(market_data, original_text=""):
|
|
|
|
| 896 |
<div class="row">
|
| 897 |
<div class="col-12">
|
| 898 |
<p class="lead text-light mb-3 text-center" style="color: #ffffff !important;">
|
| 899 |
+
<strong style="color: #ffffff !important;">Insira os indicadores técnicos para análise com IA FinBERT + Sistema Robusto:</strong>
|
| 900 |
</p>
|
| 901 |
</div>
|
| 902 |
</div>
|
|
|
|
| 918 |
<div class="col-12 col-md-6">
|
| 919 |
<div class="d-flex align-items-center mb-2">
|
| 920 |
<span class="badge bg-success me-2">✅</span>
|
| 921 |
+
<span class="text-light" style="color: #ffffff !important;"><strong style="color: #ffffff !important;">Análise de sentimento FinBERT</strong> + Sistema Robusto de fallback</span>
|
| 922 |
</div>
|
| 923 |
<div class="d-flex align-items-center mb-2">
|
| 924 |
<span class="badge bg-success me-2">✅</span>
|
|
|
|
| 936 |
<span class="badge bg-primary me-1">Volume</span>
|
| 937 |
<span class="badge bg-primary me-1">Momentum</span>
|
| 938 |
<span class="badge bg-success">🤖 FinBERT AI</span>
|
| 939 |
+
<span class="badge bg-warning">🔧 Sistema Robusto</span>
|
| 940 |
</p>
|
| 941 |
</div>
|
| 942 |
</div>
|