Skip to main content

ICIV股票预测竞赛SDK - 用于开发和测试交易策略

Project description

ICIV Stock Predictor SDK

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

安装

pip install iciv-predictor

快速开始

1. 创建预测器

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. 本地测试

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

或使用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 及之前的数据。

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

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

License

MIT

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

iciv_predictor-0.1.1.tar.gz (7.7 kB view details)

Uploaded Source

Built Distribution

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

iciv_predictor-0.1.1-py3-none-any.whl (9.0 kB view details)

Uploaded Python 3

File details

Details for the file iciv_predictor-0.1.1.tar.gz.

File metadata

  • Download URL: iciv_predictor-0.1.1.tar.gz
  • Upload date:
  • Size: 7.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for iciv_predictor-0.1.1.tar.gz
Algorithm Hash digest
SHA256 4817bc0207c082b585eb378ee6a56156236c25f8a366ffaf75ebef7269eb2705
MD5 4b35cd0f00fdea054de31a65b32571dc
BLAKE2b-256 8f8e6de3af4d4f16c087940886ac58b81aef221c06968cbe6b7cbf8e97617c4c

See more details on using hashes here.

File details

Details for the file iciv_predictor-0.1.1-py3-none-any.whl.

File metadata

  • Download URL: iciv_predictor-0.1.1-py3-none-any.whl
  • Upload date:
  • Size: 9.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.3

File hashes

Hashes for iciv_predictor-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 2c132dee539ded13747d25d09980fc2e8f418459132db1d479cd4d82d523fda5
MD5 ff567b194cb5f78f2b5f5d1fec03a794
BLAKE2b-256 22c1ee4a4a9b2e4ce15e28915c00d9a0c2e78066bcd8c5821c6eec72f408f026

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