量化投资入门教程六——技术指标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的安装到量化编程的实现只需简单几步(具体见=viewthread&tid=54&extra=page%3D1轻松安装Python、掘金量化平台及相关工具包)1.2策略代码(可直接在python中实现)1.2.1ma.ini[strategy]username=password=;回测模式mode=4td_addr=localhost:8001strategy_id=;订阅代码注意及时更新subscribe_symbols=SHFE.ag1705.tick,SHFE.ag1705.bar.60[backtest]start_time=2017-02-1521:00:00end_time=2017-03-0716: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###############################################################loggersettings##############################################################[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.2ma.py#!/usr/bin/envpython#encoding:utf-8importnumpyasnpfromcollectionsimportdequefromgmsdkimport*fromtalibimportSMA#算法用到的一些常量,阀值,主要用于信号过滤eps=1e-6threshold=0.235tick_size=0.2half_tick_size=tick_size/2significant_diff=tick_size*2.6classMA(StrategyBase):'''strategyexample1:MAdecisionpricecrosslongMA,thenplaceaorder,temporaryreversetrendsplacemoreorders'''def__init__(self,*args,**kwargs):#importpdb;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])self.last_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')or200self.timeperiod=self.config.getint('para','timeperiod')or20self.bar_type=self.config.getint('para','bar_type')or60self.close_buffer=deque(maxlen=self.window_size)self.significant_diff=self.config.getfloat('para','significant_diff')orsignificant_diff#preparehistoricalbarsforMAcalculating#从数据服务中准备一段历史数据,使得收到第一个bar后就可以按需要计算malast_closes=[bar.closeforbarinself.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数据到达事件defon_bar(self,bar):#确认下bar数据是订阅的分时ifbar.bar_type==self.bar_type:#把数据加入缓存self.close_buffer.append(bar.close)#调用策略计算self.algo_action()#响应tick数据到达事件defon_tick(self,tick):#更新市场最新成交价self.last_price=tick.last_pricedefon_execution(self,execution):#打印订单成交回报信息print((receivedexecution:%s%execution.exec_type))#策略的算法函数,策略的交易逻辑实现部分defalgo_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(self.last_price-last_ma,4)#当前最新价格跟ma之间的差,成交价相对ma偏离#print'close:',closeprint(('closemadelta:{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(('poslong:{0}vwap:{1},posshort:{2},vwap:{3}'.format(b_p.volumeifb_pelse0.0,round(b_p.vwap,2)ifb_pelse0.0,a_p.volumeifa_pelse0.0,round(a_p.vwap,2)ifa_pelse0.0)))ifcrossanddeltathresholdandmomentum=significant_diff:##收盘价上穿均线,且当前价格偏离满足门限过滤条件,多信号#没有空仓,开多if(a_pisNoneora_p.volumeeps):#依次获取下单的交易量,下单量是配置的一个整数数列,用于仓位管理,可用配置文件中设置vol=self.trade_unit[0]#如果本次下单量大于0,发出买入委托交易指令ifvoleps:self.open_long(self.exchange,self.sec_id,self.last_price,vol)else:#如果有空仓,平掉空仓ifa_panda_p.volumeeps:self.close_short(self.exchange,self.sec_id,self.last_price,a_p.volume)elifcrossanddelta-thresholdandmomentum=-significant_diff:##bar收盘价下穿ma均线,且偏离满足信号过滤条件#没有多仓时,开空if(b_pisNoneorb_p.volumeeps):vol=self.trade_unit[0]ifvoleps:self.open_short(self.exchange,self.sec_id,self.last_price,vol)else:#已有多仓,平掉多仓ifb_pandb_p.volumeeps:self.close_long(self.exchange,self.sec_id,self.last_price,b_p.volume)else:##其他情况,忽略不处理pass##订单完全成交defon_order_filled(self,order):print(('''receivedorderfilled:sec_id:{0},side:{1},volume:{2},filledprice:{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')#importpdb;pdb.set_trace()#python调试开关print('strategyready,waitingformarketdata......')#策略进入运行,等待数据事件ret=ma.run()#打印策略退出状态print((MAexit:{}.format(

1 / 12
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功