当前位置:文档之家› 量化投资入门教程六——技术指标MA策略

量化投资入门教程六——技术指标MA策略

量化投资入门教程六——技术指标MA策略目录1.策略原理及代码1.1策略原理1.2策略代码1.2.1ATR.ini1.2.2ATR.py1.2.3stock_pool.csv2.Python相关函数2.1Python标准函数2.2掘金接口函数3.金融术语(移动平均线)1.策略原理及代码1.1策略原理基于ta-lib的MA策略。

如果当前价格高于MA,买入股票;如果当前价格低于MA,卖出股票。

实现量化投资策略的相关编程并非想象中这么困难,从Python的安装到量化编程的实现只需简单几步(具体见/q/forum.php?mod=viewthread&tid=54&extra=page%3D1轻松安装Python、掘金量化平台及相关工具包)1.2策略代码(可直接在python中实现)1.2.1 ma.ini[strategy]username=password=;回测模式mode=4td_addr=localhost:8001strategy_id=;订阅代码注意及时更新subscribe_symbols=SHFE.ag1705.tick,SHFE.ag1705.bar.60[backtest]start_time=2017-02-15 21:00:00end_time=2017-03-07 16:00:00;策略初始资金initial_cash=10000000;委托量成交比率,默认=1(每个委托100%成交)transaction_ratio=1;手续费率,默认=0(不计算手续费)commission_ratio=0.0004;滑点比率,默认=0(无滑点)slippage_ratio=0price_type=1;基准bench_symbol=SHSE.000300[para]trade_exchange=SHFEtrade_symbol=ag1705window_size=200bar_type=60tick_size=1significant_diff=21timeperiod=20############################################################## # logger settings############################################################## [loggers]keys=root[logger_root]level=DEBUGhandlers=console,file[handlers]keys=console,file[handler_file]class=handlers.RotatingFileHandlerargs=('ma.log','a','maxBytes=10000','backupCount=5')formatter=simple[handler_console]class=StreamHandlerargs = (sys.stdout,)formatter=simple[formatters]keys = simple[formatter_simple]format=%(asctime)s - %(name)s - %(levelname)s - %(message)sdatefmt=1.2.2 ma.py#!/usr/bin/env python# encoding: utf-8import numpy as npfrom collections import dequefrom gmsdk import *from talib import SMA# 算法用到的一些常量,阀值,主要用于信号过滤eps = 1e-6threshold = 0.235tick_size = 0.2half_tick_size = tick_size / 2significant_diff = tick_size * 2.6class MA(StrategyBase):''' strategy example1: MA decision price cross long MA, then place a order, temporary reverse trends place more orders '''def __init__(self, *args, **kwargs):#import pdb; pdb.set_trace()super(MA, self).__init__(*args, **kwargs)# 策略初始化工作在这里写,从外部读取静态数据,读取策略配置参数等工作,只在策略启动初始化时执行一次。

# 从配置文件中读取配置参数self.exchange = self.config.get('para', 'trade_exchange')self.sec_id = self.config.get('para', 'trade_symbol')self.symbol = ".".join([self.exchange, self.sec_id])st_price = 0.0self.trade_unit = [3, 1, 2, 0]# self.trade_count = 0self.trade_limit = len(self.trade_unit)self.window_size = self.config.getint('para', 'window_size') or 200self.timeperiod = self.config.getint('para', 'timeperiod') or 20self.bar_type = self.config.getint('para', 'bar_type') or 60self.close_buffer = deque(maxlen=self.window_size)self.significant_diff = self.config.getfloat('para', 'significant_diff') or significant_diff# prepare historical bars for MA calculating# 从数据服务中准备一段历史数据,使得收到第一个bar后就可以按需要计算malast_closes = [bar.close for bar in self.get_last_n_bars(self.symbol, self.bar_type,self.window_size,end_time=self.start_time)]last_closes.reverse() #因为查询出来的时间是倒序排列,需要倒一下顺序self.close_buffer.extend(last_closes)# 响应bar数据到达事件def on_bar(self, bar):# 确认下bar数据是订阅的分时if bar.bar_type == self.bar_type:# 把数据加入缓存self.close_buffer.append(bar.close)# 调用策略计算self.algo_action()# 响应tick数据到达事件def on_tick(self, tick):# 更新市场最新成交价st_price = st_pricedef on_execution(self, execution):#打印订单成交回报信息print(("received execution: %s" % execution.exec_type))#策略的算法函数,策略的交易逻辑实现部分def algo_action(self):# type: () -> object#数据转换,方便调用ta-lib函数进行技术指标的计算,这里用SMA指标close = np.asarray(self.close_buffer)ma = SMA(close, timeperiod=self.timeperiod)delta = round(close[-1] - ma[-1],4) # 最新数据点,bar的收盘价跟ma的差cross = (close[-1] - ma[-1]) * (close[-3] - ma[-3]) < 0 ## 判断有否交叉last_ma = round(ma[-1], 4) # 均线ma的最新值momentum = round(st_price - last_ma,4) # 当前最新价格跟ma之间的差,成交价相对ma偏离 #print 'close: ', closeprint(('close ma delta: {0}, last_ma: {1}, momentum: {2}'.format(delta, last_ma, momentum)))a_p = self.get_position(self.exchange, self.sec_id, OrderSide_Ask) #查询策略所持有的空仓b_p = self.get_position(self.exchange, self.sec_id, OrderSide_Bid) #查询策略所持有的多仓# 打印持仓信息print(('pos long: {0} vwap: {1}, pos short: {2}, vwap: {3}'.format(b_p.volume if b_p else 0.0, round(b_p.vwap,2) if b_p else 0.0,a_p.volume if a_p else 0.0,round(a_p.vwap,2) if a_p else 0.0)))if cross and delta > threshold and momentum >= significant_diff: ## 收盘价上穿均线,且当前价格偏离满足门限过滤条件,多信号# 没有空仓,开多if (a_p is None or a_p.volume < eps):# 依次获取下单的交易量,下单量是配置的一个整数数列,用于仓位管理,可用配置文件中设置 vol = self.trade_unit[0]# 如果本次下单量大于0, 发出买入委托交易指令if vol > eps:self.open_long(self.exchange, self.sec_id, st_price, vol)else:# 如果有空仓,平掉空仓if a_p and a_p.volume > eps:self.close_short(self.exchange, self.sec_id, st_price, a_p.volume)elif cross and delta < -threshold and momentum <= - significant_diff: ## bar 收盘价下穿ma 均线,且偏离满足信号过滤条件# 没有多仓时,开空if (b_p is None or b_p.volume < eps):vol = self.trade_unit[0]if vol > eps:self.open_short(self.exchange, self.sec_id, st_price, vol)else:# 已有多仓,平掉多仓if b_p and b_p.volume > eps:self.close_long(self.exchange, self.sec_id, st_price, b_p.volume)else: ## 其他情况,忽略不处理pass## 订单完全成交def on_order_filled(self, order):print(('''received order filled: sec_id: {0}, side: {1}, volume: {2}, filled price: {3}, filled: {4} '''.format(order.sec_id, order.side, order.volume, order.filled_vwap, order.filled_volume)))# 策略启动入口if __name__ == '__main__':# 初始化策略ma = MA(config_file='ma.ini')#import pdb; pdb.set_trace() # python调试开关print('strategy ready, waiting for market data ......')# 策略进入运行,等待数据事件ret = ma.run()# 打印策略退出状态print(("MA exit: {}".format(ma.get_strerror(ret))))2.Python相关函数2.1Python标准函数2.2掘金接口函数3.金融术语移动平均线:Moving Average,简称MA,原本的意思是移动平均,由于我们将其制作成线形,所以一般称之为移动平均线,简称均线。

相关主题