Metadata-Version: 2.4
Name: iciv-predictor
Version: 0.1.3
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, PredictionOutput
import numpy as np

class MyPredictor(BasePredictor):
    def __init__(self, df, predict_steps=48):
        super().__init__(df, predict_steps)
        # 初始化你的参数
        self.short_ma = 12
        self.long_ma = 48
    
    def predict_step(self, current_idx):
        """
        预测当前时间点
        
        Args:
            current_idx: 当前索引，只能使用历史数据 df[:current_idx+1]
        
        Returns:
            PredictionOutput 或 None
        """
        if current_idx < self.long_ma:
            return None
        
        # 获取历史收盘价
        closes = self.get_close_prices(current_idx)
        
        # 计算均线
        short_avg = closes[-self.short_ma:].mean()
        long_avg = closes[-self.long_ma:].mean()
        
        # 判断方向
        if short_avg > long_avg:
            direction = 1   # 看涨，买入
        elif short_avg < long_avg:
            direction = -1  # 看跌，卖出
        else:
            direction = 0   # 持有
        
        return PredictionOutput(
            predict_from_idx=current_idx,
            predicted_prices=np.zeros(self.predict_steps),
            predicted_returns=np.zeros(self.predict_steps),
            confidence=0.6,
            direction=direction
        )
```

### 2. 本地测试

```bash
iciv-test my_predictor.py --data 000021_SZ.csv
```

或使用Python：

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

# 加载数据
df = pd.read_csv('000021_SZ.csv')
df['trade_time'] = pd.to_datetime(df['datetime'])

# 创建预测器
predictor = MyPredictor(df)

# 运行回测
backtester = Backtester()
result = backtester.run(df, predictor)

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

### 3. 提交到平台

测试通过后，将你的 `.py` 文件提交到 https://stock.w3drop.com

## API 参考

### BasePredictor

基类，所有预测器必须继承此类。

**方法**:

| 方法 | 说明 |
|------|------|
| `__init__(df, predict_steps=48)` | 初始化，predict_steps为预测步长 |
| `predict_step(current_idx)` | **必须实现**，返回PredictionOutput |
| `get_historical_data(idx)` | 获取历史DataFrame |
| `get_close_prices(idx)` | 获取历史收盘价数组 |
| `get_returns(idx)` | 获取历史收益率数组 |

### PredictionOutput

预测输出结构。

**字段**:

| 字段 | 类型 | 说明 |
|------|------|------|
| `predict_from_idx` | int | 预测起始索引 |
| `predicted_prices` | np.ndarray | 预测价格序列 |
| `predicted_returns` | np.ndarray | 预测收益率序列 |
| `confidence` | float | 置信度 (0-1) |
| `direction` | int | **交易信号**: 1=买入, -1=卖出, 0=持有 |

## 回测规则

1. **预测频率**: 每48步（约4小时）预测一次
2. **测试集**: 使用后20%数据
3. **交易逻辑**:
   - direction=1 且无持仓 → 买入
   - direction=-1 且有持仓 → 卖出
4. **手续费**: 买卖各万分之三
5. **强制平仓**: 测试期结束时平仓

## 注意事项

⚠️ **禁止使用未来数据**！`predict_step(idx)` 只能访问 `idx` 及之前的数据。

```python
# ✅ 正确
closes = self.get_close_prices(current_idx)

# ❌ 错误 - 访问了未来数据
future = self.df['close'].iloc[current_idx + 10]
```

## License

MIT
