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- Python 3.7+
- pandas, numpy, yfinance, matplotlib (required)
- ta-lib, scipy, scikit-learn (optional, for advanced features)
How to use backtesting-trading-strategies
- 1.Fetch historical data using fetch_data.py with your symbol and desired period
- 2.Run a backtest with backtest.py specifying strategy, symbol, and timeframe
- 3.Review the generated summary metrics, trade log, and equity curve chart in the reports folder
- 4.Optionally run optimize.py with a parameter grid to find best-performing settings
- 5.Adjust strategy parameters based on results and re-test until satisfied with performance
Use cases
- 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
- 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
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.
Yes. Use the --params flag with JSON to specify custom values, or use optimize.py to grid search across parameter ranges.
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.
Use optimize.py with --param-grid to specify ranges for each parameter. It performs grid search and returns the best-performing combination.
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
| 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 {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
| 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
Related skills
More from gracefullight/stock-checker and the wider catalog.

stock-analysis
Analyze stocks and cryptocurrencies with Yahoo Finance data, portfolio tracking, and multi-dimensional scoring.

trading-analysis
Generate institutional-grade investment reports with technical analysis, AI insights, and professional charts for stocks and ETFs.

yahoo-finance
Get stock prices, quotes, fundamentals, earnings, options, dividends, and analyst ratings from Yahoo Finance—no API key required.

adaptive-metrics
Reduce Grafana Cloud Metrics billing by auto-aggregating high-cardinality labels and dropping unused metrics.

admin
Manage Grafana Cloud organizations, stacks, RBAC, SSO, service accounts, and user provisioning.

admission-control
Implement validation and mutation admission handlers for grafana-app-sdk resources.