-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdashboard.py
More file actions
509 lines (426 loc) · 17.8 KB
/
dashboard.py
File metadata and controls
509 lines (426 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
#!/usr/bin/env python3
"""
LLM Trader Dashboard
Real-time monitoring and visualization of the trading system using Streamlit.
"""
import streamlit as st
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import time
import sys
import os
# Add src to path
sys.path.append('src')
# Import our modules
from main import LLMTrader
from data.persistence import DataPersistence
# Page configuration
st.set_page_config(
page_title="🤖 LLM Trader Dashboard",
page_icon="📈",
layout="wide",
initial_sidebar_state="expanded"
)
# Custom CSS
st.markdown("""
<style>
.metric-card {
background-color: #f0f2f6;
padding: 20px;
border-radius: 10px;
border-left: 5px solid #ff4b4b;
}
.positive {
border-left-color: #00cc44;
}
.negative {
border-left-color: #ff4b4b;
}
.neutral {
border-left-color: #ffa500;
}
</style>
""", unsafe_allow_html=True)
class TradingDashboard:
"""Streamlit dashboard for LLM Trader monitoring."""
def __init__(self):
self.trader = None
self.persistence = DataPersistence()
self.initialize_system()
def initialize_system(self):
"""Initialize the trading system."""
try:
with st.spinner("Initializing LLM Trader system..."):
self.trader = LLMTrader()
self.trader.initialize_components()
st.success("✅ System initialized successfully!")
except Exception as e:
st.error(f"❌ Failed to initialize system: {str(e)}")
st.info("💡 Make sure you have set your OpenAI API key in config.json or as an environment variable")
def run(self):
"""Main dashboard interface."""
st.title("🤖 LLM Trader Dashboard")
st.markdown("---")
# Sidebar
self.sidebar()
# Main content
if self.trader:
tab1, tab2, tab3, tab4, tab5 = st.tabs([
"📊 Overview", "📈 Portfolio", "🎯 Signals",
"📋 Trade History", "⚙️ System Status"
])
with tab1:
self.overview_tab()
with tab2:
self.portfolio_tab()
with tab3:
self.signals_tab()
with tab4:
self.trades_tab()
with tab5:
self.system_tab()
else:
st.error("❌ Trading system not initialized. Please check your configuration.")
def sidebar(self):
"""Sidebar with controls and information."""
st.sidebar.title("🎛️ Controls")
# Quick Actions
st.sidebar.subheader("⚡ Quick Actions")
if st.sidebar.button("🔄 Run Trading Cycle", type="primary"):
self.run_trading_cycle()
if st.sidebar.button("📊 Update Portfolio"):
self.update_portfolio()
if st.sidebar.button("🎲 Run Simulation"):
self.run_simulation()
# System Info
st.sidebar.subheader("ℹ️ System Info")
st.sidebar.metric("Status", "🟢 Online" if self.trader else "🔴 Offline")
if self.trader:
portfolio = self.trader.get_portfolio_status()
st.sidebar.metric("Portfolio Value", f"${portfolio.get('total_value', 0):,.2f}")
st.sidebar.metric("Cash", f"${portfolio.get('cash', 0):,.2f}")
st.sidebar.metric("Positions", len(portfolio.get('positions', {})))
# Configuration
st.sidebar.subheader("⚙️ Configuration")
st.sidebar.json({
"symbols": ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"],
"risk_tolerance": 0.1,
"max_positions": 10
})
def overview_tab(self):
"""Main overview dashboard."""
st.header("📊 System Overview")
if not self.trader:
return
# Key Metrics Row
col1, col2, col3, col4 = st.columns(4)
portfolio = self.trader.get_portfolio_status()
with col1:
total_value = portfolio.get('total_value', 0)
pnl = portfolio.get('total_pnl', 0)
pnl_color = "positive" if pnl >= 0 else "negative"
st.markdown(f"""
<div class="metric-card {pnl_color}">
<h3>${total_value:,.2f}</h3>
<p>Portfolio Value</p>
<small style="color: {'green' if pnl >= 0 else 'red'}">
{'+' if pnl >= 0 else ''}${pnl:,.2f} ({portfolio.get('return_pct', 0):.2f}%)
</small>
</div>
""", unsafe_allow_html=True)
with col2:
cash = portfolio.get('cash', 0)
st.markdown(f"""
<div class="metric-card neutral">
<h3>${cash:,.2f}</h3>
<p>Available Cash</p>
<small>Cash Position</small>
</div>
""", unsafe_allow_html=True)
with col3:
positions = len(portfolio.get('positions', {}))
st.markdown(f"""
<div class="metric-card neutral">
<h3>{positions}</h3>
<p>Open Positions</p>
<small>Active Trades</small>
</div>
""", unsafe_allow_html=True)
with col4:
daily_pnl = portfolio.get('daily_pnl', 0)
daily_color = "positive" if daily_pnl >= 0 else "negative"
st.markdown(f"""
<div class="metric-card {daily_color}">
<h3>${daily_pnl:,.2f}</h3>
<p>Daily P&L</p>
<small>Today's Performance</small>
</div>
""", unsafe_allow_html=True)
# Performance Chart
st.subheader("📈 Portfolio Performance")
self.plot_portfolio_performance()
# Recent Signals
st.subheader("🎯 Recent Signals")
self.display_recent_signals()
def portfolio_tab(self):
"""Portfolio analysis and visualization."""
st.header("📈 Portfolio Analysis")
if not self.trader:
return
portfolio = self.trader.get_portfolio_status()
# Portfolio Composition
col1, col2 = st.columns(2)
with col1:
st.subheader("💰 Asset Allocation")
positions = portfolio.get('positions', {})
if positions:
# Prepare data for pie chart
labels = []
values = []
for symbol, pos_data in positions.items():
labels.append(symbol)
values.append(pos_data.get('current_value', 0))
# Add cash
labels.append("Cash")
values.append(portfolio.get('cash', 0))
fig = px.pie(
values=values,
names=labels,
title="Portfolio Composition"
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No open positions")
with col2:
st.subheader("📊 Position Details")
if positions:
pos_data = []
for symbol, pos_info in positions.items():
pnl = pos_info.get('current_value', 0) - (pos_info.get('shares', 0) * pos_info.get('avg_price', 0))
pnl_pct = (pnl / (pos_info.get('shares', 0) * pos_info.get('avg_price', 0))) * 100 if pos_info.get('shares', 0) * pos_info.get('avg_price', 0) > 0 else 0
pos_data.append({
'Symbol': symbol,
'Shares': pos_info.get('shares', 0),
'Avg Price': f"${pos_info.get('avg_price', 0):.2f}",
'Current Value': f"${pos_info.get('current_value', 0):.2f}",
'P&L': f"${pnl:.2f} ({pnl_pct:.2f}%)"
})
st.dataframe(pd.DataFrame(pos_data), use_container_width=True)
else:
st.info("No position details available")
# Performance Metrics
st.subheader("📈 Performance Metrics")
metrics_col1, metrics_col2, metrics_col3 = st.columns(3)
with metrics_col1:
st.metric("Total Return", f"{portfolio.get('return_pct', 0):.2f}%")
with metrics_col2:
st.metric("Daily Return", f"{portfolio.get('daily_return_pct', 0):.2f}%")
with metrics_col3:
st.metric("Sharpe Ratio", "1.8") # Placeholder
def signals_tab(self):
"""Trading signals display and analysis."""
st.header("🎯 Trading Signals")
# Generate new signals
if st.button("🔄 Generate New Signals"):
with st.spinner("Analyzing market data..."):
try:
symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']
results = self.trader.run_trading_cycle(symbols)
signals = results.get('signals', {})
# Display signals
for symbol, signal_data in signals.items():
col1, col2, col3, col4 = st.columns(4)
signal = signal_data.get('signal', 'HOLD')
confidence = signal_data.get('confidence', 0)
strength = signal_data.get('strength', 'MODERATE')
# Color coding
if signal == 'BUY':
color = '🟢'
elif signal == 'SELL':
color = '🔴'
else:
color = '🟡'
with col1:
st.metric(f"{color} {symbol}", signal)
with col2:
st.metric("Confidence", f"{confidence:.2f}")
with col3:
st.metric("Strength", strength)
with col4:
st.metric("Sentiment", f"{signal_data.get('sentiment_score', 0):.2f}")
# Reasoning
with st.expander(f"📝 {symbol} Analysis"):
st.write(signal_data.get('reasoning', 'No reasoning available'))
except Exception as e:
st.error(f"Failed to generate signals: {str(e)}")
def trades_tab(self):
"""Trade history and analysis."""
st.header("📋 Trade History")
try:
trades = self.persistence.load_trades()
if trades:
trades_df = pd.DataFrame(trades)
# Summary stats
col1, col2, col3, col4 = st.columns(4)
with col1:
st.metric("Total Trades", len(trades_df))
with col2:
winning_trades = len(trades_df[trades_df.get('pnl', 0) > 0]) if 'pnl' in trades_df.columns else 0
st.metric("Winning Trades", winning_trades)
with col3:
win_rate = (winning_trades / len(trades_df) * 100) if len(trades_df) > 0 else 0
st.metric("Win Rate", f"{win_rate:.1f}%")
with col4:
total_pnl = trades_df.get('pnl', 0).sum() if 'pnl' in trades_df.columns else 0
st.metric("Total P&L", f"${total_pnl:,.2f}")
# Trade history table
st.subheader("📊 Recent Trades")
if len(trades_df) > 0:
# Format for display
display_df = trades_df.copy()
if 'timestamp' in display_df.columns:
display_df['timestamp'] = pd.to_datetime(display_df['timestamp']).dt.strftime('%Y-%m-%d %H:%M')
st.dataframe(display_df.tail(10), use_container_width=True)
# P&L over time chart
if 'pnl' in trades_df.columns and 'timestamp' in trades_df.columns:
st.subheader("💰 P&L Over Time")
trades_df['timestamp'] = pd.to_datetime(trades_df['timestamp'])
trades_df = trades_df.sort_values('timestamp')
fig = px.line(
trades_df,
x='timestamp',
y='pnl',
title="Trade P&L Over Time"
)
st.plotly_chart(fig, use_container_width=True)
else:
st.info("No trade history available")
except Exception as e:
st.error(f"Failed to load trade history: {str(e)}")
def system_tab(self):
"""System status and configuration."""
st.header("⚙️ System Status")
# System Health
st.subheader("🔍 System Health")
health_col1, health_col2, health_col3 = st.columns(3)
with health_col1:
status = "🟢 Online" if self.trader else "🔴 Offline"
st.metric("System Status", status)
with health_col2:
# Check API connectivity (simplified)
api_status = "🟢 Connected" # Placeholder
st.metric("API Status", api_status)
with health_col3:
last_update = datetime.now().strftime("%H:%M:%S")
st.metric("Last Update", last_update)
# Configuration
st.subheader("⚙️ Configuration")
with st.expander("View Configuration"):
st.json({
"openai_api_key": "***configured***" if self.trader else "Not set",
"risk_tolerance": 0.1,
"initial_capital": 100000,
"max_positions": 10,
"trading_universe": ["AAPL", "MSFT", "GOOGL", "AMZN", "TSLA"]
})
# Logs
st.subheader("📋 System Logs")
with st.expander("View Recent Logs"):
st.code("""
2025-09-02 22:25:04 - __main__ - INFO - System initialized
2025-09-02 22:25:05 - sentiment.sentiment_analyzer - INFO - Sentiment analysis completed
2025-09-02 22:25:06 - fundamental.fundamental_analyzer - INFO - Fundamental analysis completed
2025-09-02 22:25:07 - strategy.strategy_engine - INFO - Trading signals generated
2025-09-02 22:25:08 - agent.trading_agent - INFO - Portfolio updated
""")
def plot_portfolio_performance(self):
"""Plot portfolio performance over time."""
# This is a placeholder - in a real implementation, you'd load historical data
dates = pd.date_range(start=datetime.now() - timedelta(days=30), end=datetime.now(), freq='D')
values = np.cumsum(np.random.normal(100, 500, len(dates))) + 100000
fig = go.Figure()
fig.add_trace(go.Scatter(
x=dates,
y=values,
mode='lines',
name='Portfolio Value',
line=dict(color='#00cc44', width=2)
))
fig.update_layout(
title="Portfolio Value Over Time",
xaxis_title="Date",
yaxis_title="Value ($)",
height=400
)
st.plotly_chart(fig, use_container_width=True)
def display_recent_signals(self):
"""Display recent trading signals."""
# Placeholder signals
signals_data = [
{"symbol": "AAPL", "signal": "BUY", "confidence": 0.85, "reasoning": "Strong fundamentals and positive sentiment"},
{"symbol": "MSFT", "signal": "HOLD", "confidence": 0.65, "reasoning": "Mixed signals, awaiting clarification"},
{"symbol": "GOOGL", "signal": "SELL", "confidence": 0.72, "reasoning": "Negative sentiment and weak fundamentals"}
]
for signal in signals_data:
col1, col2, col3, col4 = st.columns([1, 1, 1, 3])
signal_type = signal['signal']
if signal_type == 'BUY':
emoji = '🟢'
elif signal_type == 'SELL':
emoji = '🔴'
else:
emoji = '🟡'
with col1:
st.write(f"{emoji} **{signal['symbol']}**")
with col2:
st.write(f"**{signal_type}**")
with col3:
st.write(f"{signal['confidence']:.2f}")
with col4:
st.write(signal['reasoning'])
def run_trading_cycle(self):
"""Run a complete trading cycle."""
if not self.trader:
st.error("System not initialized")
return
with st.spinner("Running trading cycle..."):
try:
symbols = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']
results = self.trader.run_trading_cycle(symbols)
st.success(f"✅ Trading cycle completed! Executed {len(results.get('trades', []))} trades")
st.rerun()
except Exception as e:
st.error(f"❌ Trading cycle failed: {str(e)}")
def update_portfolio(self):
"""Update portfolio data."""
if not self.trader:
st.error("System not initialized")
return
with st.spinner("Updating portfolio..."):
try:
portfolio = self.trader.update_portfolio()
st.success("✅ Portfolio updated successfully!")
st.rerun()
except Exception as e:
st.error(f"❌ Portfolio update failed: {str(e)}")
def run_simulation(self):
"""Run market simulation."""
if not self.trader:
st.error("System not initialized")
return
with st.spinner("Running simulation..."):
try:
results = self.trader.run_simulation(days=30)
st.success("✅ Simulation completed!")
st.json(results)
except Exception as e:
st.error(f"❌ Simulation failed: {str(e)}")
def main():
"""Main function to run the dashboard."""
dashboard = TradingDashboard()
dashboard.run()
if __name__ == "__main__":
main()