Notebooks

89 notebooks across quantitative trading, signals, data, and execution

Featured

FeaturedBacktestingBeginner

Simple Vectorized Backtest

Build a fast vectorized backtesting engine using pandas — ideal for quickly evaluating strategy logic across large price histories.

vectorizedpandasbacktest
FeaturedDashboardBeginner

Streamlit Trading Dashboard

Build an interactive trading dashboard with Streamlit — live P&L charts, position tables, and key metric widgets.

streamlitdashboardvisualization
FeaturedDataBeginner

Bybit OHLCV Fetch

Fetch historical and live OHLCV data from the Bybit REST API with pagination, rate limiting, and incremental update support.

bybitOHLCVREST API
FeaturedDemoIntermediate

Simple Paper Trading Engine

Build a paper trading engine that simulates order execution against live market data without risking real capital.

paper tradingsimulationorders
FeaturedPerformanceBeginner

Drawdown Analysis

Compute max drawdown, drawdown duration, recovery time, and underwater curves to rigorously assess strategy risk.

drawdownriskunderwater
FeaturedSignalsAdvanced

Regime-Based Signal Classifier

Route signals through regime-specific classifiers — use different models for bull, bear, and range-bound market conditions.

regimesclassifieradaptive
FeaturedSignalsAdvanced

LSTM Price Prediction

Build and train an LSTM neural network on OHLCV sequences for price direction prediction — includes feature scaling and walk-forward validation.

LSTMdeep learningprediction
FeaturedSignalsBeginner

Bollinger Band Reversion

Mean-reversion strategy using Bollinger Band extremes — enter on band touch, exit on mid-band return, with volatility filters.

bollinger bandsmean reversionvolatility

All 89 notebooks

BacktestingBeginner

Simple Vectorized Backtest

Build a fast vectorized backtesting engine using pandas — ideal for quickly evaluating strategy logic across large price histories.

vectorizedpandasbacktest
BacktestingIntermediate

Event-Driven Backtest

Implement an event-driven backtesting loop that processes bar-by-bar signals, supporting realistic order simulation and state tracking.

event-drivenorder simulationbacktest
BacktestingBeginner

Include Trading Fees

Model maker/taker fees, funding rates, and cumulative cost drag in your backtests to produce realistic net-return estimates.

feescommissionsfunding rates
BacktestingIntermediate

Slippage Model

Add market impact and slippage models to your backtest — fixed, percentage-based, and volume-proportional approaches covered.

slippagemarket impactexecution
BacktestingIntermediate

Position Sizing

Implement fixed fractional, Kelly criterion, and volatility-targeted position sizing methods and compare their equity curve profiles.

position sizingkellyrisk management
BacktestingIntermediate

Backtesting with vectorbt

Use the vectorbt library for high-performance portfolio backtesting with built-in metrics, portfolio simulation, and visualization.

vectorbtportfolioperformance
BacktestingIntermediate

Backtrader Example

Walk through a complete strategy implementation in Backtrader — broker config, data feeds, indicators, and trade logging.

backtraderframeworkstrategy
DashboardBeginner

Streamlit Trading Dashboard

Build an interactive trading dashboard with Streamlit — live P&L charts, position tables, and key metric widgets.

streamlitdashboardvisualization
DashboardIntermediate

Plotly Dash Dashboard

Create a production-grade analytical dashboard using Plotly Dash with callbacks, multi-page layout, and live data updates.

dashplotlyinteractive
DashboardBeginner

Plot Trades on Chart

Overlay entry/exit markers and trade annotations on candlestick charts to visually review strategy execution quality.

chartstradesmatplotlib
DashboardIntermediate

Live P&L Plot

Build a real-time updating P&L chart that streams trade results and renders running equity with drawdown shading.

livepnlreal-time
DataIntermediate

Store OHLCV in TimescaleDB

Set up TimescaleDB hypertables and write efficient ingestion pipelines for time-series OHLCV data at scale.

timescaledbpostgresqltime-series
DataBeginner

Store OHLCV in PostgreSQL

Design and populate a PostgreSQL schema for market data — table structure, indexing strategy, and bulk insert patterns.

postgresqlsqlstorage
DataBeginner

Save to CSV & Parquet

Persist and reload market data efficiently using CSV and Parquet formats — compare file size, read speed, and schema handling.

parquetcsvpandas
DataIntermediate

Correlation Analysis

Compute rolling and static correlation matrices across assets and time periods to identify regime shifts and diversification opportunities.

correlationportfoliostatistics
DataIntermediate

Volatility Analysis

Analyse realised and implied volatility using EWMA, Parkinson, and Garman-Klass estimators with regime breakdowns.

volatilityEWMAregimes
DataBeginner

Price Analysis

Exploratory price analysis: return distributions, autocorrelation, fat tails, and stationarity tests on OHLCV data.

returnsstatisticsEDA
DataBeginner

Symbol Format Handling

Normalise trading pair formats across exchanges — handle BTC/USDT, BTCUSDT, BTC-USDT variants in a unified pipeline.

symbolsnormalisationexchange
DataBeginner

Timezone Standardisation

Convert timestamps across exchange timezones to UTC, handle DST edge cases, and align multi-source data to a common index.

timezonesUTCdatetime
DataBeginner

Resample Timeframes

Aggregate tick, 1m, and 5m OHLCV data into higher timeframes with correct open/high/low/close/volume resampling semantics.

resamplingtimeframesaggregation
DataBeginner

Handle Missing Data

Detect, classify, and fill gaps in price data — forward-fill, interpolation, and gap-flagging strategies for OHLCV series.

missing datagapsimputation
DataBeginner

Clean OHLCV Data

Full OHLCV cleaning pipeline: outlier removal, zero-volume detection, HLOC consistency checks, and duplicate bar elimination.

cleaningoutliersvalidation
DataBeginner

Bybit OHLCV Fetch

Fetch historical and live OHLCV data from the Bybit REST API with pagination, rate limiting, and incremental update support.

bybitOHLCVREST API
DataBeginner

Hyperliquid OHLCV Fetch

Download OHLCV candlestick data from Hyperliquid's API, handling their unique candle format and perpetual contract symbols.

hyperliquidOHLCVperpetuals
DataBeginner

OKX OHLCV Fetch

Retrieve OHLCV data from OKX REST API with support for spot, futures, and options instruments across all timeframes.

okxOHLCVfutures
DataBeginner

Binance OHLCV Fetch

Fetch full market history from Binance using the klines endpoint — handles the 1000-bar limit, pagination, and rate limits.

binanceOHLCVklines
DataIntermediate

Blockchain Data Fetcher

Fetch on-chain metrics — hash rate, active addresses, transaction volume — from public blockchain APIs for use as trading signals.

on-chainblockchainbitcoin
DemoIntermediate

Simple Paper Trading Engine

Build a paper trading engine that simulates order execution against live market data without risking real capital.

paper tradingsimulationorders
DemoIntermediate

Bybit Demo Trading

Connect to Bybit's demo environment and execute automated trades using demo API keys — full order lifecycle covered.

bybitdemolive execution
DemoBeginner

Log Trades

Implement a trade logging system that persists entry/exit details, P&L, and metadata to a database for post-trade analysis.

loggingtrade historydatabase
ExecutionIntermediate

Limit vs Market Orders

Compare execution quality between limit and market orders — analyse fill rates, slippage, and cost under different market conditions.

orderslimitmarket
ExecutionAdvanced

Retry Failed Orders

Build a robust order retry system with exponential backoff, partial fill detection, and error classification for production trading.

retryerror handlingrobustness
ExecutionIntermediate

Binance Order Execution

End-to-end order placement on Binance — authentication, spot vs futures routing, order types, and WebSocket order status updates.

binanceexecutionwebsocket
PerformanceBeginner

Drawdown Analysis

Compute max drawdown, drawdown duration, recovery time, and underwater curves to rigorously assess strategy risk.

drawdownriskunderwater
PerformanceBeginner

Sharpe & Sortino Ratios

Calculate Sharpe, Sortino, and Calmar ratios from a trade ledger — with annualisation, rolling windows, and regime breakdowns.

sharpesortinorisk-adjusted
PerformanceBeginner

Trade Metrics

Compute win rate, profit factor, average trade duration, expectancy, and per-trade P&L statistics from a complete trade ledger.

win rateprofit factorexpectancy
PerformanceBeginner

Equity Curve Visualisation

Plot equity curves, drawdown overlays, rolling Sharpe, and monthly P&L heatmaps for a comprehensive performance tearsheet.

equity curvetearsheetheatmap
PerformanceBeginner

QuantStats Report

Generate professional HTML tearsheets using QuantStats — full metrics, benchmark comparison, and rolling performance analysis.

quantstatstearsheetbenchmark
SignalsAdvanced

Meta-Labeling

Apply Marcos Lopez de Prado's meta-labeling framework to add a secondary ML model that filters primary strategy signals.

meta-labelingMLsignal filtering
SignalsAdvanced

Triple Barrier Labeling

Implement the triple barrier method for ML label generation — upper/lower barriers and a time-based barrier with dynamic sizing.

triple barrierlabelsML
SignalsIntermediate

Liquidity & Volume Confirmation

Use liquidity and volume metrics to confirm or filter primary signals — reducing false entries in low-volume conditions.

liquidityvolumeconfirmation
SignalsAdvanced

ML Feature Signal Fusion

Combine technical indicator features with ML model outputs into a unified signal score using weighted ensemble methods.

MLfusionensemble
SignalsIntermediate

Pattern & Indicator Confluence

Build a confluence engine that fires only when chart patterns and technical indicators agree — reducing noise and improving precision.

patternsconfluenceindicators
SignalsIntermediate

Multi-Timeframe Alignment

Align signals across multiple timeframes — only trade when the 1H, 4H, and 1D all agree on direction.

multi-timeframealignmenttrend
SignalsAdvanced

Regime-Based Signal Classifier

Route signals through regime-specific classifiers — use different models for bull, bear, and range-bound market conditions.

regimesclassifieradaptive
SignalsIntermediate

Volatility-Adjusted Filter

Scale signal thresholds dynamically with realised volatility to maintain consistent signal frequency across market regimes.

volatilityadaptivefiltering
SignalsIntermediate

Trend & Momentum Confirmation

Combine trend-following and momentum indicators into a dual-confirmation system that only signals when both agree.

trendmomentumconfirmation
SignalsIntermediate

TA Signal Confluence Engine

Score and rank technical indicator signals by confluence — build a composite signal that aggregates agreement across indicators.

technical analysisscoringcomposite
SignalsAdvanced

LSTM Price Prediction

Build and train an LSTM neural network on OHLCV sequences for price direction prediction — includes feature scaling and walk-forward validation.

LSTMdeep learningprediction
SignalsIntermediate

Regression Signal Model

Train a regression model to predict next-bar returns from technical features — with walk-forward cross-validation and feature importance.

regressionpredictionfeatures
SignalsIntermediate

Classification Signal Model

Predict trade direction (long/short/flat) using a classification model trained on lagged returns, volume, and volatility features.

classificationdirectionML
SignalsIntermediate

Prepare ML Dataset

Full ML data prep pipeline — feature engineering from OHLCV, labeling, train/test split with time-series awareness, and scaling.

feature engineeringpreprocessingdataset
SignalsIntermediate

Triangle Pattern Detection

Algorithmically detect ascending, descending, and symmetrical triangles using pivot-based trendline fitting.

triangleschart patternstrendlines
SignalsAdvanced

Head & Shoulders Detection

Detect head and shoulders (and inverse) patterns programmatically using peak/trough analysis and neckline confirmation.

head and shoulderschart patternsreversal
SignalsIntermediate

Flag & Pennant Detection

Identify bull/bear flags and pennant consolidation patterns by detecting sharp moves followed by tight parallel channels.

flagspennantscontinuation
SignalsBeginner

Swing High / Low Detector

Detect swing highs and lows with configurable lookback — the building block for pattern recognition, S/R, and structure mapping.

swingsstructurepivot points
SignalsIntermediate

BOS & CHoCH Detection

Detect Break of Structure (BOS) and Change of Character (CHoCH) events for smart money concept (SMC) based trading.

SMCBOSCHoCH
SignalsBeginner

Market Structure (HH/HL/LH/LL)

Map higher highs, higher lows, lower highs, and lower lows to track market structure and identify trend health.

market structuretrendHH HL
SignalsIntermediate

Order Block Detection

Identify institutional order blocks — the last up/down candle before a strong impulse move — for SMC-based entry zones.

order blocksSMCinstitutional
SignalsBeginner

Breakout Detection

Detect price breakouts from consolidation ranges, Donchian channels, and volatility compression zones with volume confirmation.

breakoutconsolidationvolume
SignalsIntermediate

Support & Resistance Zones

Compute dynamic support and resistance zones from historical price clusters, volume nodes, and swing pivot history.

supportresistancezones
SignalsBeginner

Candlestick Patterns

Detect classic candlestick patterns — doji, engulfing, hammer, shooting star, and morning/evening star — using TA-Lib.

candlestickTA-Libreversal
SignalsBeginner

Bollinger Band Reversion

Mean-reversion strategy using Bollinger Band extremes — enter on band touch, exit on mid-band return, with volatility filters.

bollinger bandsmean reversionvolatility
SignalsIntermediate

Multi-Indicator Score Strategy

Build a composite scoring system that ranks and combines signals from multiple indicators into a single entry/exit score.

compositescoringmulti-indicator
SignalsAdvanced

ML + TA Combined Strategy

Combine a trained ML classifier with traditional TA signals — use ML for direction, TA for timing entry and exit precision.

MLtechnical analysishybrid
SignalsAdvanced

Regime-Based Strategy Switching

Automatically switch between trend-following and mean-reversion modes based on a real-time market regime classifier.

regimesadaptiveswitching
SignalsIntermediate

Dynamic Stop + Volatility Strategy

Set stop-loss distances dynamically based on ATR — wider stops in high-volatility regimes, tighter in compressed markets.

ATRstopsvolatility
SignalsIntermediate

Volatility Squeeze Strategy

Trade Bollinger Band / Keltner Channel squeezes — enter on the first directional expansion after a compression period.

squeezebollingerkeltner
SignalsBeginner

ATR Volatility Breakout

Enter breakout trades when price exceeds a multiple of ATR from the prior day's close — a classic volatility expansion strategy.

ATRbreakoutvolatility
SignalsIntermediate

Volume Momentum Confirmation

Use OBV, VWAP deviation, and volume spikes to confirm momentum signals — only trade when volume supports the move.

volumemomentumOBV
SignalsIntermediate

Breakout Momentum Follow-Through

Enter breakouts only when followed by momentum confirmation — filtering false breakouts with ROC and volume threshold checks.

breakoutfollow-throughmomentum
SignalsBeginner

Rate of Change Strategy

Use the Rate of Change (ROC) indicator to build a momentum strategy — with look-back optimisation and regime filtering.

ROCmomentumlookback
SignalsBeginner

MACD Momentum Strategy

Classic MACD crossover strategy enhanced with histogram divergence signals, zero-line filters, and regime context.

MACDcrossovermomentum
SignalsIntermediate

VWAP Reversion Strategy

Intraday mean-reversion strategy trading deviations from VWAP — with standard deviation bands and time-of-day filters.

VWAPmean reversionintraday
SignalsBeginner

Keltner Channel Reversion

Mean-reversion strategy based on Keltner Channel extremes — compare performance against Bollinger Band reversion on the same asset.

keltnermean reversionchannels
SignalsIntermediate

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.

z-scorestatisticsmean reversion
SignalsBeginner

RSI Mean Reversion

RSI overbought/oversold mean-reversion strategy with dynamic threshold adaptation based on rolling percentile of RSI.

RSImean reversionoverbought
SignalsBeginner

Supertrend Strategy

Trend-following strategy using the Supertrend indicator — with ATR multiplier tuning and regime-filtered entry logic.

supertrendtrend followingATR
SignalsBeginner

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.

donchianbreakoutturtle trading
SignalsBeginner

ADX Trend Strength Strategy

Use ADX to measure trend strength and gate trades — only enter directional trades when ADX exceeds a configurable threshold.

ADXtrend strengthfilter
SignalsBeginner

EMA Ribbon Trend Strategy

Use a multi-EMA ribbon to identify trend direction and strength — enter when the ribbon is aligned and expanding.

EMAribbontrend following
SignalsBeginner

MA Crossover Strategy

The classic moving average crossover — SMA, EMA, and WMA variants with parameter sweep analysis and transaction cost sensitivity.

moving averagecrossovertrend
SignalsIntermediate

Build a Custom Indicator

Create a fully custom technical indicator from scratch in pandas — vectorised, compatible with TA-Lib and pandas-ta pipelines.

custom indicatorpandasvectorized
SignalsBeginner

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.

TA-LibindicatorsRSI MACD
SignalsBeginner

Technical Analysis with pandas-ta

Use the pandas-ta library for fast, vectorised indicator computation — covers setup, strategy objects, and bulk indicator runs.

pandas-taindicatorsvectorized
UtilitiesBeginner

API Key Management

Securely store, load, and rotate exchange API keys — environment variables, .env files, and encrypted key stores.

API keyssecurityconfiguration
UtilitiesIntermediate

Rate Limit Handling

Implement token-bucket and leaky-bucket rate limiters for exchange API calls — with retry logic and request queuing.

rate limitingAPIthrottling
UtilitiesBeginner

Logging Setup

Set up structured logging for trading bots — rotating file handlers, log levels, contextual fields, and integration with monitoring.

loggingmonitoringdebugging
UtilitiesBeginner

Config Management

Manage multi-environment configs for trading systems — pydantic-settings, YAML/TOML files, and environment-based overrides.

configurationpydanticenvironments
Notebooks · BitPredict