Vectorbt 标志

Vectorbt

社区
agiprolabs
vectorbt

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

概览

发布者agiprolabs
代码仓库claude-trading-skills
技能名称vectorbt
星标数
434
复刻数
85
附带文件
4
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 4 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 agiprolabs 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Vectorbt AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/agiprolabs/claude-trading-skills/tree/main/skills/vectorbt
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

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
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Vectorbt,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Vectorbt。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Vectorbt 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

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

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Vectorbt AI 技能有什么作用?

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

为什么在 TypingMind 中使用 Vectorbt?

因为您只需安装一次,就能搭配任何模型使用。Vectorbt 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Vectorbt?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/agiprolabs/claude-trading-skills/tree/main/skills/vectorbt。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Vectorbt?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Vectorbt 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Vectorbt 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Vectorbt AI 技能免费吗?

是的。agiprolabs 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇