Spaces:
Configuration error
Configuration error
File size: 10,071 Bytes
91ac0d2 778d63d 91ac0d2 |
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 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
# ๐ค Financial AI Predictor
An advanced machine learning system for stock price prediction using ensemble models and comprehensive feature engineering.




## ๐ฏ Overview
Financial AI Predictor combines state-of-the-art machine learning models with advanced financial feature engineering to predict stock prices. Built with robustness and educational value in mind, it demonstrates best practices for applying ML to financial markets.
### โจ Key Features
- ๐ง **Ensemble ML Models**: Random Forest + Gradient Boosting + Ridge Regression
- ๐ **Advanced Feature Engineering**: 50+ technical indicators and market features
- โฐ **Real-time Data**: Live market data from Yahoo Finance
- ๐ฌ **Robust Validation**: Time series cross-validation with walk-forward analysis
- ๐ฏ **Uncertainty Quantification**: Confidence intervals and model consensus
- ๐ **Interactive Interface**: Professional Gradio web interface
- ๐ **No API Keys**: 100% free public data sources
## ๐ Quick Start
### Installation
```bash
# Clone the repository
git clone https://github.com/yourusername/financial-ai-predictor.git
cd financial-ai-predictor
# Install dependencies
pip install -r requirements.txt
# Run the application
python financial_ai_predictor.py
```
### Docker Setup (Optional)
```bash
# Build Docker image
docker build -t financial-ai-predictor .
# Run container
docker run -p 7860:7860 financial-ai-predictor
```
### Basic Usage
1. **Launch the app**: `python financial_ai_predictor.py`
2. **Open browser**: Navigate to `http://localhost:7860`
3. **Enter stock symbol**: e.g., "AAPL", "GOOGL", "TSLA"
4. **Click "Run AI Analysis"**: Wait for model training and prediction
5. **Review results**: Analysis report, charts, and feature importance
## ๐ How It Works
### 1. Data Collection
- Downloads 2 years of historical OHLCV data from Yahoo Finance
- Real-time price and volume information
- Automatic data quality checks and cleaning
### 2. Feature Engineering
```python
# Technical Indicators
- Price momentum (5, 20 day)
- Moving averages (5, 10, 20, 50 day)
- RSI, MACD, Bollinger Bands
- ADX, Stochastic, Williams %R
- Volume indicators (OBV, CMF, VWAP)
# Market Regime Features
- Volatility ratios and regimes
- Trend strength indicators
- Gap analysis and fill rates
- Price-volume relationships
```
### 3. Model Architecture
```python
# Ensemble Models
models = {
'random_forest': RandomForestRegressor(n_estimators=200),
'gradient_boost': GradientBoostingRegressor(n_estimators=150),
'ridge': Ridge(alpha=1.0)
}
# Time Series Validation
validation = TimeSeriesSplit(n_splits=5)
```
### 4. Prediction Pipeline
1. **Feature Extraction**: Calculate all technical indicators
2. **Model Inference**: Each model generates independent prediction
3. **Ensemble**: Performance-weighted average of predictions
4. **Uncertainty**: Confidence intervals from model disagreement
## ๐ Supported Assets
- **US Stocks**: All NYSE, NASDAQ listed companies
- **International Stocks**: Major global exchanges
- **ETFs**: Index funds, sector ETFs, commodity ETFs
- **Cryptocurrencies**: BTC-USD, ETH-USD, and major coins
- **Market Indices**: S&P 500 (^GSPC), NASDAQ (^IXIC), Dow Jones
### Example Symbols
```
AAPL, GOOGL, MSFT, TSLA, NVDA, AMZN, META
SPY, QQQ, VTI, IWM, GLD, SLV
BTC-USD, ETH-USD, ADA-USD
^GSPC, ^IXIC, ^DJI, ^VIX
```
## ๐ฌ Technical Details
### Feature Engineering Pipeline
```python
def extract_features(data):
features = pd.DataFrame()
# Price features
features['returns'] = data['Close'].pct_change()
features['log_returns'] = np.log(data['Close'] / data['Close'].shift(1))
# Technical indicators
features['rsi'] = ta.momentum.rsi(data['Close'])
features['macd'] = ta.trend.macd_diff(data['Close'])
features['bb_position'] = calculate_bollinger_position(data['Close'])
# Volume features
features['volume_ratio'] = data['Volume'] / data['Volume'].rolling(20).mean()
features['obv'] = ta.volume.on_balance_volume(data['Close'], data['Volume'])
return features
```
### Model Training
```python
# Time series cross-validation
tscv = TimeSeriesSplit(n_splits=5)
for train_idx, val_idx in tscv.split(features):
X_train = features.iloc[train_idx]
y_train = targets.iloc[train_idx]
model.fit(X_train, y_train)
score = model.score(X_val, y_val)
```
### Performance Metrics
- **Rยฒ Score**: Coefficient of determination
- **MAE**: Mean Absolute Error
- **RMSE**: Root Mean Square Error
- **Directional Accuracy**: Percentage of correct direction predictions
## ๐ Example Output
```
๐ค FINANCIAL AI PREDICTOR - AAPL
๐ CURRENT STATUS
โข Current Price: $182.50
โข Analysis Date: 2025-01-15 14:30:00
โข Recommendation: ๐ข BUY
๐ฏ ENSEMBLE PREDICTION
โข Next Day Target: $184.20
โข Expected Return: +0.93%
โข Prediction Confidence: 73.5%
๐ค MODEL PERFORMANCE
โข Random Forest: Rยฒ = 0.0847 ยฑ 0.0234
โข Gradient Boost: Rยฒ = 0.0756 ยฑ 0.0198
โข Ridge: Rยฒ = 0.0542 ยฑ 0.0156
๐ง TOP PREDICTIVE FEATURES
โข rsi: 0.0234
โข bb_position: 0.0198
โข volume_ratio: 0.0176
โข macd: 0.0145
```
## ๐ฏ Best Practices
### For Users
1. **Diversification**: Never rely on a single prediction
2. **Risk Management**: Use appropriate position sizing
3. **Validation**: Cross-check with fundamental analysis
4. **Timeframes**: Consider multiple prediction horizons
5. **Market Conditions**: Be aware of regime changes
### For Developers
1. **Feature Engineering**: Domain knowledge is crucial
2. **Validation**: Always use time series aware validation
3. **Overfitting**: Monitor out-of-sample performance
4. **Data Quality**: Clean and validate input data
5. **Model Updates**: Retrain periodically
## โ ๏ธ Important Disclaimers
### ๐ Educational Purpose
This tool is designed for:
- Learning about machine learning in finance
- Understanding feature engineering techniques
- Demonstrating ensemble methods
- Exploring financial data analysis
### ๐ Risk Warnings
- **Not Financial Advice**: Predictions are for educational purposes only
- **Past Performance**: Does not guarantee future results
- **Model Limitations**: Cannot predict black swan events
- **Market Risk**: All investments carry risk of loss
- **Professional Advice**: Consult qualified financial advisors
### ๐ฌ Technical Limitations
- **Market Efficiency**: Predictable patterns may be arbitraged away
- **Regime Changes**: Models may fail during market shifts
- **Data Dependency**: Quality depends on input data
- **Overfitting**: Historical patterns may not persist
## ๐ ๏ธ Configuration
### Environment Variables
```bash
# Optional: Set data cache directory
export YFINANCE_CACHE_DIR="/path/to/cache"
# Optional: Set log level
export LOG_LEVEL="INFO"
```
### Custom Configuration
```python
# Modify model parameters
MODELS_CONFIG = {
'random_forest': {
'n_estimators': 200,
'max_depth': 15,
'min_samples_split': 5
},
'gradient_boost': {
'n_estimators': 150,
'max_depth': 8,
'learning_rate': 0.1
}
}
# Modify feature engineering
FEATURE_CONFIG = {
'ma_periods': [5, 10, 20, 50],
'momentum_periods': [5, 10, 20],
'volatility_windows': [5, 20, 60]
}
```
## ๐งช Testing
```bash
# Run basic tests
python -m pytest tests/
# Test specific components
python -m pytest tests/test_features.py
python -m pytest tests/test_models.py
# Run with coverage
pytest --cov=financial_ai_predictor tests/
```
## ๐ Dependencies
### Core Requirements
- **Python**: 3.8+
- **NumPy**: Scientific computing
- **Pandas**: Data manipulation
- **Scikit-learn**: Machine learning models
- **yfinance**: Financial data
- **TA**: Technical analysis indicators
- **Gradio**: Web interface
- **Plotly**: Interactive visualizations
### Optional Enhancements
- **SciPy**: Advanced statistical functions
- **Statsmodels**: Econometric models
- **Jupyter**: Interactive development
## ๐ค Contributing
1. **Fork** the repository
2. **Create** a feature branch (`git checkout -b feature/amazing-feature`)
3. **Commit** your changes (`git commit -m 'Add amazing feature'`)
4. **Push** to the branch (`git push origin feature/amazing-feature`)
5. **Open** a Pull Request
### Development Setup
```bash
# Clone for development
git clone https://github.com/yourusername/financial-ai-predictor.git
cd financial-ai-predictor
# Install development dependencies
pip install -r requirements-dev.txt
# Run in development mode
python financial_ai_predictor.py --debug
```
## ๐ License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
## ๐ Acknowledgments
- **Yahoo Finance**: For providing free financial data
- **TA-Lib**: Technical analysis library
- **Scikit-learn**: Machine learning framework
- **Gradio**: Easy-to-use ML interfaces
- **Plotly**: Interactive visualization library
## ๐ Support
- **Issues**: [GitHub Issues](https://github.com/yourusername/financial-ai-predictor/issues)
- **Discussions**: [GitHub Discussions](https://github.com/yourusername/financial-ai-predictor/discussions)
- **Email**: your.email@example.com
## ๐ฎ Roadmap
### Version 2.0
- [ ] Deep learning models (LSTM, Transformer)
- [ ] Alternative data integration
- [ ] Multi-asset portfolio optimization
- [ ] Real-time streaming predictions
- [ ] Advanced risk metrics
### Version 1.5
- [ ] Options pricing models
- [ ] Sector rotation analysis
- [ ] Economic indicators integration
- [ ] Backtesting framework
- [ ] Performance attribution
---
**โญ Star this repository if you find it useful!**
**๐ Found a bug? Please open an issue.**
**๐ก Have an idea? Start a discussion.**
---
*Built with โค๏ธ for the financial ML community* |