AcyLa's picture
Update ML Intern artifact metadata
21d3e25 verified
|
Raw History Blame Contribute Delete
9.4 kB
---
tags:
- ml-intern
---
# Multi-Asset Predictive Model
**Ensemble ML pipeline (LightGBM + LSTM with attention) covering 14 ETFs, commodities, and international market assets.**
Trained on 15+ years of Yahoo Finance historical data with 202+ engineered features per asset, including Nadaraya-Watson envelope estimation and multi-window Bollinger Band systems.
---
## Covered Assets
### US ETFs & Commodities
| Ticker | Name | Bars | Date Range |
|--------|------|------|------------|
| QQQ | Invesco QQQ (Nasdaq 100) | 6,920 | 1999–2026 |
| SPY | SPDR S&P 500 ETF | 8,462 | 1993–2026 |
| GLD | SPDR Gold Shares | 5,487 | 2004–2026 |
| SLV | iShares Silver Trust | 5,125 | 2006–2026 |
| USO | US Oil Fund (Crude Oil) | 5,138 | 2006–2026 |
### Non-US Market ETFs
| Ticker | Name | Market | Bars |
|--------|------|--------|------|
| EEM | iShares Emerging Markets | Emerging Markets | 5,891 |
| EFA | iShares MSCI EAFE | Developed non-US | 6,297 |
| EWJ | iShares MSCI Japan | Japan | 7,671 |
| EWG | iShares MSCI Germany | Germany | 7,671 |
| EWU | iShares MSCI United Kingdom | UK | 7,671 |
| FXI | iShares China Large-Cap | China | 5,516 |
| INDA | iShares MSCI India | India | 3,672 |
| EWZ | iShares MSCI Brazil | Brazil | 6,579 |
| KWEB | KraneShares China Internet | China Internet | 3,298 |
---
## Architecture
```
Data Download (Yahoo Finance) β†’ Feature Engineering (202+ indicators) β†’ Label Generation (multi-horizon) β†’ LightGBM + LSTM Ensemble β†’ Prediction API
```
### Feature Categories (202+ per asset)
1. **Nadaraya-Watson Envelope** β€” Vectorized kernel regression for trend smoothing + overbought/oversold envelopes (10 features)
2. **Bollinger Bands (multi-window)** β€” 3 windows (20/50/100) Γ— 3 std devs (2.0/2.5/3.0) = 45 BB features, including squeeze detection and band-walk signals
3. **Trend** β€” EMA (9/21/50/100/200), SMA (20/50/100/200), MACD, ADX, Ichimoku Cloud (30+ features)
4. **Momentum** β€” RSI (7/14/21), Stochastic, Williams %R, ROC, CCI, Awesome Oscillator (20+ features)
5. **Volatility** β€” ATR (14/21/50), Keltner Channel, Donchian Channel, Historical Volatility (20+ features)
6. **Volume** β€” OBV, MFI, CMF, VWAP (10/20/50), Volume Ratio (10+ features)
7. **Price Structure** β€” Multi-horizon returns, candlestick patterns, drawdown, HH/LL detection (40+ features)
8. **Calendar** β€” Day of week, month, quarter-end effects (10 features)
9. **Cross-Asset Correlation** β€” Beta and rolling correlation with SPY and GLD benchmarks (15+ features)
### Model Architecture
- **LightGBM** β€” Gradient-boosted trees for tabular features. 300 estimators, 127 leaves, feature_fraction=0.7
- **LSTM with Attention** β€” 2-layer LSTM (hidden=128) with attention pooling, LayerNorm, GELU head. Sequence length=60
- **Ensemble** β€” Weighted average of LightGBM + LSTM, weights auto-tuned on validation set
### Prediction Horizons
- **1-day** (next session)
- **5-day** (1 week)
- **21-day** (1 month)
### Labeling
- **Regression** β€” Future return: `close[t+h] / close[t] - 1`
- **Classification** β€” Directional: BUY (>+2%), SELL (<-2%), HOLD (between)
- **Triple-Barrier** β€” LΓ³pez de Prado method with upper/lower barriers and time stop
---
## Training Results (Quick Split β€” 70/15/15)
| Asset | 1d Dir.Acc | 5d Dir.Acc | 21d Dir.Acc | Best Sharpe |
|-------|-----------|-----------|------------|-------------|
| **SPY** | 56.8% | 62.5% | **72.0%** | 7.23 |
| **QQQ** | 54.3% | 59.4% | **68.7%** | 6.25 |
| **EFA** | 52.7% | 57.7% | **67.9%** | 5.93 |
| **EWU** | 53.2% | 59.2% | **67.5%** | 6.80 |
| **EWJ** | 49.9% | 51.1% | **69.4%** | 5.60 |
| **EEM** | 46.5% | 57.3% | **64.1%** | 5.74 |
| **EWG** | 54.2% | 54.7% | 52.3% | 2.34 |
| **EWZ** | 49.6% | 55.5% | 55.7% | 1.98 |
| **FXI** | 51.1% | 53.0% | 53.5% | 3.45 |
| **USO** | 46.0% | 48.8% | 50.6% | 1.44 |
| **GLD** | 47.8% | 40.6% | 40.4% | -0.19 |
| **SLV** | 49.4% | 44.4% | 36.8% | -0.13 |
| **INDA** | 48.5% | 44.2% | 49.5% | 0.22 |
| **KWEB** | 46.7% | 50.9% | 47.6% | -0.26 |
**Key findings:**
- **US equity ETFs (SPY, QQQ) show the strongest predictability** at 21-day horizon (69-72% directional accuracy, Sharpe 6-7)
- **Developed market ETFs (EFA, EWU, EWJ, EWG)** also show strong 21-day signals (52-69%)
- **Emerging markets (EEM, EWZ)** show moderate predictability at 5-21 day horizons
- **Commodities (GLD, SLV, USO) and India/China (INDA, KWEB)** are harder to predict β€” closer to 50% (random) at most horizons
- **1-day predictions** are near 50% for most assets β€” consistent with efficient market hypothesis at short horizons
---
## Usage
### Install
```bash
pip install yfinance pandas numpy scikit-learn lightgbm ta torch pyarrow joblib scipy huggingface_hub
```
### Predict β€” Single Asset
```bash
python predict.py --ticker QQQ
# Output:
# QQQ β€” Invesco QQQ (Nasdaq 100)
# Consensus: BUY (1/3)
# h= 1d: HOLD conf=50% pred=-0.0077
# h= 5d: HOLD conf=50% pred=+0.0042
# h=21d: BUY conf=65% pred=+0.0130
```
### Predict β€” All Assets
```bash
python predict.py --all
# Output:
# QQQ: BUY (1/3)
# SPY: HOLD (3/3)
# GLD: HOLD (3/3)
# ...
```
### Fast Mode (LightGBM only, no LSTM)
```bash
python predict.py --ticker SPY --no-lstm
```
### Python API
```python
from predict import AssetPredictor
predictor = AssetPredictor("QQQ")
results = predictor.get_multi_horizon()
print(results['consensus']) # "BUY (2/3)"
for h in [1, 5, 21]:
print(f"{h}d: {results[h]['signal']} conf={results[h]['confidence']:.0%}")
```
### Retrain Models
```bash
# Single asset
python train.py --ticker QQQ
# All assets
python train.py --all
# With walk-forward backtest
python train.py --all --backtest
# LightGBM only (faster)
python train.py --all --no-lstm
```
---
## File Structure
```
multi_asset_predictor/
β”œβ”€β”€ config.py # All hyperparameters (assets, features, model params)
β”œβ”€β”€ data_loader.py # Yahoo Finance download with parquet caching
β”œβ”€β”€ nadaraya_watson.py # Vectorized NW envelope estimator
β”œβ”€β”€ features.py # 202+ feature engineering (NW, BB, trend, momentum, etc.)
β”œβ”€β”€ labels.py # Multi-horizon regression + classification + triple-barrier
β”œβ”€β”€ models.py # LightGBMPredictor + LSTMPredictor + EnsemblePredictor
β”œβ”€β”€ backtest.py # Walk-forward CV with purging (LΓ³pez de Prado)
β”œβ”€β”€ train.py # CLI training pipeline
β”œβ”€β”€ batch_train.py # Batch LightGBM training for all assets
β”œβ”€β”€ batch_train_lstm.py # Batch LSTM training for all assets
β”œβ”€β”€ predict.py # Prediction API + CLI
β”œβ”€β”€ asset_models/ # Trained models (per-ticker subdirectories)
β”‚ β”œβ”€β”€ QQQ/
β”‚ β”‚ β”œβ”€β”€ lgbm_h1.joblib # LightGBM model (1-day horizon)
β”‚ β”‚ β”œβ”€β”€ lgbm_h5.joblib # LightGBM model (5-day horizon)
β”‚ β”‚ β”œβ”€β”€ lgbm_h21.joblib # LightGBM model (21-day horizon)
β”‚ β”‚ β”œβ”€β”€ lstm_h1.pt # LSTM model (1-day horizon)
β”‚ β”‚ β”œβ”€β”€ lstm_h5.pt # LSTM model (5-day horizon)
β”‚ β”‚ β”œβ”€β”€ lstm_h21.pt # LSTM model (21-day horizon)
β”‚ β”‚ β”œβ”€β”€ weights_h*.joblib # Ensemble weights per horizon
β”‚ β”‚ β”œβ”€β”€ feature_cols.joblib # Feature column names
β”‚ β”‚ └── meta.json # Asset metadata
β”‚ β”œβ”€β”€ SPY/ ...
β”‚ └── ... (14 assets total)
└── asset_results/ # Evaluation metrics (JSON per asset)
```
---
## Data Provenance
- **Source**: Yahoo Finance (yfinance API)
- **Data**: OHLCV (Open/High/Low/Close/Volume), auto-adjusted
- **Interval**: Daily (1d)
- **History**: 15-30 years depending on asset (1993-2026 for SPY, 1999-2026 for QQQ)
- **Caching**: Parquet files in `asset_data_cache/`
## Key Design Decisions
1. **No target leakage** β€” Target columns (`Target_*`) are excluded from features. Verified via feature importance check.
2. **Three-way split** β€” 70% train / 15% validation / 15% test (chronological, no overlap)
3. **Walk-forward ready** β€” Full walk-forward with purging available via `--backtest` flag
4. **Cross-asset features** β€” Beta and rolling correlation with SPY and GLD benchmarks
5. **Nadaraya-Watson vectorized** β€” Uses `sliding_window_view` for O(n) computation (vs O(nΒ²) naive)
6. **Multi-window Bollinger** β€” 9 Bollinger Band variants per asset + squeeze + band-walk signals
## Honest Assessment
- 50-55% directional accuracy at 1-day horizon is statistically meaningful (markets are efficient at short horizons)
- 55-72% at 21-day horizon for trending assets (SPY, QQQ, EFA, EWU, EWJ) represents a genuine edge
- Commodities and some emerging markets are harder to predict β€” closer to random
- These models provide signal, not certainty. Always use risk management (stop-losses, position sizing)
- For production: retrain monthly, use walk-forward backtesting, add sentiment/on-chain features
## Dependencies
`yfinance pandas numpy scikit-learn lightgbm ta torch pyarrow joblib scipy huggingface_hub`
<!-- ml-intern-provenance -->
## Generated by ML Intern
This model repository was generated by [ML Intern](https://github.com/huggingface/ml-intern), an agent for machine learning research and development on the Hugging Face Hub.
- Try ML Intern: https://smolagents-ml-intern.hf.space
- Source code: https://github.com/huggingface/ml-intern