PROTECTED SOURCE SCRIPT

SPY Downside Risk - Bond Flow Indicator (Daily)

16
## **SPY Downside Risk - Bond Flow Indicator**

### 📊 **Overview**

A professional bond market risk monitoring indicator that assesses SPY (S&P 500 ETF) downside risk by tracking Treasury yield spreads and credit spreads. The indicator provides two complementary display modes for comprehensive market analysis.

---

### 🎯 **Key Features**

#### **Mode 1: Spreads Analysis**
Monitor critical fixed-income risk indicators:

- **10Y-2Y Treasury Spread**
- 🔵 Blue Line (> 20bp): Normal economic expansion
- 🟠 Orange Line (0-20bp): Flight-to-safety sentiment emerging
- 🔴 Red Line (< 0bp): **Yield curve inversion - Recession warning**

- **HY-IG Credit Spread** (High Yield - Investment Grade)
- 🟣 Purple Line: Credit spread widening - Rising default risk
- 🟢 Green Line: Credit spread tightening - Risk appetite improving

#### **Mode 2: Bond ETFs Capital Flow**
Track capital movements across four major bond ETFs:

- **SHY** (🔴 Red): 1-3 Year Treasury - Short-term safety
- **TLT** (🟠 Orange): 20+ Year Treasury - Long-term safety
- **LQD** (🟡 Yellow): Investment Grade Bonds - Quality credit
- **HYG** (🔵 Blue): High Yield Bonds - Risk appetite

---

### 🔧 **Input Parameters**

| Parameter | Default | Description |
|-----------|---------|-------------|
| **Display Mode** | Spreads | Choose between "Spreads" or "Bond ETFs" view |
| **ROC Period** | 10 | Rate of change period (for Bond ETFs mode smoothing) |
| **10Y-2Y Threshold** | 20 bp | Spread narrowing threshold indicating safe-haven flows |
| **VIX Filter Level** | 18 | Volatility threshold for heightened market stress |

---

### 📈 **How to Use**

#### **Yield Curve Inversion Signal**
When 10Y-2Y spread inverts (< 0bp):
- Historically precedes recession within 6-24 months
- Equity markets may face correction in 3-12 months
- Consider defensive positioning (bonds, gold, utilities)

#### **Credit Spread Expansion**
When HY-IG spread rapidly widens:
- Corporate default risk increasing
- Capital flowing from risky assets to safety
- Potential equity market pullback ahead

#### **Capital Flow Analysis**
- **SHY ⬆️ + HYG ⬇️** = Risk-off mode, equity pressure mounting
- **HYG ⬆️ + SHY ⬇️** = Risk-on sentiment, bullish for equities
- **TLT surge** = Long rates falling, economic slowdown expected
- **LQD + HYG divergence** = Credit quality differentiation

---

### 📊 **Real-Time Debug Table**

Upper-right corner displays key metrics:

**Spreads Mode:**
- **10Y-2Y Spread**: Current yield curve spread (basis points)
- **Credit Spread**: HY-IG spread (basis points)
- **VIX**: Market volatility index

**Bond ETFs Mode:**
- **SHY Flow**: Short-term Treasury momentum (%)
- **HYG Flow**: High-yield bond momentum (%)
- **VIX**: Market volatility index

**Color Coding:**
- 🔴 Red = High risk / Inverted
- 🟠 Orange = Caution / Elevated
- 🔵 Blue/Gray = Normal conditions

---

### ⚠️ **Trading Signals**

#### **High Risk Scenarios**
1. **Yield curve inverted** (Red line < 0) + **VIX > 18** (Orange)
- Action: Reduce equity exposure, increase cash/bonds

2. **Credit spread widening** + **HYG Flow negative**
- Action: Avoid high-yield debt, favor quality bonds

3. **SHY Flow positive** + **SPY declining**
- Action: Flight-to-safety confirmed, defensive positioning

#### **Bullish Scenarios**
1. **Steep yield curve** (Blue line > 50bp) + **HYG Flow > 3%**
- Action: Risk-on environment, equity allocation appropriate

2. **Credit spread tightening** + **Low VIX** (< 15)
- Action: Favorable credit conditions, growth exposure

---

### 🔔 **Alert System**

**Built-in Alert:**
- **Treasury Spread Inversion Alert**: Triggers when 10Y-2Y spread crosses below 0

**How to Set Up:**
1. Click "Create Alert" in TradingView
2. Select condition: "Treasury Spread Inversion Alert"
3. Configure notification preferences

---

### 📚 **Data Sources**

**Treasury Yields** - Federal Reserve Economic Data (FRED):
- `DGS2`: 2-Year Treasury Constant Maturity Rate
- `DGS10`: 10-Year Treasury Constant Maturity Rate

**Credit Spreads** - FRED:
- `BAMLC0A1CAAAEY`: ICE BofA US Corporate Index Option-Adjusted Spread
- `BAMLH0A0HYM2`: ICE BofA US High Yield Index Option-Adjusted Spread

**ETF Data** - AMEX/NASDAQ:
- iShares 1-3 Year Treasury Bond ETF (SHY)
- iShares 20+ Year Treasury Bond ETF (TLT)
- iShares iBoxx $ Investment Grade Corporate Bond ETF (LQD)
- iShares iBoxx $ High Yield Corporate Bond ETF (HYG)

**Volatility** - CBOE:
- VIX Index (Volatility Index)

**Update Frequency**: Daily (FRED data typically 1-2 day lag)

---

### 💡 **Best Practices**

1. **Timeframe**: Use on **Daily charts** for optimal signal quality
2. **Confirmation**: Combine with SPY price action, volume, and momentum indicators
3. **Risk Management**: Signals are early warnings - adjust positions gradually
4. **Mode Switching**: Toggle between modes weekly to understand both spread dynamics and flow patterns
5. **Historical Context**: Review past inversion periods (2000, 2007, 2019) for signal validation

---

### 📖 **Interpretation Guide**

#### **Recession Probability Matrix**

| 10Y-2Y Spread | Credit Spread | VIX | Risk Level |
|---------------|---------------|-----|------------|
| < -20bp | Widening | > 25 | 🔴 Very High |
| -20bp to 0 | Widening | > 18 | 🟠 High |
| 0-20bp | Stable | 15-18 | 🟡 Moderate |
| > 20bp | Tightening | < 15 | 🟢 Low |

#### **Lead Times (Historical Average)**
- Yield curve inversion → Recession: **12-18 months**
- Credit spread surge → Equity peak: **3-6 months**
- Safe-haven flows → Volatility spike: **1-4 weeks**

---

### 🎓 **Educational Notes**

**Why Monitor Treasury Spreads?**
- Long-term rates reflect growth expectations
- Short-term rates reflect Fed policy
- Inversion = Market expects Fed to cut rates (recession ahead)

**Why Track Credit Spreads?**
- Measures corporate borrowing stress
- Leading indicator of credit cycle turns
- High correlation with equity risk premiums

**Why Bond ETF Flows Matter?**
- Real-time capital allocation signals
- Faster than spread movements
- Shows risk sentiment shifts

---

### ⚙️ **Technical Specifications**

- **Version**: PineScript v5
- **Type**: Indicator (Non-overlay)
- **Calculation**: Daily timeframe only
- **Lookback Period**: 10 bars (customizable for ETF mode)

---

### 🚨 **Risk Disclaimer**

**IMPORTANT NOTICES:**

1. **Historical Performance**: Past yield curve inversions don't guarantee future recession timing
2. **False Signals**: Brief inversions (<30 days) may not indicate recession
3. **Data Lag**: FRED economic data has 1-2 business day delay
4. **Complementary Tool**: Use alongside fundamental and technical analysis
5. **Not Financial Advice**: For educational and research purposes only

**This indicator does not:**
- Provide specific buy/sell signals
- Guarantee trading profits
- Replace professional financial advice
- Account for individual risk tolerance

---

### 📞 **Support & Updates**

- **Questions**: Contact via TradingView private message
- **Bug Reports**: Describe issue with screenshot and chart settings
- **Feature Requests**: Suggestions welcome for future versions

---

### 📋 **Version History**

**v1.0** (December 2025)
- Initial release
- Dual-mode display (Spreads + Bond ETFs)
- Real-time debug table
- Yield curve inversion alert
- VIX filter integration

---

### 📄 **License**

**Protected Script** - Source code is not publicly available. Authorized users only.

---

**DISCLAIMER**: This indicator is provided "as-is" for educational purposes. Trading and investing involve substantial risk of loss. Always conduct your own research and consult with a licensed financial advisor before making investment decisions.

---

**© 2025 | SPY Downside Risk Indicator | All Rights Reserved**

Aviso legal

As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.