3 分钟快速生成代码
输入想法,AI 即刻生成可运行代码
相对强弱指标(RSI)是量化交易中最常用的摆动类技术指标之一。在 JoinQuant(聚宽)平台上,我们可以通过内置的 jqlib.technical_analysis 快速计算 RSI,并结合超买超卖信号构建自动交易策略。
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))
set_option('use_real_price', True):建议开启动态复权(真实价格)模式,可有效避免回测中的未来函数。from jqlib.technical_analysis import RSI:聚宽内置技术分析模块,直接调用 API 即可获得经过优化的指标计算结果。RSI(security_list, check_date, N1=14):
security_list:股票代码或股票列表。check_date:查询日期。N1:RSI 统计周期(默认常用周期为 6、12、14 或 24)。