量化交易入门笔记-MACD指标策略

'''
实现DIFF、DEA均为正,DIFF向上突破DEA,买入股票;
DIFF、DEA均为负,DIFF向下突破DEA,卖出股票
'''

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指标的DIF/DEA和MACK的值
    macd_diff, macd_dea, macd_macd = MACD(security, check_date=context.current_dt, SHORT=12, LONG=16, MID=9)
    print(macd_diff, macd_dea, macd_macd)
    # 取得当前现金
    cash = context.portfolio.cash
    # 如果当前有余额,并且DIFF/DEA均为正,DEFF向上突破DEA
    if macd_diff > 0 and macd_dea > 0 and macd_diff > 0:
        # 用所有cash买入股票
        order_value(security, cash)
        # 输出日志
        log.info('买入股票 %s' % (security))
    # 如果DIFF/DEA均为负,DIFF向下跌破DEA,并且目前有头寸
    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))

回测详情:

注:本文章为个人学习笔记,参考了一些书籍与官方教程,不作任何商业用途!

猜你喜欢

转载自blog.csdn.net/weixin_38486884/article/details/83111208