# Trading Algorithm Project A production-ready modular trading system that supports multiple strategies for paper and live trading on Alpaca Markets. ## Features - **Multiple Strategy Support**: Conservative and Enhanced trend-following strategies - **Paper & Live Trading**: Safe testing with paper trading, production-ready for live trading - **Modular Architecture**: Clean separation of concerns for easy maintenance - **Risk Management**: Position sizing, drawdown limits, and trailing stops - **Professional Logging**: Comprehensive trade and performance logging - **Configuration Management**: Environment-based and file-based configuration - **Strategy Comparison**: Built-in tools to compare strategy performance ## Project Structure ``` trading/ ├── src/ │ ├── data_handler.py # Market data retrieval and processing │ ├── strategy_conservative.py # Conservative trend-following strategy │ ├── strategy_enhanced.py # Enhanced trend-following with tighter risk controls │ ├── strategy_factory.py # Strategy selection and instantiation │ ├── risk_manager.py # Position sizing and risk controls │ ├── trading_engine.py # Main trading execution engine │ └── logger_setup.py # Logging configuration ├── config/ │ └── trading_config.py # Configuration settings ├── logs/ # Generated log files ├── main.py # Application entry point ├── compare_strategies.py # Strategy comparison tool └── README.md ``` ## Strategy Types ### Conservative Strategy - **Philosophy**: Let big winners run, relaxed exit conditions - **Trailing Stops**: 18-40% (wider range for bigger moves) - **Emergency Exits**: 28-day maximum hold time - **Best For**: Trending markets, patient traders ### Enhanced Strategy - **Philosophy**: Tighter risk control, early loss protection - **Trailing Stops**: 12-40% (tighter range for quicker exits) - **Emergency Exits**: 7-14 day maximum hold time - **Entry Conditions**: More selective (2% above trend line) - **Best For**: Volatile markets, risk-conscious traders ## Quick Start ### 1. Setup Environment ```bash # Clone and navigate to project cd /path/to/trading # Install dependencies pip install alpaca-trade-api pandas numpy python-dotenv # Setup environment variables echo "ALPACA_API_KEY=your_api_key" > .env echo "ALPACA_SECRET_KEY=your_secret_key" >> .env echo "ALPACA_BASE_URL=https://paper-api.alpaca.markets" >> .env echo "STRATEGY_TYPE=enhanced" >> .env ``` ### 2. Run Backtesting ```bash # Test conservative strategy python3 main.py --mode backtest --strategy conservative # Test enhanced strategy python3 main.py --mode backtest --strategy enhanced # Compare both strategies python3 compare_strategies.py ``` ### 3. Paper Trading ```bash # Start paper trading with enhanced strategy python3 main.py --mode paper --strategy enhanced # Start paper trading with conservative strategy python3 main.py --mode paper --strategy conservative ``` ## Configuration ### Environment Variables - `ALPACA_API_KEY`: Your Alpaca API key - `ALPACA_SECRET_KEY`: Your Alpaca secret key - `ALPACA_BASE_URL`: API endpoint (paper or live) - `STRATEGY_TYPE`: Default strategy ("conservative" or "enhanced") ### Strategy Selection You can select strategies in multiple ways: 1. **Command Line**: `--strategy enhanced` 2. **Environment Variable**: `STRATEGY_TYPE=conservative` 3. **Config File**: Modify `trading_config.py` Priority: Command line > Environment variable > Config file ## Usage Examples ```bash # Backtest enhanced strategy for 90 days python3 main.py --mode backtest --strategy enhanced --days 90 # Paper trade with conservative strategy python3 main.py --mode paper --strategy conservative # Compare strategies side-by-side python3 compare_strategies.py # Check strategy configuration python3 -c "from config.trading_config import TradingConfig; print(TradingConfig())" ``` ## Strategy Comparison The `compare_strategies.py` script provides detailed performance comparison: - **Returns**: Total return vs market benchmark - **Risk Metrics**: Max drawdown, Sharpe ratio - **Trade Analytics**: Win rate, profit factor, average wins/losses - **Timing**: Time in market, trade frequency ## Risk Management Both strategies include comprehensive risk controls: - **Position Sizing**: Configurable risk per trade - **Trailing Stops**: Dynamic stop-loss adjustment - **Emergency Exits**: Maximum hold time limits - **Drawdown Limits**: Account protection thresholds - **Market Hours**: Trading only during market hours ## Logging The system generates detailed logs in the `logs/` directory: - `trading.log`: General trading activity - `trades.log`: Trade execution details - `risk.log`: Risk management events - `performance.log`: Performance metrics ## Safety Features - **Paper Trading First**: Always test with paper money - **Fail-Safe Defaults**: Conservative settings by default - **Error Handling**: Graceful error recovery - **Position Limits**: Maximum position size controls - **Market Data Validation**: Data quality checks ## Development To add a new strategy: 1. Create new strategy file in `src/strategy_your_name.py` 2. Inherit from base strategy pattern (see existing strategies) 3. Register in `src/strategy_factory.py` 4. Update configuration options 5. Test with backtesting before live usage ## Support For issues or questions: 1. Check logs in `logs/` directory 2. Verify API keys and permissions 3. Test with paper trading first 4. Review strategy configuration ## Disclaimer This software is for educational and testing purposes. Always test thoroughly with paper trading before using real money. Past performance does not guarantee future results.