mcpField
B
backtesting-trading-strategies

backtesting-trading-strategies

github.com/jeremylongshoreData & databases2.9k4.7k installsUpdated 2d ago
Repository

About backtesting-trading-strategies

A backtesting skill for quantitative researchers and strategy developers that simulates trading strategies on historical data. It includes built-in strategies, performance and risk metrics, parameter grid search, and chart outputs; results describe past simulations, not future performance.

Key features

  1. 01Includes eight built-in strategies
  2. 02Calculates performance and risk metrics
  3. 03Optimizes parameters with grid search
  4. 04Produces equity curve charts
  5. 05Exports trade-by-trade analysis

Use cases

  1. 01Compare historical strategy results
  2. 02Review drawdowns and risk metrics
  3. 03Search for parameter combinations
  4. 04Inspect trades and equity curves

Install

Copy the command and run it in a terminal.

$npx skills add https://github.com/jeremylongshore/tons-of-skills-marketplace --skill backtesting-trading-strategies

After installing, type/backtesting-trading-strategiesin Claude Code to confirm it loaded.

Bundled files

References and scripts installed along with SKILL.md.

commands/
backtest-strategy.md
compare-strategies.md
optimize-parameters.md
walk-forward.md
config/
settings.yaml
references/
errors.md
examples.md
implementation.md
scripts/
backtest.py
fetch_data.py
metrics.py
optimize.py
strategies.py
tests/
test_metrics.py
test_strategies.py

Details

From the project README

Backtesting Trading Strategies

Overview

Simulate trading strategies against historical data. Results describe a historical simulation, not expected future performance. The framework includes 8 built-in strategies, the metrics listed below, and parameter optimization.

Key Features:

  • 8 pre-built trading strategies (SMA, EMA, RSI, MACD, Bollinger, Breakout, Mean Reversion, Momentum)
  • Performance metrics (Sharpe, Sortino, Calmar, VaR, max drawdown)
  • Parameter grid search optimization
  • Equity curve visualization
  • Trade-by-trade analysis

Prerequisites

Before invoking this skill, the user installs the required dependencies in the Python environment used for the simulation:

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 \
      --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]}'
    

Output

Performance Metrics
MetricDescription
Total ReturnOverall percentage gain/loss
CAGRCompound annual growth rate
Sharpe RatioHistorical risk-adjusted return
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; N/A with no observed losses
ExpectancyExpected value per trade
Example Output

Figure-free layout; actual values depend on the input series, fees, slippage, strategy and parameters. Do not present these placeholders as measured returns.

HISTORICAL SIMULATION: [strategy]
[symbol] | [start_date] to [end_date]
Total Return: [computed] | Max Drawdown: [computed]
Sharpe Ratio: [computed] | Win Rate: [computed]
Total Trades: [observed] | Profit Factor: [computed or N/A]

Profit factor is unavailable when no losing trades were observed, including a zero-trade run or a single winning/breakeven trade. A single losing trade yields zero gross profit divided by its loss; this is not evidence of strategy quality. Zero/one-trade samples cannot establish performance, and optimization is an in-sample historical comparison rather than a forecast.

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 # Starting simulated capital in quote-currency units
  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

Use Read to inspect references/errors.md for common issues and solutions.

Examples

See 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

Comments

Markdown supported