Metadata-Version: 2.4
Name: iciv-predictor
Version: 0.2.0
Summary: ICIV股票预测竞赛SDK - 用于开发和测试交易策略
Author-email: ICIV Lab <iciv@example.com>
License: MIT
Project-URL: Homepage, https://stock.w3drop.com
Project-URL: Documentation, https://stock.w3drop.com/docs
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
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
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: pandas>=1.5.0
Requires-Dist: numpy>=1.21.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0.0; extra == "dev"

# ICIV Stock Predictor SDK

股票预测竞赛 SDK，用于开发和本地测试交易策略。

## 安装

```bash
pip install iciv-predictor
```

## 快速开始

### 1. 写一个预测器

```python
from iciv_predictor import BasePredictor

class MyPredictor(BasePredictor):
    def predict_step(self, current_idx):
        # 你能看到的所有历史数据
        closes = self.get_close_prices(current_idx)
        if len(closes) < 30:
            return None

        # 你的算法（n_seg 融合 / LSTM / 随便什么）
        short_ma = closes[-12:].mean()
        long_ma = closes[-48:].mean()
        pred_change_pct = (short_ma - long_ma) / long_ma * 100

        # ===== 用便利方法表达交易意图（推荐）=====
        if pred_change_pct > 1.0:
            # 涨幅越大仓位越重，clip 到 [0, 1]
            return self.signal_buy(
                current_idx,
                ratio=min(1.0, pred_change_pct / 2),
                predicted_change_pct=pred_change_pct,
                stop_loss_pct=0.05,    # 跌 5% 止损
            )
        if pred_change_pct < -0.5:
            return self.signal_sell(current_idx, predicted_change_pct=pred_change_pct)
        return self.signal_hold(current_idx)
```

### 2. 本地测试

```python
from iciv_predictor import Backtester, BacktestConfig
import pandas as pd

df = pd.read_csv('000021_SZ.csv')
df['trade_time'] = pd.to_datetime(df['trade_time'])

# 划测试集（后 20% 交易日）
df['_d'] = df['trade_time'].dt.date
days = df['_d'].unique()
test_start_idx = df[df['_d'] == days[int(len(days) * 0.8)]].index[-1]
df.drop('_d', axis=1, inplace=True)

predictor = MyPredictor(df)
result = Backtester(BacktestConfig(initial_capital=1_000_000)).run(
    df, predictor, test_start_idx=test_start_idx,
)

print(f"收益率: {result.total_return:+.2f}%")
print(f"最大回撤: {result.max_drawdown:.2f}%")
print(f"胜率: {result.win_rate:.1f}%  交易: {result.total_trades} 次")
```

### 3. 提交到平台

把 `.py` 文件提交到 https://stock.icivlab.com

## API 参考

### `PredictionOutput`

引擎按如下优先级处理：

| # | 字段 | 含义 |
|---|---|---|
| 1 | `stop_loss_pct` / `take_profit_pct` | 触发即强平，先于其他信号 |
| 2 | `target_position` ∈ `[0.0, 1.0]` | 调到目标仓位 |
| 3 | `position_delta` ∈ `[-1.0, 1.0]` | 在当前仓位上加减 |
| 4 | `direction` ∈ `{-1, 0, 1}` | 老语义：1 = 满仓买、-1 = 全平、0 = 不动 |

> ⚠️ **本平台不支持做空、不支持加杠杆**：所有目标仓位最终 clip 到 `[0.0, max_position_pct]`。

展示字段（不影响交易）：
- `predicted_change_pct`: 预测下一周期涨跌幅 %
- `metadata`: 任意 JSON dict，落库 + 前端展示

### `BasePredictor` 便利方法

```python
self.signal_buy(idx, ratio=0.5, stop_loss_pct=0.05)     # 半仓买，5% 止损
self.signal_sell(idx)                                    # 全平
self.signal_hold(idx)                                    # 不动
self.signal_adjust(idx, target_position=0.7)             # 调到 70% 仓位
```

### `BacktestConfig`

| 字段 | 默认 | 说明 |
|---|---|---|
| `initial_capital` | 1_000_000 | 初始资金 |
| `buy_fee_rate` / `sell_fee_rate` | 万三 | 佣金 |
| `stamp_tax_rate` | 千一 | 卖出印花税 |
| `max_position_pct` | 1.0 | 单笔最大仓位（≤ 1.0） |
| `min_trade_value` | 1000.0 | 最小交易金额 |
| `rebalance_threshold` | 0.0 | 仓位差小于此比例不交易（防抖） |

## 数据规范

- K 线 5 分钟一根，每天 49 根（9:30–15:00）
- 列：`trade_time, open, high, low, close, volume, amount`
- `predict_step(current_idx)` 中**只能访问 `df[:current_idx+1]`**，禁止使用未来数据

## 0.2.0 变更

- ✨ `PredictionOutput` 加入 `target_position` / `position_delta` / `stop_loss_pct` / `take_profit_pct` / `predicted_change_pct` / `metadata`
- ✨ `BasePredictor` 加 `signal_buy / signal_sell / signal_hold / signal_adjust`
- ✨ `Backtester` 支持非梭哈仓位管理 + 止损止盈 + 防抖
- 🔒 仓位强制 `[0, 1]`：本平台不做空、不加杠杆
- ✅ 老的 `direction=±1` 用法 100% 向后兼容

## License

MIT
