Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 |
-
|
| 23 |
-
|
| 24 |
-
|
|
|
|
| 25 |
|
| 26 |
-
|
| 27 |
-
self.update_counter += 1
|
| 28 |
-
self.last_update = current_time
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
| 33 |
|
|
|
|
| 34 |
self.timestamps.append(current_time.strftime('%H:%M:%S'))
|
|
|
|
|
|
|
| 35 |
|
| 36 |
live_data = {}
|
| 37 |
|
| 38 |
for symbol in self.symbols:
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 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 >
|
| 154 |
-
research_text = f"**Bullish Momentum** π\n
|
| 155 |
-
research_conf =
|
| 156 |
-
elif change < -
|
| 157 |
-
research_text = f"**Bearish Pressure** π\n
|
| 158 |
-
research_conf =
|
| 159 |
else:
|
| 160 |
-
research_text = f"**Consolidation
|
| 161 |
-
research_conf =
|
| 162 |
|
| 163 |
analyses['research'] = {
|
| 164 |
'emoji': 'π',
|
| 165 |
-
'title': '
|
| 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
|
| 177 |
-
'analysis': f"**{
|
| 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
|
| 199 |
-
'analysis': f"**{risk_level} RISK**\n
|
| 200 |
'confidence': 80
|
| 201 |
}
|
| 202 |
|
| 203 |
# Decision Engine
|
| 204 |
-
if change > 2
|
| 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 =
|
| 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': '
|
| 228 |
-
'analysis': f"**{decision}** π―\n
|
| 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': '
|
| 239 |
-
'technical': {'emoji': 'π', 'title': 'Technical', 'analysis': '
|
| 240 |
-
'risk': {'emoji': 'π‘οΈ', 'title': 'Risk', 'analysis': '
|
| 241 |
-
'decision': {'emoji': 'π―', 'title': 'Decision', 'analysis': 'HOLD
|
| 242 |
}
|
| 243 |
|
| 244 |
# Initialize components
|
| 245 |
market_data = RealTimeMarketData()
|
| 246 |
trading_agents = AI_TradingAgents()
|
| 247 |
|
| 248 |
-
def
|
| 249 |
-
"""Create
|
| 250 |
live_data = market_data.generate_live_data()
|
| 251 |
|
| 252 |
-
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
'
|
| 256 |
-
'
|
| 257 |
-
'
|
| 258 |
-
'
|
| 259 |
-
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
|
| 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 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 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.
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 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 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 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 |
-
|
| 325 |
-
|
| 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.
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
row=2, col=2
|
| 338 |
-
)
|
| 339 |
|
| 340 |
fig.update_layout(
|
| 341 |
-
|
| 342 |
-
title_text=f"π AUTO-REFRESHING LIVE DASHBOARD β’ Update #{market_data.update_counter} β’ {datetime.now().strftime('%H:%M:%S')}",
|
| 343 |
template='plotly_dark',
|
| 344 |
-
|
| 345 |
-
font=dict(size=12)
|
| 346 |
)
|
| 347 |
|
| 348 |
-
return fig
|
| 349 |
|
| 350 |
-
def
|
| 351 |
-
"""
|
|
|
|
|
|
|
| 352 |
if not symbol_input:
|
| 353 |
# Market overview
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
|
| 358 |
-
for symbol
|
| 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
|
| 369 |
else:
|
| 370 |
-
# Specific symbol
|
| 371 |
-
symbol = symbol_input.upper()
|
| 372 |
if symbol in live_data:
|
| 373 |
analysis = trading_agents.analyze_market(symbol, live_data)
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 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 |
-
|
| 383 |
-
|
| 384 |
|
| 385 |
-
return
|
| 386 |
else:
|
| 387 |
-
return f"# β Symbol
|
| 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
|
| 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
|
| 419 |
-
## *Auto-Refresh Every
|
| 420 |
|
| 421 |
-
π **
|
| 422 |
""")
|
| 423 |
|
| 424 |
with gr.Row():
|
| 425 |
with gr.Column(scale=1):
|
| 426 |
-
gr.Markdown("### π― Stock Selection")
|
| 427 |
symbol_input = gr.Textbox(
|
| 428 |
-
label="
|
| 429 |
-
placeholder="AAPL, TSLA... (empty for
|
| 430 |
max_lines=1
|
| 431 |
)
|
| 432 |
gr.Markdown("""
|
| 433 |
-
**Tracked
|
| 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("###
|
| 442 |
|
| 443 |
-
with gr.
|
| 444 |
-
with gr.
|
| 445 |
-
|
| 446 |
-
|
|
|
|
|
|
|
|
|
|
| 447 |
)
|
| 448 |
|
| 449 |
-
with gr.
|
| 450 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 451 |
|
| 452 |
gr.Markdown(f"""
|
| 453 |
---
|
| 454 |
-
**π
|
| 455 |
-
|
| 456 |
-
**π― Tracking:** {len(market_data.symbols)} stocks with real-time AI analysis
|
| 457 |
""")
|
| 458 |
|
| 459 |
-
#
|
| 460 |
-
|
| 461 |
-
fn=
|
| 462 |
inputs=[symbol_input],
|
| 463 |
-
outputs=[
|
| 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
|
| 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)
|
|
|
|
|
|
|
|
|
|
|
|