Skip to content

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

16 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

AlgoTrade AI πŸ“ˆ

Python Streamlit XGBoost Plotly Yahoo Finance

A full-stack AI-powered algorithmic trading simulator combining supervised ML, reinforcement learning, portfolio optimisation, and advanced risk modelling β€” with live daily trading signals and explainable AI.

πŸš€ Live App Β· πŸ“Š Features Β· πŸ› οΈ Tech Stack Β· ⚑ Quick Start


Overview

AlgoTrade AI is a quantitative finance research platform built end-to-end in Python. It fetches live market data from Yahoo Finance, runs trained ML and RL models to generate trading signals, and presents everything through an interactive Streamlit dashboard with eight analytical pages.

The platform is designed to demonstrate skills relevant to quant research, algorithmic trading, and ML engineering roles β€” covering the full pipeline from raw data ingestion to deployed web application.


Features

πŸ“‘ Daily Signal (flagship feature)

  • Fetches live OHLCV data from Yahoo Finance up to yesterday's close β€” automatically every day
  • Runs all three trained models (XGBoost, Random Forest, Logistic Regression) and displays BUY / HOLD / SELL
  • SHAP explainability β€” bar chart showing exactly which feature influenced the prediction and by how much
  • AI reasoning cards β€” plain English explanation of RSI, MACD, Bollinger Bands, MA crossovers, and model confidence
  • 90-day candlestick chart with signal marked, MACD subplot, RSI subplot

πŸ€– ML Prediction Engine

  • Three trained classifiers: XGBoost, Random Forest, Logistic Regression
  • Price chart with BUY/SELL signal markers and probability band
  • Real model evaluation metrics: Accuracy, Precision, Recall, ROC-AUC, F1
  • Feature importance bar chart from trained model
  • Confusion matrix
  • Equity curve vs Buy & Hold

🧠 RL Agent

  • Reinforcement learning trading agent (PPO-based momentum strategy)
  • Portfolio vs Buy & Hold chart with trade markers
  • Training reward curve
  • Rolling 20-day portfolio returns
  • Trade distribution and recent trades table

πŸ“Š Portfolio Overview

  • Unified equity curve comparison: ML vs RL vs Buy & Hold
  • Drawdown chart for both strategies
  • Live quote panel (price, open, high, low, volume)
  • Strategy metrics comparison table
  • Signal indicators (RSI, MACD, BB Width, MA Cross)

πŸ’Ό Portfolio Optimiser

  • Modern Portfolio Theory with 1,000 random portfolio simulations
  • Efficient frontier scatter plot coloured by Sharpe ratio
  • Max Sharpe and Min Volatility portfolios highlighted
  • Optimal weight allocation donut chart
  • Correlation matrix heatmap
  • Individual stock return and volatility cards

⚠️ Risk VaR

  • Historical VaR, Parametric VaR, Monte Carlo VaR β€” all three methods
  • Confidence level slider updates all three simultaneously
  • Rolling 60-day VaR chart
  • Daily return distribution histogram
  • Realised vs EWMA predicted volatility

🎲 Monte Carlo Simulation

  • Up to 5,000 Geometric Brownian Motion price paths
  • Fan chart with 5th / 25th / 50th / 75th / 95th percentile bands
  • Final value distribution histogram
  • Scenario summary (Bear / Low / Base / High / Bull)
  • Distribution stats: mean, std dev, skewness, kurtosis, tail probabilities

πŸ“‹ Trade Log

  • Full execution history for ML and RL strategies
  • Real P&L calculated from actual BUY β†’ SELL round trips (not simulated)
  • Cumulative P&L chart with individual trade bars
  • P&L distribution histogram
  • Monthly breakdown bar chart
  • Trade stats: win rate, avg win/loss, profit factor, best/worst trade

Tech Stack

Layer Technology
Language Python 3.10+
Dashboard Streamlit
ML Models scikit-learn, XGBoost
RL Agent Momentum-based strategy (PPO architecture)
Data Yahoo Finance via yfinance
Visualisation Plotly
Explainability SHAP
Numerical NumPy, pandas
Deployment Streamlit Community Cloud

Project Structure

StockProject/
β”‚
β”œβ”€β”€ data/
β”‚   β”œβ”€β”€ raw/                    # OHLCV CSVs downloaded from Yahoo Finance
β”‚   β”‚   β”œβ”€β”€ AAPL.csv
β”‚   β”‚   β”œβ”€β”€ TSLA.csv
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ processed/              # Feature-engineered CSVs for model training
β”‚   β”‚   β”œβ”€β”€ AAPL_features.csv
β”‚   β”‚   └── ...
β”‚   β”œβ”€β”€ data_loader.py          # Downloads raw data from Yahoo Finance
β”‚   └── live_feed.py            # Fetches live data + computes features daily
β”‚
β”œβ”€β”€ ml_price_prediction/
β”‚   β”œβ”€β”€ train_model.py          # Trains XGBoost, RF, Logistic Regression
β”‚   β”œβ”€β”€ predict.py              # Generates signals from trained models
β”‚   └── evaluation.py          # Model evaluation metrics
β”‚
β”œβ”€β”€ ml_strategy_rl/
β”‚   β”œβ”€β”€ rl_agent.py             # DQN-based RL agent
β”‚   β”œβ”€β”€ trading_environment.py  # Custom Gym-style trading environment
β”‚   β”œβ”€β”€ q_learning_agent.py     # Q-learning baseline
β”‚   β”œβ”€β”€ reward_functions.py     # Reward shaping
β”‚   └── train_rl_agent.py       # RL training loop
β”‚
β”œβ”€β”€ backtesting/
β”‚   β”œβ”€β”€ backtester.py           # Core backtesting engine
β”‚   └── performance_metrics.py  # Sharpe, VaR, drawdown, win rate etc.
β”‚
β”œβ”€β”€ risk_management/
β”‚   β”œβ”€β”€ var_model.py            # VaR calculations
β”‚   β”œβ”€β”€ monte_carlo.py          # Monte Carlo simulation
β”‚   β”œβ”€β”€ volatility_prediction.py
β”‚   └── risk_controls.py
β”‚
β”œβ”€β”€ portfolio/
β”‚   β”œβ”€β”€ allocation.py
β”‚   └── portfolio_manager.py
β”‚
β”œβ”€β”€ models/                     # Trained .pkl model files
β”‚   β”œβ”€β”€ xgb_model.pkl
β”‚   β”œβ”€β”€ random_forest_model.pkl
β”‚   └── logistic_model.pkl
β”‚
β”œβ”€β”€ signals/
β”‚   └── trading_signals.csv
β”‚
β”œβ”€β”€ dashboard/
β”‚   └── AlgoTradeAI/
β”‚       └── trading_app/
β”‚           β”œβ”€β”€ app.py                      # Home page
β”‚           β”œβ”€β”€ utils.py                    # Shared theme, data loaders, sidebar
β”‚           └── pages/
β”‚               β”œβ”€β”€ Daily_Signal.py         # πŸ“‘ Live daily prediction
β”‚               β”œβ”€β”€ ML_Prediction.py        # πŸ€– ML model signals
β”‚               β”œβ”€β”€ RL_Agent.py             # 🧠 RL trading agent
β”‚               β”œβ”€β”€ Overview.py             # πŸ“Š Portfolio overview
β”‚               β”œβ”€β”€ Portfolio_Optimizer.py  # πŸ’Ό Efficient frontier
β”‚               β”œβ”€β”€ Price_Indicators.py     # πŸ“ˆ Technical analysis
β”‚               β”œβ”€β”€ Risk_VaR.py             # ⚠️  Value at Risk
β”‚               β”œβ”€β”€ Monte_Carlo.py          # 🎲 Price path simulation
β”‚               └── Trade_Log.py            # πŸ“‹ Execution history
β”‚
β”œβ”€β”€ requirements.txt
└── README.md

Quick Start

1. Clone the repository

git clone https://github.com/Varsh24-hash/AI-trading.git
cd StockProject

2. Install dependencies

pip install -r requirements.txt

3. Download raw data

python data/data_loader.py

4. Train the models

python ml_price_prediction/train_model.py

5. Run the dashboard

streamlit run dashboard/AlgoTradeAI/trading_app/app.py

Machine Learning Pipeline

Feature Engineering

Six features are computed from raw OHLCV data β€” these match exactly between training and live inference:

Feature Description
return_1d Previous day's percentage return
MA_10 10-day simple moving average
MA_50 50-day simple moving average
volatility 10-day rolling annualised volatility
volume_change Day-over-day volume percentage change
RSI 14-period Relative Strength Index

Models

Model Use case
XGBoost Primary signal β€” gradient boosted trees, handles non-linearity
Random Forest Ensemble baseline β€” robust to overfitting
Logistic Regression Linear baseline β€” interpretable coefficients

All models are trained on an 80/20 time-series split (no data leakage).

Signal Logic

Probability > 0.60  β†’  BUY
Probability < 0.40  β†’  SELL
Otherwise           β†’  HOLD

Live Daily Signal

The daily signal feature is the key differentiator of this project. Unlike models trained on a fixed historical window, it:

  1. Fetches 2 years of data from Yahoo Finance up to yesterday's close
  2. Computes all 6 features on the fresh data
  3. Runs the saved .pkl model β€” no retraining required
  4. Generates a BUY / HOLD / SELL signal for tomorrow
  5. Explains the decision using SHAP values and indicator analysis

This means the signal is always based on the most recent market data available, without any manual intervention.


Supported Tickers

Ticker Company
AAPL Apple Inc.
TSLA Tesla Inc.
MSFT Microsoft Corp.
GOOGL Alphabet Inc.
AMZN Amazon.com
NVDA NVIDIA Corp.
META Meta Platforms
JPM JPMorgan Chase
V Visa Inc.
WMT Walmart Inc.

Performance Metrics

All strategy backtests report the following metrics:

  • Total Return β€” cumulative portfolio growth
  • Annualised Return β€” CAGR assuming 252 trading days
  • Volatility β€” annualised standard deviation of daily returns
  • Sharpe Ratio β€” excess return per unit of risk
  • Max Drawdown β€” largest peak-to-trough decline
  • Win Rate β€” percentage of profitable trading days
  • Calmar Ratio β€” annualised return / max drawdown
  • Sortino Ratio β€” downside-only risk-adjusted return
  • VaR (Historical / Parametric / Monte Carlo) β€” daily loss limit at confidence level
  • CVaR / Expected Shortfall β€” average loss beyond VaR threshold

Deployment

The app is deployed on Streamlit Community Cloud and rebuilds automatically on every push to main.

Live URL: https://ai-trading-8yddslultqfz2hfv9yt32z.streamlit.app


Author

Built by Varshini and Chandrakala as a quantitative finance and ML engineering portfolio project.

LinkedIn GitHub

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

Packages

Contributors

Languages