量化 | 基础框架(下)
2021-09-02 本文已影响0人
opcc
更多
只有这些还不够,可以根据自己的需要再完善功能。我为了满足需求,又增加了参数调优和绘图功能。
所谓参数调优,就是把测试了一次的策略换不同参数再测,获得最优解。然而这毕竟是拟合过程,对于不同标的最优参数肯定是不一样的,而且历史数据得出的参数也不能代表未来一定受用,只能作为分析的参考。
def SarN(df,ma,s,m,cash):
result = []
ma = df['close'].rolling(window=ma).mean()
for i in range(1,s+1,2):
for j in range(1,m+1,2):
#sar = talib.SAR(df.high, df.low,i/100,j/100)
sar = mySAR(df,i/100,j/100)
status = md = lastc = shou = count = win = 0
cash0 = cash
for k in range(len(df)):
if ma[k]>=sar[k] and ma[k-1]<sar[k-1] and status==0:
lastc = df.close[k]
shou = int(cash/lastc/100)
buy = df.close[k]*shou*100
status = 1
cash0 -= buy*1.007
count += 1
if (ma[k]<=sar[k] and ma[k-1]>sar[k-1] or k==len(df)-1) and status==1:
sell = df.close[k]*shou*100
status = 0
cash0 += sell
chajia = df.close[k]-lastc
lastmd = round((chajia)/lastc*10,2)
if lastmd < md:
md = lastmd
if chajia > 0:
win +=1
if count == 0:
sl = 0
else:
sl = round(win/count*100,2)
lrl = round((cash0-cash)/cash*10,2)
result.append([i/10,j/10,lrl,md,sl])
result = sorted(result,key=(lambda x:[x[2],x[3]]),reverse=True)
return result[0]
我是按利润率和最大回撤排序出最好的参数组合作为结果返回的。
绘图可以直观分析策略好坏。基于matplotlib库的mplfinance库专门用于金融类绘图。
def tu(df,tb1,tb2,hs300,m1=[],m2=[],p=[]):
#s1 = np.where(tb3<0,np.nan,tb3)
#s2 = np.where(tb3>0,np.nan,tb3)
add_plot = [mpf.make_addplot(m1,scatter=True, markersize=100, marker='^', color='m'),
mpf.make_addplot(m2,scatter=True, markersize=100, marker='v', color='c'),
#mpf.make_addplot(p,scatter=True, markersize=100, marker='.',color='b'),
mpf.make_addplot(tb1),
mpf.make_addplot(tb2),
mpf.make_addplot(hs300,panel=2,color='b'),
mpf.make_addplot(p,panel=2, scatter=True, markersize=200, marker='.',color='r')
]
mc = mpf.make_marketcolors(up='r',down='g',edge='inherit',
wick={'up':'r','down':'g'},
volume='cornflowerblue',
ohlc='i'
)
s = mpf.make_mpf_style(marketcolors=mc,
facecolor='black',
edgecolor='snow',
figcolor='black',
gridcolor='snow',
gridstyle=':',
rc={'font.family':'SimHei',
'axes.unicode_minus':'False',
'axes.edgecolor':'snow',
'axes.labelcolor': 'snow',
'axes.titlecolor': 'snow',
'grid.alpha':0.5,
'ytick.color':'snow',
'xtick.color':'snow'
})
mpf.plot(df,
type='candle',
volume=True,
addplot=add_plot,
style=s,
datetime_format='%Y-%m-%d',
#tight_layout=True,
figscale=1.5,
xrotation=15,
title='沪深300',
ylabel='价格',
ylabel_lower='成交量')
plt.show()
大体框架有了,代码还需优化,功能有待完善。