Metadata-Version: 2.4
Name: time-series-model-transfer-function-analyzer
Version: 0.1.2
Summary: 时序模型传递函数分析器 - 自动推导ARIMA模型的传递函数表达式
Project-URL: Homepage, https://github.com/zym9863/time-series-model-transfer-function-analyzer
Project-URL: Repository, https://github.com/zym9863/time-series-model-transfer-function-analyzer
Project-URL: Issues, https://github.com/zym9863/time-series-model-transfer-function-analyzer/issues
Author-email: zym <ym214413520@gmail.com>
License-File: LICENSE
Keywords: arima,econometrics,signal-processing,time-series,transfer-function
Classifier: Development Status :: 3 - Alpha
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: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Information Analysis
Classifier: Topic :: Scientific/Engineering :: Mathematics
Requires-Python: >=3.9
Requires-Dist: click>=8.0
Requires-Dist: fastapi>=0.115.14
Requires-Dist: numpy>=1.24
Requires-Dist: pydantic-settings>=2.10.1
Requires-Dist: pydantic>=2.0
Requires-Dist: python-multipart>=0.0.20
Requires-Dist: pyyaml>=6.0
Requires-Dist: rich>=13.0
Requires-Dist: sympy>=1.12
Requires-Dist: uvicorn[standard]>=0.35.0
Provides-Extra: dev
Requires-Dist: black>=23.0; extra == 'dev'
Requires-Dist: flake8>=6.0; extra == 'dev'
Requires-Dist: isort>=5.12; extra == 'dev'
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Provides-Extra: docs
Requires-Dist: myst-parser>=2.0; extra == 'docs'
Requires-Dist: sphinx-rtd-theme>=1.3; extra == 'docs'
Requires-Dist: sphinx>=7.0; extra == 'docs'
Description-Content-Type: text/markdown

[English](README_EN.md) | [中文](README.md)

# 时序模型传递函数分析器

[![Python Version](https://img.shields.io/badge/python-3.9+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
[![Tests](https://img.shields.io/badge/tests-passing-brightgreen.svg)](tests/)

一个用于自动推导时间序列模型传递函数的Python库。支持ARIMA和SARIMA模型的参数化输入和传递函数的符号推导。

## 🚀 核心功能

### 1. 模型参数化输入与解析
- 支持多种输入方式：命令行参数、配置文件（JSON/YAML）、交互式输入
- 自动验证模型参数的有效性
- 支持符号参数和数值参数

### 2. 传递函数自动推导与生成
- 基于符号计算自动推导传递函数表达式
- 将ARIMA/SARIMA模型转换为关于滞后算子B的多项式比值形式
- 支持LaTeX、纯文本、JSON等多种输出格式

### 3. 高级分析功能
- 稳定性分析（极点、零点计算）
- 脉冲响应函数计算
- 频率响应分析
- 系统特性评估

## 📦 安装

### 使用uv（推荐）
```bash
uv add time-series-model-transfer-function-analyzer
```

### 使用pip
```bash
pip install time-series-model-transfer-function-analyzer
```

### 从源码安装
```bash
git clone https://github.com/zym9863/time-series-model-transfer-function-analyzer.git
cd time-series-model-transfer-function-analyzer
uv sync
```

## 🎯 快速开始

### FastAPI Web服务

本项目提供了完整的FastAPI Web服务，支持通过HTTP API进行时间序列模型分析。

#### 启动服务

```bash
# 方法1：使用启动脚本
python scripts/start_api.py

# 方法2：直接使用uvicorn
uvicorn src.api.app:create_app --factory --host 0.0.0.0 --port 8000 --reload

# 方法3：使用便捷脚本
# Windows
scripts/start_api.bat

# Linux/macOS
chmod +x scripts/start_api.sh
./scripts/start_api.sh
```

#### 访问API文档

启动服务后，可以通过以下地址访问：

- **API文档 (Swagger UI)**: http://localhost:8000/docs
- **API文档 (ReDoc)**: http://localhost:8000/redoc
- **OpenAPI规范**: http://localhost:8000/openapi.json
- **健康检查**: http://localhost:8000/api/v1/health

#### API使用示例

**1. 健康检查**
```bash
curl -X GET "http://localhost:8000/api/v1/health"
```

**2. ARIMA模型分析**
```bash
curl -X POST "http://localhost:8000/api/v1/analyze/arima" \
  -H "Content-Type: application/json" \
  -d '{
    "p": 2,
    "d": 1,
    "q": 1,
    "ar_params": [0.5, -0.3],
    "ma_params": [0.2],
    "include_stability": true
  }'
```

**3. 通过模型字符串分析**
```bash
curl -X POST "http://localhost:8000/api/v1/analyze/model-string" \
  -H "Content-Type: application/json" \
  -d '{
    "model_string": "ARIMA(2,1,1)",
    "include_stability": true,
    "include_impulse": true
  }'
```

**4. 获取支持的模型类型**
```bash
curl -X GET "http://localhost:8000/api/v1/models"
```

### 命令行工具

#### 基本用法
```bash
# 分析简单ARIMA模型
tsm-analyzer analyze -m "ARIMA(2,1,1)"

# 分析SARIMA模型并输出LaTeX格式
tsm-analyzer analyze -m "SARIMA(2,1,1)(1,1,1,12)" --format latex

# 从配置文件分析
tsm-analyzer analyze -f examples/arima_example.json --include-analysis

# 交互式输入
tsm-analyzer analyze --interactive
```

#### 高级分析
```bash
# 计算脉冲响应
tsm-analyzer impulse -m "ARIMA(2,1,1)" --max-lag 10

# 计算频率响应
tsm-analyzer frequency -m "ARIMA(2,1,1)" --frequencies "0,0.1,0.2,0.3,0.4,0.5"

# 稳定性分析
tsm-analyzer stability -m "ARIMA(2,1,1)"
```

### Python API

#### 基本使用
```python
from time_series_analyzer import TimeSeriesAnalyzer

# 创建分析器
analyzer = TimeSeriesAnalyzer()

# 创建ARIMA模型
model = analyzer.create_arima_model(
    p=2, d=1, q=1,
    ar_params=[0.5, -0.3],
    ma_params=[0.2]
)

# 推导传递函数
transfer_func = analyzer.derive_transfer_function(model)
print(f"传递函数: {transfer_func}")

# 分析稳定性
stability = analyzer.analyze_stability(model)
print(f"系统稳定性: {stability['is_stable']}")
```

#### 便捷函数
```python
from time_series_analyzer import analyze_arima, parse_and_analyze

# 快速分析ARIMA模型
result = analyze_arima(
    p=2, d=1, q=1,
    ar_params=[0.5, -0.3],
    ma_params=[0.2],
    include_stability=True,
    include_impulse=True
)

# 从字符串解析并分析
result = parse_and_analyze(
    "SARIMA(2,1,1)(1,1,1,12)",
    include_stability=True
)
```

## 📋 支持的模型

### ARIMA模型
- **ARIMA(p,d,q)**: 自回归积分移动平均模型
- 支持任意阶数的AR、I、MA部分
- 自动处理差分操作

### SARIMA模型
- **SARIMA(p,d,q)(P,D,Q,m)**: 季节性ARIMA模型
- 支持季节性和非季节性参数
- 灵活的季节性周期设置

## 🔧 配置文件格式

### JSON格式
```json
{
  "model_type": "ARIMA",
  "p": 2,
  "d": 1,
  "q": 1,
  "ar_params": [0.5, -0.3],
  "ma_params": [0.2],
  "constant": 0
}
```

### YAML格式
```yaml
model_type: SARIMA
p: 2
d: 1
q: 1
P: 1
D: 1
Q: 1
m: 12
ar_params: [0.5, -0.3]
ma_params: [0.2]
seasonal_ar_params: [0.8]
seasonal_ma_params: [0.4]
```

## 📊 输出格式

### LaTeX数学表达式
```latex
\section{ARIMA(2,1,1) 模型分析}

\subsection{传递函数}
$H(B) = \frac{1 + 0.2B}{(1 - 0.5B + 0.3B^2)(1-B)}$
```

### 纯文本格式
```
==================================================
ARIMA(2,1,1) 模型分析
==================================================

传递函数:
------------------------------
H(B) = (1 + 0.2*B) / ((1 - 0.5*B + 0.3*B**2)*(1 - B))

稳定性分析:
------------------------------
系统稳定性: 稳定
最大极点模长: 0.8660
```

### JSON结构化数据
```json
{
  "timestamp": "2024-01-01T12:00:00",
  "model": {
    "model_type": "ARIMA",
    "parameters": {"p": 2, "d": 1, "q": 1}
  },
  "transfer_function": {
    "numerator": "1 + 0.2*B",
    "denominator": "(1 - 0.5*B + 0.3*B**2)*(1 - B)",
    "poles": [{"real": 0.5, "imag": 0.866}],
    "zeros": [{"real": -5.0, "imag": 0.0}]
  }
}
```

## 🧮 数学原理

### ARIMA模型的传递函数

对于ARIMA(p,d,q)模型：
```
φ(B)(1-B)^d X_t = θ(B)ε_t
```

其传递函数为：
```
H(B) = θ(B) / [φ(B)(1-B)^d]
```

其中：
- φ(B) = 1 - φ₁B - φ₂B² - ... - φₚBᵖ (自回归多项式)
- θ(B) = 1 + θ₁B + θ₂B² + ... + θₑBᵠ (移动平均多项式)
- (1-B)^d 是差分算子

### SARIMA模型的传递函数

对于SARIMA(p,d,q)(P,D,Q,m)模型：
```
φ(B)Φ(B^m)(1-B)^d(1-B^m)^D X_t = θ(B)Θ(B^m)ε_t
```

其传递函数为：
```
H(B) = θ(B)Θ(B^m) / [φ(B)Φ(B^m)(1-B)^d(1-B^m)^D]
```

## 🔍 示例分析

### 示例1：ARIMA(1,1,1)模型

```python
from time_series_analyzer import parse_and_analyze

# 分析ARIMA(1,1,1)模型
result = parse_and_analyze(
    "ARIMA(1,1,1)",
    include_stability=True,
    include_impulse=True,
    max_lag=10
)

print("模型信息:")
print(f"  类型: {result['model']['model_type']}")
print(f"  参数: p={result['model']['parameters']['p']}, "
      f"d={result['model']['parameters']['d']}, "
      f"q={result['model']['parameters']['q']}")

print("\n传递函数:")
print(f"  分子: {result['transfer_function']['numerator']}")
print(f"  分母: {result['transfer_function']['denominator']}")

print(f"\n稳定性: {'稳定' if result['stability']['is_stable'] else '不稳定'}")
```

### 示例2：季节性模型分析

```python
from time_series_analyzer import TimeSeriesAnalyzer

analyzer = TimeSeriesAnalyzer()

# 创建SARIMA模型
model = analyzer.create_sarima_model(
    p=1, d=1, q=1,      # 非季节性部分
    P=1, D=1, Q=1, m=12, # 季节性部分（月度数据）
    ar_params=[0.7],
    ma_params=[0.3],
    seasonal_ar_params=[0.5],
    seasonal_ma_params=[0.2]
)

# 生成完整报告
report = analyzer.generate_report(
    model,
    format='text',
    include_analysis=True
)

print(report)
```

## 🛠️ 开发

### 环境设置
```bash
# 克隆仓库
git clone https://github.com/zym9863/time-series-model-transfer-function-analyzer.git
cd time-series-model-transfer-function-analyzer

# 安装开发依赖
uv sync --dev

# 运行测试
uv run pytest

# 代码格式化
uv run black src tests
uv run isort src tests

# 类型检查
uv run mypy src
```

### 项目结构
```
time-series-model-transfer-function-analyzer/
├── src/
│   ├── time_series_analyzer/    # 核心分析库
│   │   ├── __init__.py          # 主要API导出
│   │   ├── models.py            # ARIMA/SARIMA模型定义
│   │   ├── transfer_function.py # 传递函数推导引擎
│   │   ├── parsers.py           # 输入解析器
│   │   ├── formatters.py        # 输出格式化器
│   │   ├── api.py              # 高级API接口
│   │   └── cli.py              # 命令行工具
│   └── api/                     # FastAPI Web服务
│       ├── __init__.py
│       ├── app.py              # FastAPI应用主文件
│       ├── config.py           # 配置管理
│       ├── middleware.py       # 中间件
│       ├── schemas.py          # 请求/响应模型
│       └── routers/            # API路由
│           ├── __init__.py
│           ├── analysis.py     # 分析服务路由
│           ├── health.py       # 健康检查路由
│           └── models.py       # 模型管理路由
├── scripts/                     # 启动脚本
│   ├── start_api.py            # Python启动脚本
│   ├── start_api.bat           # Windows批处理脚本
│   └── start_api.sh            # Linux/macOS脚本
├── tests/                       # 测试套件
├── examples/                    # 示例配置文件
├── docs/                   # 文档
└── pyproject.toml          # 项目配置
```

## 📚 API参考

### 核心类

#### `TimeSeriesAnalyzer`
主要的分析器类，提供所有分析功能。

**方法:**
- `create_arima_model()` - 创建ARIMA模型
- `create_sarima_model()` - 创建SARIMA模型
- `derive_transfer_function()` - 推导传递函数
- `analyze_stability()` - 稳定性分析
- `compute_impulse_response()` - 计算脉冲响应
- `compute_frequency_response()` - 计算频率响应
- `generate_report()` - 生成分析报告

#### `ARIMAModel` / `SeasonalARIMAModel`
模型数据类，使用Pydantic进行验证。

#### `TransferFunction`
传递函数表示类，包含分子、分母多项式和分析方法。

### 便捷函数

- `analyze_arima()` - 快速分析ARIMA模型
- `analyze_sarima()` - 快速分析SARIMA模型
- `parse_and_analyze()` - 从字符串解析并分析

### FastAPI端点

#### 健康检查
- `GET /api/v1/health` - 服务健康检查

#### 模型管理
- `GET /api/v1/models` - 获取支持的模型类型
- `GET /api/v1/models/validate/{model_string}` - 验证模型字符串

#### 分析服务
- `POST /api/v1/analyze/arima` - 分析ARIMA模型
- `POST /api/v1/analyze/sarima` - 分析SARIMA模型
- `POST /api/v1/analyze/model-string` - 通过模型字符串分析
- `GET /api/v1/analyze/transfer-function/{model_string}` - 仅获取传递函数
- `GET /api/v1/analyze/stability/{model_string}` - 仅获取稳定性分析

#### 请求/响应格式

所有API端点都使用JSON格式进行数据交换。详细的请求和响应格式请参考：
- **Swagger UI文档**: http://localhost:8000/docs
- **ReDoc文档**: http://localhost:8000/redoc

## 🤝 贡献

欢迎贡献代码！请遵循以下步骤：

1. Fork 项目
2. 创建特性分支 (`git checkout -b feature/amazing-feature`)
3. 提交更改 (`git commit -m 'Add amazing feature'`)
4. 推送到分支 (`git push origin feature/amazing-feature`)
5. 开启 Pull Request

### 贡献指南

- 确保所有测试通过
- 添加适当的测试覆盖
- 遵循代码风格指南
- 更新相关文档

## 📄 许可证

本项目采用 MIT 许可证 - 查看 [LICENSE](LICENSE) 文件了解详情。

## 🙏 致谢

- [SymPy](https://www.sympy.org/) - 符号数学计算
- [Pydantic](https://pydantic-docs.helpmanual.io/) - 数据验证
- [Click](https://click.palletsprojects.com/) - 命令行界面
- [Rich](https://rich.readthedocs.io/) - 终端美化

## 📞 联系方式

- 项目主页: https://github.com/zym9863/time-series-model-transfer-function-analyzer
- 问题反馈: https://github.com/zym9863/time-series-model-transfer-function-analyzer/issues

---

**注意**: 这是一个学术研究工具，主要用于教学和研究目的。在生产环境中使用前请充分测试。