Skip to content

Repository files navigation

πŸ₯‡ Gold Price Predictor

Gold Price Predictor

πŸ”΄ Live Demo

A machine learning web app that predicts gold prices using Random Forest and XGBoost, enriched with macroeconomic features, multi-step forecasting, SHAP explainability, Optuna hyperparameter tuning, PSI drift monitoring, and MLflow experiment tracking via DagsHub.


What It Does

I built this to cover the full ML lifecycle β€” not just training a model, but monitoring it, tracking experiments over time, and explaining individual predictions. Gold price prediction made sense as a use case because it's driven by measurable macroeconomic factors I could pull for free.

The app has 5 tabs:

πŸ“Š Market Dashboard

Live gold price chart (line or candlestick) with selectable moving averages (20, 50, 200-day) and lookback periods up to 5 years. Five real-time macro indicator cards β€” USD Index (DXY), 10-Year Treasury Yield, Oil (WTI), S&P 500, and VIX β€” each showing the latest value and daily change. A news sentiment panel powered by VADER scores recent gold-related headlines from Yahoo Finance as supplementary context. Sentiment is not a model input β€” it gives background colour around the current prediction.

πŸ€– Price Prediction

Predicts tomorrow's gold closing price with a 95% confidence interval and a gauge chart. Below that, a multi-step recursive forecast (3, 5, or 7 trading days ahead) with a widening confidence band chart and a full forecast table showing predicted price, confidence range, and percentage change per day. Two SHAP charts explain exactly why the model made each prediction in dollar terms.

πŸ“ˆ Model Performance

Four metric cards β€” RMSE, MAE, RΒ², and MAPE. An actual vs predicted price chart with an error panel below. An error distribution histogram and a scatter plot with a perfect-fit reference line.

πŸ” Monitoring

PSI (Population Stability Index) and KS test drift detection across all features with a colour-coded bar chart. Prediction distribution and residual PSI checks. MLflow run history table with an RMSE trend chart across all past runs.

🎯 Optuna Trial History

Appears after training with Optuna enabled. Shows a podium with the top 3 trials (πŸ₯‡πŸ₯ˆπŸ₯‰) by RMSE, a convergence chart with the running best line, the best hyperparameters as metric cards, a full trial history table with medal rankings, and an RMSE distribution histogram.


Tech Stack

Layer Tool
Gold price data yfinance β€” GC=F (gold futures)
Macro indicators yfinance β€” DXY, TNX, CL=F, GSPC, VIX
ML models scikit-learn (Random Forest) + XGBoost
Hyperparameter tuning optuna β€” TPE sampler, 10–50 trials
Explainability shap β€” waterfall + summary charts
Drift monitoring scipy.stats β€” custom PSI + KS implementation
Experiment tracking MLflow β€” local or DagsHub remote
News sentiment vaderSentiment + yfinance headlines
Visualisation Plotly
Frontend Streamlit
Hosting Streamlit Community Cloud (free)

I replaced Evidently AI with a custom PSI + KS implementation using scipy. PSI was originally developed for financial model monitoring in banking and credit risk β€” a much better fit for this use case than a generic observability tool.


How the ML Model Works

Raw OHLCV data (GC=F gold futures β€” 1 to 5 years)
    + Macro data (DXY, TNX, CL=F, GSPC, VIX)
            β”‚
            β–Ό
    Feature Engineering (19 base + 7 macro = 26 features)
    β”œβ”€β”€ Lag prices:      lag_1, lag_2, lag_3, lag_5, lag_10
    β”œβ”€β”€ Rolling stats:   7/20/50-day moving average + std dev
    β”œβ”€β”€ Momentum:        5-day change, 1-day and 5-day % returns
    β”œβ”€β”€ Intraday:        High-Low range, Open-Close gap
    β”œβ”€β”€ Calendar:        Day of week, month, year
    └── Macro:           DXY, 10Y yield, oil, S&P 500 return, VIX
            β”‚
            β–Ό
    Chronological Train/Test Split (never random for time series)
            β”‚
            β–Ό
    Optional: Optuna Tuning (10–50 trials, TPE sampler)
    Searches: n_estimators, max_depth, learning_rate,
              subsample, colsample_bytree, regularisation params
            β”‚
            β–Ό
    Model Training β€” Random Forest or XGBoost
            β”‚
            β–Ό
    Evaluation β†’ RMSE, MAE, RΒ², MAPE on test set
            β”‚
            β”œβ”€β”€ MLflow logs params, metrics, run name, model artifact
            β”œβ”€β”€ SHAP explains each prediction in dollar terms
            └── PSI + KS monitors for data drift (train vs test)

Understanding the Metrics

Metric What it means Good value for gold
RMSE Average prediction error in USD per oz Lower is better
MAE Similar to RMSE, less skewed by large errors Lower is better
RΒ² How much price variance the model explains (0–1) Close to 1.0
MAPE Error as a percentage of the actual price Below 1% is excellent

Understanding SHAP

Feature importance shows which inputs matter globally. SHAP goes further β€” for each specific prediction it shows how much every feature pushed the price up or down in dollar terms:

Today's prediction: $2,847
  Yesterday's price   β†’ +$38  (pushed UP)
  VIX fear index      β†’ +$22  (pushed UP)
  USD index           β†’ -$15  (pushed DOWN)
  10Y Treasury yield  β†’ -$9   (pushed DOWN)
  Baseline (avg pred) β†’  $2,811
                      ─────────
  Total predicted     β†’  $2,847

Understanding the Monitoring

PSI β€” Population Stability Index

Compares the feature distributions the model was trained on against what it sees in the test period. Originally developed for financial model monitoring in banking.

PSI Status Action
< 0.10 🟒 Stable No action needed
0.10 – 0.25 🟑 Monitor Keep watching
β‰₯ 0.25 πŸ”΄ Retrain Retrain recommended

KS Test β€” Kolmogorov-Smirnov

A statistical test checking whether two distributions are significantly different. A p-value below 0.05 means the difference is unlikely to be random noise.


Understanding Multi-Step Forecasting

The app uses recursive forecasting β€” the model predicts Day 1, feeds that prediction back as input for Day 2, and so on up to 7 trading days. The confidence band widens each day using a √step multiplier. By Day 7 the band is intentionally wider than Day 1 β€” that is correct behaviour, not a bug.


Understanding Optuna

Optuna searches for the best hyperparameters using a TPE sampler. Unlike grid search, it learns from each trial and focuses on the most promising parameter regions. A chronological validation split within the training data scores each trial β€” the test set is never touched during tuning.


A Note on News Sentiment

The sentiment panel is display-only β€” it does not feed into the model. Yahoo Finance only provides the last few days of headlines, which isn't enough historical data to train on. It gives useful background context when interpreting a prediction but does not affect what the model outputs.


MLflow Run Identification

The sidebar has a mandatory MLflow Run Label field that must be filled before training. Whatever you type becomes part of the run name:

TestRun-1__XGBoost__20260523_143022

This exact name appears in DagsHub / the local MLflow UI so you can find your specific run instantly β€” even when multiple people are using the app at the same time.


Project Structure

gold-price-predictor/
β”‚
β”œβ”€β”€ app.py              ← Main Streamlit app β€” all 5 tabs and UI logic
β”œβ”€β”€ data.py             ← Gold + macro data fetching and feature engineering
β”œβ”€β”€ model.py            ← Model training, evaluation, multi-step forecast, prediction
β”œβ”€β”€ monitoring.py       ← Custom PSI + KS drift monitoring
β”œβ”€β”€ sentiment.py        ← VADER news sentiment via yfinance headlines
β”œβ”€β”€ shap_utils.py       ← SHAP waterfall and summary chart data
β”œβ”€β”€ mlflow_utils.py     ← MLflow experiment logging (local or DagsHub)
β”œβ”€β”€ tuning.py           ← Optuna hyperparameter search for RF and XGBoost
β”œβ”€β”€ train.py            ← Standalone training script (optional CLI use)
β”‚
β”œβ”€β”€ .github/
β”‚   └── workflows/
β”‚       └── retrain.yml ← GitHub Actions workflow (manual trigger only)
β”‚
β”œβ”€β”€ .streamlit/
β”‚   └── secrets.toml    ← Credentials template (NOT committed to GitHub)
β”‚
β”œβ”€β”€ runtime.txt         ← Pins Python 3.11 for Streamlit Cloud
β”œβ”€β”€ requirements.txt    ← All Python dependencies
β”œβ”€β”€ .gitignore          ← Excludes mlruns/, secrets.toml, __pycache__, etc.
└── README.md           ← This file

Running Locally

1. Clone the repo

git clone https://github.com/<your-username>/gold-price-predictor.git
cd gold-price-predictor

2. Create a virtual environment

python -m venv .venv

# macOS / Linux:
source .venv/bin/activate

# Windows:
.venv\Scripts\activate

3. Install dependencies

pip install -r requirements.txt

4. Run the app

streamlit run app.py

Opens at http://localhost:8501.

5. Browse MLflow runs locally

In a second terminal with the venv active:

mlflow ui

Open http://localhost:5000 to see all training runs, compare metrics, and inspect artifacts.


Deploying to Streamlit Community Cloud

  1. Push your code to a public GitHub repo
  2. Go to share.streamlit.io and sign in with GitHub
  3. Click "Create app" and fill in:
    • Repository: your-username/gold-price-predictor
    • Branch: main
    • Main file path: app.py
  4. Click "Deploy" β€” Streamlit Cloud reads requirements.txt and installs everything automatically

Optional: DagsHub Remote MLflow

By default MLflow logs to a local mlruns/ folder which resets when Streamlit Cloud restarts. DagsHub gives you persistent tracking at no cost.

  1. Create a free account at dagshub.com
  2. Connect your GitHub repo
  3. Inside your DagsHub repo go to Remote β†’ Experiments and copy the MLflow tracking URI
  4. Get an access token from dagshub.com/user/settings/tokens
  5. Go to Streamlit Cloud β†’ App Settings β†’ Secrets and add:
[mlflow]
dagshub_username = "your-dagshub-username"
dagshub_repo     = "gold-price-predictor"
dagshub_token    = "your-token-here"

Ideas for Future Versions

  • Multi-output forecasting β€” train a separate model per horizon instead of recursive chaining
  • Hyperparameter comparison across runs β€” visualise how params changed between sessions
  • Additional macro features β€” CPI release dates, Fed meeting dates as binary flags
  • Scheduled auto-retraining β€” re-enable the GitHub Actions cron trigger when needed

About

Gold price prediction web app using Random Forest and XGBoost, with macroeconomic features, PSI drift monitoring, and MLflow experiment tracking via DagsHub.

Topics

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages