怎么调用KDJ和MACD指标
我现在想自己练习编写策略,想请教大神们我应该怎么在策略中调用KDJ或者MACD指标?
问题描述
解决方案
在JoinQuant(聚宽)平台上编写量化策略时,调用KDJ和MACD等经典技术指标是非常常见的需求。虽然聚宽的 jqlib 提供了一些内置指标,但最通用且灵活的方式是使用 Python 的第三方技术分析库 TA-Lib。
核心思路
- 获取历史数据:使用
attribute_history或get_bars获取股票的最高价(high)、最低价(low)和收盘价(close)。 - 调用 TA-Lib 计算指标:将获取到的数据传入
talib.MACD和talib.STOCH(计算KDJ)函数中。
完整策略示例代码
以下是一个简单的策略框架,演示了如何在 handle_data 中计算并调用这两个指标:
# 导入聚宽函数库
import jqdata
# 导入技术分析库 TA-Lib
import talib
import numpy as np
# 初始化函数
def initialize(context):
# 设定要操作的股票(如:平安银行)
g.security = '000001.XSHE'
# 设定沪深300作为基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 每个单位时间调用一次
def handle_data(context, data):
security = g.security
# 1. 获取历史数据 (KDJ需要high, low, close;MACD需要close)
# 获取过去35天的数据以确保指标计算有足够的数据预热
hist_data = attribute_history(security, 35, '1d', ['high', 'low', 'close'], df=True)
if len(hist_data) < 35:
return # 数据不足时跳过
close_prices = hist_data['close'].values
high_prices = hist_data['high'].values
low_prices = hist_data['low'].values
# 2. 计算 MACD 指标
# talib.MACD 返回三个数组: macd (DIF), macdsignal (DEA), macdhist (MACD柱)
macd, macdsignal, macdhist = talib.MACD(close_prices, fastperiod=12, slowperiod=26, signalperiod=9)
# 获取最新一天的 MACD 值
current_macd = macd[-1]
current_signal = macdsignal[-1]
current_hist = macdhist[-1]
# 3. 计算 KDJ 指标
# talib.STOCH 计算 KD 值,J 值需要手动计算 (J = 3*K - 2*D)
slowk, slowd = talib.STOCH(high_prices, low_prices, close_prices,
fastk_period=9, slowk_period=3, slowk_matype=0,
slowd_period=3, slowd_matype=0)
# 获取最新一天的 K, D, J 值
current_k = slowk[-1]
current_d = slowd[-1]
current_j = 3 * current_k - 2 * current_d
# 打印日志查看指标值
log.info("MACD: DIF=%.2f, DEA=%.2f, HIST=%.2f" % (current_macd, current_signal, current_hist))
log.info("KDJ: K=%.2f, D=%.2f, J=%.2f" % (current_k, current_d, current_j))
# 4. 简单的交易逻辑示例 (金叉买入,死叉卖出)
cash = context.portfolio.available_cash
positions = context.portfolio.positions[security].closeable_amount
# MACD 金叉 (DIF 上穿 DEA) 且 KDJ 的 J 值小于 100 (防止超买)
if macd[-2] < macdsignal[-2] and macd[-1] > macdsignal[-1] and current_j < 100:
if cash > 0:
order_value(security, cash)
log.info("MACD金叉,买入 %s" % security)
# MACD 死叉 (DIF 下穿 DEA)
elif macd[-2] > macdsignal[-2] and macd[-1] < macdsignal[-1]:
if positions > 0:
order_target(security, 0)
log.info("MACD死叉,卖出 %s" % security)
关键点解析
- 数据长度:计算MACD和KDJ需要一定长度的历史数据进行平滑计算(通常称为预热期)。例如MACD默认慢线是26天,建议至少获取35天以上的数据(
attribute_history(..., 35, ...))。 - TA-Lib的输入格式:TA-Lib的函数要求输入的数据类型为
numpy.ndarray,因此我们使用.values将 pandas 的 Series 转换为 numpy 数组。 - KDJ的J值:TA-Lib的
STOCH函数只返回 K 值和 D 值,J 值需要根据公式J = 3 * K - 2 * D自行计算。
通过这种方式,你可以轻松地在聚宽平台上调用并组合各种复杂的技术指标来完善你的量化策略。