backtesting
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
Chinesebacktesting
回测
Purpose
用途
This skill enables OpenClaw to perform backtesting on historical financial data, simulating trading strategies to measure metrics like returns, drawdowns, and Sharpe ratio. Use it to validate strategies before live trading, identifying potential flaws in logic or risk exposure.
本技能支持OpenClaw对历史金融数据执行回测,模拟交易策略以测算收益率、回撤、Sharpe ratio等指标。可用于实盘交易前验证策略,识别逻辑或风险敞口存在的潜在缺陷。
When to Use
适用场景
Apply this skill when developing or refining trading strategies, such as evaluating a moving average crossover on stock data. Use it for quantitative analysis in algorithmic trading, portfolio optimization, or risk assessment, especially when historical data is available and strategies need empirical validation.
在开发或优化交易策略时使用该技能,比如评估股票数据上的移动平均交叉策略。适用于算法交易、投资组合优化或风险评估中的量化分析场景,尤其适用于有可用历史数据、需要对策略进行实证验证的情况。
Key Capabilities
核心功能
- Simulate trades using historical price data from CSV, JSON, or API sources.
- Compute performance metrics including total return, volatility, maximum drawdown, and risk-adjusted returns.
- Support for common indicators like SMA, RSI, and Bollinger Bands via integrated libraries.
- Handle multiple assets or portfolios, with options for transaction costs, slippage, and position sizing.
- Output results in JSON format for easy parsing and visualization.
- 支持使用来自CSV、JSON或API来源的历史价格数据模拟交易
- 计算总收益率、波动率、最大回撤、风险调整后收益等绩效指标
- 通过集成库支持SMA、RSI、Bollinger Bands等常用指标
- 支持多资产或投资组合,可配置交易成本、滑点、头寸规模等参数
- 以JSON格式输出结果,便于解析和可视化
Usage Patterns
使用方式
To backtest a strategy, provide a Python script defining the strategy logic, historical data source, and parameters. Always set the API key via environment variable before running. For CLI, use flags to specify inputs; for API, send a POST request with a JSON payload. Validate data integrity first by checking for missing values or incorrect timestamps. Run tests iteratively, adjusting parameters based on initial results.
$OPENCLAW_API_KEY要回测一个策略,需要提供定义策略逻辑、历史数据源和参数的Python脚本。运行前请务必通过环境变量设置API密钥。CLI模式下使用参数指定输入;API模式下发送携带JSON payload的POST请求。首先校验数据完整性,检查是否有缺失值或时间戳错误。迭代运行测试,根据初步结果调整参数。
$OPENCLAW_API_KEYCommon Commands/API
常用命令/API
Use the OpenClaw CLI for quick tests or the REST API for programmatic integration. Authentication requires setting in your environment.
$OPENCLAW_API_KEY-
CLI Command: Run a backtest with a strategy file and data source.
openclaw backtest --strategy strategy.py --data historical.csv --start-date 2020-01-01 --end-date 2023-01-01 --capital 10000This executes the strategy on the specified date range with initial capital. -
API Endpoint: POST to /v1/backtest with JSON body.
curl -X POST https://api.openclaw.ai/v1/backtest \ -H "Authorization: Bearer $OPENCLAW_API_KEY" \ -d '{"strategy": "def trade(data): return buy if data['close'] > data['sma'] else sell", "data_source": "historical.csv", "params": {"start_date": "2020-01-01"}}'Expect a JSON response with keys like "returns" and "drawdown". -
Config Format: Use YAML for strategy configurations, e.g.,
strategy: name: moving_average parameters: period: 20 threshold: 0.05Load this via CLI with.--config strategy.yaml
使用OpenClaw CLI进行快速测试,或使用REST API实现程序化集成。身份验证需要在环境中设置。
$OPENCLAW_API_KEY-
CLI命令:使用策略文件和数据源运行回测。
openclaw backtest --strategy strategy.py --data historical.csv --start-date 2020-01-01 --end-date 2023-01-01 --capital 10000该命令会在指定的日期范围内使用初始资金执行策略。 -
API端点:向/v1/backtest发送POST请求,请求体为JSON格式。
curl -X POST https://api.openclaw.ai/v1/backtest \ -H "Authorization: Bearer $OPENCLAW_API_KEY" \ -d '{"strategy": "def trade(data): return buy if data['\''close'\''] > data['\''sma'\''] else sell", "data_source": "historical.csv", "params": {"start_date": "2020-01-01"}}'预期返回包含"returns"、"drawdown"等字段的JSON响应。 -
配置格式:使用YAML编写策略配置,示例如下:
strategy: name: moving_average parameters: period: 20 threshold: 0.05可通过CLI的参数加载配置。--config strategy.yaml
Integration Notes
集成说明
Integrate with data providers like Yahoo Finance or Alpha Vantage by specifying URLs in the data source flag (e.g., ). For Python workflows, import OpenClaw as a library: . Ensure compatibility by using Python 3.8+ and handling dependencies via . If combining with other skills, chain outputs; for example, use results from a "data-fetch" skill as input here.
--data https://example.com/data.csvimport openclaw; result = openclaw.backtest(strategy_file='strategy.py', data='historical.csv')pip install openclaw-finance可通过在数据源参数中指定URL对接Yahoo Finance、Alpha Vantage等数据提供商(例如)。对于Python工作流,可将OpenClaw作为库导入:。请使用Python 3.8+以确保兼容性,通过安装依赖。如果要和其他技能结合,可以串联输出:例如使用"data-fetch"技能的输出作为本技能的输入。
--data https://example.com/data.csvimport openclaw; result = openclaw.backtest(strategy_file='strategy.py', data='historical.csv')pip install openclaw-financeError Handling
错误处理
Anticipate errors like invalid data formats, missing API keys, or strategy failures. Check for before execution; if absent, the command will exit with code 401. Handle runtime errors by wrapping calls in try-except blocks, e.g.,
$OPENCLAW_API_KEYtry:
openclaw.backtest(strategy='strategy.py', data='historical.csv')
except ValueError as e:
print(f"Data error: {e} - Verify CSV columns match expected format.")Common issues: Invalid dates return code 400; use flag for detailed logs. Always validate strategy code for syntax errors before running.
--verbose需预判无效数据格式、API密钥缺失、策略运行失败等错误。执行前检查是否配置,若缺失命令将以401状态码退出。通过try-except代码块包裹调用处理运行时错误,示例如下:
$OPENCLAW_API_KEYtry:
openclaw.backtest(strategy='strategy.py', data='historical.csv')
except ValueError as e:
print(f"Data error: {e} - Verify CSV columns match expected format.")常见问题:无效日期将返回400状态码;使用参数获取详细日志。运行前请务必校验策略代码是否存在语法错误。
--verboseConcrete Usage Examples
实际使用示例
-
Backtest a simple SMA crossover strategy on Apple stock data:
openclaw backtest --strategy examples/sma_crossover.py --data aapl_historical.csv --params '{"short_period": 10, "long_period": 30}' --capital 5000This simulates buying when short SMA crosses above long SMA, outputting metrics like 15% annual return. -
Evaluate a portfolio strategy with multiple assets and fees:
curl -X POST https://api.openclaw.ai/v1/backtest -H "Authorization: Bearer $OPENCLAW_API_KEY" -d '{"strategy": "portfolio_alloc.py", "data_source": ["aapl.csv", "goog.csv"], "params": {"fee_per_trade": 5.0}}'This assesses a diversified portfolio, calculating net returns after fees, e.g., 12% with 8% drawdown.
-
对苹果股票数据回测简单的SMA交叉策略:
openclaw backtest --strategy examples/sma_crossover.py --data aapl_historical.csv --params '{"short_period": 10, "long_period": 30}' --capital 5000该命令模拟当短期SMA上穿长期SMA时买入,输出15%年化收益率等指标。 -
评估含多资产和手续费的投资组合策略:
curl -X POST https://api.openclaw.ai/v1/backtest -H "Authorization: Bearer $OPENCLAW_API_KEY" -d '{"strategy": "portfolio_alloc.py", "data_source": ["aapl.csv", "goog.csv"], "params": {"fee_per_trade": 5.0}}'该命令评估多元化投资组合,计算扣除手续费后的净收益,例如12%收益率、8%回撤。
Graph Relationships
关联关系
- Related to: trading (dependency for strategy execution)
- Related to: financial-analysis (provides input data and metrics)
- Connected to: risk-management (outputs risk metrics for further analysis)
- Links with: data-fetch (uses fetched historical data as input)
- 依赖项:trading(策略执行的依赖)
- 关联项:financial-analysis(提供输入数据和指标)
- 关联项:risk-management(输出风险指标供进一步分析)
- 关联项:data-fetch(使用获取到的历史数据作为输入)