Agent skill

Backtrader

by agiprolabs in agiprolabs/claude-trading-skills

Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

MITAuto-check passedBackend & APIs

Install Backtrader

skills CLI
$ npx skills add agiprolabs/claude-trading-skills --skill backtrader -a claude-code

Project install by default; add -g for ~/.claude/skills/.

GitHub CLI
$ gh skill install agiprolabs/claude-trading-skills backtrader --agent claude-code

Project scope by default; add --scope user for a personal install. Needs GitHub CLI 2.90.0 or later (public preview).

Manual copy
$ git clone --depth 1 https://github.com/agiprolabs/claude-trading-skills.git skills-src && mkdir -p .claude/skills && cp -r skills-src/skills/backtrader .claude/skills/backtrader && rm -rf skills-src

Use ~/.claude/skills/ instead of .claude/skills for a personal install. The folder must contain SKILL.md.

Claude Code skills documentation · loads skills from .claude/skills/

Facts

Skill name
backtrader
GitHub stars
410
Token cost
~2.4k tokens
SKILL.md length
626 words
Files
5 (incl. scripts, references)
Skills in repo
68
Repo updated
First seen
Licence
MIT

At a glance

Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

  • Works in 5 steps: Cerebro (the engine) → Strategy (your logic) → Data Feed → …
  • Tasks that involve Event-driven systems
  • SKILL.md covers Event-Driven vs Vectorized, Core Concepts, Order Types and Position Sizing (Sizers), plus 7 more sections
  • Runs Python scripts from its folder; calls python and uv

What it does

Backtrader is an agent skill from agiprolabs/claude-trading-skills. Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

Its SKILL.md is about 2.4k tokens, which your agent loads only when the skill is triggered. The skill folder holds 6 other files, including scripts and reference files (for example `references/api_guide.md`, `references/strategy_patterns.md` and `scripts/backtest_strategy.py`).

It sits in Backend & APIs, covering Event-driven systems and Trading and backtesting. The repository describes itself as: 68 trading, DeFi, and quantitative finance Agent Skills. Works with Claude Code, Cursor, Codex, Gemini CLI, and 30+ other tools. The licence is MIT.

When your agent uses it

  • Tasks that involve Event-driven systems
  • Tasks that involve Trading and backtesting

Example prompts

  • “/backtrader”

Requirements

  • Python 3

Workflow steps

5 steps, taken from the step headings in SKILL.md.

  1. Cerebro (the engine)
  2. Strategy (your logic)
  3. Data Feed
  4. Broker
  5. Analyzers

What it can do on your machine

Read from SKILL.md and the folder at commit 981e1d7. It shows what the files ask for, not the result of running them.

  • Tool permissions

    Pre-approves nothing: there is no allowed-tools line, so your agent's usual permission prompts apply.

    From allowed-tools in the SKILL.md frontmatter.

  • Runs code

    Ships 2 files in scripts/ (Python), which the agent can run.

    Shell commands in SKILL.md call:

    • python
    • uv

    From the folder's file list and the shell code blocks in SKILL.md.

  • Network

    No URLs in SKILL.md. Its commands use uv, which can reach the network depending on how they are called.

    From URLs in SKILL.md, links to its own repository left out.

  • Credentials

    Names no API keys, tokens, secrets or passwords.

    From names ending in _API_KEY, _TOKEN, _SECRET, _KEY or _PASSWORD in SKILL.md.

Context cost

Backtrader loads about 2.4k tokens when it runs, and up to ~6.5k if it reads all its reference files. Until then it costs about 31 tokens; SKILL.md has 626 words of instructions outside code blocks.

Always · name and description, kept in context so the agent knows when to use it
~31
When it runs · the whole SKILL.md, loaded when a task matches
~2.4k
With references · SKILL.md plus every file in references/, read only if the agent opens them
~6.5k

Estimates: characters ÷ 4, the usual rule of thumb; real counts depend on the model's tokenizer. Scripts and assets cost tokens only if the agent reads them.

Safety

Auto-check passed

The automated check found no risky patterns in SKILL.md.

Automated static check — not a guarantee. Review scripts before installing. It scans the text of SKILL.md for risky patterns (piping downloads into a shell, reading credential files, hidden Unicode, destructive commands); the scripts in this folder are not scanned.

SKILL.md

The full file from agiprolabs/claude-trading-skills at commit 981e1d7, republished under its MIT licence (© agiprolabs). 626 words, ~2,444 tokens.

Download SKILL.mdSave it as .claude/skills/backtrader/SKILL.md (or your agent's skills folder). This skill also uses 4 other files; get the full folder from GitHub.
name
backtrader
description
Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators

Backtrader

Backtrader is a Python event-driven backtesting framework that processes data bar-by-bar, simulating realistic execution with a built-in broker, order management, and position tracking. Unlike vectorized frameworks (vectorbt, pandas), backtrader walks through history one bar at a time, firing callbacks that let you implement complex order logic that depends on previous fills, partial executions, and conditional brackets.

Event-Driven vs Vectorized

AspectBacktrader (event-driven)vectorbt (vectorized)
Execution modelBar-by-bar callbacksWhole-array operations
SpeedSlower (Python loop)Fast (NumPy/Numba)
Order typesMarket, limit, stop, stop-limit, bracket, OCOMarket only (native)
RealismBuilt-in broker with commission, slippage, marginManual slippage modeling
Multi-timeframeNative resampledataManual alignment
Best forComplex strategies, bracket orders, portfolioFast parameter sweeps, simple signals

Use backtrader when you need:

  • Bracket orders (entry + stop loss + take profit as a unit)
  • Stop-limit or trailing stop orders
  • Order-dependent logic (scale in after first fill, cancel if not filled in N bars)
  • Multi-timeframe strategies (daily signals, hourly execution)
  • Realistic commission and slippage modeling

Use vectorbt when you need:

  • Fast parameter optimization over thousands of combinations
  • Simple long/short signals without complex order management
  • Quick prototyping and statistical analysis of results

Core Concepts

Backtrader has five core objects that interact through an event loop:

1. Cerebro (the engine)

The central orchestrator. You add strategies, data feeds, analyzers, and sizers to Cerebro, then call run().

python
import backtrader as bt

cerebro = bt.Cerebro()
cerebro.addstrategy(MyStrategy, fast_period=10, slow_period=30)
cerebro.adddata(data_feed)
cerebro.broker.setcash(100_000)
cerebro.broker.setcommission(commission=0.003)  # 0.3%
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharpe")
cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown")
cerebro.run()
2. Strategy (your logic)

A Strategy subclass contains all trading logic. Key methods:

  • __init__() — Define indicators. Runs once before backtesting starts.
  • next() — Called on every bar. Place orders here.
  • notify_order(order) — Called when order status changes (submitted, accepted, completed, canceled, margin, expired).
  • notify_trade(trade) — Called when a trade opens or closes. Access P&L here.
python
class EMACrossover(bt.Strategy):
    params = (
        ("fast_period", 10),
        ("slow_period", 30),
    )

    def __init__(self) -> None:
        self.ema_fast = bt.ind.EMA(period=self.p.fast_period)
        self.ema_slow = bt.ind.EMA(period=self.p.slow_period)
        self.crossover = bt.ind.CrossOver(self.ema_fast, self.ema_slow)

    def next(self) -> None:
        if not self.position:
            if self.crossover > 0:
                self.buy()
        elif self.crossover < 0:
            self.close()
3. Data Feed

Backtrader data feeds provide OHLCV lines. The most common approach is loading from a pandas DataFrame:

python
import pandas as pd

df = pd.DataFrame({
    "open": [...], "high": [...], "low": [...],
    "close": [...], "volume": [...],
}, index=pd.DatetimeIndex([...]))

data = bt.feeds.PandasData(dataname=df)
cerebro.adddata(data)

For CSV files:

python
data = bt.feeds.GenericCSVData(
    dataname="ohlcv.csv",
    dtformat="%Y-%m-%d",
    openinterest=-1,  # no open interest column
)
4. Broker

The built-in broker simulates order execution with configurable cash, commission, and slippage.

python
cerebro.broker.setcash(100_000)
cerebro.broker.setcommission(commission=0.003)  # 0.3% per trade

# Cheat-on-open: execute at the open of the signal bar (avoids lookahead)
cerebro.broker.set_coo(True)
5. Analyzers

Analyzers compute performance metrics after the backtest completes.

python
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name="sharpe",
                    riskfreerate=0.0, annualize=True, timeframe=bt.TimeFrame.Days)
cerebro.addanalyzer(bt.analyzers.DrawDown, _name="drawdown")
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name="trades")
cerebro.addanalyzer(bt.analyzers.Returns, _name="returns")

results = cerebro.run()
strat = results[0]

sharpe = strat.analyzers.sharpe.get_analysis()
dd = strat.analyzers.drawdown.get_analysis()
trades = strat.analyzers.trades.get_analysis()

Order Types

Backtrader supports complex order types critical for realistic crypto backtesting.

Market Order
python
self.buy()  # market buy
self.sell()  # market sell
self.close()  # close current position
Limit Order
python
self.buy(exectype=bt.Order.Limit, price=95.0)
self.sell(exectype=bt.Order.Limit, price=105.0)
Stop Order

Triggers a market order when price reaches the stop level:

python
self.sell(exectype=bt.Order.Stop, price=90.0)  # stop loss
Stop-Limit Order

Triggers a limit order when price reaches the stop level:

python
self.buy(exectype=bt.Order.StopLimit, price=100.0, plimit=101.0)
Bracket Order

Entry + stop loss + take profit as an atomic unit. If the stop fills, the take profit is canceled (and vice versa).

python
self.buy_bracket(
    price=100.0,           # entry limit
    stopprice=95.0,        # stop loss
    limitprice=110.0,      # take profit
    exectype=bt.Order.Limit,
    stopexec=bt.Order.Stop,
    limitexec=bt.Order.Limit,
)

See references/strategy_patterns.md for bracket order patterns with ATR-based stops.


Show full SKILL.md (237 more words)Show less

Position Sizing (Sizers)

Sizers determine how many units to buy/sell per order.

python
# Fixed size
cerebro.addsizer(bt.sizers.FixedSize, stake=100)

# Percent of portfolio
cerebro.addsizer(bt.sizers.PercentSizer, percents=95)

# All available cash
cerebro.addsizer(bt.sizers.AllInSizer, percents=95)

Custom sizer:

python
class RiskSizer(bt.Sizer):
    params = (("risk_pct", 0.02),)

    def _getsizing(self, comminfo, cash, data, isbuy):
        risk_amount = cash * self.p.risk_pct
        atr = self.strategy.atr[0]
        if atr <= 0:
            return 0
        size = risk_amount / atr
        return int(size)

Crypto Considerations

24/7 Markets

Crypto trades around the clock. When using daily bars, there are no weekends to skip. Set the session times or use sessionstart/sessionend if analyzing specific windows.

High Fees

DEX swaps on Solana typically cost 0.25-0.30% per trade. Set commission accordingly:

python
cerebro.broker.setcommission(commission=0.003)  # 0.3% round trip per side
Fractional Sizing

Crypto allows fractional units. Backtrader supports this natively -- no special config needed.

Slippage

For realistic simulation, enable cheat-on-open and add slippage:

python
cerebro.broker.set_coo(True)
cerebro.broker.set_slippage_perc(0.001)  # 0.1% slippage
Volatile Data

Crypto OHLCV data often has extreme wicks. Use ATR-based stops rather than fixed percentage stops to adapt to volatility.


Multi-Timeframe

Backtrader can resample data to multiple timeframes within a single strategy:

python
data_1h = bt.feeds.PandasData(dataname=df_1h)
cerebro.adddata(data_1h)

# Resample 1h to daily
cerebro.resampledata(data_1h, timeframe=bt.TimeFrame.Days, compression=1)

Access in strategy:

python
def __init__(self):
    self.ema_1h = bt.ind.EMA(self.datas[0], period=20)    # hourly
    self.ema_daily = bt.ind.EMA(self.datas[1], period=20)  # daily

Custom Indicators

python
class SpreadIndicator(bt.Indicator):
    lines = ("spread", "zscore",)
    params = (("period", 20),)

    def __init__(self):
        mean = bt.ind.SMA(self.data, period=self.p.period)
        std = bt.ind.StdDev(self.data, period=self.p.period)
        self.lines.spread = self.data - mean
        self.lines.zscore = self.lines.spread / std

Plotting

Backtrader includes matplotlib-based plotting:

python
cerebro.plot(style="candlestick", volume=True)

For headless environments, save to file:

python
import matplotlib
matplotlib.use("Agg")
figs = cerebro.plot(style="candlestick")
figs[0][0].savefig("backtest_result.png", dpi=150)

Integration with Other Skills

  • pandas-ta: Compute indicators externally, add as data feed columns. See references/api_guide.md for adding extra lines.
  • trading-visualization: Export trade log from notify_trade and plot with the visualization skill.
  • position-sizing: Use the position-sizing skill for Kelly or volatility-targeting sizers.
  • risk-management: Apply portfolio-level guardrails from the risk-management skill as strategy filters.
  • slippage-modeling: Use slippage estimates from the slippage-modeling skill to configure set_slippage_perc.

Files

References
  • references/api_guide.md — Cerebro, Strategy, Broker, Analyzer, Data Feed API reference
  • references/strategy_patterns.md — Reusable strategy patterns: crossover, mean reversion, multi-timeframe, custom indicators
Scripts
  • scripts/backtest_strategy.py — Complete EMA crossover backtest with analyzers and synthetic data
  • scripts/bracket_orders.py — Bracket order demonstration with RSI entry and ATR-based stops

Quick Start

bash
uv pip install backtrader pandas numpy matplotlib
python scripts/backtest_strategy.py --demo
python scripts/bracket_orders.py --demo

© agiprolabs, MIT. Rendered from Markdown: HTML in the file is shown as text, images as links, and headings moved down two levels. Raw file

Files

SKILL.md and 4 other files (scripts, references) in skills/backtrader of agiprolabs/claude-trading-skills.

  • SKILL.md
  • references/api_guide.md
  • references/strategy_patterns.md
  • scripts/backtest_strategy.py
  • scripts/bracket_orders.py

Open the folder on GitHubat commit 981e1d7

Compare with similar skills

Backtrader next to the 5 skills that share the most tags, products or categories with it. Stars are the repository's; “used in” counts other GitHub owners with a copy.

Backtrader compared with similar skills
SkillStarsUsed inTokensAuto-checkLicenceRepo updated
Backtrader this skillagiprolabs/claude-trading-skills410—~2.4kAutomated safety check: PassMIT
Llmquant StrategiesLLMQuant/skills2291 repos~559Automated safety check: PassMIT
Cryptofeed2025Emma/vibe-coding-cn23k1 repos~1.6kAutomated safety check: PassMIT
Backtestinggauss314/skills246—~2.4kAutomated safety check: PassMIT
Polymarket2025Emma/vibe-coding-cn23k1 repos~1.6kAutomated safety check: PassMIT
Signalsalsk1992/CloddsBot2.9k—~720Automated safety check: PassMIT

Similar skills

  • Llmquant Strategies

    LLMQuant/skills

    Router skill for LLMQuant hedge-fund and PM strategy workflows.

    229 GitHub starsUsed in 1 repo~559 tokens
    Backend & APIsAuto-check passed
  • Cryptofeed

    2025Emma/vibe-coding-cn

    Cryptofeed - Real-time cryptocurrency market data feeds from 40+ exchanges.

    23k GitHub starsUsed in 1 repo~1.6k tokens
    Backend & APIsAuto-check passed
  • Backtesting

    gauss314/skills

    Academic backtesting framework for quantitative research. An agent skill from gauss314/skills.

    246 GitHub stars~2.4k tokensUpdated 3 mo ago
    Business, Finance & HRAuto-check passed
  • Polymarket

    2025Emma/vibe-coding-cn

    Comprehensive Polymarket skill covering prediction markets, API, trading, market data, and real-time WebSocket data streaming.

    23k GitHub starsUsed in 1 repo~1.6k tokens
    Backend & APIsAuto-check passed
  • Signals

    alsk1992/CloddsBot

    Signal trading - RSS, Twitter, Telegram triggers to trades. An agent skill from alsk1992/CloddsBot.

    2.9k GitHub stars~720 tokensUpdated 5 days ago
    Backend & APIsAuto-check passed
  • Verify

    alsk1992/CloddsBot

    Verify agent identity using ERC-8004 on-chain registry. An agent skill from alsk1992/CloddsBot.

    2.9k GitHub stars~1.2k tokensUpdated 5 days ago
    Backend & APIsAuto-check passed

More from agiprolabs/claude-trading-skills

All 68 skills in this repo
  • Birdeye API

    agiprolabs/claude-trading-skills

    Solana token market data via Birdeye — prices, OHLCV, trades, token metadata, security checks, and trader activity

    410 GitHub stars~1.8k tokensUpdated 1 mo ago
    Auto-check passed
  • Coingecko API

    agiprolabs/claude-trading-skills

    Broad crypto market data from CoinGecko covering 13,000+ tokens.

    410 GitHub stars~1.6k tokensUpdated 1 mo ago
    Auto-check passed
  • Cointegration Analysis

    agiprolabs/claude-trading-skills

    Cointegration testing for pairs trading using Engle-Granger, Johansen, and rolling stability analysis

    410 GitHub stars~2.1k tokensUpdated 1 mo ago
    Auto-check passed
  • Copy Trading

    agiprolabs/claude-trading-skills

    Wallet evaluation, monitoring, and copy-trade strategy design for Solana DEX trading

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Correlation Analysis

    agiprolabs/claude-trading-skills

    Cross-asset correlation analysis including rolling correlation, hierarchical clustering, tail dependence, and regime-dependent correlation

    410 GitHub stars~2.4k tokensUpdated 1 mo ago
    Auto-check passed
  • Cost Basis Engine

    agiprolabs/claude-trading-skills

    Multi-method cost basis computation including specific identification, FIFO, LIFO, HIFO, and proportional average cost with partial sell handling

    410 GitHub stars~3.1k tokensUpdated 1 mo ago
    Auto-check passed

Questions about Backtrader

What does Backtrader do?

Event-driven backtesting with bar-by-bar execution, complex order types, multiple analyzers, and custom indicators. Backtrader is an agent skill from agiprolabs/claude-trading-skills.

When should I use Backtrader?

Backtrader fits situations like: tasks that involve Event-driven systems; tasks that involve Trading and backtesting.

How do I install Backtrader in Claude Code?

Run `npx skills add agiprolabs/claude-trading-skills --skill backtrader -a claude-code`. Or copy the skill folder (skills/backtrader in agiprolabs/claude-trading-skills) into .claude/skills/backtrader in your project. Claude Code loads it when a task matches its description.

How do I install Backtrader in Codex?

Run `npx skills add agiprolabs/claude-trading-skills --skill backtrader -a codex`. Or copy the skill folder (skills/backtrader in agiprolabs/claude-trading-skills) into .agents/skills/backtrader in your project. Codex loads it when a task matches its description.

Can I use Backtrader in Cursor, Gemini CLI or GitHub Copilot?

Cursor, Gemini CLI, GitHub Copilot and OpenCode also load SKILL.md folders. With the skills CLI, run `npx skills add agiprolabs/claude-trading-skills --skill backtrader -a cursor` (or -a gemini-cli, github-copilot or opencode for the others). To copy it by hand, put the folder in .cursor/skills/backtrader, .gemini/skills/backtrader, .github/skills/backtrader and .opencode/skills/backtrader in your project.

What does Backtrader need to run?

Going by SKILL.md and its folder, Backtrader needs Python for the scripts in its folder and the command-line tools its instructions call (python and uv). Our summary lists: Python 3.

Does Backtrader access the network?

SKILL.md contains no URLs. Its commands use uv, which can reach the network depending on how they are called. This is read from the text; nothing was executed.

Is Backtrader safe to install?

Our automated static check of SKILL.md found no risky patterns, such as piping downloads into a shell, reading credential files or hidden Unicode. It is not a guarantee. The check reads SKILL.md only: the scripts in the folder are not scanned, so read them before running anything.

What licence does Backtrader use?

Backtrader is published under the MIT licence (the repository's licence). It allows redistribution, so the full SKILL.md is shown on this page.

How many tokens does Backtrader use?

About 2.4k tokens (SKILL.md is roughly 9.8k characters). Agents keep only the skill's name and description in context until a task matches; then they load SKILL.md in full. Its references folder adds about 4k tokens, read only when the agent opens those files.

What are the alternatives to Backtrader?

Skills that share tags, products or a category with Backtrader: Llmquant Strategies (LLMQuant/skills, 229 stars), Cryptofeed (2025Emma/vibe-coding-cn, 23k stars), Backtesting (gauss314/skills, 246 stars) and Polymarket (2025Emma/vibe-coding-cn, 23k stars). The comparison table on this page puts their stars, adoption, token cost, safety result and licence side by side.

Who maintains Backtrader?

agiprolabs (a GitHub user) maintains it in agiprolabs/claude-trading-skills, which has 410 GitHub stars. The repository holds 68 skills in this directory. The repository was last updated on September 3, 2026.

Source: agiprolabs/claude-trading-skills on GitHub. Facts on this page come from the repository at the commit we read; the author's words are quoted as theirs.