来源:袖手财经 作者:袖手
本文选取股票“002617.SZ”(露笑科技)2019.01.01-2020.04.03区间的交易数据,对双均线策略进行了Python实现,并对回测结果予以评述。
(一)双均线策略规则:
-
短均线上穿长均线(金叉),买进;
-
短均线下穿长均线(死叉),卖出;
-
其余情况,无操作。
(二)Python实现过程:
#导入相关模块
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
#从Wind接口导出数据,并转换为DataFrame形式输出。
from WindPy import w
w.start()
raw_data=w.wsd("002617.SZ", "close", "2019-01-01", "2020-04-03", "Fill=Previous")
if raw_data.ErrorCode == 0:
#数据装入Pandas的DataFrame
fm=pd.DataFrame(raw_data.Data,index=raw_data.Fields,columns=raw_data.Times).T
fm['LMA'] = fm.CLOSE.rolling(12,min_periods = 0).mean() #12日均线时间序列
fm['SMA'] = fm.CLOSE.rolling(6,min_periods = 0).mean() #6日均线时间序列
fm['position']=0 #记录持仓
fm['trade']=0 #记录交易
fm['time']=raw_data.Times #日期序列
print('fm:/n',fm)
else:
print("Error Code:",raw_data.ErrorCode)
print("Error Message:", raw_data.Data[0][0])
#策略函数
def Strategy(fm):
for i in range(12,len(fm)-1):
#当前空仓、金叉,买进。
if (fm.SMA[i-1]<fm.LMA[i-1]) & (fm.SMA[i]>fm.LMA[i]) & (fm.position[i]==0):
fm.iloc[i,4]=1
fm.iloc[i+1,3]=1
#当前持仓、死叉,卖出。
elif (fm.SMA[i-1]>fm.LMA[i-1]) & (fm.SMA[i]<fm.LMA[i]) & (fm.position[i]==1):
fm.iloc[i,4]=-1
fm.iloc[i+1,3]=0
#其他情况,仓位不变。
else:
fm.iloc[i+1,3]=fm.iloc[i,3]
#日收益率ret,累计净值nav,基准净值benchmark。
fm['ret'] = fm.CLOSE.pct_change(1).fillna(0)
fm['nav'] = (1 + fm.ret*fm.position).cumprod()
fm['benchmark'] = fm.CLOSE/fm.CLOSE[0]
return fm
#评价函数
def Performace(fm):
# 年化收益率
rety = fm.nav[fm.shape[0] - 1]**(250/fm.shape[0]) - 1
# 夏普比率
Sharp = (fm.ret*fm.position).mean()/(fm.ret*fm.position).std()*np.sqrt(250)
# 最大回撤率
DrawDown = 1 - fm.nav/fm.nav.cummax()
MaxDrawDown = max(DrawDown)
print('夏普比率为:',round(Sharp,2))
print('年化收益率为:{}%'.format(round(rety*100,2)))
print('最大回撤为:{}%'.format(round(MaxDrawDown*100,2)))
# 作图
xtick = np.round(np.linspace(0,fm.shape[0] - 1,7),0)
xtick = xtick.astype(np.int)
xticklabel = fm.time[xtick]
plt.figure(figsize = (9,4))
ax = plt.axes()
plt.plot(np.arange(fm.shape[0]),fm.benchmark,'black',label = 'benchmark',linewidth = 2)
plt.plot(np.arange(fm.shape[0]),fm.nav,'red',label = 'nav',linewidth = 2)
#RS为相对强弱指数。
plt.plot(np.arange(fm.shape[0]),fm.nav/fm.benchmark,'yellow',label = 'RS',linewidth = 2)
plt.legend()
ax.set_xticks(xtick)
ax.set_xticklabels(xticklabel)
return rety,Sharp,MaxDrawDown
fm=Strategy(fm)
rety,Sharp,MaxDrawDown= Performace(fm)
(三)运行结果呈现:
夏普比率为: 0.31 年化收益率为:3.84% 最大回撤为:40.7%
推荐阅读: