PluginBench
Skill
Review
Audit score 70

backtesting-trading-strategies

gracefullight/stock-checker

Backtest trading strategies against historical data with performance metrics and parameter optimization.

What is backtesting-trading-strategies?

Validate crypto and traditional trading strategies using historical price data before risking real capital. Calculates risk-adjusted returns (Sharpe, Sortino, Calmar), max drawdown, and trade statistics. Use when testing strategy viability, comparing approaches, or optimizing parameters.

  • Run backtests on 8 pre-built strategies (SMA, EMA, RSI, MACD, Bollinger, Breakout, Mean Reversion, Momentum)
  • Calculate comprehensive performance metrics including Sharpe ratio, Sortino ratio, max drawdown, and VaR
  • Generate equity curves and trade-by-trade analysis logs
  • Optimize strategy parameters via grid search to find best-performing combinations
  • Support both crypto (BTC-USD, ETH-USD) and traditional stock symbols
  • Cache historical data locally to avoid repeated downloads

How to install backtesting-trading-strategies

npx skills add https://github.com/gracefullight/stock-checker --skill backtesting-trading-strategies
Prerequisites
  • Python 3.7+
  • pandas, numpy, yfinance, matplotlib (required)
  • ta-lib, scipy, scikit-learn (optional, for advanced features)
Claude Code
Cursor
Windsurf
Cline

How to use backtesting-trading-strategies

  1. 1.Fetch historical data using fetch_data.py with your symbol and desired period
  2. 2.Run a backtest with backtest.py specifying strategy, symbol, and timeframe
  3. 3.Review the generated summary metrics, trade log, and equity curve chart in the reports folder
  4. 4.Optionally run optimize.py with a parameter grid to find best-performing settings
  5. 5.Adjust strategy parameters based on results and re-test until satisfied with performance

Use cases

Good for
  • Test a moving average crossover strategy on Bitcoin over the past 2 years to validate signal quality
  • Compare RSI reversal vs MACD strategies on the same stock to determine which has better risk-adjusted returns
  • Optimize SMA fast/slow period parameters to find the combination with highest Sharpe ratio
  • Validate a breakout strategy before deploying it with real capital
  • Analyze trade statistics (win rate, profit factor, max consecutive losses) to assess strategy robustness
Who it's for
  • Traders evaluating new strategies before live trading
  • Quantitative analysts comparing strategy performance across assets
  • Risk managers assessing drawdown and volatility characteristics
  • Developers building automated trading systems who need historical validation

backtesting-trading-strategies FAQ

What data sources are supported?

yfinance is the default provider, supporting stocks, ETFs, and crypto pairs (e.g., BTC-USD, ETH-USD). Data is cached locally to avoid repeated downloads.

Can I backtest with custom parameters?

Yes. Use the --params flag with JSON to specify custom values, or use optimize.py to grid search across parameter ranges.

What do the performance metrics mean?

Sharpe Ratio measures risk-adjusted return (target >1.5). Sortino focuses on downside risk. Max Drawdown shows the largest peak-to-trough decline. Profit Factor is gross profit divided by gross loss.

How do I optimize strategy parameters?

Use optimize.py with --param-grid to specify ranges for each parameter. It performs grid search and returns the best-performing combination.

What commissions and slippage are assumed?

Default is 0.1% commission and 0.05% slippage per trade, configurable in config/settings.yaml.

Full instructions (SKILL.md)

Source of truth, from gracefullight/stock-checker.


name: backtesting-trading-strategies description: | Backtest crypto and traditional trading strategies against historical data. Calculates performance metrics (Sharpe, Sortino, max drawdown), generates equity curves, and optimizes strategy parameters. Use when user wants to test a trading strategy, validate signals, or compare approaches. Trigger with phrases like "backtest strategy", "test trading strategy", "historical performance", "simulate trades", "optimize parameters", or "validate signals". allowed-tools: Read, Write, Edit, Grep, Glob, Bash(python:*) version: 2.0.0 author: Jeremy Longshore jeremy@intentsolutions.io license: MIT

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:

pip install pandas numpy yfinance matplotlib

Optional for advanced features:

pip install ta-lib scipy scikit-learn

Instructions

Step 1: Fetch Historical Data

python {baseDir}/scripts/fetch_data.py --symbol BTC-USD --period 2y --interval 1d

Data is cached to {baseDir}/data/{symbol}_{interval}.csv for reuse.

Step 2: Run Backtest

Basic backtest with default parameters:

python {baseDir}/scripts/backtest.py --strategy sma_crossover --symbol BTC-USD --period 1y

Advanced backtest with custom parameters:

# Example: backtest with specific date range
python {baseDir}/scripts/backtest.py \
  --strategy rsi_reversal \
  --symbol ETH-USD \
  --period 1y \
  --capital 10000 \
  --params '{"period": 14, "overbought": 70, "oversold": 30}'

Step 3: Analyze Results

Results are saved to {baseDir}/reports/ including:

  • *_summary.txt - Performance metrics
  • *_trades.csv - Trade log
  • *_equity.csv - Equity curve data
  • *_chart.png - Visual equity curve

Step 4: Optimize Parameters

Find optimal parameters via grid search:

python {baseDir}/scripts/optimize.py \
  --strategy sma_crossover \
  --symbol BTC-USD \
  --period 1y \
  --param-grid '{"fast_period": [10, 20, 30], "slow_period": [50, 100, 200]}'

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 {baseDir}/config/settings.yaml:

data:
  provider: yfinance
  cache_dir: ./data

backtest:
  default_capital: 10000
  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 {baseDir}/references/errors.md for common issues and solutions.

Examples

See {baseDir}/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