## Pyreto

A Python library for tail risk management inspired by Nassim Taleb's approach to fat tails and Karl Popper's philosophy of science. Pyreto provides tools for fitting non-Gaussian distributions to financial returns and calculating robust risk metrics.

### Features

- **Non-Gaussian Distribution Fitting**: Fit heavy-tailed distributions to return data
- **Expected Shortfall (ES)**: Calculate conditional VaR for better tail risk measurement
- **Multiple Models**: Support for Alpha-Stable, Student's T, and Normal-Inverse Gaussian distributions
- **Visual Proof**: Generate plots that visually demonstrate fat tails compared to normal distribution
- **Model Comparison**: Compare multiple distributions and their risk metrics

### Installation

```bash
pip install -e .
```

Or for development:

```bash
pip install -e ".[dev]"
```

### Quick Start

#### Basic Usage

```python
import pyreto
import numpy as np

# Generate sample returns (heavy-tailed)
np.random.seed(42)
returns = np.random.standard_t(3, 1000) * 0.01  # Student's T with 3 df

# Fit all available models
result = pyreto.dist.fit(returns)

# Print comprehensive summary
result['print_summary']()

# Access individual models
student_model = result['models']['student_t']
print(student_model.summary())

# Plot comparison
fig = result['comparison'].plot_comparison()
fig.show()
```

#### Loading from CSV

```python
import pyreto

# Load from CSV file
result = pyreto.dist.fit('returns.csv', column='daily_returns')

# Generate all plots
plots = result['create_plots']()
plots['comparison'].savefig('comparison.png')
```

#### Working with Individual Distributions

```python
from pyreto.distributions import StudentT
import numpy as np

# Create returns data
returns = np.random.standard_t(3, 1000) * 0.01

# Fit Student's T distribution
model = StudentT(returns)
model.fit()

# Calculate risk metrics
var_5 = model.var(0.05)   # 5% VaR
es_5 = model.es(0.05)     # 5% Expected Shortfall
var_1 = model.var(0.01)   # 1% VaR
es_1 = model.es(0.01)     # 1% Expected Shortfall

print(f"5% VaR: {var_5:.4f}")
print(f"5% ES: {es_5:.4f}")
print(f"1% VaR: {var_1:.4f}")
print(f"1% ES: {es_1:.4f}")

# Generate diagnostic plot
fig = model.plot_fit()
fig.show()
```

### Available Distributions

1. **Alpha-Stable** (`alpha_stable`)
   - Most general stable distribution
   - Parameters: alpha (stability), beta (skewness), c (scale), mu (location)
   - Can model extremely heavy tails

2. **Student's T** (`student_t`)
   - Heavy-tailed with finite variance (df > 2)
   - Parameters: df (degrees of freedom), loc, scale
   - Good balance of flexibility and tractability

3. **Normal-Inverse Gaussian** (`nig`)
   - Flexible heavy-tailed distribution
   - Parameters: alpha, beta, delta, mu
   - Analytically tractable

### Philosophy

Pyreto is built on two philosophical pillars:

1. **Taleb's Fat Tail Awareness**: Traditional risk management assumes normal distributions, which dramatically underestimates tail risk. Pyreto uses heavy-tailed distributions that better capture extreme events.

2. **Popper's Falsifiability**: Models should be testable and falsifiable. Pyreto provides visual and statistical tools to validate whether models adequately capture tail behavior.

### Function Reference

#### Main Function

```python
pyreto.dist.fit(data, column=None, models=None, alpha_levels=None)
```

**Parameters:**
- `data`: str (CSV path), pd.DataFrame, np.ndarray, or list of returns
- `column`: Column name for DataFrame/CSV (optional)
- `models`: List of models to fit (default: all available)
- `alpha_levels`: Significance levels for VaR/ES (default: [0.05, 0.01])

**Returns:**
- Dictionary with models, comparison, plots, and analysis tools

#### Distribution Methods

All distribution classes inherit from `DistributionFitter`:

- `fit()`: Fit distribution parameters
- `pdf(x)`: Probability density function
- `cdf(x)`: Cumulative distribution function
- `ppf(q)`: Percent point (inverse CDF)
- `var(alpha)`: Value at Risk
- `es(alpha)`: Expected Shortfall
- `plot_fit()`: Diagnostic plots
- `summary()`: Text summary

### Example Output

```
======================================================================
PYRETO TAIL RISK ANALYSIS - NON-GAUSSIAN DISTRIBUTION FIT
======================================================================

Data Summary:
  Number of observations: 1000
  Mean: 0.000156
  Std Dev: 0.011234
  Skewness: 0.023456
  Kurtosis: 6.789012

  Jarque-Bera Test:
    Statistic: 245.67
    P-value: 0.000000
    Normal? No (α=0.05)

======================================================================
FATTED MODELS:
======================================================================

student_t:
  df: 3.123456
  loc: 0.000234
  scale: 0.008765

alpha_stable:
  alpha: 1.456789
  beta: 0.034567
  c: 0.005432
  mu: 0.000123

nig:
  alpha: 1.234567
  beta: 0.045678
  delta: 0.006789
  mu: 0.000234

======================================================================
RISK METRICS COMPARISON:
======================================================================
           VaR_5%    ES_5%   VaR_1%    ES_1%
Model                                      
student_t  -0.0213  -0.0345  -0.0456  -0.0789
alpha_stable -0.0245 -0.0421 -0.0589 -0.1245
nig         -0.0221 -0.0367 -0.0489 -0.0898

======================================================================
FAT TAIL EVIDENCE:
======================================================================

student_t:
  95% VaR is 1.42x Normal VaR
  99% VaR is 2.15x Normal VaR
  → SIGNIFICANT FAT TAILS DETECTED
```

### License

MIT License - see LICENSE file for details.

### Contributing

This library follows Popperian principles - all models and assumptions should be falsifiable. When contributing:

1. Provide tests that can falsify your implementation
2. Include visual diagnostics
3. Document limitations and assumptions
4. Add examples that demonstrate both success and failure cases
