Skip to content

laurentvv/Trading-AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

188 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

English | δΈ­ζ–‡ | ΰ€Ήΰ€Ώΰ€‚ΰ€¦ΰ₯€ | EspaΓ±ol | FranΓ§ais | Ψ§Ω„ΨΉΨ±Ψ¨ΩŠΨ© | বাংলা | Русский | PortuguΓͺs | Bahasa Indonesia

Hybrid AI Trading Banner


πŸ“ˆ Hybrid AI Trading System πŸ“ˆ

An expert decision-support system for NASDAQ and Oil (WTI) ETF trading, leveraging a tri-modal hybrid artificial intelligence for robust and nuanced trading signals.

Project Status Python Version License


πŸ“š Table of Contents


🌟 About the Project

This project is an expert decision-support system for ETF trading, using a tri-modal hybrid AI approach. It is designed to provide a comprehensive and robust analysis by combining several AI perspectives.

πŸš€ Dual-Ticker Strategy (Analysis vs. Trading)

The system uses an innovative approach to maximize model accuracy:

  • High-Fidelity Analysis: AI models analyze global reference indices (^NDX for Nasdaq, CL=F for WTI Crude Oil). These indices offer longer history and "purer" trends, without the noise related to trading hours or ETF fees.
  • ETF Execution: Real orders are placed on the corresponding tickers on Trading 212 (SXRV.DE, CRUDP.PA), using T212 live prices (via positions API) for position sizing. Portfolio state is synchronized directly from T212 (sync_state_from_t212()), and live prices are injected into the analysis pipeline (_inject_t212_live_price() in src/data.py).

🧠 Hybrid AI Engine

The system merges ten distinct signals:

  1. Classic Quantitative Model: RandomForest/GradientBoosting/LogisticRegression ensemble trained on technical and macroeconomic indicators.
  2. TimesFM 2.5 (Google Research): State-of-the-art foundation model for time-series forecasting.
  3. Kronos-base (NeoQuasar): A foundation model trained on 12B+ K-line records for zero-shot financial forecasting (102M parameters).
  4. TensorTrade / PPO (Reinforcement Learning): RL agent (stable-baselines3) training a PPO policy in a custom Gymnasium trading environment at each run.
  5. Oil-Bench Model (Gemma 4:e4b): Energy-specialized model merging EIA fundamental data (Stocks, Imports, Refinery utilization) and sentiment for WTI trading.
  6. Textual LLM (Gemma 4:e4b): Contextual analysis of raw data, real-time news via the AlphaEar skill, and integration of dynamic macro-economic web research.
  7. Visual LLM (Gemma 4:e4b): Direct analysis of technical charts (enhanced_trading_chart.png).
  8. Sentiment Analysis: Hybrid analysis combining Alpha Vantage and "hot" trends from AlphaEar (Weibo, WallstreetCN).
  9. Decentralized Data (Hyperliquid): Analysis of speculative sentiment on Oil (WTI) via Funding Rate and Open Interest.
  10. Vincent Ganne Model: Geopolitical and cross-asset analysis (WTI, Brent, Gas, DXY, MA200) for detecting macroeconomic bottoms.

The goal is to produce a final decision (BUY, SELL, HOLD) with an absolute priority on Accuracy First.

🧘 Decision Philosophy: "Cognitive Prudence"

Unlike classic trading algorithms that panic as soon as volatility explodes, this system applies an informed investor approach:

  • Strong Consensus Required: A quantitative model (Classic) may cry wolf (SELL), but if cognitive models (Text LLM, Vision, TimesFM) remain neutral, the system will prefer HOLD.
  • Confidence Filter: A movement decision (Buy or Sell) is only validated if the global confidence exceeds a safety threshold (generally 40%). Below this, the system considers the signal as "noise" and remains on standby.
  • Capital Protection: In VERY_HIGH risk mode, HOLD serves as a shield. It prevents entering an unstable market and avoids exiting prematurely on a simple technical correction if fundamentals (News/Vision/Hyperliquid) do not confirm an imminent crash.

✨ Key Features

  • Dual-Ticker Approach: Analyze the index, trade the ETF.
  • T212 Live Prices: Real-time recovery of EUR prices via the Trading 212 API (0.2s), with yfinance fallback and parquet cache.
  • Dated Brent Spread: Monitoring of physical market tension via the spread between Brent Spot (Dated) and Brent Futures.
  • Network Resilience: yfinance circuit breaker with separate trackers (info vs. download), 10s timeout on all network calls.
  • Cache Auto-Invalidation: Parquet cache auto-detects staleness (> 2 days) and forces a refresh. Use refresh_cache.py for manual cache clearing.
  • Advanced Cognition: Use of Gemma 4 for better technical/fundamental synthesis.
  • News & Blockchain Sentiment: Integration of AlphaEar and Hyperliquid to capture social and speculative sentiment.
  • Automated Scheduler: schedule.py script for continuous execution (8:30 AM - 6:00 PM) on a server.
  • Advanced Risk Management: Automatic signal adjustment based on volatility and market regime.
  • Production Backtesting: Standalone backtest engine (backtest_prod.py) replaying real prod signals against real prices with T212 fees β€” no external dependencies.

πŸ’» Tech Stack

  • Language: Python 3.12+
  • Calculations & Data: pandas, numpy, yfinance, pyarrow, pandas_datareader, hyperliquid-python-sdk
  • Machine Learning: scikit-learn, shap
  • AI & LLM: requests, ollama
  • Web Scraping & Search: beautifulsoup4, duckduckgo_search, crawl4ai
  • Visualization: matplotlib, seaborn, mplfinance
  • Utilities: tqdm, rich, python-dotenv, schedule

βš™οΈ Performance & Hardware

The system is designed to be performant on consumer hardware without requiring a dedicated GPU.

  • CPU Only: LLM inference (Gemma 4 via Ollama) and TimesFM are optimized for fast CPU execution if enough RAM is available.
  • Recommended RAM: 16 GB minimum (32 GB suggested to run Gemma 4 comfortably).
  • Execution Time: ~2 to 5 minutes for a full cycle (including web crawling, ML training, TimesFM predictions, and 3 LLM analyses).
  • API Speed: Ultra-fast Trading 212 integration (<1s for live price recovery).

πŸ“‚ Project Structure

The project is organized modularly for better maintainability.

Trading-AI/
β”œβ”€β”€ src/                     # Core modules
β”‚   β”œβ”€β”€ eia_client.py               # Energy fundamental data client
β”‚   β”œβ”€β”€ oil_bench_model.py          # Energy specialized model
β”‚   β”œβ”€β”€ tensortrade_model.py        # Reinforcement Learning signal (PPO/SB3)
β”‚   β”œβ”€β”€ enhanced_decision_engine.py # Fusion engine and Vincent Ganne model
β”‚   β”œβ”€β”€ advanced_risk_manager.py    # Trend-Aware risk management
β”‚   β”œβ”€β”€ adaptive_weight_manager.py  # Dynamic model weighting
β”‚   β”œβ”€β”€ t212_executor.py            # Real execution on Trading 212
β”‚   β”œβ”€β”€ timesfm_model.py            # TimesFM 2.5 integration
β”‚   └── ...                         # Data, Features, LLM Client
β”œβ”€β”€ tests/                   # Test and validation scripts
β”‚   β”œβ”€β”€ check_cache.py               # Inspect Parquet cache files (dates, sizes)
β”‚   β”œβ”€β”€ check_db.py                  # Inspect SQLite databases (tables, rows)
β”‚   β”œβ”€β”€ check_live.py                # Live market prices via yfinance
β”‚   β”œβ”€β”€ test_full_cycle.py           # End-to-end T212 buy/wait/sell test
β”‚   └── ...                          # Unit & integration tests
β”œβ”€β”€ data_cache/              # Market and macro data (Parquet)
β”œβ”€β”€ logs_prod/               # Production logs (trading_journal.csv, T212 state)
β”œβ”€β”€ src/                     # Core modules
β”‚   β”œβ”€β”€ enhanced_decision_engine.py  # Fusion engine and Vincent Ganne model
β”‚   β”œβ”€β”€ t212_executor.py             # Real execution on Trading 212
β”‚   β”œβ”€β”€ tensortrade_model.py         # Reinforcement Learning signal (PPO/SB3)
β”‚   └── ...                          # Data, Features, LLM Client, Risk, etc.
β”œβ”€β”€ main.py                  # Single entry point (Analysis & Trading)
β”œβ”€β”€ backtest_prod.py         # Standalone production backtest (signals vs buy&hold)
β”œβ”€β”€ schedule.py              # Live scheduler (8:30 AM - 6:00 PM)
β”œβ”€β”€ refresh_cache.py         # CLI utility to force-refresh Parquet cache
β”œβ”€β”€ .env                     # API Keys (Alpha Vantage, T212, EIA)
└── README.md                # This documentation

πŸš€ Quick Start

Follow these steps to set up your local development environment.

βœ… Prerequisites

  • Python 3.12+ (via uv)
  • Ollama installed and running locally.
  • Downloaded LLM model: ollama pull gemma4:e4b

βš™οΈ Installation

  1. Clone the repository:

    git clone https://github.com/laurentvv/Trading-AI.git
    cd Trading-AI
  2. Install uv (if not already done): See astral.sh/uv for installation instructions.

  3. Install Foundation Models (CRUCIAL Step): Run the installation scripts to clone the models into vendor/ and apply patches:

    python setup_timesfm.py
    python setup_kronos.py
  4. Initialize and synchronize the environment:

    uv sync
  5. Install browsers for Web research (Crawl4AI):

    uv run python -m playwright install chromium
  6. Configure your API keys: Create a .env file in the project root:

    ALPHA_VANTAGE_API_KEY="YOUR_KEY"
    EIA_API_KEY="YOUR_KEY"
    

πŸ› οΈ Usage

The system trains its models on the most recent data at each execution before giving a decision.

Simulation Mode (Paper Trading)

To test the system without risk with a fictitious capital of €1000, use the --simul flag. The system will manage a strict history of buys and sells.

# Run a simulated analysis (Default: SXRV.DE - Nasdaq 100 EUR)
uv run main.py --simul

# Run on Oil (WTI)
uv run main.py --ticker CRUDP.PA --simul

Real Execution (Trading 212)

The system is now fully integrated with Trading 212:

  • Portfolio Verification: Before any action, the robot consults your real cash and positions.
  • API Management: Includes automatic retry mechanisms against request limits (Rate Limiting).
# Run analysis with real execution (Demo or Real according to .env)
uv run main.py --t212

πŸ§ͺ Production Backtesting

The system includes a standalone production backtest engine (backtest_prod.py) that replays actual prod signals from logs_prod/trading_journal.csv against real prices from data_cache/ Parquet files.

Features

  • Real signals: Replays the exact decisions of the 9-model hybrid engine.
  • Real prices: Uses actual ETF OHLCV data (SXRV.DE, CRUDP.PA) β€” no US proxies.
  • T212 fees: Simulates Trading 212's 0.1% per-trade fee model.
  • Baseline comparison: Automatically computes buy-and-hold performance as benchmark.
  • Metrics: Sharpe Ratio, Maximum Drawdown, Win Rate, Alpha, Total Return per ticker.

Usage

uv run python backtest_prod.py

Results saved to logs_prod/backtest_report.json with equity curves CSV.


🀝 Contributing

Contributions are welcome! Feel free to fork the project and open a Pull Request.


πŸ“œ License

Distributed under the MIT License.


πŸ“§ Contact

Project Link: https://github.com/laurentvv/Trading-AI

About

Advanced Hybrid AI expert system for NASDAQ & Oil (WTI) ETF trading. Merges Quantitative ML, LLMs (Gemma 4), TimesFM 2.5, Visual Chart Analysis, and EIA Fundamentals for high-accuracy signals. Features dual-ticker strategy and Trading 212 execution.

Topics

Resources

Stars

Watchers

Forks

Contributors