Edwin Salguero commited on
Commit Β·
9f44dc9
1
Parent(s): f820bf2
feat(ui): add robust multi-interface UI system (Streamlit, Dash, Jupyter, WebSocket) with launcher, docs, and integration tests [skip ci]
Browse filesFiles changed (10)
- README.md+82-3
- UI_SETUP.mdAdded+390
- requirements.txt+54-19
- tests/test_ui_integration.pyAdded+147
- ui/__init__.pyAdded+24
- ui/dash_app.pyAdded+657
- ui/jupyter_widgets.pyAdded+556
- ui/streamlit_app.pyAdded+679
- ui/websocket_server.pyAdded+461
- ui_launcher.pyAdded+269
22 unmodified lines2324252627282930313233343571 unmodified lines1071081091101111121131141151161171181191201211221231241031251261271284 unmodified lines133134135114136137138139140119141142143144139 unmodified lines28428528628728828929029129229329429529625 unmodified lines32232332432532632732832963 unmodified lines39339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544622 unmodified lines- **Account Management**: Portfolio monitoring and position tracking- **Order Types**: Market orders, limit orders, and order cancellation
### π¨ Comprehensive UI System- **Streamlit UI**: Quick prototyping and data science workflows- **Dash UI**: Enterprise-grade interactive dashboards- **Jupyter UI**: Interactive notebook-based interfaces- **WebSocket API**: Real-time trading data streaming- **Multi-interface Support**: Choose the right UI for your needs
### Advanced Features- **Docker Support**: Containerized deployment for consistency- **Comprehensive Logging**: Detailed logs for debugging and performance analysis71 unmodified lines
## π Quick Start
### 1. Launch the UI (Recommended)```bash# Launch Streamlit UI (best for beginners)python ui_launcher.py streamlit
# Launch Dash UI (best for production)python ui_launcher.py dash
# Launch Jupyter Labpython ui_launcher.py jupyter
# Launch all UIspython ui_launcher.py all```
### 1. Run the Demo### 2. Run the Demo```bashpython demo.py```4 unmodified lines- Show trading workflow execution- Run backtesting on historical data
### 2. Start Paper Trading### 3. Start Paper Trading```bashpython -m agentic_ai_system.main --mode live --duration 60```
### 3. Run Backtesting### 4. Run Backtesting```bashpython -m agentic_ai_system.main --mode backtest --start-date 2024-01-01 --end-date 2024-01-31```139 unmodified linesβ βββ π synthetic_data_generator.py # Test data generationβ βββ π logger_config.py # Logging configurationββββ π¨ ui/ # User interface systemβ βββ π __init__.py # UI package initializationβ βββ π streamlit_app.py # Streamlit web applicationβ βββ π dash_app.py # Dash enterprise dashboardβ βββ π jupyter_widgets.py # Jupyter interactive widgetsβ βββ π websocket_server.py # Real-time WebSocket serverββββ π§ͺ tests/ # Test suiteβ βββ π __init__.pyβ βββ π test_data_ingestion.py25 unmodified linesββββ π demo.py # Main demo scriptβββ π finrl_demo.py # FinRL-specific demoβββ π ui_launcher.py # UI launcher scriptβββ π UI_SETUP.md # UI setup documentationβββ π DOCKER_HUB_SETUP.md # Docker Hub documentationββββ π .venv/ # Python virtual environment63 unmodified lines take_profit: 0.05```
## π¨ User Interface System
The project includes a comprehensive UI system with multiple interface options:
### Available UIs
#### **Streamlit UI** (Recommended for beginners)- **URL**: http://localhost:8501- **Features**: Interactive widgets, real-time data visualization, easy configuration- **Best for**: Data scientists, quick experiments, rapid prototyping
#### **Dash UI** (Recommended for production)- **URL**: http://localhost:8050- **Features**: Enterprise-grade dashboards, advanced charts, professional styling- **Best for**: Production dashboards, real-time monitoring, complex analytics
#### **Jupyter UI** (For research)- **URL**: http://localhost:8888- **Features**: Interactive notebooks, code execution, rich documentation- **Best for**: Research, experimentation, educational purposes
#### **WebSocket API** (For developers)- **URL**: ws://localhost:8765- **Features**: Real-time data streaming, trading signals, portfolio updates- **Best for**: Real-time trading signals, live data streaming
### Quick UI Launch```bash# Launch individual UIspython ui_launcher.py streamlit # Streamlit UIpython ui_launcher.py dash # Dash UIpython ui_launcher.py jupyter # Jupyter Labpython ui_launcher.py websocket # WebSocket server
# Launch all UIs at oncepython ui_launcher.py all```
### UI Features- **Real-time Data Visualization**: Live market data charts and indicators- **Portfolio Monitoring**: Real-time portfolio value and P&L tracking- **Trading Controls**: Start/stop trading, backtesting, risk management- **FinRL Training**: Interactive model training and evaluation- **Alpaca Integration**: Account management and order execution- **Configuration Management**: Easy parameter tuning and strategy setup
For detailed UI documentation, see [UI_SETUP.md](UI_SETUP.md).
## π Performance Monitoring
### Logging123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390# UI Integration Guide
This guide covers the comprehensive UI system for the Algorithmic Trading project, providing multiple interface options for different use cases.
## π― UI Options Overview
### 1. **Streamlit UI** - Quick Prototyping- **Best for**: Data scientists, quick experiments, rapid prototyping- **Features**: Interactive widgets, real-time data visualization, easy configuration- **Port**: 8501- **URL**: http://localhost:8501
### 2. **Dash UI** - Enterprise Dashboards- **Best for**: Production dashboards, real-time monitoring, complex analytics- **Features**: Advanced charts, real-time updates, professional styling- **Port**: 8050- **URL**: http://localhost:8050
### 3. **Jupyter UI** - Interactive Notebooks- **Best for**: Research, experimentation, educational purposes- **Features**: Interactive widgets, code execution, rich documentation- **Port**: 8888- **URL**: http://localhost:8888
### 4. **WebSocket Server** - Real-time Data- **Best for**: Real-time trading signals, live data streaming- **Features**: WebSocket API, real-time updates, trading signals- **Port**: 8765- **URL**: ws://localhost:8765
## π Quick Start
### Prerequisites```bash# Install UI dependenciespip install -r requirements.txt
# Verify installationpython -c "import streamlit, dash, plotly, ipywidgets; print('β
All UI dependencies installed')"```
### Launch Individual UIs
#### Streamlit (Recommended for beginners)```bashpython ui_launcher.py streamlit```
#### Dash (Recommended for production)```bashpython ui_launcher.py dash```
#### Jupyter Lab```bashpython ui_launcher.py jupyter```
#### WebSocket Server```bashpython ui_launcher.py websocket```
#### Launch All UIs```bashpython ui_launcher.py all```
## π Streamlit UI Features
### Dashboard- **System Status**: Real-time trading status, portfolio value, P&L- **Configuration Management**: Load and modify trading parameters- **Quick Actions**: One-click data loading, Alpaca connection, model training
### Data Ingestion- **Multiple Sources**: CSV, Alpaca API, Synthetic data- **Data Validation**: Automatic data quality checks- **Technical Indicators**: Automatic calculation of moving averages, RSI, MACD- **Interactive Charts**: Candlestick, line, volume charts with Plotly
### Alpaca Integration- **Account Connection**: Secure API key management- **Market Status**: Real-time market hours and status- **Position Monitoring**: Current positions and portfolio value- **Order Management**: Buy/sell order execution
### FinRL Training- **Algorithm Selection**: PPO, A2C, DDPG, TD3- **Hyperparameter Tuning**: Learning rate, batch size, training steps- **Training Progress**: Real-time training metrics and progress- **Model Evaluation**: Performance metrics and backtesting
### Trading Controls- **Live Trading**: Start/stop live trading with Alpaca- **Backtesting**: Historical strategy testing- **Risk Management**: Position sizing and drawdown limits- **Emergency Stop**: Immediate trading halt
### Portfolio Monitoring- **Real-time Portfolio**: Live portfolio value and P&L- **Position Analysis**: Individual position performance- **Allocation Charts**: Portfolio allocation visualization- **Risk Metrics**: Sharpe ratio, drawdown analysis
## π Dash UI Features
### Enterprise Dashboard- **Professional Styling**: Bootstrap themes and responsive design- **Real-time Updates**: Live data streaming and updates- **Advanced Charts**: Interactive Plotly charts with zoom, pan, hover- **Multi-page Navigation**: Tabbed interface for different functions
### Advanced Analytics- **Technical Analysis**: Advanced charting with indicators- **Performance Metrics**: Comprehensive trading performance analysis- **Risk Management**: Advanced risk monitoring and alerts- **Strategy Comparison**: Multiple strategy backtesting and comparison
### Real-time Monitoring- **Live Trading Activity**: Real-time trade execution monitoring- **System Alerts**: Automated alerts for important events- **Portfolio Tracking**: Live portfolio updates and analysis- **Market Data**: Real-time market data visualization
## π Jupyter UI Features
### Interactive Development- **Widget-based Interface**: Interactive controls for all functions- **Code Execution**: Direct Python code execution and experimentation- **Data Exploration**: Interactive data analysis and visualization- **Model Development**: Iterative model training and testing
### Research Tools- **Notebook Integration**: Rich documentation and code examples- **Data Analysis**: Pandas and NumPy integration- **Visualization**: Matplotlib, Seaborn, Plotly integration- **Experiment Tracking**: Training history and model comparison
## π WebSocket API
### Real-time Data Streaming```javascript// Connect to WebSocket serverconst ws = new WebSocket('ws://localhost:8765');
// Listen for market data updatesws.onmessage = function(event) { const data = JSON.parse(event.data); if (data.type === 'market_data') { console.log('Price:', data.price); console.log('Volume:', data.volume); } if (data.type === 'trading_signal') { console.log('Signal:', data.signal); } if (data.type === 'portfolio_update') { console.log('Portfolio:', data.account); }};```
### Available Message Types- `market_data`: Real-time price and volume data- `trading_signal`: FinRL model trading signals- `portfolio_update`: Account and position updates- `trading_status`: Trading system status- `system_alert`: System alerts and notifications
## π οΈ Configuration
### Environment Variables```bash# Alpaca API credentialsexport ALPACA_API_KEY="your_api_key"export ALPACA_SECRET_KEY="your_secret_key"
# UI configurationexport STREAMLIT_SERVER_PORT=8501export DASH_SERVER_PORT=8050export JUPYTER_PORT=8888export WEBSOCKET_PORT=8765```
### Configuration File```yaml# config.yamlui: streamlit: server_port: 8501 server_address: "0.0.0.0" theme: "light" dash: server_port: 8050 server_address: "0.0.0.0" theme: "bootstrap" jupyter: port: 8888 ip: "0.0.0.0" token: "" websocket: host: "0.0.0.0" port: 8765 max_connections: 100```
## π§ Customization
### Adding Custom Charts```python# In ui/streamlit_app.pydef create_custom_chart(data): fig = go.Figure() fig.add_trace(go.Scatter( x=data['timestamp'], y=data['custom_indicator'], name='Custom Indicator' )) return fig```
### Custom Trading Strategies```python# In ui/dash_app.pydef custom_strategy(data, config): # Implement your custom strategy signals = [] for i in range(len(data)): if data['sma_20'][i] > data['sma_50'][i]: signals.append('BUY') else: signals.append('SELL') return signals```
### WebSocket Custom Messages```python# In ui/websocket_server.pyasync def broadcast_custom_message(self, message_type, data): message = { "type": message_type, "timestamp": datetime.now().isoformat(), "data": data } await self.broadcast(message)```
## π Deployment
### Docker Deployment```bash# Build UI-enabled Docker imagedocker build -t trading-ui .
# Run with UI ports exposeddocker run -p 8501:8501 -p 8050:8050 -p 8888:8888 -p 8765:8765 trading-ui```
### Production Deployment```bash# Using Gunicorn for productionpip install gunicorn
# Start Dash app with Gunicorngunicorn -w 4 -b 0.0.0.0:8050 ui.dash_app:app
# Start Streamlit with production settingsstreamlit run ui/streamlit_app.py --server.port 8501 --server.address 0.0.0.0```
### Cloud Deployment```bash# Deploy to Herokuheroku create trading-ui-appgit push heroku main
# Deploy to AWSaws ecs create-service --cluster trading-cluster --service-name trading-ui```
## π Troubleshooting
### Common Issues
#### Port Already in Use```bash# Find process using portlsof -i :8501
# Kill processkill -9 <PID>
# Or use different portpython ui_launcher.py streamlit --port 8502```
#### Missing Dependencies```bash# Install missing packagespip install streamlit dash plotly ipywidgets
# Or reinstall all requirementspip install -r requirements.txt```
#### Alpaca Connection Issues```bash# Check API credentialsecho $ALPACA_API_KEYecho $ALPACA_SECRET_KEY
# Test connectionpython -c "from agentic_ai_system.alpaca_broker import AlpacaBroker; print('Connection test')"```
### Debug Mode```bash# Enable debug loggingexport LOG_LEVEL=DEBUG
# Run with debug outputpython ui_launcher.py streamlit --debug```
## π API Reference
### Streamlit Functions- `create_streamlit_app()`: Create Streamlit application- `TradingUI.run()`: Run the main UI application- `load_configuration()`: Load trading configuration- `display_system_status()`: Show system status
### Dash Functions- `create_dash_app()`: Create Dash application- `TradingDashApp.setup_layout()`: Setup dashboard layout- `TradingDashApp.setup_callbacks()`: Setup interactive callbacks
### Jupyter Functions- `create_jupyter_interface()`: Create Jupyter interface- `TradingJupyterUI.display_interface()`: Display interactive widgets- `TradingJupyterUI.update_chart()`: Update chart displays
### WebSocket Functions- `create_websocket_server()`: Create WebSocket server- `TradingWebSocketServer.broadcast()`: Broadcast messages- `TradingWebSocketServer.handle_client_message()`: Handle client messages
## π€ Contributing
### Adding New UI Features1. Create feature branch: `git checkout -b feature/new-ui-feature`2. Implement feature in appropriate UI module3. Add tests in `tests/ui/` directory4. Update documentation5. Submit pull request
### UI Development Guidelines- Follow PEP 8 style guidelines- Add type hints for all functions- Include docstrings for all classes and methods- Write unit tests for new features- Update documentation for new features
## π Support
For UI-related issues:1. Check the troubleshooting section2. Review the logs in `logs/ui/` directory3. Create an issue on GitHub with detailed error information4. Include system information and error logs
## π Updates
### UI Version History- **v1.0.0**: Initial UI implementation with Streamlit, Dash, Jupyter, and WebSocket- **v1.1.0**: Added real-time data streaming and advanced charts- **v1.2.0**: Enhanced portfolio monitoring and risk management- **v1.3.0**: Added custom strategy development tools
### Upcoming Features- **v1.4.0**: Machine learning model visualization- **v1.5.0**: Advanced backtesting interface- **v1.6.0**: Multi-asset portfolio management- **v1.7.0**: Social trading features 12345678910111213141516171819123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354pyyamlpandasnumpymatplotlibseabornpytestpytest-covpython-dateutilscipyfinrlstable-baselines3gymnasiumtensorboardtorchopencv-python-headlessalpaca-pypython-dotenvrequestswebsocket-client# Core dependenciesnumpy>=1.21.0pandas>=1.3.0scikit-learn>=1.0.0matplotlib>=3.5.0seaborn>=0.11.0yaml>=5.4.0requests>=2.25.0python-dotenv>=0.19.0
# FinRL dependenciesstable-baselines3>=1.5.0gym>=0.21.0torch>=1.9.0
# Alpaca integrationalpaca-trade-api>=2.0.0
# Testingpytest>=6.0.0pytest-cov>=2.12.0
# UI Dependenciesstreamlit>=1.28.0plotly>=5.15.0dash>=2.14.0dash-bootstrap-components>=1.4.0dash-extensions>=1.0.0dash-table>=5.0.0dash-cytoscape>=0.3.0dash-mantine-components>=0.12.0dash-iconify>=0.1.0dash-uploader>=0.6.0dash-daq>=0.5.0
# Additional UI enhancementsrich>=13.0.0tqdm>=4.64.0ipywidgets>=8.0.0voila>=0.4.0jupyter-dash>=0.4.0
# Real-time updateswebsockets>=10.0asyncio-mqtt>=0.11.0
# Data visualizationbokeh>=3.0.0altair>=5.0.0vega-lite>=5.0.0
# Authentication and securitydash-auth>=2.0.0flask-login>=0.6.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147"""Test UI integration for the algorithmic trading system"""
import pytestimport sysimport osfrom unittest.mock import patch, MagicMock
# Add project root to pathsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
def test_ui_imports(): """Test that UI modules can be imported""" try: from ui import create_streamlit_app, create_dash_app, create_jupyter_interface, TradingWebSocketServer assert True except ImportError as e: pytest.fail(f"Failed to import UI modules: {e}")
def test_streamlit_app_creation(): """Test Streamlit app creation""" try: from ui.streamlit_app import TradingUI ui = TradingUI() assert ui is not None assert hasattr(ui, 'config') assert hasattr(ui, 'data') assert hasattr(ui, 'alpaca_broker') except Exception as e: pytest.fail(f"Failed to create Streamlit UI: {e}")
def test_dash_app_creation(): """Test Dash app creation""" try: from ui.dash_app import TradingDashApp app = TradingDashApp() assert app is not None assert hasattr(app, 'app') assert hasattr(app, 'config') except Exception as e: pytest.fail(f"Failed to create Dash app: {e}")
def test_jupyter_ui_creation(): """Test Jupyter UI creation""" try: from ui.jupyter_widgets import TradingJupyterUI ui = TradingJupyterUI() assert ui is not None assert hasattr(ui, 'config') assert hasattr(ui, 'data') except Exception as e: pytest.fail(f"Failed to create Jupyter UI: {e}")
def test_websocket_server_creation(): """Test WebSocket server creation""" try: from ui.websocket_server import TradingWebSocketServer server = TradingWebSocketServer(host="localhost", port=8765) assert server is not None assert server.host == "localhost" assert server.port == 8765 assert hasattr(server, 'clients') except Exception as e: pytest.fail(f"Failed to create WebSocket server: {e}")
def test_ui_launcher_imports(): """Test UI launcher imports""" try: import ui_launcher assert hasattr(ui_launcher, 'check_dependencies') assert hasattr(ui_launcher, 'launch_streamlit') assert hasattr(ui_launcher, 'launch_dash') assert hasattr(ui_launcher, 'launch_jupyter') assert hasattr(ui_launcher, 'launch_websocket_server') except Exception as e: pytest.fail(f"Failed to import UI launcher: {e}")
@patch('subprocess.run')def test_ui_launcher_functions(mock_run): """Test UI launcher functions""" mock_run.return_value = MagicMock() try: import ui_launcher # Test dependency check result = ui_launcher.check_dependencies() assert isinstance(result, bool) # Test launcher functions (they should not raise exceptions) ui_launcher.launch_streamlit() ui_launcher.launch_dash() ui_launcher.launch_jupyter() ui_launcher.launch_websocket_server() except Exception as e: pytest.fail(f"Failed to test UI launcher functions: {e}")
def test_ui_configuration(): """Test UI configuration loading""" try: from agentic_ai_system.main import load_config config = load_config() # Check if UI-related config can be added config['ui'] = { 'streamlit': { 'server_port': 8501, 'server_address': "0.0.0.0" }, 'dash': { 'server_port': 8050, 'server_address': "0.0.0.0" } } assert 'ui' in config assert 'streamlit' in config['ui'] assert 'dash' in config['ui'] except Exception as e: pytest.fail(f"Failed to test UI configuration: {e}")
def test_ui_dependencies(): """Test that UI dependencies are available""" required_packages = [ 'streamlit', 'dash', 'plotly', 'ipywidgets' ] missing_packages = [] for package in required_packages: try: __import__(package) except ImportError: missing_packages.append(package) if missing_packages: pytest.skip(f"Missing UI dependencies: {missing_packages}") else: assert True
if __name__ == "__main__": pytest.main([__file__]) 123456789101112131415161718192021222324"""UI Package for Algorithmic Trading System
This package provides multiple UI options:- Streamlit: Quick prototyping and data science workflows- Dash: Enterprise-grade interactive dashboards- Jupyter: Notebook-based interfaces- WebSocket: Real-time trading interfaces"""
__version__ = "1.0.0"__author__ = "Algorithmic Trading Team"
from .streamlit_app import create_streamlit_appfrom .dash_app import create_dash_appfrom .jupyter_widgets import create_jupyter_interfacefrom .websocket_server import TradingWebSocketServer
__all__ = [ "create_streamlit_app", "create_dash_app", "create_jupyter_interface", "TradingWebSocketServer"] 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657"""Dash UI for Algorithmic Trading System
Enterprise-grade interactive dashboard with:- Real-time market data visualization- Advanced trading analytics- Portfolio management- Risk monitoring- Strategy backtesting"""
import dashfrom dash import dcc, html, Input, Output, State, callback_contextimport dash_bootstrap_components as dbcfrom dash_bootstrap_components import themesimport plotly.graph_objects as goimport plotly.express as pximport pandas as pdimport numpy as npimport yamlimport osimport sysfrom datetime import datetime, timedeltaimport asyncioimport threadingimport timefrom typing import Dict, Any, Optional
# Add project root to pathsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from agentic_ai_system.main import load_configfrom agentic_ai_system.data_ingestion import load_data, validate_data, add_technical_indicatorsfrom agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfigfrom agentic_ai_system.alpaca_broker import AlpacaBrokerfrom agentic_ai_system.orchestrator import run_backtest, run_live_trading
class TradingDashApp: def __init__(self): self.app = dash.Dash( __name__, external_stylesheets=[ themes.BOOTSTRAP, "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" ], suppress_callback_exceptions=True ) self.config = None self.data = None self.alpaca_broker = None self.finrl_agent = None self.setup_layout() self.setup_callbacks() def setup_layout(self): """Setup the main application layout""" self.app.layout = dbc.Container([ # Header dbc.Row([ dbc.Col([ html.H1([ html.I(className="fas fa-chart-line me-3"), "Algorithmic Trading System" ], className="text-primary mb-4 text-center") ]) ]), # Navigation tabs dbc.Tabs([ dbc.Tab(self.create_dashboard_tab(), label="Dashboard", tab_id="dashboard"), dbc.Tab(self.create_data_tab(), label="Data", tab_id="data"), dbc.Tab(self.create_trading_tab(), label="Trading", tab_id="trading"), dbc.Tab(self.create_analytics_tab(), label="Analytics", tab_id="analytics"), dbc.Tab(self.create_portfolio_tab(), label="Portfolio", tab_id="portfolio"), dbc.Tab(self.create_settings_tab(), label="Settings", tab_id="settings") ], id="tabs", active_tab="dashboard"), # Store components for data persistence dcc.Store(id="config-store"), dcc.Store(id="data-store"), dcc.Store(id="alpaca-store"), dcc.Store(id="finrl-store"), dcc.Store(id="trading-status-store"), # Interval for real-time updates dcc.Interval( id="interval-component", interval=5*1000, # 5 seconds n_intervals=0 ) ], fluid=True) def create_dashboard_tab(self): """Create the main dashboard tab""" return dbc.Container([ # System status cards dbc.Row([ dbc.Col(self.create_status_card("Trading Status", "Active", "success"), width=3), dbc.Col(self.create_status_card("Portfolio Value", "$100,000", "info"), width=3), dbc.Col(self.create_status_card("Daily P&L", "+$1,250", "success"), width=3), dbc.Col(self.create_status_card("Risk Level", "Low", "warning"), width=3) ], className="mb-4"), # Charts row dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Price Chart"), dbc.CardBody([ dcc.Graph(id="price-chart", style={"height": "400px"}) ]) ]) ], width=8), dbc.Col([ dbc.Card([ dbc.CardHeader("Portfolio Allocation"), dbc.CardBody([ dcc.Graph(id="allocation-chart", style={"height": "400px"}) ]) ]) ], width=4) ], className="mb-4"), # Trading activity and alerts dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Recent Trades"), dbc.CardBody([ html.Div(id="trades-table") ]) ]) ], width=6), dbc.Col([ dbc.Card([ dbc.CardHeader("System Alerts"), dbc.CardBody([ html.Div(id="alerts-list") ]) ]) ], width=6) ]) ]) def create_data_tab(self): """Create the data management tab""" return dbc.Container([ dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Data Configuration"), dbc.CardBody([ dbc.Row([ dbc.Col([ dbc.Label("Data Source"), dbc.Select( id="data-source-select", options=[ {"label": "CSV File", "value": "csv"}, {"label": "Alpaca API", "value": "alpaca"}, {"label": "Synthetic Data", "value": "synthetic"} ], value="csv" ) ], width=4), dbc.Col([ dbc.Label("Symbol"), dbc.Input( id="symbol-input", type="text", value="AAPL", placeholder="Enter symbol" ) ], width=4), dbc.Col([ dbc.Label("Timeframe"), dbc.Select( id="timeframe-select", options=[ {"label": "1 Minute", "value": "1m"}, {"label": "5 Minutes", "value": "5m"}, {"label": "15 Minutes", "value": "15m"}, {"label": "1 Hour", "value": "1h"}, {"label": "1 Day", "value": "1d"} ], value="1m" ) ], width=4) ], className="mb-3"), dbc.Row([ dbc.Col([ dbc.Button("Load Data", id="load-data-btn", color="primary", className="me-2"), dbc.Button("Refresh Data", id="refresh-data-btn", color="secondary") ]) ]) ]) ]) ], width=6), dbc.Col([ dbc.Card([ dbc.CardHeader("Data Statistics"), dbc.CardBody([ html.Div(id="data-stats") ]) ]) ], width=6) ], className="mb-4"), # Data visualization dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader([ html.Span("Market Data Visualization"), dbc.ButtonGroup([ dbc.Button("Candlestick", id="candlestick-btn", size="sm"), dbc.Button("Line", id="line-btn", size="sm"), dbc.Button("Volume", id="volume-btn", size="sm") ], className="float-end") ]), dbc.CardBody([ dcc.Graph(id="market-chart", style={"height": "500px"}) ]) ]) ]) ]) ]) def create_trading_tab(self): """Create the trading controls tab""" return dbc.Container([ # Trading configuration dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Trading Configuration"), dbc.CardBody([ dbc.Row([ dbc.Col([ dbc.Label("Capital"), dbc.Input( id="capital-input", type="number", value=100000, step=1000 ) ], width=3), dbc.Col([ dbc.Label("Order Size"), dbc.Input( id="order-size-input", type="number", value=10, step=1 ) ], width=3), dbc.Col([ dbc.Label("Max Position"), dbc.Input( id="max-position-input", type="number", value=100, step=10 ) ], width=3), dbc.Col([ dbc.Label("Max Drawdown"), dbc.Input( id="max-drawdown-input", type="number", value=0.05, step=0.01, min=0, max=1 ) ], width=3) ], className="mb-3"), dbc.Row([ dbc.Col([ dbc.Button("Start Trading", id="start-trading-btn", color="success", className="me-2"), dbc.Button("Stop Trading", id="stop-trading-btn", color="danger", className="me-2"), dbc.Button("Emergency Stop", id="emergency-stop-btn", color="warning") ]) ]) ]) ]) ], width=6), dbc.Col([ dbc.Card([ dbc.CardHeader("Alpaca Connection"), dbc.CardBody([ dbc.Row([ dbc.Col([ dbc.Label("API Key"), dbc.Input( id="alpaca-api-key", type="password", placeholder="Enter Alpaca API key" ) ], width=6), dbc.Col([ dbc.Label("Secret Key"), dbc.Input( id="alpaca-secret-key", type="password", placeholder="Enter Alpaca secret key" ) ], width=6) ], className="mb-3"), dbc.Row([ dbc.Col([ dbc.Button("Connect", id="connect-alpaca-btn", color="primary", className="me-2"), dbc.Button("Disconnect", id="disconnect-alpaca-btn", color="secondary") ]) ]) ]) ]) ], width=6) ], className="mb-4"), # Trading activity dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Live Trading Activity"), dbc.CardBody([ html.Div(id="trading-activity") ]) ]) ]) ]) ]) def create_analytics_tab(self): """Create the analytics tab""" return dbc.Container([ # FinRL training dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("FinRL Model Training"), dbc.CardBody([ dbc.Row([ dbc.Col([ dbc.Label("Algorithm"), dbc.Select( id="finrl-algorithm-select", options=[ {"label": "PPO", "value": "PPO"}, {"label": "A2C", "value": "A2C"}, {"label": "DDPG", "value": "DDPG"}, {"label": "TD3", "value": "TD3"} ], value="PPO" ) ], width=3), dbc.Col([ dbc.Label("Learning Rate"), dbc.Input( id="learning-rate-input", type="number", value=0.0003, step=0.0001, min=0.0001, max=0.01 ) ], width=3), dbc.Col([ dbc.Label("Training Steps"), dbc.Input( id="training-steps-input", type="number", value=100000, step=1000 ) ], width=3), dbc.Col([ dbc.Label("Batch Size"), dbc.Select( id="batch-size-select", options=[ {"label": "32", "value": 32}, {"label": "64", "value": 64}, {"label": "128", "value": 128}, {"label": "256", "value": 256} ], value=64 ) ], width=3) ], className="mb-3"), dbc.Row([ dbc.Col([ dbc.Button("Start Training", id="start-training-btn", color="primary", className="me-2"), dbc.Button("Stop Training", id="stop-training-btn", color="danger") ]) ]) ]) ]) ], width=6), dbc.Col([ dbc.Card([ dbc.CardHeader("Training Progress"), dbc.CardBody([ dbc.Progress(id="training-progress", value=0, className="mb-3"), html.Div(id="training-metrics") ]) ]) ], width=6) ], className="mb-4"), # Backtesting dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Strategy Backtesting"), dbc.CardBody([ dbc.Row([ dbc.Col([ dbc.Button("Run Backtest", id="run-backtest-btn", color="primary", className="me-2"), dbc.Button("Export Results", id="export-backtest-btn", color="secondary") ]) ]), html.Div(id="backtest-results") ]) ]) ]) ]) ]) def create_portfolio_tab(self): """Create the portfolio management tab""" return dbc.Container([ # Portfolio overview dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Portfolio Overview"), dbc.CardBody([ dbc.Row([ dbc.Col([ html.H4("Total Value", className="text-muted"), html.H3(id="total-value", children="$100,000") ], width=3), dbc.Col([ html.H4("Cash", className="text-muted"), html.H3(id="cash-value", children="$25,000") ], width=3), dbc.Col([ html.H4("Invested", className="text-muted"), html.H3(id="invested-value", children="$75,000") ], width=3), dbc.Col([ html.H4("P&L", className="text-muted"), html.H3(id="pnl-value", children="+$1,250", className="text-success") ], width=3) ]) ]) ]) ]) ], className="mb-4"), # Positions and allocation dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("Current Positions"), dbc.CardBody([ html.Div(id="positions-table") ]) ]) ], width=8), dbc.Col([ dbc.Card([ dbc.CardHeader("Allocation Chart"), dbc.CardBody([ dcc.Graph(id="portfolio-allocation-chart", style={"height": "300px"}) ]) ]) ], width=4) ]) ]) def create_settings_tab(self): """Create the settings tab""" return dbc.Container([ dbc.Row([ dbc.Col([ dbc.Card([ dbc.CardHeader("System Configuration"), dbc.CardBody([ dbc.Row([ dbc.Col([ dbc.Label("Config File"), dbc.Input( id="config-file-input", type="text", value="config.yaml", placeholder="Enter config file path" ) ], width=6), dbc.Col([ dbc.Label("Log Level"), dbc.Select( id="log-level-select", options=[ {"label": "DEBUG", "value": "DEBUG"}, {"label": "INFO", "value": "INFO"}, {"label": "WARNING", "value": "WARNING"}, {"label": "ERROR", "value": "ERROR"} ], value="INFO" ) ], width=6) ], className="mb-3"), dbc.Row([ dbc.Col([ dbc.Button("Load Config", id="load-config-btn", color="primary", className="me-2"), dbc.Button("Save Config", id="save-config-btn", color="success") ]) ]) ]) ]) ], width=6), dbc.Col([ dbc.Card([ dbc.CardHeader("System Status"), dbc.CardBody([ html.Div(id="system-status") ]) ]) ], width=6) ]) ]) def create_status_card(self, title, value, color): """Create a status card component""" return dbc.Card([ dbc.CardBody([ html.H5(title, className="card-title text-muted"), html.H3(value, className=f"text-{color}") ]) ]) def setup_callbacks(self): """Setup all Dash callbacks""" @self.app.callback( Output("config-store", "data"), Input("load-config-btn", "n_clicks"), State("config-file-input", "value"), prevent_initial_call=True ) def load_configuration(n_clicks, config_file): if n_clicks: try: config = load_config(config_file) return config except Exception as e: return {"error": str(e)} return dash.no_update @self.app.callback( Output("data-store", "data"), Input("load-data-btn", "n_clicks"), State("config-store", "data"), prevent_initial_call=True ) def load_market_data(n_clicks, config): if n_clicks and config: try: data = load_data(config) if data is not None: return data.to_dict('records') except Exception as e: return {"error": str(e)} return dash.no_update @self.app.callback( Output("price-chart", "figure"), Input("data-store", "data"), Input("interval-component", "n_intervals") ) def update_price_chart(data, n_intervals): if data and isinstance(data, list): df = pd.DataFrame(data) if not df.empty: fig = go.Figure(data=[go.Candlestick( x=df['timestamp'], open=df['open'], high=df['high'], low=df['low'], close=df['close'] )]) fig.update_layout( title="Market Data", xaxis_title="Date", yaxis_title="Price ($)", height=400 ) return fig return go.Figure() @self.app.callback( Output("allocation-chart", "figure"), Input("alpaca-store", "data"), Input("interval-component", "n_intervals") ) def update_allocation_chart(alpaca_data, n_intervals): # Mock portfolio allocation data labels = ['AAPL', 'GOOGL', 'MSFT', 'TSLA', 'Cash'] values = [30, 25, 20, 15, 10] fig = go.Figure(data=[go.Pie(labels=labels, values=values)]) fig.update_layout( title="Portfolio Allocation", height=400 ) return fig @self.app.callback( Output("trading-activity", "children"), Input("interval-component", "n_intervals") ) def update_trading_activity(n_intervals): # Mock trading activity trades = [ {"time": "09:30:15", "symbol": "AAPL", "action": "BUY", "quantity": 10, "price": 150.25}, {"time": "09:35:22", "symbol": "GOOGL", "action": "SELL", "quantity": 5, "price": 2750.50}, {"time": "09:40:08", "symbol": "MSFT", "action": "BUY", "quantity": 15, "price": 320.75} ] table_rows = [] for trade in trades: color = "success" if trade["action"] == "BUY" else "danger" table_rows.append( dbc.Row([ dbc.Col(trade["time"], width=2), dbc.Col(trade["symbol"], width=2), dbc.Col(trade["action"], width=2, className=f"text-{color}"), dbc.Col(str(trade["quantity"]), width=2), dbc.Col(f"${trade['price']:.2f}", width=2), dbc.Col(f"${trade['quantity'] * trade['price']:.2f}", width=2) ], className="mb-2") ) return table_rows
def create_dash_app(): """Create and return the Dash application""" app = TradingDashApp() return app.app
if __name__ == "__main__": app = create_dash_app() app.run_server(debug=True, host="0.0.0.0", port=8050) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556"""Jupyter Widgets UI for Algorithmic Trading System
Interactive notebook interface for:- Data exploration and visualization- Strategy development and testing- Model training and evaluation- Real-time trading simulation"""
import ipywidgets as widgetsfrom IPython.display import display, HTML, clear_outputimport plotly.graph_objects as goimport plotly.express as pximport pandas as pdimport numpy as npimport yamlimport osimport sysfrom datetime import datetime, timedeltafrom typing import Dict, Any, Optionalimport asyncioimport threadingimport time
# Add project root to pathsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from agentic_ai_system.main import load_configfrom agentic_ai_system.data_ingestion import load_data, validate_data, add_technical_indicatorsfrom agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfigfrom agentic_ai_system.alpaca_broker import AlpacaBrokerfrom agentic_ai_system.orchestrator import run_backtest, run_live_trading
class TradingJupyterUI: def __init__(self): self.config = None self.data = None self.alpaca_broker = None self.finrl_agent = None self.trading_active = False self.setup_widgets() def setup_widgets(self): """Setup all interactive widgets""" # Configuration widgets self.config_file = widgets.Text( value='config.yaml', description='Config File:', style={'description_width': '120px'} ) self.load_config_btn = widgets.Button( description='Load Configuration', button_style='primary', icon='cog' ) self.config_output = widgets.Output() # Data widgets self.data_source = widgets.Dropdown( options=['csv', 'alpaca', 'synthetic'], value='csv', description='Data Source:', style={'description_width': '120px'} ) self.symbol_input = widgets.Text( value='AAPL', description='Symbol:', style={'description_width': '120px'} ) self.timeframe_input = widgets.Dropdown( options=['1m', '5m', '15m', '1h', '1d'], value='1m', description='Timeframe:', style={'description_width': '120px'} ) self.load_data_btn = widgets.Button( description='Load Data', button_style='success', icon='database' ) self.data_output = widgets.Output() # Alpaca widgets self.alpaca_api_key = widgets.Password( description='API Key:', style={'description_width': '120px'} ) self.alpaca_secret_key = widgets.Password( description='Secret Key:', style={'description_width': '120px'} ) self.connect_alpaca_btn = widgets.Button( description='Connect to Alpaca', button_style='info', icon='link' ) self.alpaca_output = widgets.Output() # FinRL widgets self.finrl_algorithm = widgets.Dropdown( options=['PPO', 'A2C', 'DDPG', 'TD3'], value='PPO', description='Algorithm:', style={'description_width': '120px'} ) self.learning_rate = widgets.FloatSlider( value=0.0003, min=0.0001, max=0.01, step=0.0001, description='Learning Rate:', style={'description_width': '120px'}, readout_format='.4f' ) self.training_steps = widgets.IntSlider( value=100000, min=1000, max=1000000, step=1000, description='Training Steps:', style={'description_width': '120px'} ) self.batch_size = widgets.Dropdown( options=[32, 64, 128, 256], value=64, description='Batch Size:', style={'description_width': '120px'} ) self.start_training_btn = widgets.Button( description='Start Training', button_style='warning', icon='play' ) self.finrl_output = widgets.Output() # Trading widgets self.capital_input = widgets.IntText( value=100000, description='Capital ($):', style={'description_width': '120px'} ) self.order_size_input = widgets.IntText( value=10, description='Order Size:', style={'description_width': '120px'} ) self.start_trading_btn = widgets.Button( description='Start Trading', button_style='danger', icon='rocket' ) self.stop_trading_btn = widgets.Button( description='Stop Trading', button_style='danger', icon='stop' ) self.trading_output = widgets.Output() # Backtesting widgets self.run_backtest_btn = widgets.Button( description='Run Backtest', button_style='primary', icon='chart-line' ) self.backtest_output = widgets.Output() # Chart widgets self.chart_type = widgets.Dropdown( options=['Candlestick', 'Line', 'Volume', 'Technical Indicators'], value='Candlestick', description='Chart Type:', style={'description_width': '120px'} ) self.chart_output = widgets.Output() # Setup callbacks self.load_config_btn.on_click(self.on_load_config) self.load_data_btn.on_click(self.on_load_data) self.connect_alpaca_btn.on_click(self.on_connect_alpaca) self.start_training_btn.on_click(self.on_start_training) self.start_trading_btn.on_click(self.on_start_trading) self.stop_trading_btn.on_click(self.on_stop_trading) self.run_backtest_btn.on_click(self.on_run_backtest) self.chart_type.observe(self.on_chart_type_change, names='value') def on_load_config(self, b): """Handle configuration loading""" with self.config_output: clear_output() try: self.config = load_config(self.config_file.value) print(f"β
Configuration loaded from {self.config_file.value}") print(f"Symbol: {self.config['trading']['symbol']}") print(f"Capital: ${self.config['trading']['capital']:,}") print(f"Timeframe: {self.config['trading']['timeframe']}") print(f"Broker: {self.config['execution']['broker_api']}") except Exception as e: print(f"β Error loading configuration: {e}") def on_load_data(self, b): """Handle data loading""" with self.data_output: clear_output() try: if self.config: # Update config with widget values self.config['data_source']['type'] = self.data_source.value self.config['trading']['symbol'] = self.symbol_input.value self.config['trading']['timeframe'] = self.timeframe_input.value print(f"Loading data for {self.symbol_input.value}...") self.data = load_data(self.config) if self.data is not None and not self.data.empty: print(f"β
Loaded {len(self.data)} data points") print(f"Date range: {self.data['timestamp'].min()} to {self.data['timestamp'].max()}") print(f"Price range: ${self.data['close'].min():.2f} - ${self.data['close'].max():.2f}") # Add technical indicators self.data = add_technical_indicators(self.data) print(f"β
Added technical indicators") # Update chart self.update_chart() else: print("β Failed to load data") else: print("β οΈ Please load configuration first") except Exception as e: print(f"β Error loading data: {e}") def on_connect_alpaca(self, b): """Handle Alpaca connection""" with self.alpaca_output: clear_output() try: if self.alpaca_api_key.value and self.alpaca_secret_key.value: # Update config with API keys if self.config: self.config['alpaca']['api_key'] = self.alpaca_api_key.value self.config['alpaca']['secret_key'] = self.alpaca_secret_key.value self.config['execution']['broker_api'] = 'alpaca_paper' print("Connecting to Alpaca...") self.alpaca_broker = AlpacaBroker(self.config) account_info = self.alpaca_broker.get_account_info() if account_info: print("β
Connected to Alpaca") print(f"Account ID: {account_info['account_id']}") print(f"Status: {account_info['status']}") print(f"Buying Power: ${account_info['buying_power']:,.2f}") print(f"Portfolio Value: ${account_info['portfolio_value']:,.2f}") else: print("β Failed to connect to Alpaca") else: print("β οΈ Please load configuration first") else: print("β οΈ Please enter Alpaca API credentials") except Exception as e: print(f"β Error connecting to Alpaca: {e}") def on_start_training(self, b): """Handle FinRL training""" with self.finrl_output: clear_output() try: if self.data is not None: print("Starting FinRL training...") # Create FinRL config finrl_config = FinRLConfig( algorithm=self.finrl_algorithm.value, learning_rate=self.learning_rate.value, batch_size=self.batch_size.value, buffer_size=1000000, learning_starts=100, gamma=0.99, tau=0.005, train_freq=1, gradient_steps=1, verbose=1, tensorboard_log='logs/finrl_tensorboard' ) # Initialize agent self.finrl_agent = FinRLAgent(finrl_config) # Train the agent result = self.finrl_agent.train( data=self.data, config=self.config, total_timesteps=self.training_steps.value, use_real_broker=False ) if result['success']: print("β
Training completed successfully!") print(f"Algorithm: {result['algorithm']}") print(f"Timesteps: {result['total_timesteps']:,}") print(f"Model saved: {result['model_path']}") else: print("β Training failed") else: print("β οΈ Please load data first") except Exception as e: print(f"β Error during training: {e}") def on_start_trading(self, b): """Handle trading start""" with self.trading_output: clear_output() try: if self.config and self.alpaca_broker: print("Starting live trading...") self.trading_active = True # Update config with widget values self.config['trading']['capital'] = self.capital_input.value self.config['execution']['order_size'] = self.order_size_input.value # Start trading in background thread def run_trading(): try: run_live_trading(self.config, self.data) except Exception as e: print(f"Trading error: {e}") trading_thread = threading.Thread(target=run_trading) trading_thread.daemon = True trading_thread.start() print("β
Live trading started") else: print("β οΈ Please load configuration and connect to Alpaca first") except Exception as e: print(f"β Error starting trading: {e}") def on_stop_trading(self, b): """Handle trading stop""" with self.trading_output: clear_output() self.trading_active = False print("β
Trading stopped") def on_run_backtest(self, b): """Handle backtesting""" with self.backtest_output: clear_output() try: if self.config and self.data is not None: print("Running backtest...") # Update config with widget values self.config['trading']['capital'] = self.capital_input.value result = run_backtest(self.config, self.data) if result['success']: print("β
Backtest completed") print(f"Total Return: {result['total_return']:.2%}") print(f"Sharpe Ratio: {result['sharpe_ratio']:.2f}") print(f"Max Drawdown: {result['max_drawdown']:.2%}") print(f"Total Trades: {result['total_trades']}") else: print("β Backtest failed") else: print("β οΈ Please load configuration and data first") except Exception as e: print(f"β Error during backtest: {e}") def on_chart_type_change(self, change): """Handle chart type change""" if self.data is not None: self.update_chart() def update_chart(self): """Update the chart display""" with self.chart_output: clear_output() if self.data is None: return if self.chart_type.value == "Candlestick": fig = go.Figure(data=[go.Candlestick( x=self.data['timestamp'], open=self.data['open'], high=self.data['high'], low=self.data['low'], close=self.data['close'] )]) fig.update_layout( title=f"{self.config['trading']['symbol']} Candlestick Chart", xaxis_title="Date", yaxis_title="Price ($)", height=500 ) display(fig) elif self.chart_type.value == "Line": fig = px.line(self.data, x='timestamp', y='close', title=f"{self.config['trading']['symbol']} Price Chart") fig.update_layout(height=500) display(fig) elif self.chart_type.value == "Volume": fig = go.Figure() fig.add_trace(go.Bar( x=self.data['timestamp'], y=self.data['volume'], name='Volume' )) fig.update_layout( title=f"{self.config['trading']['symbol']} Volume Chart", xaxis_title="Date", yaxis_title="Volume", height=500 ) display(fig) elif self.chart_type.value == "Technical Indicators": fig = go.Figure() # Add price fig.add_trace(go.Scatter( x=self.data['timestamp'], y=self.data['close'], name='Close Price', line=dict(color='blue') )) # Add moving averages if available if 'sma_20' in self.data.columns: fig.add_trace(go.Scatter( x=self.data['timestamp'], y=self.data['sma_20'], name='SMA 20', line=dict(color='orange') )) if 'sma_50' in self.data.columns: fig.add_trace(go.Scatter( x=self.data['timestamp'], y=self.data['sma_50'], name='SMA 50', line=dict(color='red') )) fig.update_layout( title=f"{self.config['trading']['symbol']} Technical Indicators", xaxis_title="Date", yaxis_title="Price ($)", height=500 ) display(fig) def display_interface(self): """Display the complete Jupyter interface""" # Header display(HTML(""" <div style="text-align: center; margin-bottom: 20px;"> <h1>π€ Algorithmic Trading System</h1> <p>Interactive Jupyter Interface for Trading Analysis</p> </div> """)) # Configuration section display(HTML("<h2>βοΈ Configuration</h2>")) config_widgets = widgets.VBox([ widgets.HBox([self.config_file, self.load_config_btn]), self.config_output ]) display(config_widgets) # Data section display(HTML("<h2>π₯ Data Management</h2>")) data_widgets = widgets.VBox([ widgets.HBox([self.data_source, self.symbol_input, self.timeframe_input]), widgets.HBox([self.load_data_btn]), self.data_output ]) display(data_widgets) # Alpaca section display(HTML("<h2>π¦ Alpaca Integration</h2>")) alpaca_widgets = widgets.VBox([ widgets.HBox([self.alpaca_api_key, self.alpaca_secret_key]), widgets.HBox([self.connect_alpaca_btn]), self.alpaca_output ]) display(alpaca_widgets) # FinRL section display(HTML("<h2>π§ FinRL Training</h2>")) finrl_widgets = widgets.VBox([ widgets.HBox([self.finrl_algorithm, self.learning_rate]), widgets.HBox([self.training_steps, self.batch_size]), widgets.HBox([self.start_training_btn]), self.finrl_output ]) display(finrl_widgets) # Trading section display(HTML("<h2>π― Trading Controls</h2>")) trading_widgets = widgets.VBox([ widgets.HBox([self.capital_input, self.order_size_input]), widgets.HBox([self.start_trading_btn, self.stop_trading_btn]), self.trading_output ]) display(trading_widgets) # Backtesting section display(HTML("<h2>π Backtesting</h2>")) backtest_widgets = widgets.VBox([ widgets.HBox([self.run_backtest_btn]), self.backtest_output ]) display(backtest_widgets) # Chart section display(HTML("<h2>π Data Visualization</h2>")) chart_widgets = widgets.VBox([ widgets.HBox([self.chart_type]), self.chart_output ]) display(chart_widgets)
def create_jupyter_interface(): """Create and return the Jupyter interface""" ui = TradingJupyterUI() return ui 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679"""Streamlit UI for Algorithmic Trading System
A comprehensive web interface for:- Real-time market data visualization- Trading strategy configuration- FinRL model training and evaluation- Portfolio management- Risk monitoring"""
import streamlit as stimport plotly.graph_objects as goimport plotly.express as pximport pandas as pdimport numpy as npimport yamlimport osimport sysfrom datetime import datetime, timedeltafrom typing import Dict, Any, Optionalimport asyncioimport threadingimport time
# Add project root to pathsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from agentic_ai_system.main import load_configfrom agentic_ai_system.data_ingestion import load_data, validate_data, add_technical_indicatorsfrom agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfigfrom agentic_ai_system.alpaca_broker import AlpacaBrokerfrom agentic_ai_system.orchestrator import run_backtest, run_live_trading
# Page configurationst.set_page_config( page_title="Algorithmic Trading System", page_icon="π", layout="wide", initial_sidebar_state="expanded")
# Custom CSS for better stylingst.markdown("""<style> .main-header { font-size: 2.5rem; font-weight: bold; color: #1f77b4; text-align: center; margin-bottom: 2rem; } .metric-card { background-color: #f0f2f6; padding: 1rem; border-radius: 0.5rem; border-left: 4px solid #1f77b4; } .success-metric { border-left-color: #28a745; } .warning-metric { border-left-color: #ffc107; } .danger-metric { border-left-color: #dc3545; } .sidebar .sidebar-content { background-color: #f8f9fa; }</style>""", unsafe_allow_html=True)
class TradingUI: def __init__(self): self.config = None self.data = None self.alpaca_broker = None self.finrl_agent = None self.session_state = st.session_state # Initialize session state if 'trading_active' not in self.session_state: self.session_state.trading_active = False if 'current_portfolio' not in self.session_state: self.session_state.current_portfolio = {} if 'trading_history' not in self.session_state: self.session_state.trading_history = [] def load_configuration(self): """Load and display configuration""" st.sidebar.header("βοΈ Configuration") # Config file selector config_files = [f for f in os.listdir('.') if f.endswith('.yaml') or f.endswith('.yml')] selected_config = st.sidebar.selectbox( "Select Configuration File", config_files, index=0 if 'config.yaml' in config_files else 0 ) if st.sidebar.button("Load Configuration"): try: self.config = load_config(selected_config) st.sidebar.success(f"β
Configuration loaded: {selected_config}") return True except Exception as e: st.sidebar.error(f"β Error loading config: {e}") return False return False def display_system_status(self): """Display system status and metrics""" st.header("π System Status") col1, col2, col3, col4 = st.columns(4) with col1: st.metric( label="Trading Status", value="π’ Active" if self.session_state.trading_active else "π΄ Inactive", delta="Running" if self.session_state.trading_active else "Stopped" ) with col2: if self.config: st.metric( label="Capital", value=f"${self.config['trading']['capital']:,}", delta="Available" ) else: st.metric(label="Capital", value="Not Loaded") with col3: if self.alpaca_broker: try: account_info = self.alpaca_broker.get_account_info() if account_info: st.metric( label="Portfolio Value", value=f"${float(account_info['portfolio_value']):,.2f}", delta=f"{float(account_info['equity']) - float(account_info['portfolio_value']):,.2f}" ) except: st.metric(label="Portfolio Value", value="Not Connected") else: st.metric(label="Portfolio Value", value="Not Connected") with col4: if self.data is not None: st.metric( label="Data Points", value=f"{len(self.data):,}", delta=f"Latest: {self.data['timestamp'].max().strftime('%Y-%m-%d')}" ) else: st.metric(label="Data Points", value="Not Loaded") def data_ingestion_panel(self): """Data ingestion and visualization panel""" st.header("π₯ Data Ingestion") col1, col2 = st.columns([2, 1]) with col1: if self.config: if st.button("Load Market Data"): with st.spinner("Loading data..."): try: self.data = load_data(self.config) if self.data is not None and not self.data.empty: st.success(f"β
Loaded {len(self.data)} data points") # Add technical indicators self.data = add_technical_indicators(self.data) st.info(f"β
Added technical indicators") else: st.error("β Failed to load data") except Exception as e: st.error(f"β Error loading data: {e}") with col2: if self.data is not None: st.subheader("Data Summary") st.write(f"**Symbol:** {self.config['trading']['symbol']}") st.write(f"**Timeframe:** {self.config['trading']['timeframe']}") st.write(f"**Date Range:** {self.data['timestamp'].min().strftime('%Y-%m-%d')} to {self.data['timestamp'].max().strftime('%Y-%m-%d')}") st.write(f"**Price Range:** ${self.data['close'].min():.2f} - ${self.data['close'].max():.2f}") # Data visualization if self.data is not None: st.subheader("π Market Data Visualization") # Chart type selector chart_type = st.selectbox( "Chart Type", ["Candlestick", "Line", "OHLC", "Volume"] ) if chart_type == "Candlestick": fig = go.Figure(data=[go.Candlestick( x=self.data['timestamp'], open=self.data['open'], high=self.data['high'], low=self.data['low'], close=self.data['close'] )]) fig.update_layout( title=f"{self.config['trading']['symbol']} Candlestick Chart", xaxis_title="Date", yaxis_title="Price ($)", height=500 ) st.plotly_chart(fig, use_container_width=True) elif chart_type == "Line": fig = px.line(self.data, x='timestamp', y='close', title=f"{self.config['trading']['symbol']} Price Chart") fig.update_layout(height=500) st.plotly_chart(fig, use_container_width=True) elif chart_type == "Volume": fig = go.Figure() fig.add_trace(go.Bar( x=self.data['timestamp'], y=self.data['volume'], name='Volume' )) fig.update_layout( title=f"{self.config['trading']['symbol']} Volume Chart", xaxis_title="Date", yaxis_title="Volume", height=500 ) st.plotly_chart(fig, use_container_width=True) def alpaca_integration_panel(self): """Alpaca broker integration panel""" st.header("π¦ Alpaca Integration") col1, col2 = st.columns([1, 1]) with col1: if st.button("Connect to Alpaca"): if self.config and self.config['execution']['broker_api'] in ['alpaca_paper', 'alpaca_live']: with st.spinner("Connecting to Alpaca..."): try: self.alpaca_broker = AlpacaBroker(self.config) account_info = self.alpaca_broker.get_account_info() if account_info: st.success("β
Connected to Alpaca") self.session_state.alpaca_connected = True else: st.error("β Failed to connect to Alpaca") except Exception as e: st.error(f"β Connection error: {e}") else: st.warning("β οΈ Alpaca not configured in settings") with col2: if st.button("Disconnect from Alpaca"): self.alpaca_broker = None self.session_state.alpaca_connected = False st.success("β
Disconnected from Alpaca") # Account information display if self.alpaca_broker: st.subheader("Account Information") try: account_info = self.alpaca_broker.get_account_info() if account_info: col1, col2, col3 = st.columns(3) with col1: st.metric( label="Buying Power", value=f"${float(account_info['buying_power']):,.2f}" ) with col2: st.metric( label="Portfolio Value", value=f"${float(account_info['portfolio_value']):,.2f}" ) with col3: st.metric( label="Equity", value=f"${float(account_info['equity']):,.2f}" ) # Market hours market_hours = self.alpaca_broker.get_market_hours() if market_hours: status_color = "π’" if market_hours['is_open'] else "π΄" st.info(f"{status_color} Market Status: {'OPEN' if market_hours['is_open'] else 'CLOSED'}") if market_hours['next_open']: st.write(f"Next Open: {market_hours['next_open']}") if market_hours['next_close']: st.write(f"Next Close: {market_hours['next_close']}") # Current positions positions = self.alpaca_broker.get_positions() if positions: st.subheader("Current Positions") positions_df = pd.DataFrame(positions) st.dataframe(positions_df) else: st.info("No current positions") except Exception as e: st.error(f"Error fetching account info: {e}") def finrl_training_panel(self): """FinRL model training panel""" st.header("π§ FinRL Model Training") if not self.data is not None: st.warning("β οΈ Please load market data first") return col1, col2 = st.columns([2, 1]) with col1: st.subheader("Training Configuration") # Training parameters algorithm = st.selectbox( "Algorithm", ["PPO", "A2C", "DDPG", "TD3"], index=0 ) learning_rate = st.slider( "Learning Rate", min_value=0.0001, max_value=0.01, value=0.0003, step=0.0001, format="%.4f" ) total_timesteps = st.slider( "Total Timesteps", min_value=1000, max_value=1000000, value=100000, step=1000 ) batch_size = st.selectbox( "Batch Size", [32, 64, 128, 256], index=1 ) with col2: st.subheader("Training Controls") if st.button("Start Training", type="primary"): if self.data is not None: with st.spinner("Training FinRL model..."): try: # Create FinRL config finrl_config = FinRLConfig( algorithm=algorithm, learning_rate=learning_rate, batch_size=batch_size, buffer_size=1000000, learning_starts=100, gamma=0.99, tau=0.005, train_freq=1, gradient_steps=1, verbose=1, tensorboard_log='logs/finrl_tensorboard' ) # Initialize agent self.finrl_agent = FinRLAgent(finrl_config) # Train the agent result = self.finrl_agent.train( data=self.data, config=self.config, total_timesteps=total_timesteps, use_real_broker=False ) if result['success']: st.success("β
Training completed successfully!") st.write(f"Model saved: {result['model_path']}") self.session_state.model_trained = True else: st.error("β Training failed") except Exception as e: st.error(f"β Training error: {e}") # Training progress and metrics if hasattr(self.session_state, 'model_trained') and self.session_state.model_trained: st.subheader("Model Performance") if st.button("Evaluate Model"): if self.finrl_agent: with st.spinner("Evaluating model..."): try: # Use last 100 data points for evaluation eval_data = self.data.tail(100) prediction_result = self.finrl_agent.predict( data=eval_data, config=self.config, use_real_broker=False ) if prediction_result['success']: col1, col2, col3 = st.columns(3) with col1: st.metric( label="Initial Value", value=f"${prediction_result['initial_value']:,.2f}" ) with col2: st.metric( label="Final Value", value=f"${prediction_result['final_value']:,.2f}" ) with col3: return_pct = prediction_result['total_return'] * 100 st.metric( label="Total Return", value=f"{return_pct:.2f}%", delta=f"{return_pct:.2f}%" ) st.write(f"Total Trades: {prediction_result['total_trades']}") else: st.error("β Model evaluation failed") except Exception as e: st.error(f"β Evaluation error: {e}") def trading_controls_panel(self): """Trading controls and execution panel""" st.header("π― Trading Controls") col1, col2 = st.columns([1, 1]) with col1: st.subheader("Backtesting") if st.button("Run Backtest"): if self.data is not None and self.config: with st.spinner("Running backtest..."): try: result = run_backtest(self.config, self.data) if result['success']: st.success("β
Backtest completed") # Display backtest results col1, col2, col3 = st.columns(3) with col1: st.metric( label="Total Return", value=f"{result['total_return']:.2%}" ) with col2: st.metric( label="Sharpe Ratio", value=f"{result['sharpe_ratio']:.2f}" ) with col3: st.metric( label="Max Drawdown", value=f"{result['max_drawdown']:.2%}" ) # Store results in session state self.session_state.backtest_results = result else: st.error("β Backtest failed") except Exception as e: st.error(f"β Backtest error: {e}") with col2: st.subheader("Live Trading") if st.button("Start Live Trading", type="primary"): if self.config and self.alpaca_broker: self.session_state.trading_active = True st.success("β
Live trading started") # Start trading in background thread def run_trading(): try: run_live_trading(self.config, self.data) except Exception as e: st.error(f"Trading error: {e}") trading_thread = threading.Thread(target=run_trading) trading_thread.daemon = True trading_thread.start() else: st.warning("β οΈ Please configure Alpaca connection first") if st.button("Stop Live Trading"): self.session_state.trading_active = False st.success("β
Live trading stopped") def portfolio_monitoring_panel(self): """Portfolio monitoring and analytics panel""" st.header("π Portfolio Monitoring") if not self.alpaca_broker: st.warning("β οΈ Connect to Alpaca to view portfolio") return try: # Portfolio overview account_info = self.alpaca_broker.get_account_info() if account_info: col1, col2, col3, col4 = st.columns(4) with col1: st.metric( label="Total Value", value=f"${float(account_info['portfolio_value']):,.2f}" ) with col2: st.metric( label="Cash", value=f"${float(account_info['cash']):,.2f}" ) with col3: st.metric( label="Buying Power", value=f"${float(account_info['buying_power']):,.2f}" ) with col4: equity = float(account_info['equity']) portfolio_value = float(account_info['portfolio_value']) pnl = equity - portfolio_value st.metric( label="P&L", value=f"${pnl:,.2f}", delta=f"{pnl:,.2f}" ) # Positions table positions = self.alpaca_broker.get_positions() if positions: st.subheader("Current Positions") positions_df = pd.DataFrame(positions) if not positions_df.empty: # Calculate additional metrics positions_df['market_value'] = positions_df['quantity'].astype(float) * positions_df['current_price'].astype(float) positions_df['unrealized_pl'] = positions_df['unrealized_pl'].astype(float) positions_df['unrealized_plpc'] = positions_df['unrealized_plpc'].astype(float) # Display positions st.dataframe( positions_df[['symbol', 'quantity', 'current_price', 'market_value', 'unrealized_pl', 'unrealized_plpc']], use_container_width=True ) # Position chart fig = px.pie( positions_df, values='market_value', names='symbol', title="Portfolio Allocation" ) st.plotly_chart(fig, use_container_width=True) else: st.info("No positions found") else: st.info("No current positions") except Exception as e: st.error(f"Error fetching portfolio data: {e}") def run(self): """Main UI application""" # Header st.markdown('<h1 class="main-header">π€ Algorithmic Trading System</h1>', unsafe_allow_html=True) # Load configuration if self.load_configuration(): self.config = load_config('config.yaml') # Sidebar navigation st.sidebar.title("Navigation") page = st.sidebar.selectbox( "Select Page", ["Dashboard", "Data Ingestion", "Alpaca Integration", "FinRL Training", "Trading Controls", "Portfolio Monitoring"] ) # Display system status self.display_system_status() # Page routing if page == "Dashboard": st.header("π Dashboard") if self.config: st.subheader("System Configuration") config_col1, config_col2 = st.columns(2) with config_col1: st.write(f"**Symbol:** {self.config['trading']['symbol']}") st.write(f"**Capital:** ${self.config['trading']['capital']:,}") st.write(f"**Timeframe:** {self.config['trading']['timeframe']}") with config_col2: st.write(f"**Broker:** {self.config['execution']['broker_api']}") st.write(f"**FinRL Algorithm:** {self.config['finrl']['algorithm']}") st.write(f"**Risk Max Drawdown:** {self.config['risk']['max_drawdown']:.1%}") # Quick actions st.subheader("Quick Actions") col1, col2, col3 = st.columns(3) with col1: if st.button("Load Data", type="primary"): if self.config: with st.spinner("Loading data..."): self.data = load_data(self.config) if self.data is not None: st.success("β
Data loaded successfully") with col2: if st.button("Connect Alpaca"): if self.config and self.config['execution']['broker_api'] in ['alpaca_paper', 'alpaca_live']: with st.spinner("Connecting..."): self.alpaca_broker = AlpacaBroker(self.config) st.success("β
Connected to Alpaca") with col3: if st.button("Start Training"): if self.data is not None: st.info("Navigate to FinRL Training page to configure and start training") elif page == "Data Ingestion": self.data_ingestion_panel() elif page == "Alpaca Integration": self.alpaca_integration_panel() elif page == "FinRL Training": self.finrl_training_panel() elif page == "Trading Controls": self.trading_controls_panel() elif page == "Portfolio Monitoring": self.portfolio_monitoring_panel()
def main(): """Main application entry point""" ui = TradingUI() ui.run()
if __name__ == "__main__": main() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461"""WebSocket Server for Real-time Trading Data
Provides real-time updates for:- Market data streaming- Trading signals- Portfolio updates- System alerts"""
import asyncioimport websocketsimport jsonimport loggingimport threadingimport timefrom datetime import datetime, timedeltafrom typing import Dict, Any, List, Optionalimport pandas as pdimport osimport sys
# Add project root to pathsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from agentic_ai_system.main import load_configfrom agentic_ai_system.data_ingestion import load_data, add_technical_indicatorsfrom agentic_ai_system.alpaca_broker import AlpacaBrokerfrom agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfig
class TradingWebSocketServer: def __init__(self, host="localhost", port=8765): self.host = host self.port = port self.clients = set() self.config = None self.alpaca_broker = None self.finrl_agent = None self.trading_active = False self.market_data = None self.portfolio_data = {} # Setup logging logging.basicConfig(level=logging.INFO) self.logger = logging.getLogger(__name__) async def register(self, websocket): """Register a new client""" self.clients.add(websocket) self.logger.info(f"Client connected. Total clients: {len(self.clients)}") # Send initial data await self.send_initial_data(websocket) async def unregister(self, websocket): """Unregister a client""" self.clients.remove(websocket) self.logger.info(f"Client disconnected. Total clients: {len(self.clients)}") async def send_initial_data(self, websocket): """Send initial data to new client""" initial_data = { "type": "initial_data", "timestamp": datetime.now().isoformat(), "config": self.config, "portfolio": self.portfolio_data, "trading_status": self.trading_active } await websocket.send(json.dumps(initial_data)) async def broadcast(self, message): """Broadcast message to all connected clients""" if self.clients: message_str = json.dumps(message) await asyncio.gather( *[client.send(message_str) for client in self.clients], return_exceptions=True ) async def handle_market_data(self): """Handle real-time market data updates""" while True: try: if self.config and self.alpaca_broker: # Get real-time market data symbol = self.config['trading']['symbol'] # Get current price current_price = await self.get_current_price(symbol) if current_price: market_update = { "type": "market_data", "timestamp": datetime.now().isoformat(), "symbol": symbol, "price": current_price, "volume": await self.get_current_volume(symbol) } await self.broadcast(market_update) self.logger.info(f"Broadcasted market data for {symbol}: ${current_price}") await asyncio.sleep(1) # Update every second except Exception as e: self.logger.error(f"Error in market data handler: {e}") await asyncio.sleep(5) # Wait before retrying async def handle_portfolio_updates(self): """Handle portfolio updates""" while True: try: if self.alpaca_broker: # Get portfolio information account_info = self.alpaca_broker.get_account_info() positions = self.alpaca_broker.get_positions() if account_info: portfolio_update = { "type": "portfolio_update", "timestamp": datetime.now().isoformat(), "account": { "buying_power": float(account_info['buying_power']), "portfolio_value": float(account_info['portfolio_value']), "equity": float(account_info['equity']), "cash": float(account_info['cash']) }, "positions": positions if positions else [] } await self.broadcast(portfolio_update) self.portfolio_data = portfolio_update await asyncio.sleep(5) # Update every 5 seconds except Exception as e: self.logger.error(f"Error in portfolio updates: {e}") await asyncio.sleep(10) # Wait before retrying async def handle_trading_signals(self): """Handle trading signals from FinRL agent""" while True: try: if self.trading_active and self.finrl_agent and self.market_data is not None: # Generate trading signals signal = await self.generate_trading_signal() if signal: signal_update = { "type": "trading_signal", "timestamp": datetime.now().isoformat(), "signal": signal } await self.broadcast(signal_update) self.logger.info(f"Broadcasted trading signal: {signal}") await asyncio.sleep(10) # Generate signals every 10 seconds except Exception as e: self.logger.error(f"Error in trading signals: {e}") await asyncio.sleep(30) # Wait before retrying async def get_current_price(self, symbol): """Get current price for symbol""" try: if self.alpaca_broker: # Get latest price from Alpaca latest_trade = self.alpaca_broker.get_latest_trade(symbol) if latest_trade: return float(latest_trade['p']) return None except Exception as e: self.logger.error(f"Error getting current price: {e}") return None async def get_current_volume(self, symbol): """Get current volume for symbol""" try: if self.alpaca_broker: # Get latest trade volume latest_trade = self.alpaca_broker.get_latest_trade(symbol) if latest_trade: return int(latest_trade['s']) return None except Exception as e: self.logger.error(f"Error getting current volume: {e}") return None async def generate_trading_signal(self): """Generate trading signal using FinRL agent""" try: if self.finrl_agent and self.market_data is not None: # Use recent data for prediction recent_data = self.market_data.tail(100) prediction_result = self.finrl_agent.predict( data=recent_data, config=self.config, use_real_broker=False ) if prediction_result['success']: # Generate signal based on prediction current_price = await self.get_current_price(self.config['trading']['symbol']) if current_price: signal = { "action": "HOLD", # Default action "confidence": 0.5, "price": current_price, "reasoning": "Model prediction" } # Determine action based on prediction if prediction_result['total_return'] > 0.02: # 2% positive return signal["action"] = "BUY" signal["confidence"] = min(0.9, 0.5 + abs(prediction_result['total_return'])) elif prediction_result['total_return'] < -0.02: # 2% negative return signal["action"] = "SELL" signal["confidence"] = min(0.9, 0.5 + abs(prediction_result['total_return'])) return signal return None except Exception as e: self.logger.error(f"Error generating trading signal: {e}") return None async def handle_client_message(self, websocket, message): """Handle incoming client messages""" try: data = json.loads(message) message_type = data.get("type") if message_type == "load_config": # Load configuration config_file = data.get("config_file", "config.yaml") self.config = load_config(config_file) response = { "type": "config_loaded", "success": True, "config": self.config } await websocket.send(json.dumps(response)) elif message_type == "connect_alpaca": # Connect to Alpaca api_key = data.get("api_key") secret_key = data.get("secret_key") if api_key and secret_key: self.config['alpaca']['api_key'] = api_key self.config['alpaca']['secret_key'] = secret_key self.config['execution']['broker_api'] = 'alpaca_paper' self.alpaca_broker = AlpacaBroker(self.config) response = { "type": "alpaca_connected", "success": True } await websocket.send(json.dumps(response)) else: response = { "type": "alpaca_connected", "success": False, "error": "Missing API credentials" } await websocket.send(json.dumps(response)) elif message_type == "start_trading": # Start trading self.trading_active = True response = { "type": "trading_started", "success": True } await websocket.send(json.dumps(response)) # Broadcast to all clients await self.broadcast({ "type": "trading_status", "active": True, "timestamp": datetime.now().isoformat() }) elif message_type == "stop_trading": # Stop trading self.trading_active = False response = { "type": "trading_stopped", "success": True } await websocket.send(json.dumps(response)) # Broadcast to all clients await self.broadcast({ "type": "trading_status", "active": False, "timestamp": datetime.now().isoformat() }) elif message_type == "load_data": # Load market data if self.config: self.market_data = load_data(self.config) if self.market_data is not None: self.market_data = add_technical_indicators(self.market_data) response = { "type": "data_loaded", "success": True, "data_points": len(self.market_data) } else: response = { "type": "data_loaded", "success": False, "error": "Failed to load data" } else: response = { "type": "data_loaded", "success": False, "error": "Configuration not loaded" } await websocket.send(json.dumps(response)) elif message_type == "train_model": # Train FinRL model if self.market_data is not None: algorithm = data.get("algorithm", "PPO") learning_rate = data.get("learning_rate", 0.0003) training_steps = data.get("training_steps", 100000) finrl_config = FinRLConfig( algorithm=algorithm, learning_rate=learning_rate, batch_size=64, buffer_size=1000000, learning_starts=100, gamma=0.99, tau=0.005, train_freq=1, gradient_steps=1, verbose=1, tensorboard_log='logs/finrl_tensorboard' ) self.finrl_agent = FinRLAgent(finrl_config) # Train in background thread def train_model(): try: result = self.finrl_agent.train( data=self.market_data, config=self.config, total_timesteps=training_steps, use_real_broker=False ) # Broadcast training completion asyncio.create_task(self.broadcast({ "type": "training_completed", "success": result['success'], "result": result })) except Exception as e: asyncio.create_task(self.broadcast({ "type": "training_completed", "success": False, "error": str(e) })) training_thread = threading.Thread(target=train_model) training_thread.daemon = True training_thread.start() response = { "type": "training_started", "success": True } else: response = { "type": "training_started", "success": False, "error": "Market data not loaded" } await websocket.send(json.dumps(response)) else: # Unknown message type response = { "type": "error", "message": f"Unknown message type: {message_type}" } await websocket.send(json.dumps(response)) except json.JSONDecodeError: response = { "type": "error", "message": "Invalid JSON message" } await websocket.send(json.dumps(response)) except Exception as e: response = { "type": "error", "message": f"Server error: {str(e)}" } await websocket.send(json.dumps(response)) async def websocket_handler(self, websocket, path): """Main WebSocket handler""" await self.register(websocket) try: async for message in websocket: await self.handle_client_message(websocket, message) except websockets.exceptions.ConnectionClosed: pass finally: await self.unregister(websocket) async def start_server(self): """Start the WebSocket server""" # Start background tasks asyncio.create_task(self.handle_market_data()) asyncio.create_task(self.handle_portfolio_updates()) asyncio.create_task(self.handle_trading_signals()) # Start WebSocket server server = await websockets.serve( self.websocket_handler, self.host, self.port ) self.logger.info(f"WebSocket server started on ws://{self.host}:{self.port}") # Keep server running await server.wait_closed() def run_server(self): """Run the server in a separate thread""" def run(): asyncio.run(self.start_server()) server_thread = threading.Thread(target=run) server_thread.daemon = True server_thread.start() return server_thread
def create_websocket_server(host="localhost", port=8765): """Create and return a WebSocket server instance""" return TradingWebSocketServer(host=host, port=port) 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269#!/usr/bin/env python3"""UI Launcher for Algorithmic Trading System
Provides multiple UI options:- Streamlit: Quick prototyping and data science workflows- Dash: Enterprise-grade interactive dashboards- Jupyter: Notebook-based interfaces- WebSocket: Real-time trading interfaces"""
import argparseimport sysimport osimport subprocessimport webbrowserimport timeimport threadingfrom typing import Optional
def check_dependencies(): """Check if required UI dependencies are installed""" required_packages = [ 'streamlit', 'dash', 'plotly', 'ipywidgets' ] missing_packages = [] for package in required_packages: try: __import__(package) except ImportError: missing_packages.append(package) if missing_packages: print(f"β Missing required packages: {', '.join(missing_packages)}") print("Please install them using: pip install -r requirements.txt") return False return True
def launch_streamlit(): """Launch Streamlit application""" print("π Launching Streamlit UI...") # Create streamlit app file if it doesn't exist streamlit_app_path = "ui/streamlit_app.py" if not os.path.exists(streamlit_app_path): print(f"β Streamlit app not found at {streamlit_app_path}") return False try: # Launch Streamlit cmd = [ sys.executable, "-m", "streamlit", "run", streamlit_app_path, "--server.port", "8501", "--server.address", "0.0.0.0", "--browser.gatherUsageStats", "false" ] print(f"Running: {' '.join(cmd)}") subprocess.run(cmd) return True except Exception as e: print(f"β Error launching Streamlit: {e}") return False
def launch_dash(): """Launch Dash application""" print("π Launching Dash UI...") # Create dash app file if it doesn't exist dash_app_path = "ui/dash_app.py" if not os.path.exists(dash_app_path): print(f"β Dash app not found at {dash_app_path}") return False try: # Launch Dash cmd = [ sys.executable, dash_app_path ] print(f"Running: {' '.join(cmd)}") subprocess.run(cmd) return True except Exception as e: print(f"β Error launching Dash: {e}") return False
def launch_jupyter(): """Launch Jupyter interface""" print("π Launching Jupyter UI...") try: # Launch Jupyter Lab cmd = [ sys.executable, "-m", "jupyter", "lab", "--port", "8888", "--ip", "0.0.0.0", "--no-browser" ] print(f"Running: {' '.join(cmd)}") subprocess.run(cmd) return True except Exception as e: print(f"β Error launching Jupyter: {e}") return False
def launch_websocket_server(): """Launch WebSocket server""" print("π Launching WebSocket Server...") try: from ui.websocket_server import create_websocket_server server = create_websocket_server(host="0.0.0.0", port=8765) server_thread = server.run_server() print("β
WebSocket server started on ws://0.0.0.0:8765") print("Press Ctrl+C to stop the server") # Keep the main thread alive try: while True: time.sleep(1) except KeyboardInterrupt: print("\nπ Stopping WebSocket server...") return True except Exception as e: print(f"β Error launching WebSocket server: {e}") return False
def open_browser(url: str, delay: int = 2): """Open browser after delay""" def open_url(): time.sleep(delay) try: webbrowser.open(url) print(f"π Opened browser to: {url}") except Exception as e: print(f"β οΈ Could not open browser: {e}") browser_thread = threading.Thread(target=open_url) browser_thread.daemon = True browser_thread.start()
def main(): """Main launcher function""" parser = argparse.ArgumentParser( description="UI Launcher for Algorithmic Trading System", formatter_class=argparse.RawDescriptionHelpFormatter, epilog="""Examples: python ui_launcher.py streamlit # Launch Streamlit UI python ui_launcher.py dash # Launch Dash UI python ui_launcher.py jupyter # Launch Jupyter Lab python ui_launcher.py websocket # Launch WebSocket server python ui_launcher.py all # Launch all UIs """ ) parser.add_argument( "ui_type", choices=["streamlit", "dash", "jupyter", "websocket", "all"], help="Type of UI to launch" ) parser.add_argument( "--no-browser", action="store_true", help="Don't automatically open browser" ) parser.add_argument( "--port", type=int, help="Custom port number (overrides default)" ) args = parser.parse_args() # Check dependencies if not check_dependencies(): sys.exit(1) print("π€ Algorithmic Trading System - UI Launcher") print("=" * 50) success = False if args.ui_type == "streamlit": success = launch_streamlit() if success and not args.no_browser: open_browser("http://localhost:8501") elif args.ui_type == "dash": success = launch_dash() if success and not args.no_browser: open_browser("http://localhost:8050") elif args.ui_type == "jupyter": success = launch_jupyter() if success and not args.no_browser: open_browser("http://localhost:8888") elif args.ui_type == "websocket": success = launch_websocket_server() elif args.ui_type == "all": print("π Launching all UI interfaces...") # Launch WebSocket server in background websocket_thread = threading.Thread(target=launch_websocket_server) websocket_thread.daemon = True websocket_thread.start() # Launch Streamlit streamlit_thread = threading.Thread(target=launch_streamlit) streamlit_thread.daemon = True streamlit_thread.start() # Launch Dash dash_thread = threading.Thread(target=launch_dash) dash_thread.daemon = True dash_thread.start() # Launch Jupyter jupyter_thread = threading.Thread(target=launch_jupyter) jupyter_thread.daemon = True jupyter_thread.start() if not args.no_browser: open_browser("http://localhost:8501", 3) # Streamlit open_browser("http://localhost:8050", 5) # Dash open_browser("http://localhost:8888", 7) # Jupyter print("β
All UIs launched!") print("π Streamlit: http://localhost:8501") print("π Dash: http://localhost:8050") print("π Jupyter: http://localhost:8888") print("π WebSocket: ws://localhost:8765") # Keep main thread alive try: while True: time.sleep(1) except KeyboardInterrupt: print("\nπ Stopping all UIs...") success = True if success: print("β
UI launched successfully!") else: print("β Failed to launch UI") sys.exit(1)
if __name__ == "__main__": main() README.md+82-3
UI_SETUP.mdAdded+390
requirements.txt+54-19
tests/test_ui_integration.pyAdded+147
ui/__init__.pyAdded+24
ui/dash_app.pyAdded+657
ui/jupyter_widgets.pyAdded+556
ui/streamlit_app.pyAdded+679
ui/websocket_server.pyAdded+461
ui_launcher.pyAdded+269