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

joinquant 技术分析教程:基于 jqlib 构建 RSI 摆动指标策略

joinquant | 发布时间: 2026/7/28
以下内容由 EasyQuant 生成。

问题描述

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

Title: joinquant 技术分析教程:基于 jqlib 构建 RSI 摆动指标策略

Question: 如何在 joinquant 中调用技术分析库计算 RSI 指标并实现超买超卖交易?

解决方案

joinquant 技术分析教程:基于 jqlib 构建 RSI 摆动指标策略

相对强弱指标(RSI)是量化交易中最常用的摆动类技术指标之一。在 JoinQuant(聚宽)平台上,我们可以通过内置的 jqlib.technical_analysis 快速计算 RSI,并结合超买超卖信号构建自动交易策略。


1. RSI 指标交易逻辑

  • 超卖信号(买入):当 RSI 指标低于设定的超卖阈值(如 30)时,表明市场可能被低估,产生买入信号。
  • 超买信号(卖出):当 RSI 指标高于设定的超买阈值(如 70)时,表明市场可能过度过热,产生平仓/卖出信号。

2. 完整 Python 策略代码

import jqdata
from jqlib.technical_analysis import RSI

def initialize(context):
    # 设定标的(如平安银行)
    g.security = '000001.XSHE'
    # 设定基准
    set_benchmark('000300.XSHG')
    # 真实价格模式(动态复权)
    set_option('use_real_price', True)
    # 设置交易手续费
    set_order_cost(OrderCost(close_tax=0.001, open_commission=0.0003, close_commission=0.0003, min_commission=5), type='stock')
    
    # 参数设置
    g.rsi_period = 14     # RSI 计算周期
    g.buy_threshold = 30  # 超卖买入界限
    g.sell_threshold = 70 # 超买卖出界限
    
    # 每日开盘交易
    run_daily(market_open, time='9:30')

def market_open(context):
    security = g.security
    current_date = context.current_dt.strftime('%Y-%m-%d')
    
    # 通过 jqlib 计算 RSI 指标
    # RSI 返回值为字典格式,key 为股票代码
    rsi_dict = RSI([security], check_date=current_date, N1=g.rsi_period)
    rsi_value = rsi_dict[security]
    
    # 若数据无效,跳过
    if rsi_value is None or rsi_value != rsi_value:
        return
        
    cash = context.portfolio.available_cash
    position = context.portfolio.positions[security].closeable_amount
    
    # 触发超卖:全仓买入
    if rsi_value < g.buy_threshold and cash > 0:
        order_value(security, cash)
        log.info("RSI (%.2f) < %d,超卖买入 %s" % (rsi_value, g.buy_threshold, security))
        
    # 触发超买:清仓卖出
    elif rsi_value > g.sell_threshold and position > 0:
        order_target(security, 0)
        log.info("RSI (%.2f) > %d,超买平仓 %s" % (rsi_value, g.sell_threshold, security))

3. 关键函数详解

  1. set_option('use_real_price', True):建议开启动态复权(真实价格)模式,可有效避免回测中的未来函数。
  2. from jqlib.technical_analysis import RSI:聚宽内置技术分析模块,直接调用 API 即可获得经过优化的指标计算结果。
  3. RSI(security_list, check_date, N1=14)
    • security_list:股票代码或股票列表。
    • check_date:查询日期。
    • N1:RSI 统计周期(默认常用周期为 6、12、14 或 24)。