MACD是股市最常用的指标,一般认为当DIF值由负变为正时为购买金融产品的时机,而DIF值由正变负时为卖出时机
算法思路
获取前一日的MACD值,当其大于0时候金融产品的买入,而当MACD小于时进行卖出
# coding=utf-8
from __future__ import print_function, absolute_import
from gm.api import *
import numpy as np
import talib
# 策略中必须有init方法
def init(context):
context.symbol = "SZSE.300296" # 利亚德
context.frequency = "1d"
context.fields = "open,high,low,close"
context.volume = 200
schedule(schedule_func=algo, date_rule="1d",time_rule="09:35:00")
def algo(context):
now = context.now
last_day = get_previous_trading_date("SZSE",now)
data = history_n(symbol=context.symbol, frequency=context.frequency, count=35, end_time=now, fields=context.fields, fill_missing="last", adjust=ADJUST_PREV, df=True)
open = np.asarray((data["open"].values))
high = np.asarray((data["high"].values))
low = np.asarray((data["low"].values))
close = np.asarray((data["close"].values))
macd,_,_ = talib.MACD(close)
macd = macd[-1]
if macd > 0:
order_volume(symbol=context.symbol, volume=context.volume, side=PositionSide_Long, order_type=OrderType_Market, position_effect=PositionEffect_Open)
print("买入")
elif macd < 0:
print("卖出")
order_volume(symbol=context.symbol, volume=context.volume,side=PositionSide_Short, order_type=OrderType_Market, position_effect=PositionEffect_Close)
if __name__ == '__main__':
run(strategy_id='xxxxxxxxxxxxxxxxx',
filename='main.py',
mode=MODE_BACKTEST,
token='xxxxxxxxxxxxxxxxxxxxxx',
backtest_start_time='2017-01-01 09:00:00',
backtest_end_time='2017-12-31 15:00:00',
backtest_initial_cash=20000,
backtest_adjust=ADJUST_PREV)