Notebooks
89 notebooks across quantitative trading, signals, data, and execution
Featured
Simple Vectorized Backtest
Build a fast vectorized backtesting engine using pandas — ideal for quickly evaluating strategy logic across large price histories.
Streamlit Trading Dashboard
Build an interactive trading dashboard with Streamlit — live P&L charts, position tables, and key metric widgets.
Bybit OHLCV Fetch
Fetch historical and live OHLCV data from the Bybit REST API with pagination, rate limiting, and incremental update support.
Simple Paper Trading Engine
Build a paper trading engine that simulates order execution against live market data without risking real capital.
Drawdown Analysis
Compute max drawdown, drawdown duration, recovery time, and underwater curves to rigorously assess strategy risk.
Regime-Based Signal Classifier
Route signals through regime-specific classifiers — use different models for bull, bear, and range-bound market conditions.
LSTM Price Prediction
Build and train an LSTM neural network on OHLCV sequences for price direction prediction — includes feature scaling and walk-forward validation.
Bollinger Band Reversion
Mean-reversion strategy using Bollinger Band extremes — enter on band touch, exit on mid-band return, with volatility filters.
All 89 notebooks
Simple Vectorized Backtest
Build a fast vectorized backtesting engine using pandas — ideal for quickly evaluating strategy logic across large price histories.
Event-Driven Backtest
Implement an event-driven backtesting loop that processes bar-by-bar signals, supporting realistic order simulation and state tracking.
Include Trading Fees
Model maker/taker fees, funding rates, and cumulative cost drag in your backtests to produce realistic net-return estimates.
Slippage Model
Add market impact and slippage models to your backtest — fixed, percentage-based, and volume-proportional approaches covered.
Position Sizing
Implement fixed fractional, Kelly criterion, and volatility-targeted position sizing methods and compare their equity curve profiles.
Backtesting with vectorbt
Use the vectorbt library for high-performance portfolio backtesting with built-in metrics, portfolio simulation, and visualization.
Backtrader Example
Walk through a complete strategy implementation in Backtrader — broker config, data feeds, indicators, and trade logging.
Streamlit Trading Dashboard
Build an interactive trading dashboard with Streamlit — live P&L charts, position tables, and key metric widgets.
Plotly Dash Dashboard
Create a production-grade analytical dashboard using Plotly Dash with callbacks, multi-page layout, and live data updates.
Plot Trades on Chart
Overlay entry/exit markers and trade annotations on candlestick charts to visually review strategy execution quality.
Live P&L Plot
Build a real-time updating P&L chart that streams trade results and renders running equity with drawdown shading.
Store OHLCV in TimescaleDB
Set up TimescaleDB hypertables and write efficient ingestion pipelines for time-series OHLCV data at scale.
Store OHLCV in PostgreSQL
Design and populate a PostgreSQL schema for market data — table structure, indexing strategy, and bulk insert patterns.
Save to CSV & Parquet
Persist and reload market data efficiently using CSV and Parquet formats — compare file size, read speed, and schema handling.
Correlation Analysis
Compute rolling and static correlation matrices across assets and time periods to identify regime shifts and diversification opportunities.
Volatility Analysis
Analyse realised and implied volatility using EWMA, Parkinson, and Garman-Klass estimators with regime breakdowns.
Price Analysis
Exploratory price analysis: return distributions, autocorrelation, fat tails, and stationarity tests on OHLCV data.
Symbol Format Handling
Normalise trading pair formats across exchanges — handle BTC/USDT, BTCUSDT, BTC-USDT variants in a unified pipeline.
Timezone Standardisation
Convert timestamps across exchange timezones to UTC, handle DST edge cases, and align multi-source data to a common index.
Resample Timeframes
Aggregate tick, 1m, and 5m OHLCV data into higher timeframes with correct open/high/low/close/volume resampling semantics.
Handle Missing Data
Detect, classify, and fill gaps in price data — forward-fill, interpolation, and gap-flagging strategies for OHLCV series.
Clean OHLCV Data
Full OHLCV cleaning pipeline: outlier removal, zero-volume detection, HLOC consistency checks, and duplicate bar elimination.
Bybit OHLCV Fetch
Fetch historical and live OHLCV data from the Bybit REST API with pagination, rate limiting, and incremental update support.
Hyperliquid OHLCV Fetch
Download OHLCV candlestick data from Hyperliquid's API, handling their unique candle format and perpetual contract symbols.
OKX OHLCV Fetch
Retrieve OHLCV data from OKX REST API with support for spot, futures, and options instruments across all timeframes.
Binance OHLCV Fetch
Fetch full market history from Binance using the klines endpoint — handles the 1000-bar limit, pagination, and rate limits.
Blockchain Data Fetcher
Fetch on-chain metrics — hash rate, active addresses, transaction volume — from public blockchain APIs for use as trading signals.
Simple Paper Trading Engine
Build a paper trading engine that simulates order execution against live market data without risking real capital.
Bybit Demo Trading
Connect to Bybit's demo environment and execute automated trades using demo API keys — full order lifecycle covered.
Log Trades
Implement a trade logging system that persists entry/exit details, P&L, and metadata to a database for post-trade analysis.
Limit vs Market Orders
Compare execution quality between limit and market orders — analyse fill rates, slippage, and cost under different market conditions.
Retry Failed Orders
Build a robust order retry system with exponential backoff, partial fill detection, and error classification for production trading.
Binance Order Execution
End-to-end order placement on Binance — authentication, spot vs futures routing, order types, and WebSocket order status updates.
Drawdown Analysis
Compute max drawdown, drawdown duration, recovery time, and underwater curves to rigorously assess strategy risk.
Sharpe & Sortino Ratios
Calculate Sharpe, Sortino, and Calmar ratios from a trade ledger — with annualisation, rolling windows, and regime breakdowns.
Trade Metrics
Compute win rate, profit factor, average trade duration, expectancy, and per-trade P&L statistics from a complete trade ledger.
Equity Curve Visualisation
Plot equity curves, drawdown overlays, rolling Sharpe, and monthly P&L heatmaps for a comprehensive performance tearsheet.
QuantStats Report
Generate professional HTML tearsheets using QuantStats — full metrics, benchmark comparison, and rolling performance analysis.
Meta-Labeling
Apply Marcos Lopez de Prado's meta-labeling framework to add a secondary ML model that filters primary strategy signals.
Triple Barrier Labeling
Implement the triple barrier method for ML label generation — upper/lower barriers and a time-based barrier with dynamic sizing.
Liquidity & Volume Confirmation
Use liquidity and volume metrics to confirm or filter primary signals — reducing false entries in low-volume conditions.
ML Feature Signal Fusion
Combine technical indicator features with ML model outputs into a unified signal score using weighted ensemble methods.
Pattern & Indicator Confluence
Build a confluence engine that fires only when chart patterns and technical indicators agree — reducing noise and improving precision.
Multi-Timeframe Alignment
Align signals across multiple timeframes — only trade when the 1H, 4H, and 1D all agree on direction.
Regime-Based Signal Classifier
Route signals through regime-specific classifiers — use different models for bull, bear, and range-bound market conditions.
Volatility-Adjusted Filter
Scale signal thresholds dynamically with realised volatility to maintain consistent signal frequency across market regimes.
Trend & Momentum Confirmation
Combine trend-following and momentum indicators into a dual-confirmation system that only signals when both agree.
TA Signal Confluence Engine
Score and rank technical indicator signals by confluence — build a composite signal that aggregates agreement across indicators.
LSTM Price Prediction
Build and train an LSTM neural network on OHLCV sequences for price direction prediction — includes feature scaling and walk-forward validation.
Regression Signal Model
Train a regression model to predict next-bar returns from technical features — with walk-forward cross-validation and feature importance.
Classification Signal Model
Predict trade direction (long/short/flat) using a classification model trained on lagged returns, volume, and volatility features.
Prepare ML Dataset
Full ML data prep pipeline — feature engineering from OHLCV, labeling, train/test split with time-series awareness, and scaling.
Triangle Pattern Detection
Algorithmically detect ascending, descending, and symmetrical triangles using pivot-based trendline fitting.
Head & Shoulders Detection
Detect head and shoulders (and inverse) patterns programmatically using peak/trough analysis and neckline confirmation.
Flag & Pennant Detection
Identify bull/bear flags and pennant consolidation patterns by detecting sharp moves followed by tight parallel channels.
Swing High / Low Detector
Detect swing highs and lows with configurable lookback — the building block for pattern recognition, S/R, and structure mapping.
BOS & CHoCH Detection
Detect Break of Structure (BOS) and Change of Character (CHoCH) events for smart money concept (SMC) based trading.
Market Structure (HH/HL/LH/LL)
Map higher highs, higher lows, lower highs, and lower lows to track market structure and identify trend health.
Order Block Detection
Identify institutional order blocks — the last up/down candle before a strong impulse move — for SMC-based entry zones.
Breakout Detection
Detect price breakouts from consolidation ranges, Donchian channels, and volatility compression zones with volume confirmation.
Support & Resistance Zones
Compute dynamic support and resistance zones from historical price clusters, volume nodes, and swing pivot history.
Candlestick Patterns
Detect classic candlestick patterns — doji, engulfing, hammer, shooting star, and morning/evening star — using TA-Lib.
Bollinger Band Reversion
Mean-reversion strategy using Bollinger Band extremes — enter on band touch, exit on mid-band return, with volatility filters.
Multi-Indicator Score Strategy
Build a composite scoring system that ranks and combines signals from multiple indicators into a single entry/exit score.
ML + TA Combined Strategy
Combine a trained ML classifier with traditional TA signals — use ML for direction, TA for timing entry and exit precision.
Regime-Based Strategy Switching
Automatically switch between trend-following and mean-reversion modes based on a real-time market regime classifier.
Dynamic Stop + Volatility Strategy
Set stop-loss distances dynamically based on ATR — wider stops in high-volatility regimes, tighter in compressed markets.
Volatility Squeeze Strategy
Trade Bollinger Band / Keltner Channel squeezes — enter on the first directional expansion after a compression period.
ATR Volatility Breakout
Enter breakout trades when price exceeds a multiple of ATR from the prior day's close — a classic volatility expansion strategy.
Volume Momentum Confirmation
Use OBV, VWAP deviation, and volume spikes to confirm momentum signals — only trade when volume supports the move.
Breakout Momentum Follow-Through
Enter breakouts only when followed by momentum confirmation — filtering false breakouts with ROC and volume threshold checks.
Rate of Change Strategy
Use the Rate of Change (ROC) indicator to build a momentum strategy — with look-back optimisation and regime filtering.
MACD Momentum Strategy
Classic MACD crossover strategy enhanced with histogram divergence signals, zero-line filters, and regime context.
VWAP Reversion Strategy
Intraday mean-reversion strategy trading deviations from VWAP — with standard deviation bands and time-of-day filters.
Keltner Channel Reversion
Mean-reversion strategy based on Keltner Channel extremes — compare performance against Bollinger Band reversion on the same asset.
Z-Score Reversion Strategy
Build a statistical mean-reversion strategy using z-score of price relative to a rolling mean — with entry/exit threshold tuning.
RSI Mean Reversion
RSI overbought/oversold mean-reversion strategy with dynamic threshold adaptation based on rolling percentile of RSI.
Supertrend Strategy
Trend-following strategy using the Supertrend indicator — with ATR multiplier tuning and regime-filtered entry logic.
Donchian Channel Breakout
Classic Donchian Channel breakout strategy — go long on new N-day highs, short on new N-day lows, with trailing stop exits.
ADX Trend Strength Strategy
Use ADX to measure trend strength and gate trades — only enter directional trades when ADX exceeds a configurable threshold.
EMA Ribbon Trend Strategy
Use a multi-EMA ribbon to identify trend direction and strength — enter when the ribbon is aligned and expanding.
MA Crossover Strategy
The classic moving average crossover — SMA, EMA, and WMA variants with parameter sweep analysis and transaction cost sensitivity.
Build a Custom Indicator
Create a fully custom technical indicator from scratch in pandas — vectorised, compatible with TA-Lib and pandas-ta pipelines.
Technical Analysis with TA-Lib
Tour of TA-Lib's most useful indicators — RSI, MACD, Bollinger Bands, ATR, and ADX — with correct parameter usage and pitfalls.
Technical Analysis with pandas-ta
Use the pandas-ta library for fast, vectorised indicator computation — covers setup, strategy objects, and bulk indicator runs.
API Key Management
Securely store, load, and rotate exchange API keys — environment variables, .env files, and encrypted key stores.
Rate Limit Handling
Implement token-bucket and leaky-bucket rate limiters for exchange API calls — with retry logic and request queuing.
Logging Setup
Set up structured logging for trading bots — rotating file handlers, log levels, contextual fields, and integration with monitoring.
Config Management
Manage multi-environment configs for trading systems — pydantic-settings, YAML/TOML files, and environment-based overrides.