# Premium Analyzer: Practical Examples & Debugging

## Real-World Example Scenarios

### Scenario 1: Perfect Premium Opportunity ✅ (SHOULD ALERT)

```
Time: 11:30 AM (Good time window)
Premium: 45 paisa
Historical average: 120 paisa
Percentile: 8% (Bottom 8% - VERY CHEAP)
Z-Score: -2.8 (2.8 sigma below mean)
OI: 85,000 (up from 72,000 - BUILDING)
OI Z-Score: +1.2 (accelerating upward)
Volume: 150 (above 65th percentile)
Days to Expiry: 5 (Safe, not DTE trap)

Result: ✅ ALERT FIRES
Reason: All filters pass - cheap premium with institutional buying
Score: 85/100
Win Probability: ~70%
Recommendation: BUY (good entry with support)
```

### Scenario 2: Cheap But No OI Support ❌ (SHOULD NOT ALERT)

```
Time: 11:30 AM
Premium: 48 paisa
Percentile: 9% (Very cheap)
Z-Score: -2.6 (Statistically cheap)
OI: 72,000 (down from 85,000 - DECLINING)
OI Z-Score: -0.3 (decelerating, OI being withdrawn)
Volume: 140 (above 60th percentile)
Days to Expiry: 5

Result: ❌ NO ALERT
Reason: Fails OI filter (min Z-score 0.5, got -0.3)
Explanation: Premium is cheap but OI declining = no institutional support
         Traders exiting positions = high risk of further decline
Recommendation: SKIP (wait for OI to stabilize)
```

### Scenario 3: Building OI But Premium Not Cheap ❌ (SHOULD NOT ALERT)

```
Time: 11:30 AM
Premium: 150 paisa
Percentile: 55% (Average, NOT cheap)
Z-Score: +0.8 (slightly above average)
OI: 92,000 (up from 78,000 - BUILDING)
OI Z-Score: +1.5 (accelerating)
Volume: 160 (high)
Days to Expiry: 5

Result: ❌ NO ALERT
Reason: Fails percentile filter (needs < 10%, got 55%)
Explanation: OI is building but premium is expensive, not cheap
         Buying pressure on expensive premium = trap
Recommendation: SKIP (sellers still winning)
```

### Scenario 4: Cheap During Market Open ❌ (SHOULD NOT ALERT)

```
Time: 9:30 AM (Within 30 min market open exclusion)
Premium: 42 paisa
Percentile: 7% (Very cheap)
Z-Score: -2.9 (Very cheap)
OI: 88,000 (up from 75,000)
OI Z-Score: +1.3
Volume: 155
Days to Expiry: 5

Result: ❌ NO ALERT
Reason: Fails market open filter
Explanation: At 9:30 AM, Kite data still catching up, volatility extreme
         This cheap premium often reverses by 9:45
Recommendation: SKIP (wait until 9:45+ for real opportunity)
```

### Scenario 5: Perfect Opportunity at Close ❌ (SHOULD NOT ALERT)

```
Time: 3:25 PM (Within 15 min close exclusion)
Premium: 46 paisa
Percentile: 9% (Very cheap)
Z-Score: -2.7
OI: 91,000 (up from 82,000)
OI Z-Score: +1.2
Volume: 145
Days to Expiry: 5

Result: ❌ NO ALERT
Reason: Fails market close filter
Explanation: Premium cheap at 3:25 but likely reverses at open next day
         Trapped positions often unwind overnight
Recommendation: SKIP (close is dangerous for intraday buys)
```

---

## Debugging Strategies

### Strategy 1: Check What's Being Filtered

Enable debug logging and see rejection reasons:

```bash
# Count rejections by reason
grep "$(date +%Y-%m-%d)" storage/logs/laravel.log | \
  grep "Premium opportunity rejected" | \
  awk -F': ' '{print $2}' | \
  cut -d'-' -f1 | \
  sort | uniq -c | sort -rn
```

**Expected output**:
```
     45 premium_not_cheap
     32 oi_not_building
     18 market_open_volatility
     12 low_volume
      8 insufficient_samples
      3 too_close_to_expiry
      1 premium_extreme
```

**What this tells you**:
- If `premium_not_cheap` is high: Loosen `PREMIUM_PERCENTILE_LOW` (8→12)
- If `oi_not_building` is high: Loosen `PREMIUM_MIN_OI_Z_SCORE` (0.5→0.2)
- If `low_volume` is high: Loosen `PREMIUM_MIN_VOLUME_PCT` (0.60→0.55)
- If `market_open_volatility` is high: This is correct filtering!

### Strategy 2: Analyze Successful Alerts

```bash
# Show all successful alerts today
grep "$(date +%Y-%m-%d)" storage/logs/laravel.log | grep "Premium alert created"
```

**Expected output**:
```
Premium alert created (CE): Score=82.45, Confidence=91.2%
Premium alert created (PE): Score=75.33, Confidence=87.5%
Premium alert created (CE): Score=88.10, Confidence=94.7%
```

**Good signs**:
- Score > 70 (premium is very cheap)
- Confidence > 85% (all filters validated)
- 3-8 alerts per trading day (right frequency)

### Strategy 3: Manual Verification

Pick one alert and verify manually:

```php
// In tinker or test
$metric = PremiumMetric::latest()->first();
$pair = $metric->trackedPair;

dump([
    'pair' => $pair->name,
    'side' => $metric->side,
    'percentile' => $metric->percentile,
    'z_score' => $metric->z_score,
    'oi_z_score' => $metric->z_oi,
    'volume_pct' => $metric->volume_percentile,
    'last_premium' => $metric->last_premium,
    'mean_premium' => $metric->mean_premium,
    'last_oi' => $metric->last_oi,
    'sample_count' => $metric->sample_count,
    'days_to_expiry' => $pair->expiry->diffInDays(now()),
]);
```

---

## Tuning Process (Step by Step)

### Day 1-3: Baseline
- Use CONSERVATIVE settings
- Count daily alerts
- Note win/loss ratio
- Document rejection patterns

### Day 4-6: First Adjustment
- If alerts < 3/day: Loosen percentile (10→12)
- If alerts > 12/day: Tighten Z-score (2.5→2.8)
- If win rate < 50%: Increase OI requirement (0.5→0.7)
- If win rate > 80%: Keep settings, scale position size

### Day 7+: Fine Tuning
- Adjust one parameter at a time
- Wait 3 days to see impact
- Never adjust all at once (can't tell what worked)
- Keep a log: https://docs.google.com/sheets/

---

## Common Mistakes & Fixes

### Mistake 1: Loosening All Thresholds at Once
❌ **Bad**: Lower Z, lower percentile, lower OI, lower volume all at once
✅ **Good**: Lower one parameter, wait 3 days, evaluate, then adjust next

### Mistake 2: Chasing Alerts
❌ **Bad**: Getting 2 alerts, loosening filters to get 20 alerts
✅ **Good**: 5 quality alerts beat 50 mediocre alerts

### Mistake 3: Ignoring Time Filters
❌ **Bad**: Disabling market open exclusion to catch "early movers"
✅ **Good**: Early moves in first 30 min are often reversals

### Mistake 4: Ignoring OI Direction
❌ **Bad**: "Percentile is perfect, why do I keep losing?"
✅ **Good**: Check if OI is building (rising) or declining

### Mistake 5: Not Adjusting for Expiry Week
❌ **Bad**: Using same thresholds all month
✅ **Good**: In expiry week, loosen slightly (DTE changes behavior)

---

## Performance Benchmarks

### By Time of Day

```
9:15-9:45   (Market Open)
  Alerts: Many (filtered by 30-min exclusion)
  Win Rate: ~45% (opening volatility)

9:45-12:00  (Morning Session)
  Alerts: 40-60% of daily total
  Win Rate: ~65% (best time to trade)

12:00-2:30  (Afternoon Session)
  Alerts: 20-30% of daily total
  Win Rate: ~60% (steady, slow)

2:30-3:30   (Late Afternoon)
  Alerts: 10-20% of daily total
  Win Rate: ~55% (tapering)

3:30-3:45   (Market Close)
  Alerts: Filtered by 15-min exclusion
  Win Rate: ~40% (closing chaos)
```

**Best time to trade**: **9:45 AM - 12:00 PM** (morning session)

### By Days to Expiry

```
5+ DTE
  Alerts: Many
  Win Rate: ~70% (stable premium behavior)
  Best for: 2-5 day holds

3-4 DTE
  Alerts: Moderate
  Win Rate: ~65% (slight gamma acceleration)
  Best for: 1-2 day holds

2 DTE
  Alerts: Few (filtered by min DTE)
  Win Rate: ~60% (gamma accelerating)
  Best for: Intraday

1 DTE
  Alerts: Blocked (min 2 DTE)
  Win Rate: ~40% (gamma trap)
  Best for: Scalping only
```

---

## Q&A: Common Questions

**Q: Why is cheap premium being filtered out?**
A: Usually because OI is declining (institutional sellers winning). In that case, avoid the trade.

**Q: Should I lower PREMIUM_MIN_OI_Z_SCORE to get more trades?**
A: No! Low OI is where most losses happen. Better to skip some trades than take bad ones.

**Q: What if my win rate is 50% but alerts are 10/day?**
A: You have too many alerts. Tighten filters (higher Z-score, lower percentile).

**Q: Can I trade during market open?**
A: Possible but not recommended. First 30 min = 2% OI daily moves = gamma trap.

**Q: Should I trade different parameters for CE vs PE?**
A: Yes! If PE is naturally cheaper, use higher Z threshold for PE.

**Q: How often should I change parameters?**
A: Once per week. More frequent = can't measure impact. Less frequent = missing seasonal shifts.

---

## Files to Monitor

1. **View rejections**: `tail -f storage/logs/laravel.log | grep "Premium opportunity rejected"`
2. **View alerts**: `tail -f storage/logs/laravel.log | grep "Premium alert created"`
3. **Check metrics DB**: `SELECT * FROM premium_metrics WHERE created_at > DATE_SUB(NOW(), INTERVAL 1 DAY);`
4. **Backtest**: Compare timestamp of alert vs actual premium 5 mins later

---

## Next Steps

1. ✅ Copy conservative settings to `.env`
2. ✅ Enable `PREMIUM_ALERT_DEBUG=true`
3. ✅ Monitor logs for 3 days
4. ✅ Count alerts and win rates
5. ✅ Adjust ONE parameter
6. ✅ Repeat for 1 week
7. ✅ Document your optimal config
