dasycaus 1.0.1
Dynamic Asymmetric Causality Tests for Time Series Analysis
License: MIT
Requires Python: >=3.8
Keywords: causality, granger-causality, asymmetric-causality, time-series, econometrics, var-model, bootstrap, hatemi-j

# DASYCAUS: Dynamic Asymmetric Causality Tests

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A Python library for **Dynamic Asymmetric and Symmetric Causality Tests** in time series analysis, based on the methodology developed by Hatemi-J (2012, 2021).

## 📚 Overview

DASYCAUS provides a comprehensive implementation of:

- **Static Symmetric Causality Tests** (Granger causality with bootstrap)
- **Static Asymmetric Causality Tests** (testing positive and negative components separately)
- **Dynamic Symmetric Causality Tests** (time-varying causality using subsamples)
- **Dynamic Asymmetric Causality Tests** (time-varying asymmetric causality)

The library implements leverage-adjusted bootstrap procedures for accurate critical value computation and supports various information criteria for optimal lag selection.

## 🔬 Theoretical Background

This library is based on the following key papers:

1. **Hatemi-J, A. (2021).** "Dynamic Asymmetric Causality Tests with an Application." *arXiv:2106.07612*.
   
2. **Hatemi-J, A. (2012).** "Asymmetric Causality Tests with an Application." *Empirical Economics*, 43(1), 447-456.

3. **Hacker, S. and Hatemi-J, A. (2006).** "Tests for causality between integrated variables using asymptotic and bootstrap distributions: theory and application." *Applied Economics*, 38(13), 1489-1500.

4. **Hacker, S. and Hatemi-J, A. (2012).** "A bootstrap test for causality with endogenous lag length choice: theory and application in finance." *Journal of Economic Studies*, 39(2), 144-160.

## 🚀 Installation

### From PyPI (when published)

```bash
pip install dasycaus
```

### From Source

```bash
git clone https://github.com/merwanroudane/dasycaus.git
cd dasycaus
pip install -e .
```

### With Optional Dependencies

```bash
# For plotting capabilities
pip install dasycaus[plotting]

# For data export features
pip install dasycaus[export]

# For all features
pip install dasycaus[full]
```

## 📋 Requirements

**Core Dependencies:**
- Python >= 3.8
- NumPy >= 1.20.0
- SciPy >= 1.7.0

**Optional Dependencies:**
- matplotlib >= 3.5.0 (for plotting)
- pandas >= 1.3.0 (for data export)

## 🔧 Quick Start

### Example 1: Static Symmetric Causality Test

```python
import numpy as np
from dasycaus import symmetric_causality_test

# Load your data (T x n matrix)
data = np.loadtxt('your_data.txt')

# Conduct symmetric causality test
results = symmetric_causality_test(
    data=data,
    maxlags=8,
    integration_order=1,
    info_criterion='hjc',
    bootstrap_sims=1000,
    significance_levels=[0.05, 0.10]
)

print(f"Test Statistic: {results['test_statistic']:.4f}")
print(f"Optimal Lag: {results['optimal_lag']}")
print(f"Reject H0 at 5%: {results['reject_null'][0.05]}")
```

### Example 2: Static Asymmetric Causality Test

```python
from dasycaus import asymmetric_causality_test

# Test positive components
results_positive = asymmetric_causality_test(
    data=data,
    maxlags=8,
    component='positive',  # or 'negative'
    integration_order=1,
    info_criterion='hjc',
    bootstrap_sims=1000
)

print(f"Positive Component Test Statistic: {results_positive['test_statistic']:.4f}")
```

### Example 3: Dynamic Symmetric Causality Test

```python
from dasycaus import dynamic_symmetric_causality_test
from dasycaus.utils import plot_dynamic_causality, create_summary_table

# Conduct dynamic test
results = dynamic_symmetric_causality_test(
    data=data,
    maxlags=8,
    integration_order=1,
    info_criterion='hjc',
    bootstrap_sims=1000,
    subsample_method='recursive'  # or 'rolling'
)

# Print summary
print(create_summary_table(results))

# Plot results
plot_dynamic_causality(
    results,
    significance_level=0.05,
    title="Dynamic Causality Test Results",
    save_path="dynamic_test.png"
)
```

### Example 4: Dynamic Asymmetric Causality Test

```python
from dasycaus import dynamic_asymmetric_causality_test

# Test dynamic asymmetric causality for positive components
results = dynamic_asymmetric_causality_test(
    data=data,
    maxlags=8,
    component='positive',
    integration_order=1,
    info_criterion='hjc',
    bootstrap_sims=1000,
    subsample_method='recursive'
)

# Visualize
plot_dynamic_causality(results, significance_level=0.10)
```

## 📊 Key Features

### 1. Data Transformation
Transform integrated variables into cumulative positive and negative components:

```python
from dasycaus import transform_to_cumulative_components

positive_components = transform_to_cumulative_components(
    data, 
    component='positive',
    include_trend=True
)

negative_components = transform_to_cumulative_components(
    data,
    component='negative',
    include_trend=True
)
```

### 2. Lag Selection
Multiple information criteria supported:

```python
from dasycaus import select_optimal_lag, compare_criteria

# Single criterion
lag_info = select_optimal_lag(
    data,
    maxlags=12,
    info_criterion='hjc'  # 'aic', 'aicc', 'sbc', 'hqc', 'hjc'
)

# Compare all criteria
comparison = compare_criteria(data, maxlags=12)
print(comparison['optimal_lags'])
```

### 3. Bootstrap Critical Values
Leverage-adjusted bootstrap for accurate inference:

```python
from dasycaus import bootstrap_critical_values

cv = bootstrap_critical_values(
    data,
    lag_order=4,
    integration_order=1,
    num_simulations=1000,
    significance_level=0.05,
    leverage_adjustment=True
)
```

### 4. Subsample Methods

**Recursive Method:** Starts with minimum size, adds one observation each iteration
```python
subsample_method='recursive'
```

**Rolling Window Method:** Fixed window size, rolls forward
```python
subsample_method='rolling'
```

## 📈 Application Example: Oil Prices and Stock Market

Replicating the analysis from Hatemi-J (2021):

```python
import numpy as np
from dasycaus import dynamic_asymmetric_causality_test
from dasycaus.utils import plot_dynamic_causality

# Load data (log of oil prices and stock prices)
data = np.loadtxt('oil_stock_data.txt')  # 1990-2020

# Test if oil price increases cause stock market increases
results_positive = dynamic_asymmetric_causality_test(
    data=data,
    maxlags=4,
    component='positive',
    integration_order=1,
    info_criterion='hjc',
    bootstrap_sims=1000,
    subsample_method='recursive'
)

# Test if oil price decreases cause stock market decreases
results_negative = dynamic_asymmetric_causality_test(
    data=data,
    maxlags=4,
    component='negative',
    integration_order=1,
    info_criterion='hjc',
    bootstrap_sims=1000,
    subsample_method='recursive'
)

# Visualize results
plot_dynamic_causality(
    results_positive,
    significance_level=0.10,
    title="H0: Oil Price Increase Does Not Cause Stock Market Increase"
)
```

## 📖 Documentation

### Main Functions

#### `symmetric_causality_test`
Conducts static Granger causality test with bootstrap critical values.

**Parameters:**
- `data`: (T, n) array of time series data
- `maxlags`: Maximum lag order to consider
- `integration_order`: Integration order (0, 1, or 2)
- `info_criterion`: 'aic', 'aicc', 'sbc', 'hqc', or 'hjc'
- `bootstrap_sims`: Number of bootstrap simulations
- `significance_levels`: List of significance levels
- `random_seed`: Seed for reproducibility

**Returns:** Dictionary with test statistic, optimal lag, critical values, and rejection decisions.

#### `asymmetric_causality_test`
Tests causality in positive or negative components separately.

**Additional Parameters:**
- `component`: 'positive' or 'negative'
- `include_trend`: Whether to include deterministic trend

#### `dynamic_symmetric_causality_test`
Time-varying causality test using subsamples.

**Additional Parameters:**
- `subsample_method`: 'recursive' or 'rolling'

**Returns:** Dictionary with subsample results, test ratios, and rejection patterns.

#### `dynamic_asymmetric_causality_test`
Time-varying asymmetric causality test.

Combines data transformation with dynamic testing.

## 🧪 Testing

Run the test suite:

```bash
pytest tests/ -v --cov=dasycaus
```

## 📝 Citation

If you use this library in your research, please cite:

```bibtex
@software{roudane2024dasycaus,
  author = {Roudane, Merwan},
  title = {DASYCAUS: Dynamic Asymmetric Causality Tests in Python},
  year = {2024},
  url = {https://github.com/merwanroudane/dasycaus},
}
```

And the original methodology papers:

```bibtex
@article{hatemi2012asymmetric,
  title={Asymmetric causality tests with an application},
  author={Hatemi-J, Abdulnasser},
  journal={Empirical Economics},
  volume={43},
  number={1},
  pages={447--456},
  year={2012}
}

@article{hatemi2021dynamic,
  title={Dynamic Asymmetric Causality Tests with an Application},
  author={Hatemi-J, Abdulnasser},
  journal={arXiv preprint arXiv:2106.07612},
  year={2021}
}
```

## 🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/AmazingFeature`)
3. Commit your changes (`git commit -m 'Add some AmazingFeature'`)
4. Push to the branch (`git push origin feature/AmazingFeature`)
5. Open a Pull Request

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 👤 Author

**Dr. Merwan Roudane**
- Email: merwanroudane920@gmail.com
- GitHub: [@merwanroudane](https://github.com/merwanroudane)

## 🙏 Acknowledgments

This library is a Python implementation of the methodology developed by:
- **Prof. Abdulnasser Hatemi-J** (UAE University)
- **Dr. Alan Mustafa** (IEEE)

Original GAUSS code: DASCT01 - Gauss Module for Estimating the Dynamic Asymmetric and Symmetric Causality Tests

## 📚 References

- Hatemi-J, A. (2003). A new method to choose optimal lag order in stable and unstable VAR models. *Applied Economics Letters*, 10(3), 135-137.
- Toda, H.Y. and Yamamoto, T. (1995). Statistical inference in vector autoregressions with possibly integrated processes. *Journal of Econometrics*, 66, 225-250.
- Phillips, P.C., Shi, S., and Yu, J. (2015). Testing for multiple bubbles: historical episodes of exuberance and collapse in the S&P 500. *International Economic Review*, 56(4), 1043-1078.

## 🔍 Keywords

causality, Granger causality, asymmetric causality, dynamic causality, time series, econometrics, VAR model, bootstrap, Hatemi-J, oil prices, stock market, financial econometrics

---

**Note:** This is an independent implementation for educational and research purposes. For the original GAUSS implementation, please contact the original authors.