A comprehensive cryptocurrency trading system that uses linear regression models to predict price movements and execute trades based on technical indicators and market data from Coinbase.
π Live Demo: Generate real crypto price predictions using machine learning!
git clone https://github.com/Deftextra/crypto_trader.git
cd crypto_trader
python3 -m venv venv
source venv/bin/activate
pip install -r requirements.txt
python main.py --mode predict --symbol BTC-USD
- Data Collection: Fetches real-time and historical cryptocurrency data from Coinbase Pro API
- Feature Engineering: Creates 100+ technical indicators and features from raw price data
- Machine Learning: Implements multiple linear regression models with feature selection
- Trading Strategy: Executes trades based on model predictions with risk management
- Backtesting: Comprehensive backtesting framework with performance analytics
- Visualization: Creates detailed performance reports and charts
- Risk Management: Position sizing, stop-loss, take-profit, and drawdown controls
crypto_trader/
βββ data/
β βββ __init__.py
β βββ collector.py # Data collection from Coinbase API
βββ utils/
β βββ __init__.py
β βββ features.py # Feature engineering and technical indicators
βββ models/
β βββ __init__.py
β βββ linear_model.py # Linear regression models
β βββ saved/ # Directory for saved models
βββ strategies/
β βββ __init__.py
β βββ linear_strategy.py # Trading strategy implementation
βββ backtesting/
β βββ __init__.py
β βββ backtest.py # Backtesting framework
βββ output/ # Generated visualizations and reports
βββ main.py # Main application entry point
βββ requirements.txt # Python dependencies
βββ README.md # This file
- Clone or create the project directory:
mkdir crypto_trader
cd crypto_trader
- Create a virtual environment:
python3 -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies:
pip install -r requirements.txt
The system supports four main modes of operation:
Train a model on historical data and save it for later use:
python main.py --mode train --symbol BTC-USD --days 90
Run a complete backtest on historical data:
python main.py --mode backtest --symbol BTC-USD --days 60 --save-viz
Options:
--save-viz
: Save performance visualizations--output-dir
: Specify output directory for results
Generate price predictions for current market conditions:
python main.py --mode predict --symbol BTC-USD
Or use a previously saved model:
python main.py --mode predict --symbol BTC-USD --model-path models/saved/BTC-USD_20240115_143022.joblib
Compare different model configurations:
python main.py --mode compare --symbol BTC-USD --days 60
The system works with any cryptocurrency pair available on Coinbase Pro. Popular pairs include:
- BTC-USD (Bitcoin)
- ETH-USD (Ethereum)
- ADA-USD (Cardano)
- DOT-USD (Polkadot)
- LINK-USD (Chainlink)
- LTC-USD (Litecoin)
- XLM-USD (Stellar)
- ALGO-USD (Algorand)
The system uses default configuration parameters that can be customized by modifying the _get_default_config()
method in main.py
:
config = {
# Data parameters
'symbol': 'BTC-USD',
'days': 60,
'granularity': 3600, # 1 hour intervals
# Model parameters
'model_type': 'ridge', # 'linear', 'ridge', 'lasso', 'elastic'
'feature_selection': 'kbest', # 'none', 'kbest', 'rfe'
'n_features': 15,
'target_hours': 1, # Prediction horizon
# Strategy parameters
'prediction_threshold': 0.5, # Minimum prediction confidence (%)
'lookback_periods': 5,
# Risk management
'initial_capital': 10000,
'max_position_size': 0.1, # 10% of portfolio
'stop_loss_pct': 0.02, # 2% stop loss
'take_profit_pct': 0.04, # 4% take profit
'max_drawdown_pct': 0.1, # 10% max drawdown
'min_prediction_confidence': 0.01,
# Backtesting
'commission': 0.001, # 0.1% commission
'slippage': 0.001 # 0.1% slippage
}
The system automatically generates 100+ features from raw OHLCV data:
- Moving Averages (SMA, EMA) with multiple periods
- Bollinger Bands
- RSI (Relative Strength Index)
- MACD (Moving Average Convergence Divergence)
- Stochastic Oscillator
- Average True Range (ATR)
- Williams %R
- Price changes and returns
- High-low percentage ranges
- Volume-weighted average price (VWAP)
- Price position within daily range
- Rolling means, standard deviations, min/max
- Volatility measures
- Skewness of price movements
- Historical values of key indicators
- Multiple lookback periods
- Hour of day, day of week, month
- Cyclical encoding of time features
The system supports multiple linear regression variants:
- Linear Regression: Basic linear regression
- Ridge Regression: L2 regularization for feature stability
- Lasso Regression: L1 regularization for feature selection
- Elastic Net: Combined L1/L2 regularization
The system includes comprehensive risk management:
- Position Sizing: Based on portfolio value and prediction confidence
- Stop Loss: Automatic loss cutting at specified percentage
- Take Profit: Profit taking at target levels
- Maximum Drawdown: Trading halt if losses exceed threshold
- Confidence Threshold: Only trade on high-confidence predictions
Backtesting provides detailed performance analytics:
- Total return, annual return
- Risk-adjusted returns (Sharpe, Sortino, Calmar ratios)
- Maximum drawdown
- Volatility
- Value at Risk (VaR)
- Conditional VaR
- Total trades, win rate
- Average win/loss
- Profit factor
- Trade duration statistics
The system generates comprehensive performance reports including:
- Portfolio value over time
- Drawdown charts
- Returns distribution
- Price charts with trading signals
- Rolling performance metrics
==================================================
BACKTEST RESULTS
==================================================
Symbol: BTC-USD
Period: 60 days
Initial Capital: $10,000.00
Final Value: $10,847.32
Total Return: 8.47%
Annual Return: 51.82%
Volatility: 45.23%
Sharpe Ratio: 1.15
Max Drawdown: -12.34%
Total Trades: 23
Win Rate: 60.87%
Profit Factor: 1.67
- Educational Purpose: This system is for educational and research purposes only
- No Financial Advice: Not intended as financial advice or recommendations
- Past Performance: Past performance does not guarantee future results
- Market Risk: Cryptocurrency trading involves substantial risk of loss
- No Warranty: The system is provided "as-is" without warranties
The system respects Coinbase Pro API rate limits by:
- Adding delays between requests
- Using reasonable request frequencies
- Caching data when possible
To contribute to this project:
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
This project is provided for educational purposes. Use at your own risk.
For issues or questions:
- Check the logs in
crypto_trader.log
- Review the error messages
- Ensure all dependencies are installed
- Verify API connectivity
- Initial release
- Basic linear regression models
- Coinbase data integration
- Comprehensive backtesting
- Risk management system
- Performance visualization