Sandbox
@marketcalls/vectorbt-backtesting-skills

VectorBT backtesting skills for agent coding tools

This repo packages skills and reference rules for generating VectorBT trading backtests. The skills cover setup, backtesting, optimization, quick stats, and strategy comparison, while the rule files define data sources, indicators, costs, validation, plotting, and tearsheets. It is built to work through `npx skills` across many coding agents.

202 stars44 forksPythonUpdated 2mo ago
Who it's for

Builders who use agent coding tools to explore and validate trading strategies across Indian, US, and crypto markets.

What it delivers

You can generate market-aware backtests with realistic costs, benchmark comparisons, and ready-made strategy templates.

What it does

Command-based skills

Provides `/setup`, `/backtest`, `/optimize`, `/quick-stats`, and `/strategy-compare` skills for common backtesting tasks.

Market-specific cost models

Covers Indian, US, and crypto fee structures with configurable `fees` and `fixed_fees` values.

OpenAlgo ta indicator workflow

Uses `openalgo.ta` as the default indicator library, with signals like `exrem`, `crossover`, and `crossunder`.

OpenStatz tearsheets

Generates offline HTML tearsheets with metrics, drawdown analysis, rolling stats, monthly heatmaps, and Monte Carlo simulation.

Strategy template library

Includes 12 ready-made templates such as EMA crossover, RSI, Donchian, Supertrend, MACD, dual momentum, and walk-forward.

Robustness and validation rules

Adds walk-forward analysis, Monte Carlo trade shuffle, noise injection, parameter sensitivity, and delay testing.

How to get it

  1. 1Install the skills into your project using npx skills. The CLI auto-detects your AI…
    # GitHub shorthand
    npx skills add marketcalls/vectorbt-backtesting-skills
    
    # Full GitHub URL
    npx skills add https://github.com/marketcalls/vectorbt-backtesting-skills
  2. 2Install a specific skill only
    npx skills add marketcalls/vectorbt-backtesting-skills -s backtest
    npx skills add marketcalls/vectorbt-backtesting-skills -s optimize
    npx skills add marketcalls/vectorbt-backtesting-skills -s vectorbt-expert
    npx skills add marketcalls/vectorbt-backtesting-skills -s setup
  3. 3List available skills before installing
    npx skills add marketcalls/vectorbt-backtesting-skills -l
  4. 4Install globally (available across all projects)
    npx skills add marketcalls/vectorbt-backtesting-skills -g
  5. 5Indian Markets — requires OpenAlgo
    git clone https://github.com/marketcalls/openalgo.git
    cd openalgo
    pip install -r requirements.txt
    python app.py
  6. 6Detects OS, creates venv, installs dependencies, creates folder structure, and collects…
    /setup
    /setup python3.12

README

VectorBT Backtesting Skills for Agentic Coding Tools

A comprehensive collection of backtesting skills for trading strategies using VectorBT. Works with 40+ AI coding agents via skills.sh — including Claude Code, Cursor, Codex, OpenCode, Cline, Windsurf, GitHub Copilot, Gemini CLI, Roo Code, and more.

Supports Indian markets, US markets, and Crypto markets with realistic transaction cost modeling, OpenAlgo indicators (100+, TA-Lib available on request), market-specific benchmarking, OpenStatz tearsheets, and robustness testing. Broker-neutral by design — fee models use industry-standard references that can be customized for any broker.

Quick Install

Install the skills into your project using npx skills. The CLI auto-detects your AI coding agent and installs skills to the correct directory.

# GitHub shorthand
npx skills add marketcalls/vectorbt-backtesting-skills

# Full GitHub URL
npx skills add https://github.com/marketcalls/vectorbt-backtesting-skills

Install a specific skill only:

npx skills add marketcalls/vectorbt-backtesting-skills -s backtest
npx skills add marketcalls/vectorbt-backtesting-skills -s optimize
npx skills add marketcalls/vectorbt-backtesting-skills -s vectorbt-expert
npx skills add marketcalls/vectorbt-backtesting-skills -s setup

List available skills before installing:

npx skills add marketcalls/vectorbt-backtesting-skills -l

Install globally (available across all projects):

npx skills add marketcalls/vectorbt-backtesting-skills -g

Supported AI Coding Agents

Skills are installed via skills.sh which supports 40+ agents. Each agent reads skills from its own directory:

AgentSkills Directory
Claude Code.claude/skills/
Cursor.agents/skills/
Codex.agents/skills/
OpenCode.agents/skills/
Cline.agents/skills/
Windsurf.agents/skills/
GitHub Copilot.agents/skills/
Gemini CLI.agents/skills/
Roo Code.agents/skills/
+ 30 moreAuto-detected by npx skills

The npx skills add command detects which agents you have installed and places the skill files in the correct paths automatically.

Supported Markets

MarketData SourceFee ReferenceDefault Benchmark
IndiaOpenAlgo (NSE, BSE, NFO, MCX)Delivery, Intraday, F&O (4-segment)NIFTY 50
USyfinance (NYSE, NASDAQ)Stocks, Options, Futures (per-share + per-contract)S&P 500
Cryptoyfinance / CCXTSpot, Perpetual Futures (maker/taker)Bitcoin
CustomAny provider via extensible patternUser-definedUser-defined

Broker-neutral: Fee models use realistic industry-standard defaults and can be adjusted for any broker by changing the fees and fixed_fees constants.

Capabilities

Skills (User-Invocable Commands)

CommandWhat It Does
/setupDetects OS, creates venv, installs OpenAlgo + all packages (TA-Lib optional), creates backtesting/ folders, configures .env with API keys
/backtestGenerates a complete backtest script with signals, market-specific fees, benchmark comparison, plain-language report, OpenStatz tearsheet
/optimizeParameter grid search with OpenAlgo ta indicators, tqdm progress bars, Plotly heatmaps, best params vs benchmark
/quick-statsInline code block (no file) — fetch data, run EMA crossover, print compact stats + benchmark alpha
/strategy-compareSide-by-side comparison of multiple strategies on same symbol, overlaid equity curves

Pre-Built Strategy Templates (12)

StrategyTypeDescription
EMA CrossoverTrendEMA 10/20 crossover
RSIMean-reversionRSI(14) oversold/overbought
Donchian ChannelBreakoutChannel breakout with shifted levels (no lookahead)
SupertrendTrendSupertrend with intraday session windows (9:30-15:00, exit 15:15)
MACDTrend + BreakoutMACD zero-line regime + signal-candle breakout
SDA2TrendWMA + STDDEV + ATR band system
Double MomentumMomentumMOM + MOM-of-MOM with next-bar fill
Dual MomentumRotationQuarterly ETF rotation (NIFTYBEES vs GOLDBEES)
Buy & HoldPassiveStatic multi-asset allocation with FD benchmark
RSI AccumulationAccumulationWeekly RSI slab-wise buying (5%/10%/20% by RSI level)
Walk-ForwardValidationRolling train/test optimization with WFE scoring
Realistic CostsAnalysisSame strategy across 5 fee tiers (zero to full delivery)

Knowledge Base (20 Rule Files)

CategoryWhat's Covered
DataOpenAlgo (India), yfinance (US/Global), CCXT (Crypto), custom providers, .env + python-dotenv, CSV loading, resampling
IndicatorsOpenAlgo ta by default - 100+ indicators (EMA, SMA, RSI, MACD, BBands, ATR, ADX, STDDEV, MOM, Supertrend, Donchian, Ichimoku, HMA, KAMA, ALMA, ZLEMA, VWMA, oscillators, statistical, hybrid). TA-Lib only if explicitly requested
Signalsta.exrem() signal cleaning, ta.crossover(), ta.crossunder(), ta.flip() regime detection
Simulationfrom_signals, from_orders, from_holding, long/short/both directions
SizingPercent, Value, TargetPercent, whole shares (min_size=1), futures lot sizes, fractional crypto
CostsIndia: 4-segment model (Delivery 0.111%, Intraday 0.0225%, Futures 0.018%, Options 0.098%). US: Per-share + per-contract model (Stocks ~0.01%, Options ~0.2%, Futures ~0.001%). Crypto: Maker/taker model (Spot 0.1%, Futures 0.02%/0.05%, funding rates). All customizable.
FuturesSEBI revised lot sizes (Dec 2025): NIFTY=65, BANKNIFTY=30, FINNIFTY=60. US: E-mini/Micro contract specs
RiskStop loss, take profit, trailing stop (sl_trail)
OptimizationLoop-based (OpenAlgo ta / TA-Lib compliant) + broadcasting (vbt.MA exception for parameter sweeps)
BenchmarkingIndia: NIFTY 50 via OpenAlgo. US: S&P 500 (^GSPC). Crypto: Bitcoin (BTC-USD). Strategy vs Benchmark table always produced
ReportingPlain-language backtest explanation for normal traders. OpenStatz HTML tearsheets with 30+ metrics, Monte Carlo simulations
PlottingPlotly dark theme, candlestick with xaxis type="category" (no weekend gaps), VectorBT 7-panel plot pack
ValidationWalk-forward analysis (WFE ratio), robustness testing (Monte Carlo trade shuffle, noise injection, parameter sensitivity, entry/exit delay, cross-symbol validation)
Safety10 common pitfalls with prevention, checklist before going live

Prerequisites

1. AI Coding Agent

Install any supported AI coding agent. For example:

Then install the skills:

npx skills add marketcalls/vectorbt-backtesting-skills

2. Data Source Setup

Indian Markets — requires OpenAlgo:

git clone https://github.com/marketcalls/openalgo.git
cd openalgo
pip install -r requirements.txt
python app.py

OpenAlgo runs locally at http://127.0.0.1:5000. You need a broker account connected via OpenAlgo and an API key from the dashboard. See OpenAlgo documentation.

US Markets — no setup needed. Uses yfinance (public Yahoo Finance data).

Crypto Markets — no setup needed for public data (yfinance or CCXT). Exchange API keys are optional (only for private endpoints).

3. Python Environment Setup

Use the /setup skill for automated setup, or manually:

python -m venv venv
source venv/bin/activate   # Linux/Mac
# venv\Scripts\activate    # Windows

# Install Python packages (OpenAlgo ta is the default indicator library - no C library needed)
pip install openalgo vectorbt plotly anywidget nbformat pandas numpy yfinance python-dotenv tqdm scipy numba ipywidgets openstatz ccxt

# Optional: only if you want to be able to request TA-Lib explicitly in a backtest
brew install ta-lib         # macOS
# sudo apt install libta-lib-dev  # Linux
pip install ta-lib

4. Configure API Keys

cp .env.sample .env
# Edit .env with your API keys

Usage Examples

/setup - Environment Setup

Detects OS, creates venv, installs dependencies, creates folder structure, and collects API keys into .env.

/setup
/setup python3.12

/backtest - Quick Backtest

Create a complete backtest script with market-specific fees, benchmark comparison, plain-language report, and OpenStatz tearsheet.

# Indian Markets
/backtest ema-crossover SBIN NSE D
/backtest rsi RELIANCE NSE D
/backtest supertrend NIFTY NFO 5m

# US Markets
/backtest ema-crossover AAPL
/backtest rsi MSFT

# Crypto Markets
/backtest ema-crossover BTC-USD

/optimize - Parameter Optimization

Optimize strategy parameters, generate Plotly heatmaps, and compare best parameters vs benchmark.

/optimize ema-crossover SBIN NSE D
/optimize rsi AAPL

/quick-stats - Inline Stats

Print key backtest stats with benchmark comparison without creating a file.

/quick-stats RELIANCE
/quick-stats AAPL
/quick-stats BTC-USD

/strategy-compare - Compare Strategies

Compare multiple strategies side-by-side with benchmark.

/strategy-compare RELIANCE ema-crossover rsi donchian
/strategy-compare AAPL ema-crossover rsi macd

Key Features

Multi-Market Transaction Costs

Realistic fee models for each market, auto-selected based on the asset. All fee constants are configurable — adjust for your broker by changing the fees and fixed_fees values.

Indian Market Fees

Segmentfeesfixed_fees
Delivery Equity0.00111 (0.111%)Rs 20/order
Intraday Equity0.000225 (0.0225%)Rs 20/order
F&O Futures0.00018 (0.018%)Rs 20/order
F&O Options0.00098 (0.098%)Rs 20/order

US Market Fees

Segmentfeesfixed_fees
Stocks (Pro/Fixed)0.0001 (0.01%)$1.00/order
Stocks (Commission-Free)0.00001 (~0.001%)$0
Options0.002 (0.2%)$0.65/contract
E-mini Futures (ES, NQ)0.000009 (~0.001%)$2.25/contract
Micro Futures (MES, MNQ)0.00002 (~0.002%)$0.55/contract

Crypto Market Fees

Segmentfeesfixed_fees
Spot (Base)0.001 (0.1%)$0
Spot (Discounted)0.00075 (0.075%)$0
USDT-M Futures (Taker)0.0005 (0.05%)$0
USDT-M Futures (Maker)0.0002 (0.02%)$0
COIN-M Futures (Taker)0.0005 (0.05%)$0

Using a different broker? Simply override the fee constants in your backtest script. The rule files include detailed breakdowns (STT, exchange fees, regulatory fees, clearing fees) so you can recalculate for any broker.

OpenAlgo ta Indicators (Default)

All strategies use openalgo.ta for technical indicators by default - 100+ indicators across trend, momentum, volatility, volume, oscillators, statistical, and hybrid categories. VectorBT built-in indicators are never used.

from openalgo import ta
ema_fast = ta.ema(close, 10)
st_line, st_direction = ta.supertrend(high, low, close, period=10, multiplier=3.0)
entries = ta.exrem(buy_raw.fillna(False), sell_raw.fillna(False))

Specialty indicators with no TA-Lib equivalent (Supertrend, Donchian, Ichimoku, HMA, KAMA, ALMA, ZLEMA, VWMA) plus signal utilities (exrem, crossover, crossunder, flip) always come from openalgo.ta.

TA-Lib (Opt-In Only)

Only used when the user explicitly asks for "talib"/"TA-Lib" in their request:

import talib as tl
ema_fast = pd.Series(tl.EMA(close.values, timeperiod=10), index=close.index)

Market-Specific Benchmarks

MarketDefault BenchmarkSource
IndiaNIFTY 50OpenAlgo (NSE_INDEX)
USS&P 500yfinance (^GSPC or SPY)
CryptoBitcoinyfinance (BTC-USD)

Every backtest produces a Strategy vs Benchmark comparison table.

OpenStatz Tearsheets

A modern interactive tearsheet with 30+ metrics, drawdown analysis, rolling statistics, monthly heatmaps, and Monte Carlo simulations. ostz.dashboard(...) renders the same interactive dashboard as openstatz serve into a single self-contained offline HTML file - no server, no [app] extra, no network. OpenStatz replaces QuantStats project-wide and keeps a numerical-parity contract on its metrics.

import openstatz as ostz  # alias as ostz, not os - avoids shadowing the stdlib os module

# dashboard() needs the benchmark as a returns Series (not a ticker string)
benchmark = ostz.providers.download_returns("^NSEI").reindex(pf.returns().index).fillna(0)
ostz.dashboard(pf.returns(), benchmark=benchmark, output="tearsheet.html")

Plain-Language Report Explanation

Every backtest explains results so normal traders can understand:

* Total Return: Your strategy made 45.23% while NIFTY 50 made 32.10%
  -> BEAT the market by 13.13%
* Max Drawdown: -12.34% - the biggest drop from peak
  -> On Rs 10,00,000 capital, worst temporary loss = Rs 1,23,400
* Sharpe Ratio: 1.45 (return per unit of risk, >1 decent, >2 excellent)

Extensible Data Providers

Built-in support for OpenAlgo, yfinance, and CCXT. Add custom providers (Alpaca, Twelve Data, etc.) following the pattern in data-fetching.md. All API keys stored in .env via python-dotenv.

SEBI Revised Lot Sizes (Effective 31 Dec 2025)

IndexLot SizeExchange
Nifty 5065NFO
Nifty Bank30NFO
Nifty Financial Services60NFO
Nifty Midcap Select120NFO
Nifty Next 5025NFO
BSE Sensex20BFO
BSE Bankex30BFO
BSE Sensex 5070BFO

Backtesting Folder Structure

Strategy name = folder name. Symbol name = file prefix. Each strategy folder is self-contained.

backtesting/
├── ema_crossover/
│   ├── .env
│   ├── SBIN_ema_crossover_backtest.py
│   ├── SBIN_ema_crossover_trades.csv
│   ├── SBIN_tearsheet.html
│   ├── AAPL_ema_crossover_backtest.py
│   └── AAPL_ema_crossover_trades.csv
├── rsi/
│   ├── .env
│   ├── INFY_rsi_backtest.py
│   └── ...
├── supertrend/
│   └── ...
└── custom/
    └── ...

Project Structure

.
├── .claude/
│   └── skills/
│       ├── setup/                    # /setup - Environment setup
│       │   └── SKILL.md
│       ├── backtest/                 # /backtest - Quick backtest
│       │   └── SKILL.md
│       ├── optimize/                 # /optimize - Parameter optimization
│       │   └── SKILL.md
│       ├── quick-stats/              # /quick-stats - Inline stats
│       │   └── SKILL.md
│       ├── strategy-compare/         # /strategy-compare - Compare strategies
│       │   └── SKILL.md
│       └── vectorbt-expert/          # Knowledge base (auto-loaded)
│           ├── SKILL.md              # Main skill (modular reference hub)
│           └── rules/                # 20 modular rule files
│               ├── data-fetching.md
│               ├── simulation-modes.md
│               ├── position-sizing.md
│               ├── indicators-signals.md
│               ├── openalgo-ta-helpers.md
│               ├── stop-loss-take-profit.md
│               ├── parameter-optimization.md
│               ├── performance-analysis.md
│               ├── plotting.md
│               ├── indian-market-costs.md
│               ├── us-market-costs.md
│               ├── crypto-market-costs.md
│               ├── futures-backtesting.md
│               ├── long-short-trading.md
│               ├── csv-data-resampling.md
│               ├── walk-forward.md
│               ├── robustness-testing.md
│               ├── pitfalls.md
│               ├── strategy-catalog.md
│               ├── openstatz-tearsheet.md
│               └── assets/           # Production-ready templates
│                   ├── ema_crossover/backtest.py
│                   ├── rsi/backtest.py
│                   ├── donchian/backtest.py
│                   ├── supertrend/backtest.py
│                   ├── macd/backtest.py
│                   ├── sda2/backtest.py
│                   ├── momentum/backtest.py
│                   ├── dual_momentum/backtest.py
│                   ├── buy_hold/backtest.py
│                   ├── rsi_accumulation/backtest.py
│                   ├── walk_forward/template.py
│                   └── realistic_costs/template.py
├── .env.sample                      # Environment template (copy to .env)
├── backtesting/                      # Generated backtest scripts (per strategy)
│   ├── ema_crossover/
│   ├── rsi/
│   ├── donchian/
│   ├── supertrend/
│   ├── macd/
│   ├── sda2/
│   ├── momentum/
│   ├── dual_momentum/
│   ├── buy_hold/
│   ├── rsi_accumulation/
│   ├── walk_forward/
│   └── custom/
└── README.md

Rule Files Reference

Rule FileDescription
data-fetching.mdOpenAlgo (India), yfinance (US), CCXT (Crypto), custom providers, .env setup
simulation-modes.mdfrom_signals, from_orders, from_holding, direction types
position-sizing.mdAmount/Value/Percent/TargetPercent sizing, whole shares
indicators-signals.mdOpenAlgo ta indicator reference (default), TA-Lib opt-in, signal generation
openalgo-ta-helpers.mdComplete OpenAlgo ta catalog (100+ indicators): exrem, crossover, Supertrend, Donchian, Ichimoku, MAs
stop-loss-take-profit.mdFixed SL, TP, trailing stop configurations
parameter-optimization.mdBroadcasting and loop-based optimization, heatmaps
performance-analysis.mdStats, metrics, benchmark comparison, CAGR calculation
plotting.mdCandlestick (category x-axis), VectorBT plots, custom Plotly
indian-market-costs.mdIndian market fee model — delivery, intraday, F&O (4-segment)
us-market-costs.mdUS market fee model — stocks, options, futures (per-share + per-contract)
crypto-market-costs.mdCrypto fee model — spot, perpetual futures, funding rates (maker/taker)
futures-backtesting.mdSEBI revised lot sizes (Dec 2025), US contract specs, value sizing
long-short-trading.mdSimultaneous long/short, direction comparison
csv-data-resampling.mdLoading CSV data, resampling with Indian market alignment
walk-forward.mdWalk-forward analysis, WFE ratio, rolling optimization
robustness-testing.mdMonte Carlo, noise test, parameter sensitivity, delay test
pitfalls.md10 common mistakes and checklist before going live
strategy-catalog.mdAll strategy types with code snippets and asset references
openstatz-tearsheet.mdOpenStatz interactive offline dashboard, 30+ metrics, Monte Carlo (replaces QuantStats)

Data Sources

SourceUse CaseTickers/CodesAPI Key Required
OpenAlgoIndian markets (primary)NSE, BSE, NFO, BFO, CDS, MCX, NSE_INDEX, BSE_INDEXYes (OPENALGO_API_KEY)
yfinanceUS markets, global, cryptoAAPL, SPY, ^GSPC, ^NSEI, BTC-USD, ETH-USDNo
CCXTCrypto exchangesBTC/USDT, ETH/USDT (higher resolution data)Optional
CustomAny providerUser-definedUser-defined

Configuration

Copy the .env.sample and fill in your API keys:

cp .env.sample .env

The .env file supports:

# Indian Markets (OpenAlgo)
OPENALGO_API_KEY=your_openalgo_api_key_here
OPENALGO_HOST=http://127.0.0.1:5000

# Crypto Markets (CCXT) — Optional
CRYPTO_API_KEY=
CRYPTO_SECRET_KEY=

# Custom Data Providers - add your own keys
# ALPACA_API_KEY=
# TWELVEDATA_API_KEY=

US market data via yfinance does not require an API key.

License

MIT

Files in the repo

Repository payload6 top-level entries
  • .claude
  • backtesting
  • .env.sample
  • .gitignore
  • README.md
  • requirements.txt

Discussion (0)

Ask about usage, or say what you built with it

Sign in to join the discussion.

No comments yet. Be the first to say what this is good for.

More skills

obra/
superpowers

An agentic skills framework & software development methodology that works.

285k
1 add

Turn any codebase, with its docs, SQL schemas, configs, and PDFs, into a queryable knowledge graph. A /graphify skill for Claude Code, Cursor, Codex, and Gemini CLI: local deterministic AST parsing, every edge explained, no vector store.

117k
1 add
Vincentwei1021/
anything2explainer

Topic in, narrated explainer video out. A Claude Code / Codex skill that turns any topic into a black-canvas motion-graphics explainer video with TTS voiceover, subtitles and a chapter progress bar. Chinese or English; every frame drawn in code with Remotion.

666

Open-source AI job search: scan job portals, evaluate listings into a structured A-H report with a global 1-5 score, tailor your CV, track applications — runs locally in your AI coding CLI (Claude Code, Codex, OpenCode, Antigravity…)

71k