# Spearman Correlation

The **Spearman rank correlation** measures the **monotonic relationship** between two variables.

It is robust to:
- Non-normality  
- Outliers  
- Non-linear relationships  

---

# 📌 When to Use
Use Spearman when:
- Data is ordinal OR not normally distributed  
- Relationship is monotonic but not linear  
- Outliers make Pearson unreliable  

---

# 📐 Formula (Simple)

Compute Pearson correlation on the **ranks**:

$$
\rho = \text{Pearson}( \text{rank}(X), \text{rank}(Y) )
$$

For no ties, an alternative formula:

$$
\rho = 1 - \frac{6 \sum d_i^2}{n(n^2 - 1)}
$$

where $ d_i $ = difference in ranks.

---

# 🔬 Numerical Example

Data:

| X | Y |
|---|---|
| 10 | 20 |
| 20 | 25 |
| 30 | 40 |

Ranks:

| X | Rank X | Y | Rank Y |
|---|--------|---|--------|
|10 | 1      |20 | 1      |
|20 | 2      |25 | 2      |
|30 | 3      |40 | 3      |

Difference in ranks = 0 → perfect monotonic relationship:

$$
\rho = 1
$$

---

# 🧪 Assumptions
- Variables must be at least **ordinal**
- Relationship monotonic

---

# 🧠 Interpretation
- ρ = 1: perfect increasing monotonic  
- ρ = -1: perfect decreasing monotonic  
- ρ = 0: no monotonic trend  

---

# 📎 Advanced Math
Spearman is equivalent to Pearson on the ranked data.

---

# 🐍 Python Implementation

SciPy:
https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.spearmanr.html

Used in StatInsight:
```python
from scipy.stats import spearmanr
rho, p = spearmanr(x, y)
```

# 📎 Related Tests
[Pearson Correlation](correlation/pearson.md)

[Partial Spearman Correlation](correlation/partial-spearman.md)