nstung463/kimi-agent-skills/trading-strategy-backtest
Claude Code and agent skill by nstung463/kimi-agent-skills
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"},{"type":"plugin","description":"Custom plugin integration"}]
Checking that the SKILL.md file is still in the repository.
将「投资交易策略描述」(含事件驱动、选股、组合)转成可运行的「回测代码」,输出回测结果、可视化图表和分析报告。当用户描述买卖条件、事件后收益、股票池筛选回测等量化场景时触发。
Install
npx vskill@latest install nstung463/kimi-agent-skills/trading-strategy-backtestSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as serejaris/kimi-skills/trading-strategy-backtest.
Quick Strategy Backtest
IMPORTANT: Output-Language Lock
- The final conversation reply and every deliverable (dashboard / charts / tables / custom_html) must follow the language of the user's latest query, not the market; if the user explicitly requests a language, follow that request
- Decide a single
output_language = "zh" | "en"first, and route every user-visible string through it; when generating the dashboard, passbuild_dashboard_data(..., language=output_language)explicitly - If the prompt is in English and the symbols are China / Hong Kong stocks, both the reply and the deliverables must stay in English; stock references should default to ticker code such as
600519.SH/0700.HK - If the prompt is in Chinese, both the reply and the deliverables must stay in Chinese; when a Chinese stock name is known, prefer the Chinese name
- "Deliverables" covers every user-visible field; commonly missed ones include
strategy_name(dashboard top title — always pass it), module title / subtitle,trades_tablecolumn labels,textmodule body, and matplotlib titles — all followoutput_language. - Do not make this mistake: the HTML is in English but the actual conversation reply switches back to Chinese
- If the English stock name is uncertain, use the ticker code instead of a Chinese stock name
IMPORTANT: Reproducible Script and Accounting Semantics
- A `.py` script is mandatory: strategy backtests must write the implementation to a
.pyfile in cwd and generate results by runningpython <script>.py; do not complete the backtest only through a temporary one-off shell snippet - Self-designed strategies: plan before implementing: when the user asks the agent to "design / find / optimize a strategy" itself, you must first write an internal strategy plan (signals, entry/exit conditions, execution timing, sizing, costs, whether scaling in / partial exits are allowed, multi-symbol vs event study). Then route through the skill, read the relevant reference files, and revise the plan. Only after the plan passes look-ahead, warm-up, accounting, export, and dashboard checks are you allowed to write code
- Default
position_accounting="lot_level": every buy usesbuy_lotto create an independent lot (withlot_id), every sell usesclose_lots_fifo(FIFO). With the default flat-only entry gate and full-exit semantics, the lot count is always ≤ 1 andtrades.csvrows = full open-close cycles; scaling / grid / rotation strategies get per-lot attribution for free - Mandatory long-only rules: pure-Python cash equity / ETF backtests default to long-only lot-level accounting. Buy / sell / equity calculations must call
buy_lot / close_lots_fifo / close_lot / compute_lot_equityfromreference.accounting.export_results(position_accounting="lot_level")is only an export-time validator; it does not recompute FIFO, cash, fees, or PnL for you - Long-only helper responsibilities:
buy_lotcreates an independent long lot and deducts entry cost;close_lots_fifosells one or more long lots by FIFO and returns closed-trade records;close_lotfully or partially closes one specified long lot for grid / LIFO / custom matching;compute_lot_equitymarks cash plus open long lots to current equity - Sizing responsibility:
buy_lot/buy_average_costare not sizing helpers; they only execute the providedsizeand validate cash. Before calling them, compute an affordable round-lotsizefrom availablecash, fill price, commissions, andlot_size. For fixed-cash scale-ins, cap the target cash at available cash (for exampletarget_cash = min(lot_cash, cash)); after round-lot flooring, skip or record ignored whensize <= 0instead of usinginsufficient cashas normal control flow - Short / leverage routing: if a strategy includes shorting, margin buys, securities lending, margin requirements, negative cash, borrow fees, or financing interest, do not expand the details in
SKILL.md; readreference/short_leverage_routes.md - Flat-position entry gate (default hard rule): every buy execution block must be guarded by a flat-position condition (
position == 0/not open_lots/ current weight is 0); repeated buy signals while holding may only increment ignored counters and must not change cash / position / open_lots. Add a runtime assert in code: storeprior_positionbefore the buy block andassert not (prior_position > 0 and buy_executed)after it. Strategies that allow scaling (user prompt contains "add-on / scale in / every signal buys / grid / staged entry / overlapping events") may relax this gate - Opt in to
position_accounting="aggregate_average_cost"(usebuy_average_cost / sell_average_cost, nolot_id) only when the user explicitly asks for "per-trade PnL on average cost" / "alignment with broker statement cost basis" / "pure DCA where every entry is interchangeable". Otherwise stay onlot_level - Strategy backtest export must call
export_results(..., is_flat_at_end=True, position_accounting="lot_level"|"aggregate_average_cost", ...); the export layer rejects missing period-end flat confirmation,lot_leveltrades withoutlot_id, oraggregate_average_costtrades that containlot_id
Trigger Conditions
Trigger this skill when any of the following is true:
- The user asks for a backtest
- The user provides quantitative descriptions such as entry/exit rules, symbols, frequency, or time range
- The user asks for backtest metrics or a report
- The user describes an event / signal / condition and wants to know the subsequent performance. Typical phrasing:
- "Buy after XX and hold for N days; how did it perform?"
- "What was the return after event XX?"
- "After the signal triggers, hold N days and sell"
- "Run an event study"
- "Is this strategy effective?"
- "Screen stocks that satisfy XX and check later performance"
- The user wants multi-symbol stock-selection backtests or portfolio rebalancing
Out of Scope
- Intraday / minute / tick backtesting: this skill only supports daily or lower-frequency data (daily, weekly, monthly). If the user asks for minute bars, 5-minute bars, ticks, and so on, state directly that it is unsupported
- Futures / options / perpetuals / convertible bonds and other derivatives: the accounting helpers only cover cash equity / ETF; margin, contract multipliers, daily mark-to-market, and rollover are out of scope — state directly that it is unsupported
- Short selling / leverage / margin financing: still in beta, temporarily unsupported; only cash long positions are covered today, and securities borrowing, margin maintenance, liquidation, and leverage ratios are not handled
- Full cross-sectional factor stock-selection strategies
User-Facing Communication Rules
During clarification and in the final reply, do not expose code variable names, implementation details, or framework jargon. Everything should be communicated in natural language:
- ❌ "Use pandas rolling to compute MA120"
- ✅ "Calculated the 120-day moving average"
- ❌ "Signal is generated on bar i and executed on bar i+1"
- ✅ "After the signal is confirmed, buy at the next day's open"
- ❌ "A-share T+1 is enforced by entry_bar"
- ✅ "In A shares, you cannot sell on the same day you buy; the earliest sell is the next day"
Implementation details are internal. They must never appear in user-facing text (clarification or result interpretation).
Decide First: Do You Need Clarification?
Principle: only ask questions that are truly necessary to avoid being wrong. Do not dump eight questions on the user at once. Use defaults whenever that is safe. Keep clarification to 1-3 questions.
Clarification Gate (hard rule): before writing code, running a backtest, exporting CSV/JSON, or generating HTML, pass this section first. If any "Must Ask" item applies and the user has not answered it, stop and ask 1-3 short questions; do not guess with defaults or implement a "probably right" version first. User phrases like "you decide" or "use defaults" do not override questions that would otherwise make the result wrong. If no Must Ask item applies, continue the quick flow and disclose any defaults in the final reply.
Must Ask (Wrong if You Don't)
If the information below is missing, the result can change completely. Do not guess; ask.
- Signal definition is ambiguous: the user says "breakout", "volume surge", or "uptrend". Is this a point-in-time event (the instant of crossing) or a persistent state? Without clarification, the generated strategy may be fundamentally different
- Lifecycle is unclear: the prompt says "first", "first buy point", or "buy again on the next golden cross" but does not define reset conditions. Is the event one-time only, or repeatable?
- Compound-exit semantics are unclear: entry is A and B and C, but the user only says "exit on reverse signal". Does "reverse" mean the full mirror condition, or only one sub-condition?
Should Ask (Ask if Ambiguous; Otherwise Use Defaults)
- Backtest range — ask if the user did not specify one; if they say "last three years", it can be inferred
- Position sizing — for single-symbol strategy backtests, default to full position and disclose it; for multi-symbol / portfolio tasks, clarify or ask about weights. If the user mentions "partial allocation", "10%", etc., confirm the actual number
- Execution timing — default is next-day open; if the user says "buy the same day", ask whether that means same-day close or next-day open
Use Defaults Directly (Do Not Ask)
- Fees / slippage: 3 bps for continuous strategies; 0 for event-study style setups
- Data frequency: daily
- T+1 / lot size: enabled automatically for A shares
- Dashboard: generate by default
If the task involves multiple strategies / multiple symbols (priority vs secondary, rotation, hedging, switching), immediately read the "Multi-Strategy Interaction" section in `reference/strategy_parsing.md` and check priority, preemption, switching timing, and ownership of constraints item by item. If any answer is unclear, ask the user.
Look-ahead judgment principle: do not rely only on fixed keywords. The key question is whether an order, rebalance, selection, stop-loss, take-profit, or size decision uses information that was not available at that decision time. Future returns may be used as an outcome variable in event studies, but not as the event trigger / selection / sizing / risk-control condition. The next bar's open may be used as the execution price after a bar-i signal is confirmed, but it must not feed back into the bar-i signal. The examples below are only high-risk patterns, not a complete blacklist; missing those examples does not mean the code is safe. Grep/pattern scans help surface risky code shapes, but they do not replace manual timing review.
The following are common patterns, not an exhaustive list. When they appear, point out the issue and confirm how to handle it:
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/trading-strategy-backtest/SKILL.md
Popularity
- Repository stars
- 4
- Repository forks
- 1
- 7-day trend score
- 13
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hookspluginCustom plugin integration
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/nstung463/kimi-agent-skills/trading-strategy-backtest)