Metadata-Version: 2.4
Name: forecaster-ai
Version: 0.2.4
Summary: Enterprise-grade time series forecasting package with ARIMA, Prophet, and LSTM models
Author-email: Surya Tripathi <suryaec1099@gmail.com>
License: MIT
Project-URL: Homepage, https://github.com/surya08084/forecaster-ai
Project-URL: Documentation, https://forecasting-package.readthedocs.io
Project-URL: Repository, https://github.com/surya08084/forecaster-ai
Project-URL: Bug Tracker, https://github.com/surya08084/forecaster-ai/issues
Keywords: forecasting,time-series,machine-learning,arima,prophet,lstm,mlops
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: scikit-learn>=1.3.0
Requires-Dist: statsmodels>=0.14.0
Requires-Dist: prophet>=1.1.0
Requires-Dist: torch>=2.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: fastapi>=0.100.0
Requires-Dist: uvicorn[standard]>=0.23.0
Requires-Dist: mlflow>=2.5.0
Requires-Dist: optuna>=3.3.0
Requires-Dist: pyyaml>=6.0
Requires-Dist: python-dateutil>=2.8.0
Requires-Dist: holidays>=0.30
Requires-Dist: matplotlib>=3.7.0
Requires-Dist: seaborn>=0.12.0
Requires-Dist: scipy>=1.11.0
Requires-Dist: prometheus-client>=0.17.0
Requires-Dist: python-multipart>=0.0.6
Provides-Extra: dev
Requires-Dist: pytest>=7.4.0; extra == "dev"
Requires-Dist: pytest-cov>=4.1.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21.0; extra == "dev"
Requires-Dist: black>=23.7.0; extra == "dev"
Requires-Dist: ruff>=0.0.280; extra == "dev"
Requires-Dist: mypy>=1.4.0; extra == "dev"
Requires-Dist: pre-commit>=3.3.0; extra == "dev"
Requires-Dist: ipython>=8.14.0; extra == "dev"
Requires-Dist: jupyter>=1.0.0; extra == "dev"
Requires-Dist: notebook>=7.0.0; extra == "dev"
Provides-Extra: docs
Requires-Dist: mkdocs>=1.5.0; extra == "docs"
Requires-Dist: mkdocs-material>=9.1.0; extra == "docs"
Requires-Dist: mkdocstrings[python]>=0.22.0; extra == "docs"
Provides-Extra: all
Requires-Dist: forecasting[dev,docs]; extra == "all"
Dynamic: license-file

# Forecaster AI 📈

[![PyPI version](https://badge.fury.io/py/forecaster-ai.svg)](https://badge.fury.io/py/forecaster-ai)
[![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

An enterprise-grade time series forecasting package with **automatic decomposition**, MLOps capabilities, and support for multiple forecasting models including ARIMA, Prophet, and LSTM.

## ✨ Key Features

### 🎯 Advanced Forecasting
- **Automatic Time Series Decomposition** (STL, Classical) - NEW! ⭐
- **Multiple Models**: ARIMA, Prophet, LSTM, and Ensemble methods
- **Intermittent Demand Forecasting**: Croston's, SBA, TSB methods
- **New Product Forecasting**: Cold start with bootstrapping
- **Adaptive Pattern Detection**: Automatically chooses best approach

### 🔄 Data Processing
- **Smart Decomposition**: Separates trend, seasonality, and residuals
- **Outlier Detection**: IQR, Z-score, MAD methods
- **Missing Value Handling**: Multiple imputation strategies
- **Data Validation**: Comprehensive quality checks

### 🚀 MLOps Integration
- **Experiment Tracking**: MLflow integration
- **Model Registry**: Version control and lifecycle management
- **Performance Monitoring**: Real-time drift detection
- **REST API**: FastAPI-based endpoints

### 🌐 Production Ready
- **Docker Support**: Containerized deployment
- **CI/CD Pipeline**: Automated testing and deployment
- **Monitoring**: Prometheus and Grafana integration
- **Scalability**: Horizontal scaling support

## 📦 Installation

```bash
pip install forecaster-ai
```

### From source

```bash
git clone https://github.com/surya08084/forecaster-ai.git
cd forecasting-package
pip install -e .
```

## 🚀 Quick Start

### Basic Forecasting with Decomposition

```python
import pandas as pd
from forecasting.core.config import ForecastConfig, PreprocessingConfig
from forecasting.models.prophet import ProphetForecaster

# Prepare data
dates = pd.date_range('2023-01-01', periods=365, freq='D')
values = [100 + i * 0.5 + 20 * np.sin(2 * np.pi * i / 7) for i in range(365)]
data = pd.Series(values, index=dates, name='sales')

# Configure with automatic decomposition
config = ForecastConfig(
    model_type='prophet',
    horizon=30,
    frequency='D',
    preprocessing=PreprocessingConfig(
        enable_decomposition=True,      # Enable decomposition
        decomposition_method='stl',     # STL or 'classical'
        decomposition_model='additive', # 'additive' or 'multiplicative'
        seasonal_period=7,              # Weekly seasonality
        handle_outliers=True
    )
)

# Create and train model
model = ProphetForecaster(config)
model.fit(data)

# Make predictions (automatically reconstructed to original scale)
predictions, conf_intervals = model.predict(horizon=30)

# Access decomposition components
components = model.get_decomposition_components()
print("Trend:", components['trend'])
print("Seasonal:", components['seasonal'])
print("Residual:", components['residual'])
```

### Standalone Time Series Decomposition

```python
from forecasting.data.preprocessors import TimeSeriesDecomposer

# Create decomposer
decomposer = TimeSeriesDecomposer(
    method='stl',           # Robust to outliers
    model='additive',       # or 'multiplicative'
    period=7                # Weekly seasonality
)

# Decompose time series
trend, seasonal, residual = decomposer.fit_transform(data)

# Reconstruct original
reconstructed = decomposer.reconstruct()
```

### Intermittent Demand (Sparse Data)

```python
from forecasting.data.special_cases import IntermittentDemandHandler

# For data with many zeros (retail, spare parts)
handler = IntermittentDemandHandler(
    method='sba',  # Syntetos-Boylan Approximation
    alpha=0.1
)

handler.fit(sparse_data)
forecast = handler.predict(horizon=12)
```

### New Product Forecasting (Cold Start)

```python
from forecasting.data.special_cases import NewProductHandler

# Bootstrap from similar products
handler = NewProductHandler()
bootstrap_data = handler.bootstrap_from_similar(
    similar_products={
        'product_A': historical_data_A,
        'product_B': historical_data_B
    },
    similarity_scores={
        'product_A': 0.85,
        'product_B': 0.72
    }
)

# Use bootstrap data for forecasting
config = ForecastConfig(model_type='prophet', horizon=30)
model = ProphetForecaster(config)
model.fit(bootstrap_data)
predictions, _ = model.predict()
```

## 📖 Model Usage

### ARIMA with Decomposition

```python
from forecasting.core.config import ForecastConfig, PreprocessingConfig
from forecasting.models.arima import ARIMAForecaster

config = ForecastConfig(
    model_type='arima',
    horizon=30,
    preprocessing=PreprocessingConfig(
        enable_decomposition=True,
        decomposition_method='stl'
    ),
    model_params={
        'order': (1, 1, 1),           # (p, d, q)
        'seasonal_order': (1, 1, 1, 7) # (P, D, Q, s)
    }
)

model = ARIMAForecaster(config)
model.fit(data)
predictions, conf_intervals = model.predict()
```

### Prophet with Custom Seasonality

```python
config = ForecastConfig(
    model_type='prophet',
    horizon=30,
    preprocessing=PreprocessingConfig(
        enable_decomposition=True
    ),
    model_params={
        'seasonality_mode': 'multiplicative',
        'yearly_seasonality': True,
        'weekly_seasonality': True,
        'daily_seasonality': False
    }
)

model = ProphetForecaster(config)
model.fit(data)
predictions, conf_intervals = model.predict()
```

### LSTM Deep Learning

```python
config = ForecastConfig(
    model_type='lstm',
    horizon=30,
    preprocessing=PreprocessingConfig(
        enable_decomposition=True,
        normalize=True
    ),
    model_params={
        'hidden_size': 64,
        'num_layers': 2,
        'dropout': 0.2,
        'learning_rate': 0.001,
        'epochs': 100
    }
)

model = LSTMForecaster(config)
model.fit(data)
predictions, conf_intervals = model.predict()
```

## 🔧 Advanced Features

### Data Validation

```python
from forecasting.data.validators import TimeSeriesValidator

validator = TimeSeriesValidator()
is_valid, errors = validator.validate(data)

# Check stationarity
is_stationary, p_value = validator.check_stationarity(data)

# Detect seasonality
has_seasonality, period = validator.detect_seasonality(data)

# Detect outliers
outliers = validator.detect_outliers(data, method='iqr')
```

### Evaluation Metrics

```python
from forecasting.evaluation.metrics import ForecastMetrics

metrics = ForecastMetrics()

# Calculate metrics
mae = metrics.mae(actual, predicted)
rmse = metrics.rmse(actual, predicted)
mape = metrics.mape(actual, predicted)
smape = metrics.smape(actual, predicted)
mase = metrics.mase(actual, predicted, seasonal_period=7)
```

### Backtesting

```python
from forecasting.evaluation.backtesting import RollingOriginBacktester

backtester = RollingOriginBacktester(
    initial_window=100,
    horizon=10,
    step=1
)

results = backtester.run(model, data)
print(f"Average RMSE: {results['avg_rmse']}")
```

### MLflow Tracking

```python
from forecasting.mlops.tracking import ExperimentTracker

tracker = ExperimentTracker(
    experiment_name='sales_forecasting',
    tracking_uri='http://localhost:5000'
)

with tracker.start_run():
    model.fit(data)
    tracker.log_params(config.get_model_params())
    tracker.log_metrics({'rmse': rmse, 'mae': mae})
    tracker.log_model(model, 'prophet_model')
```

## 🌐 REST API

### Start API Server

```bash
# Using uvicorn
uvicorn forecasting.api.main:app --host 0.0.0.0 --port 8000

# Using Docker
docker-compose up
```

### API Endpoints

```python
import requests

# Health check
response = requests.get('http://localhost:8000/health')

# Make prediction
response = requests.post(
    'http://localhost:8000/predict',
    json={
        'data': data.tolist(),
        'horizon': 30,
        'model_type': 'prophet',
        'enable_decomposition': True
    }
)
predictions = response.json()['predictions']
```

## 📊 Why Decomposition?

### Benefits

1. **Better Accuracy**: Models work on clean residuals
2. **Faster Training**: Simpler patterns to learn
3. **Interpretability**: Understand trend vs seasonality
4. **Robustness**: Handles outliers better

### When to Use

- ✅ **Regular patterns**: Daily, weekly, monthly seasonality
- ✅ **Trending data**: Long-term growth or decline
- ✅ **Clean forecasts**: Separate noise from signal

### When to Skip

- ❌ **Intermittent demand**: Use Croston's methods instead
- ❌ **New products**: Use bootstrapping instead
- ❌ **Very short series**: Not enough data to decompose

The package **automatically detects** which approach to use!

## 📚 Documentation

- **[Quick Start Guide](QUICK_START_USAGE.md)** - Complete usage examples
- **[Migration Guide](MIGRATION_GUIDE.md)** - Updating from old API
- **[PyPI Publishing](PYPI_PUBLISHING_GUIDE.md)** - Publishing guide
- **[Examples](examples/)** - Jupyter notebooks and scripts

## 🔄 What's New in v0.2.2

### ⭐ Major Features
- **Automatic Time Series Decomposition** (STL & Classical methods)
- **Adaptive Pattern Detection** (Regular, Intermittent, New Product)
- **Intermittent Demand Forecasting** (Croston's, SBA, TSB)
- **New Product Forecasting** (Bootstrapping from similar products)
- **Enhanced Preprocessing Pipeline** (Outliers, normalization, decomposition)

### 🔧 Improvements
- Configuration-based API for consistency
- Automatic reconstruction of predictions
- Component access for analysis
- Better error handling

## 🤝 Contributing

Contributions are welcome! Please read our [Contributing Guide](CONTRIBUTING.md).

## 📄 License

This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.

## 👤 Author

**Surya Tripathi**
- Email: suryaec1099@gmail.com
- GitHub: [@surya08084](https://github.com/surya08084)

## 🙏 Acknowledgments

- STL decomposition based on Cleveland et al. (1990)
- Croston's method for intermittent demand
- Prophet by Facebook Research
- MLflow for experiment tracking

## 📈 Citation

If you use this package in your research, please cite:

```bibtex
@software{forecaster_ai,
  author = {Tripathi, Surya},
  title = {Forecaster AI: Enterprise Time Series Forecasting with Automatic Decomposition},
  year = {2024},
  url = {https://github.com/surya08084/forecaster-ai}
}
```

---

Made with ❤️ by Bob and Surya
