双均线策略加上MACD指标过滤(附:量化策略源码)

# -*- coding: utf-8 -*-

# 简便起见,可以直接用 from gm.api import *
from gm.api import run
from gm.api import ADJUST_PREV
from gm.api import MODE_BACKTEST
from gm.api import subscribe
from gm.api import history_n
from gm.api import order_percent
from gm.api import order_volume
from gm.api import (OrderSide_Buy, OrderSide_Sell)
from gm.api import (PositionEffect_Open, PositionEffect_Close)
from gm.api import OrderType_Market
from datetime import datetime
from datetime import timedelta
import talib
import numpy as np
from collections import deque

#本策略基于掘金量化交易平台 网址:www.myquant.cn

# 常用参量设置
DATE_STR = "%Y-%m-%d"
TIME_STR = "%Y-%m-%d %H:%M:%S"

HIST_WINDOW = 40
SHORT_PERIOD = 5
LONG_PERIOD = 20

def init(context):
    # 全局变量设置
    context.dict_stock_price = dict()
    # 以 50 EFT作为交易标的
    context.stock_pool = ['SHSE.600000']
    # 订阅日线行情
    subscribe(symbols=context.stock_pool, frequency='1d', wait_group=True)
    # 日期设定,避免出现未来函数,将起始日往前取一日
    start_date = datetime.strptime(context.backtest_start_time, TIME_STR)
    context.start_date = datetime.strftime(start_date - timedelta(days=1),
                                           TIME_STR)
    # 获取起始日之前行情,便于计算指标
    deque_close = deque(maxlen=HIST_WINDOW)
    for stock in context.stock_pool:
        history_info = history_n(symbol=stock, 
                                 frequency='1d', 
                                 count=HIST_WINDOW,
                                 adjust=ADJUST_PREV,
                                 adjust_end_time=context.backtest_end_time,
                                 end_time=context.start_date,
                                 fields='close')
        for bar in history_info:
            deque_close.append(bar['close'])
        context.dict_stock_price.setdefault(stock, deque_close)
    print('finish initialization')
        
def on_bar(context, bars):
    for bar in bars:
        if bar.symbol not in context.dict_stock_price.keys():
            print('Warning: cannot obtain price of stock {} at date {}'.format(
                    bar.symbol, context.now))
        # 数据填充
        context.dict_stock_price[bar.symbol].append(bar.close)
        # 计算指标,这里以双均线为例
        closes = np.array(context.dict_stock_price[bar.symbol])
        short_ma = talib.SMA(closes, SHORT_PERIOD)
        long_ma = talib.SMA(closes, LONG_PERIOD)
        macd, macd_signal, macd_hist = talib.MACD(closes, 
                                                  fastperiod=12, 
                                                  slowperiod=26, 
                                                  signalperiod=9)
        # 金叉,满仓买入
        if short_ma[-2] <= long_ma[-2] and short_ma[-1] > long_ma[-1]:
            order_percent(symbol=bar.symbol,
                          percent=1.0,
                          side=OrderSide_Buy,
                          order_type=OrderType_Market,
                          position_effect=PositionEffect_Open,
                          price=0)
            print(context.now)
        # 死叉或者 MACD 绿柱,全部卖出
        pos = context.account().position(symbol=bar.symbol, side=OrderSide_Buy)
        if (short_ma[-2] >= long_ma[-2] and short_ma[-1] < long_ma[-1]) or \
            macd_hist[-1] < 0:
            if pos is None:
                continue
            order_volume(symbol=bar.symbol,
                         volume=pos.volume,
                         side=OrderSide_Sell,
                         order_type=OrderType_Market,
                         position_effect=PositionEffect_Close,
                         price=0)
if __name__ == "__main__":
    run(strategy_id='569b4ffc-6d44-11e8-bd88-80ce62334e41',
        filename='demo_05.py',
        mode=MODE_BACKTEST,
        backtest_adjust=ADJUST_PREV,
        token='64c33fc82f334e11e1138eefea8ffc241db4a2a0',
        backtest_start_time='2017-01-17 09:00:00',
        backtest_end_time='2018-06-21 15:00:00')

来源:掘金量化 myquant.cn

推荐阅读: | 量化交易  | 期货模拟交易 | python量化交易 | 股票数据  | 量化交易策略 | 机器学习算法  | 多因子选股 |  

                   | 双均线策略 |  网格交易法 |  海龟交易法  |  跨期套利  | 行业轮动  | 指数增强  | 跨品种套利 | 日内交易 | 

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值