🚀 AI 一键生成 ptrade 策略代码
立即体验

ptrade 平台如何编写 CCI 顺势指标量化交易策略?(附 Python 完整源码)

ptrade | 发布时间: 2026/8/1
以下内容由 EasyQuant 生成。

问题描述

请根据以下 SEO 主题生成完整页面内容:

Title: ptrade 技术指标开发:如何编写自定义 CCI 顺势指标策略?

Question: 如何在 ptrade 中自定义计算 CCI 顺势指标并实现超买超卖交易策略?

解决方案

ptrade 平台如何编写 CCI 顺势指标量化交易策略?

顺势指标(Commodity Channel Index,简称 CCI)是一种经典的中短线技术分析工具,主要用于判断股票或期货是否处于超买或超卖状态。在 ptrade 量化平台中,我们可以直接利用平台提供的 get_CCI 函数快速计算该指标,并构建自动化交易策略。


一、CCI 指标交易逻辑

  1. 超卖买入:当 CCI 指标从下上方突破 -100(超卖区反弹)时,视为买入信号。
  2. 超买卖出:当 CCI 指标从上下方跌破 +100(超买区回落)或价格回调时,卖出所持仓位。

二、核心 API 说明

在 ptrade 中,使用 get_CCI 计算顺势指标:

get_CCI(high, low, close, n=14)
  • high:最高价的时间序列数据 (numpy.ndarray)。
  • low:最低价的时间序列数据 (numpy.ndarray)。
  • close:收盘价的时间序列数据 (numpy.ndarray)。
  • n:计算周期,默认为 14。
  • 返回值:返回 CCI 指标的时间序列 (numpy.ndarray)。

三、完整 Python 策略源码

以下是在 ptrade 平台中可直接运行的 CCI 策略代码:

def initialize(context):
    # 设置股票池(以恒生电子为例)
    g.security = '600570.SS'
    set_universe(g.security)
    # 设置基准
    set_benchmark('000300.SS')

def handle_data(context, data):
    security = g.security
    
    # 获取过去100天的历史高、低、收盘价数据
    h = get_history(100, '1d', ['close', 'high', 'low'], security_list=security)
    if h is None or len(h) < 14:
        return
        
    high_data = h['high'].values
    low_data = h['low'].values
    close_data = h['close'].values
    
    # 计算 CCI 指标(14日周期)
    cci_data = get_CCI(high_data, low_data, close_data, 14)
    current_cci = cci_data[-1]
    previous_cci = cci_data[-2]
    
    # 获取账户可用资金与当前持仓
    cash = context.portfolio.cash
    position = get_position(security).amount
    
    # 交易逻辑实现
    # 1. CCI 从下往上突破 -100,买入信号
    if previous_cci < -100 and current_cci >= -100:
        if cash > 0:
            order_value(security, cash)
            log.info("CCI上穿-100超卖区,买入股票 %s" % security)
            
    # 2. CCI 从上往下跌破 +100,卖出信号
    elif previous_cci > 100 and current_cci <= 100:
        if position > 0:
            order_target(security, 0)
            log.info("CCI下穿+100超买区,卖出股票 %s" % security)

四、策略优化提示

  1. 多指标结合:建议配合 MACD 或 KDJ 指标共同研判,规避 CCI 在强趋势行情中的指标钝化风险。
  2. 止损止盈设置:可以在 handle_data 中加入移动止损或固定百分比止损,提高策略的抗风险能力。