Agent Skills
› edtechre/pybroker
› pybroker-strategy-creator
pybroker-strategy-creator
GitHub用于生成、适配和调试 PyBroker 算法交易策略代码。支持回测、参数优化及风险控制,确保无未来函数泄露,提供从需求到可运行代码的完整工作流。
Trigger Scenarios
需要创建或修改 PyBroker 交易策略代码
进行量化策略回测或参数优化
排查 PyBroker 策略中的逻辑错误或数据泄露问题
Install
npx skills add edtechre/pybroker --skill pybroker-strategy-creator -g -y
SKILL.md
Frontmatter
{
"name": "pybroker-strategy-creator",
"description": "Create, adapt, review, and debug PyBroker algorithmic trading strategy and backtest code using the bundled PyBroker wiki references generated from the local docs. Use when an agent needs to turn trading rules into PyBroker Strategy\/ExecContext logic, add indicators, models, stops, ranking, rotation, position sizing, rebalancing, custom data sources, walkforward analysis, bootstrap metrics, parameter optimization, multiple time intervals, slippage modeling, margin trading, parallelization, or dynamic symbol selection, or to answer PyBroker usage questions."
}
PyBroker Strategy Creator
Overview
Create practical PyBroker strategy code from user intent while preserving backtest hygiene, including no lookahead leakage, explicit sizing, clear risk controls, and locally valid PyBroker API usage.
Workflow
- Extract the strategy spec: universe, data source, date range, timeframe, long/short permissions, entry and exit rules, sizing, stops, ranking, rebalancing cadence, model training needs, and desired output file/notebook.
- Ask only for missing blockers. If details are absent but noncritical, make conservative assumptions and state them in the final answer or code comments.
- Read
references/wiki-index.mdto choose the smallest relevant wiki page. For nontrivial strategy work, also readreferences/pybroker-patterns.md. - Build a complete runnable strategy surface:
- start scripts with
pybroker.disable_progress_bar()andpybroker.enable_data_source_cache("<name>") - create a
StrategyConfigwhen cash, fees, delays, exits, margin, or returned signals/stops/positions matter - define indicators with
highest,lowest,returns, the built-in factories inpybroker.indicator(such asatr), orindicatorwith vectorized NumPy/Numba functions - define model sources with
pybroker.modelonly when training or loading predictions is part of the request - write execution functions that use completed-bar arrays such as
ctx.close[-1], guard lookbacks withctx.barsorwarmup, and set at most one order side per symbol per bar - add executions with
Strategy.add_execution, passinghyperparams=when optimization is involved,intervals=for higher-timeframe bars, and.intervals(...)-bound indicators/models for per-interval computation, and cap positions withstrategy.set_max_long_positions/set_max_short_positions - run
backtestfor a single train/test pass,walkforwardfor model/walk-forward evaluation, oroptimizefor hyperparameter search; passtimeframe=whenever an execution declaresintervals=or binds a model/indicator to an interval
- start scripts with
- Validate the produced code as far as the environment allows. At minimum, run syntax checks for created Python files. Run tests or a small local-data backtest when the repo and data make that practical.
Implementation Rules
- Treat PyBroker as a backtesting framework, not a source of financial advice. Make strategy assumptions explicit and avoid performance claims that are not supported by the produced backtest.
- Use completed historical bar data only. Do not use future prices, future indicator values, or shuffled time series unless explicitly doing a model training split that PyBroker supports. An indicator value at bar
imay depend only on inputs at indexiand earlier: no backward shifts such asshift(-1), and no negative indexing into full-length arrays inside indicator functions (a negative index silently wraps to the end of the series — the future). - Start generated scripts with
pybroker.disable_progress_bar()so backtest progress output does not flood agent context, andpybroker.enable_data_source_cache("<strategy_name>")(orpybroker.enable_caches) so repeated runs do not refetch data. Addpybroker.disable_logging()when running many backtests, such as parameter optimization. - Report
result.metrics_dfas the human-readable summary. When structured output is needed (agent parsing, saved report files, downstream tools), useresult.to_json()/result.to_json_str(): the default payload serializes metrics, trades, orders, and bootstrap capped atmax_rows=100rows per table,symbols=filters to specific tickers, andinclude=opts intoportfolio/positions/metrics_df/signals/stops(positionsneedsStrategyConfig(record_position_bars=True)). Do not replace themetrics_dfprint outright: the default JSON payload (trades plus orders) is usually larger than the metrics table. - Never use pandas to implement indicator or execution logic.
BarDataandExecContextprice fields are NumPy arrays: operate on them directly, prefer the vectorized helpers (highv,lowv,sumv,returnv,cross,atr) when they fit, and JIT-compile explicit loops with Numba@njit. Never construct apd.Seriesorpd.DataFrameand never call pandas methods such as.rolling,.ewm,.shift, or.applyinside an indicator function or a per-bar execution function. - If a Numba
@njitfunction fails to compile or raises a cryptic error such as aTypingError, re-run once with theNUMBA_DISABLE_JIT=1environment variable to get a readable Python traceback, fix the underlying code, then remove the variable so the backtest runs compiled. - Self-test novel indicator logic for lookahead with the bump-last-bar check in
references/pybroker-patterns.md: recompute after changing only the final input bar and assert every earlier output is unchanged. - Use
ctx.calc_target_shares(target_size)for allocation-based sizing andctx.set_target_shares(target, dir="long")to rebalance toward a target allocation. Use fixedctx.buy_sharesorctx.sell_sharesonly when the user asks for fixed share sizing. - Check
ctx.long_pos()orctx.short_pos()before entering or exiting positions. Usectx.sell_all_shares()andctx.cover_all_shares()for full exits. - Set entry-time stops on the same bar as the entry order:
hold_bars,stop_loss_pct,stop_profit_pct, orstop_trailing_pct. - Orders fill at
PriceType.MIDDLE— the midpoint of the low and high of the execution bar, which under the defaultbuy_delay/sell_delayof1is the bar after the signal, soPriceType.CLOSEmeans the next bar's close. Override withctx.buy_fill_price/ctx.sell_fill_price, which take aPriceType(OPEN,HIGH,LOW,CLOSE,MIDDLE,AVERAGE), a number, or a(symbol, bar_data)callable, and read back asNonerather thanMIDDLEuntil set. A limit price only gates the fill: the order still fills at the fill price, never at the limit, soctx.buy_limit_price = 200against a midpoint of108books108. StrategyConfig.exit_on_last_bardefaults toFalse, which leaves any position still open when the data ends. That position never becomes aTrade, sotrade_count,win_rate,total_pnland every other trade-level metric silently exclude it while its P&L sits inunrealized_pnl. Setexit_on_last_bar=Truewhenever trade statistics are reported; exits fill atexit_sell_fill_price/exit_cover_fill_price, bothPriceType.MIDDLE, and inwalkforwardthe liquidation fires only on each symbol's true final bar, never at window boundaries. Bar-level metrics (sharpe,max_drawdown) are computed from per-bar market value and barely move either way.calc_bootstrapis abacktest/walkforward/optimizeparameter defaulting toFalse, not aStrategyConfigfield. Passcalc_bootstrap=Trueto populateresult.bootstrapwithconf_intervals(BCa — bias corrected and accelerated — intervals for profit factor and Sharpe; 6x2, MultiIndexed onnamethenconf, columnslower/upper) anddrawdown_conf(percentile bounds on max drawdown; 4x2, indexed onconf, columnsamount/percent). It leavesmetrics_dfunchanged, costs roughlybars x StrategyConfig.bootstrap_samples(default10_000, so lower it on intraday data), and needsStrategyConfig.bars_per_yearor the Sharpe intervals are per-bar rather than annualized.- Rank symbols with
ctx.long_scoreandctx.short_scoreand cap positions withstrategy.set_max_long_positions(n)/strategy.set_max_short_positions(n); theStrategyConfigfields of the same names are deprecated. Scores rank descending on both sides: short orders go to the symbols with the highestshort_score, so negate a lowest-wins short signal (for examplectx.short_score = -rocto short the most negative momentum). For rank-and-rotate portfolios callstrategy.enable_rotation(worst_rank_held=...); rotation is exclusive, so execution functions then only set scores and any order fields they set are ignored. - For parameter search, register values with
pybroker.hyperparam(name, default=..., low=..., high=..., step=...), attach them via indicator kwargs oradd_execution(..., hyperparams=[...]), read them withctx.hyperparam("name"), and runstrategy.optimize(score_fn, sampler="grid")(or"tpe"/"random"withn_trials=). Optimization does not support trainable models; use pretrained models or indicator-based rules. - For multi-timeframe logic, declare
add_execution(..., intervals="weekly")and read compressed bars withctx.interval("weekly").intervals=provides bars only; to compute an indicator or train a model per interval, bind it withindicator.intervals("weekly")/model_source.intervals("weekly")inindicators=/models=— bound intervals are available throughctx.intervalwithout declaring them again. Binding is exhaustive: include"base"(e.g..intervals("base", "weekly")) to keep the base-timeframe variant; unbound sources default to base. When any execution declares or binds intervals,backtest/walkforwardrequiretimeframe=for the base data. - Model trading costs with
strategy.set_slippage_model(...):FixedSlippageModel(bps=...)for constant costs,VolatilitySlippageModelfor ATR-scaled slippage,VolumeSlippageModelfor volume-capped fills. Only enable margin (StrategyConfig(leverage=..., interest_rate=...), which requiresbars_per_year) when the user asks for it. result.positionsis empty unlessStrategyConfig(record_position_bars=True); enable it only when the user needs per-bar position output. The per-barresult.portfolioequity curve is always populated.- Use
strategy.set_before_execorstrategy.set_after_execfor cross-symbol portfolio logic instead of hiding global state inside a per-symbol execution function. - Optional packages are not PyBroker dependencies: name the required
pip installfor any data source or library the script imports (for examplepip install yfinanceforYFinance) and never assume one is importable. When the network or a data-source package is unavailable, validate with a tiny local DataFrame passed toStrategyinstead. - If exact API names, constructor parameters, or methods matter, read
references/api-public-surface.md. - For exact type signatures — the writable
ExecContextorder/stop attributes, property and parameter types, enum members — read the matchingreferences/pybroker_*.pyistub (pybroker_context.pyiforExecContextand slippage). - If the user wants a standalone file, copy and adapt
assets/strategy_template.py.
Common Deliverables
- Standalone
.pybacktest script. - Notebook-ready PyBroker cells.
- Refactor of an existing strategy file.
- Debugging notes and patches for invalid
ExecContextusage. - Focused tests using local DataFrame data when live data sources are unavailable.
Resources
references/wiki-index.md: start here for topic routing across the bundled PyBroker wiki.references/wiki-01-getting-started-with-data-sources.md: Yahoo Finance, Alpaca, Alpaca Crypto, AKShare, data caching, and data source setup.references/wiki-02-backtesting-a-strategy.md: defining execution rules, adding executions, running backtests, and filtering data.references/wiki-03-evaluating-with-bootstrap-metrics.md: evaluation metrics, confidence intervals, bootstrap metrics, and drawdown.references/wiki-04-ranking-long-and-short-signals.md: ranking long/short signals by score and max positions.references/wiki-05-writing-indicators.md: custom indicators, vector helpers, TA-Lib, built-in indicators, and indicator sets.references/wiki-06-training-a-model.md: model training, model predictions, caching, and walkforward analysis.references/wiki-07-creating-a-custom-data-source.md: extendingDataSource, DataFrame inputs, CSV inputs, and custom columns.references/wiki-08-applying-stops.md: stop loss, take profit, trailing stops, limit prices, stop exit prices, and stop cancellation.references/wiki-09-rebalancing-positions.md: equal weighting, before/after execution hooks, and portfolio optimization.references/wiki-10-rotational-trading.md: rotational strategy examples, universe rotation, and custom position sizing.references/wiki-11-configuring-parallelization.md: worker counts, parallel indicators and model training, and the Ray backend.references/wiki-12-parameter-optimization.md: hyperparams, grid/TPE/random samplers, and walkforward optimization.references/wiki-13-margin-trading.md: leverage, buying power, margin interest, and shorting on margin.references/wiki-14-modeling-slippage.md: fixed, volatility, and volume slippage models plus custom slippage.references/wiki-15-multiple-time-intervals.md: interval types, compressing bars, and multi-timeframe strategies.references/wiki-16-time-series-models.md: GARCH volatility forecasting and models on lagged returns.references/wiki-17-multi-symbol-models.md: pooled models trained across multiple symbols.references/wiki-18-dynamic-symbol-selection.md:SymbolSelectorand per-window universe selection.references/wiki-faqs.md: common PyBroker usage questions and edge cases.references/api-public-surface.md: generated public API signatures and first docstring sentences from local source.references/pybroker_context.pyi: generated type stubs forExecContext(including its writable order/stop attributes),IntervalContext,RotationContext,ExecResult, and the slippage models.references/pybroker_strategy.pyi: generated type stubs forStrategy,StrategyConfig,TestResult, and the optimization types.references/pybroker_types.pyi: generated type stubs for enums,BarData,Portfolio, order/trade/position records, and evaluation result types.references/pybroker_model.pyi: generated type stubs formodel(),indicator(), vector helpers, data sources, and top-level module functions.references/pybroker-patterns.md: load when writing nontrivial strategy code, debugging PyBroker API usage, or adding indicators, stops, models, ranking, rebalancing, or walkforward analysis.assets/strategy_template.py: copy and adapt when creating a new standalone strategy script.
Version History
- db53c67 Current 2026-08-20 08:27


