Trading Strategy Enhancements¶
Based on: "We Backtested a Viral Trading Strategy" article insights Date: October 10, 2025 Status: โ Phase 1 & 2 Complete
๐ฏ What We Implemented¶
Phase 1: Enhanced Strategy Features โ ¶
1. ATR (Average True Range) Calculations¶
- Added
calculate_atr()- Measures stock volatility - Added
calculate_atr_percent()- Normalizes ATR as % of price - Purpose: Adapt risk management to each stock's unique volatility
2. ATR-Based Stop Losses (Replaces Fixed %)¶
Before:
stop_loss = current_price * 0.95 # Fixed -5% for all stocks
take_profit = current_price * 1.10 # Fixed +10%
After:
stop_loss = current_price - (3 * atr) # Adapts to volatility
take_profit = current_price + (3 * atr) # Symmetric risk/reward
Why This Matters: - Volatile stocks (CABA, biotech) get wider stops โ less likely to get stopped out on noise - Stable stocks (NVDA, big cap) get tighter stops โ better capital preservation - 3x ATR = article's recommendation for robust risk/reward
3. 200-Day SMA Trend Filter โจ¶
New Entry Requirement:
if current_price > sma_200:
# Long-term uptrend โ
else:
# SKIP - Don't fight long-term downtrend โ
Impact: - Article showed this was #2 most important feature for ML model - Prevents buying stocks in long-term bear markets - Simple, proven, works across all market conditions
4. Volatility Entry Filter (ATR%)โจ¶
New Entry Requirement:
atr_pct = (atr / current_price) * 100
if atr_pct < 5.0:
# Calm market โ
- Good time to enter
else:
# Too volatile โ - Wait for stability
Impact: - Article showed ATR% was #1 most important feature (highest importance!) - Avoids entering during chaotic, unpredictable periods - Waits for "calm before the breakout"
Phase 2: Walk-Forward Backtesting โ ¶
New Tool: backtest_walk_forward.py¶
The Problem (From Article): - Original strategy claimed 5,394% profit - Turned out to be curve-fitted to historical data - When tested properly โ Near-zero profit
The Solution: Walk-Forward Analysis
Traditional Backtest (WRONG):
Train on ALL data (2020-2025) โ Optimize โ Test on SAME data
Result: Overfitted, unrealistic
Walk-Forward (CORRECT):
Period 1: Train on 2020-2021 โ Test on Jan-Mar 2022 โ
Period 2: Train on 2020-2022 โ Test on Apr-Jun 2022 โ
Period 3: Train on 2021-2022 โ Test on Jul-Sep 2022 โ
... rolls forward through time
Result: Tests on UNSEEN future data โ Realistic
Key Features: - Configurable train/test windows (default: 12 months train, 3 months test) - Triple-Barrier Method for trade exits (3x ATR profit/stop, 30-day time limit) - Tracks win rate, average return, exit reasons - Prevents overfitting by design
Usage:
# Backtest QQQ from 2020-2025
uv run python3 tools/backtest_walk_forward.py QQQ --start-year 2020 --end-year 2025
# Backtest SPY with custom windows
uv run python3 tools/backtest_walk_forward.py SPY --train-months 6 --test-months 2
๐ Enhanced Momentum Strategy (Example)¶
Entry Criteria (All Must Be True)¶
| Criterion | Threshold | Purpose | Source |
|---|---|---|---|
| Price > SMA(200) | Long-term uptrend | Don't fight trend | Article #2 feature |
| ATR% < 5.0% | Not too volatile | Enter during calm | Article #1 feature |
| RSI > 60 | Strong momentum | Ride the wave | Classic indicator |
| Price > SMA(20) | Short-term uptrend | Confirm direction | Classic indicator |
| 7-Day Gain > 5% | Recent strength | Hot stock filter | Momentum signal |
Exit Rules (ATR-Based)¶
- Stop Loss: Entry - (3 ร ATR)
- Take Profit: Entry + (3 ร ATR)
- Risk/Reward: Always 1:1 (symmetric)
Example: CABA @ $3.00, ATR = $0.20 - Entry: $3.00 - Stop: $2.40 (-20%, adapts to biotech volatility) - Target: $3.60 (+20%)
Example: NVDA @ $190, ATR = $5.00 - Entry: $190 - Stop: $175 (-7.9%, tighter for stable stock) - Target: $205 (+7.9%)
๐ Before vs. After Comparison¶
| Component | Before | After | Improvement |
|---|---|---|---|
| Stop Loss | Fixed -5% | 3ร ATR (dynamic) | Adapts to volatility |
| Take Profit | Fixed +10% | 3ร ATR (dynamic) | Symmetric risk/reward |
| Trend Filter | 20-day SMA only | 200-day SMA required | Avoid long-term downtrends |
| Volatility Check | None | ATR% < 5% | Enter during calm markets |
| Backtesting | None | Walk-forward | Prevent overfitting |
| Win Definition | Hope for +10% | Triple-barrier method | Systematic exits |
๐ How to Use the Enhanced System¶
1. Interactive Testing (Paper Account)¶
Select option 1 (Momentum Strategy) โ You'll now see: - 200-SMA filter check โจ - ATR% volatility filter โจ - ATR-based stop/target prices โจ - Risk/reward ratio
2. Walk-Forward Backtest (Validate Strategy)¶
# Test enhanced momentum on QQQ (2020-2025)
uv run python3 tools/backtest_walk_forward.py QQQ
# Test on your favorite stock
uv run python3 tools/backtest_walk_forward.py NVDA --start-year 2022
This shows TRUE out-of-sample performance (not curve-fitted!).
3. Check CABA Trailing Stop¶
Your CABA trailing stop monitor is still running:
๐ Expected Improvements¶
Based on the article's findings:
Risk Management¶
- Before: One-size-fits-all stops โ frequent unnecessary stop-outs
- After: ATR-based stops โ fewer false stops, better risk/reward
Win Rate¶
- Before: No trend filter โ bought stocks in downtrends โ low win rate
- After: 200-SMA filter โ only uptrends โ higher win rate expected
Drawdowns¶
- Before: Entered during volatile spikes โ caught in whipsaws
- After: ATR% filter โ entered during calm โ smoother equity curve
Realistic Performance¶
- Before: No backtesting โ guessing if strategy works
- After: Walk-forward testing โ KNOW it works (or doesn't!)
๐งช Next Steps (Optional)¶
Phase 3: Machine Learning (If Walk-Forward Shows Promise)¶
If backtests show positive results, we can:
- Feature Engineering
- Normalize all indicators (MACD/price, RSI/100, etc.)
- Create distance metrics (price vs SMA200)
-
Add MACD histogram, volume indicators
-
ML Model Training
- Use LightGBM (article's choice)
- Train on historical walk-forward data
-
Learn complex patterns human rules miss
-
Triple-Barrier Labeling
- Systematically label "good" vs "bad" trades
- Model learns what defines a winning setup
But: Only do this if Phase 2 backtests show the rule-based strategy has an edge!
๐ Key Lessons from the Article¶
1. Always Walk-Forward Test¶
"Optimizing on full dataset is curve-fitting. It's a lie."
2. Volatility Is King¶
"ATR% was the #1 most important feature. The model learned to be selective."
3. Don't Fight the Trend¶
"200-SMA filter was #2. Never trade against the primary trend."
4. Accept Lower Returns for Lower Risk¶
"376% out-of-sample beats 791% in-sample because it's REAL."
5. Systematic Beats Discretionary¶
"Triple-barrier method removes emotion from exits."
๐ Files Modified/Created¶
Modified:¶
tools/strategy_tester.py- Enhanced with ATR, SMA200, volatility filters
Created:¶
tools/backtest_walk_forward.py- Walk-forward backtesting frameworkSTRATEGY_ENHANCEMENTS.md- This documentTRAILING_STOP_GUIDE.md- CABA trailing stop documentation (earlier today)
Running:¶
- CABA 15% trailing stop monitor (background process)
โ๏ธ Configuration¶
All enhancements use these defaults (can be customized):
- ATR Period: 14 days
- ATR Multiplier for Stops: 3x
- ATR% Volatility Threshold: 5.0%
- Long-term Trend: 200-day SMA
- Short-term Trend: 20-day SMA
- Walk-Forward Train: 12 months
- Walk-Forward Test: 3 months
- Triple-Barrier Time Limit: 30 days
Status: โ Ready to test! Recommendation: Run walk-forward backtest on QQQ or SPY to validate the enhanced strategy works historically.