What is Backtesting?

Backtesting is the process of testing a trading strategy using historical market data to see how it would have performed in the past. Think of it as a time machine for your trading ideas.

Why Backtesting Matters

Before risking real money, you want to know if your trading strategy actually works. Backtesting helps you:

  • Validate your ideas - Test if your strategy makes money
  • Understand risks - See how much you could lose during bad periods
  • Build confidence - Trust your strategy when markets get volatile
  • Save money - Learn from simulated losses instead of real ones
  • Optimize parameters - Fine-tune your strategy for better results

Important: Past performance doesn't guarantee future results. Backtesting shows what would have happened, not what will happen. Always combine backtesting with other analysis and risk management.

How Backtesting Works

The backtesting process follows these steps:

  1. Define Your Strategy - Set rules for when to buy and sell (e.g., "Buy when RSI is below 30, sell when it's above 70")
  2. Load Historical Data - Get past price and volume data for your chosen stocks
  3. Execute the Strategy - Simulate trades following your rules on historical data
  4. Track Performance - Record all trades, profits, losses, and positions
  5. Calculate Metrics - Analyze returns, risk, win rate, and other key performance indicators
  6. Review and Refine - Adjust your strategy based on results and test again

Backtesting Flow

┌─────────────────┐
│ Define Strategy │  (Your trading rules)
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Load Historical │  (Past price data)
│      Data       │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Execute Trades  │  (Simulate buying/selling)
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Track Positions │  (Monitor profit/loss)
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ Calculate       │  (Analyze performance)
│    Metrics      │
└────────┬────────┘
         │
         ▼
┌─────────────────┐
│ View Results    │  (Make decisions)
└─────────────────┘

Key Concepts

Strategy

A strategy is a set of rules that determine when to buy and sell. It can be as simple as "buy when price drops 5%, sell when it rises 10%" or as complex as combining multiple technical indicators, fundamental data, and sentiment analysis.

Signals

Signals are specific points where your strategy triggers an action. An entry signal tells you when to buy, and an exit signal tells you when to sell.

Risk Management

Rules that protect your capital:

  • Stop Loss - Maximum loss you'll accept (e.g., sell if price drops 2%)
  • Take Profit - Target gain where you'll sell (e.g., sell at 5% profit)
  • Position Sizing - How much money to invest per trade (e.g., 10% of capital)
  • Trailing Stop - Moving stop loss that locks in gains as price rises

Performance Metrics

Key measurements to evaluate your strategy:

  • Total Return - Overall percentage gain or loss
  • Sharpe Ratio - Risk-adjusted returns (higher is better, above 1.0 is good)
  • Max Drawdown - Largest peak-to-trough decline (how bad it got)
  • Win Rate - Percentage of profitable trades
  • Profit Factor - Total gains divided by total losses (above 1.5 is good)

Types of Trading Strategies

Stratify provides 4 template strategies to get you started. Each represents a different trading philosophy:

Momentum Strategy

Follows market trends by buying when prices are rising and selling when they're falling. Uses indicators like RSI and moving averages to identify momentum.

Best for: Trending markets, riding strong price movements

Mean Reversion

Buys when prices drop below average and sells when they return to normal. Based on the idea that prices eventually revert to their mean.

Best for: Range-bound markets, buying dips in quality stocks

Breakout Strategy

Captures new trends by buying when price breaks above recent highs with strong volume. Aims to catch the start of major moves.

Best for: Capturing explosive moves, early trend identification

Sentiment-Based

Combines social media sentiment with technical analysis. Trades when positive buzz aligns with favorable technical signals.

Best for: Event-driven trading, meme stocks, news-sensitive names

Common Backtesting Pitfalls

Avoid these mistakes when backtesting:

Overfitting

Tweaking parameters until they perfectly match historical data. This creates a strategy that only works on past data, not future markets. Test on multiple time periods and stocks.

Look-Ahead Bias

Using information that wouldn't have been available at the time. For example, using tomorrow's closing price to make today's decision. Stratify prevents this automatically.

Ignoring Transaction Costs

Forgetting about commissions, slippage, and spreads. A strategy with many trades might look profitable but lose money after costs. Always include realistic costs.

Too Little Data

Testing on just a few months or only during bull markets. Test on at least 2-3 years including different market conditions (bull, bear, sideways).

Backtesting Best Practices

  • Test on multiple symbols (different sectors, market caps)
  • Include various market conditions (bull, bear, sideways)
  • Use realistic commission and slippage assumptions
  • Always use proper risk management (stop losses, position sizing)
  • Don't over-optimize - simpler strategies often work better
  • Walk-forward test: optimize on past data, test on future data
  • Paper trade before using real money

Ready to Start Backtesting?

Stratify comes with 4 pre-built template strategies so you can start backtesting immediately. No coding required - just configure, test, and analyze.

Run Your First Backtest

Backtest Configuration Options

When running a backtest, you can configure numerous parameters to match your trading style:

Basic Settings

Symbol Selection

Choose which stocks to test:

  • Single symbol: Test one stock at a time for detailed analysis
  • Multiple symbols: Test a portfolio of stocks (comma-separated)
  • From watchlist: Import all symbols from a specific watchlist

Date Range

Test period selection:

  • Start Date: When to begin the backtest (min: 2015-01-01)
  • End Date: When to end (max: yesterday)
  • Recommended: At least 2 years to capture different market conditions

Timeframe

Bar size for analysis:

  • 1d - Daily bars (recommended for swing trading)
  • 1h - Hourly bars (day trading strategies)
  • 15m - 15-minute bars (active trading)
  • 1w - Weekly bars (long-term strategies)

Initial Capital

Starting account balance for the simulation. Default: $100,000. This affects position sizing and number of shares per trade.

Risk Management Parameters

Stop Loss

Maximum loss per trade before automatic exit:

  • Specified as percentage (e.g., 2% = exit if price drops 2%)
  • Or fixed dollar amount (e.g., $500 per trade)
  • Typical range: 1-5% for stocks, 2-10% for volatile assets

Take Profit

Target profit level for automatic exit:

  • Also specified as percentage or dollar amount
  • Typical range: 3-10% (should be at least 1.5x stop loss for positive expectancy)
  • Optional: can rely on strategy exit signals instead

Position Sizing

How much capital to risk per trade:

  • Fixed percentage: Use X% of capital per trade (e.g., 10%)
  • Risk-based: Risk X% per trade based on stop loss distance
  • Fixed shares: Always buy same number of shares
  • Conservative: 5-10% per position, Aggressive: 20-25%

Maximum Positions

Limit concurrent open positions to control overall portfolio risk. Example: max 5 positions means at most 5 stocks held simultaneously.

Trailing Stop (Advanced)

Dynamic stop loss that moves up as price increases, locking in profits. Example: 1% trailing stop means stop loss follows 1% below highest price reached.

Transaction Costs

Commission

Broker fees per trade. Modern brokers: $0. Traditional: $5-10 per trade or 0.005% per share. Default: 0.1%

Slippage

Difference between expected and actual fill price. Typical: 0.05-0.2%. More for illiquid stocks. Default: 0.1%

Important: Always include realistic transaction costs. A strategy with 100 trades/year and 0.2% total costs loses 20% to fees alone!

Understanding Backtest Results

After a backtest completes, you'll see comprehensive performance analytics:

Returns Metrics

Total Return

%

Overall profit/loss: (Final Equity - Initial Capital) / Initial Capital × 100

Example: $100k → $115k = +15% return

CAGR (Compound Annual Growth Rate)

%/year

Annualized return accounting for compounding. More accurate than simple annualized return.

Good: >10%/year • Great: >15%/year

Risk Metrics

Max Drawdown

%

Largest peak-to-trough decline. Measures worst-case loss you'd experience.

Good: <15% • Acceptable: 15-25% • High Risk: >30%

Volatility (Annualized)

%

Standard deviation of returns. Measures consistency of performance.

Low: <15% • Medium: 15-30% • High: >30%

Sharpe Ratio

ratio

Risk-adjusted returns: (Return - Risk-free Rate) / Volatility. Higher is better.

Poor: <1 • Good: 1-2 • Excellent: >2

Sortino Ratio

ratio

Like Sharpe but only penalizes downside volatility. Better measure for asymmetric strategies.

Typically 20-50% higher than Sharpe ratio

Trading Statistics

Total Trades

count

Number of complete buy-sell cycles. More trades = more commission costs but also more opportunities.

Win Rate

%

Percentage of profitable trades. Winning Trades / Total Trades × 100

Good: >50% • Note: Can be profitable with <50% win rate if winners are larger than losers

Profit Factor

ratio

Total gains / Total losses. Must be >1.0 to be profitable.

Acceptable: 1.2-1.5 • Good: 1.5-2.0 • Excellent: >2.0

Average Trade Duration

days

How long positions are held on average. Helps classify strategy type (day trading vs swing vs position).

Result Visualizations

Stratify provides multiple charts to understand strategy performance:

📈 Equity Curve

Shows account value over time. Key insights:

  • Smooth upward curve = consistent returns
  • Jagged with big swings = high volatility
  • Flat periods = drawdowns (underwater periods)
  • Steep drops = major losses to investigate

📉 Drawdown Chart

Shows distance from peak equity. Highlights:

  • Duration of underwater periods
  • Frequency of drawdowns
  • Recovery time after losses

📊 Monthly Returns Heatmap

Grid showing returns for each month. Quickly spot seasonality patterns and consistent/inconsistent months.

📦 Trade Distribution

Histogram of P&L per trade. Shows if you have many small wins/losses or few large ones.

Troubleshooting Common Issues

❌ No Trades Executed

Possible causes:

  • Strategy parameters too strict (RSI never reaches threshold)
  • Insufficient data for indicator calculations (need warmup period)
  • Position sizing too large (not enough capital for even 1 share)
  • Date range too short

Solutions: Relax parameters, extend date range, reduce position size.

❌ Poor Performance (Losing Money)

Check:

  • Are transaction costs too high? (reduce trading frequency)
  • Is stop loss too tight? (getting stopped out too early)
  • Does the strategy fit the market regime? (momentum in trending, reversion in ranging)
  • Is position sizing appropriate?

Try: Different symbols, different time periods, adjusting risk parameters.

❌ Data Gaps or Missing Bars

Causes:

  • Stock wasn't public during part of test period
  • Data source has gaps (low-volume stocks)
  • Market holidays or halts

Solution: Check symbol's listing date, try different symbols, use forward-fill option in settings.

❌ Unrealistic Results (Too Good)

Warning signs:

  • Sharpe ratio > 3 with many trades
  • 100% win rate or close to it
  • No drawdowns

Likely: Look-ahead bias, overfitting, or missing transaction costs. Review strategy logic and costs.

Related Resources