BA

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.zip

Installs 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 historical
69 charsno explicit “when” trigger
Intermediate

Key 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

You give it
Trading strategy, symbol, historical period, and optional parameters
You get back
Performance metrics summary, trade log, equity curve data, and chart visualization

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

  1. 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
    
  2. 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}'
    
  3. 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).

  4. 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

MetricDescription
Total ReturnOverall percentage gain/loss
CAGRCompound annual growth rate
Sharpe RatioRisk-adjusted return (target: >1.5)
Sortino RatioDownside risk-adjusted return
Calmar RatioReturn divided by max drawdown

Risk Metrics

MetricDescription
Max DrawdownLargest peak-to-trough decline
VaR (95%)Value at Risk at 95% confidence
CVaR (95%)Expected loss beyond VaR
VolatilityAnnualized standard deviation

Trade Statistics

MetricDescription
Total TradesNumber of round-trip trades
Win RatePercentage of profitable trades
Profit FactorGross profit divided by gross loss
ExpectancyExpected 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

StrategyDescriptionKey Parameters
sma_crossoverSimple moving average crossoverfast_period, slow_period
ema_crossoverExponential MA crossoverfast_period, slow_period
rsi_reversalRSI overbought/oversoldperiod, overbought, oversold
macdMACD signal line crossoverfast, slow, signal
bollinger_bandsMean reversion on bandsperiod, std_dev
breakoutPrice breakout from rangelookback, threshold
mean_reversionReturn to moving averageperiod, z_threshold
momentumRate of change momentumperiod, 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

FilePurpose
scripts/backtest.pyMain backtesting engine
scripts/fetch_data.pyHistorical data fetcher
scripts/strategies.pyStrategy definitions
scripts/metrics.pyPerformance calculations
scripts/optimize.pyParameter optimization

Resources

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

pip install pandas numpy yfinance matplotlibpip install ta-lib scipy scikit-learn (optional)

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.

SkillInstallsUpdatedSafetyDifficulty
backtesting-trading-strategies (this skill)1027dReviewIntermediate
backtesting-frameworks172moNo flagsAdvanced
quant-analyst1032moNo flagsAdvanced
stock-analyzer712moReviewBeginner

Try saying

Example prompts that trigger this skill in your AI assistant.

More by jeremylongshore

View all by jeremylongshore

analyzing-logs

jeremylongshore

Analyze application logs to detect performance issues, identify error patterns, and improve stability by extracting key insights.

14123

ollama-setup

jeremylongshore

Configure auto-configure Ollama when user needs local LLM deployment, free AI alternatives, or wants to eliminate hosted API costs. Trigger phrases: "install ollama", "local AI", "free LLM", "self-hosted AI", "replace OpenAI", "no API costs". Use when appropriate context detected. Trigger with relevant phrases based on skill purpose.

1167

generating-database-seed-data

jeremylongshore

Process this skill enables AI assistant to generate realistic test data and database seed scripts for development and testing environments. it uses faker libraries to create realistic data, maintains relational integrity, and allows configurable data volumes. u... Use when working with databases or data models. Trigger with phrases like 'database', 'query', or 'schema'.

1033

cursor-codebase-indexing

jeremylongshore

Execute set up and optimize Cursor codebase indexing. Triggers on "cursor index setup", "codebase indexing", "index codebase", "cursor semantic search". Use when working with cursor codebase indexing functionality. Trigger with phrases like "cursor codebase indexing", "cursor indexing", "cursor".

885

testing-mobile-apps

jeremylongshore

Execute mobile app testing on iOS and Android devices/simulators. Use when performing specialized testing. Trigger with phrases like "test mobile app", "run iOS tests", or "validate Android functionality".

810

generating-trading-signals

jeremylongshore

Generate trading signals using technical indicators (RSI, MACD, Bollinger Bands, etc.). Combines multiple indicators into composite signals with confidence scores. Use when analyzing assets for trading opportunities or checking technical indicators. Trigger with phrases like "get trading signals", "check indicators", "analyze for entry", "scan for opportunities", "generate buy/sell signals", or "technical analysis".

725

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.

17126

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.

103355

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.

71214

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.

43193

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.

1198

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.

881

Search skills

Search the agent skills registry