Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

polars-backtest

БесплатноБез исполняемых скриптовНе проверен

Backtest trading strategies with the polars-backtest library (Rust-powered Polars extension, Finlab-compatible). Use when the user asks about backtesting…

Yvictorот Yvictor★ 19 звёзд на GitHub11 установок в других каталогах

Об этом скилле

polars-backtest

High-performance portfolio backtesting for Polars long-format DataFrames. Rust core, Finlab-compatible semantics (parity ~2e-16), T+1 execution.

pip install polars-backtest    # or: uv add polars-backtest

Reference files — read when needed

File When to read
references/api.md Full parameter reference, BacktestReport surface, trades schema, wide-format API, plugin expressions
references/execution-semantics.md Exact timing/price/fee/stop mechanics — read before answering "when does it trade / at what price / how are fees applied"
references/finlab-migration.md Porting finlab sim() code; param and Report mapping; unsupported params
references/recipes.md Data prep, top-N ranking, masks, long/short, sweeps, live-trading actions

Data requirements

Long format: one row per (date, symbol). Required columns (names remappable via parameters, values can also be pl.Expr):

Column Dtype Notes
date pl.Date preferred (ISO strings accepted) Sort by date; unsorted input is auto-sorted but slower
symbol str
close (= trade_at_price) Float64 Use adjusted prices; NaN/≤0 treated as invalid
weight (= position) Boolean or Float64 Bool → equal weights among True. Float → Finlab normalization. Nulls auto-filled with False/0.0

Optional columns picked up when present / when features need them:

  • factor — adjustment factor, raw_price = adj_price / factor. Missing column silently means factor=1.0.
  • open, high, low — required only when touched_exit=True.
  • limit_up, limit_down, trading_value — enable liquidity metrics (buyHigh, sellLow, capacity). Column names are configurable via the limit_up/limit_down/trading_value parameters of backtest_with_report.

Quick start

import polars as pl
import polars_backtest as pl_bt   # registers the df.bt namespace

# Boolean signal -> equal-weight portfolio, monthly rebalance
df = df.with_columns(
    (pl.col("close") >= pl.col("close").rolling_max(60).over("symbol"))
    .alias("weight")
)

report = df.bt.backtest_with_report(position="weight", resample="M")
report.stats          # 1-row DataFrame: total_return, cagr, max_drawdown, daily_sharpe, ...
report.creturn        # DataFrame [date, creturn]
report.trades         # per-trade records with mae/gmfe/bmfe/mdd/pdays

# Equity curve only (faster, for optimization loops)
curve = df.bt.backtest(position="weight", resample="M")   # DataFrame [date, creturn]

# Function form is identical: pl_bt.backtest(df, ...) / pl_bt.backtest_with_report(df, ...)

Parameters at a glance

Exact signature — see references/api.md for full semantics.

Parameter Default Meaning
trade_at_price "close" Price column/Expr for valuation and execution
position "weight" Weight column/Expr (bool signals or float weights)
date, symbol "date", "symbol" Column names/Exprs
open, high, low "open"… Used only with touched_exit=True
factor "factor" str only; raw = adj / factor; missing → 1.0
resample "D" None, D, W, W-MON…W-SUN, M, ME, Q, QE, Y, YE, A. MS/QS raise ValueError (no start-of-period support). None = trade only on position change
resample_offset None Delay rebalance by calendar days: "1d", "2d", "1W". Non-negative only; bad strings silently ignored
fee_ratio 0.001425 Fee on buy AND sell notional (TW default)
tax_ratio 0.003 Tax on sell side only (TW default)
stop_loss 1.0 = off Positive fraction: 0.1 exits at −10%
take_profit inf = off 0.2 exits at +20%
trail_stop inf = off 0.08 exits 0.08 below peak cr since entry
touched_exit False Intraday OHLC stop detection, same-day exit at the stop level
stop_trading_next_period True Stopped stock excluded from the next rebalance
position_limit 1.0 Max weight per stock (clip; float-weight excess → cash)
retain_cost_when_rebalance False True: stops keep measuring from original entry across rebalances
benchmark (report only) None Symbol string in your data, or DataFrame with date+creturn → enables alpha/beta/m12WinRate
limit_up, limit_down (report only) "limit_up", "limit_down" Raw limit-price columns for liquidity metrics

Execution model (the 20-second version)

Full mechanics: references/execution-semantics.md.

  • T+1: a signal on date T trades on the next trading day at that day's trade_at_price. No same-bar fills. Last-date signals become pending trades (null entry_date/exit_date in report.trades).
  • **Delta tradi
Полный SKILL.md на GitHub

Установить polars-backtest в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

references/api.mdreferences/execution-semantics.mdreferences/finlab-migration.mdreferences/recipes.md

FAQ

Что делает скилл polars-backtest?

Backtest trading strategies with the polars-backtest library (Rust-powered Polars extension, Finlab-compatible). Use when the user asks about backtesting, portfolio simulation, trading strategy evaluation, stop loss/take profit simulation, rebalancing, migrating from finlab, or anything involving polars_backtest / df.bt. 使用 polars-backtest 回測交易策略。當使用者提到回測、投資組合模擬、策略績效評估、停損停利、再平衡、finlab 遷移或 polars_backtest 時使用。

Как установить скилл polars-backtest?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл polars-backtest запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

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

Сравнить polars-backtest с