File size: 13,229 Bytes
859af74
 
46590b0
859af74
46590b0
 
 
 
 
 
859af74
 
46590b0
 
 
 
 
 
 
 
 
 
859af74
46590b0
 
 
 
859af74
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859af74
 
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859af74
46590b0
 
 
 
 
 
 
859af74
46590b0
 
 
859af74
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859af74
 
 
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
859af74
 
46590b0
859af74
46590b0
 
 
859af74
46590b0
 
 
 
 
 
 
 
859af74
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859af74
46590b0
 
 
 
 
 
859af74
 
 
46590b0
859af74
 
 
 
46590b0
 
 
 
 
859af74
 
 
46590b0
 
 
 
 
 
859af74
46590b0
 
 
 
 
 
859af74
 
46590b0
 
 
 
 
859af74
 
 
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
859af74
46590b0
 
 
 
 
 
 
 
 
859af74
 
46590b0
 
 
 
 
859af74
 
46590b0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
859af74
 
46590b0
 
859af74
46590b0
859af74
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
#!/usr/bin/env python3
"""
Demo script for the Algorithmic Trading System with FinRL and Alpaca Integration

This script demonstrates the complete trading workflow including:
- Data ingestion from multiple sources (CSV, Alpaca, Synthetic)
- Strategy generation with technical indicators
- Order execution with Alpaca broker
- FinRL reinforcement learning integration
- Real-time trading capabilities
"""

import os
import sys
import time
import logging
from datetime import datetime, timedelta
from typing import Dict, Any

# Add the project root to the path
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from agentic_ai_system.main import load_config
from agentic_ai_system.orchestrator import run, run_backtest, run_live_trading
from agentic_ai_system.data_ingestion import load_data, validate_data, add_technical_indicators
from agentic_ai_system.finrl_agent import FinRLAgent, FinRLConfig
from agentic_ai_system.alpaca_broker import AlpacaBroker

def setup_logging():
    """Setup logging configuration"""
    logging.basicConfig(
        level=logging.INFO,
        format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
        handlers=[
            logging.StreamHandler(),
            logging.FileHandler('logs/demo.log')
        ]
    )

def print_system_info(config: Dict[str, Any]):
    """Print system configuration information"""
    print("\n" + "="*60)
    print("๐Ÿค– ALGORITHMIC TRADING SYSTEM WITH FINRL & ALPACA")
    print("="*60)
    
    print(f"\n๐Ÿ“Š Data Source: {config['data_source']['type']}")
    print(f"๐Ÿ“ˆ Trading Symbol: {config['trading']['symbol']}")
    print(f"๐Ÿ’ฐ Capital: ${config['trading']['capital']:,}")
    print(f"โฑ๏ธ  Timeframe: {config['trading']['timeframe']}")
    print(f"๐Ÿ”ง Broker API: {config['execution']['broker_api']}")
    
    if config['execution']['broker_api'] in ['alpaca_paper', 'alpaca_live']:
        print(f"๐Ÿฆ Alpaca Account Type: {config['alpaca']['account_type']}")
        print(f"๐Ÿ“ก Alpaca Base URL: {config['alpaca']['base_url']}")
    
    print(f"๐Ÿง  FinRL Algorithm: {config['finrl']['algorithm']}")
    print(f"๐Ÿ“š Learning Rate: {config['finrl']['learning_rate']}")
    print(f"๐ŸŽฏ Training Steps: {config['finrl']['training']['total_timesteps']:,}")
    
    print("\n" + "="*60)

def demo_data_ingestion(config: Dict[str, Any]):
    """Demonstrate data ingestion capabilities"""
    print("\n๐Ÿ“ฅ DATA INGESTION DEMO")
    print("-" * 30)
    
    try:
        # Load data
        print(f"Loading data from source: {config['data_source']['type']}")
        data = load_data(config)
        
        if data is not None and not data.empty:
            print(f"โœ… Successfully loaded {len(data)} data points")
            print(f"๐Ÿ“… Date range: {data['timestamp'].min()} to {data['timestamp'].max()}")
            print(f"๐Ÿ’ฐ Price range: ${data['close'].min():.2f} - ${data['close'].max():.2f}")
            
            # Validate data
            if validate_data(data):
                print("โœ… Data validation passed")
                
                # Add technical indicators
                data_with_indicators = add_technical_indicators(data)
                print(f"โœ… Added {len(data_with_indicators.columns) - len(data.columns)} technical indicators")
                
                return data_with_indicators
            else:
                print("โŒ Data validation failed")
                return None
        else:
            print("โŒ Failed to load data")
            return None
            
    except Exception as e:
        print(f"โŒ Error in data ingestion: {e}")
        return None

def demo_alpaca_integration(config: Dict[str, Any]):
    """Demonstrate Alpaca broker integration"""
    print("\n๐Ÿฆ ALPACA INTEGRATION DEMO")
    print("-" * 30)
    
    if config['execution']['broker_api'] not in ['alpaca_paper', 'alpaca_live']:
        print("โš ๏ธ  Alpaca integration not configured (using simulation mode)")
        return None
    
    try:
        # Initialize Alpaca broker
        print("Connecting to Alpaca...")
        alpaca_broker = AlpacaBroker(config)
        
        # Get account information
        account_info = alpaca_broker.get_account_info()
        if account_info:
            print(f"โœ… Connected to Alpaca {config['alpaca']['account_type']} account")
            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}")
            print(f"   Equity: ${account_info['equity']:,.2f}")
        
        # Check market status
        market_hours = alpaca_broker.get_market_hours()
        if market_hours:
            print(f"๐Ÿ“ˆ Market Status: {'๐ŸŸข OPEN' if market_hours['is_open'] else '๐Ÿ”ด CLOSED'}")
            if market_hours['next_open']:
                print(f"   Next Open: {market_hours['next_open']}")
            if market_hours['next_close']:
                print(f"   Next Close: {market_hours['next_close']}")
        
        # Get current positions
        positions = alpaca_broker.get_positions()
        if positions:
            print(f"๐Ÿ“Š Current Positions: {len(positions)}")
            for pos in positions:
                print(f"   {pos['symbol']}: {pos['quantity']} shares @ ${pos['current_price']:.2f}")
        else:
            print("๐Ÿ“Š No current positions")
        
        return alpaca_broker
        
    except Exception as e:
        print(f"โŒ Error connecting to Alpaca: {e}")
        return None

def demo_finrl_training(config: Dict[str, Any], data):
    """Demonstrate FinRL training"""
    print("\n๐Ÿง  FINRL TRAINING DEMO")
    print("-" * 30)
    
    try:
        # Initialize FinRL agent
        finrl_config = FinRLConfig(
            algorithm=config['finrl']['algorithm'],
            learning_rate=config['finrl']['learning_rate'],
            batch_size=config['finrl']['batch_size'],
            buffer_size=config['finrl']['buffer_size'],
            learning_starts=config['finrl']['learning_starts'],
            gamma=config['finrl']['gamma'],
            tau=config['finrl']['tau'],
            train_freq=config['finrl']['train_freq'],
            gradient_steps=config['finrl']['gradient_steps'],
            verbose=config['finrl']['verbose'],
            tensorboard_log=config['finrl']['tensorboard_log']
        )
        
        agent = FinRLAgent(finrl_config)
        
        # Use a subset of data for demo training
        demo_data = data.tail(500) if len(data) > 500 else data
        print(f"Training on {len(demo_data)} data points...")
        
        # Train the agent (shorter training for demo)
        training_steps = min(10000, config['finrl']['training']['total_timesteps'])
        result = agent.train(
            data=demo_data,
            config=config,
            total_timesteps=training_steps,
            use_real_broker=False  # Use simulation for demo training
        )
        
        if result['success']:
            print(f"โœ… Training completed successfully!")
            print(f"   Algorithm: {result['algorithm']}")
            print(f"   Timesteps: {result['total_timesteps']:,}")
            print(f"   Model saved: {result['model_path']}")
            
            # Test prediction
            print("\n๐Ÿ”ฎ Testing predictions...")
            prediction_result = agent.predict(
                data=demo_data.tail(100),
                config=config,
                use_real_broker=False
            )
            
            if prediction_result['success']:
                print(f"โœ… Prediction completed!")
                print(f"   Initial Value: ${prediction_result['initial_value']:,.2f}")
                print(f"   Final Value: ${prediction_result['final_value']:,.2f}")
                print(f"   Total Return: {prediction_result['total_return']:.2%}")
                print(f"   Total Trades: {prediction_result['total_trades']}")
            
            return agent
        else:
            print(f"โŒ Training failed: {result['error']}")
            return None
            
    except Exception as e:
        print(f"โŒ Error in FinRL training: {e}")
        return None

def demo_trading_workflow(config: Dict[str, Any], data):
    """Demonstrate complete trading workflow"""
    print("\n๐Ÿ”„ TRADING WORKFLOW DEMO")
    print("-" * 30)
    
    try:
        # Run single trading cycle
        print("Running trading workflow...")
        result = run(config)
        
        if result['success']:
            print("โœ… Trading workflow completed successfully!")
            print(f"   Data Loaded: {'โœ…' if result['data_loaded'] else 'โŒ'}")
            print(f"   Signal Generated: {'โœ…' if result['signal_generated'] else 'โŒ'}")
            print(f"   Order Executed: {'โœ…' if result['order_executed'] else 'โŒ'}")
            print(f"   Execution Time: {result['execution_time']:.2f} seconds")
            
            if result['order_executed'] and result['execution_result']:
                exec_result = result['execution_result']
                print(f"   Order ID: {exec_result.get('order_id', 'N/A')}")
                print(f"   Action: {exec_result['action']}")
                print(f"   Symbol: {exec_result['symbol']}")
                print(f"   Quantity: {exec_result['quantity']}")
                print(f"   Price: ${exec_result['price']:.2f}")
                print(f"   Total Value: ${exec_result['total_value']:.2f}")
        else:
            print("โŒ Trading workflow failed!")
            for error in result['errors']:
                print(f"   Error: {error}")
        
        return result
        
    except Exception as e:
        print(f"โŒ Error in trading workflow: {e}")
        return None

def demo_backtest(config: Dict[str, Any], data):
    """Demonstrate backtesting capabilities"""
    print("\n๐Ÿ“Š BACKTESTING DEMO")
    print("-" * 30)
    
    try:
        # Run backtest on recent data
        end_date = datetime.now().strftime('%Y-%m-%d')
        start_date = (datetime.now() - timedelta(days=30)).strftime('%Y-%m-%d')
        
        print(f"Running backtest from {start_date} to {end_date}...")
        result = run_backtest(config, start_date, end_date)
        
        if result['success']:
            print("โœ… Backtest completed successfully!")
            print(f"   Initial Capital: ${result['initial_capital']:,.2f}")
            print(f"   Final Value: ${result['final_value']:,.2f}")
            print(f"   Total Return: {result['total_return']:.2%}")
            print(f"   Total Trades: {result['total_trades']}")
            
            # Calculate additional metrics
            if result['total_trades'] > 0:
                win_rate = len([t for t in result['trades'] if t.get('execution', {}).get('success', False)]) / result['total_trades']
                print(f"   Win Rate: {win_rate:.2%}")
        else:
            print(f"โŒ Backtest failed: {result.get('error', 'Unknown error')}")
        
        return result
        
    except Exception as e:
        print(f"โŒ Error in backtesting: {e}")
        return None

def main():
    """Main demo function"""
    setup_logging()
    
    try:
        # Load configuration
        config = load_config()
        print_system_info(config)
        
        # Demo 1: Data Ingestion
        data = demo_data_ingestion(config)
        if data is None:
            print("โŒ Cannot proceed without data")
            return
        
        # Demo 2: Alpaca Integration
        alpaca_broker = demo_alpaca_integration(config)
        
        # Demo 3: FinRL Training
        finrl_agent = demo_finrl_training(config, data)
        
        # Demo 4: Trading Workflow
        workflow_result = demo_trading_workflow(config, data)
        
        # Demo 5: Backtesting
        backtest_result = demo_backtest(config, data)
        
        # Summary
        print("\n" + "="*60)
        print("๐ŸŽ‰ DEMO COMPLETED SUCCESSFULLY!")
        print("="*60)
        print("\n๐Ÿ“‹ Summary:")
        print(f"   โœ… Data Ingestion: {'Working' if data is not None else 'Failed'}")
        print(f"   โœ… Alpaca Integration: {'Working' if alpaca_broker is not None else 'Simulation Mode'}")
        print(f"   โœ… FinRL Training: {'Working' if finrl_agent is not None else 'Failed'}")
        print(f"   โœ… Trading Workflow: {'Working' if workflow_result and workflow_result['success'] else 'Failed'}")
        print(f"   โœ… Backtesting: {'Working' if backtest_result and backtest_result['success'] else 'Failed'}")
        
        print("\n๐Ÿš€ Next Steps:")
        print("   1. Set up your Alpaca API credentials in .env file")
        print("   2. Configure your trading strategy in config.yaml")
        print("   3. Run live trading with: python -m agentic_ai_system.main --mode live")
        print("   4. Monitor performance in logs/ directory")
        
    except Exception as e:
        print(f"โŒ Demo failed with error: {e}")
        logging.error(f"Demo error: {e}", exc_info=True)

if __name__ == "__main__":
    main()