@Channelchan
2018-01-06T06:43:26.000000Z
字数 4599
阅读 85995
用Python量化你的技术分析
均线理论是当今应用最普遍的技术指标之一,它帮助交易者确认现有趋势、判断将出现的趋势、发现过度延生即将反转的趋势。另外均线与趋势是西蒙斯被TED采访时提到的关键词,因此做量化你必须懂,而且是深入地懂这两个词的真正意义。






from jaqs.data import DataViewfrom jaqs.data import RemoteDataServiceimport osimport numpy as npimport talib as taimport pandas as pdfrom datetime import datetimeimport matplotlib.pyplot as pltimport warningswarnings.filterwarnings("ignore")dv = DataView()dataview_folder = 'JAQS_Data/hs300'dv.load_dataview(dataview_folder)
Dataview loaded successfully.
def change_index(df):df.index = pd.Index(map(lambda x: datetime.strptime(str(x),"%Y%m%d") , df.index))return df
data = change_index(dv.get_ts('close').loc[20170105:])data['SMA'] = ta.abstract.MA(data, 20, price='600036.SH')data['WMA'] = ta.abstract.WMA(data, 20, price='600036.SH')data['TRIMA'] = ta.abstract.TRIMA(data, 20, price='600036.SH')data['EMA'] = ta.abstract.EMA(data, 20, price='600036.SH')data['DEMA'] = ta.abstract.DEMA(data, 20, price='600036.SH')data['KAMA'] = ta.abstract.KAMA(data, 20, price='600036.SH')
fig = plt.figure(figsize=(15, 7))plt.plot(data['600036.SH'])plt.plot(data['SMA'], alpha=0.5)plt.plot(data['WMA'], alpha=0.5)plt.plot(data['TRIMA'], alpha=0.5)plt.plot(data['EMA'], alpha=0.5)plt.plot(data['DEMA'], alpha=0.5)plt.plot(data['KAMA'], alpha=0.5)plt.legend(loc='lower right')plt.show()

两条均线的三种交易方法
1. 当均线金叉(短期大于长期均线)时候买进,死叉(短期小于长期)时卖出。
2. 当价格上穿两条均线时买入,但价格下穿其中一条均线时卖出。
3. 当两条均线都处于向上方向时买入,当两条均线都处于下跌方向时卖出。
#MA_Strategy_1import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.SHORTPERIOD = 10context.LONGPERIOD = 20def handle_bar(context, bar_dict):price = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')short_avg = talib.SMA(price, context.SHORTPERIOD)long_avg = talib.SMA(price, context.LONGPERIOD)plot("short avg", short_avg[-1])plot("long avg", long_avg[-1])# 计算现在portfolio中股票的仓位cur_position = context.portfolio.positions[context.s1].quantity# 计算现在portfolio中的现金可以购买多少股票shares = context.portfolio.cash/bar_dict[context.s1].close# 如果短均线从上往下跌破长均线,也就是在目前的bar短线平均值低于长线平均值,而上一个bar的短线平均值高于长线平均值if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0:# 进行清仓order_target_value(context.s1, 0)# 如果短均线从下往上突破长均线,为入场信号if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0:# 满仓入股order_shares(context.s1, shares)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-31","accounts": {'stock':1000000},"benchmark": "000001.XSHE"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

#MA_Strategy_2import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.SHORTPERIOD = 10context.LONGPERIOD = 20def handle_bar(context, bar_dict):price = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')short_avg = talib.SMA(price, context.SHORTPERIOD)long_avg = talib.SMA(price, context.LONGPERIOD)cur_position = context.portfolio.positions[context.s1].quantityshares = context.portfolio.cash/bar_dict[context.s1].closeif price[-1] < short_avg[-1] or price[-1] < long_avg[-1] and cur_position > 0:order_target_value(context.s1, 0)if price[-1] > short_avg[-1] and price[-1] > long_avg[-1]:order_shares(context.s1, shares)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-31","accounts": {'stock':1000000},"benchmark": "000001.XSHE"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

#MA_Strategy_3import rqalphafrom rqalpha.api import *import talibdef init(context):context.s1 = "000001.XSHE"context.SHORTPERIOD = 10context.LONGPERIOD = 30def handle_bar(context, bar_dict):price = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close')short_avg = talib.SMA(price, context.SHORTPERIOD)long_avg = talib.SMA(price, context.LONGPERIOD)cur_position = context.portfolio.positions[context.s1].quantityshares = context.portfolio.cash/bar_dict[context.s1].closeif len(long_avg)== context.LONGPERIOD+1:if short_avg[-1] < short_avg[-2] and long_avg[-1] < long_avg[-2] and cur_position > 0:order_target_value(context.s1, 0)if short_avg[-1] > short_avg[-2] and long_avg[-1] > long_avg[-2]:order_shares(context.s1, shares)config = {"base": {"start_date": "2015-06-01","end_date": "2017-12-30","accounts": {'stock':1000000},"benchmark": "000001.XSHE"},"extra": {"log_level": "error",},"mod": {"sys_analyser": {"enabled": True,"plot": True}}}rqalpha.run_func(init=init, handle_bar=handle_bar, config=config)

更换标的与均线类型回测策略。
