Metadata-Version: 2.4
Name: GeneralBacktest
Version: 1.0.1
Summary: 一个灵活高效的量化策略回测框架，支持多资产组合、任意调仓频率、向量化计算和丰富的性能分析
Author-email: Elen Young <yang13515360252@163.com>
License: MIT
Project-URL: Homepage, https://github.com/ElenYoung/GeneralBacktest
Project-URL: Bug Reports, https://github.com/ElenYoung/GeneralBacktest/issues
Project-URL: Source, https://github.com/ElenYoung/GeneralBacktest
Project-URL: Documentation, https://github.com/ElenYoung/GeneralBacktest#readme
Keywords: backtest,quantitative,trading,finance,portfolio
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
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: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Classifier: Topic :: Scientific/Engineering
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.20.0
Requires-Dist: pandas>=1.3.0
Requires-Dist: matplotlib>=3.3.0
Provides-Extra: database
Requires-Dist: quantchdb>=0.1.0; extra == "database"
Provides-Extra: excel
Requires-Dist: openpyxl>=3.0.0; extra == "excel"
Provides-Extra: full
Requires-Dist: quantchdb>=0.1.0; extra == "full"
Requires-Dist: openpyxl>=3.0.0; extra == "full"
Dynamic: license-file

# GeneralBacktest

[![PyPI version](https://badge.fury.io/py/GeneralBacktest.svg)](https://badge.fury.io/py/GeneralBacktest)
[![Python 3.8+](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)

**GeneralBacktest** 是一个灵活高效的量化策略回测框架，专为多资产组合策略设计。核心理念是"权重→交易→净值"，支持任意调仓频率、真实交易细节模拟、向量化高性能计算和丰富的性能分析。

## ✨ 主要特性

- 🎯 **灵活的调仓策略**：支持任意调仓频率和时间点，无需固定周期
- 🚀 **高性能计算**：向量化实现，支持数千标的、数年数据的快速回测
- 💰 **真实交易模拟**：
  - 调仓阈值控制（避免微小调整）
  - 买卖分开计费
  - 滑点模拟
  - 调仓日盈亏拆分（持仓/卖出/买入）
- 📊 **丰富的性能指标**：15+ 常用指标
  - 收益率指标：累计收益、年化收益
  - 风险指标：波动率、最大回撤
  - 风险调整指标：夏普比率、索提诺比率、卡玛比率
  - 尾部风险：VaR、CVaR
  - 相对指标：信息比率、超额收益
  - 交易指标：换手率
- 📈 **专业的可视化**：8+ 图表类型
  - 净值曲线与回撤
  - 策略对比
  - 超额收益分析
  - 月度收益热力图
  - 换手率分析
  - 持仓变化
  - 综合 Dashboard

## 📦 安装

### 基础安装

```bash
pip install GeneralBacktest
```

### 完整安装（包含数据库支持）

如果需要使用 `run_backtest_ETF()` 或 `run_backtest_stock()` 方法连接数据库：

```bash
pip install GeneralBacktest[database]
```

或安装所有可选依赖：

```bash
pip install GeneralBacktest[full]
```

### 依赖说明

- **必需依赖**：`numpy`, `pandas`, `matplotlib`
- **可选依赖**：
  - `quantchdb`：用于数据库连接（ETF/股票数据）
  - `openpyxl`：用于导出 Excel 报告

## 🚀 快速开始

### 基础用法 - 本地数据回测

```python
from GeneralBacktest import GeneralBacktest
import pandas as pd

# 准备权重数据（调仓信号）
weights_data = pd.DataFrame({
    'date': ['2023-01-01', '2023-01-01', '2023-06-01', '2023-06-01'],
    'code': ['stock_A', 'stock_B', 'stock_A', 'stock_B'],
    'weight': [0.6, 0.4, 0.3, 0.7]
})

# 准备价格数据（日线行情）
price_data = pd.DataFrame({
    'date': pd.date_range('2023-01-01', '2023-12-31', freq='D'),
    'code': 'stock_A',
    'open': [...],
    'close': [...],
    'adj_factor': [...]  # 复权因子
})
# ... 更多股票数据

# 创建回测实例
bt = GeneralBacktest(start_date="2023-01-01", end_date="2023-12-31")

# 运行回测
results = bt.run_backtest(
    weights_data=weights_data,
    price_data=price_data,
    buy_price="open",              # 买入价格字段
    sell_price="close",            # 卖出价格字段
    adj_factor_col="adj_factor",   # 复权因子字段
    close_price_col="close",       # 收盘价字段
    rebalance_threshold=0.005,     # 调仓阈值：0.5%
    transaction_cost=[0.001, 0.001],  # 买卖成本各 0.1%
    slippage=0.0005,               # 滑点：0.05%
    initial_capital=1.0
)

# 查看性能指标
bt.print_metrics()

# 生成可视化报告
bt.plot_all()  # 综合 Dashboard
bt.plot_nav_curve()  # 净值曲线
bt.plot_monthly_returns()  # 月度收益热力图
```

### 高级用法 - ETF 数据库回测（需要数据库配置）

> **注意**：`run_backtest_ETF()` 和 `run_backtest_stock()` 方法需要特定的数据库配置（`db_config`），这些方法需要有特定数据库支持。一般建议使用 `run_backtest()` 方法。

```python
from GeneralBacktest import GeneralBacktest
import pandas as pd

# 准备权重数据
weights_data = pd.DataFrame({
    'date': ['2023-01-01', '2023-01-01'],
    'code': ['510300', '510500'],  # ETF 代码
    'weight': [0.6, 0.4]
})

# 数据库配置（需要有效的数据库访问权限）
db_config = {
    'host': 'your_host',
    'port': 9000,
    'user': 'your_user',
    'password': 'your_password',
    'database': 'etf'
}

# 创建回测实例
bt = GeneralBacktest(start_date="2023-01-01", end_date="2023-12-31")

# 运行 ETF 回测（自动从数据库获取价格数据）
results = bt.run_backtest_ETF(
    etf_db_config=db_config,
    weights_data=weights_data,
    buy_price='open',
    sell_price='open',
    transaction_cost=[0.001, 0.001],
    rebalance_threshold=0.005
)

bt.print_metrics()
bt.plot_all()
```

## 📚 核心概念

### 权重数据格式

权重数据表示组合在各个调仓日的目标仓位：

| date       | code    | weight |
|------------|---------|--------|
| 2023-01-01 | stock_A | 0.6    |
| 2023-01-01 | stock_B | 0.4    |
| 2023-06-01 | stock_A | 0.3    |
| 2023-06-01 | stock_B | 0.7    |

- 每个调仓日的权重和应为 1.0
- 不同调仓日可以有不同的持仓数量

### 价格数据格式

价格数据包含资产的日线行情：

| date       | code    | open | high | low  | close | adj_factor |
|------------|---------|------|------|------|-------|------------|
| 2023-01-01 | stock_A | 10.0 | 10.5 | 9.8  | 10.2  | 1.0        |
| 2023-01-02 | stock_A | 10.2 | 10.8 | 10.1 | 10.5  | 1.0        |

- `adj_factor`：复权因子，用于计算真实收益
- 买卖价格可以灵活指定（开盘价、收盘价等）

### 调仓机制

1. **调仓阈值**：只有当目标权重与当前权重差异超过阈值时才交易
2. **买卖拆分**：先卖出不需要的仓位，再买入新仓位
3. **成本计算**：买卖分开计费，可设置不同费率
4. **滑点模拟**：买入价格上浮、卖出价格下压

## 📊 性能指标说明

| 指标类别 | 指标名称 | 说明 |
|---------|---------|------|
| **收益指标** | 累计收益率 | 期末/期初 - 1 |
| | 年化收益率 | 按交易日年化 |
| **风险指标** | 年化波动率 | 日收益率标准差年化 |
| | 最大回撤 | 从峰值到谷底的最大损失 |
| | 最大回撤持续期 | 最长回撤时间（天） |
| **风险调整** | 夏普比率 | 年化收益/年化波动率 |
| | 索提诺比率 | 年化收益/下行波动率 |
| | 卡玛比率 | 年化收益/最大回撤 |
| **尾部风险** | VaR (95%) | 5%分位数损失 |
| | CVaR (95%) | 超过VaR的平均损失 |
| **相对指标** | 信息比率 | 超额收益/跟踪误差 |
| | 超额年化收益 | 相对基准的年化超额 |
| **交易指标** | 换手率 | 调仓时的买卖金额 |

## 🎨 可视化示例

框架提供多种可视化方法：

```python
# 1. 综合 Dashboard（推荐）
bt.plot_all()

# 2. 净值曲线和回撤
bt.plot_nav_curve()

# 3. 策略与基准对比
bt.plot_comparison()

# 4. 超额收益分析
bt.plot_excess_returns()

# 5. 月度收益热力图
bt.plot_monthly_returns()

# 6. 换手率分析
bt.plot_turnover()

# 7. 持仓变化热力图
bt.plot_positions()

# 8. 收益分布直方图
bt.plot_return_distribution()
```

## 🔧 高级配置

### 自定义基准

```python
# 提供基准权重数据
benchmark_weights = pd.DataFrame({
    'date': ['2023-01-01'],
    'code': ['index_300'],
    'weight': [1.0]
})

results = bt.run_backtest(
    weights_data=weights_data,
    price_data=price_data,
    benchmark_weights=benchmark_weights,
    benchmark_name="HS300",
    ...
)
```

### 导出结果

```python
# 获取回测结果
nav_series = bt.daily_nav  # 日度净值序列
positions = bt.daily_positions  # 持仓明细
trade_records = bt.trade_records  # 交易记录
metrics = bt.metrics  # 性能指标字典

# 导出为 DataFrame
import pandas as pd
pd.DataFrame(metrics, index=[0]).to_excel('metrics.xlsx')
```

## 📖 API 文档

### GeneralBacktest 类

#### 初始化
```python
GeneralBacktest(start_date: str, end_date: str)
```

#### 主要方法

- `run_backtest(...)`: 通用回测方法（推荐）
- `run_backtest_ETF(...)`: ETF 回测（需数据库配置）
- `run_backtest_stock(...)`: 股票回测（需数据库配置）
- `print_metrics()`: 打印性能指标
- `plot_all()`: 生成综合报告
- `plot_nav_curve()`: 绘制净值曲线
- `plot_comparison()`: 策略对比图
- `plot_excess_returns()`: 超额收益图
- `plot_monthly_returns()`: 月度收益热力图
- `plot_turnover()`: 换手率图
- `plot_positions()`: 持仓热力图
- `plot_return_distribution()`: 收益分布图

## 🤝 贡献

欢迎提交 Issue 和 Pull Request！

## 📄 许可证

本项目采用 MIT 许可证 - 详见 [LICENSE](LICENSE) 文件

## 👨‍💻 作者

Elen Young - yang13515360252@example.com

## 🔗 相关链接

- [GitHub 仓库](https://github.com/ElenYoung/GeneralBacktest)
- [问题反馈](https://github.com/ElenYoung/GeneralBacktest/issues)
- [更新日志](https://github.com/ElenYoung/GeneralBacktest/releases)

## ⚠️ 免责声明

本框架仅供学习和研究使用，不构成任何投资建议。使用本框架进行的任何投资决策，风险自负。

## 📝 更新日志

### v1.0.0 (2026-01-24)
- 🎉 首次发布
- ✨ 支持灵活调仓频率
- ✨ 向量化高性能计算
- ✨ 15+ 性能指标
- ✨ 8+ 可视化图表
- ✨ 支持基准对比
- ✨ 真实交易细节模拟
