jonyling/eth-usd-price-prediction
收藏资源简介:
# ETH-USD 4h Price Direction Model A production-grade machine learning pipeline that predicts **4-hour forward returns** for ETH/USD using 1-minute Binance OHLCV data fused with 7 years of Ethereum on-chain metrics from Dune Analytics. --- ## Project Overview | | | |---|---| | **Target** | 4h forward return: `close[t+4] / close[t] - 1` | | **Model** | LightGBM Regressor (Optuna-tuned) | | **Bar size** | 1h (resampled from 1-min) | | **Features** | 84 (price, volume, technicals, on-chain, cyclical) | | **Training data** | ~52,000 hourly bars (~7 years) | | **Train / Holdout split** | 80 / 20 (time-based) | --- ## Backtest Results (Out-of-Sample Holdout) | Metric | Value | |---|---| | Sharpe Ratio | **2.8** | | Cumulative Return | **+39.7%** | | Max Drawdown | **-4.3%** | | Win Rate | **74.2%** | | Number of Trades | 58 | | Trading cost | 0.10% per trade (Binance Spot w/ BNB) | ### Robustness Checks | Test | Result | |---|---| | Data leakage | ✅ PASS | | OOS stability (both halves Sharpe > 0) | ✅ PASS | | Monte Carlo (100 paths, % positive Sharpe) | ✅ PASS — 100% | --- ## Feature Categories - **Price returns**: 1h, 2h, 4h, 6h, 12h, 24h, 48h, 168h lookback - **Candle structure**: body ratio, range %, close location value, gap high/low - **Moving averages**: SMA and price-vs-SMA at 4h, 12h, 24h, 48h, 168h - **Volume**: volume ratios, volatility, OBV - **Technical indicators**: RSI (6h, 14h, 24h), MACD, Bollinger Bands - **On-chain (Ethereum)**: transaction count, active senders/receivers, ETH transferred, gas used — with 24h/168h MAs, % changes, and momentum - **Cyclical time**: hour and day-of-week encoded as sin/cos - **Lagged features**: return and range lags at 1, 2, 3, 4, 6, 12 bars --- ## Repo Structure ``` ├── ETH-USD_ML.ipynb # Full pipeline: EDA → features → training → backtest ├── feature_engineering.py # Feature engineering utilities ├── fetch_xrp_eth.py # Data fetching from Binance ├── parquet-conversion.py # CSV → Parquet conversion ├── Dune_Query.ipynb # On-chain data pulls from Dune Analytics ├── model_export/ │ ├── lgbm_eth_4h_regressor.joblib # Trained model (sklearn API) │ ├── lgbm_eth_4h_regressor.txt # Trained model (LightGBM native) │ ├── feature_pipeline.py # Feature engineering for inference │ ├── predict.py # Signal generator CLI │ └── config.json # Model metadata & hyperparameters ├── cnn_lstm/ # CNN-LSTM experiment (did not beat LGBM) │ ├── train.py # Model training script │ ├── predict.py # Inference / signal generation │ ├── feature_pipeline.py # Feature engineering for CNN-LSTM │ ├── alert_runner.py # Telegram alert runner │ ├── config.json # Model config │ └── setup_cron.sh # Cron job setup ``` --- ## Quickstart ### 1. Install dependencies ```bash pip install lightgbm polars pandas numpy scikit-learn optuna ta ``` ### 2. Generate signals from new data ```bash cd model_export python predict.py --input latest_hourly.csv --output signals.csv ``` Input CSV must contain hourly OHLCV columns (`open`, `high`, `low`, `close`, `volume`) plus Ethereum on-chain columns (see `config.json` for the full feature list). ### 3. Signal interpretation - `signal = 1` → **Long**: predicted return > entry threshold (`K × cost`) - `signal = -1` → **Short**: predicted return < −threshold - `signal = 0` → **Flat**: no trade The volatility filter (24h rolling std of hourly returns > median) must also be satisfied for a trade to trigger. --- ## Data Sources | Source | Data | Coverage | |---|---|---| | Binance API | ETH/USDT 1-minute OHLCV | ~7 years | | Dune Analytics | Ethereum on-chain metrics | ~7 years | --- ## Model Hyperparameters (Optuna-tuned) | Parameter | Value | |---|---| | Learning rate | 0.00758 | | Max depth | 6 | | Num leaves | 57 | | Min child samples | 96 | | Subsample | 0.708 | | Colsample by tree | 0.549 | | L1 reg (alpha) | 0.203 | | L2 reg (lambda) | 0.196 | --- ## Deep Learning Experiments (CNN-LSTM & Transformer) We tested several deep learning architectures to see whether neural sequence models could improve on the LightGBM baseline. **None outperformed it.** ### Architectures Tested | Model | Input | Window | Params | Target | |---|---|---|---|---| | CNN-LSTM (1-min bars) | `(120, 31)` | 2h lookback | ~200K | 1-min fwd return | | Transformer Encoder (1h bars) | `(168, 42)` | 7d lookback | ~300K+ | 4h fwd return | | CNN-LSTM (4h bars) | `(42, 27)` | 7d lookback | ~10K | z-scored 4h fwd return | | Hybrid: CNN-LSTM embeddings + LGBM | 27 flat + 32 LSTM + 1 pred = 60 | — | — | 4h fwd return | All models used PyTorch on GPU, Huber loss, Adam/AdamW optimizers, and early stopping. ### Results vs. LightGBM | Approach | Sharpe | Return | Win Rate | Max DD | |---|---|---|---|---| | **LGBM 4h Regression** | **2.8** | **+39.7%** | **74.2%** | **-4.3%** | | CNN-LSTM 1-min | — | — | ~49.6% | — | | Transformer 1h | — | — | ~49.7% | — | | Hybrid embeds + LGBM | +0.26 | +1.95% | low | -19.12% | The 1-min CNN-LSTM and 1h Transformer both **collapsed to predicting ≈ 0** for every bar (R² ≈ 0.000, direction accuracy ≈ coin-flip), generating zero actionable trades at any threshold. ### Why Deep Learning Failed Here 1. **Signal-to-noise ratio is too low.** Crypto returns at 1-min and 1-hour frequencies are nearly symmetric around zero. Under Huber/MSE loss the optimal strategy is to predict the mean (≈ 0) — which minimizes loss but is useless for trading. 2. **Neural nets are overparameterized for the data.** The 4h dataset has only ~13K non-overlapping samples; even the deliberately small 10K-parameter CNN-LSTM struggled. Tree-based models handle this low-sample regime far better by finding sharp nonlinear thresholds without gradient-based representation learning. 3. **Proxy features ≠ real order-book data.** Microstructure features (Corwin-Schultz spread, VPIN, Amihud illiquidity) estimated from OHLCV are noisy approximations that lack the granularity of actual Level-2 bid/ask depth. 4. **Huber loss is symmetric.** The model receives no extra penalty for wrong-direction predictions, so it is never incentivized to make bold directional calls — it collapses to the mean. 5. **Embedding aggregation is lossy.** Compressing 240 × 32-dim 1-min LSTM hidden states into a single 4h summary (via mean pooling or last-value) destroys temporal ordering and fine-grained information. ### Conclusion CNN-LSTM embeddings *did* appear in 8 of the top-20 feature importances in the hybrid model, suggesting they capture some temporal structure — but those patterns are not profitable enough to overcome noise and beat LGBM's Sharpe of 2.8. The expected value of further deep learning investment is negative: $$E[\text{value}] \approx P(\Delta\text{Sharpe}>0) \times \Delta\text{Sharpe} - \text{compute cost} - \text{overfitting risk} < 0$$ The LightGBM 4h regression model remains the clear winner. --- ## Dataset The full merged dataset (1-min OHLCV + 7-year on-chain features) is available on Hugging Face: [jonyling/eth-usd-price-prediction](https://huggingface.co/datasets/jonyling/eth-usd-price-prediction) --- ## Disclaimer This project is for **educational and research purposes only**. Past backtest performance does not guarantee future results. Nothing here constitutes financial advice.




