149 lines
5.5 KiB
Plaintext
149 lines
5.5 KiB
Plaintext
# Enhanced Emotional Damage Strategy - Algorithm Details
|
|
|
|
## Strategy Overview
|
|
The Enhanced Emotional Damage Strategy is an algorithmic trading approach that uses market sentiment (Fear & Greed Index) combined with technical analysis to time market entries and exits. The strategy aims to capitalize on market fear by moving to cash during panic periods and reinvesting in volatile stocks during recovery phases.
|
|
|
|
## Core Algorithm Components
|
|
|
|
### 1. Fear & Greed Index-Based Market Timing
|
|
- **Data Source**: CNN Fear & Greed Index (0-100 scale)
|
|
- **Fear Threshold**: 25 (market panic trigger)
|
|
- **Greed Threshold**: 75 (profit-taking trigger)
|
|
- **Logic**:
|
|
- When F&G < 25: Move to cash (avoid further losses)
|
|
- When F&G recovers > 25: Select volatile stocks (recovery play)
|
|
- When F&G > 75: Move to QQQ (safe haven)
|
|
|
|
### 2. Gradual Transition System (4-Step Process)
|
|
**Critical Fix Applied**: Original algorithm had compounding error creating impossible returns.
|
|
|
|
#### Fixed Implementation:
|
|
```python
|
|
def start_transition(self, date, target_type, stocks=None):
|
|
# Calculate TOTAL funds available for transition at START
|
|
# Store fixed allocation plan to prevent compounding
|
|
|
|
def gradual_transition(self, date, target_type, stocks=None):
|
|
# Execute 1/4 of predetermined allocation each step
|
|
# NO recalculation of total value per step
|
|
```
|
|
|
|
**Transition Types**:
|
|
- **TO_CASH**: Sell all non-QQQ positions over 4 trading days
|
|
- **TO_VOLATILE**: Buy selected volatile stocks with available cash
|
|
- **TO_QQQ**: Sell all positions and buy QQQ over 4 days
|
|
|
|
**Why 4 Steps**: Reduces market impact and slippage from large position changes
|
|
|
|
### 3. Technical Indicator Filtering
|
|
For volatile stock selection, requires 2 out of 3 indicators showing upward trend:
|
|
|
|
#### MACD Golden Cross
|
|
```python
|
|
macd > macd_signal # Current MACD above signal line
|
|
```
|
|
|
|
#### RSI First Derivative Positive
|
|
```python
|
|
current_rsi > previous_rsi # RSI trending upward
|
|
```
|
|
|
|
#### EMA Crossover (5/20 period)
|
|
```python
|
|
ema_5 > ema_20 # Short-term momentum over long-term
|
|
```
|
|
|
|
### 4. Stop-Loss Protection (15% Rule)
|
|
- **Trigger**: Any volatile stock position drops 15% below average purchase price
|
|
- **Action**: Immediately sell position and buy equivalent QQQ shares
|
|
- **Purpose**: Risk management to prevent large losses
|
|
|
|
## State Machine Implementation
|
|
|
|
```
|
|
QQQ_HOLD → [F&G < 25] → FEAR_TRANSITION → CASH_WAIT
|
|
↓ (4 steps)
|
|
CASH_WAIT → [F&G ≥ 25] → GREED_TRANSITION → VOLATILE_STOCKS
|
|
↓ (4 steps) ↓ [F&G > 75]
|
|
QQQ_TRANSITION
|
|
↓ (4 steps)
|
|
QQQ_HOLD
|
|
```
|
|
|
|
## Key Algorithm Fixes Applied
|
|
|
|
### Original Bug: Compounding Error
|
|
```python
|
|
# WRONG (caused 129M% impossible returns):
|
|
total_value = self.calculate_portfolio_value(date)
|
|
target_qqq_value = total_value * step_size # Created money each step!
|
|
```
|
|
|
|
### Fixed Algorithm:
|
|
```python
|
|
# CORRECT (realistic 516% over 17 years):
|
|
def start_transition(self, date, target_type):
|
|
self.transition_cash_pool = calculate_total_available_cash()
|
|
|
|
def gradual_transition(self, date, target_type):
|
|
cash_this_step = self.transition_cash_pool * step_size # Fixed amount
|
|
```
|
|
|
|
## Performance Characteristics
|
|
|
|
### Risk Management Features:
|
|
- **Maximum Drawdown Control**: Move to cash during market panic
|
|
- **Position Sizing**: Equal-weight allocation across selected stocks
|
|
- **Stop-Loss**: 15% maximum loss per position
|
|
- **Gradual Execution**: 4-step transitions reduce market impact
|
|
|
|
### Expected Behavior:
|
|
- **Bull Markets**: Moderate participation via QQQ
|
|
- **Bear Markets**: Cash preservation during panic phases
|
|
- **Recovery Phases**: Aggressive positioning in volatile stocks
|
|
- **Overheated Markets**: Defensive shift back to QQQ
|
|
|
|
## Technical Implementation Details
|
|
|
|
### Database Dependencies:
|
|
- `fear_greed_index`: CNN F&G historical data
|
|
- `{ticker}`: Individual stock OHLCV + technical indicators
|
|
- `qqq`: QQQ ETF historical prices (to be added)
|
|
- `fear_greed_data.spy_close`: SPY benchmark data
|
|
|
|
### Performance Metrics Calculated:
|
|
- Total Return, Annual Return, Sharpe Ratio
|
|
- Maximum Drawdown and recovery periods
|
|
- Win/Loss ratio and trade frequency
|
|
- Correlation with market benchmarks
|
|
|
|
## Known Limitations & Future Improvements
|
|
|
|
### Current Issues:
|
|
1. **QQQ Data**: Currently using SPY prices for QQQ trades (unrealistic)
|
|
2. **Network Dependency**: Requires external data feeds for F&G index
|
|
3. **Market Regime Changes**: May not adapt to structural market shifts
|
|
|
|
### Planned Enhancements:
|
|
1. **Real QQQ Data**: Download actual QQQ historical prices
|
|
2. **Dynamic Thresholds**: Adjust F&G thresholds based on market volatility
|
|
3. **Sector Rotation**: Add sector-specific volatile stock selection
|
|
4. **Risk Scaling**: Position size based on volatility estimates
|
|
|
|
## Backtest Results (After Bug Fix)
|
|
- **Period**: 2007-2025 (17+ years)
|
|
- **Total Return**: 516.8% (vs impossible 129M% before fix)
|
|
- **Annual Return**: ~11% (realistic performance)
|
|
- **Max Drawdown**: TBD (pending QQQ data fix)
|
|
- **Trade Count**: 4 major transitions (simple strategy behavior)
|
|
|
|
## Files Structure:
|
|
```
|
|
strategy/emotional-damage/
|
|
├── backtest_emotional_damage_enhanced_v2.py # Main strategy (fixed)
|
|
├── generate_enhanced_pdf_report.py # Report generator
|
|
├── enhanced_emotional_damage_strategy_report_*.pdf # Results
|
|
└── enhanced-emotional-damage.txt # This documentation
|
|
```
|
|
|
|
**Status**: Strategy logic fixed, awaiting real QQQ data for complete validation. |