← 返回 Skills 市场
zhaocaixia888

Backtesting Framework

作者 zhaocaixia888 · GitHub ↗ · v1.0.0 · MIT-0
cross-platform ✓ 安全检测通过
44
总下载
0
收藏
0
当前安装
1
版本数
在 OpenClaw 中安装
/install backtesting-framework
功能描述
Strategy backtesting framework for futures and stocks. Supports moving average crossovers, RSI mean reversion, Bollinger Bands breakout, and custom strategie...
使用说明 (SKILL.md)

Backtesting Framework — 策略回测框架

Pure Python backtesting engine for futures and stock strategies. No external dependencies beyond NumPy.

Quick Start

import numpy as np

# Sample price data (close prices)
prices = np.array([100, 102, 101, 105, 107, 106, 110, 108, 112, 115])

def ma_crossover(prices, fast=3, slow=5):
    """Moving Average Crossover Strategy"""
    fast_ma = np.convolve(prices, np.ones(fast)/fast, mode='valid')
    slow_ma = np.convolve(prices, np.ones(slow)/slow, mode='valid')
    
    # Align arrays
    min_len = min(len(fast_ma), len(slow_ma))
    fast_ma = fast_ma[-min_len:]
    slow_ma = slow_ma[-min_len:]
    
    # Generate signals: 1 = buy, -1 = sell, 0 = hold
    signals = np.zeros(min_len)
    signals[1:] = np.where(fast_ma[1:] > slow_ma[1:], 1, -1)
    
    return signals

def backtest(prices, signals, initial_capital=10000):
    """Run a backtest and return performance metrics."""
    # Pad signals to match prices
    pad = len(prices) - len(signals)
    signals = np.pad(signals, (pad, 0), 'constant', constant_values=0)
    
    # Calculate returns
    returns = np.diff(prices) / prices[:-1]
    strategy_returns = signals[:-1] * returns
    
    # Performance metrics
    total_return = np.prod(1 + strategy_returns) - 1
    sharpe = np.mean(strategy_returns) / np.std(strategy_returns) * np.sqrt(252) if np.std(strategy_returns) > 0 else 0
    win_rate = np.sum(strategy_returns > 0) / np.sum(strategy_returns != 0) if np.sum(strategy_returns != 0) > 0 else 0
    
    # Max drawdown
    cumulative = np.cumprod(1 + strategy_returns)
    peak = np.maximum.accumulate(cumulative)
    drawdown = (cumulative - peak) / peak
    max_dd = np.min(drawdown)
    
    return {
        "total_return": total_return,
        "sharpe_ratio": sharpe,
        "win_rate": win_rate,
        "max_drawdown": max_dd,
        "final_capital": initial_capital * (1 + total_return)
    }

Built-in Strategies

1. Moving Average Crossover (均线金叉死叉)

def ma_strategy(prices, fast=5, slow=20):
    fast_ma = np.convolve(prices, np.ones(fast)/fast, mode='valid')
    slow_ma = np.convolve(prices, np.ones(slow)/slow, mode='valid')
    min_len = min(len(fast_ma), len(slow_ma))
    signals = np.zeros(min_len)
    signals[1:] = np.where(fast_ma[1:min_len] > slow_ma[1:min_len], 1, -1)
    return signals

2. RSI Mean Reversion (RSI均值回归)

def rsi_strategy(prices, period=14, oversold=30, overbought=70):
    deltas = np.diff(prices)
    gains = np.where(deltas > 0, deltas, 0)
    losses = np.where(deltas \x3C 0, -deltas, 0)
    avg_gain = np.convolve(gains, np.ones(period)/period, mode='valid')
    avg_loss = np.convolve(losses, np.ones(period)/period, mode='valid')
    rs = avg_gain / np.where(avg_loss == 0, 0.001, avg_loss)
    rsi = 100 - (100 / (1 + rs))
    signals = np.zeros(len(rsi))
    signals[rsi \x3C oversold] = 1
    signals[rsi > overbought] = -1
    return signals

3. Bollinger Bands Breakout (布林带突破)

def bb_strategy(prices, period=20, std_dev=2):
    sma = np.convolve(prices, np.ones(period)/period, mode='valid')
    rolling_std = np.array([np.std(prices[i:i+period]) for i in range(len(prices)-period+1)])
    upper = sma + std_dev * rolling_std
    lower = sma - std_dev * rolling_std
    
    signals = np.zeros(len(sma))
    price_aligned = prices[period-1:]
    signals[price_aligned > upper] = -1  # Short at upper band
    signals[price_aligned \x3C lower] = 1   # Long at lower band
    return signals

Output Format

🔬 策略回测报告

策略: MA Crossover (5, 20)
品种: IF2606 (沪深300)
时间: 2026-01-01 ~ 2026-05-21

📊 绩效指标
• 总收益率:    +15.3%
• 年化收益:    +38.2%
• 夏普比率:    1.45  🟢
• 胜率:        42.5%
• 最大回撤:    -8.7%
• 交易次数:    42次

📈 资金曲线
期初: ¥10,000
期末: ¥11,530

⚠️ 回测表现不代表未来收益

Notes

  • All strategies use only NumPy for calculations
  • Backtest results are hypothetical and do not account for: slippage, commissions, liquidity
  • Always forward-test (paper trade) before going live
  • Overfitting is the #1 enemy — keep strategies simple
  • Use multiple timeframes to validate strategy robustness
安全使用建议
Reasonable to install from a security perspective. Treat the included strategies as educational examples only: backtest results can be misleading, and the skill does not account for real trading risks such as slippage, commissions, liquidity, or overfitting.
能力标签
crypto
能力评估
Purpose & Capability
The stated purpose is financial strategy backtesting, and the artifact contains only markdown instructions and Python code examples for calculating indicators and performance metrics.
Instruction Scope
Runtime instructions are scoped to local numerical analysis and report generation; there are no instructions to trade live, access accounts, override agent behavior, or handle sensitive data.
Install Mechanism
The metadata declares a python3 binary requirement, while examples also import NumPy; this is a dependency clarity issue, not a security concern.
Credentials
The requested environment is proportionate for the purpose: local Python execution for calculations, with no file-system scanning, network calls, package-install commands, or external services in the skill artifact.
Persistence & Privilege
No persistence, privilege escalation, background workers, credential use, or mutation of user accounts or installed skills is present.
如何使用
  1. 确保已安装 OpenClaw(本地或 Docker 部署)
  2. 在对话框中输入安装命令:/install backtesting-framework
  3. 安装完成后,直接呼叫该 Skill 的名称或使用 /backtesting-framework 触发
  4. 根据 Skill 的参数说明提供必要输入,即可获得结构化输出
版本历史
v1.0.0
Initial release: strategy backtesting for futures and stocks with performance reports
元数据
Slug backtesting-framework
版本 1.0.0
许可证 MIT-0
累计安装 0
当前安装数 0
历史版本数 1
常见问题

Backtesting Framework 是什么?

Strategy backtesting framework for futures and stocks. Supports moving average crossovers, RSI mean reversion, Bollinger Bands breakout, and custom strategie... 它是一个面向 Claude Code / OpenClaw 的 AI Agent Skill 插件,目前累计下载 44 次。

如何安装 Backtesting Framework?

在 OpenClaw 或 Claude Code 对话框中运行命令「/install backtesting-framework」即可一键安装,无需额外配置。

Backtesting Framework 是免费的吗?

是的,Backtesting Framework 完全免费,采用 MIT-0 许可证,可自由下载、安装和使用。

Backtesting Framework 支持哪些平台?

Backtesting Framework 跨平台运行,可在任意部署了 OpenClaw / Claude Code 的环境中使用(cross-platform)。

谁开发了 Backtesting Framework?

由 zhaocaixia888(@zhaocaixia888)开发并维护,当前版本 v1.0.0。

💬 留言讨论