Skip to content

Quantitative trading framework implementing Max Dama strategies: mean reversion, momentum, Kelly Criterion risk management, EMA smoothing, online algorithms, and backtesting with performance metrics.

License

Notifications You must be signed in to change notification settings

rigneshroot/maxdama-trading

Repository files navigation

Max Dama Automated Trading System

Ever wondered how quantitative traders actually build their systems? This project brings Max Dama's legendary trading guide to life with real, working Python code.

What's This All About?

Back in 2008-2011, Max Dama wrote one of the best practical guides to automated trading. This repo implements the key ideas from that guide so you can actually use them. No fluff, just the good stuff:

  • Smart Trading Strategies - Mean reversion, momentum, and calendar effects that actually work
  • Signal Processing - The math tricks that separate signal from noise (EMA smoothing, normalization, online algorithms)
  • Risk Management - Kelly Criterion to figure out exactly how much to bet without blowing up
  • Backtesting - Test your ideas on historical data before risking real money
  • Performance Metrics - Know if you're actually making money or just getting lucky

Getting Started (Choose Your Adventure)

The "I Just Want to See It Work" Option

Google Colab - Zero setup, runs in your browser:

  1. Grab the notebook: MaxDama_Trading_System.ipynb
  2. Upload it to Google Colab
  3. Hit Runtime → Run all
  4. Watch your strategy make (or lose) fake money!

You'll get:

  • A complete mean reversion strategy running on sample data
  • Kelly Criterion telling you how much to bet
  • Pretty charts showing your equity curve
  • All the performance stats traders care about

No Python install, no dependencies, no headaches. Just click and go.

The "I Want to Run This Locally" Option

If you prefer running things on your own machine:

Installation

# Clone or navigate to the repository
cd maxdama-automated-trading

# Install dependencies
pip install -r requirements.txt

Run Examples

# Example 1: Mean Reversion Strategy
cd examples
python example_mean_reversion.py

# Example 2: Momentum Strategy
python example_momentum.py

# Example 3: Kelly Criterion
python example_kelly.py

Project Structure

maxdama-automated-trading/
├── src/
│   ├── core/              # Core data types and backtester
│   │   ├── data_types.py  # Bar, Quote, Tick, Position, Order, Trade
│   │   └── backtester.py  # Event-driven backtesting engine
│   ├── strategies/        # Trading strategies
│   │   ├── base_strategy.py
│   │   ├── mean_reversion.py
│   │   ├── momentum.py
│   │   └── first_day_month.py
│   ├── signals/           # Signal processing toolbox
│   │   └── smoothing.py   # EMA, normalization, online algorithms
│   ├── risk/              # Risk management
│   │   └── kelly_criterion.py
│   └── analysis/          # Performance metrics
│       └── performance_metrics.py
├── examples/              # Example scripts
│   ├── simple_kelly_test.py      # No dependencies
│   ├── example_mean_reversion.py
│   ├── example_momentum.py
│   └── example_kelly.py
├── MaxDama_Trading_System.ipynb  # Google Colab notebook
├── README.md              # This file
├── QUICKSTART.md          # Installation guide
├── LICENSE                # MIT License
├── .gitignore             # Git ignore rules
├── requirements.txt       # Python dependencies
├── tests/                 # Unit tests
├── config/                # Configuration files
└── results/               # Backtest results

How to Actually Use This Thing

Example 1: Mean Reversion (Buy Low, Sell High)

The classic strategy - when prices go too far from average, bet they'll come back:

from core.data_types import Bar
from strategies.mean_reversion import MeanReversionStrategy
from core.backtester import Backtester

# Set up the strategy
strategy = MeanReversionStrategy(
    symbol="SPY",
    lookback_period=20,      # Use 20-day average
    entry_threshold=2.0,     # Enter when 2 std devs away
    exit_threshold=0.5,      # Exit when back to normal
    position_size=100        # Trade 100 shares at a time
)

# Run the backtest
backtester = Backtester(strategy, initial_capital=100000.0)
results = backtester.run(bars)  # bars = your historical data

# Check if you made money
print(f"Total Return: {results['total_return_pct']:.2f}%")
print(f"Sharpe Ratio: {results['sharpe_ratio']:.2f}")
print(f"Max Drawdown: {results['max_drawdown_pct']:.2f}%")

Example 2: Momentum (Ride the Trend)

When fast moving average crosses slow moving average, jump on the trend:

from strategies.momentum import MomentumStrategy

strategy = MomentumStrategy(
    symbol="SPY",
    fast_period=10,    # 10-day fast average
    slow_period=30,    # 30-day slow average
    position_size=100
)

backtester = Backtester(strategy, initial_capital=100000.0)
results = backtester.run(bars)

Example 3: Kelly Criterion (How Much Should I Bet?)

Don't guess at position sizing - let math tell you:

from risk.kelly_criterion import kelly_empirical, kelly_continuous
import numpy as np

# Got some backtest returns? Find optimal leverage
returns = np.array([0.01, -0.005, 0.02, -0.01, 0.015])

# Method 1: Works for any return distribution
kelly_f, info = kelly_empirical(returns)
print(f"Optimal leverage: {kelly_f:.2%}")

# Method 2: Assumes normal returns (faster)
mean_ret = np.mean(returns)
var_ret = np.var(returns)
kelly_f = kelly_continuous(mean_ret, var_ret)
print(f"Kelly fraction: {kelly_f:.2%}")

# Pro tip: Most traders use half-Kelly (safer)
print(f"Half-Kelly (recommended): {kelly_f/2:.2%}")

Example 4: Signal Processing (Clean Up Noisy Data)

Smooth out the noise to see the real signal:

from signals.smoothing import EMA, OnlineLinearRegression

# Smooth price data with exponential moving average
ema = EMA(weight=0.1)
smoothed_price = ema.update_periodic(current_price)

# Online regression (updates in real-time)
regression = OnlineLinearRegression(weight=0.05)
predicted_y, std_error = regression.update(x, y)

The Cool Stuff (What Max Dama Actually Taught Us)

Trading Strategies That Work

Mean Reversion - "What goes up must come down"

  • When a stock price gets way too high or low compared to its average, it usually snaps back
  • We use z-scores (standard deviations) to spot these extremes
  • Enter when price is 2+ standard deviations from mean, exit when it normalizes
  • Think of it like a rubber band - stretch it too far and it'll snap back

Momentum - "The trend is your friend"

  • When something's going up, it tends to keep going up (until it doesn't)
  • We use moving average crossovers to catch these trends
  • Golden cross (fast MA crosses above slow MA) = buy signal
  • Death cross (fast MA crosses below slow MA) = sell signal

First Day of Month - "Follow the money"

  • James Altucher found that buying SPY on the last day of the month and selling the next day has a 63% win rate
  • Why? 401(k) contributions, IRAs, mutual fund inflows all hit at month-end
  • It's a calendar effect - not magic, just institutional money flows

Signal Processing (Making Sense of Noisy Data)

EMA Smoothing - "Cut through the noise"

ema += weight * (new_signal - ema)
  • Prices jump around like crazy. EMA smooths them out while keeping recent data more important
  • Helps you see the real trend instead of random noise
  • Bonus: Pushes your signal horizon further out so you have time to actually trade on it

Normalization - "Compare apples to apples"

signal = (bid_size - ask_size) / (bid_size + ask_size)
  • Raw differences are misleading. What matters is proportional differences
  • A 100-share imbalance means different things when total size is 1,000 vs 100,000
  • Normalize everything so signals are comparable across different stocks/times

Online Algorithms - "Update in real-time without recalculating everything"

  • Calculate covariance, variance, and regression on-the-fly
  • No need to store all historical data or recalculate from scratch
  • Perfect for live trading where every millisecond counts

Kelly Criterion (Stop Guessing at Position Sizes)

The Problem: How much should you bet on each trade?

  • Too little = you make no money even when you're right
  • Too much = one bad streak wipes you out

The Solution: Kelly Criterion finds the optimal bet size mathematically

For coin flips:

f = 2p - 1  # where p = win probability

If you have a 60% edge, bet 20% of your bankroll. Simple.

For trading (Gaussian returns):

f = μ / σ²  # mean return / variance

Real talk: Most pros use half-Kelly because:

  • Full Kelly is mathematically optimal but psychologically brutal
  • Half-Kelly gives you 75% of the growth with way less volatility
  • You sleep better at night

Backtesting (Test Before You Wreck)

Michael Dubno's Golden Rules:

  1. No time travel - Process data one point at a time, just like real life
  2. Control everything - Random seeds, timestamps, all of it. Results must be reproducible
  3. Same code everywhere - Backtest, paper trading, live trading should use identical logic

Common Ways People Screw This Up:

  • Survivorship bias - Testing only on stocks that didn't go bankrupt (duh, they look great!)
  • Look-ahead bias - Using tomorrow's data to make today's decision (time travel isn't real)
  • Unrealistic costs - Ignoring commissions, slippage, and market impact
  • Overfitting - Finding patterns in noise that won't repeat

Our backtester handles all this correctly. You're welcome.

Performance Metrics

The system calculates comprehensive performance metrics:

  • Sharpe Ratio: Risk-adjusted returns
  • Max Drawdown: Largest peak-to-trough decline
  • Win Rate: Percentage of profitable trades
  • Sortino Ratio: Downside-only risk adjustment
  • Calmar Ratio: Return / max drawdown
  • Information Coefficient: Signal-return correlation
  • Profit Factor: Gross profit / gross loss

Configuration

Strategy parameters can be configured in config/strategy_config.yaml or passed directly to strategy constructors.

Testing

# Run unit tests
pytest tests/ -v

# Run specific test
pytest tests/test_kelly.py -v

Files Overview

Documentation

  • README.md - This file, complete documentation
  • QUICKSTART.md - Installation and troubleshooting guide
  • LICENSE - MIT License with trading disclaimer

Notebooks

  • MaxDama_Trading_System.ipynb - Google Colab notebook (run in browser!)

Source Code

  • src/core/ - Data types and backtesting engine
  • src/strategies/ - Trading strategies (mean reversion, momentum, etc.)
  • src/signals/ - Signal processing (EMA, normalization, online algorithms)
  • src/risk/ - Kelly Criterion for position sizing
  • src/analysis/ - Performance metrics (Sharpe, drawdown, etc.)

Examples

  • examples/simple_kelly_test.py - Kelly Criterion demo (no dependencies)
  • examples/example_mean_reversion.py - Mean reversion backtest
  • examples/example_momentum.py - Momentum strategy backtest
  • examples/example_kelly.py - Comprehensive Kelly examples

References

Max Dama PDF Source

Original PDF: Max Dama on Automated Trading

This implementation is based on concepts from Max Dama on Automated Trading (2008-2011):

  • Section 2: Industry overview and buy-side strategies
  • Section 4: Alpha (strategies and signal processing)
  • Section 5: Simulation (backtesting and pitfalls)
  • Section 6: Risk (Kelly Criterion, portfolio allocation)
  • Section 7: Execution (transaction costs and liquidity)

Key Sections Implemented

  • Section 2.3: Buy-side strategies (mean reversion, momentum)
  • Section 4.5: First day of month effect (James Altucher)
  • Section 4.7: Weighted midpoint (microprice)
  • Section 4.8: Signal processing toolbox (EMA, normalization, online algorithms)
  • Section 5.2: Backtesting simulators
  • Section 5.5: Michael Dubno's backtesting principles
  • Section 6.1: Single strategy allocation (Kelly Criterion)
  • Section 6.4: Empirical Kelly code

License

MIT License - See LICENSE file for details.

Disclaimer: This software is for educational purposes only. Trading involves substantial risk of loss.

Author

Implemented based on Max Dama's automated trading guide.

About

Quantitative trading framework implementing Max Dama strategies: mean reversion, momentum, Kelly Criterion risk management, EMA smoothing, online algorithms, and backtesting with performance metrics.

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published