commit 1d99e38517e75ff70f935ff759e2c6272596cb04 Author: Zhongwei Li Date: Sun Nov 30 08:17:51 2025 +0800 Initial commit diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json new file mode 100644 index 0000000..fb91e8a --- /dev/null +++ b/.claude-plugin/plugin.json @@ -0,0 +1,16 @@ +{ + "name": "trading-strategy-backtester", + "description": "Backtest trading strategies with historical data, performance metrics, and risk analysis", + "version": "1.0.0", + "author": { + "name": "Intent Solutions IO", + "email": "jeremy@intentsolutions.ai", + "url": "https://intentsolutions.ai" + }, + "skills": [ + "./skills" + ], + "commands": [ + "./commands" + ] +} \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..ea0c38b --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ +# trading-strategy-backtester + +Backtest trading strategies with historical data, performance metrics, and risk analysis diff --git a/commands/backtest-strategy.md b/commands/backtest-strategy.md new file mode 100644 index 0000000..ecee345 --- /dev/null +++ b/commands/backtest-strategy.md @@ -0,0 +1,202 @@ +--- +description: Backtest trading strategies with historical data and comprehensive performance analysis +shortcut: bs +--- + +# Backtest Trading Strategy + +Test trading strategies against historical data with performance metrics, risk analysis, and optimization. + +## Usage + +Implement comprehensive backtesting with: + +### Parameters +- **Strategy**: Type of strategy to test +- **Symbol**: Asset or portfolio to test +- **Period**: Historical timeframe +- **Initial Capital**: Starting amount +- **Parameters**: Strategy-specific settings + +## Implementation + +```javascript +class StrategyBacktester { + constructor() { + this.strategies = { + movingAverage: new MovingAverageStrategy(), + rsi: new RSIStrategy(), + macd: new MACDStrategy(), + breakout: new BreakoutStrategy(), + meanReversion: new MeanReversionStrategy(), + momentum: new MomentumStrategy(), + pairs: new PairsTrading(), + gridTrading: new GridTradingStrategy() + }; + } + + async backtest(params) { + const { + strategy = 'movingAverage', + symbol = 'BTC/USDT', + period = '1y', + capital = 10000, + parameters = {} + } = params; + + // Fetch historical data + const data = await this.fetchHistoricalData(symbol, period); + + // Run strategy + const trades = await this.runStrategy( + this.strategies[strategy], + data, + parameters + ); + + // Calculate metrics + const performance = this.calculatePerformance(trades, capital); + const risk = this.calculateRiskMetrics(trades, data); + + // Optimization + const optimized = await this.optimizeParameters( + strategy, + data, + parameters + ); + + return { + summary: this.generateSummary(performance, risk), + trades, + performance, + risk, + optimized, + equity: this.calculateEquityCurve(trades, capital) + }; + } + + async runStrategy(strategy, data, params) { + const trades = []; + let position = null; + + for (let i = strategy.lookback; i < data.length; i++) { + const slice = data.slice(0, i + 1); + const signals = strategy.generateSignals(slice, params); + + if (!position && signals.entry) { + position = { + type: signals.type, + entryPrice: data[i].close, + entryTime: data[i].timestamp, + size: signals.size || 1 + }; + } + + if (position && signals.exit) { + trades.push({ + ...position, + exitPrice: data[i].close, + exitTime: data[i].timestamp, + pnl: this.calculatePnL(position, data[i].close), + duration: data[i].timestamp - position.entryTime + }); + position = null; + } + } + + return trades; + } + + calculatePerformance(trades, capital) { + let equity = capital; + const returns = []; + + for (const trade of trades) { + const returnPct = trade.pnl / equity; + returns.push(returnPct); + equity += trade.pnl; + } + + return { + totalReturn: ((equity - capital) / capital) * 100, + winRate: trades.filter(t => t.pnl > 0).length / trades.length * 100, + avgWin: this.average(trades.filter(t => t.pnl > 0).map(t => t.pnl)), + avgLoss: this.average(trades.filter(t => t.pnl < 0).map(t => Math.abs(t.pnl))), + profitFactor: this.calculateProfitFactor(trades), + sharpeRatio: this.calculateSharpe(returns), + maxDrawdown: this.calculateMaxDrawdown(trades, capital), + calmarRatio: this.calculateCalmar(returns), + totalTrades: trades.length + }; + } + + calculateRiskMetrics(trades, data) { + return { + var95: this.calculateVaR(trades, 0.95), + cvar95: this.calculateCVaR(trades, 0.95), + maxConsecutiveLosses: this.maxConsecutiveLosses(trades), + recoveryFactor: this.calculateRecoveryFactor(trades), + ulcerIndex: this.calculateUlcerIndex(trades), + sortinoRatio: this.calculateSortino(trades) + }; + } +} + +class MovingAverageStrategy { + lookback = 200; + + generateSignals(data, params) { + const { fast = 50, slow = 200 } = params; + + if (data.length < slow) return {}; + + const fastMA = this.sma(data.slice(-fast), fast); + const slowMA = this.sma(data.slice(-slow), slow); + const prevFastMA = this.sma(data.slice(-fast - 1, -1), fast); + const prevSlowMA = this.sma(data.slice(-slow - 1, -1), slow); + + // Golden cross + if (prevFastMA < prevSlowMA && fastMA > slowMA) { + return { entry: true, type: 'LONG', size: 1 }; + } + + // Death cross + if (prevFastMA > prevSlowMA && fastMA < slowMA) { + return { exit: true }; + } + + return {}; + } + + sma(data, period) { + return data.reduce((sum, d) => sum + d.close, 0) / period; + } +} + +// Display results +class BacktestDisplay { + display(results) { + return ` +╔════════════════════════════════════════════════════════════════╗ +║ STRATEGY BACKTEST RESULTS ║ +╠════════════════════════════════════════════════════════════════╣ +${this.formatSummary(results.summary)} +╠════════════════════════════════════════════════════════════════╣ +║ PERFORMANCE METRICS ║ +╠════════════════════════════════════════════════════════════════╣ +${this.formatPerformance(results.performance)} +╠════════════════════════════════════════════════════════════════╣ +║ RISK METRICS ║ +╠════════════════════════════════════════════════════════════════╣ +${this.formatRisk(results.risk)} +╠════════════════════════════════════════════════════════════════╣ +║ TRADE DISTRIBUTION ║ +╠════════════════════════════════════════════════════════════════╣ +${this.formatDistribution(results.trades)} +╚════════════════════════════════════════════════════════════════╝ +`; + } +} +``` + +This provides comprehensive strategy backtesting with performance analysis and risk metrics. \ No newline at end of file diff --git a/plugin.lock.json b/plugin.lock.json new file mode 100644 index 0000000..a41076f --- /dev/null +++ b/plugin.lock.json @@ -0,0 +1,85 @@ +{ + "$schema": "internal://schemas/plugin.lock.v1.json", + "pluginId": "gh:jeremylongshore/claude-code-plugins-plus:plugins/crypto/trading-strategy-backtester", + "normalized": { + "repo": null, + "ref": "refs/tags/v20251128.0", + "commit": "7c6a117eb5c43bf159d969a9869b7ed9d8f3a876", + "treeHash": "d75e7fc67d7f8f0057f677105f8cb8c4df2ecffad47023f98602512da2cd293f", + "generatedAt": "2025-11-28T10:18:50.643241Z", + "toolVersion": "publish_plugins.py@0.2.0" + }, + "origin": { + "remote": "git@github.com:zhongweili/42plugin-data.git", + "branch": "master", + "commit": "aa1497ed0949fd50e99e70d6324a29c5b34f9390", + "repoRoot": "/Users/zhongweili/projects/openmind/42plugin-data" + }, + "manifest": { + "name": "trading-strategy-backtester", + "description": "Backtest trading strategies with historical data, performance metrics, and risk analysis", + "version": "1.0.0" + }, + "content": { + "files": [ + { + "path": "README.md", + "sha256": "ac163e2583c1150c41ce2b8cd57db7665acafa608b43f5ce3cc41806545891ff" + }, + { + "path": ".claude-plugin/plugin.json", + "sha256": "1d7c6f82399f12b8ff3ebf317800a9ab4c75cea982eb50cc40dfe3a8d015ed31" + }, + { + "path": "commands/backtest-strategy.md", + "sha256": "1015422525888bea65522b10842d26845d6e572952b0d3adfe3fcaee54cc1bd0" + }, + { + "path": "skills/skill-adapter/references/examples.md", + "sha256": "922bbc3c4ebf38b76f515b5c1998ebde6bf902233e00e2c5a0e9176f975a7572" + }, + { + "path": "skills/skill-adapter/references/best-practices.md", + "sha256": "c8f32b3566252f50daacd346d7045a1060c718ef5cfb07c55a0f2dec5f1fb39e" + }, + { + "path": "skills/skill-adapter/references/README.md", + "sha256": "6b4214407fe98f172636d20c734e0eb1f8d69854b1b16848dc0ddefcd12e190b" + }, + { + "path": "skills/skill-adapter/scripts/helper-template.sh", + "sha256": "0881d5660a8a7045550d09ae0acc15642c24b70de6f08808120f47f86ccdf077" + }, + { + "path": "skills/skill-adapter/scripts/validation.sh", + "sha256": "92551a29a7f512d2036e4f1fb46c2a3dc6bff0f7dde4a9f699533e446db48502" + }, + { + "path": "skills/skill-adapter/scripts/README.md", + "sha256": "739d8ae706594ea7aaeedfe8836e6a0270d6d2a4a6cf5eb695007347b2731f9f" + }, + { + "path": "skills/skill-adapter/assets/test-data.json", + "sha256": "ac17dca3d6e253a5f39f2a2f1b388e5146043756b05d9ce7ac53a0042eee139d" + }, + { + "path": "skills/skill-adapter/assets/README.md", + "sha256": "c5b578e31c5dba65eaa3ceff45e92b37994734601be678e5c65145caf0181516" + }, + { + "path": "skills/skill-adapter/assets/skill-schema.json", + "sha256": "f5639ba823a24c9ac4fb21444c0717b7aefde1a4993682897f5bf544f863c2cd" + }, + { + "path": "skills/skill-adapter/assets/config-template.json", + "sha256": "0c2ba33d2d3c5ccb266c0848fc43caa68a2aa6a80ff315d4b378352711f83e1c" + } + ], + "dirSha256": "d75e7fc67d7f8f0057f677105f8cb8c4df2ecffad47023f98602512da2cd293f" + }, + "security": { + "scannedAt": null, + "scannerVersion": null, + "flags": [] + } +} \ No newline at end of file diff --git a/skills/skill-adapter/assets/README.md b/skills/skill-adapter/assets/README.md new file mode 100644 index 0000000..aab8505 --- /dev/null +++ b/skills/skill-adapter/assets/README.md @@ -0,0 +1,8 @@ +# Assets + +Bundled resources for trading-strategy-backtester skill + +- [ ] backtest_report_template.html: HTML template for generating backtesting reports with visualizations and performance metrics. +- [ ] optimization_report_template.html: HTML template for generating parameter optimization reports. +- [ ] example_backtest_config.json: Example JSON configuration file for running backtests with different strategies and parameters. +- [ ] example_optimization_config.json: Example JSON configuration file for parameter optimization. diff --git a/skills/skill-adapter/assets/config-template.json b/skills/skill-adapter/assets/config-template.json new file mode 100644 index 0000000..16f1712 --- /dev/null +++ b/skills/skill-adapter/assets/config-template.json @@ -0,0 +1,32 @@ +{ + "skill": { + "name": "skill-name", + "version": "1.0.0", + "enabled": true, + "settings": { + "verbose": false, + "autoActivate": true, + "toolRestrictions": true + } + }, + "triggers": { + "keywords": [ + "example-trigger-1", + "example-trigger-2" + ], + "patterns": [] + }, + "tools": { + "allowed": [ + "Read", + "Grep", + "Bash" + ], + "restricted": [] + }, + "metadata": { + "author": "Plugin Author", + "category": "general", + "tags": [] + } +} diff --git a/skills/skill-adapter/assets/skill-schema.json b/skills/skill-adapter/assets/skill-schema.json new file mode 100644 index 0000000..8dc154c --- /dev/null +++ b/skills/skill-adapter/assets/skill-schema.json @@ -0,0 +1,28 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Claude Skill Configuration", + "type": "object", + "required": ["name", "description"], + "properties": { + "name": { + "type": "string", + "pattern": "^[a-z0-9-]+$", + "maxLength": 64, + "description": "Skill identifier (lowercase, hyphens only)" + }, + "description": { + "type": "string", + "maxLength": 1024, + "description": "What the skill does and when to use it" + }, + "allowed-tools": { + "type": "string", + "description": "Comma-separated list of allowed tools" + }, + "version": { + "type": "string", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "description": "Semantic version (x.y.z)" + } + } +} diff --git a/skills/skill-adapter/assets/test-data.json b/skills/skill-adapter/assets/test-data.json new file mode 100644 index 0000000..f0cd871 --- /dev/null +++ b/skills/skill-adapter/assets/test-data.json @@ -0,0 +1,27 @@ +{ + "testCases": [ + { + "name": "Basic activation test", + "input": "trigger phrase example", + "expected": { + "activated": true, + "toolsUsed": ["Read", "Grep"], + "success": true + } + }, + { + "name": "Complex workflow test", + "input": "multi-step trigger example", + "expected": { + "activated": true, + "steps": 3, + "toolsUsed": ["Read", "Write", "Bash"], + "success": true + } + } + ], + "fixtures": { + "sampleInput": "example data", + "expectedOutput": "processed result" + } +} diff --git a/skills/skill-adapter/references/README.md b/skills/skill-adapter/references/README.md new file mode 100644 index 0000000..7bedfa2 --- /dev/null +++ b/skills/skill-adapter/references/README.md @@ -0,0 +1,8 @@ +# References + +Bundled resources for trading-strategy-backtester skill + +- [ ] trading_strategy_api.md: Documentation for the trading strategy API, including available strategies, parameters, and data formats. +- [ ] performance_metrics.md: Detailed explanations of the performance metrics used in backtesting, such as Sharpe ratio, Sortino ratio, and maximum drawdown. +- [ ] risk_analysis.md: Information on risk analysis techniques, including Value at Risk (VaR) and Conditional Value at Risk (CVaR). +- [ ] data_sources.md: Documentation on available data sources and how to access them. diff --git a/skills/skill-adapter/references/best-practices.md b/skills/skill-adapter/references/best-practices.md new file mode 100644 index 0000000..3505048 --- /dev/null +++ b/skills/skill-adapter/references/best-practices.md @@ -0,0 +1,69 @@ +# Skill Best Practices + +Guidelines for optimal skill usage and development. + +## For Users + +### Activation Best Practices + +1. **Use Clear Trigger Phrases** + - Match phrases from skill description + - Be specific about intent + - Provide necessary context + +2. **Provide Sufficient Context** + - Include relevant file paths + - Specify scope of analysis + - Mention any constraints + +3. **Understand Tool Permissions** + - Check allowed-tools in frontmatter + - Know what the skill can/cannot do + - Request appropriate actions + +### Workflow Optimization + +- Start with simple requests +- Build up to complex workflows +- Verify each step before proceeding +- Use skill consistently for related tasks + +## For Developers + +### Skill Development Guidelines + +1. **Clear Descriptions** + - Include explicit trigger phrases + - Document all capabilities + - Specify limitations + +2. **Proper Tool Permissions** + - Use minimal necessary tools + - Document security implications + - Test with restricted tools + +3. **Comprehensive Documentation** + - Provide usage examples + - Document common pitfalls + - Include troubleshooting guide + +### Maintenance + +- Keep version updated +- Test after tool updates +- Monitor user feedback +- Iterate on descriptions + +## Performance Tips + +- Scope skills to specific domains +- Avoid overlapping trigger phrases +- Keep descriptions under 1024 chars +- Test activation reliability + +## Security Considerations + +- Never include secrets in skill files +- Validate all inputs +- Use read-only tools when possible +- Document security requirements diff --git a/skills/skill-adapter/references/examples.md b/skills/skill-adapter/references/examples.md new file mode 100644 index 0000000..b1d8bd2 --- /dev/null +++ b/skills/skill-adapter/references/examples.md @@ -0,0 +1,70 @@ +# Skill Usage Examples + +This document provides practical examples of how to use this skill effectively. + +## Basic Usage + +### Example 1: Simple Activation + +**User Request:** +``` +[Describe trigger phrase here] +``` + +**Skill Response:** +1. Analyzes the request +2. Performs the required action +3. Returns results + +### Example 2: Complex Workflow + +**User Request:** +``` +[Describe complex scenario] +``` + +**Workflow:** +1. Step 1: Initial analysis +2. Step 2: Data processing +3. Step 3: Result generation +4. Step 4: Validation + +## Advanced Patterns + +### Pattern 1: Chaining Operations + +Combine this skill with other tools: +``` +Step 1: Use this skill for [purpose] +Step 2: Chain with [other tool] +Step 3: Finalize with [action] +``` + +### Pattern 2: Error Handling + +If issues occur: +- Check trigger phrase matches +- Verify context is available +- Review allowed-tools permissions + +## Tips & Best Practices + +- ✅ Be specific with trigger phrases +- ✅ Provide necessary context +- ✅ Check tool permissions match needs +- ❌ Avoid vague requests +- ❌ Don't mix unrelated tasks + +## Common Issues + +**Issue:** Skill doesn't activate +**Solution:** Use exact trigger phrases from description + +**Issue:** Unexpected results +**Solution:** Check input format and context + +## See Also + +- Main SKILL.md for full documentation +- scripts/ for automation helpers +- assets/ for configuration examples diff --git a/skills/skill-adapter/scripts/README.md b/skills/skill-adapter/scripts/README.md new file mode 100644 index 0000000..8c2b48c --- /dev/null +++ b/skills/skill-adapter/scripts/README.md @@ -0,0 +1,8 @@ +# Scripts + +Bundled resources for trading-strategy-backtester skill + +- [ ] backtest_strategy.py: Script to execute backtesting with specified parameters and output results to a file. +- [ ] optimize_parameters.py: Script to perform parameter optimization using a genetic algorithm or similar method. +- [ ] compare_strategies.py: Script to compare the performance of different trading strategies based on historical data. +- [ ] walk_forward_analysis.py: Script to conduct walk-forward analysis to evaluate the robustness of a trading strategy. diff --git a/skills/skill-adapter/scripts/helper-template.sh b/skills/skill-adapter/scripts/helper-template.sh new file mode 100755 index 0000000..c4aae90 --- /dev/null +++ b/skills/skill-adapter/scripts/helper-template.sh @@ -0,0 +1,42 @@ +#!/bin/bash +# Helper script template for skill automation +# Customize this for your skill's specific needs + +set -e + +function show_usage() { + echo "Usage: $0 [options]" + echo "" + echo "Options:" + echo " -h, --help Show this help message" + echo " -v, --verbose Enable verbose output" + echo "" +} + +# Parse arguments +VERBOSE=false + +while [[ $# -gt 0 ]]; do + case $1 in + -h|--help) + show_usage + exit 0 + ;; + -v|--verbose) + VERBOSE=true + shift + ;; + *) + echo "Unknown option: $1" + show_usage + exit 1 + ;; + esac +done + +# Your skill logic here +if [ "$VERBOSE" = true ]; then + echo "Running skill automation..." +fi + +echo "✅ Complete" diff --git a/skills/skill-adapter/scripts/validation.sh b/skills/skill-adapter/scripts/validation.sh new file mode 100755 index 0000000..590af58 --- /dev/null +++ b/skills/skill-adapter/scripts/validation.sh @@ -0,0 +1,32 @@ +#!/bin/bash +# Skill validation helper +# Validates skill activation and functionality + +set -e + +echo "🔍 Validating skill..." + +# Check if SKILL.md exists +if [ ! -f "../SKILL.md" ]; then + echo "❌ Error: SKILL.md not found" + exit 1 +fi + +# Validate frontmatter +if ! grep -q "^---$" "../SKILL.md"; then + echo "❌ Error: No frontmatter found" + exit 1 +fi + +# Check required fields +if ! grep -q "^name:" "../SKILL.md"; then + echo "❌ Error: Missing 'name' field" + exit 1 +fi + +if ! grep -q "^description:" "../SKILL.md"; then + echo "❌ Error: Missing 'description' field" + exit 1 +fi + +echo "✅ Skill validation passed"