Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -14,6 +14,7 @@ class RealTimeMarketData:
|
|
| 14 |
self.symbols = symbols
|
| 15 |
self.last_prices = {}
|
| 16 |
self.data_history = {symbol: [] for symbol in symbols}
|
|
|
|
| 17 |
self.timestamps = []
|
| 18 |
self.update_counter = 0
|
| 19 |
|
|
@@ -21,6 +22,7 @@ class RealTimeMarketData:
|
|
| 21 |
for symbol in symbols:
|
| 22 |
self.last_prices[symbol] = np.random.uniform(150, 250)
|
| 23 |
self.data_history[symbol] = [self.last_prices[symbol]]
|
|
|
|
| 24 |
|
| 25 |
self.timestamps = [datetime.now().strftime('%H:%M:%S')]
|
| 26 |
|
|
@@ -31,7 +33,7 @@ class RealTimeMarketData:
|
|
| 31 |
|
| 32 |
# Add new timestamp
|
| 33 |
self.timestamps.append(current_time.strftime('%H:%M:%S'))
|
| 34 |
-
if len(self.timestamps) >
|
| 35 |
self.timestamps.pop(0)
|
| 36 |
|
| 37 |
live_data = {}
|
|
@@ -44,7 +46,7 @@ class RealTimeMarketData:
|
|
| 44 |
|
| 45 |
# Add to history
|
| 46 |
self.data_history[symbol].append(new_price)
|
| 47 |
-
if len(self.data_history[symbol]) >
|
| 48 |
self.data_history[symbol].pop(0)
|
| 49 |
|
| 50 |
# Calculate metrics
|
|
@@ -91,7 +93,6 @@ class AI_TradingAgents:
|
|
| 91 |
β’ Expanding profit margins
|
| 92 |
β’ Market leadership position
|
| 93 |
β’ Positive institutional sentiment
|
| 94 |
-
β’ Strong balance sheet
|
| 95 |
|
| 96 |
**Recommendation: BUY** (85% confidence)
|
| 97 |
**Price Target: ${current_price * 1.15:.2f}**"""
|
|
@@ -103,7 +104,6 @@ class AI_TradingAgents:
|
|
| 103 |
β’ Increasing competitive pressures
|
| 104 |
β’ Wait for better entry point
|
| 105 |
β’ Support at ${current_price * 0.95:.2f}
|
| 106 |
-
β’ Monitor earnings closely
|
| 107 |
|
| 108 |
**Recommendation: HOLD** (70% confidence)"""
|
| 109 |
research_conf = 70
|
|
@@ -142,8 +142,7 @@ class AI_TradingAgents:
|
|
| 142 |
- Support: ${support:.2f}
|
| 143 |
- Resistance: ${resistance:.2f}
|
| 144 |
β’ RSI: {65 if change > 0 else 35} ({rsi_level})
|
| 145 |
-
β’ Volume: {data['volume']:,}
|
| 146 |
-
β’ Momentum: {'Positive' if change > 0 else 'Negative'}""",
|
| 147 |
'confidence': 75
|
| 148 |
}
|
| 149 |
|
|
@@ -152,17 +151,14 @@ class AI_TradingAgents:
|
|
| 152 |
risk_level = "HIGH"
|
| 153 |
position_size = "1-2%"
|
| 154 |
stop_loss = "10%"
|
| 155 |
-
risk_reward = "1:2"
|
| 156 |
elif volatility > 1.5:
|
| 157 |
risk_level = "MEDIUM"
|
| 158 |
position_size = "2-3%"
|
| 159 |
stop_loss = "8%"
|
| 160 |
-
risk_reward = "1:2.5"
|
| 161 |
else:
|
| 162 |
risk_level = "LOW"
|
| 163 |
position_size = "3-4%"
|
| 164 |
stop_loss = "6%"
|
| 165 |
-
risk_reward = "1:3"
|
| 166 |
|
| 167 |
analyses['risk'] = {
|
| 168 |
'emoji': 'π‘οΈ',
|
|
@@ -170,11 +166,9 @@ class AI_TradingAgents:
|
|
| 170 |
'analysis': f"""**{risk_level} RISK PROFILE**
|
| 171 |
|
| 172 |
β’ Volatility: {volatility:.1f}%
|
| 173 |
-
β’
|
| 174 |
-
β’ Stop-Loss: {stop_loss}
|
| 175 |
-
β’ Risk-Reward
|
| 176 |
-
β’ Maximum Drawdown: 12%
|
| 177 |
-
β’ Correlation: Low with portfolio
|
| 178 |
β’ Monitoring: {'Intensive' if risk_level == 'HIGH' else 'Standard'}""",
|
| 179 |
'confidence': 80
|
| 180 |
}
|
|
@@ -183,38 +177,23 @@ class AI_TradingAgents:
|
|
| 183 |
if change > 2 and volatility < 4:
|
| 184 |
decision = "BUY"
|
| 185 |
confidence = 85
|
| 186 |
-
reason = "Strong bullish momentum with favorable risk metrics and positive fundamentals"
|
| 187 |
-
action = "Enter long position with trailing stop at 8%. Target 15-20% upside."
|
| 188 |
elif change < -2:
|
| 189 |
decision = "SELL"
|
| 190 |
confidence = 78
|
| 191 |
-
reason = "Significant downward pressure with deteriorating technicals"
|
| 192 |
-
action = "Consider short opportunities or wait for stabilization. Set tight stop-loss."
|
| 193 |
else:
|
| 194 |
decision = "HOLD"
|
| 195 |
confidence = 72
|
| 196 |
-
reason = "Consolidation phase with mixed signals. Awaiting clearer market direction."
|
| 197 |
-
action = "Monitor for breakout above resistance or breakdown below support."
|
| 198 |
|
| 199 |
analyses['decision'] = {
|
| 200 |
'emoji': 'π―',
|
| 201 |
'title': 'Trading Decision',
|
| 202 |
'analysis': f"""**FINAL DECISION: {decision}** π―
|
| 203 |
|
| 204 |
-
**Confidence
|
| 205 |
-
**
|
| 206 |
-
**
|
| 207 |
|
| 208 |
-
**
|
| 209 |
-
{reason}
|
| 210 |
-
|
| 211 |
-
**Execution Plan:**
|
| 212 |
-
{action}
|
| 213 |
-
|
| 214 |
-
**Key Factors:**
|
| 215 |
-
β’ Fundamental Score: {analyses['research']['confidence']}%
|
| 216 |
-
β’ Technical Score: {analyses['technical']['confidence']}%
|
| 217 |
-
β’ Risk Assessment: {analyses['risk']['confidence']}%""",
|
| 218 |
'confidence': confidence,
|
| 219 |
'decision': decision
|
| 220 |
}
|
|
@@ -222,7 +201,7 @@ class AI_TradingAgents:
|
|
| 222 |
return analyses
|
| 223 |
|
| 224 |
def _get_error_analysis(self, symbol):
|
| 225 |
-
error_msg = "Data temporarily unavailable.
|
| 226 |
return {
|
| 227 |
'research': {'emoji': 'π', 'title': 'Research', 'analysis': error_msg, 'confidence': 0},
|
| 228 |
'technical': {'emoji': 'π', 'title': 'Technical', 'analysis': error_msg, 'confidence': 0},
|
|
@@ -234,146 +213,268 @@ class AI_TradingAgents:
|
|
| 234 |
market_data = RealTimeMarketData()
|
| 235 |
trading_agents = AI_TradingAgents()
|
| 236 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 237 |
def get_ai_agents_analysis(symbol_input=""):
|
| 238 |
"""Get detailed analysis from all AI agents"""
|
| 239 |
live_data = market_data.generate_live_data()
|
| 240 |
|
| 241 |
if not symbol_input:
|
| 242 |
-
return "# π€ AI Agents Analysis\n\n**Please enter a stock symbol to see detailed analysis
|
| 243 |
|
| 244 |
symbol = symbol_input.upper()
|
| 245 |
if symbol not in live_data:
|
| 246 |
-
return f"# β Symbol Not Found\n\n'{symbol}'
|
| 247 |
|
| 248 |
-
# Get analysis from all agents
|
| 249 |
analysis = trading_agents.analyze_market(symbol, live_data)
|
| 250 |
|
| 251 |
detailed_report = f"""
|
| 252 |
-
# π€ AI Agents
|
| 253 |
|
| 254 |
-
## π {symbol} - Real-time Analysis
|
| 255 |
**Current Price:** ${live_data[symbol]['current_price']:.2f}
|
| 256 |
**24h Change:** {live_data[symbol]['change']:+.2f}%
|
| 257 |
-
**Last Update:** {datetime.now().strftime('%H:%M:%S')}
|
| 258 |
-
**Analysis Cycle:** #{market_data.update_counter}
|
| 259 |
|
| 260 |
---
|
| 261 |
|
| 262 |
## {analysis['research']['emoji']} {analysis['research']['title']}
|
| 263 |
-
**Confidence
|
| 264 |
|
| 265 |
{analysis['research']['analysis']}
|
| 266 |
|
| 267 |
---
|
| 268 |
|
| 269 |
## {analysis['technical']['emoji']} {analysis['technical']['title']}
|
| 270 |
-
**Confidence
|
| 271 |
|
| 272 |
{analysis['technical']['analysis']}
|
| 273 |
|
| 274 |
---
|
| 275 |
|
| 276 |
## {analysis['risk']['emoji']} {analysis['risk']['title']}
|
| 277 |
-
**Confidence
|
| 278 |
|
| 279 |
{analysis['risk']['analysis']}
|
| 280 |
|
| 281 |
---
|
| 282 |
|
| 283 |
## {analysis['decision']['emoji']} {analysis['decision']['title']}
|
| 284 |
-
**Confidence
|
| 285 |
|
| 286 |
{analysis['decision']['analysis']}
|
| 287 |
-
|
| 288 |
-
---
|
| 289 |
-
|
| 290 |
-
### π― Multi-Agent Consensus
|
| 291 |
-
- **Overall Confidence:** {np.mean([a['confidence'] for a in analysis.values()]):.1f}%
|
| 292 |
-
- **Final Recommendation:** {analysis['decision']['decision']}
|
| 293 |
-
- **Risk Level:** {'High' if analysis['risk']['confidence'] < 70 else 'Medium' if analysis['risk']['confidence'] < 80 else 'Low'}
|
| 294 |
-
- **Market Outlook:** {'Bullish' if analysis['research']['confidence'] > 80 else 'Neutral' if analysis['research']['confidence'] > 65 else 'Bearish'}
|
| 295 |
-
|
| 296 |
-
*Analysis generated by Multi-Agent AI Trading System*
|
| 297 |
"""
|
| 298 |
return detailed_report
|
| 299 |
|
| 300 |
-
def get_agents_performance():
|
| 301 |
-
"""Get performance overview of all agents"""
|
| 302 |
-
live_data = market_data.generate_live_data()
|
| 303 |
-
|
| 304 |
-
performance_data = []
|
| 305 |
-
for symbol in market_data.symbols:
|
| 306 |
-
analysis = trading_agents.analyze_market(symbol, live_data)
|
| 307 |
-
performance_data.append({
|
| 308 |
-
'Symbol': symbol,
|
| 309 |
-
'Price': f"${live_data[symbol]['current_price']:.2f}",
|
| 310 |
-
'Change': f"{live_data[symbol]['change']:+.2f}%",
|
| 311 |
-
'Research': f"{analysis['research']['confidence']}%",
|
| 312 |
-
'Technical': f"{analysis['technical']['confidence']}%",
|
| 313 |
-
'Risk': f"{analysis['risk']['confidence']}%",
|
| 314 |
-
'Decision': analysis['decision']['decision'],
|
| 315 |
-
'Confidence': f"{analysis['decision']['confidence']}%"
|
| 316 |
-
})
|
| 317 |
-
|
| 318 |
-
df = pd.DataFrame(performance_data)
|
| 319 |
-
return df
|
| 320 |
-
|
| 321 |
# Create the interface
|
| 322 |
-
with gr.Blocks(theme=gr.themes.Soft(), title="AI
|
| 323 |
|
| 324 |
gr.Markdown("""
|
| 325 |
-
# π€ AI
|
| 326 |
-
## *
|
| 327 |
|
| 328 |
-
**
|
| 329 |
""")
|
| 330 |
|
| 331 |
with gr.Row():
|
| 332 |
with gr.Column(scale=1):
|
| 333 |
symbol_input = gr.Textbox(
|
| 334 |
-
label="
|
| 335 |
-
placeholder="
|
| 336 |
max_lines=1
|
| 337 |
)
|
| 338 |
gr.Markdown("""
|
| 339 |
-
**
|
| 340 |
-
|
| 341 |
-
**π€ AI Agents:**
|
| 342 |
-
- π Research Agent: Fundamental Analysis
|
| 343 |
-
- π Technical Agent: Price & Patterns
|
| 344 |
-
- π‘οΈ Risk Agent: Risk Management
|
| 345 |
-
- π― Decision Engine: Final Recommendation
|
| 346 |
""")
|
| 347 |
-
|
| 348 |
-
with gr.Column(scale=2):
|
| 349 |
-
gr.Markdown("### π Agents Performance Overview")
|
| 350 |
-
agents_performance = gr.DataFrame(
|
| 351 |
-
label="AI Agents Confidence Levels",
|
| 352 |
-
every=5,
|
| 353 |
-
value=get_agents_performance
|
| 354 |
-
)
|
| 355 |
|
| 356 |
-
with gr.
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 363 |
|
| 364 |
gr.Markdown(f"""
|
| 365 |
---
|
| 366 |
-
**π Live
|
| 367 |
-
*
|
| 368 |
-
|
| 369 |
-
**π Analysis Includes:**
|
| 370 |
-
- Fundamental company research and growth prospects
|
| 371 |
-
- Technical price patterns and market structure
|
| 372 |
-
- Comprehensive risk assessment and position sizing
|
| 373 |
-
- Final trading decision with execution plan
|
| 374 |
""")
|
| 375 |
|
| 376 |
-
# Update
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 377 |
symbol_input.change(
|
| 378 |
fn=get_ai_agents_analysis,
|
| 379 |
inputs=[symbol_input],
|
|
|
|
| 14 |
self.symbols = symbols
|
| 15 |
self.last_prices = {}
|
| 16 |
self.data_history = {symbol: [] for symbol in symbols}
|
| 17 |
+
self.confidence_history = {symbol: [] for symbol in symbols}
|
| 18 |
self.timestamps = []
|
| 19 |
self.update_counter = 0
|
| 20 |
|
|
|
|
| 22 |
for symbol in symbols:
|
| 23 |
self.last_prices[symbol] = np.random.uniform(150, 250)
|
| 24 |
self.data_history[symbol] = [self.last_prices[symbol]]
|
| 25 |
+
self.confidence_history[symbol] = []
|
| 26 |
|
| 27 |
self.timestamps = [datetime.now().strftime('%H:%M:%S')]
|
| 28 |
|
|
|
|
| 33 |
|
| 34 |
# Add new timestamp
|
| 35 |
self.timestamps.append(current_time.strftime('%H:%M:%S'))
|
| 36 |
+
if len(self.timestamps) > 20:
|
| 37 |
self.timestamps.pop(0)
|
| 38 |
|
| 39 |
live_data = {}
|
|
|
|
| 46 |
|
| 47 |
# Add to history
|
| 48 |
self.data_history[symbol].append(new_price)
|
| 49 |
+
if len(self.data_history[symbol]) > 20:
|
| 50 |
self.data_history[symbol].pop(0)
|
| 51 |
|
| 52 |
# Calculate metrics
|
|
|
|
| 93 |
β’ Expanding profit margins
|
| 94 |
β’ Market leadership position
|
| 95 |
β’ Positive institutional sentiment
|
|
|
|
| 96 |
|
| 97 |
**Recommendation: BUY** (85% confidence)
|
| 98 |
**Price Target: ${current_price * 1.15:.2f}**"""
|
|
|
|
| 104 |
β’ Increasing competitive pressures
|
| 105 |
β’ Wait for better entry point
|
| 106 |
β’ Support at ${current_price * 0.95:.2f}
|
|
|
|
| 107 |
|
| 108 |
**Recommendation: HOLD** (70% confidence)"""
|
| 109 |
research_conf = 70
|
|
|
|
| 142 |
- Support: ${support:.2f}
|
| 143 |
- Resistance: ${resistance:.2f}
|
| 144 |
β’ RSI: {65 if change > 0 else 35} ({rsi_level})
|
| 145 |
+
β’ Volume: {data['volume']:,}""",
|
|
|
|
| 146 |
'confidence': 75
|
| 147 |
}
|
| 148 |
|
|
|
|
| 151 |
risk_level = "HIGH"
|
| 152 |
position_size = "1-2%"
|
| 153 |
stop_loss = "10%"
|
|
|
|
| 154 |
elif volatility > 1.5:
|
| 155 |
risk_level = "MEDIUM"
|
| 156 |
position_size = "2-3%"
|
| 157 |
stop_loss = "8%"
|
|
|
|
| 158 |
else:
|
| 159 |
risk_level = "LOW"
|
| 160 |
position_size = "3-4%"
|
| 161 |
stop_loss = "6%"
|
|
|
|
| 162 |
|
| 163 |
analyses['risk'] = {
|
| 164 |
'emoji': 'π‘οΈ',
|
|
|
|
| 166 |
'analysis': f"""**{risk_level} RISK PROFILE**
|
| 167 |
|
| 168 |
β’ Volatility: {volatility:.1f}%
|
| 169 |
+
β’ Position Size: {position_size}
|
| 170 |
+
β’ Stop-Loss: {stop_loss}
|
| 171 |
+
β’ Risk-Reward: 1:{3 if risk_level == 'LOW' else 2}
|
|
|
|
|
|
|
| 172 |
β’ Monitoring: {'Intensive' if risk_level == 'HIGH' else 'Standard'}""",
|
| 173 |
'confidence': 80
|
| 174 |
}
|
|
|
|
| 177 |
if change > 2 and volatility < 4:
|
| 178 |
decision = "BUY"
|
| 179 |
confidence = 85
|
|
|
|
|
|
|
| 180 |
elif change < -2:
|
| 181 |
decision = "SELL"
|
| 182 |
confidence = 78
|
|
|
|
|
|
|
| 183 |
else:
|
| 184 |
decision = "HOLD"
|
| 185 |
confidence = 72
|
|
|
|
|
|
|
| 186 |
|
| 187 |
analyses['decision'] = {
|
| 188 |
'emoji': 'π―',
|
| 189 |
'title': 'Trading Decision',
|
| 190 |
'analysis': f"""**FINAL DECISION: {decision}** π―
|
| 191 |
|
| 192 |
+
**Confidence:** {confidence}%
|
| 193 |
+
**Price:** ${current_price:.2f}
|
| 194 |
+
**Change:** {change:+.2f}%
|
| 195 |
|
| 196 |
+
**Action:** {'Enter long position' if decision == 'BUY' else 'Wait for setup'}""",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 197 |
'confidence': confidence,
|
| 198 |
'decision': decision
|
| 199 |
}
|
|
|
|
| 201 |
return analyses
|
| 202 |
|
| 203 |
def _get_error_analysis(self, symbol):
|
| 204 |
+
error_msg = "Data temporarily unavailable."
|
| 205 |
return {
|
| 206 |
'research': {'emoji': 'π', 'title': 'Research', 'analysis': error_msg, 'confidence': 0},
|
| 207 |
'technical': {'emoji': 'π', 'title': 'Technical', 'analysis': error_msg, 'confidence': 0},
|
|
|
|
| 213 |
market_data = RealTimeMarketData()
|
| 214 |
trading_agents = AI_TradingAgents()
|
| 215 |
|
| 216 |
+
def create_live_price_chart():
|
| 217 |
+
"""Create live price movement chart"""
|
| 218 |
+
live_data = market_data.generate_live_data()
|
| 219 |
+
|
| 220 |
+
fig = go.Figure()
|
| 221 |
+
|
| 222 |
+
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
|
| 223 |
+
for i, (symbol, data) in enumerate(live_data.items()):
|
| 224 |
+
fig.add_trace(go.Scatter(
|
| 225 |
+
x=data['timestamps'],
|
| 226 |
+
y=data['prices'],
|
| 227 |
+
mode='lines+markers',
|
| 228 |
+
name=symbol,
|
| 229 |
+
line=dict(color=colors[i], width=3),
|
| 230 |
+
marker=dict(size=6),
|
| 231 |
+
hovertemplate=f'<b>{symbol}</b><br>%{{x}}<br>$%{{y:.2f}}<extra></extra>'
|
| 232 |
+
))
|
| 233 |
+
|
| 234 |
+
fig.update_layout(
|
| 235 |
+
title=f"π Live Price Movement - Update #{market_data.update_counter}",
|
| 236 |
+
template='plotly_dark',
|
| 237 |
+
height=400,
|
| 238 |
+
xaxis_title="Time",
|
| 239 |
+
yaxis_title="Price ($)",
|
| 240 |
+
showlegend=True
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
return fig
|
| 244 |
+
|
| 245 |
+
def create_confidence_chart(symbol_input=""):
|
| 246 |
+
"""Create AI agents confidence comparison chart"""
|
| 247 |
+
live_data = market_data.generate_live_data()
|
| 248 |
+
|
| 249 |
+
if not symbol_input:
|
| 250 |
+
symbol = 'AAPL'
|
| 251 |
+
else:
|
| 252 |
+
symbol = symbol_input.upper()
|
| 253 |
+
|
| 254 |
+
if symbol not in live_data:
|
| 255 |
+
symbol = 'AAPL'
|
| 256 |
+
|
| 257 |
+
analysis = trading_agents.analyze_market(symbol, live_data)
|
| 258 |
+
|
| 259 |
+
agents = list(analysis.keys())
|
| 260 |
+
confidences = [analysis[agent]['confidence'] for agent in agents]
|
| 261 |
+
colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
|
| 262 |
+
|
| 263 |
+
fig = go.Figure()
|
| 264 |
+
|
| 265 |
+
fig.add_trace(go.Bar(
|
| 266 |
+
x=agents,
|
| 267 |
+
y=confidences,
|
| 268 |
+
marker_color=colors,
|
| 269 |
+
text=[f"{c}%" for c in confidences],
|
| 270 |
+
textposition='auto',
|
| 271 |
+
hovertemplate='<b>%{x}</b><br>Confidence: %{y}%<extra></extra>'
|
| 272 |
+
))
|
| 273 |
+
|
| 274 |
+
fig.update_layout(
|
| 275 |
+
title=f"π€ AI Agents Confidence - {symbol}",
|
| 276 |
+
template='plotly_dark',
|
| 277 |
+
height=400,
|
| 278 |
+
xaxis_title="AI Agents",
|
| 279 |
+
yaxis_title="Confidence Level (%)",
|
| 280 |
+
yaxis_range=[0, 100]
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
return fig
|
| 284 |
+
|
| 285 |
+
def create_market_sentiment_chart():
|
| 286 |
+
"""Create market sentiment pie chart"""
|
| 287 |
+
live_data = market_data.generate_live_data()
|
| 288 |
+
|
| 289 |
+
decisions = {'BUY': 0, 'SELL': 0, 'HOLD': 0}
|
| 290 |
+
for symbol in live_data.keys():
|
| 291 |
+
analysis = trading_agents.analyze_market(symbol, live_data)
|
| 292 |
+
decision = analysis['decision']['decision']
|
| 293 |
+
decisions[decision] += 1
|
| 294 |
+
|
| 295 |
+
fig = go.Figure()
|
| 296 |
+
|
| 297 |
+
fig.add_trace(go.Pie(
|
| 298 |
+
labels=list(decisions.keys()),
|
| 299 |
+
values=list(decisions.values()),
|
| 300 |
+
hole=0.4,
|
| 301 |
+
marker_colors=['#00CC96', '#EF553B', '#636EFA'],
|
| 302 |
+
hovertemplate='<b>%{label}</b><br>%{value} stocks<extra></extra>'
|
| 303 |
+
))
|
| 304 |
+
|
| 305 |
+
fig.update_layout(
|
| 306 |
+
title="π― Market Sentiment - AI Recommendations",
|
| 307 |
+
template='plotly_dark',
|
| 308 |
+
height=400
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
return fig
|
| 312 |
+
|
| 313 |
+
def create_performance_chart():
|
| 314 |
+
"""Create stock performance comparison chart"""
|
| 315 |
+
live_data = market_data.generate_live_data()
|
| 316 |
+
|
| 317 |
+
symbols = list(live_data.keys())
|
| 318 |
+
changes = [live_data[symbol]['change'] for symbol in symbols]
|
| 319 |
+
prices = [live_data[symbol]['current_price'] for symbol in symbols]
|
| 320 |
+
|
| 321 |
+
fig = make_subplots(
|
| 322 |
+
rows=1, cols=2,
|
| 323 |
+
subplot_titles=['24h Performance (%)', 'Current Prices ($)'],
|
| 324 |
+
specs=[[{"type": "bar"}, {"type": "bar"}]]
|
| 325 |
+
)
|
| 326 |
+
|
| 327 |
+
# Performance bars
|
| 328 |
+
fig.add_trace(go.Bar(
|
| 329 |
+
x=symbols,
|
| 330 |
+
y=changes,
|
| 331 |
+
name='24h Change',
|
| 332 |
+
marker_color=['#00CC96' if c > 0 else '#EF553B' for c in changes],
|
| 333 |
+
text=[f"{c:+.2f}%" for c in changes],
|
| 334 |
+
textposition='auto'
|
| 335 |
+
), row=1, col=1)
|
| 336 |
+
|
| 337 |
+
# Price bars
|
| 338 |
+
fig.add_trace(go.Bar(
|
| 339 |
+
x=symbols,
|
| 340 |
+
y=prices,
|
| 341 |
+
name='Current Price',
|
| 342 |
+
marker_color='#636EFA',
|
| 343 |
+
text=[f"${p:.2f}" for p in prices],
|
| 344 |
+
textposition='auto'
|
| 345 |
+
), row=1, col=2)
|
| 346 |
+
|
| 347 |
+
fig.update_layout(
|
| 348 |
+
title="π Market Performance Overview",
|
| 349 |
+
template='plotly_dark',
|
| 350 |
+
height=400,
|
| 351 |
+
showlegend=False
|
| 352 |
+
)
|
| 353 |
+
|
| 354 |
+
return fig
|
| 355 |
+
|
| 356 |
def get_ai_agents_analysis(symbol_input=""):
|
| 357 |
"""Get detailed analysis from all AI agents"""
|
| 358 |
live_data = market_data.generate_live_data()
|
| 359 |
|
| 360 |
if not symbol_input:
|
| 361 |
+
return "# π€ AI Agents Analysis\n\n**Please enter a stock symbol to see detailed analysis**"
|
| 362 |
|
| 363 |
symbol = symbol_input.upper()
|
| 364 |
if symbol not in live_data:
|
| 365 |
+
return f"# β Symbol Not Found\n\n'{symbol}' not in tracked symbols."
|
| 366 |
|
|
|
|
| 367 |
analysis = trading_agents.analyze_market(symbol, live_data)
|
| 368 |
|
| 369 |
detailed_report = f"""
|
| 370 |
+
# π€ AI Agents Analysis - {symbol}
|
| 371 |
|
|
|
|
| 372 |
**Current Price:** ${live_data[symbol]['current_price']:.2f}
|
| 373 |
**24h Change:** {live_data[symbol]['change']:+.2f}%
|
| 374 |
+
**Last Update:** {datetime.now().strftime('%H:%M:%S')}
|
|
|
|
| 375 |
|
| 376 |
---
|
| 377 |
|
| 378 |
## {analysis['research']['emoji']} {analysis['research']['title']}
|
| 379 |
+
**Confidence:** {analysis['research']['confidence']}%
|
| 380 |
|
| 381 |
{analysis['research']['analysis']}
|
| 382 |
|
| 383 |
---
|
| 384 |
|
| 385 |
## {analysis['technical']['emoji']} {analysis['technical']['title']}
|
| 386 |
+
**Confidence:** {analysis['technical']['confidence']}%
|
| 387 |
|
| 388 |
{analysis['technical']['analysis']}
|
| 389 |
|
| 390 |
---
|
| 391 |
|
| 392 |
## {analysis['risk']['emoji']} {analysis['risk']['title']}
|
| 393 |
+
**Confidence:** {analysis['risk']['confidence']}%
|
| 394 |
|
| 395 |
{analysis['risk']['analysis']}
|
| 396 |
|
| 397 |
---
|
| 398 |
|
| 399 |
## {analysis['decision']['emoji']} {analysis['decision']['title']}
|
| 400 |
+
**Confidence:** {analysis['decision']['confidence']}%
|
| 401 |
|
| 402 |
{analysis['decision']['analysis']}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 403 |
"""
|
| 404 |
return detailed_report
|
| 405 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 406 |
# Create the interface
|
| 407 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="AI Trading Dashboard") as demo:
|
| 408 |
|
| 409 |
gr.Markdown("""
|
| 410 |
+
# π€ AI Trading Dashboard
|
| 411 |
+
## *Live Charts & Real-time Analysis*
|
| 412 |
|
| 413 |
+
**Interactive charts with live data updates every 5 seconds**
|
| 414 |
""")
|
| 415 |
|
| 416 |
with gr.Row():
|
| 417 |
with gr.Column(scale=1):
|
| 418 |
symbol_input = gr.Textbox(
|
| 419 |
+
label="Stock Symbol",
|
| 420 |
+
placeholder="AAPL, TSLA...",
|
| 421 |
max_lines=1
|
| 422 |
)
|
| 423 |
gr.Markdown("""
|
| 424 |
+
**Tracked Stocks:** AAPL, GOOGL, MSFT, TSLA
|
| 425 |
+
**Auto-Refresh:** Every 5 seconds
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 426 |
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 427 |
|
| 428 |
+
with gr.Tabs():
|
| 429 |
+
with gr.TabItem("π Live Charts"):
|
| 430 |
+
with gr.Row():
|
| 431 |
+
price_chart = gr.Plot(
|
| 432 |
+
label="Live Price Movement",
|
| 433 |
+
every=5,
|
| 434 |
+
value=create_live_price_chart
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
with gr.Row():
|
| 438 |
+
confidence_chart = gr.Plot(
|
| 439 |
+
label="AI Agents Confidence",
|
| 440 |
+
every=5,
|
| 441 |
+
value=lambda: create_confidence_chart(symbol_input.value if symbol_input.value else "")
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
with gr.Row():
|
| 445 |
+
sentiment_chart = gr.Plot(
|
| 446 |
+
label="Market Sentiment",
|
| 447 |
+
every=5,
|
| 448 |
+
value=create_market_sentiment_chart
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
performance_chart = gr.Plot(
|
| 452 |
+
label="Performance Overview",
|
| 453 |
+
every=5,
|
| 454 |
+
value=create_performance_chart
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
with gr.TabItem("π€ AI Analysis"):
|
| 458 |
+
with gr.Row():
|
| 459 |
+
agents_analysis = gr.Markdown(
|
| 460 |
+
label="AI Agents Analysis",
|
| 461 |
+
every=5,
|
| 462 |
+
value=get_ai_agents_analysis
|
| 463 |
+
)
|
| 464 |
|
| 465 |
gr.Markdown(f"""
|
| 466 |
---
|
| 467 |
+
**π Live Dashboard Active** β’ **Last Update:** {datetime.now().strftime('%H:%M:%S')}
|
| 468 |
+
*All charts and analysis update automatically every 5 seconds*
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 469 |
""")
|
| 470 |
|
| 471 |
+
# Update confidence chart when symbol changes
|
| 472 |
+
symbol_input.change(
|
| 473 |
+
fn=lambda s: create_confidence_chart(s),
|
| 474 |
+
inputs=[symbol_input],
|
| 475 |
+
outputs=[confidence_chart]
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
symbol_input.change(
|
| 479 |
fn=get_ai_agents_analysis,
|
| 480 |
inputs=[symbol_input],
|