Metadata-Version: 2.4
Name: kepler.echo
Version: 0.2.8
Summary: A high-performance vector backtesting framework for quantitative strategies
Author-email: liubola <lby3523@gmail.com>
Maintainer-email: liubola <lby3523@gmail.com>
License-Expression: GPL-3.0-or-later
Project-URL: Homepage, https://github.com/liubola/kepler-echo
Project-URL: Repository, https://github.com/liubola/kepler-echo
Project-URL: Bug Reports, https://github.com/liubola/kepler-echo/issues
Project-URL: Documentation, https://github.com/liubola/kepler-echo/blob/main/README.md
Keywords: backtesting,quantitative,finance,vector,trading,strategy,investment
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Office/Business :: Financial
Classifier: Topic :: Scientific/Engineering
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
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: Operating System :: OS Independent
Classifier: Operating System :: POSIX
Classifier: Operating System :: Microsoft :: Windows
Classifier: Operating System :: MacOS
Classifier: Natural Language :: Chinese (Simplified)
Classifier: Natural Language :: English
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pandas>=1.0.0
Requires-Dist: numpy>=1.18.0
Provides-Extra: dev
Requires-Dist: pytest>=6.0.0; extra == "dev"
Requires-Dist: pytest-cov>=2.10.0; extra == "dev"
Requires-Dist: black>=21.0.0; extra == "dev"
Requires-Dist: flake8>=3.8.0; extra == "dev"
Requires-Dist: mypy>=0.800; extra == "dev"
Provides-Extra: plotting
Requires-Dist: matplotlib>=3.0.0; extra == "plotting"
Requires-Dist: seaborn>=0.11.0; extra == "plotting"
Provides-Extra: performance
Requires-Dist: numba>=0.50.0; extra == "performance"
Requires-Dist: cython>=0.29.0; extra == "performance"
Dynamic: license-file

# Kepler Echo

[![Python](https://img.shields.io/badge/python-3.8+-blue.svg)](https://python.org)
[![License](https://img.shields.io/badge/license-GPL%20v3-green.svg)](LICENSE)

向量化回测框架。

## 安装

```bash
pip install kepler-echo
```

## 快速开始

```python
import pandas as pd
from kepler.echo import Strategy

# 价格数据 (MultiIndex: date, item)
price_data = []
for date in ['2020-01-01', '2020-01-02']:
    for stock, o, c in [('A', 10, 10.5), ('B', 20, 20.5), ('C', 30, 30.5)]:
        price_data.append({'date': date, 'item': stock, 'open': o, 'close': c})
price = pd.DataFrame(price_data).set_index(['date', 'item'])

# 信号
signal = pd.DataFrame({
    'A': [0.5, 0.6],
    'B': [-0.3, -0.2],
}, index=pd.date_range('2020-01-01', periods=2))

# 回测
result = (
    Strategy(begin="2020-01-01", end="2020-12-31")
    .data(price)
    .signal(signal)
    .commission((0.001, 0.001))
    .run()
)

print(result.nav)
```

## API

### Strategy

```python
Strategy(
    begin="2001-01-01",        # 开始日期
    end="今天",                 # 结束日期
    matching="next_bar",       # 撮合: next_bar / current_bar
    benchmark="",              # 基准 (数据中的某列)
    commission=(0, 0),         # 手续费 (做多, 做空)
)
```

### 方法

| 方法 | 说明 |
|------|------|
| `.data(df, exec_price='open')` | 添加价格数据 |
| `.signal(df)` | 添加信号 |
| `.commission((long, short))` | 设置手续费 |
| `.benchmark(symbol)` | 设置基准 |
| `.run()` | 运行，返回结果 |
| `.plot(log=True)` | 绘图 |

### 数据格式

支持两种格式：

**1. pandas DataFrame (MultiIndex)**

index 为 `['date', 'item']`，columns 必须包含 `close` 和 `exec_price` 指定的列：

```python
                      close  open
date       item
2020-01-01 A        10.5    10
           B        20.5    20
2020-01-02 A        11.0    10.5
           B        21.0    20.5
```

**2. xarray DataArray**

三维数组，维度为 `(date, item, feature)`：

```python
import xarray as xr
import numpy as np

# 创建 xarray DataArray
dates = pd.date_range('2020-01-01', periods=2)
items = ['A', 'B']
features = ['open', 'close']

data = xr.DataArray(
    np.random.randn(2, 2, 2),
    dims=['date', 'item', 'feature'],
    coords={'date': dates, 'item': items, 'feature': features}
)

# 使用
result = Strategy().data(data, exec_price='open').signal(signal).run()
```

### 信号格式

**宽格式:**
```python
signal = pd.DataFrame({
    '000001.SZ': [0.5, 0.6],
    '000002.SZ': [-0.3, -0.2],
}, index=pd.date_range('2020-01-01', periods=2))
```

**长格式:**
```python
signal = pd.DataFrame({
    'date': ['2020-01-01', '2020-01-01'],
    'stockid': ['000001.SZ', '000002.SZ'],
    'weight': [0.5, -0.3]
})
```

### 结果

```python
result.nav      # 净值 DataFrame
result.hold     # 最终持仓
result.signal   # 原始信号
result.stats    # 统计 (turnover)
```

**nav 列说明：**

| 列名 | 说明 |
|------|------|
| `strategy` | 策略净值 |
| `{benchmark}` | 基准净值（如果设置了 benchmark） |
| `relative` | 相对净值 = strategy / benchmark（如果设置了 benchmark） |
| `drawdown` | 动态回撤（相对收益的回撤，或绝对收益的回撤） |

## 撮合方式

- `next_bar`: 下一根 K 线的 `exec_price` 价格（默认）
- `current_bar`: 当前 K 线收盘价

## 执行价格

`exec_price` 参数指定 next_bar 模式下的执行价格列:

```python
.data(price)                       # 使用开盘价（默认）
.data(price, exec_price='vwap')    # 使用 VWAP
.data(price, exec_price='close')   # 使用收盘价
```

## 许可证

GPL-3.0-or-later
