《海龟交易法则》中介绍了一种趋势类的择时策略——N日突破策略。策略的核心思想为:当天收盘价超过N1天内最高价认为上升趋势成立,作为买入信号;当天收盘价低于N2天内最低价格认为下跌趋势成立,作为卖出信号。也就是说,N日趋势突破买入即为N日创新高买入,股价创出阶段性新高或历史新高后,一方面说明该股有资金在运作,相对比较强势,更容易顺势而上,另一方面创新高后近期买入的投资者都有获利,上档的套牢盘比较少,股价上冲的阻力也较小,更容易继续上涨。反之,N日趋势跌破时卖出的逻辑思维一样成立。
实现例程
# N日突破择时策略
import pandas_datareader.data as web
import pandas as pd
import numpy as np
import datetime
import matplotlib.pyplot as plt
#股票数据获取及处理接口
def GetStockDatApi(stockName=None,stockTimeS=None,stockTimeE=None, N1=15,N2=5):
stockdata = web.DataReader(stockName, "yahoo", stockTimeS, stockTimeE)
stockdata['N1_High'] = stockdata.High.rolling(window=N1).max()#计算最近N1个交易日最高价
expan_max = stockdata.Close.expanding().max()
stockdata['N1_High'].fillna(value=expan_max,inplace=True)#目前出现过的最大值填充前N1个nan
stockdata['N2_Low'] = stockdata.Low.rolling(window=N2).min()#计算最近N2个交易日最低价
expan_min = stockdata.Close.expanding().min()
stockdata['N2_Low'].fillna(value=expan_min,inplace=True)#目前出现过的最小值填充前N2个nan
#收盘价超过N1最高价 买入股票持有
buy_index = stockdata[stockdata.Close > stockdata.N1_High.shift(1)].index
stockdata.loc[buy_index,'signal'] = 1
#收盘价超过N2最低价 卖出股票持有
sell_index = stockdata[stockdata.Close < stockdata.N2_Low.shift(1)].index
stockdata.loc[sell_index,'signal'] = 0
stockdata['signal'].fillna(method = 'ffill',inplace = True)
stockdata['signal'] = stockdata.signal.shift(1)
stockdata['signal'].fillna(method = 'bfill',inplace = True)
return stockdata
# N日突破买卖信号区间显示
skip_days = 0
df_stockload = GetStockDatApi("600410.SS",datetime.datetime(2018, 10, 1), datetime.datetime(2019, 4, 1))
print(df_stockload)
df_stockload.Close.plot()
for kl_index, today in df_stockload.iterrows():
if today.signal == 1 and skip_days == 0: # 买入
skip_days = -1
start = df_stockload.index.get_loc(kl_index)
plt.annotate('买入',xy=(kl_index,df_stockload.Close.asof(kl_index)),xytext=(kl_index, df_stockload.Close.asof(kl_index)+2),arrowprops=dict(facecolor='r',shrink=0.1),horizontalalignment='left',verticalalignment='top')
print("buy:",kl_index)
elif today.signal == 0 and skip_days == -1: # 卖出
skip_days = 0
end = df_stockload.index.get_loc(kl_index)
if df_stockload.Close[end] < df_stockload.Close[start]: # 赔钱显示绿色
plt.fill_between(df_stockload.index[start:end], 0, df_stockload.Close[start:end], color='green', alpha=0.38)
else: # 赚钱显示红色
plt.fill_between(df_stockload.index[start:end], 0, df_stockload.Close[start:end], color='red', alpha=0.38)
plt.annotate('卖出',xy=(kl_index,df_stockload.Close.asof(kl_index)),xytext=(kl_index+datetime.timedelta(days=5), df_stockload.Close.asof(kl_index)+2),arrowprops=dict(facecolor='g',shrink=0.1),horizontalalignment='left',verticalalignment='top')
print("sell:",kl_index)
plt.legend(loc='best')
plt.title(u"华胜天成 N日突破择时")
plt.show()
"""
#买/卖时间
buy: 2018-11-07 00:00:00
sell: 2018-11-26 00:00:00
buy: 2019-01-17 00:00:00
sell: 2019-01-22 00:00:00
buy: 2019-02-19 00:00:00
"""
输出
总结
介绍了N日突破择时策略的实现,需要说明的是该策略中并未考虑风险因素、设定止损机制、仓位分配机制,并且也忽略了手续费,仅作为入门研究参考