A full-stack AI-powered stock trading simulation platform with support for multiple brokers.
- AI-Powered Trading: Uses TensorFlow and Scikit-learn for price prediction, and NLP for sentiment analysis
- Multi-Broker Support: Integrates with Alpaca (US stocks) and Interactive Brokers (global markets)
- Trading Modes: Paper Trading (simulation) and Live Trading options
- Real-time Analytics: Dashboard for monitoring AI trades and performance
- Market Data Collection: Fetch and store real-time and historical data
- Advanced AI Strategies: LSTM model, sentiment analysis, technical indicators, and reinforcement learning
The RealTradR platform implements a sophisticated AI trading strategy that combines multiple signals:
-
Machine Learning Models (
ml_models.py)- LSTM Networks for time series prediction
- Ensemble models combining multiple prediction techniques
- Sentiment-aware models that adjust predictions based on market sentiment
-
Sentiment Analysis (
sentiment_analyzer.py)- Twitter/X sentiment analysis for stock symbols
- Reddit discussions and sentiment tracking
- Financial news sentiment extraction
- Weighted sentiment scoring across multiple sources
-
Technical Indicators (
technical_indicators.py)- Comprehensive set of technical indicators (SMA, EMA, MACD, RSI, etc.)
- Market regime detection (bull/bear market identification)
- Volatility analysis and adaptive parameters
-
Risk Management (
risk_management.py)- Dynamic stop-loss and take-profit calculations based on volatility
- Position sizing using Kelly criterion and volatility-adjusted methods
- Correlation analysis to prevent overexposure to similar assets
- Drawdown control mechanisms to reduce risk during downturns
The advanced_strategy.py module integrates all these components with configurable weights:
- Technical signals (default: 40% weight)
- Sentiment signals (default: 30% weight)
- Machine learning predictions (default: 30% weight)
The strategy dynamically adjusts its parameters based on detected market regimes and implements sophisticated position sizing to optimize risk-adjusted returns.
The strategy can be backtested using historical data to evaluate performance before deploying with real money:
# Run backtest with default parameters
python run_backtest.py
# Run backtest with custom parameters
python run_backtest.py --config custom_strategy_config.json- Backend: Python (FastAPI)
- AI Core: TensorFlow, Scikit-learn, NLTK
- Database: PostgreSQL (trade history), Redis (caching)
- Frontend: Angular (dashboard)
- Trading Framework: Integrated with Hummingbot for execution
- Security: JWT authentication
- Python 3.8+
- Node.js 14+
- PostgreSQL
- Redis
- Docker (optional)
- Clone the repository
git clone https://github.com/yourusername/RealTradR.git
cd RealTradR- Set up the backend
cd backend
pip install -r requirements.txt
python setup_db.py- Set up the frontend
cd ../frontend
npm install-
Configure your broker API keys in
config.yaml -
Start the application
# Start backend
cd backend
uvicorn main:app --reload
# Start frontend
cd ../frontend
ng serveConfigure your broker settings in config.yaml:
broker:
default: alpaca # Use Alpaca as default
alpaca:
api_key: YOUR_ALPACA_API_KEY
api_secret: YOUR_ALPACA_API_SECRET
paper_trading: true # Set to false for live trading
ibkr:
tws_port: 7497
tws_host: 127.0.0.1
client_id: 1
paper_trading: true # Set to false for live trading
ai:
use_sentiment: true
use_technical: true
use_reinforcement: true
model_update_frequency: daily # Options: hourly, daily, weeklyThe trading strategy is configured through strategy_config.json:
{
"symbols": ["AAPL", "MSFT", "GOOGL", "AMZN", "META"],
"cash_limit": 100000.0,
"sentiment_weight": 0.3,
"technical_weight": 0.4,
"ml_weight": 0.3,
"position_sizing": "kelly", // Options: "equal", "kelly", "volatility"
"max_position_pct": 20.0,
"use_market_regime": true,
"use_sentiment": true,
"use_ml_models": true
// See full configuration options in the file
}The system tracks and reports the following performance metrics:
- Sharpe Ratio: Risk-adjusted return measurement
- Maximum Drawdown: Largest peak-to-trough decline
- Win Rate: Percentage of profitable trades
- Profit Factor: Ratio of gross profits to gross losses
- Daily Returns: Daily percentage returns of the strategy
- Volatility: Standard deviation of returns
RealTradR uses Alpaca for paper and live trading. To set up your API credentials:
- Create an account at Alpaca
- Obtain your API key and secret from the Alpaca dashboard
- Add them to your
strategy_config.jsonfile:
"api_credentials": {
"use_test_credentials": true,
"api_key": "YOUR_API_KEY",
"api_secret": "YOUR_API_SECRET",
"paper_trading": true
}Alpaca offers different tiers of market data access:
- Free tier: Limited to real-time quotes and snapshot data
- Paid tier: Includes historical data and more advanced features
If you're using the free tier, RealTradR will automatically fall back to using mock data for historical analysis while still using real-time quotes for execution.
The strategy_config.json file contains all configurable parameters:
"symbols": ["AAPL", "MSFT", "GOOGL", "AMZN", "META"],
"cash_limit": 100000.0"signal_weights": {
"sentiment": 0.3,
"technical": 0.4,
"ml": 0.3
}"position_sizing": {
"method": "kelly",
"max_position_pct": 0.2,
"base_position_pct": 0.05,
"min_position_dollars": 1000
}"risk_management": {
"stop_loss": 2.0,
"take_profit": 5.0,
"max_drawdown": 25.0,
"correlation_threshold": 0.7
}"market_data": {
"default_days": 60,
"timeframes": ["1D", "1H", "15Min"],
"use_mock_data_on_api_failure": true,
"mock_data_volatility": 0.015,
"use_mock_data": false
}The main script run_strategy_with_real_data.py accepts the following command line arguments:
--config FILE: Path to configuration file (default: strategy_config.json)--paper: Run in paper trading mode (default)--live: Run in live trading mode (use with caution!)--mock: Use mock data instead of real market data--continuous: Run the strategy continuously--interval SECONDS: Interval between strategy runs in continuous mode (default: 300)--report: Generate a performance report after execution--verbose: Enable verbose logging
# Run once with paper trading
python run_strategy_with_real_data.py --paper --report
# Run continuously with 5-minute intervals
python run_strategy_with_real_data.py --paper --continuous --interval 300
# Run with mock data for testing
python run_strategy_with_real_data.py --paper --mock --reportIf you encounter 403 Forbidden errors when connecting to the Alpaca API:
- Check your API credentials: Ensure your API key and secret are correct
- Verify account status: Make sure your Alpaca account is active
- Check endpoint permissions: The free tier has limited access to historical data
- Use mock data: Enable
use_mock_data: truein the config for testing
If you see TensorFlow DLL loading errors on Windows:
- Install the Microsoft Visual C++ Redistributable for Visual Studio 2015, 2017, and 2019
- Ensure you have the correct version of CUDA and cuDNN installed (if using GPU)
- Try reinstalling TensorFlow with:
pip uninstall tensorflow && pip install tensorflow - The system will automatically fall back to simplified ML models if TensorFlow fails to load
If the strategy is running slowly:
- Reduce the number of symbols being traded
- Increase the interval between strategy runs
- Use a smaller lookback period for historical data
- Disable sentiment analysis if not needed
RealTradR includes comprehensive logging and monitoring:
- Trade logs: Stored in
trades.csvandtrades.json - Performance reports: Generated as JSON files with timestamp (e.g.,
report_20250324_223624.json) - Console logs: Real-time logging of strategy execution, signals, and trades
- Alert system: Configurable alerts for significant events (price movements, execution issues)
For production deployment:
- Set up proper monitoring and alerting
- Use a dedicated server or cloud instance
- Configure automatic restart in case of crashes
- Set up regular backups of configuration and trade data
- Consider using a process manager like PM2 or supervisord
The RealTradR backend exposes the following REST API endpoints:
GET /api/strategy/status: Get current strategy statusPOST /api/strategy/start: Start the strategyPOST /api/strategy/stop: Stop the strategyPUT /api/strategy/config: Update strategy configuration
GET /api/trades: Get list of executed tradesGET /api/positions: Get current positionsPOST /api/trades/execute: Manually execute a trade
GET /api/performance: Get performance metricsGET /api/performance/daily: Get daily performance dataGET /api/performance/report: Generate performance report
This project is licensed under the MIT License - see the LICENSE file for details.
RealTradR includes comprehensive tests for all components:
# Run all tests
pytest
# Run specific test modules
pytest tests/test_sentiment_analyzer.py
pytest tests/test_technical_indicators.py
pytest tests/test_ml_models.py
pytest tests/test_advanced_strategy.py
pytest tests/test_risk_management.py
# Run backtests with performance evaluation
python tests/run_strategy_backtest.py