xtrade-ai


Namextrade-ai JSON
Version 1.2.0 PyPI version JSON
download
home_pageNone
SummaryA comprehensive reinforcement learning framework for algorithmic trading
upload_time2025-09-01 18:09:19
maintainerNone
docs_urlNone
authorNone
requires_python<3.14,>=3.8
licenseMIT
keywords trading reinforcement-learning algorithmic-trading machine-learning finance ai trading-bot quantitative-finance
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # XTrade-AI Framework

[![PyPI version](https://badge.fury.io/py/xtrade-ai.svg)](https://badge.fury.io/py/xtrade-ai)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)

A comprehensive reinforcement learning framework for algorithmic trading with enhanced error handling, memory management, and thread safety.

## 🚀 Quick Start

### Installation

```bash
# Install from PyPI
pip install xtrade-ai

# Install with optional dependencies
pip install xtrade-ai[gpu]

# Or install from source
git clone https://github.com/anasamu/xtrade-ai-framework.git
cd xtrade-ai-framework
pip install -r requirements/base.txt
pip install -e .
```

### Basic Usage

```python
from xtrade_ai import XTradeAIFramework, XTradeAIConfig

# Create configuration
config = XTradeAIConfig()
config.model.baseline_algorithm = "PPO"
config.trading.initial_balance = 10000.0

# Initialize framework
framework = XTradeAIFramework(config)

# Train the model
framework.train(training_data, epochs=100)

# Make predictions
prediction = framework.predict(market_data)
print(f"Action: {prediction['action']}, Confidence: {prediction['confidence']}")
```

### Command Line Interface

```bash
# Check framework health
xtrade-ai health

# Train a model
xtrade-ai train --config config.yaml --data training_data.csv

# Make predictions
xtrade-ai predict --model model.pkl --data market_data.csv

# Run backtesting
xtrade-ai backtest --model model.pkl --data historical_data.csv
```

## 📋 Table of Contents

- [Features](#-features)
- [Project Structure](#-project-structure)
- [Architecture](#-architecture)
- [Installation](#-installation)
- [Configuration](#-configuration)
- [Usage Examples](#-usage-examples)
- [API Reference](#-api-reference)
- [Advanced Features](#-advanced-features)
- [Performance Optimization](#-performance-optimization)
- [Deployment](#-deployment)
- [Docker Images](#-docker-images)
- [Troubleshooting](#-troubleshooting)
- [Contributing](#-contributing)
- [License](#-license)

## ✨ Features

### 🤖 AI/ML Capabilities
- **Reinforcement Learning**: PPO, DQN, A2C algorithms from Stable-Baselines3
- **Ensemble Learning**: Multi-model predictions with weighted averaging
- **XGBoost Integration**: Gradient boosting for feature selection and prediction
- **Attention Mechanisms**: Transformer-based models for sequence modeling
- **Meta-Learning**: Adaptive learning across different market conditions

### 📊 Trading Features
- **Technical Analysis**: 50+ technical indicators with adaptive parameters
- **Risk Management**: Dynamic position sizing and stop-loss management
- **Portfolio Management**: Multi-asset portfolio optimization
- **Market Simulation**: Realistic market environment simulation
- **Order Management**: Intelligent order placement and execution

### 🔧 Technical Features
- **Thread Safety**: Multi-threaded training and prediction
- **Memory Management**: Automatic memory cleanup and optimization
- **Error Handling**: Comprehensive error handling and recovery
- **Performance Monitoring**: Real-time performance metrics
- **Model Persistence**: Save/load models with versioning

### 🛠️ Development Features
- **Modular Design**: Pluggable modules for easy customization
- **Configuration Management**: YAML/JSON configuration support
- **CLI Interface**: Command-line tools for all operations

## 📁 Project Structure

```
xtrade-ai/
├── docker/           # Docker configurations and images
│   ├── Dockerfile.cpu
│   ├── Dockerfile.gpu
│   └── docker-compose.yml
├── scripts/          # Build and deployment scripts
│   ├── build/        # Build and packaging scripts
│   ├── deploy/       # Deployment scripts
│   ├── clean/        # Cleanup scripts
│   ├── Makefile      # Linux/macOS build commands
│   └── build.ps1     # Windows PowerShell build commands
├── config/           # Configuration files
│   ├── env.example   # Environment variables template
│   ├── init.sql      # Database initialization
│   ├── nginx.conf    # Nginx configuration
│   └── prometheus.yml # Prometheus monitoring
├── requirements/     # Python dependencies
│   ├── base.txt      # Core dependencies
│   ├── gpu.txt       # GPU dependencies
├── xtrade_ai/        # Main package source code
├── test/             # Test suite
├── docs/             # Documentation
├── logs/             # Application logs
```

### Quick Commands

```bash
# Using Makefile (Linux/macOS)
cd scripts
make install
make build
make deploy

# Using PowerShell (Windows)
cd scripts
.\build.ps1 install
.\build.ps1 build
.\build.ps1 deploy
```
- **Logging**: Comprehensive logging with multiple levels
- **Testing**: Built-in testing and validation tools

## 🏗️ Architecture

### Core Components

```
XTrade-AI Framework
├── Core Framework (xtrade_ai_framework.py)
├── Configuration Management (config.py)
├── Data Processing (data_preprocessor.py)
├── Base Environment (base_environment.py)
├── CLI Interface (cli.py)
└── Modules/
    ├── Action Selection (action_selector.py)
    ├── Baseline3 Integration (baseline3_integration.py)
    ├── Risk Management (risk_management.py)
    ├── Technical Analysis (technical_analysis.py)
    ├── XGBoost Module (xgboost_module.py)
    ├── Monitoring (monitoring.py)
    ├── Meta Learning (meta_learning.py)
    └── Optimization (optimization.py)
```

### Data Flow

```
Market Data → Data Preprocessor → Feature Engineering → Model Ensemble → Trading Decision
     ↓              ↓                    ↓                ↓              ↓
Technical    Risk Assessment    Model Validation    Action Selection   Order Execution
Indicators   Position Sizing    Performance Check   Confidence Score   Portfolio Update
```

## 📦 Installation

### Prerequisites

- Python 3.8 or higher
- pip package manager
- Git (for development)

### Basic Installation

```bash
# Install from PyPI
pip install xtrade-ai
```

### Advanced Installation

```bash
# Install with all optional dependencies
pip install xtrade-ai[all]

# Install specific feature sets
pip install xtrade-ai[ta]      # Technical analysis
pip install xtrade-ai[dev]      # Development tools
pip install xtrade-ai[viz]      # Visualization
pip install xtrade-ai[monitor]  # Monitoring
pip install xtrade-ai[api]      # API server
```

### Docker Installation

```bash
# Pull from Docker Hub
docker pull anasamu7/xtrade-ai:latest

# Run container
docker run -it anasamu7/xtrade-ai:latest xtrade-ai --help
```

## ⚙️ Configuration

### Basic Configuration

```python
from xtrade_ai import XTradeAIConfig

# Create default configuration
config = XTradeAIConfig()

# Customize model parameters
config.model.baseline_algorithm = "PPO"
config.model.learning_rate = 3e-4
config.model.batch_size = 64

# Customize trading parameters
config.trading.initial_balance = 10000.0
config.trading.commission_rate = 0.001
config.trading.max_position_size = 0.1
```

### Configuration File (YAML)

```yaml
# config.yaml
model:
  baseline_algorithm: "PPO"
  learning_rate: 3e-4
  batch_size: 64
  state_dim: 545
  action_dim: 4
  enable_xgboost: true
  enable_risk_management: true

trading:
  initial_balance: 10000.0
  commission_rate: 0.001
  max_position_size: 0.1
  stop_loss_pct: 0.02
  take_profit_pct: 0.05

data:
  lookback_window: 100
  feature_columns: ["open", "high", "low", "close", "volume"]
  target_column: "returns"
  train_split: 0.8
  validation_split: 0.1

training:
  epochs: 100
  batch_size: 64
  validation_freq: 10
  save_freq: 50
  early_stopping_patience: 10
```

### Environment Variables

```bash
# Set environment variables
export XTRADE_AI_LOG_LEVEL=INFO
export XTRADE_AI_DATA_DIR=/path/to/data
export XTRADE_AI_MODEL_DIR=/path/to/models
export XTRADE_AI_CONFIG_FILE=/path/to/config.yaml
```

## 📚 Usage Examples

### Basic Training

```python
from xtrade_ai import XTradeAIFramework, XTradeAIConfig
import pandas as pd

# Load data
data = pd.read_csv('market_data.csv')

# Create configuration
config = XTradeAIConfig()
config.model.baseline_algorithm = "PPO"

# Initialize framework
framework = XTradeAIFramework(config)

# Train model
framework.train(data, epochs=100, validation_split=0.2)

# Save model
framework.save_model('trained_model.pkl')
```

### Advanced Training with Custom Environment

```python
from xtrade_ai import XTradeAIFramework, XTradeAIConfig, BaseEnvironment

class CustomTradingEnvironment(BaseEnvironment):
    def __init__(self, data, config):
        super().__init__(data, config)
        # Add custom logic here
    
    def step(self, action):
        # Custom step logic
        return super().step(action)

# Create custom environment
env = CustomTradingEnvironment(data, config)

# Train with custom environment
framework.train_with_environment(env, epochs=100)
```

### Ensemble Prediction

```python
# Enable ensemble learning
config.model.enable_ensemble = True
config.model.ensemble_method = "weighted_average"

# Initialize framework
framework = XTradeAIFramework(config)

# Train multiple models
framework.train_ensemble(data, models=['PPO', 'DQN', 'XGBoost'])

# Make ensemble prediction
prediction = framework.predict_ensemble(market_data)
print(f"Ensemble Action: {prediction['action']}")
print(f"Confidence: {prediction['confidence']}")
print(f"Model Weights: {prediction['weights']}")
```

### Real-time Trading

```python
import time
from xtrade_ai import XTradeAIFramework

# Load trained model
framework = XTradeAIFramework.load_model('trained_model.pkl')

# Real-time prediction loop
while True:
    # Get latest market data
    market_data = get_latest_market_data()
    
    # Make prediction
    prediction = framework.predict(market_data)
    
    # Execute trade based on prediction
    if prediction['confidence'] > 0.7:
        execute_trade(prediction['action'])
    
    time.sleep(60)  # Wait 1 minute
```

### Backtesting

```python
from xtrade_ai import XTradeAIFramework

# Load trained model
framework = XTradeAIFramework.load_model('trained_model.pkl')

# Run backtest
results = framework.backtest(
    historical_data,
    initial_balance=10000.0,
    commission_rate=0.001
)

# Print results
print(f"Total Return: {results['total_return']:.2%}")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {results['max_drawdown']:.2%}")
print(f"Win Rate: {results['win_rate']:.2%}")
```

## 🔌 API Reference

### Core Classes

#### XTradeAIFramework

Main framework class that orchestrates all components.

```python
class XTradeAIFramework:
    def __init__(self, config: XTradeAIConfig)
    def train(self, data: pd.DataFrame, epochs: int = 100) -> Dict
    def predict(self, data: pd.DataFrame) -> Dict
    def backtest(self, data: pd.DataFrame) -> Dict
    def save_model(self, path: str) -> None
    def load_model(self, path: str) -> 'XTradeAIFramework'
```

#### XTradeAIConfig

Configuration management class.

```python
class XTradeAIConfig:
    def __init__(self, config_file: str = None)
    def to_dict(self) -> Dict
    def from_dict(self, config_dict: Dict) -> None
    def save(self, path: str) -> None
    def load(self, path: str) -> None
```

#### DataPreprocessor

Data preprocessing and feature engineering.

```python
class DataPreprocessor:
    def __init__(self, config: XTradeAIConfig)
    def preprocess(self, data: pd.DataFrame) -> pd.DataFrame
    def add_technical_indicators(self, data: pd.DataFrame) -> pd.DataFrame
    def normalize_features(self, data: pd.DataFrame) -> pd.DataFrame
```

### Data Structures

#### TradingDecision

```python
@dataclass
class TradingDecision:
    action: ActionType
    confidence: float
    timestamp: datetime
    market_state: MarketState
    risk_assessment: RiskAssessment
```

#### MarketState

```python
@dataclass
class MarketState:
    price: float
    volume: float
    technical_indicators: Dict[str, float]
    market_sentiment: float
    volatility: float
```

#### Portfolio

```python
@dataclass
class Portfolio:
    balance: float
    positions: Dict[str, Position]
    total_value: float
    pnl: float
    risk_metrics: Dict[str, float]
```

## 🚀 Advanced Features

### Meta-Learning

```python
# Enable meta-learning
config.model.enable_meta_learning = True
config.model.meta_learning_rate = 0.01

# Train with meta-learning
framework.train_with_meta_learning(
    training_data,
    meta_data,
    epochs=100
)
```

### Custom Reward Functions

```python
def custom_reward_function(state, action, next_state, reward):
    # Add custom reward logic
    custom_reward = reward * 1.5  # Amplify rewards
    return custom_reward

# Set custom reward function
framework.set_reward_function(custom_reward_function)
```

### Multi-Asset Trading

```python
# Configure multi-asset trading
config.trading.assets = ['BTC/USD', 'ETH/USD', 'AAPL', 'GOOGL']
config.trading.correlation_threshold = 0.7

# Train multi-asset model
framework.train_multi_asset(data_dict, epochs=100)
```

### Real-time Monitoring

```python
# Enable monitoring
config.monitoring.enable_real_time = True
config.monitoring.metrics = ['sharpe_ratio', 'max_drawdown', 'win_rate']

# Start monitoring
framework.start_monitoring()

# Get real-time metrics
metrics = framework.get_monitoring_metrics()
```

## ⚡ Performance Optimization

### Memory Optimization

```python
# Enable memory optimization
config.performance.enable_memory_optimization = True
config.performance.max_memory_usage = 0.8

# Use memory-efficient training
framework.train_memory_efficient(data, epochs=100)
```

### Parallel Processing

```python
# Enable parallel processing
config.performance.enable_parallel = True
config.performance.num_workers = 4

# Train with parallel processing
framework.train_parallel(data, epochs=100)
```

### GPU Acceleration

```python
# Enable GPU acceleration
config.performance.enable_gpu = True
config.performance.gpu_memory_fraction = 0.8

# Train on GPU
framework.train_gpu(data, epochs=100)
```

## 🐛 Troubleshooting

### Common Issues

#### Import Errors

```bash
# Check dependencies
xtrade-ai health

# Install missing dependencies
pip install -r requirements.txt
```

#### Memory Issues

```python
# Reduce batch size
config.model.batch_size = 32

# Enable memory cleanup
config.performance.enable_memory_cleanup = True
```

#### Training Issues

```python
# Check data quality
framework.validate_data(data)

# Adjust learning rate
config.model.learning_rate = 1e-4

# Enable early stopping
config.training.early_stopping_patience = 5
```

### Debug Mode

```python
# Enable debug mode
import logging
logging.basicConfig(level=logging.DEBUG)

# Run with debug information
framework.train(data, epochs=100, debug=True)
```

### Performance Profiling

```python
# Enable performance profiling
config.performance.enable_profiling = True

# Profile training
framework.train_with_profiling(data, epochs=100)
```

## 🚀 Deployment

XTrade-AI framework supports automated deployment via GitHub Actions with PyPI package publishing and Docker image deployment.

### Automated Deployment

The framework uses GitHub Actions for continuous deployment:

- **PyPI Publishing**: Automatic package publishing to PyPI
- **Docker Images**: Multiple optimized Docker images
- **Smart Triggers**: Only deploys when relevant code changes
- **Quality Assurance**: Comprehensive testing and validation

### Quick Deployment

```bash
# Deploy to PyPI (requires credentials)
pip install build twine
python -m build --wheel --sdist
twine upload dist/*

# Deploy Docker images
docker build -f Dockerfile.pypi -t xtrade-ai:pypi .
docker build -f Dockerfile.minimal -t xtrade-ai:minimal .
docker push your-username/xtrade-ai:pypi
```

For detailed deployment information, see [DEPLOYMENT.md](DEPLOYMENT.md).

## 🐳 Docker Deployment

### CPU Version
```bash
# Start CPU version
docker-compose --profile cpu up -d

# Or run directly
docker run -p 8000:8000 xtrade/xtrade-ai:stable-CPU
```

### GPU Version
```bash
# Start GPU version (requires NVIDIA Docker)
docker-compose --profile gpu up -d

# Or run directly
docker run --gpus all -p 8000:8000 xtrade/xtrade-ai:stable-GPU
```

### Minimal Version (Development/Testing)
```bash
# Start minimal version
docker-compose --profile minimal up -d

# Or run directly
docker run -p 8002:8000 xtrade/xtrade-ai:minimal
```

### Full Stack Deployment
```bash
# Deploy complete stack with monitoring
docker-compose up -d

# Access services:
# - API (CPU): http://localhost:8000
# - API (GPU): http://localhost:8000 (same port, different container)
# - API (Minimal): http://localhost:8002
# - Grafana: http://localhost:3000 (admin/admin)
# - Prometheus: http://localhost:9090
```

### Docker Images Available

| Image | Tag | Description | Use Case |
|-------|-----|-------------|----------|
| `xtrade/xtrade-ai` | `stable-CPU` | CPU optimized version | Production CPU environments |
| `xtrade/xtrade-ai` | `stable-GPU` | GPU optimized version | Production GPU environments |
| `xtrade/xtrade-ai` | `1.0.0-CPU` | Versioned CPU release | Specific version deployment |
| `xtrade/xtrade-ai` | `1.0.0-GPU` | Versioned GPU release | Specific version deployment |

### Building Custom Images

If you want to build custom Docker images:

```bash
# Build CPU version
docker build -f docker/Dockerfile -t my-xtrade-ai:cpu .

# Build GPU version
docker build -f docker/Dockerfile.gpu -t my-xtrade-ai:gpu .

## 🤝 Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Clone repository
git clone https://github.com/anasamu/xtrade-ai-framework.git
cd xtrade-ai-framework

# Install development dependencies
pip install -e ".[dev]"

# Run tests
pytest

# Run linting
black xtrade_ai/
isort xtrade_ai/
flake8 xtrade_ai/
```

### Code Style

- Follow PEP 8 style guidelines
- Use type hints for all functions
- Write comprehensive docstrings
- Add unit tests for new features

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 🙏 Acknowledgments

- [Stable-Baselines3](https://github.com/DLR-RM/stable-baselines3) for RL algorithms
- [Gymnasium](https://github.com/Farama-Foundation/Gymnasium) for environment interface
- [XGBoost](https://github.com/dmlc/xgboost) for gradient boosting
- [Pandas](https://pandas.pydata.org/) for data manipulation
- [NumPy](https://numpy.org/) for numerical computing

## 📞 Support

- **Documentation**: [https://xtrade-ai-framework.readthedocs.io/en/latest/](https://xtrade-ai-framework.readthedocs.io/en/latest/)
- **Issues**: [GitHub Issues](https://github.com/anasamu/xtrade-ai-framework/issues)
- **Email**: <anasamu7@gmail.com>

**Disclaimer**: This framework is for educational and research purposes. Trading involves risk, and past performance does not guarantee future results. Always perform thorough testing before using in live trading.

            

Raw data

            {
    "_id": null,
    "home_page": null,
    "name": "xtrade-ai",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<3.14,>=3.8",
    "maintainer_email": "Anas Amu <anasamu7@gmail.com>",
    "keywords": "trading, reinforcement-learning, algorithmic-trading, machine-learning, finance, ai, trading-bot, quantitative-finance",
    "author": null,
    "author_email": "Anas Amu <anasamu7@gmail.com>",
    "download_url": null,
    "platform": null,
    "description": "# XTrade-AI Framework\n\n[![PyPI version](https://badge.fury.io/py/xtrade-ai.svg)](https://badge.fury.io/py/xtrade-ai)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Python 3.8+](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)\n\nA comprehensive reinforcement learning framework for algorithmic trading with enhanced error handling, memory management, and thread safety.\n\n## \ud83d\ude80 Quick Start\n\n### Installation\n\n```bash\n# Install from PyPI\npip install xtrade-ai\n\n# Install with optional dependencies\npip install xtrade-ai[gpu]\n\n# Or install from source\ngit clone https://github.com/anasamu/xtrade-ai-framework.git\ncd xtrade-ai-framework\npip install -r requirements/base.txt\npip install -e .\n```\n\n### Basic Usage\n\n```python\nfrom xtrade_ai import XTradeAIFramework, XTradeAIConfig\n\n# Create configuration\nconfig = XTradeAIConfig()\nconfig.model.baseline_algorithm = \"PPO\"\nconfig.trading.initial_balance = 10000.0\n\n# Initialize framework\nframework = XTradeAIFramework(config)\n\n# Train the model\nframework.train(training_data, epochs=100)\n\n# Make predictions\nprediction = framework.predict(market_data)\nprint(f\"Action: {prediction['action']}, Confidence: {prediction['confidence']}\")\n```\n\n### Command Line Interface\n\n```bash\n# Check framework health\nxtrade-ai health\n\n# Train a model\nxtrade-ai train --config config.yaml --data training_data.csv\n\n# Make predictions\nxtrade-ai predict --model model.pkl --data market_data.csv\n\n# Run backtesting\nxtrade-ai backtest --model model.pkl --data historical_data.csv\n```\n\n## \ud83d\udccb Table of Contents\n\n- [Features](#-features)\n- [Project Structure](#-project-structure)\n- [Architecture](#-architecture)\n- [Installation](#-installation)\n- [Configuration](#-configuration)\n- [Usage Examples](#-usage-examples)\n- [API Reference](#-api-reference)\n- [Advanced Features](#-advanced-features)\n- [Performance Optimization](#-performance-optimization)\n- [Deployment](#-deployment)\n- [Docker Images](#-docker-images)\n- [Troubleshooting](#-troubleshooting)\n- [Contributing](#-contributing)\n- [License](#-license)\n\n## \u2728 Features\n\n### \ud83e\udd16 AI/ML Capabilities\n- **Reinforcement Learning**: PPO, DQN, A2C algorithms from Stable-Baselines3\n- **Ensemble Learning**: Multi-model predictions with weighted averaging\n- **XGBoost Integration**: Gradient boosting for feature selection and prediction\n- **Attention Mechanisms**: Transformer-based models for sequence modeling\n- **Meta-Learning**: Adaptive learning across different market conditions\n\n### \ud83d\udcca Trading Features\n- **Technical Analysis**: 50+ technical indicators with adaptive parameters\n- **Risk Management**: Dynamic position sizing and stop-loss management\n- **Portfolio Management**: Multi-asset portfolio optimization\n- **Market Simulation**: Realistic market environment simulation\n- **Order Management**: Intelligent order placement and execution\n\n### \ud83d\udd27 Technical Features\n- **Thread Safety**: Multi-threaded training and prediction\n- **Memory Management**: Automatic memory cleanup and optimization\n- **Error Handling**: Comprehensive error handling and recovery\n- **Performance Monitoring**: Real-time performance metrics\n- **Model Persistence**: Save/load models with versioning\n\n### \ud83d\udee0\ufe0f Development Features\n- **Modular Design**: Pluggable modules for easy customization\n- **Configuration Management**: YAML/JSON configuration support\n- **CLI Interface**: Command-line tools for all operations\n\n## \ud83d\udcc1 Project Structure\n\n```\nxtrade-ai/\n\u251c\u2500\u2500 docker/           # Docker configurations and images\n\u2502   \u251c\u2500\u2500 Dockerfile.cpu\n\u2502   \u251c\u2500\u2500 Dockerfile.gpu\n\u2502   \u2514\u2500\u2500 docker-compose.yml\n\u251c\u2500\u2500 scripts/          # Build and deployment scripts\n\u2502   \u251c\u2500\u2500 build/        # Build and packaging scripts\n\u2502   \u251c\u2500\u2500 deploy/       # Deployment scripts\n\u2502   \u251c\u2500\u2500 clean/        # Cleanup scripts\n\u2502   \u251c\u2500\u2500 Makefile      # Linux/macOS build commands\n\u2502   \u2514\u2500\u2500 build.ps1     # Windows PowerShell build commands\n\u251c\u2500\u2500 config/           # Configuration files\n\u2502   \u251c\u2500\u2500 env.example   # Environment variables template\n\u2502   \u251c\u2500\u2500 init.sql      # Database initialization\n\u2502   \u251c\u2500\u2500 nginx.conf    # Nginx configuration\n\u2502   \u2514\u2500\u2500 prometheus.yml # Prometheus monitoring\n\u251c\u2500\u2500 requirements/     # Python dependencies\n\u2502   \u251c\u2500\u2500 base.txt      # Core dependencies\n\u2502   \u251c\u2500\u2500 gpu.txt       # GPU dependencies\n\u251c\u2500\u2500 xtrade_ai/        # Main package source code\n\u251c\u2500\u2500 test/             # Test suite\n\u251c\u2500\u2500 docs/             # Documentation\n\u251c\u2500\u2500 logs/             # Application logs\n```\n\n### Quick Commands\n\n```bash\n# Using Makefile (Linux/macOS)\ncd scripts\nmake install\nmake build\nmake deploy\n\n# Using PowerShell (Windows)\ncd scripts\n.\\build.ps1 install\n.\\build.ps1 build\n.\\build.ps1 deploy\n```\n- **Logging**: Comprehensive logging with multiple levels\n- **Testing**: Built-in testing and validation tools\n\n## \ud83c\udfd7\ufe0f Architecture\n\n### Core Components\n\n```\nXTrade-AI Framework\n\u251c\u2500\u2500 Core Framework (xtrade_ai_framework.py)\n\u251c\u2500\u2500 Configuration Management (config.py)\n\u251c\u2500\u2500 Data Processing (data_preprocessor.py)\n\u251c\u2500\u2500 Base Environment (base_environment.py)\n\u251c\u2500\u2500 CLI Interface (cli.py)\n\u2514\u2500\u2500 Modules/\n    \u251c\u2500\u2500 Action Selection (action_selector.py)\n    \u251c\u2500\u2500 Baseline3 Integration (baseline3_integration.py)\n    \u251c\u2500\u2500 Risk Management (risk_management.py)\n    \u251c\u2500\u2500 Technical Analysis (technical_analysis.py)\n    \u251c\u2500\u2500 XGBoost Module (xgboost_module.py)\n    \u251c\u2500\u2500 Monitoring (monitoring.py)\n    \u251c\u2500\u2500 Meta Learning (meta_learning.py)\n    \u2514\u2500\u2500 Optimization (optimization.py)\n```\n\n### Data Flow\n\n```\nMarket Data \u2192 Data Preprocessor \u2192 Feature Engineering \u2192 Model Ensemble \u2192 Trading Decision\n     \u2193              \u2193                    \u2193                \u2193              \u2193\nTechnical    Risk Assessment    Model Validation    Action Selection   Order Execution\nIndicators   Position Sizing    Performance Check   Confidence Score   Portfolio Update\n```\n\n## \ud83d\udce6 Installation\n\n### Prerequisites\n\n- Python 3.8 or higher\n- pip package manager\n- Git (for development)\n\n### Basic Installation\n\n```bash\n# Install from PyPI\npip install xtrade-ai\n```\n\n### Advanced Installation\n\n```bash\n# Install with all optional dependencies\npip install xtrade-ai[all]\n\n# Install specific feature sets\npip install xtrade-ai[ta]      # Technical analysis\npip install xtrade-ai[dev]      # Development tools\npip install xtrade-ai[viz]      # Visualization\npip install xtrade-ai[monitor]  # Monitoring\npip install xtrade-ai[api]      # API server\n```\n\n### Docker Installation\n\n```bash\n# Pull from Docker Hub\ndocker pull anasamu7/xtrade-ai:latest\n\n# Run container\ndocker run -it anasamu7/xtrade-ai:latest xtrade-ai --help\n```\n\n## \u2699\ufe0f Configuration\n\n### Basic Configuration\n\n```python\nfrom xtrade_ai import XTradeAIConfig\n\n# Create default configuration\nconfig = XTradeAIConfig()\n\n# Customize model parameters\nconfig.model.baseline_algorithm = \"PPO\"\nconfig.model.learning_rate = 3e-4\nconfig.model.batch_size = 64\n\n# Customize trading parameters\nconfig.trading.initial_balance = 10000.0\nconfig.trading.commission_rate = 0.001\nconfig.trading.max_position_size = 0.1\n```\n\n### Configuration File (YAML)\n\n```yaml\n# config.yaml\nmodel:\n  baseline_algorithm: \"PPO\"\n  learning_rate: 3e-4\n  batch_size: 64\n  state_dim: 545\n  action_dim: 4\n  enable_xgboost: true\n  enable_risk_management: true\n\ntrading:\n  initial_balance: 10000.0\n  commission_rate: 0.001\n  max_position_size: 0.1\n  stop_loss_pct: 0.02\n  take_profit_pct: 0.05\n\ndata:\n  lookback_window: 100\n  feature_columns: [\"open\", \"high\", \"low\", \"close\", \"volume\"]\n  target_column: \"returns\"\n  train_split: 0.8\n  validation_split: 0.1\n\ntraining:\n  epochs: 100\n  batch_size: 64\n  validation_freq: 10\n  save_freq: 50\n  early_stopping_patience: 10\n```\n\n### Environment Variables\n\n```bash\n# Set environment variables\nexport XTRADE_AI_LOG_LEVEL=INFO\nexport XTRADE_AI_DATA_DIR=/path/to/data\nexport XTRADE_AI_MODEL_DIR=/path/to/models\nexport XTRADE_AI_CONFIG_FILE=/path/to/config.yaml\n```\n\n## \ud83d\udcda Usage Examples\n\n### Basic Training\n\n```python\nfrom xtrade_ai import XTradeAIFramework, XTradeAIConfig\nimport pandas as pd\n\n# Load data\ndata = pd.read_csv('market_data.csv')\n\n# Create configuration\nconfig = XTradeAIConfig()\nconfig.model.baseline_algorithm = \"PPO\"\n\n# Initialize framework\nframework = XTradeAIFramework(config)\n\n# Train model\nframework.train(data, epochs=100, validation_split=0.2)\n\n# Save model\nframework.save_model('trained_model.pkl')\n```\n\n### Advanced Training with Custom Environment\n\n```python\nfrom xtrade_ai import XTradeAIFramework, XTradeAIConfig, BaseEnvironment\n\nclass CustomTradingEnvironment(BaseEnvironment):\n    def __init__(self, data, config):\n        super().__init__(data, config)\n        # Add custom logic here\n    \n    def step(self, action):\n        # Custom step logic\n        return super().step(action)\n\n# Create custom environment\nenv = CustomTradingEnvironment(data, config)\n\n# Train with custom environment\nframework.train_with_environment(env, epochs=100)\n```\n\n### Ensemble Prediction\n\n```python\n# Enable ensemble learning\nconfig.model.enable_ensemble = True\nconfig.model.ensemble_method = \"weighted_average\"\n\n# Initialize framework\nframework = XTradeAIFramework(config)\n\n# Train multiple models\nframework.train_ensemble(data, models=['PPO', 'DQN', 'XGBoost'])\n\n# Make ensemble prediction\nprediction = framework.predict_ensemble(market_data)\nprint(f\"Ensemble Action: {prediction['action']}\")\nprint(f\"Confidence: {prediction['confidence']}\")\nprint(f\"Model Weights: {prediction['weights']}\")\n```\n\n### Real-time Trading\n\n```python\nimport time\nfrom xtrade_ai import XTradeAIFramework\n\n# Load trained model\nframework = XTradeAIFramework.load_model('trained_model.pkl')\n\n# Real-time prediction loop\nwhile True:\n    # Get latest market data\n    market_data = get_latest_market_data()\n    \n    # Make prediction\n    prediction = framework.predict(market_data)\n    \n    # Execute trade based on prediction\n    if prediction['confidence'] > 0.7:\n        execute_trade(prediction['action'])\n    \n    time.sleep(60)  # Wait 1 minute\n```\n\n### Backtesting\n\n```python\nfrom xtrade_ai import XTradeAIFramework\n\n# Load trained model\nframework = XTradeAIFramework.load_model('trained_model.pkl')\n\n# Run backtest\nresults = framework.backtest(\n    historical_data,\n    initial_balance=10000.0,\n    commission_rate=0.001\n)\n\n# Print results\nprint(f\"Total Return: {results['total_return']:.2%}\")\nprint(f\"Sharpe Ratio: {results['sharpe_ratio']:.2f}\")\nprint(f\"Max Drawdown: {results['max_drawdown']:.2%}\")\nprint(f\"Win Rate: {results['win_rate']:.2%}\")\n```\n\n## \ud83d\udd0c API Reference\n\n### Core Classes\n\n#### XTradeAIFramework\n\nMain framework class that orchestrates all components.\n\n```python\nclass XTradeAIFramework:\n    def __init__(self, config: XTradeAIConfig)\n    def train(self, data: pd.DataFrame, epochs: int = 100) -> Dict\n    def predict(self, data: pd.DataFrame) -> Dict\n    def backtest(self, data: pd.DataFrame) -> Dict\n    def save_model(self, path: str) -> None\n    def load_model(self, path: str) -> 'XTradeAIFramework'\n```\n\n#### XTradeAIConfig\n\nConfiguration management class.\n\n```python\nclass XTradeAIConfig:\n    def __init__(self, config_file: str = None)\n    def to_dict(self) -> Dict\n    def from_dict(self, config_dict: Dict) -> None\n    def save(self, path: str) -> None\n    def load(self, path: str) -> None\n```\n\n#### DataPreprocessor\n\nData preprocessing and feature engineering.\n\n```python\nclass DataPreprocessor:\n    def __init__(self, config: XTradeAIConfig)\n    def preprocess(self, data: pd.DataFrame) -> pd.DataFrame\n    def add_technical_indicators(self, data: pd.DataFrame) -> pd.DataFrame\n    def normalize_features(self, data: pd.DataFrame) -> pd.DataFrame\n```\n\n### Data Structures\n\n#### TradingDecision\n\n```python\n@dataclass\nclass TradingDecision:\n    action: ActionType\n    confidence: float\n    timestamp: datetime\n    market_state: MarketState\n    risk_assessment: RiskAssessment\n```\n\n#### MarketState\n\n```python\n@dataclass\nclass MarketState:\n    price: float\n    volume: float\n    technical_indicators: Dict[str, float]\n    market_sentiment: float\n    volatility: float\n```\n\n#### Portfolio\n\n```python\n@dataclass\nclass Portfolio:\n    balance: float\n    positions: Dict[str, Position]\n    total_value: float\n    pnl: float\n    risk_metrics: Dict[str, float]\n```\n\n## \ud83d\ude80 Advanced Features\n\n### Meta-Learning\n\n```python\n# Enable meta-learning\nconfig.model.enable_meta_learning = True\nconfig.model.meta_learning_rate = 0.01\n\n# Train with meta-learning\nframework.train_with_meta_learning(\n    training_data,\n    meta_data,\n    epochs=100\n)\n```\n\n### Custom Reward Functions\n\n```python\ndef custom_reward_function(state, action, next_state, reward):\n    # Add custom reward logic\n    custom_reward = reward * 1.5  # Amplify rewards\n    return custom_reward\n\n# Set custom reward function\nframework.set_reward_function(custom_reward_function)\n```\n\n### Multi-Asset Trading\n\n```python\n# Configure multi-asset trading\nconfig.trading.assets = ['BTC/USD', 'ETH/USD', 'AAPL', 'GOOGL']\nconfig.trading.correlation_threshold = 0.7\n\n# Train multi-asset model\nframework.train_multi_asset(data_dict, epochs=100)\n```\n\n### Real-time Monitoring\n\n```python\n# Enable monitoring\nconfig.monitoring.enable_real_time = True\nconfig.monitoring.metrics = ['sharpe_ratio', 'max_drawdown', 'win_rate']\n\n# Start monitoring\nframework.start_monitoring()\n\n# Get real-time metrics\nmetrics = framework.get_monitoring_metrics()\n```\n\n## \u26a1 Performance Optimization\n\n### Memory Optimization\n\n```python\n# Enable memory optimization\nconfig.performance.enable_memory_optimization = True\nconfig.performance.max_memory_usage = 0.8\n\n# Use memory-efficient training\nframework.train_memory_efficient(data, epochs=100)\n```\n\n### Parallel Processing\n\n```python\n# Enable parallel processing\nconfig.performance.enable_parallel = True\nconfig.performance.num_workers = 4\n\n# Train with parallel processing\nframework.train_parallel(data, epochs=100)\n```\n\n### GPU Acceleration\n\n```python\n# Enable GPU acceleration\nconfig.performance.enable_gpu = True\nconfig.performance.gpu_memory_fraction = 0.8\n\n# Train on GPU\nframework.train_gpu(data, epochs=100)\n```\n\n## \ud83d\udc1b Troubleshooting\n\n### Common Issues\n\n#### Import Errors\n\n```bash\n# Check dependencies\nxtrade-ai health\n\n# Install missing dependencies\npip install -r requirements.txt\n```\n\n#### Memory Issues\n\n```python\n# Reduce batch size\nconfig.model.batch_size = 32\n\n# Enable memory cleanup\nconfig.performance.enable_memory_cleanup = True\n```\n\n#### Training Issues\n\n```python\n# Check data quality\nframework.validate_data(data)\n\n# Adjust learning rate\nconfig.model.learning_rate = 1e-4\n\n# Enable early stopping\nconfig.training.early_stopping_patience = 5\n```\n\n### Debug Mode\n\n```python\n# Enable debug mode\nimport logging\nlogging.basicConfig(level=logging.DEBUG)\n\n# Run with debug information\nframework.train(data, epochs=100, debug=True)\n```\n\n### Performance Profiling\n\n```python\n# Enable performance profiling\nconfig.performance.enable_profiling = True\n\n# Profile training\nframework.train_with_profiling(data, epochs=100)\n```\n\n## \ud83d\ude80 Deployment\n\nXTrade-AI framework supports automated deployment via GitHub Actions with PyPI package publishing and Docker image deployment.\n\n### Automated Deployment\n\nThe framework uses GitHub Actions for continuous deployment:\n\n- **PyPI Publishing**: Automatic package publishing to PyPI\n- **Docker Images**: Multiple optimized Docker images\n- **Smart Triggers**: Only deploys when relevant code changes\n- **Quality Assurance**: Comprehensive testing and validation\n\n### Quick Deployment\n\n```bash\n# Deploy to PyPI (requires credentials)\npip install build twine\npython -m build --wheel --sdist\ntwine upload dist/*\n\n# Deploy Docker images\ndocker build -f Dockerfile.pypi -t xtrade-ai:pypi .\ndocker build -f Dockerfile.minimal -t xtrade-ai:minimal .\ndocker push your-username/xtrade-ai:pypi\n```\n\nFor detailed deployment information, see [DEPLOYMENT.md](DEPLOYMENT.md).\n\n## \ud83d\udc33 Docker Deployment\n\n### CPU Version\n```bash\n# Start CPU version\ndocker-compose --profile cpu up -d\n\n# Or run directly\ndocker run -p 8000:8000 xtrade/xtrade-ai:stable-CPU\n```\n\n### GPU Version\n```bash\n# Start GPU version (requires NVIDIA Docker)\ndocker-compose --profile gpu up -d\n\n# Or run directly\ndocker run --gpus all -p 8000:8000 xtrade/xtrade-ai:stable-GPU\n```\n\n### Minimal Version (Development/Testing)\n```bash\n# Start minimal version\ndocker-compose --profile minimal up -d\n\n# Or run directly\ndocker run -p 8002:8000 xtrade/xtrade-ai:minimal\n```\n\n### Full Stack Deployment\n```bash\n# Deploy complete stack with monitoring\ndocker-compose up -d\n\n# Access services:\n# - API (CPU): http://localhost:8000\n# - API (GPU): http://localhost:8000 (same port, different container)\n# - API (Minimal): http://localhost:8002\n# - Grafana: http://localhost:3000 (admin/admin)\n# - Prometheus: http://localhost:9090\n```\n\n### Docker Images Available\n\n| Image | Tag | Description | Use Case |\n|-------|-----|-------------|----------|\n| `xtrade/xtrade-ai` | `stable-CPU` | CPU optimized version | Production CPU environments |\n| `xtrade/xtrade-ai` | `stable-GPU` | GPU optimized version | Production GPU environments |\n| `xtrade/xtrade-ai` | `1.0.0-CPU` | Versioned CPU release | Specific version deployment |\n| `xtrade/xtrade-ai` | `1.0.0-GPU` | Versioned GPU release | Specific version deployment |\n\n### Building Custom Images\n\nIf you want to build custom Docker images:\n\n```bash\n# Build CPU version\ndocker build -f docker/Dockerfile -t my-xtrade-ai:cpu .\n\n# Build GPU version\ndocker build -f docker/Dockerfile.gpu -t my-xtrade-ai:gpu .\n\n## \ud83e\udd1d Contributing\n\nWe welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.\n\n### Development Setup\n\n```bash\n# Clone repository\ngit clone https://github.com/anasamu/xtrade-ai-framework.git\ncd xtrade-ai-framework\n\n# Install development dependencies\npip install -e \".[dev]\"\n\n# Run tests\npytest\n\n# Run linting\nblack xtrade_ai/\nisort xtrade_ai/\nflake8 xtrade_ai/\n```\n\n### Code Style\n\n- Follow PEP 8 style guidelines\n- Use type hints for all functions\n- Write comprehensive docstrings\n- Add unit tests for new features\n\n## \ud83d\udcc4 License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## \ud83d\ude4f Acknowledgments\n\n- [Stable-Baselines3](https://github.com/DLR-RM/stable-baselines3) for RL algorithms\n- [Gymnasium](https://github.com/Farama-Foundation/Gymnasium) for environment interface\n- [XGBoost](https://github.com/dmlc/xgboost) for gradient boosting\n- [Pandas](https://pandas.pydata.org/) for data manipulation\n- [NumPy](https://numpy.org/) for numerical computing\n\n## \ud83d\udcde Support\n\n- **Documentation**: [https://xtrade-ai-framework.readthedocs.io/en/latest/](https://xtrade-ai-framework.readthedocs.io/en/latest/)\n- **Issues**: [GitHub Issues](https://github.com/anasamu/xtrade-ai-framework/issues)\n- **Email**: <anasamu7@gmail.com>\n\n**Disclaimer**: This framework is for educational and research purposes. Trading involves risk, and past performance does not guarantee future results. Always perform thorough testing before using in live trading.\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "A comprehensive reinforcement learning framework for algorithmic trading",
    "version": "1.2.0",
    "project_urls": {
        "Bug Tracker": "https://github.com/anasamu/xtrade-ai-framework/issues",
        "Documentation": "https://xtrade-ai-framework.readthedocs.io/en/latest/",
        "Homepage": "https://github.com/anasamu/xtrade-ai-framework",
        "Repository": "https://github.com/anasamu/xtrade-ai-framework.git",
        "Source Code": "https://github.com/anasamu/xtrade-ai-framework"
    },
    "split_keywords": [
        "trading",
        " reinforcement-learning",
        " algorithmic-trading",
        " machine-learning",
        " finance",
        " ai",
        " trading-bot",
        " quantitative-finance"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "3551ecca41d20556b38a56b779744f5120f7134da5583c2ccce70a371ba1ae08",
                "md5": "6e3e6c42e952f566f80c0290e8d2f379",
                "sha256": "641be5ea8531e1a629a887f9a4cfde6c56d0eb078dc13f07bbfbf68fa9ac5300"
            },
            "downloads": -1,
            "filename": "xtrade_ai-1.2.0-py3-none-manylinux_2_17_x86_64.whl",
            "has_sig": false,
            "md5_digest": "6e3e6c42e952f566f80c0290e8d2f379",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<3.14,>=3.8",
            "size": 26231073,
            "upload_time": "2025-09-01T18:09:19",
            "upload_time_iso_8601": "2025-09-01T18:09:19.932171Z",
            "url": "https://files.pythonhosted.org/packages/35/51/ecca41d20556b38a56b779744f5120f7134da5583c2ccce70a371ba1ae08/xtrade_ai-1.2.0-py3-none-manylinux_2_17_x86_64.whl",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2025-09-01 18:09:19",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "anasamu",
    "github_project": "xtrade-ai-framework",
    "github_not_found": true,
    "lcname": "xtrade-ai"
}
        
Elapsed time: 1.57417s