OmidSakaki commited on
Commit
4edaa56
Β·
verified Β·
1 Parent(s): 1c95ce1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +177 -332
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  import pandas as pd
3
  import numpy as np
@@ -5,7 +6,6 @@ import yfinance as yf
5
  import plotly.graph_objects as go
6
  from plotly.subplots import make_subplots
7
  from datetime import datetime, timedelta
8
- import asyncio
9
  import time
10
  import warnings
11
  warnings.filterwarnings('ignore')
@@ -17,116 +17,52 @@ class RealTimeMarketData:
17
  self.data_history = {symbol: [] for symbol in symbols}
18
  self.timestamps = []
19
  self.update_counter = 0
20
- self.last_update = datetime.now()
21
 
22
- def generate_live_data(self):
23
- """Generate realistic live market data with actual changes"""
24
- current_time = datetime.now()
 
25
 
26
- # Always generate new data for demo purposes
27
- self.update_counter += 1
28
- self.last_update = current_time
29
 
30
- # Keep only last 15 timestamps for performance
31
- if len(self.timestamps) > 15:
32
- self.timestamps.pop(0)
 
33
 
 
34
  self.timestamps.append(current_time.strftime('%H:%M:%S'))
 
 
35
 
36
  live_data = {}
37
 
38
  for symbol in self.symbols:
39
- try:
40
- # Get actual current price from Yahoo Finance
41
- ticker = yf.Ticker(symbol)
42
- current_info = ticker.info
43
- base_price = current_info.get('currentPrice',
44
- current_info.get('regularMarketPrice',
45
- current_info.get('previousClose', 150)))
46
-
47
- # Add realistic random movement
48
- if symbol in self.last_prices:
49
- # More visible changes for demo (1-3%)
50
- change_pct = np.random.uniform(-2, 2)
51
- current_price = self.last_prices[symbol] * (1 + change_pct/100)
52
- else:
53
- current_price = base_price
54
-
55
- self.last_prices[symbol] = current_price
56
-
57
- # Add to history
58
- if symbol not in self.data_history:
59
- self.data_history[symbol] = []
60
-
61
- self.data_history[symbol].append(current_price)
62
-
63
- # Keep only last 15 prices
64
- if len(self.data_history[symbol]) > 15:
65
- self.data_history[symbol].pop(0)
66
-
67
- # Ensure timestamps match
68
- current_timestamps = self.timestamps[-len(self.data_history[symbol]):]
69
- if len(current_timestamps) != len(self.data_history[symbol]):
70
- current_timestamps = [f"{(datetime.now() - timedelta(seconds=i*5)).strftime('%H:%M:%S')}"
71
- for i in range(len(self.data_history[symbol])-1, -1, -1)]
72
-
73
- # Calculate change
74
- if len(self.data_history[symbol]) > 1:
75
- change = ((current_price - self.data_history[symbol][0]) /
76
- self.data_history[symbol][0]) * 100
77
- else:
78
- change = 0
79
-
80
- live_data[symbol] = {
81
- 'prices': self.data_history[symbol].copy(),
82
- 'timestamps': current_timestamps,
83
- 'current_price': current_price,
84
- 'change': change,
85
- 'volume': np.random.randint(1000000, 5000000),
86
- 'update_count': self.update_counter,
87
- 'last_updated': current_time.strftime('%H:%M:%S')
88
- }
89
-
90
- except Exception as e:
91
- print(f"Error with {symbol}: {e}")
92
- live_data[symbol] = self._generate_simulated_data(symbol)
93
 
94
  return live_data
95
-
96
- def _generate_simulated_data(self, symbol):
97
- """Generate realistic simulated data"""
98
- if symbol not in self.last_prices:
99
- self.last_prices[symbol] = np.random.uniform(150, 250)
100
-
101
- # Visible price movement for demo
102
- change_pct = np.random.uniform(-2.5, 2.5)
103
- new_price = self.last_prices[symbol] * (1 + change_pct/100)
104
- self.last_prices[symbol] = new_price
105
-
106
- # Add to history
107
- if symbol not in self.data_history:
108
- self.data_history[symbol] = []
109
-
110
- self.data_history[symbol].append(new_price)
111
-
112
- if len(self.data_history[symbol]) > 15:
113
- self.data_history[symbol].pop(0)
114
-
115
- # Generate timestamps
116
- current_timestamps = [f"{(datetime.now() - timedelta(seconds=i*5)).strftime('%H:%M:%S')}"
117
- for i in range(len(self.data_history[symbol])-1, -1, -1)]
118
-
119
- change = ((new_price - self.data_history[symbol][0]) / self.data_history[symbol][0]) * 100
120
-
121
- return {
122
- 'prices': self.data_history[symbol].copy(),
123
- 'timestamps': current_timestamps,
124
- 'current_price': new_price,
125
- 'change': change,
126
- 'volume': np.random.randint(1000000, 5000000),
127
- 'update_count': self.update_counter,
128
- 'last_updated': datetime.now().strftime('%H:%M:%S')
129
- }
130
 
131
  class AI_TradingAgents:
132
  def __init__(self):
@@ -136,7 +72,6 @@ class AI_TradingAgents:
136
  'risk': {'name': 'Risk Agent', 'emoji': 'πŸ›‘οΈ'},
137
  'decision': {'name': 'Decision Engine', 'emoji': '🎯'}
138
  }
139
- self.last_analysis = {}
140
 
141
  def analyze_market(self, symbol, market_data):
142
  if symbol not in market_data:
@@ -146,339 +81,249 @@ class AI_TradingAgents:
146
  current_price = data['current_price']
147
  change = data['change']
148
 
149
- # Make analysis dynamic based on price changes
150
  analyses = {}
151
 
152
  # Research Agent
153
- if change > 1.5:
154
- research_text = f"**Bullish Momentum** πŸš€\n\nβ€’ Strong price action\nβ€’ Positive market sentiment\nβ€’ Institutional interest growing\nβ€’ **Recommendation: BUY** (88% confidence)\nβ€’ Target: ${current_price * 1.12:.2f}"
155
- research_conf = 88
156
- elif change < -1.5:
157
- research_text = f"**Bearish Pressure** πŸ“‰\n\nβ€’ Price weakness evident\nβ€’ Consider waiting for stabilization\nβ€’ Support at ${current_price * 0.95:.2f}\nβ€’ **Recommendation: HOLD** (72% confidence)"
158
- research_conf = 72
159
  else:
160
- research_text = f"**Consolidation Phase** βš–οΈ\n\nβ€’ Sideways movement\nβ€’ Awaiting catalyst\nβ€’ Good risk-reward setup\nβ€’ **Recommendation: HOLD** (78% confidence)"
161
- research_conf = 78
162
 
163
  analyses['research'] = {
164
  'emoji': 'πŸ“Š',
165
- 'title': 'Fundamental Analysis',
166
  'analysis': research_text,
167
  'confidence': research_conf
168
  }
169
 
170
  # Technical Agent
171
- rsi_level = "Overbought" if change > 2 else "Oversold" if change < -2 else "Neutral"
172
  trend = "Bullish" if change > 0 else "Bearish"
173
-
174
  analyses['technical'] = {
175
  'emoji': 'πŸ“ˆ',
176
- 'title': 'Technical Analysis',
177
- 'analysis': f"**{rsi_level} - {trend} Trend**\n\nβ€’ Price: ${current_price:.2f}\nβ€’ Change: {change:+.2f}%\nβ€’ RSI: {65 if change > 0 else 35}\nβ€’ Volume: {data['volume']:,}\nβ€’ Momentum: {'Positive' if change > 0 else 'Negative'}",
178
  'confidence': 75
179
  }
180
 
181
  # Risk Agent
182
  volatility = abs(change)
183
- if volatility > 3:
184
- risk_level = "HIGH"
185
- position_size = "1-2%"
186
- stop_loss = "10%"
187
- elif volatility > 1.5:
188
- risk_level = "MEDIUM"
189
- position_size = "2-3%"
190
- stop_loss = "8%"
191
- else:
192
- risk_level = "LOW"
193
- position_size = "3-4%"
194
- stop_loss = "6%"
195
-
196
  analyses['risk'] = {
197
  'emoji': 'πŸ›‘οΈ',
198
- 'title': 'Risk Assessment',
199
- 'analysis': f"**{risk_level} RISK**\n\nβ€’ Volatility: {volatility:.1f}%\nβ€’ Position Size: {position_size}\nβ€’ Stop-Loss: {stop_loss}\nβ€’ Risk-Reward: 1:{3 if risk_level == 'LOW' else 2}\nβ€’ Monitoring: {'Intensive' if risk_level == 'HIGH' else 'Standard'}",
200
  'confidence': 80
201
  }
202
 
203
  # Decision Engine
204
- if change > 2 and volatility < 4:
205
  decision = "BUY"
206
  confidence = 85
207
- reason = "Strong uptrend with controlled risk"
208
- action = "Enter long position with trailing stop"
209
  elif change < -2:
210
  decision = "SELL"
211
- confidence = 78
212
- reason = "Significant downward pressure"
213
- action = "Consider short opportunities or wait"
214
- elif abs(change) < 0.5:
215
- decision = "HOLD"
216
- confidence = 65
217
- reason = "Minimal movement, awaiting direction"
218
- action = "Monitor for breakout signals"
219
  else:
220
  decision = "HOLD"
221
  confidence = 70
222
- reason = "Moderate movement, needs confirmation"
223
- action = "Wait for clearer trend establishment"
224
 
225
  analyses['decision'] = {
226
  'emoji': '🎯',
227
- 'title': 'Trading Decision',
228
- 'analysis': f"**{decision}** 🎯\n\n**Confidence:** {confidence}%\n**Current Price:** ${current_price:.2f}\n**Price Change:** {change:+.2f}%\n**Reason:** {reason}\n\n**Action:** {action}",
229
  'confidence': confidence,
230
  'decision': decision
231
  }
232
 
233
- self.last_analysis[symbol] = analyses
234
  return analyses
235
 
236
  def _get_error_analysis(self, symbol):
237
  return {
238
- 'research': {'emoji': 'πŸ“Š', 'title': 'Research', 'analysis': 'Data unavailable', 'confidence': 0},
239
- 'technical': {'emoji': 'πŸ“ˆ', 'title': 'Technical', 'analysis': 'Data unavailable', 'confidence': 0},
240
- 'risk': {'emoji': 'πŸ›‘οΈ', 'title': 'Risk', 'analysis': 'Data unavailable', 'confidence': 0},
241
- 'decision': {'emoji': '🎯', 'title': 'Decision', 'analysis': 'HOLD - No data', 'confidence': 0, 'decision': 'HOLD'}
242
  }
243
 
244
  # Initialize components
245
  market_data = RealTimeMarketData()
246
  trading_agents = AI_TradingAgents()
247
 
248
- def create_live_dashboard():
249
- """Create auto-updating dashboard"""
250
  live_data = market_data.generate_live_data()
251
 
252
- fig = make_subplots(
253
- rows=2, cols=2,
254
- subplot_titles=[
255
- 'πŸ“ˆ Live Price Movement (Auto-Refresh)',
256
- 'πŸ“Š Real-Time Performance',
257
- 'πŸ”„ Recent Price Changes',
258
- '🎯 Market Sentiment'
259
- ],
260
- specs=[
261
- [{"type": "scatter"}, {"type": "bar"}],
262
- [{"type": "scatter"}, {"type": "pie"}]
263
- ],
264
- vertical_spacing=0.12
265
- )
 
 
 
 
 
266
 
267
- # 1. Live price lines
268
  colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
269
  for i, (symbol, data) in enumerate(live_data.items()):
270
- fig.add_trace(
271
- go.Scatter(
272
- x=data['timestamps'],
273
- y=data['prices'],
274
- mode='lines+markers',
275
- name=f'{symbol}',
276
- line=dict(color=colors[i % len(colors)], width=3),
277
- marker=dict(size=6),
278
- hovertemplate=f'<b>{symbol}</b><br>%{{x}}<br>$%{{y:.2f}}<br>Change: {data["change"]:+.2f}%<extra></extra>'
279
- ),
280
- row=1, col=1
281
- )
282
-
283
- # 2. Performance bars
284
- symbols = list(live_data.keys())
285
- changes = [live_data[s]['change'] for s in symbols]
286
- current_prices = [live_data[s]['current_price'] for s in symbols]
287
 
288
- fig.add_trace(
289
- go.Bar(
290
- x=symbols,
291
- y=changes,
292
- marker_color=['#00CC96' if c > 0 else '#EF553B' for c in changes],
293
- text=[f"${p:.2f}\n({c:+.2f}%)" for p, c in zip(current_prices, changes)],
294
- textposition='auto',
295
- name='Performance'
296
- ),
297
- row=1, col=2
298
  )
299
 
300
- # 3. Recent changes
301
- if live_data:
302
- first_symbol = list(live_data.keys())[0]
303
- data = live_data[first_symbol]
304
- if len(data['prices']) > 3:
305
- recent_changes = []
306
- for i in range(1, min(4, len(data['prices']))):
307
- change = ((data['prices'][-i] - data['prices'][-i-1]) / data['prices'][-i-1]) * 100
308
- recent_changes.append(change)
309
-
310
- fig.add_trace(
311
- go.Scatter(
312
- x=data['timestamps'][-3:],
313
- y=recent_changes[::-1],
314
- mode='lines+markers+text',
315
- name='Recent Changes',
316
- line=dict(color='#FECA57', width=4),
317
- marker=dict(size=10),
318
- text=[f"{c:+.2f}%" for c in recent_changes[::-1]],
319
- textposition='top center'
320
- ),
321
- row=2, col=1
322
- )
323
 
324
- # 4. Market sentiment
325
- bullish = len([d for d in live_data.values() if d['change'] > 0])
326
- bearish = len([d for d in live_data.values() if d['change'] < 0])
327
- neutral = len([d for d in live_data.values() if d['change'] == 0])
328
 
329
- fig.add_trace(
330
- go.Pie(
331
- labels=['Bullish', 'Bearish', 'Neutral'],
332
- values=[bullish, bearish, neutral],
333
- hole=0.4,
334
- marker_colors=['#00CC96', '#EF553B', '#636EFA'],
335
- name='Market Sentiment'
336
- ),
337
- row=2, col=2
338
- )
339
 
340
  fig.update_layout(
341
- height=800,
342
- title_text=f"πŸ”„ AUTO-REFRESHING LIVE DASHBOARD β€’ Update #{market_data.update_counter} β€’ {datetime.now().strftime('%H:%M:%S')}",
343
  template='plotly_dark',
344
- showlegend=True,
345
- font=dict(size=12)
346
  )
347
 
348
- return fig, live_data
349
 
350
- def generate_analysis(symbol_input, live_data):
351
- """Generate dynamic analysis"""
 
 
352
  if not symbol_input:
353
  # Market overview
354
- analysis_text = f"# πŸ“Š Live Market Overview\n\n"
355
- analysis_text += f"**Last Update:** {datetime.now().strftime('%H:%M:%S')}\n"
356
- analysis_text += f"**Total Updates:** {market_data.update_counter}\n\n"
357
 
358
- for symbol, data in live_data.items():
359
  analysis = trading_agents.analyze_market(symbol, live_data)
360
  decision = analysis['decision']
361
-
362
- trend_emoji = "🟒" if data['change'] > 0 else "πŸ”΄" if data['change'] < 0 else "🟑"
363
- analysis_text += f"## {trend_emoji} {symbol}\n"
364
- analysis_text += f"**Price:** ${data['current_price']:.2f} | "
365
- analysis_text += f"**Change:** {data['change']:+.2f}%\n"
366
- analysis_text += f"**Decision:** {decision['decision']} ({decision['confidence']}% confidence)\n\n"
367
 
368
- return analysis_text
369
  else:
370
- # Specific symbol analysis
371
- symbol = symbol_input.upper().strip()
372
  if symbol in live_data:
373
  analysis = trading_agents.analyze_market(symbol, live_data)
374
-
375
- analysis_text = f"# 🎯 {symbol} Live Analysis\n\n"
376
- analysis_text += f"**Current Price:** ${live_data[symbol]['current_price']:.2f}\n"
377
- analysis_text += f"**24h Change:** {live_data[symbol]['change']:+.2f}%\n"
378
- analysis_text += f"**Last Updated:** {datetime.now().strftime('%H:%M:%S')}\n"
379
- analysis_text += f"**Update Count:** #{market_data.update_counter}\n\n"
380
 
381
  for agent_type, agent_analysis in analysis.items():
382
- analysis_text += f"## {agent_analysis['emoji']} {agent_analysis['title']}\n"
383
- analysis_text += f"{agent_analysis['analysis']}\n\n"
384
 
385
- return analysis_text
386
  else:
387
- return f"# ❌ Symbol Not Found\n\n'{symbol}' is not in our tracked symbols. Try: {', '.join(market_data.symbols)}"
388
-
389
- def update_interface(symbol_input=""):
390
- """Main update function called automatically"""
391
- try:
392
- dashboard, live_data = create_live_dashboard()
393
- analysis = generate_analysis(symbol_input, live_data)
394
- return dashboard, analysis
395
- except Exception as e:
396
- # Return error state
397
- error_fig = go.Figure()
398
- error_fig.add_annotation(
399
- text="πŸ”„ Updating... Please wait",
400
- xref="paper", yref="paper",
401
- x=0.5, y=0.5,
402
- showarrow=False,
403
- font=dict(size=20)
404
- )
405
- error_fig.update_layout(height=400, template='plotly_dark')
406
- return error_fig, "# πŸ”„ Updating... Please wait"
407
 
408
- # Create auto-refreshing interface
409
- with gr.Blocks(
410
- theme=gr.themes.Soft(
411
- primary_hue="blue",
412
- secondary_hue="slate"
413
- ),
414
- title="πŸ€– Auto-Refresh AI Trading System"
415
- ) as demo:
416
 
417
  gr.Markdown("""
418
- # πŸ€– Real-Time AI Trading System
419
- ## *Auto-Refresh Every 5 Seconds*
420
 
421
- πŸ”„ **Charts and data update automatically - no clicking needed!**
422
  """)
423
 
424
  with gr.Row():
425
  with gr.Column(scale=1):
426
- gr.Markdown("### 🎯 Stock Selection")
427
  symbol_input = gr.Textbox(
428
- label="Enter Stock Symbol",
429
- placeholder="AAPL, TSLA... (empty for market overview)",
430
  max_lines=1
431
  )
432
  gr.Markdown("""
433
- **Tracked Stocks:** AAPL, GOOGL, MSFT, TSLA
434
-
435
- ⏰ **Auto-Refresh:** Every 5 seconds
436
- πŸ“Š **Live Data:** Real-time price movements
437
- πŸ€– **AI Analysis:** Dynamic recommendations
438
  """)
439
-
440
  with gr.Column(scale=2):
441
- gr.Markdown("### πŸ“Š Live Auto-Refresh Dashboard")
442
 
443
- with gr.Tabs():
444
- with gr.TabItem("πŸ“ˆ Live Charts"):
445
- chart_output = gr.Plot(
446
- label="Auto-Refreshing Market Data"
 
 
 
447
  )
448
 
449
- with gr.TabItem("πŸ€– AI Analysis"):
450
- analysis_output = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
451
 
452
  gr.Markdown(f"""
453
  ---
454
- **πŸ”„ System Status:** Auto-Refresh Active β€’ **πŸ“… Last Refresh:** {datetime.now().strftime('%H:%M:%S')}
455
- **πŸ’‘ Tip:** The page automatically updates every 5 seconds with live data
456
- **🎯 Tracking:** {len(market_data.symbols)} stocks with real-time AI analysis
457
  """)
458
 
459
- # Set up auto-refresh using JavaScript
460
- demo.load(
461
- fn=update_interface,
462
  inputs=[symbol_input],
463
- outputs=[chart_output, analysis_output]
464
  )
465
-
466
- # Add JavaScript for auto-refresh
467
- demo.js = """
468
- <script>
469
- function autoRefresh() {
470
- setTimeout(function() {
471
- location.reload();
472
- }, 5000); // Refresh every 5 seconds
473
- }
474
- window.onload = autoRefresh;
475
- </script>
476
- """
477
 
478
- # Launch the application
479
  if __name__ == "__main__":
480
- demo.launch(
481
- server_name="0.0.0.0",
482
- server_port=7860,
483
- share=True
484
- )
 
1
+ # app.py - Real-Time Auto-Refresh Trading System
2
  import gradio as gr
3
  import pandas as pd
4
  import numpy as np
 
6
  import plotly.graph_objects as go
7
  from plotly.subplots import make_subplots
8
  from datetime import datetime, timedelta
 
9
  import time
10
  import warnings
11
  warnings.filterwarnings('ignore')
 
17
  self.data_history = {symbol: [] for symbol in symbols}
18
  self.timestamps = []
19
  self.update_counter = 0
 
20
 
21
+ # Initialize prices
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
 
26
+ self.timestamps = [datetime.now().strftime('%H:%M:%S')]
 
 
27
 
28
+ def generate_live_data(self):
29
+ """Generate realistic live market data"""
30
+ self.update_counter += 1
31
+ current_time = datetime.now()
32
 
33
+ # Add new timestamp
34
  self.timestamps.append(current_time.strftime('%H:%M:%S'))
35
+ if len(self.timestamps) > 20:
36
+ self.timestamps.pop(0)
37
 
38
  live_data = {}
39
 
40
  for symbol in self.symbols:
41
+ # Generate realistic price movement
42
+ change_pct = np.random.normal(0, 0.8) # More volatility
43
+ new_price = self.last_prices[symbol] * (1 + change_pct/100)
44
+ self.last_prices[symbol] = new_price
45
+
46
+ # Add to history
47
+ self.data_history[symbol].append(new_price)
48
+ if len(self.data_history[symbol]) > 20:
49
+ self.data_history[symbol].pop(0)
50
+
51
+ # Calculate metrics
52
+ current_timestamps = self.timestamps[-len(self.data_history[symbol]):]
53
+ change = ((new_price - self.data_history[symbol][0]) / self.data_history[symbol][0]) * 100
54
+
55
+ live_data[symbol] = {
56
+ 'prices': self.data_history[symbol].copy(),
57
+ 'timestamps': current_timestamps,
58
+ 'current_price': new_price,
59
+ 'change': change,
60
+ 'volume': np.random.randint(1000000, 5000000),
61
+ 'update_count': self.update_counter,
62
+ 'last_updated': current_time.strftime('%H:%M:%S')
63
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
64
 
65
  return live_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
  class AI_TradingAgents:
68
  def __init__(self):
 
72
  'risk': {'name': 'Risk Agent', 'emoji': 'πŸ›‘οΈ'},
73
  'decision': {'name': 'Decision Engine', 'emoji': '🎯'}
74
  }
 
75
 
76
  def analyze_market(self, symbol, market_data):
77
  if symbol not in market_data:
 
81
  current_price = data['current_price']
82
  change = data['change']
83
 
 
84
  analyses = {}
85
 
86
  # Research Agent
87
+ if change > 2:
88
+ research_text = f"**Bullish Momentum** πŸš€\nβ€’ Strong price action\nβ€’ **BUY** (85% confidence)"
89
+ research_conf = 85
90
+ elif change < -2:
91
+ research_text = f"**Bearish Pressure** πŸ“‰\nβ€’ Price weakness\nβ€’ **HOLD** (70% confidence)"
92
+ research_conf = 70
93
  else:
94
+ research_text = f"**Consolidation** βš–οΈ\nβ€’ Sideways movement\nβ€’ **HOLD** (75% confidence)"
95
+ research_conf = 75
96
 
97
  analyses['research'] = {
98
  'emoji': 'πŸ“Š',
99
+ 'title': 'Research',
100
  'analysis': research_text,
101
  'confidence': research_conf
102
  }
103
 
104
  # Technical Agent
 
105
  trend = "Bullish" if change > 0 else "Bearish"
 
106
  analyses['technical'] = {
107
  'emoji': 'πŸ“ˆ',
108
+ 'title': 'Technical',
109
+ 'analysis': f"**{trend} Trend**\nβ€’ Price: ${current_price:.2f}\nβ€’ Change: {change:+.2f}%\nβ€’ RSI: {60 if change > 0 else 40}",
110
  'confidence': 75
111
  }
112
 
113
  # Risk Agent
114
  volatility = abs(change)
115
+ risk_level = "HIGH" if volatility > 3 else "MEDIUM" if volatility > 1.5 else "LOW"
 
 
 
 
 
 
 
 
 
 
 
 
116
  analyses['risk'] = {
117
  'emoji': 'πŸ›‘οΈ',
118
+ 'title': 'Risk',
119
+ 'analysis': f"**{risk_level} RISK**\nβ€’ Volatility: {volatility:.1f}%\nβ€’ Position: 2-3%\nβ€’ Stop: 6-8%",
120
  'confidence': 80
121
  }
122
 
123
  # Decision Engine
124
+ if change > 2:
125
  decision = "BUY"
126
  confidence = 85
 
 
127
  elif change < -2:
128
  decision = "SELL"
129
+ confidence = 75
 
 
 
 
 
 
 
130
  else:
131
  decision = "HOLD"
132
  confidence = 70
 
 
133
 
134
  analyses['decision'] = {
135
  'emoji': '🎯',
136
+ 'title': 'Decision',
137
+ 'analysis': f"**{decision}** 🎯\nβ€’ Confidence: {confidence}%\nβ€’ Price: ${current_price:.2f}",
138
  'confidence': confidence,
139
  'decision': decision
140
  }
141
 
 
142
  return analyses
143
 
144
  def _get_error_analysis(self, symbol):
145
  return {
146
+ 'research': {'emoji': 'πŸ“Š', 'title': 'Research', 'analysis': 'No data', 'confidence': 0},
147
+ 'technical': {'emoji': 'πŸ“ˆ', 'title': 'Technical', 'analysis': 'No data', 'confidence': 0},
148
+ 'risk': {'emoji': 'πŸ›‘οΈ', 'title': 'Risk', 'analysis': 'No data', 'confidence': 0},
149
+ 'decision': {'emoji': '🎯', 'title': 'Decision', 'analysis': 'HOLD', 'confidence': 0, 'decision': 'HOLD'}
150
  }
151
 
152
  # Initialize components
153
  market_data = RealTimeMarketData()
154
  trading_agents = AI_TradingAgents()
155
 
156
+ def get_live_dataframe():
157
+ """Create live updating dataframe"""
158
  live_data = market_data.generate_live_data()
159
 
160
+ data = []
161
+ for symbol, info in live_data.items():
162
+ data.append({
163
+ 'Symbol': symbol,
164
+ 'Price': f"${info['current_price']:.2f}",
165
+ 'Change': f"{info['change']:+.2f}%",
166
+ 'Volume': f"{info['volume']:,}",
167
+ 'Last Update': info['last_updated'],
168
+ 'Update #': info['update_count']
169
+ })
170
+
171
+ df = pd.DataFrame(data)
172
+ return df
173
+
174
+ def get_live_chart():
175
+ """Create live updating chart"""
176
+ live_data = market_data.generate_live_data()
177
+
178
+ fig = go.Figure()
179
 
 
180
  colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4']
181
  for i, (symbol, data) in enumerate(live_data.items()):
182
+ fig.add_trace(go.Scatter(
183
+ x=data['timestamps'],
184
+ y=data['prices'],
185
+ mode='lines+markers',
186
+ name=symbol,
187
+ line=dict(color=colors[i], width=3),
188
+ marker=dict(size=6)
189
+ ))
 
 
 
 
 
 
 
 
 
190
 
191
+ fig.update_layout(
192
+ title=f"Live Prices - Update #{market_data.update_counter} - {datetime.now().strftime('%H:%M:%S')}",
193
+ template='plotly_dark',
194
+ height=400
 
 
 
 
 
 
195
  )
196
 
197
+ return fig
198
+
199
+ def get_performance_chart():
200
+ """Create performance chart"""
201
+ live_data = market_data.generate_live_data()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
 
203
+ symbols = list(live_data.keys())
204
+ changes = [live_data[s]['change'] for s in symbols]
 
 
205
 
206
+ fig = go.Figure()
207
+ fig.add_trace(go.Bar(
208
+ x=symbols,
209
+ y=changes,
210
+ marker_color=['green' if c > 0 else 'red' for c in changes],
211
+ text=[f"{c:+.2f}%" for c in changes],
212
+ textposition='auto'
213
+ ))
 
 
214
 
215
  fig.update_layout(
216
+ title="Today's Performance",
 
217
  template='plotly_dark',
218
+ height=300
 
219
  )
220
 
221
+ return fig
222
 
223
+ def get_analysis_report(symbol_input=""):
224
+ """Get analysis report"""
225
+ live_data = market_data.generate_live_data()
226
+
227
  if not symbol_input:
228
  # Market overview
229
+ report = f"# πŸ“Š Market Overview\n\n"
230
+ report += f"**Last Update:** {datetime.now().strftime('%H:%M:%S')}\n"
231
+ report += f"**Update Count:** {market_data.update_counter}\n\n"
232
 
233
+ for symbol in live_data.keys():
234
  analysis = trading_agents.analyze_market(symbol, live_data)
235
  decision = analysis['decision']
236
+ report += f"**{symbol}:** ${live_data[symbol]['current_price']:.2f} ({live_data[symbol]['change']:+.2f}%) - {decision['decision']}\n\n"
 
 
 
 
 
237
 
238
+ return report
239
  else:
240
+ # Specific symbol
241
+ symbol = symbol_input.upper()
242
  if symbol in live_data:
243
  analysis = trading_agents.analyze_market(symbol, live_data)
244
+ report = f"# 🎯 {symbol} Analysis\n\n"
245
+ report += f"**Price:** ${live_data[symbol]['current_price']:.2f}\n"
246
+ report += f"**Change:** {live_data[symbol]['change']:+.2f}%\n\n"
 
 
 
247
 
248
  for agent_type, agent_analysis in analysis.items():
249
+ report += f"### {agent_analysis['emoji']} {agent_analysis['title']}\n"
250
+ report += f"{agent_analysis['analysis']}\n\n"
251
 
252
+ return report
253
  else:
254
+ return f"# ❌ Symbol not found: {symbol}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
255
 
256
+ # Create the interface
257
+ with gr.Blocks(theme=gr.themes.Soft(), title="Live Trading Dashboard") as demo:
 
 
 
 
 
 
258
 
259
  gr.Markdown("""
260
+ # πŸ€– Real-Time Trading Dashboard
261
+ ## *Live Auto-Refresh Every 3 Seconds*
262
 
263
+ πŸ”„ **Data updates automatically every 3 seconds**
264
  """)
265
 
266
  with gr.Row():
267
  with gr.Column(scale=1):
 
268
  symbol_input = gr.Textbox(
269
+ label="Stock Symbol",
270
+ placeholder="AAPL, TSLA... (empty for overview)",
271
  max_lines=1
272
  )
273
  gr.Markdown("""
274
+ **Tracked:** AAPL, GOOGL, MSFT, TSLA
275
+ **Refresh:** Every 3 seconds
 
 
 
276
  """)
277
+
278
  with gr.Column(scale=2):
279
+ gr.Markdown("### πŸ“ˆ Live Market Data")
280
 
281
+ with gr.Row():
282
+ with gr.Column():
283
+ # Auto-updating dataframe
284
+ dataframe = gr.DataFrame(
285
+ label="Live Stock Prices",
286
+ every=3, # Auto-refresh every 3 seconds
287
+ value=get_live_dataframe
288
  )
289
 
290
+ with gr.Column():
291
+ # Performance chart
292
+ performance_chart = gr.Plot(
293
+ label="Performance",
294
+ every=3,
295
+ value=get_performance_chart
296
+ )
297
+
298
+ with gr.Row():
299
+ # Main price chart
300
+ price_chart = gr.Plot(
301
+ label="Live Price Movement",
302
+ every=3,
303
+ value=get_live_chart
304
+ )
305
+
306
+ with gr.Row():
307
+ # Analysis report
308
+ analysis_report = gr.Markdown(
309
+ label="AI Analysis",
310
+ every=3,
311
+ value=lambda: get_analysis_report("")
312
+ )
313
 
314
  gr.Markdown(f"""
315
  ---
316
+ **πŸ”„ Live Updates Active** β€’ **Last Data:** {datetime.now().strftime('%H:%M:%S')}
317
+ *Data refreshes automatically every 3 seconds*
 
318
  """)
319
 
320
+ # Update analysis when symbol input changes
321
+ symbol_input.change(
322
+ fn=get_analysis_report,
323
  inputs=[symbol_input],
324
+ outputs=[analysis_report]
325
  )
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
+ # Launch the app
328
  if __name__ == "__main__":
329
+ demo.launch(share=True)