Skip to content

anucoder01/Cyber_Oracle

Repository files navigation

🌌 Cyber Oracle: ML-Powered Crypto Price Prediction System

An Academic Research & Engineering Project
An end-to-end Machine Learning Bitcoin (BTC/USD) price prediction system bridging advanced predictive regression modeling with an immersive, futuristic, 3D cyber-themed dashboard.


πŸ—ΊοΈ Table of Contents

  1. Project Overview
  2. System Architecture
  3. Key Features
  4. Engineered Features (42 Inputs)
  5. Model Training & Evaluation
  6. Tech Stack
  7. Directory Structure
  8. Installation & Setup
  9. API Endpoints
  10. License

πŸ‘οΈ Project Overview

Cyber Oracle is a sophisticated crypto forecasting platform. It processes high-frequency (1-minute interval) market data, extracts complex technical indicators, trains a robust Random Forest Regressor, and provides a real-time estimation of the next minute's BTC/USD closing price.

This project was developed with a dual focus:

  1. Machine Learning Rigor: Time-series feature engineering, strict temporal data splitting (no future leakage), and scale-invariant predictions.
  2. Immersive User Experience: A futuristic web UI featuring 3D particle simulations, responsive layout dividers, a neon glow cursor, and interactive charts that visually track the model's pipeline and prediction metrics.

πŸ—οΈ System Architecture

The project consists of two primary services communicating over standard HTTP/REST (and optionally WebSockets for streaming):

graph TD
    A[btcusd_1-min_data.csv] -->|Train Model| B(train_model.py)
    B -->|Saves Bundle| C[trained_model.pkl]
    C -->|Loaded by| D[FastAPI Backend - main.py]
    E[Next.js Frontend UI] -->|1. Request Features list| D
    E -->|2. POST Raw OHLCV + Indicators| D
    D -->|3. Runs Inference & returns Prediction| E
    E -->|Renders 3D UI & Charts| F[Browser User]
Loading
  1. FastAPI Backend (/cyber-oracle/ml_backend):
    • Loads the pre-trained model and scaler bundle at startup.
    • Restores the 42-feature input matrix in the correct column order.
    • Computes standard scaler transforms and serves predictions under ~5ms.
  2. Next.js Frontend (/cyber-oracle):
    • Developed using Next.js (App Router), Tailwind CSS v4, Framer Motion, and Three.js.
    • Connects to the backend APIs to display feature importances, training metrics, pipeline status, and real-time predictions.

⚑ Key Features

  • 3D Cyberpunk Workspace: Immersive UI using @react-three/fiber and @react-three/drei rendering active particle streams in the background.
  • 3D Neural Network Visualization: View real-time data flowing through the network nodes during inference.
  • Paper Trading Dashboard: Simulate trades with a virtual $10,000 portfolio based on the Oracle's predictions, tracking win rate and PNL.
  • Multi-Asset Support: The UI dynamically shifts themes based on the selected asset (BTC, ETH, SOL, ADA).
  • Audio Feedback: Built-in sound synthesis using the native Web Audio API for immersive haptic-like feedback.
  • Feature Pipeline Tracker: Step-by-step pipeline visualization explaining the transition from raw candles to model output.
  • Sentiment Analysis Dashboard: High-fidelity UI detailing NLP sentiment impact, social metrics, and order book dynamics.
  • Interactive Charting: Implements TradingView's lightweight-charts and Chart.js for smooth candle plots and prediction comparison.
  • Model Inference Panel: An interactive prediction calculator allowing users to manually edit features and simulate model responses.

πŸ“Š Engineered Features (42 Inputs)

The model expects exactly 42 features representing the current state of the market candle and its momentum:

Category Feature Name Description
Raw OHLCV Open, High, Low, Close, Volume Core 1-minute candle parameters
Returns Return_1, Return_5, Return_15, Return_60 Percentage price returns over past $N$ minutes
Log Returns LogReturn_1, LogReturn_5 Logarithmic returns for variance stabilization
Rolling Stats (5m) RollingMean_5, RollingStd_5, RollingHigh_5, RollingLow_5 Moving averages, volatilities, and extremes (5-min window)
Rolling Stats (15m) RollingMean_15, RollingStd_15, RollingHigh_15, RollingLow_15 Moving averages, volatilities, and extremes (15-min window)
Rolling Stats (60m) RollingMean_60, RollingStd_60, RollingHigh_60, RollingLow_60 Moving averages, volatilities, and extremes (60-min window)
MA Deviations Close_vs_MA5, Close_vs_MA15, Close_vs_MA60 Ratio of close price compared to moving averages
Candle Structure Body, UpperWick, LowerWick, Spread Absolute candle sizes and trading spreads
Candle Ratios BodyRatio, UpperWickR, LowerWickR, IsBullish Normalized wick-to-body ratios and direction binary
Volume Indicators VolumeMA5, VolumeMA15, VolumeRatio Volume moving averages and current volume spike ratios
Lagged Closes Close_lag1, Close_lag2, Close_lag3, Close_lag5, Close_lag10 Historical closing prices to capture autocorrelation

πŸ“ˆ Model Training & Evaluation

The predictive engine uses a Random Forest Regressor trained on historical Bitcoin 1-minute data:

  • Time-aware split: Strict 80/20 train/test split preserving temporal order (no shuffling, to prevent future-data leakage).
  • Parameters: 300 estimators, max depth of 20, minimum samples leaf of 10, multi-core execution.

Evaluation Metrics (Hold-out Test Set)

  • Mean Absolute Error (MAE): ~ $1.50 - $4.00 (varies based on training sample size)
  • RΒ² Score: > 0.999 (highly predictive of absolute price levels due to tight 1-minute lags)
  • Directional Accuracy: ~ 52.4% (ability to predict whether the next candle is green or red)

πŸ› οΈ Tech Stack

  • Frontend: Next.js 16 (React 19), JavaScript, Tailwind CSS v4, Framer Motion, Three.js, Lightweight Charts.
  • Backend: FastAPI, Python 3, Uvicorn, Pydantic v2.
  • Machine Learning: Scikit-Learn, Pandas, NumPy, Joblib (model serialization).

πŸ“ Directory Structure

Cyber_Oracle/
β”œβ”€β”€ .gitignore                   # Root-level ignore file (excludes datasets, node_modules)
β”œβ”€β”€ README.md                    # Root project documentation
β”œβ”€β”€ package.json                 # Parent workspace package definition
β”œβ”€β”€ cyber-oracle/                # Frontend & Backend Codebase
β”‚   β”œβ”€β”€ app/                     # Next.js Application Router
β”‚   β”‚   β”œβ”€β”€ components/          # React components (3D background, Navbar, prediction panels)
β”‚   β”‚   β”œβ”€β”€ globals.css          # Cyber-grid scanline & theme styling
β”‚   β”‚   └── page.js              # Home layout orchestrating all sub-dashboards
β”‚   β”œβ”€β”€ ml_backend/              # FastAPI Python backend
β”‚   β”‚   β”œβ”€β”€ main.py              # API server (validates inputs, scales, runs inference)
β”‚   β”‚   β”œβ”€β”€ train_model.py       # Model training pipeline (engineers features, trains RF, saves model)
β”‚   β”‚   β”œβ”€β”€ requirements.txt     # Python dependencies
β”‚   β”‚   └── trained_model.pkl    # Serialized Random Forest model & Scaler bundle (ignored in Git)
β”‚   └── package.json             # Next.js npm dependencies

πŸš€ Installation & Setup

Prerequisites

  • Docker & Docker Compose (Recommended for easy setup)
  • Node.js: v18.x or later (for local development)
  • Python: v3.10 or later (for local development)

🐳 Option A: Run with Docker (Recommended)

  1. Ensure Docker Desktop is running.
  2. In the root directory (Cyber_Oracle), run:
docker-compose up --build
  1. The platform will automatically orchestrate the FastAPI backend (port 8000) and Next.js frontend (port 3000).
  2. Open http://localhost:3000 in your browser.

πŸ’» Option B: Local Manual Setup

1. Backend Setup & Training

First, navigate to the ml_backend folder:

cd cyber-oracle/ml_backend

Create a Python virtual environment and activate it:

# Windows
python -m venv venv
venv\Scripts\activate

# macOS/Linux
python3 -m venv venv
source venv/bin/activate

Install the required packages:

pip install -r requirements.txt

Training the Model:

Ensure the historical 1-minute CSV data (btcusd_1-min_data.csv) is present in the ml_backend folder, then run:

python train_model.py

This will generate the scaled feature matrix, train the Random Forest model, output regression metrics, and save trained_model.pkl.

Running the FastAPI Server:

Start the server using Uvicorn:

uvicorn main:app --reload --port 8000

The backend API documentation will be available at http://127.0.0.1:8000/docs.


2. Frontend Setup

Open a new terminal window, navigate to the cyber-oracle directory:

cd cyber-oracle

Install npm dependencies:

npm install

Run the development server:

npm run dev

Open http://localhost:3000 in your browser to interact with the platform.


πŸ”Œ API Endpoints

The backend exposes the following endpoints (default base URL: http://localhost:8000):

GET /

Health check endpoint. Verifies if the serialized model is successfully loaded.

  • Response:
    {
      "status": "ok",
      "model_loaded": true,
      "feature_count": 42,
      "target_col": "Target_NextClose"
    }

GET /features

Returns the list of 42 feature names expected by the model in the correct sequence.

POST /predict

Performs next-minute price prediction. Accepts raw values and indicators.

  • Request Body (JSON):
    {
      "Open": 104500.0,
      "High": 104800.0,
      "Low": 104300.0,
      "Close": 104650.0,
      "Volume": 1.23,
      "Return_1": 0.0015,
      "Return_5": 0.003,
      ...
    }
  • Response:
    {
      "predicted_next_close": 104682.1523,
      "currency": "USD",
      "model_version": "1.0.0",
      "inference_time_ms": 2.14
    }

πŸ“„ License

This project is licensed under the MIT License. It is intended for academic research and educational purposes. Do not use for live financial trading.

About

An advanced ML-powered cryptocurrency price prediction system featuring real-time sentiment analysis, WebSocket data pipelines, and an immersive 3D Web3 interface.

Topics

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

No releases published

Packages

 
 
 

Contributors