问题描述
import jqdata
from jqlib.technical_analysis import *
def initialize(context):
g.security = '000001.XSHE'
set_benchmark('000300.XSHG')
set_option('use_real_price',True)
def handle_data(context,data):
security = g.security
macd_diff,macd_dea,macd_macd = MACD(security,check_date=context.current_dt,SHORT=12,LONG=26,MID=9)
cash = context.portfolio.cash
if macd_diff>0 and macd_dea>0 and macd_diff > macd_dea:
order_value(security,cash)
log.info("买入股票%s"%(security))
elif macd_diff< 0 and macd_dea< 0 and macd_diff < macd_dea and context.portfolio.positions[security].closeable_amount > 0:
order_target(security,0)
log.info("卖出股票%s"%(security))
这个是按照书上写的MACD策略 总是提示
if macd_diff>0 and macd_dea>0 and macd_diff > macd_dea:
TypeError: '>' not supported between instances of 'dict' and 'int'
求高人指点
解决方案
你好!出现这个报错的原因是因为聚宽 jqlib.technical_analysis 库中的 MACD 函数返回的结果是字典(dict),而不是直接的数值(int 或 float)。
错误原因分析
当你调用 macd_diff, macd_dea, macd_macd = MACD(security, ...) 时,返回的 macd_diff 实际上是一个字典,格式类似于 {'000001.XSHE': 0.15}。字典的键是你传入的股票代码,值才是真正的 MACD 数值。
因此,当你写 if macd_diff > 0: 时,Python 尝试将一个字典和一个整数 0 进行比较,就会抛出 TypeError: '>' not supported between instances of 'dict' and 'int' 的错误。
解决方法
你需要通过股票代码作为键(key),从字典中把具体的数值提取出来,然后再进行比较。另外,context.portfolio.cash 已经过时,建议替换为 context.portfolio.available_cash。
修改后的正确代码
import jqdata
from jqlib.technical_analysis import *
def initialize(context):
g.security = '000001.XSHE'
set_benchmark('000300.XSHG')
set_option('use_real_price', True)
def handle_data(context, data):
security = g.security
# 获取 MACD 指标,返回的是三个字典
macd_diff_dict, macd_dea_dict, macd_macd_dict = MACD(
security,
check_date=context.current_dt,
SHORT=12, LONG=26, MID=9
)
# 从字典中提取出对应股票的具体数值
diff = macd_diff_dict[security]
dea = macd_dea_dict[security]
macd = macd_macd_dict[security]
# 获取可用资金(注意:cash 属性已过时,推荐使用 available_cash)
cash = context.portfolio.available_cash
# 使用提取出来的数值进行比较
if diff > 0 and dea > 0 and diff > dea:
order_value(security, cash)
log.info("买入股票 %s" % (security))
elif diff < 0 and dea < 0 and diff < dea and context.portfolio.positions[security].closeable_amount > 0:
order_target(security, 0)
log.info("卖出股票 %s" % (security))
总结
在使用聚宽的 jqlib.technical_analysis 技术指标库时,绝大多数指标函数(如 MACD, KDJ, RSI 等)为了支持同时计算多只股票,其返回值都是以股票代码为键、指标值为值的字典。在编写策略逻辑时,务必记得先通过 dict[security] 提取出数值再做逻辑判断。