Skip to main content

时序模型传递函数分析器 - 自动推导ARIMA模型的传递函数表达式

Project description

English | 中文

时序模型传递函数分析器

Python Version License Tests

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

🚀 核心功能

1. 模型参数化输入与解析

  • 支持多种输入方式:命令行参数、配置文件(JSON/YAML)、交互式输入
  • 自动验证模型参数的有效性
  • 支持符号参数和数值参数

2. 传递函数自动推导与生成

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

3. 高级分析功能

  • 稳定性分析(极点、零点计算)
  • 脉冲响应函数计算
  • 频率响应分析
  • 系统特性评估

📦 安装

使用uv(推荐)

uv add time-series-model-transfer-function-analyzer

使用pip

pip install time-series-model-transfer-function-analyzer

从源码安装

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进行时间序列模型分析。

启动服务

# 方法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使用示例

1. 健康检查

curl -X GET "http://localhost:8000/api/v1/health"

2. ARIMA模型分析

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. 通过模型字符串分析

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. 获取支持的模型类型

curl -X GET "http://localhost:8000/api/v1/models"

命令行工具

基本用法

# 分析简单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

高级分析

# 计算脉冲响应
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

基本使用

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']}")

便捷函数

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格式

{
  "model_type": "ARIMA",
  "p": 2,
  "d": 1,
  "q": 1,
  "ar_params": [0.5, -0.3],
  "ma_params": [0.2],
  "constant": 0
}

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数学表达式

\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结构化数据

{
  "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)模型

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:季节性模型分析

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)

🛠️ 开发

环境设置

# 克隆仓库
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格式进行数据交换。详细的请求和响应格式请参考:

🤝 贡献

欢迎贡献代码!请遵循以下步骤:

  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 文件了解详情。

🙏 致谢

📞 联系方式


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

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

File details

Details for the file time_series_model_transfer_function_analyzer-0.1.2.tar.gz.

File metadata

File hashes

Hashes for time_series_model_transfer_function_analyzer-0.1.2.tar.gz
Algorithm Hash digest
SHA256 734b01aa83535a95e3add68b3bf8e7dae70fed393773dc30677cade47594f3e8
MD5 7056056a29612ccc53a931b020bbbef4
BLAKE2b-256 14b1540c5d5003f0e4ee8a24342e22681c2c5758a864d7f593585e67ee179521

See more details on using hashes here.

File details

Details for the file time_series_model_transfer_function_analyzer-0.1.2-py3-none-any.whl.

File metadata

File hashes

Hashes for time_series_model_transfer_function_analyzer-0.1.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d392ea9c3b365ad69855f83e244668abb11321141aabe1a86042d71f7a7fe20f
MD5 5197356e701619bf5b4630d02bffa8cd
BLAKE2b-256 57ab1b82d69b3372008dba53480da927ed231a2b8203ff40780e93555f9945a0

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page