提供一个刚入门的量化策略,5日均线突破10日买入,5日均线突破10日卖出。最后采用盈利20%。
import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
pro = ts.pro_api()
df = pro.daily(ts_code='000333.SZ', start_date='20150101', end_date='20181216')
介绍一下Tushare,这是一个很方便调取数据的地方,大家注册后就可以导出股票的任何数据
网站地址:https://tushare.pro/
ts_code是输入股票代码,后面是两个日期,这样就能得出美的DataFrame形式的数据。
df.index=df.iloc[:,1]
df=df.sort_values(by=["trade_date"],ascending=True)
df.index=pd.to_datetime(df.index,format='%Y-%m-%d')
这里是由于Tushare导出来的数据是现在的排在前面,所以要重新排序一下
data=pd.DataFrame(index=df.index,columns=['close','mean5','mean10','signal'])
data['close']=df.close
data['mean5']=data.close.rolling(5).mean()
data['mean10']=data.close.rolling(10).mean()
data.mean5.iloc[0:9]=data.close.iloc[0:9]
data.mean10.iloc[0:9]=data.close.iloc[0:9]
plt.figure(figsize=(13,6), dpi=80)
plt.plot(data.close)
plt.plot(data.mean5)#5日20日均线图
plt.plot(data.mean10)
生成移动均线
for i in range(1,len(data)):#上穿为1,开仓,下穿为-1,空仓
if data.mean5.iloc[i]>data.mean10.iloc[i] and data.mean5.iloc[i-1] data.signal.iloc[i]=1 elif data.mean5.iloc[i] data.signal.iloc[i]=-1 else: data.signal.iloc[i]=0 data.signal.iloc[0:2]=0 生成信号 #定义策略 def strategy(data,fee): c=pd.DataFrame(index=data.index,columns=['close','signal','amount','a1','a2','cash','asset']) c.open=wanke.open c.close=data.close c.signal=data.signal c.amount.iloc[0]=0 c.cash.iloc[0]=1000000 c.asset.iloc[0]=1000000 for i in range(1,len(data)): if c.signal.iloc[i]==0:#信号为0,持仓不变 c.amount.iloc[i]=c.amount.iloc[i-1]#持仓量 c.a1.iloc[i]=0#开仓量 c.a2.iloc[i]=0#出仓量 c.cash.iloc[i]=c.cash.iloc[i-1] c.asset.iloc[i]=c.cash.iloc[i]+c.amount.iloc[i]*c.close.iloc[i]*100 elif c.signal.iloc[i]==1:#5日均线大于10日均线,预计未来上升,开仓 c.a1.iloc[i]=int(1/2*c.cash.iloc[i-1]/c.open.iloc[i]/100) c.a2.iloc[i]=0 c.amount.iloc[i]=c.amount.iloc[i-1]+c.a1.iloc[i] c.cash.iloc[i]=c.cash.iloc[i-1]-c.a1.iloc[i]*c.open.iloc[i]*100*(1+fee) c.asset.iloc[i]=c.cash.iloc[i]+c.amount.iloc[i]*c.close.iloc[i]*100 elif c.signal.iloc[i]==-1: c.a1.iloc[i]=0 c.a2.iloc[i]=int(1/3*c.amount.iloc[i-1]) c.amount.iloc[i]=c.amount.iloc[i-1]-c.a2.iloc[i] c.cash.iloc[i]=c.cash.iloc[i-1]+c.a2.iloc[i]*c.open.iloc[i]*100*(1-fee) c.asset.iloc[i]=c.cash.iloc[i]+c.amount.iloc[i]*c.close.iloc[i]*100 return c fee=0.0002 final=strategy(data,fee) 交易策略 #计算夏普比 d=pd.DataFrame(index=final.index,columns=['asset','dailyreturn','exturn','cumret']) d['asset']=final['asset'] for i in range(1,len(d)): d.dailyreturn.ix[i]=(d.asset.ix[i]-d.asset.ix[i-1])/d.asset.ix[i-1] d['exturn']=d['dailyreturn']-0.04/250 stdexturn=d['exturn'].std() meanexturn=d['exturn'].mean() import numpy as np ASR=np.sqrt(250)*meanexturn/stdexturn print(ASR) 计算夏普比 plt.plot(d.asset)#资产变动图