Vectorbt logo

Vectorbt

Community
agiprolabs
vectorbt

High-performance vectorized backtesting with parameter optimization, portfolio simulation, and rich performance metrics

Overview

Publisheragiprolabs
Repositoryclaude-trading-skills
Skill namevectorbt
Stars
434
Forks
85
Bundled files
4
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 4 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by agiprolabs on GitHub. Read the source before you install it.

Installation

Install the Vectorbt AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
    https://github.com/agiprolabs/claude-trading-skills/tree/main/skills/vectorbt
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/agiprolabs/claude-trading-skills.git /tmp/claude-trading-skills
mkdir -p .claude/skills
cp -r /tmp/claude-trading-skills/skills/vectorbt .claude/skills/vectorbt
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Vectorbt in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Vectorbt on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Vectorbt is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

Vectorized Backtesting with vectorbt

Overview

vectorbt is a Python library for vectorized backtesting — running strategy simulations using NumPy/pandas array operations instead of bar-by-bar loops. This makes it 100–1000x faster than event-driven frameworks (backtrader, zipline), enabling parameter optimization across thousands of combinations in seconds.

Key strengths:

  • Blazing speed via NumPy vectorization
  • Built-in parameter grid search and optimization
  • 50+ built-in performance metrics (Sharpe, Sortino, Calmar, max drawdown, profit factor)
  • Rich plotting (equity curves, drawdowns, trade markers, heatmaps)
  • Native pandas integration — your data stays in DataFrames throughout

Installation

bash
uv pip install vectorbt pandas numpy

vectorbt pulls in pandas, NumPy, and Plotly automatically. For technical indicators, also install pandas-ta:

bash
uv pip install vectorbt pandas-ta

Core Concepts

1. Signals — Boolean Entry/Exit Arrays

Strategies in vectorbt are expressed as boolean pandas Series (or arrays) indicating where to enter and exit positions:

python
import vectorbt as vbt
import pandas as pd

# Entry: buy when fast EMA crosses above slow EMA
entries = fast_ema > slow_ema
# Exit: sell when fast EMA crosses below slow EMA
exits = fast_ema < slow_ema

vectorbt resolves conflicting signals automatically (you can't enter while already in a position).

2. Portfolio — The Backtesting Engine

vbt.Portfolio.from_signals() is the primary backtesting function. It takes price data and entry/exit signals, simulates trades, and computes performance:

python
pf = vbt.Portfolio.from_signals(
    close=close_prices,
    entries=entries,
    exits=exits,
    init_cash=10_000,
    fees=0.003,       # 0.3% per trade
    slippage=0.005,   # 0.5% slippage
    freq="1h",        # hourly data
)

3. Metrics — Built-in Performance Analysis

python
# Full stats summary
print(pf.stats())

# Individual metrics
print(f"Total Return: {pf.total_return():.2%}")
print(f"Sharpe Ratio: {pf.sharpe_ratio():.3f}")
print(f"Max Drawdown: {pf.max_drawdown():.2%}")
print(f"Win Rate:     {pf.trades.win_rate():.2%}")

4. Parameter Optimization — Grid Search in Seconds

Pass arrays instead of scalars to test many parameter combos simultaneously:

python
import numpy as np

fast_periods = np.arange(5, 25, 2)   # 10 values
slow_periods = np.arange(20, 60, 5)  # 8 values

fast_ma = vbt.MA.run(close, fast_periods, short_name="fast")
slow_ma = vbt.MA.run(close, slow_periods, short_name="slow")

# This creates 80 parameter combinations automatically
entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)

Basic Workflow

Step 1: Load OHLCV Data

python
import pandas as pd

# From CSV
df = pd.read_csv("ohlcv.csv", parse_dates=["timestamp"], index_col="timestamp")
close = df["close"]

# From Yahoo Finance (traditional markets)
btc = vbt.YFData.download("BTC-USD", start="2023-01-01", end="2025-01-01")
close = btc.get("Close")

For Solana tokens, fetch data via the birdeye-api skill and load into a DataFrame.

Step 2: Compute Indicators

python
import pandas_ta as ta

# Using pandas-ta (see pandas-ta skill)
df.ta.ema(length=12, append=True)
df.ta.ema(length=26, append=True)
df.ta.rsi(length=14, append=True)
df.ta.bbands(length=20, std=2, append=True)

# Or using vectorbt built-ins
rsi = vbt.RSI.run(close, window=14)
bbands = vbt.BBANDS.run(close, window=20, alpha=2)

Step 3: Generate Entry/Exit Signals

python
# EMA crossover
entries = df["EMA_12"] > df["EMA_26"]
exits = df["EMA_12"] < df["EMA_26"]

# RSI mean reversion
entries = rsi.rsi_below(30)
exits = rsi.rsi_above(70)

Step 4: Run Backtest

python
pf = vbt.Portfolio.from_signals(
    close=close,
    entries=entries,
    exits=exits,
    init_cash=10_000,
    fees=0.003,
    slippage=0.005,
    size=0.95,               # use 95% of available cash
    size_type="percent",
    freq="1h",
)

Step 5: Analyze Results

python
# Summary statistics
print(pf.stats())

# Trade-level analysis
trades = pf.trades.records_readable
print(f"\nTrade count: {len(trades)}")
print(f"Avg holding period: {trades['Duration'].mean()}")

# Equity curve
pf.plot().show()

# Drawdown chart
pf.drawdowns.plot().show()

Key Portfolio Parameters

ParameterDescriptionExample
closePrice series (pd.Series or DataFrame)df["close"]
entriesBoolean entry signalsfast > slow
exitsBoolean exit signalsfast < slow
init_cashStarting capital10_000
feesFee per trade (fraction)0.003 (0.3%)
slippageSlippage per trade (fraction)0.005 (0.5%)
sizePosition size0.95
size_typeHow to interpret size"percent", "amount", "value"
freqData frequency"1h", "4h", "1d"
directionTrade direction"both", "longonly", "shortonly"
accumulateAllow adding to positionsFalse
sl_stopStop-loss level (fraction)0.05 (5%)
tp_stopTake-profit level (fraction)0.10 (10%)

Performance Metrics

Returns

  • total_return() — cumulative return over the period
  • annualized_return() — annualized compound return
  • daily_returns() — Series of daily returns

Risk

  • max_drawdown() — maximum peak-to-trough decline
  • annualized_volatility() — annualized standard deviation of returns
  • value_at_risk() — VaR at specified confidence level

Risk-Adjusted

  • sharpe_ratio() — excess return per unit volatility
  • sortino_ratio() — excess return per unit downside deviation
  • calmar_ratio() — annualized return / max drawdown
  • omega_ratio() — probability-weighted gain/loss ratio

Trade Statistics

  • trades.win_rate() — fraction of profitable trades
  • trades.profit_factor() — gross profit / gross loss
  • trades.expectancy() — average P&L per trade
  • trades.avg_winning_trade() — mean profit on winners
  • trades.avg_losing_trade() — mean loss on losers
  • trades.count() — total number of completed trades

Parameter Optimization

Grid Search

python
fast_windows = [5, 8, 12, 15, 20]
slow_windows = [20, 26, 30, 40, 50]

# Run all 25 combos at once
fast_ma = vbt.MA.run(close, fast_windows, short_name="fast")
slow_ma = vbt.MA.run(close, slow_windows, short_name="slow")

entries = fast_ma.ma_crossed_above(slow_ma)
exits = fast_ma.ma_crossed_below(slow_ma)

pf = vbt.Portfolio.from_signals(close, entries, exits, fees=0.003)

# Find best params by Sharpe
sharpe = pf.sharpe_ratio()
best_idx = sharpe.idxmax()
print(f"Best params: {best_idx}, Sharpe: {sharpe[best_idx]:.3f}")

Walk-Forward Validation

Always validate optimized parameters on out-of-sample data:

python
# Split: 70% train, 30% test
split_idx = int(len(close) * 0.7)
train_close = close.iloc[:split_idx]
test_close = close.iloc[split_idx:]

# Optimize on training data
# ... (run grid search on train_close)

# Validate best params on test data
# ... (run single backtest on test_close with best params)

See references/optimization_guide.md for detailed walk-forward methodology and overfitting prevention.

Crypto-Specific Considerations

24/7 Markets

Crypto markets never close. Use hourly or minute-based frequencies, not business-day frequencies:

python
# Correct for crypto
pf = vbt.Portfolio.from_signals(close, entries, exits, freq="1h")

# Wrong — business days assume market closures
# pf = vbt.Portfolio.from_signals(close, entries, exits, freq="1B")

Realistic Fees

DEX swaps on Solana typically cost 0.25–1% including AMM fees. CEX spot fees are 0.05–0.1%.

python
# Solana DEX (conservative)
pf = vbt.Portfolio.from_signals(close, entries, exits, fees=0.005)

# CEX spot
pf = vbt.Portfolio.from_signals(close, entries, exits, fees=0.001)

Slippage

Low-liquidity tokens can have 1–5% slippage. Always model this:

python
# High-liquidity (SOL, ETH): 0.1–0.5%
pf = vbt.Portfolio.from_signals(close, entries, exits, slippage=0.003)

# Low-liquidity memecoins: 1–3%
pf = vbt.Portfolio.from_signals(close, entries, exits, slippage=0.02)

Short History

Many tokens have less than 1 year of data. Be cautious about annualizing metrics from short samples.

Common Strategy Patterns

EMA Crossover

python
fast = vbt.MA.run(close, 12, short_name="fast")
slow = vbt.MA.run(close, 26, short_name="slow")
entries = fast.ma_crossed_above(slow)
exits = fast.ma_crossed_below(slow)

RSI Mean Reversion

python
rsi = vbt.RSI.run(close, 14)
entries = rsi.rsi_crossed_below(30)
exits = rsi.rsi_crossed_above(70)

Bollinger Band Breakout

python
bb = vbt.BBANDS.run(close, window=20, alpha=2)
entries = close > bb.upper
exits = close < bb.lower

Stop-Loss and Take-Profit

python
pf = vbt.Portfolio.from_signals(
    close, entries, exits,
    sl_stop=0.05,    # 5% stop-loss
    tp_stop=0.10,    # 10% take-profit
)

Related Skills

  • pandas-ta — Technical indicator computation (feeds vectorbt signals)
  • birdeye-api — Fetch Solana token OHLCV data for backtesting
  • trading-visualization — Advanced chart generation for backtest results
  • portfolio-analytics — Deeper portfolio-level risk/return analysis
  • position-sizing — Optimal position sizing methodology
  • risk-management — Portfolio-level risk guardrails
  • regime-detection — Market regime awareness for adaptive strategies

Files

References

  • references/api_guide.md — Complete vectorbt API reference for Portfolio, indicators, plotting, and data loading
  • references/optimization_guide.md — Grid search, walk-forward validation, overfitting prevention, and optimization best practices

Scripts

  • scripts/backtest_example.py — Three-strategy backtest comparison using synthetic data (EMA crossover, RSI mean reversion, Bollinger breakout)
  • scripts/parameter_sweep.py — EMA crossover parameter grid search with walk-forward validation

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Vectorbt AI skill do?

High-performance vectorized backtesting with parameter optimization, portfolio simulation, and rich performance metrics

Why use Vectorbt on TypingMind?

Because you install it once and use it with any model. Vectorbt is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Vectorbt in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/agiprolabs/claude-trading-skills/tree/main/skills/vectorbt. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Vectorbt?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Vectorbt?

As many as you like. As long as a model supports skills, you can use Vectorbt with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Vectorbt AI skill free?

Yes. It is published on GitHub by agiprolabs under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇