К основному содержанию
скилл CX Codex

manifoldbt-backtester — скилл для Claude Code: бэктест стратегий

Прогоняет декларативное описание стратегии по OHLCV-барам через движок manifoldbt и отдаёт восемь метрик для оценки.

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add tradermonty/claude-trading-skills --skill manifoldbt-backtester -a claude-code
Открыть на GitHub

Что делает manifoldbt-backtester

Скилл берёт спеку стратегии в JSON, прогоняет её по реальным барам и превращает лог сделок в завершённые round trips. На выходе — восемь входных значений, которые ждёт скилл backtest-expert: число сделок, win rate, средний выигрыш, средний проигрыш, максимальная просадка и остальное. Цепочка односторонняя: спека, прогон, оценка. Вердикт выносит backtest-expert, здесь только измерения.

Внутри четыре скрипта. scripts/spec.py проверяет спеку и считает параметры, scripts/run_backtest.py запускает прогон, scripts/round_trips.py сводит исполнения в пары, scripts/bridge.py собирает входы для оценщика. Три из них работают без движка, поэтому логику можно проверить отдельно. Нужен Python 3.9+ и pip install manifoldbt; ключ API не требуется. Бары подаются как CSV или Parquet с колонками timestamp, open, high, low, close, volume.

Спектр узкий намеренно: sma, ema, rsi, одно условие входа, опциональные стоп-лосс и тейк-профит, комиссии и проскальзывание в базисных пунктах, только лонги. Мультиусловные входы, шорты и мультиассетные вселенные скилл отклоняет, хотя движок это умеет. Ставьте fees_bps и slippage_bps в реалистичные значения до того, как смотреть на результат: прогон без трения получает ноль за реализм исполнения, а на коротких удержаниях именно издержки решают, выживает ли преимущество.

Какие задачи решает

  • измерить описанное словами правило на реальных барах
  • получить win rate, средний выигрыш и просадку до запуска оценщика
  • свести лог исполнений в завершённые round trips с чистой доходностью
  • посчитать число параметров стратегии для скоринга
  • проверить логику моста метрик без запуска движка

Примеры запросов агенту

  • прогони спеку strategy.json по bars.csv для BTCUSDT и сохрани результат в result.json
  • посчитай round trips по логу сделок и отдай восемь входов для backtest-expert
  • проверь спеку и скажи, сколько в ней параметров

Как установить manifoldbt-backtester

1Через Skills CLI (Vercel)

npx skills add tradermonty/claude-trading-skills --skill manifoldbt-backtester -a claude-code

2Вручную: положить файлы

~/.claude/skills/manifoldbt-backtester/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/manifoldbt-backtester/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о manifoldbt-backtester

Как установить manifoldbt-backtester в Claude?

Выполните npx skills add tradermonty/claude-trading-skills --skill manifoldbt-backtester -a claude-code. Скилл появится в ~/.claude/skills/manifoldbt-backtester/SKILL.md.

Что делает manifoldbt-backtester?

Прогоняет декларативную спеку стратегии по OHLCV-барам через движок manifoldbt, сводит исполнения в round trips и выдаёт восемь входных значений, которые оценивает скилл backtest-expert.

Что нужно для работы скилла?

Python 3.9+, пакет manifoldbt и бары в CSV или Parquet с колонками timestamp, open, high, low, close, volume. Ключ API не нужен.

Исходный текст

SKILL.md · MIT
---
name: manifoldbt-backtester
description: Runs a declarative strategy spec over OHLCV bars with the manifoldbt Rust engine, pairs the fill log into round trips, and emits the eight inputs the backtest-expert skill scores. Use when the user wants to execute a backtest, measure a rule they have described, obtain win rate / average win / average loss / max drawdown from real bars, or feed backtest-expert with measured numbers instead of estimates.
---

# manifoldbt Backtester Skill

## Purpose

Execute what `backtest-expert` teaches. That skill grades a backtest on five
dimensions, and its prerequisites say "metrics are user-provided": it scores
numbers it never produces. This skill produces them. It runs a strategy over
real bars and returns the eight inputs its evaluator asks for.

The two chain in one direction: spec, run, evaluate.

## When to Use This Skill

- A user describes a rule and wants it measured
- `backtest-expert` is about to run and the numbers do not exist yet
- A win rate, average winner, average loser or drawdown must come from bars
- A strategy's parameter count must be established for scoring

Leave the verdict to `backtest-expert`. It owns the thresholds and the red
flags, and this skill does not duplicate them.

## Prerequisites

- Python 3.9+
- `pip install manifoldbt` (Apache 2.0 with Commons Clause; the free tier covers
  everything this skill does)
- OHLCV bars as CSV or Parquet with columns `timestamp, open, high, low, close, volume`
- No API key required

## Workflow

### 1. Write the strategy spec

A spec names indicators and one entry condition. Keep it to the smallest rule
that states the hypothesis. Every added knob makes an in-sample fit easier to
reach by accident, and the evaluator penalises the count.

```json
{
  "name": "sma_cross_costed",
  "indicators": {
    "fast": { "type": "sma", "period": 20 },
    "slow": { "type": "sma", "period": 60 }
  },
  "entry": { "left": "fast", "op": ">", "right": "slow" },
  "size": 1.0,
  "stop_loss_pct": 1.5,
  "fees_bps": 5.0,
  "slippage_bps": 2.0
}
```

Field reference: `references/strategy_spec.md`.

Set `fees_bps` and `slippage_bps` to realistic values before you read any
result. A frictionless run scores 0 on execution realism, and over short holding
periods costs decide whether an edge survives.

### 2. Run it

```bash
python3 scripts/run_backtest.py \
  --spec strategy.json \
  --data bars.csv \
  --symbol BTCUSDT \
  --json-out result.json
```

The script validates the spec before it touches the data, so you see a spec
mistake in a second instead of after a long load.

### 3. Read the warnings before the numbers

The run prints warnings that change how you should read the result: a sample
under 30 trades, a span under a year, no friction modelled, or a gap between the
engine's win rate and the paired one. Each one is a reason to fix the setup and
run again.

Three conditions stop the handoff instead of producing a score: no completed
round trips, missing or non-finite maximum drawdown, and scratch trades. The
evaluator has no scratch input, so passing a population that contains them would
make its derived expectancy disagree with the completed trades.

### 4. Hand off to backtest-expert

The run ends with a command you can paste. Run it, or invoke the
`backtest-expert` skill with the same figures:

```bash
python3 skills/backtest-expert/scripts/evaluate_backtest.py \
  --total-trades 3854 --win-rate 20.24 \
  --avg-win-pct 0.2917 --avg-loss-pct 0.2342 \
  --max-drawdown-pct 99.2893 --years-tested 0 \
  --num-parameters 3 --slippage-tested
```

## Four conversions that fail without an error

Between an engine's output and the evaluator's inputs sit four conversions. Each
one yields a plausible number and scores the strategy wrongly. None of them
raises.

**A fill is one execution, a round trip is two.** The raw trade count runs at
about twice the number of round trips. Feed fills to the sample-size dimension
and you double the apparent sample, which can lift a thin backtest over a
threshold it should not clear.

**Buy and sell alternate only in the simplest case.** That holds for a
single-symbol long-only strategy that never scales a position. Shorting breaks
it, because a sell can open. Scaling breaks it, because one exit answers several
entries. A universe breaks it, because fills interleave. This skill tracks
position per symbol and closes a trip when it crosses back through flat. Entry
and exit quantities and cash values accumulate across that whole lifecycle;
their weighted-average prices are display values, while PnL comes from the cash
flows themselves.

**Costs decide small trades.** At 7 bps a side, a trade that gains 0.1% on price
loses money. Expectancy comes from the win rate and the average winner together,
so a gross win rate beside net averages misstates the edge. Percentages here are
net of fees, and `gross_return_pct` sits alongside for inspection.

**The engine signs drawdown negative.** The evaluator wants a positive
magnitude. Pass the raw value and a 38% fall scores as a flawless run.

## Scope

Supported: `sma`, `ema`, `rsi` over any OHLC column; one entry condition using
`>`, `<`, `>=`, `<=` against another indicator, a price column or a number;
optional stop-loss and take-profit; fees and slippage in basis points;
long-only.

Refused: multi-condition entries, shorting, multi-asset universes, and
indicators outside the three above. The engine does all of these. This skill
covers the shapes a one-sentence hypothesis produces, and rejects the rest
instead of half-handling it.

## Reference Files

- `references/strategy_spec.md` covers every spec field, its default, and what
  validation refuses
- `references/metric_bridge.md` covers the eight inputs, how each is derived,
  and the trap in each conversion

## Scripts

- `scripts/run_backtest.py` runs a spec against bars
- `scripts/spec.py` validates a spec and counts its parameters
- `scripts/round_trips.py` pairs fills into round trips with net returns
- `scripts/bridge.py` assembles the evaluator's eight inputs

`spec.py`, `round_trips.py` and `bridge.py` carry no dependencies and import
without the engine, so you can test the logic without running a backtest.

© tradermonty · MIT · tradermonty/claude-trading-skills

Похожие скиллы

Всё по теме «Финансы и бизнес» →
pine-backtester TradersPost Добавляет в индикаторы и стратегии Pine Script расчёт метрик доходности, просадок и статистические тесты. Помогает проверить торговые алгоритмы перед запуском. CX Codex +1 437установок strategy-framework agiprolabs Задаёт единый шаблон описания торговой стратегии: правила входа и выхода, размер позиции, риск-лимиты и критерии оценки. Пригодится, когда идея есть, а записать её нечем. CX Codex +1 500установок optimize marketcalls Генерирует Python-скрипты для перебора параметров торговых стратегий на VectorBT, строит тепловые карты Plotly и сверяет результаты с бенчмарком NIFTY. CX Codex +1 2 300установок trading-strategies agentmc15 Скилл для проектирования и тестирования торговых стратегий на рынках предсказаний. Помогает рассчитывать сигналы арбитража, импульса и возврата к среднему на Python. CX Codex +1 1 200установок walk-forward-validation agiprolabs Скилл настраивает валидацию торговых стратегий и ML-моделей на временных рядах. Помогает избежать заглядывания в будущее и оценить переобучение алгоритмов. CX Codex +1 703установок quant-analyst Seth Hobson Субагент настраивает алгоритмические торговые стратегии, рассчитывает риск-метрики и проводит бэктесты. Помогает подготовить финансовые модели на Python. CX Codex 1 366установок

Из того же набора73

stockbee-episodic-pivot-analyzer Оценивает акции на паттерн Episodic Pivot по методике Stockbee. Сопоставляет силу корпоративных новостей со всплеском объёма и дневным ценовым импульсом. CX Codex +1 2 600установок fxmacrodata-calendar Тянет официальные даты релизов макроданных из FXMacroData, чтобы планировать сделки и не входить в рынок перед CPI или решением центробанка. CX Codex +1 2 500установок contrarian-setup-gate Скилл объединяет отчёты по позиционированию COT, реакции на новости и ценовому подтверждению в единый статус сделки. Пригодится перед расчётом размера позиции в торговом пайплайне. CX Codex +1 2 500установок news-reaction-failure-analyzer Проверяет, не проигнорировал ли рынок новости, выгодные переполненной спекулятивной позиции. Это второй этап контртрендового процесса по COT. CX Codex +1 2 500установок cot-contrarian-detector Скрипт проходит по фьючерсным рынкам CFTC и ищет, где крупные спекулянты столпились на одной стороне. Пригодится, когда нужен повод копать в сторону контртрендовой сделки. CX Codex +1 2 500установок futures-position-sizer Скилл рассчитывает размер позиции по фьючерсам на основе точки входа, стоп-лосса и риск-бюджета с учётом спецификаций контракта. Работает локально через Python без ключей API. CX Codex +1 2 500установок residual-edge-analyzer Скилл отделяет доходность торговой стратегии от базовых рыночных факторов через регрессию OLS. Он помогает проверить наличие реальной альфы после бэктеста. CX Codex +1 2 400установок us-undervalued-growth-screener Ищет недооценённые растущие компании на NYSE, Nasdaq и NYSE American и доводит отбор до ранжированного отчёта с аудитом. CX Codex +1 1 600установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой