English | δΈζ | ΰ€Ήΰ€Ώΰ€ΰ€¦ΰ₯ | EspaΓ±ol | FranΓ§ais | Ψ§ΩΨΉΨ±Ψ¨ΩΨ© | বাΰ¦ΰ¦²ΰ¦Ύ | Π ΡΡΡΠΊΠΈΠΉ | PortuguΓͺs | Bahasa Indonesia
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.
- π About the Project
- π Project Structure
- π Quick Start
- π οΈ Usage
- π€ Contributing
- π License
- π§ Contact
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.
The system uses an innovative approach to maximize model accuracy:
- High-Fidelity Analysis: AI models analyze global reference indices (
^NDXfor Nasdaq,CL=Ffor 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()insrc/data.py).
The system merges ten distinct signals:
- Classic Quantitative Model: RandomForest/GradientBoosting/LogisticRegression ensemble trained on technical and macroeconomic indicators.
- TimesFM 2.5 (Google Research): State-of-the-art foundation model for time-series forecasting.
- Kronos-base (NeoQuasar): A foundation model trained on 12B+ K-line records for zero-shot financial forecasting (102M parameters).
- TensorTrade / PPO (Reinforcement Learning): RL agent (stable-baselines3) training a PPO policy in a custom Gymnasium trading environment at each run.
- Oil-Bench Model (Gemma 4:e4b): Energy-specialized model merging EIA fundamental data (Stocks, Imports, Refinery utilization) and sentiment for WTI trading.
- 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.
- Visual LLM (Gemma 4:e4b): Direct analysis of technical charts (
enhanced_trading_chart.png). - Sentiment Analysis: Hybrid analysis combining Alpha Vantage and "hot" trends from AlphaEar (Weibo, WallstreetCN).
- Decentralized Data (Hyperliquid): Analysis of speculative sentiment on Oil (WTI) via Funding Rate and Open Interest.
- 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.
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 preferHOLD. - 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_HIGHrisk mode,HOLDserves 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.
- 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.pyfor 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.pyscript 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.
- 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
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).
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
Follow these steps to set up your local development environment.
- Python 3.12+ (via
uv) - Ollama installed and running locally.
- Downloaded LLM model:
ollama pull gemma4:e4b
-
Clone the repository:
git clone https://github.com/laurentvv/Trading-AI.git cd Trading-AI -
Install
uv(if not already done): See astral.sh/uv for installation instructions. -
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
-
Initialize and synchronize the environment:
uv sync
-
Install browsers for Web research (Crawl4AI):
uv run python -m playwright install chromium
-
Configure your API keys: Create a
.envfile in the project root:ALPHA_VANTAGE_API_KEY="YOUR_KEY" EIA_API_KEY="YOUR_KEY"
The system trains its models on the most recent data at each execution before giving a decision.
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 --simulThe 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 --t212The 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.
- 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.
uv run python backtest_prod.pyResults saved to logs_prod/backtest_report.json with equity curves CSV.
Contributions are welcome! Feel free to fork the project and open a Pull Request.
Distributed under the MIT License.
Project Link: https://github.com/laurentvv/Trading-AI
