backtesting-trading-strategies
A backtesting framework for validating trading strategies with performance metrics and parameter optimization.
Install
mkdir -p .claude/skills/backtesting-trading-strategies && curl -L -o skill.zip "https://agentskills.codes/api/skills/download/1163" && unzip -o skill.zip -d .claude/skills/backtesting-trading-strategies && rm skill.zipInstalls to .claude/skills/backtesting-trading-strategies
Activation
This is the description your AI agent reads to decide when to run this skill — the better it matches your request, the more reliably it fires.
Backtest crypto and traditional trading strategies against historicalKey capabilities
- →Fetch historical market data for backtesting
- →Run backtests with 8 pre-built trading strategies
- →Calculate performance metrics like Sharpe and Sortino Ratios
- →Optimize strategy parameters using grid search
- →Generate equity curve visualizations
- →Analyze trade-by-trade results
How it works
The skill fetches historical data, applies a chosen trading strategy, simulates trades, and calculates performance and risk metrics. It can also optimize strategy parameters through grid search.
Inputs & outputs
When to use backtesting-trading-strategies
- →Backtest a trading strategy against history
- →Calculate strategy Sharpe and Sortino ratios
- →Optimize strategy parameters with grid search
- →Compare different trading approaches
About this skill
Backtesting Trading Strategies
Overview
Validate trading strategies against historical data before risking real capital. This skill provides a complete backtesting framework with 8 built-in strategies, comprehensive performance metrics, and parameter optimization.
Key Features:
- 8 pre-built trading strategies (SMA, EMA, RSI, MACD, Bollinger, Breakout, Mean Reversion, Momentum)
- Full performance metrics (Sharpe, Sortino, Calmar, VaR, max drawdown)
- Parameter grid search optimization
- Equity curve visualization
- Trade-by-trade analysis
Prerequisites
Install required dependencies:
set -euo pipefail
pip install pandas numpy yfinance matplotlib
Optional for advanced features:
set -euo pipefail
pip install ta-lib scipy scikit-learn
Instructions
-
Fetch historical data (cached to
${CLAUDE_SKILL_DIR}/data/for reuse):python ${CLAUDE_SKILL_DIR}/scripts/fetch_data.py --symbol BTC-USD --period 2y --interval 1d -
Run a backtest with default or custom parameters:
python ${CLAUDE_SKILL_DIR}/scripts/backtest.py --strategy sma_crossover --symbol BTC-USD --period 1y python ${CLAUDE_SKILL_DIR}/scripts/backtest.py \ --strategy rsi_reversal \ --symbol ETH-USD \ --period 1y \ --capital 10000 \ # 10000: 10 seconds in ms --params '{"period": 14, "overbought": 70, "oversold": 30}' -
Analyze results saved to
${CLAUDE_SKILL_DIR}/reports/-- includes*_summary.txt(performance metrics),*_trades.csv(trade log),*_equity.csv(equity curve data), and*_chart.png(visual equity curve). -
Optimize parameters via grid search to find the best combination:
python ${CLAUDE_SKILL_DIR}/scripts/optimize.py \ --strategy sma_crossover \ --symbol BTC-USD \ --period 1y \ --param-grid '{"fast_period": [10, 20, 30], "slow_period": [50, 100, 200]}' # HTTP 200 OK
Output
Performance Metrics
| Metric | Description |
|---|---|
| Total Return | Overall percentage gain/loss |
| CAGR | Compound annual growth rate |
| Sharpe Ratio | Risk-adjusted return (target: >1.5) |
| Sortino Ratio | Downside risk-adjusted return |
| Calmar Ratio | Return divided by max drawdown |
Risk Metrics
| Metric | Description |
|---|---|
| Max Drawdown | Largest peak-to-trough decline |
| VaR (95%) | Value at Risk at 95% confidence |
| CVaR (95%) | Expected loss beyond VaR |
| Volatility | Annualized standard deviation |
Trade Statistics
| Metric | Description |
|---|---|
| Total Trades | Number of round-trip trades |
| Win Rate | Percentage of profitable trades |
| Profit Factor | Gross profit divided by gross loss |
| Expectancy | Expected value per trade |
Example Output
================================================================================
BACKTEST RESULTS: SMA CROSSOVER
BTC-USD | [start_date] to [end_date]
================================================================================
PERFORMANCE | RISK
Total Return: +47.32% | Max Drawdown: -18.45%
CAGR: +47.32% | VaR (95%): -2.34%
Sharpe Ratio: 1.87 | Volatility: 42.1%
Sortino Ratio: 2.41 | Ulcer Index: 8.2
--------------------------------------------------------------------------------
TRADE STATISTICS
Total Trades: 24 | Profit Factor: 2.34
Win Rate: 58.3% | Expectancy: $197.17
Avg Win: $892.45 | Max Consec. Losses: 3
================================================================================
Supported Strategies
| Strategy | Description | Key Parameters |
|---|---|---|
sma_crossover | Simple moving average crossover | fast_period, slow_period |
ema_crossover | Exponential MA crossover | fast_period, slow_period |
rsi_reversal | RSI overbought/oversold | period, overbought, oversold |
macd | MACD signal line crossover | fast, slow, signal |
bollinger_bands | Mean reversion on bands | period, std_dev |
breakout | Price breakout from range | lookback, threshold |
mean_reversion | Return to moving average | period, z_threshold |
momentum | Rate of change momentum | period, threshold |
Configuration
Create ${CLAUDE_SKILL_DIR}/config/settings.yaml:
data:
provider: yfinance
cache_dir: ./data
backtest:
default_capital: 10000 # 10000: 10 seconds in ms
commission: 0.001 # 0.1% per trade
slippage: 0.0005 # 0.05% slippage
risk:
max_position_size: 0.95
stop_loss: null # Optional fixed stop loss
take_profit: null # Optional fixed take profit
Error Handling
See ${CLAUDE_SKILL_DIR}/references/errors.md for common issues and solutions.
Examples
See ${CLAUDE_SKILL_DIR}/references/examples.md for detailed usage examples including:
- Multi-asset comparison
- Walk-forward analysis
- Parameter optimization workflows
Files
| File | Purpose |
|---|---|
scripts/backtest.py | Main backtesting engine |
scripts/fetch_data.py | Historical data fetcher |
scripts/strategies.py | Strategy definitions |
scripts/metrics.py | Performance calculations |
scripts/optimize.py | Parameter optimization |
Resources
- yfinance - Yahoo Finance data
- TA-Lib - Technical analysis library
- QuantStats - Portfolio analytics
When not to use it
- →When real capital is at risk without prior validation
- →When required dependencies like pandas, numpy, and yfinance are not installed
- →When historical data is unavailable for the desired symbol and period
Prerequisites
Limitations
- →Requires specific Python libraries to be installed
- →Performance metrics are based on historical data and do not guarantee future results
- →Default configuration uses yfinance for data, which may have limitations
How it compares
This skill provides a structured framework with pre-built strategies and complete metrics for validating trading approaches against historical data, unlike manual, ad-hoc testing.
Compared to similar skills
backtesting-trading-strategies side by side with the closest alternatives in the catalog.
| Skill | Installs | Updated | Safety | Difficulty |
|---|---|---|---|---|
| backtesting-trading-strategies (this skill) | 10 | 27d | Review | Intermediate |
| backtesting-frameworks | 17 | 2mo | No flags | Advanced |
| quant-analyst | 103 | 2mo | No flags | Advanced |
| stock-analyzer | 71 | 2mo | Review | Beginner |
Try saying
Example prompts that trigger this skill in your AI assistant.
More by jeremylongshore
View all by jeremylongshore →You might also like
backtesting-frameworks
wshobson
Build robust backtesting systems for trading strategies with proper handling of look-ahead bias, survivorship bias, and transaction costs. Use when developing trading algorithms, validating strategies, or building backtesting infrastructure.
quant-analyst
zenobi-us
Expert quantitative analyst specializing in financial modeling, algorithmic trading, and risk analytics. Masters statistical methods, derivatives pricing, and high-frequency trading with focus on mathematical rigor, performance optimization, and profitable strategy development.
stock-analyzer
FrancyJGLisboa
Provides comprehensive technical analysis for stocks and ETFs using RSI, MACD, Bollinger Bands, and other indicators. Activates when user requests stock analysis, technical indicators, trading signals, or market data for specific ticker symbols.
google-analytics
davila7
Analyze Google Analytics data, review website performance metrics, identify traffic patterns, and suggest data-driven improvements. Use when the user asks about analytics, website metrics, traffic analysis, conversion rates, user behavior, or performance optimization.
pair-trade-screener
tradermonty
Statistical arbitrage tool for identifying and analyzing pair trading opportunities. Detects cointegrated stock pairs within sectors, analyzes spread behavior, calculates z-scores, and provides entry/exit recommendations for market-neutral strategies. Use when user requests pair trading opportunities, statistical arbitrage screening, mean-reversion strategies, or market-neutral portfolio construction. Supports correlation analysis, cointegration testing, and spread backtesting.
risk-metrics-calculation
wshobson
Calculate portfolio risk metrics including VaR, CVaR, Sharpe, Sortino, and drawdown analysis. Use when measuring portfolio risk, implementing risk limits, or building risk monitoring systems.