crypto-backtest
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCrypto Strategy Backtest Skill
加密货币策略回测Skill
Transform natural language trading ideas into validated strategies with professional backtesting, beautiful reports, and runnable code.
⚠️ SPOT ONLY: This skill supports spot trading strategies only. No leverage, no shorting, no futures/perpetual contracts. All strategies are long-only (buy low → hold → sell high).
将自然语言描述的交易想法转化为可验证的策略,同时提供专业的回测、美观的报告和可运行的代码。
⚠️ 仅支持现货交易:本Skill仅支持现货交易策略。不支持杠杆、做空、期货/永续合约。所有策略均为仅做多类型(低买→持有→高卖)。
Your Superpower
你的核心能力
You turn vague trading intuitions into professional-grade, multi-dimensional strategies. When users say "buy when cheap", you don't just slap on RSI < 30 — you build a comprehensive valuation model using multiple indicators, each with proper reasoning.
Your goal: Make strategy completion so thorough that users think "wow, I wouldn't have thought of all this myself."
你可以将模糊的交易直觉转化为专业级的多维度策略。当用户说“逢低买入”时,你不会简单地设置RSI < 30,而是会使用多个指标构建综合估值模型,每个指标都有合理的依据。
你的目标:让策略内容足够全面,使用户发出“哇,我自己都想不到这么多细节”的赞叹。
CRITICAL: Parameter Estimation Principles
关键:参数估算原则
Think like a quant: Every parameter must be justified, not guessed.
- Threshold = f(historical volatility): For spreads, use 1.5-2× standard deviation. For RSI, use 30/70 (BTC) or 25/75 (alts).
- Stop Loss > normal noise: BTC daily vol is 3-5%, so stop loss should be 5-8%, not 2%.
- Respect user's exact specs: If user says "every 6 hours", use 6h, not 2h.
- Spot only: leverage = 1x, always. No perpetuals, no shorting.
- Position Size is PERCENTAGE: means 10% of capital per trade, NOT $10!
--position-size 10 - OKX data limit: OKX only provides ~60-90 days of history. For longer backtests, use or
--exchange kucoin(if accessible).--exchange binance
像量化分析师一样思考:每个参数都必须有合理依据,不能凭空猜测。
- 阈值 = 历史波动率函数:对于价差,使用1.5-2倍标准差。对于RSI,BTC使用30/70,山寨币使用25/75。
- 止损幅度需大于正常波动:BTC日波动率为3-5%,因此止损幅度应设置为5-8%,而非2%。
- 严格遵循用户的具体要求:如果用户说“每6小时”,就使用6小时周期,不要改为2小时。
- 仅支持现货:杠杆倍数始终为1x。不支持永续合约、做空。
- 仓位大小为百分比:表示每次交易使用10%的资金,而非10美元!
--position-size 10 - OKX数据限制:OKX仅提供约60-90天的历史数据。如需更长周期的回测,请使用或
--exchange kucoin(如果可访问)。--exchange binance
CRITICAL: Strategy Completion Standards
关键:策略完善标准
When translating natural language to technical conditions, NEVER use single indicators. Always combine multiple dimensions:
将自然语言转化为技术条件时,绝不使用单一指标。始终结合多个维度:
🎯 "Undervalued/Cheap/Oversold/Dip" → Multi-Factor Valuation Model
🎯 “被低估/便宜/超卖/下跌” → 多因子估值模型
DON'T: (too simplistic, easily fooled by trends)
RSI(14) < 30DO: Combine 4-5 indicators for robust valuation scoring:
| Dimension | Indicator | Bullish Signal | Weight |
|---|---|---|---|
| Momentum | RSI(14) | < 35 | 1.0 |
| Trend Position | Price vs SMA(200) | Price < SMA200 | 1.0 |
| Volatility Band | Bollinger Bands | Price < BB_Lower | 1.0 |
| Drawdown | Price vs 90-day High | Drawdown > 25% | 1.0 |
| Momentum Divergence | MACD Histogram | Turning positive while price low | 0.5 |
| Volume Confirmation | Volume vs MA(20) | Volume spike (>1.5x) on dip | 0.5 |
Valuation Score = Sum of triggered signals × weights
- Score ≥ 3.0: Strong undervaluation
- Score 2.0-3.0: Moderate undervaluation
- Score < 2.0: Weak/no signal
错误做法:(过于简单,容易被趋势误导)
RSI(14) < 30正确做法:结合4-5个指标构建稳健的估值评分:
| 维度 | 指标 | 看涨信号 | 权重 |
|---|---|---|---|
| 动量 | RSI(14) | < 35 | 1.0 |
| 趋势位置 | 价格 vs SMA(200) | 价格 < SMA200 | 1.0 |
| 波动率区间 | 布林带(Bollinger Bands) | 价格 < BB_Lower | 1.0 |
| 回撤幅度 | 价格 vs 90日高点 | 回撤幅度 > 25% | 1.0 |
| 动量背离 | MACD柱状图 | 价格低位时柱状图转阳 | 0.5 |
| 成交量确认 | 成交量 vs MA(20) | 下跌时成交量激增(>1.5倍) | 0.5 |
估值评分 = 触发信号 × 权重的总和
- 评分 ≥ 3.0:严重低估
- 评分 2.0-3.0:中度低估
- 评分 < 2.0:信号微弱/无信号
📈 "Overvalued/Expensive/Overbought" → Multi-Factor Model
📈 “被高估/昂贵/超买” → 多因子模型
| Dimension | Indicator | Bearish Signal | Weight |
|---|---|---|---|
| Momentum | RSI(14) | > 70 | 1.0 |
| Trend Extension | Price vs SMA(200) | Price > SMA200 × 1.3 | 1.0 |
| Volatility Band | Bollinger Bands | Price > BB_Upper | 1.0 |
| From Recent Low | Price vs 90-day Low | Gain > 50% | 1.0 |
| Momentum Divergence | MACD Histogram | Turning negative while price high | 0.5 |
| Volume Dry-up | Volume vs MA(20) | Volume declining on rally | 0.5 |
| 维度 | 指标 | 看跌信号 | 权重 |
|---|---|---|---|
| 动量 | RSI(14) | > 70 | 1.0 |
| 趋势延伸 | 价格 vs SMA(200) | 价格 > SMA200 × 1.3 | 1.0 |
| 波动率区间 | 布林带 | 价格 > BB_Upper | 1.0 |
| 自近期低点涨幅 | 价格 vs 90日低点 | 涨幅 > 50% | 1.0 |
| 动量背离 | MACD柱状图 | 价格高位时柱状图转阴 | 0.5 |
| 成交量萎缩 | 成交量 vs MA(20) | 上涨时成交量下降 | 0.5 |
🚀 "Trend/Bullish/Uptrend" → Multi-Timeframe Confirmation
🚀 “趋势/看涨/上升趋势” → 多时间周期确认
DON'T: (single timeframe, easily whipsawed)
Price > EMA(21)DO: Require alignment across timeframes:
| Timeframe | Condition | Purpose |
|---|---|---|
| Long-term | Price > SMA(200) | Major trend direction |
| Medium-term | Price > EMA(50) | Intermediate trend |
| Short-term | EMA(9) > EMA(21) | Recent momentum |
| Momentum | MACD > Signal Line | Acceleration |
| Strength | ADX > 25 | Trend strength confirmation |
Entry: All conditions aligned
Exit: Short-term reversal (EMA9 < EMA21) OR momentum loss (MACD cross down)
错误做法:(单一时间周期,容易被反复止损)
Price > EMA(21)正确做法:要求多个时间周期的信号一致:
| 时间周期 | 条件 | 目的 |
|---|---|---|
| 长期 | 价格 > SMA(200) | 主要趋势方向 |
| 中期 | 价格 > EMA(50) | 中期趋势 |
| 短期 | EMA(9) > EMA(21) | 近期动量 |
| 动量 | MACD > 信号线 | 上涨加速 |
| 强度 | ADX > 25 | 趋势强度确认 |
入场:所有条件均满足
出场:短期反转(EMA9 < EMA21)或动量丧失(MACD死叉)
💥 "Breakout" → Volume-Confirmed Breakout
💥 “突破” → 成交量确认的突破
DON'T: (many false breakouts)
Price > BB_UpperDO: Require multiple confirmations:
| Condition | Purpose |
|---|---|
| Price > BB_Upper(20, 2.0) | Statistical breakout |
| Volume > 2.0 × Volume_MA(20) | Strong participation |
| Close in top 25% of candle range | Buying pressure |
| RSI(14) > 50 but < 80 | Momentum without exhaustion |
| Previous 5 candles: tight range (BB width contracting) | Coiled energy |
错误做法:(存在大量假突破)
Price > BB_Upper正确做法:要求多个确认信号:
| 条件 | 目的 |
|---|---|
| 价格 > BB_Upper(20, 2.0) | 统计意义上的突破 |
| 成交量 > 2.0 × Volume_MA(20) | 市场参与度高 |
| 收盘价位于蜡烛图顶部25%区间 | 买盘压力充足 |
| RSI(14) > 50 但 < 80 | 动量充足但未过度 |
| 前5根K线:区间收窄(布林带宽度收缩) | 蓄势待发 |
📊 "DCA" → Smart DCA with Valuation Adjustment
📊 “DCA(平均成本法)” → 结合估值调整的智能DCA
DON'T: Fixed amount every period (misses opportunities)
DO: Dynamic allocation based on valuation score:
| Valuation Score | Market State | Allocation |
|---|---|---|
| ≥ +3.0 | 🟢🟢 Extreme undervaluation | Base × 2.0 |
| +1.5 to +3.0 | 🟢 Undervalued | Base × 1.5 |
| -1.5 to +1.5 | 🟡 Fair value | Base × 1.0 |
| -3.0 to -1.5 | 🔴 Overvalued | Base × 0.5 |
| ≤ -3.0 | 🔴🔴 Extreme overvaluation | Base × 0.25 |
错误做法:固定周期投入固定金额(错失机会)
正确做法:根据估值评分动态分配资金:
| 估值评分 | 市场状态 | 资金分配 |
|---|---|---|
| ≥ +3.0 | 🟢🟢 严重低估区间 | 基础金额 × 2.0 |
| +1.5 至 +3.0 | 🟢 被低估 | 基础金额 × 1.5 |
| -1.5 至 +1.5 | 🟡 公允价值 | 基础金额 × 1.0 |
| -3.0 至 -1.5 | 🔴 被高估 | 基础金额 × 0.5 |
| ≤ -3.0 | 🔴🔴 极度谨慎 | 基础金额 × 0.25 |
🔄 "Mean Reversion" → Statistical Deviation Strategy
🔄 “均值回归” → 统计偏差策略
| Condition | Entry | Exit |
|---|---|---|
| Z-Score | Price Z-score < -2.0 | Z-score > 0 |
| BB Position | Price < BB_Lower | Price > BB_Middle |
| RSI | RSI < 30 | RSI > 50 |
| Confirmation | Volume spike on dip | - |
| 条件 | 入场 | 出场 |
|---|---|---|
| Z分数 | 价格Z分数 < -2.0 | Z分数 > 0 |
| 布林带位置 | 价格 < BB_Lower | 价格 > BB_Middle |
| RSI | RSI < 30 | RSI > 50 |
| 确认信号 | 下跌时成交量激增 | - |
Workflow
工作流程
Step 1: Understand & Expand the Intent
步骤1:理解并拓展用户需求
When user describes a trading idea:
- Identify the core strategy type: Mean reversion? Trend following? Breakout? DCA?
- Extract constraints: Asset, timeframe, risk tolerance
- Expand to multi-dimensional conditions using the templates above
- Add appropriate risk management based on strategy type
当用户描述交易想法时:
- 识别核心策略类型:均值回归?趋势跟踪?突破?DCA?
- 提取约束条件:资产类型、时间周期、风险承受能力
- 使用上述模板拓展为多维度条件
- 根据策略类型添加合适的风险管理规则
Step 2: Present Complete Strategy for Confirmation
步骤2:呈现完整策略供用户确认
CRITICAL: Present strategy in this exact YAML format. Users should be impressed by the thoroughness.
yaml
undefined关键:必须使用以下YAML格式呈现策略。用户应能感受到策略的全面性。
yaml
undefined📊 Strategy: [Descriptive Name]
📊 Strategy: [Descriptive Name]
Core Logic: [One sentence explaining the edge]
Core Logic: [One sentence explaining the edge]
Data:
primary_symbol: BTC/USDT
timeframe: 6h # MUST match user's specification
backtest_period: 365 days
indicators:
RSI: { period: 14 }
SMA: { period: 50, 200 }
BB: { period: 20, std_dev: 2 }
data_requirements: [close_price, volume]
Signal:
entry_conditions:
condition_type: ALL # ALL conditions must be met
conditions:
- RSI < 35
- Price < BB_lower
- Price < SMA200 * 0.98
exit_conditions:
condition_type: ANY # ANY condition triggers exit
conditions:
- RSI > 70
- Price > BB_upper
- Price > SMA200 * 1.05
execution_schedule:
frequency: 6h # MUST match user's specification
check_times: [00:00, 06:00, 12:00, 18:00]
Capital:
total_capital: 10000
position_size_pct: 10 # 10% of capital per trade (NOT fixed dollar amount!)
reserve_ratio: 0.2 # 20% kept as cash buffer
max_drawdown_limit: 0.15 # 15% max drawdown
Risk:
stop_loss: 8%
take_profit: 15% # or null if exit by signal only
max_account_risk: 0.75
emergency_rules:
account_risk_threshold: 0.8 # If 80% at risk → close_all
Execution:
leverage: 1x # SPOT ONLY - always 1x
order_type: market
position_side: long_only
max_positions: 1
**✅ Please review and confirm. Reply "OK" to run backtest, or tell me what to adjust.**Data:
primary_symbol: BTC/USDT
timeframe: 6h # MUST match user's specification
backtest_period: 365 days
indicators:
RSI: { period: 14 }
SMA: { period: 50, 200 }
BB: { period: 20, std_dev: 2 }
data_requirements: [close_price, volume]
Signal:
entry_conditions:
condition_type: ALL # ALL conditions must be met
conditions:
- RSI < 35
- Price < BB_lower
- Price < SMA200 * 0.98
exit_conditions:
condition_type: ANY # ANY condition triggers exit
conditions:
- RSI > 70
- Price > BB_upper
- Price > SMA200 * 1.05
execution_schedule:
frequency: 6h # MUST match user's specification
check_times: [00:00, 06:00, 12:00, 18:00]
Capital:
total_capital: 10000
position_size_pct: 10 # 10% of capital per trade (NOT fixed dollar amount!)
reserve_ratio: 0.2 # 20% kept as cash buffer
max_drawdown_limit: 0.15 # 15% max drawdown
Risk:
stop_loss: 8%
take_profit: 15% # or null if exit by signal only
max_account_risk: 0.75
emergency_rules:
account_risk_threshold: 0.8 # If 80% at risk → close_all
Execution:
leverage: 1x # SPOT ONLY - always 1x
order_type: market
position_side: long_only
max_positions: 1
**✅ 请查看并确认。回复“OK”即可运行回测,或告知需要调整的内容。**⛔ STOP: WAIT FOR USER CONFIRMATION
⛔ 停止:等待用户确认
DO NOT proceed to Step 3 until user explicitly confirms the strategy.
- If user says "OK", "确认", "没问题", "go ahead" → proceed to backtest
- If user has questions or wants changes → modify strategy and present again
- NEVER run backtest without user confirmation
在用户明确确认策略前,请勿进行步骤3。
- 如果用户回复“OK”、“确认”、“没问题”、“go ahead” → 进行回测
- 如果用户有疑问或想要修改 → 修改策略后再次呈现
- 绝不要在未获得用户确认的情况下运行回测
Step 3: Run Backtest (ONLY after user confirms)
步骤3:运行回测(仅在用户确认后)
IMPORTANT: Detect the user's language and pass the parameter accordingly:
--lang- If user writes in Chinese →
--lang zh - If user writes in English →
--lang en
This ensures the HTML report text matches the user's language.
bash
python src/backtest.py \
--symbol "BTC/USDT" \
--timeframe "4h" \
--days 365 \
--entry "rsi<35,price<sma200,price<bb_lower" \
--exit "rsi>50,price>bb_middle" \
--stop-loss 8 \
--take-profit 20 \
--output report.html \
--lang zh # or --lang en based on user's language重要:检测用户使用的语言,并相应传递参数:
--lang- 如果用户使用中文 →
--lang zh - 如果用户使用英文 →
--lang en
这能确保HTML报告的语言与用户语言一致。
bash
python src/backtest.py \
--symbol "BTC/USDT" \
--timeframe "4h" \
--days 365 \
--entry "rsi<35,price<sma200,price<bb_lower" \
--exit "rsi>50,price>bb_middle" \
--stop-loss 8 \
--take-profit 20 \
--output report.html \
--lang zh # or --lang en based on user's languageStep 4: Present Results with Insights
步骤4:呈现结果与洞察
Show metrics AND provide actionable insights:
markdown
undefined展示指标并提供可执行的洞察:
markdown
undefined📈 Backtest Results
📈 回测结果
| Metric | Value | Assessment |
|---|---|---|
| Total Return | +47.3% | ✅ Beats B&H |
| Max Drawdown | -18.2% | ⚠️ Moderate |
| Sharpe Ratio | 1.42 | ✅ Good |
| Win Rate | 64% | ✅ Healthy |
| Profit Factor | 2.1 | ✅ Strong |
| 指标 | 数值 | 评估 |
|---|---|---|
| 总收益率 | +47.3% | ✅ 优于买入持有策略 |
| 最大回撤 | -18.2% | ⚠️ 中度回撤 |
| 夏普比率 | 1.42 | ✅ 表现良好 |
| 胜率 | 64% | ✅ 健康水平 |
| 利润因子 | 2.1 | ✅ 表现强劲 |
Key Insights:
关键洞察:
- Strategy performed best during [market condition]
- Largest drawdown occurred during [event]
- Consider [specific improvement] to reduce drawdown
- 策略在[市场环境]下表现最佳
- 最大回撤发生在[事件期间]
- 建议通过[具体改进措施]降低回撤
Generated Files:
生成的文件:
- - Interactive visual report
report.html - - Runnable Python code
strategy.py
undefined- - 交互式可视化报告
report.html - - 可运行的Python代码
strategy.py
undefinedStep 5: Suggest Iterations
步骤5:建议迭代方向
Based on results, proactively suggest:
- Parameter optimizations
- Additional filters
- Alternative approaches
- Risk adjustments
根据结果主动提出建议:
- 参数优化
- 添加额外过滤条件
- 替代方案
- 风险调整
Strategy Templates Reference
策略模板参考
Template 1: Multi-Factor Value Buying
模板1:多因子价值买入策略
DATA:
- Symbol: BTC/USDT | Timeframe: 4h | Period: 365d
- Indicators: RSI(14), SMA(200), BB(20,2), High_90
SIGNAL:
| Entry (ALL) | Exit (ANY) |
|---|---|
| RSI < 35 | RSI > 65 |
| Price < SMA200_98pct | Price > SMA200 |
| Price < BB_lower | Price > BB_middle |
| Drawdown > 25% | Stop Loss 10% |
RISK: Stop 10% | Take Profit 25% | Position 10%
数据:
- 交易对:BTC/USDT | 时间周期:4h | 回测周期:365天
- 指标:RSI(14), SMA(200), BB(20,2), High_90
信号:
| 入场(需满足所有条件) | 出场(满足任一条件) |
|---|---|
| RSI < 35 | RSI > 65 |
| 价格 < SMA200 × 0.98 | 价格 > SMA200 |
| 价格 < BB_lower | 价格 > BB_middle |
| 回撤幅度 >25% | 止损10% |
风险: 止损10% | 止盈25% | 仓位10%
Template 2: Trend Following with Confirmation
模板2:多时间周期确认的趋势跟踪策略
DATA:
- Symbol: BTC/USDT | Timeframe: 4h | Period: 365d
- Indicators: SMA(200), EMA(9,21,50), MACD, ADX
SIGNAL:
| Entry (ALL) | Exit (ANY) |
|---|---|
| Price > SMA200 | EMA9 < EMA21 |
| EMA9 > EMA21 | Price < SMA50 |
| MACD > MACD_signal | MACD crossunder |
| ADX > 25 | Stop Loss 8% |
RISK: Stop 8% | Trailing Stop 3xATR | Position 15%
数据:
- 交易对:BTC/USDT | 时间周期:4h | 回测周期:365天
- 指标:SMA(200), EMA(9,21,50), MACD, ADX
信号:
| 入场(需满足所有条件) | 出场(满足任一条件) |
|---|---|
| 价格 > SMA200 | EMA9 < EMA21 |
| EMA9 > EMA21 | 价格 < SMA50 |
| MACD > 信号线 | MACD死叉 |
| ADX >25 | 止损8% |
风险: 止损8% | 追踪止损3xATR | 仓位15%
Template 3: Volume-Confirmed Breakout
模板3:成交量确认的突破策略
DATA:
- Symbol: BTC/USDT | Timeframe: 1h | Period: 180d
- Indicators: High_20, Volume_MA(20), RSI(14), BB(20,2)
SIGNAL:
| Entry (ALL) | Exit (ANY) |
|---|---|
| Price > High_20 | Price < EMA21 |
| Volume > Volume_MA_200pct | RSI > 80 |
| RSI between 50-75 | Stop Loss 5% |
| BB_width contracting | Take Profit 15% |
RISK: Stop 5% | Take Profit 15% | Position 20%
数据:
- 交易对:BTC/USDT | 时间周期:1h | 回测周期:180天
- 指标:High_20, Volume_MA(20), RSI(14), BB(20,2)
信号:
| 入场(需满足所有条件) | 出场(满足任一条件) |
|---|---|
| 价格 > High_20 | 价格 < EMA21 |
| 成交量 > Volume_MA ×2 | RSI >80 |
| RSI介于50-75之间 | 止损5% |
| 布林带宽度收缩 | 止盈15% |
风险: 止损5% | 止盈15% | 仓位20%
Template 4: Smart DCA
模板4:智能DCA策略
DATA:
- Symbol: BTC/USDT | Timeframe: 1d | Frequency: Weekly
SIGNAL (Valuation-Based Allocation):
| Score | Market State | Allocation |
|---|---|---|
| ≥ +3 | 🟢🟢 Strong buy zone | Base × 2.0 |
| +1.5 to +3 | 🟢 Undervalued | Base × 1.5 |
| -1.5 to +1.5 | 🟡 Fair value | Base × 1.0 |
| -3 to -1.5 | 🔴 Overvalued | Base × 0.5 |
| ≤ -3 | 🔴🔴 Extreme caution | Base × 0.25 |
CAPITAL: Base $200/week | Reserve 20% | Max DD 15%
数据:
- 交易对:BTC/USDT | 时间周期:1d | 频率:每周
信号(基于估值的资金分配):
| 评分 | 市场状态 | 资金分配 |
|---|---|---|
| ≥ +3 | 🟢🟢 强力买入区间 | 基础金额 ×2.0 |
| +1.5 至 +3 | 🟢 被低估 | 基础金额 ×1.5 |
| -1.5 至 +1.5 | 🟡 公允价值 | 基础金额 ×1.0 |
| -3 至 -1.5 | 🔴 被高估 | 基础金额 ×0.5 |
| ≤ -3 | 🔴🔴 极度谨慎 | 基础金额 ×0.25 |
资金: 每周基础投入200美元 | 预留20%资金 | 最大回撤15%
Template 5: Pair Trading / Relative Strength
模板5:配对交易 / 相对强度策略
CONCEPT: When two correlated assets (e.g., BTC & ETH) diverge significantly,
the underperformer tends to catch up. Trade this mean reversion.
yaml
Data:
primary_symbols: [BTC/USDT, ETH/USDT]
timeframe: 4h
lookback_period: 20 # For calculating relative performance
data_requirements: [close_price]
Signal:
entry_conditions:
condition_type: ANY
conditions:
- spread > +5% # BTC outperforming → Long ETH
- spread < -5% # ETH outperforming → Long BTC
exit_conditions:
condition_type: ANY
conditions:
- abs(spread) < 1% # Spread reverted to mean
- stop_loss: -8%
- take_profit: +15%
Capital:
total_capital: 10000
allocation_per_trade: 20% # of total capital
reserve_ratio: 0.3
Risk:
stop_loss: 8%
take_profit: 15%
max_drawdown_limit: 15%
Execution:
leverage: 1x (spot only)
order_type: market
position_side: long_onlyIMPORTANT THRESHOLD GUIDELINES:
- 20-period (80h ≈ 3.3 days) spread: use 3-5% threshold
- 50-period (200h ≈ 8 days) spread: use 5-8% threshold
- Never use >10% for short lookback - signals will never trigger!
概念: 当两个相关性较高的资产(如BTC和ETH)出现显著背离时,表现落后的资产往往会补涨。利用这种均值回归特性进行交易。
yaml
Data:
primary_symbols: [BTC/USDT, ETH/USDT]
timeframe: 4h
lookback_period: 20 # For calculating relative performance
data_requirements: [close_price]
Signal:
entry_conditions:
condition_type: ANY
conditions:
- spread > +5% # BTC outperforming → Long ETH
- spread < -5% # ETH outperforming → Long BTC
exit_conditions:
condition_type: ANY
conditions:
- abs(spread) < 1% # Spread reverted to mean
- stop_loss: -8%
- take_profit: +15%
Capital:
total_capital: 10000
allocation_per_trade: 20% # of total capital
reserve_ratio: 0.3
Risk:
stop_loss: 8%
take_profit: 15%
max_drawdown_limit: 15%
Execution:
leverage: 1x (spot only)
order_type: market
position_side: long_only重要阈值指南:
- 20周期(80小时≈3.3天)价差:使用3-5%的阈值
- 50周期(200小时≈8天)价差:使用5-8%的阈值
- 短周期回测绝不要使用>10%的阈值,否则永远不会触发信号!
Technical Reference
技术参考
Indicators Available (pandas-ta)
可用指标(基于pandas-ta)
Momentum: RSI, MACD, Stochastic, Williams %R, CCI
Trend: SMA, EMA, ADX, Aroon, Supertrend
Volatility: Bollinger Bands, ATR, Keltner Channels
Volume: OBV, Volume SMA, VWAPMomentum: RSI, MACD, Stochastic, Williams %R, CCI
Trend: SMA, EMA, ADX, Aroon, Supertrend
Volatility: Bollinger Bands, ATR, Keltner Channels
Volume: OBV, Volume SMA, VWAPRisk Profiles
风险配置
Conservative: SL=5%, TP=12%, position=5%, max 3 concurrent
Moderate: SL=8%, TP=20%, position=10%, max 5 concurrent
Aggressive: SL=12%, TP=35%, position=20%, max 8 concurrentConservative: SL=5%, TP=12%, position=5%, max 3 concurrent
Moderate: SL=8%, TP=20%, position=10%, max 5 concurrent
Aggressive: SL=12%, TP=35%, position=20%, max 8 concurrentTechnical Reference: Available Indicators
技术参考:可用指标
Momentum Indicators
动量指标
| Indicator | Column Name | Description |
|---|---|---|
| RSI | | Relative Strength Index (14) |
| Stochastic %K | | Stochastic oscillator K line |
| Stochastic %D | | Stochastic oscillator D line |
| Williams %R | | Williams %R (14) |
| CCI | | Commodity Channel Index (20) |
| MFI | | Money Flow Index (14) |
| ROC | | Rate of Change (10, 20) |
| MACD | | MACD line, signal, histogram |
| 指标 | 列名 | 描述 |
|---|---|---|
| RSI | | 相对强弱指数(14周期) |
| Stochastic %K | | 随机指标K线 |
| Stochastic %D | | 随机指标D线 |
| Williams %R | | 威廉指标(14周期) |
| CCI | | 商品通道指数(20周期) |
| MFI | | 资金流量指数(14周期) |
| ROC | | 变动率(10、20周期) |
| MACD | | MACD线、信号线、柱状图 |
Trend Indicators
趋势指标
| Indicator | Column Name | Description |
|---|---|---|
| SMA | | Simple Moving Averages |
| EMA | | Exponential Moving Averages |
| ADX | | Average Directional Index (trend strength) |
| +DI / -DI | | Directional Indicators |
| 指标 | 列名 | 描述 |
|---|---|---|
| SMA | | 简单移动平均线 |
| EMA | | 指数移动平均线 |
| ADX | | 平均趋向指数(衡量趋势强度) |
| +DI / -DI | | 趋向指标 |
Volatility Indicators
波动率指标
| Indicator | Column Name | Description |
|---|---|---|
| Bollinger Bands | | Upper, middle, lower bands |
| BB Width | | Band width (volatility measure) |
| BB %B | | Price position in BB range (0-1) |
| ATR | | Average True Range (14) |
| ATR % | | ATR as % of price |
| 指标 | 列名 | 描述 |
|---|---|---|
| 布林带 | | 上轨、中轨、下轨 |
| 布林带宽度 | | 带宽(波动率指标) |
| 布林带%b | | 价格在布林带区间内的位置(0-1) |
| ATR | | 平均真实波幅(14周期) |
| ATR百分比 | | ATR相对于价格的百分比 |
Volume Indicators
成交量指标
| Indicator | Column Name | Description |
|---|---|---|
| Volume SMA | | 20-period volume average |
| Volume Ratio | | Current volume / average |
| OBV | | On-Balance Volume |
| 指标 | 列名 | 描述 |
|---|---|---|
| 成交量均线 | | 20周期成交量均线 |
| 成交量比率 | | 当前成交量与均线的比值 |
| OBV | | 能量潮指标 |
Price Position Indicators
价格位置指标
| Indicator | Column Name | Description |
|---|---|---|
| Rolling High | | N-period high |
| Rolling Low | | N-period low |
| Drawdown | | % from rolling high |
| Price Position | | Position in 90-day range (0-1) |
| Distance from MA | | % distance from MA |
| 指标 | 列名 | 描述 |
|---|---|---|
| 滚动高点 | | N周期高点 |
| 滚动低点 | | N周期低点 |
| 回撤幅度 | | 相对于滚动高点的回撤百分比 |
| 价格位置 | | 价格在90天区间内的位置(0-1) |
| 与均线的距离 | | 价格与均线的百分比距离 |
Derived / Change Indicators
衍生/变动指标
| Indicator | Column Name | Description |
|---|---|---|
| Price Change | | 1-period change |
| Price Change 5 | | 5-period change |
| RSI Change | | RSI momentum |
| MACD Change | | MACD momentum |
| Consecutive Up | | Count of consecutive up days |
| Consecutive Down | | Count of consecutive down days |
| 指标 | 列名 | 描述 |
|---|---|---|
| 价格变动 | | 1周期变动 |
| 5周期价格变动 | | 5周期变动 |
| RSI变动 | | RSI动量 |
| MACD变动 | | MACD动量 |
| 连续上涨天数 | | 连续上涨的天数 |
| 连续下跌天数 | | 连续下跌的天数 |
Technical Reference: Condition Syntax
技术参考:条件语法
1. Simple Comparisons
1. 简单比较
rsi<30 # RSI below 30
price>sma200 # Price above SMA 200
adx>=25 # ADX at least 25
bb_pct<0.2 # Price in lower 20% of BB range
drawdown<-20 # Down 20% from recent high
volume_ratio>2 # Volume 2x above averagersi<30 # RSI低于30
price>sma200 # 价格高于SMA200
adx>=25 # ADX至少为25
bb_pct<0.2 # 价格位于布林带区间的下20%
drawdown<-20 # 较近期高点下跌20%
volume_ratio>2 # 成交量为均线的2倍以上2. Crossover / Crossunder
2. 金叉/死叉
macd_crossover # MACD crosses above signal (default)
ema9_cross_above_ema21 # EMA9 crosses above EMA21
price_crossover_sma50 # Price crosses above SMA50
rsi_crossunder_50 # RSI crosses below 50
stoch_k_cross_above_stoch_d # Stochastic golden crossmacd_crossover # MACD线上穿信号线(默认)
ema9_cross_above_ema21 # EMA9上穿EMA21
price_crossover_sma50 # 价格上穿SMA50
rsi_crossunder_50 # RSI下穿50
stoch_k_cross_above_stoch_d # 随机指标金叉3. Turning Points
3. 转折点
rsi_turning_up # RSI starts increasing
macd_hist_turning_down # MACD histogram starts decreasing
price_turning_up # Price reversal upwardrsi_turning_up # RSI开始上升
macd_hist_turning_down # MACD柱状图开始下降
price_turning_up # 价格反转向上4. Consecutive Periods
4. 连续周期
rsi<30_for_3 # RSI below 30 for 3 consecutive periods
price>sma200_for_5 # Price above SMA200 for 5 periods
consecutive_up>=3 # At least 3 consecutive up daysrsi<30_for_3 # RSI连续3个周期低于30
price>sma200_for_5 # 价格连续5个周期高于SMA200
consecutive_up>=3 # 至少连续3天上涨5. Combined Conditions
5. 组合条件
Conditions are comma-separated. Entry uses AND logic, Exit uses OR logic.
--entry "rsi<35,price<bb_lower,volume_ratio>1.5"
--exit "rsi>70,price>bb_upper"条件使用逗号分隔。入场条件使用AND逻辑,出场条件使用OR逻辑。
--entry "rsi<35,price<bb_lower,volume_ratio>1.5"
--exit "rsi>70,price>bb_upper"Important Guidelines
重要指南
- Never use single indicators - Always combine multiple dimensions
- Explain the logic - Users should understand WHY each indicator is included
- Match complexity to strategy - DCA needs valuation model, trend following needs multi-TF
- Be honest about limitations - Past performance ≠ future results
- Encourage iteration - Backtesting is a process, not a one-shot
- 绝不使用单一指标 - 始终结合多个维度
- 解释逻辑 - 用户应理解每个指标被纳入的原因
- 策略复杂度匹配 - DCA策略需要估值模型,趋势跟踪策略需要多时间周期确认
- 如实说明局限性 - 过往表现不代表未来结果
- 鼓励迭代 - 回测是一个持续优化的过程,而非一次性操作
⚠️ CRITICAL: Exchange Data Limits
⚠️ 关键:交易所数据限制
Different exchanges have different historical data limits!
| Exchange | Approximate Limit | Notes |
|---|---|---|
| OKX | ~60-90 days | Default. Good for short-term backtests |
| KuCoin | ~200 days | Good alternative for medium-term |
| Binance | 1000+ days | Most data, but blocked in some regions |
| Bybit | ~200 days | Good alternative |
If you need more than 90 days of data:
bash
undefined不同交易所的历史数据限制不同!
| 交易所 | 大致数据限制 | 说明 |
|---|---|---|
| OKX | ~60-90天 | 默认选项。适合短期回测 |
| KuCoin | ~200天 | 适合中期回测的替代选项 |
| Binance | 1000+天 | 数据量最大,但部分地区无法访问 |
| Bybit | ~200天 | 优质替代选项 |
如需超过90天的历史数据:
bash
undefinedOKX default - will only get ~90 days even if you request 365
OKX默认选项 - 即使请求365天,也仅能获取约90天数据
python src/backtest.py --symbol BTC/USDT --days 365 ...
python src/backtest.py --symbol BTC/USDT --days 365 ...
Use KuCoin for ~200 days (works in most regions)
使用KuCoin获取约200天数据(多数地区可访问)
python src/backtest.py --symbol BTC/USDT --days 180 --exchange kucoin ...
python src/backtest.py --symbol BTC/USDT --days 180 --exchange kucoin ...
Use Binance for 365+ days (if accessible in your region)
使用Binance获取365+天数据(如果所在地区可访问)
python src/backtest.py --symbol BTC/USDT --days 365 --exchange binance ...
---python src/backtest.py --symbol BTC/USDT --days 365 --exchange binance ...
---File Locations
文件位置
- Backtest engine:
src/backtest.py - Smart DCA:
src/smart_dca.py - Pair Trading:
src/pair_trading.py - Output reports: current working directory
- Generated code: current working directory
- 回测引擎:
src/backtest.py - 智能DCA:
src/smart_dca.py - 配对交易:
src/pair_trading.py - 输出报告:当前工作目录
- 生成的代码:当前工作目录
Smart DCA Usage
智能DCA使用方法
For DCA strategies, use the dedicated Smart DCA script:
bash
python src/smart_dca.py \
--symbol "BTC/USDT" \
--days 1095 \
--base-amount 200 \
--frequency 7 \
--output smart_dca_report.html \
--lang zh # or --lang en based on user's language对于DCA策略,请使用专用的智能DCA脚本:
bash
python src/smart_dca.py \
--symbol "BTC/USDT" \
--days 1095 \
--base-amount 200 \
--frequency 7 \
--output smart_dca_report.html \
--lang zh # or --lang en based on user's languagePair Trading / Relative Strength Usage
配对交易 / 相对强度使用方法
For pair trading strategies that compare two assets (e.g., BTC vs ETH):
bash
python src/pair_trading.py \
--symbol-a "BTC/USDT" \
--symbol-b "ETH/USDT" \
--days 365 \
--timeframe 4h \
--lookback 20 \
--threshold 10 \
--exit-threshold 2 \
--output pair_trading_report.html \
--lang zh # or --lang en based on user's language \
--description "Long the underperformer when BTC/ETH spread deviates"Parameters:
- : Period for calculating relative performance (default: 20)
--lookback - : Entry threshold - spread deviation % to trigger entry (default: 10)
--threshold - : Exit threshold - spread deviation % to close position (default: 2)
--exit-threshold
对于比较两个资产的配对交易策略(如BTC vs ETH):
bash
python src/pair_trading.py \
--symbol-a "BTC/USDT" \
--symbol-b "ETH/USDT" \
--days 365 \
--timeframe 4h \
--lookback 20 \
--threshold 10 \
--exit-threshold 2 \
--output pair_trading_report.html \
--lang zh # or --lang en based on user's language \
--description "Long the underperformer when BTC/ETH spread deviates"参数说明:
- : 计算相对表现的周期(默认:20)
--lookback - : 入场阈值 - 价差偏离百分比,触发入场信号(默认:10)
--threshold - : 出场阈值 - 价差偏离百分比,触发出场信号(默认:2)
--exit-threshold
Language Support
语言支持
CRITICAL: Always detect the user's language and pass the appropriate parameter:
--lang- User writes in Chinese → (report in Chinese)
--lang zh - User writes in English → (report in English)
--lang en
This ensures the generated HTML report matches the user's language preference.
关键:始终检测用户使用的语言,并传递相应的参数:
--lang- 用户使用中文 → (报告为中文)
--lang zh - 用户使用英文 → (报告为英文)
--lang en
这能确保生成的HTML报告符合用户的语言偏好。