# python实现量化交易策略

## 2 构建策略

``````import tushare as ts
import pandas as pd
import numpy as np
import copy

pro = ts.pro_api('你的token')
#1 获取沪深300成分股日线行情数据
def hqsj_hs():
df=pd.DataFrame()
for i in range(len(df1)):
df2 = pro.daily(ts_code=df1.iloc[i,1], start_date='20200101', end_date='20201231')
df=pd.concat([df,df2],axis=0)
df.to_excel('股票数据.xlsx',index=False)
hqsj_hs()
``````

``````#2 计算相关性
def xgx():
result={}
for i in range(len(df)):
key=df.iloc[i,0]
if result.get(key,False):
result[key].append(df.iloc[i,-3])
else:
result[key] = [df.iloc[i,-3]]

result1=copy.deepcopy(result)
for i in result:
if len(result[i])!=243:
del result1[i]

for i in result1:
result1[i].append([result1[i][1:],result1[i][:-1]])

result2={}
for i in result1:
aa = {}
now=pd.Series(result1[i][-1][0])
for j in result1:
pre=pd.Series(result1[j][-1][1])
xgx=now.corr(pre)
aa[j]=abs(xgx)
result2[i]=aa
#print(result2)

result3={}
for i in result2:
result3[i]={max(zip(result2[i].values(), result2[i].keys()))[1]:max(zip(result2[i].values(), result2[i].keys()))[0]}

xxx=[]
for i in result3:
for j in result3[i]:
xxx.append(result3[i][j])
b=sorted(xxx,reverse = True)[:1] #取相关性最大的

result4={}
for i in result3:
for j in result3[i]:
for x in b:
if x==result3[i][j]:
result4[i]={j:x}
print(result4)
return result4
``````

## 3 买股方案

``````#3 获取21年数据
def test_data():
result4=xgx()
ts_code=[]
for i in result4:
for j in result4[i]:
ts_code.append(j)
df = pd.DataFrame()
for i in ts_code:
df1 = pro.daily(ts_code=i, start_date='20210101', end_date='20210331')
df = pd.concat([df, df1], axis=0)
df.to_excel('股票数据1.xlsx', index=False)
test_data()

#4 买股方案
def mgfa():
timetime=list(set(timeseries))
timetime1=sorted(timetime)
result4=xgx()
ts1=[] #昨天
ts2=[] #今天
for i in result4:
ts2.append(i)
for j in result4[i]:
ts1.append(j)

result1={}
for i in range(len(df)):
time=df.iloc[i,1]
if result1.get(time,False):
aa.append(df.iloc[i,-3])
else:
aa=[]
aa.append(df.iloc[i,-3])
result1[time]=aa

result2={}
for i in result1:
if i!=20210331:
aaa=[]
for j in result1[i]:
if j >0:
aaa.append(ts2[result1[i].index(j)])
result2[timetime1[timetime1.index(i)+1]]=aaa
print(result2)
return result2
mgfa()
``````

## 4 评估策略

``````#5 获取测试数据
def cssj():
result4=xgx()
ts_code=[]
for i in result4:
ts_code.append(i)
df = pd.DataFrame()
for i in ts_code:
df1 = pro.daily(ts_code=i, start_date='20210101', end_date='20210331')
df = pd.concat([df, df1], axis=0)
df.to_excel('股票数据2.xlsx', index=False)
cssj()

#6 评估策略
def jssy():
result2=mgfa()
result4=xgx()
zdf=[]
for i in result2:
if len(result2[i]) == 1:
for j in result2[i]:
for x in range(len(df)):
if df.iloc[x, 0] == j and df.iloc[x, 1] == i:
zdf.append(df.iloc[x, -3])
else:
zdf.append(0)
bbb=1
for i in zdf:
bbb=bbb*(1+i/100)
bb=(bbb-1)*100
print('总收益率/%:',bb)
print('夏普率：', np.mean(zdf)/np.std(zdf,ddof=1))
ccc=1
hc=1
max_hc=[]
for i in zdf:
kk=ccc*(1+i/100)
if kk<ccc:
hc=hc*(1+i/100)
else:
hc=(hc-1)*100
max_hc.append(hc)
hc=1
ccc=copy.deepcopy(kk)
print('最大回撤/%:',abs(min(max_hc)))
jssy()
``````

## 完整代码

``````import tushare as ts
import pandas as pd
import numpy as np
import copy

pro = ts.pro_api('你的token')
#1 获取沪深300成分股日线行情数据
def hqsj_hs():
df=pd.DataFrame()
for i in range(len(df1)):
df2 = pro.daily(ts_code=df1.iloc[i,1], start_date='20200101', end_date='20201231')
df=pd.concat([df,df2],axis=0)
df.to_excel('股票数据.xlsx',index=False)
hqsj_hs()
#股票数据.xlsx需要手动将excel表按股票代码和交易日期升序
#2 计算相关性
def xgx():
result={}
for i in range(len(df)):
key=df.iloc[i,0]
if result.get(key,False):
result[key].append(df.iloc[i,-3])
else:
result[key] = [df.iloc[i,-3]]

result1=copy.deepcopy(result)
for i in result:
if len(result[i])!=243:
del result1[i]

for i in result1:
result1[i].append([result1[i][1:],result1[i][:-1]])

result2={}
for i in result1:
aa = {}
now=pd.Series(result1[i][-1][0])
for j in result1:
pre=pd.Series(result1[j][-1][1])
xgx=now.corr(pre)
aa[j]=abs(xgx)
result2[i]=aa
#print(result2)

result3={}
for i in result2:
result3[i]={max(zip(result2[i].values(), result2[i].keys()))[1]:max(zip(result2[i].values(), result2[i].keys()))[0]}

xxx=[]
for i in result3:
for j in result3[i]:
xxx.append(result3[i][j])
b=sorted(xxx,reverse = True)[:1] #取相关性最大的

result4={}
for i in result3:
for j in result3[i]:
for x in b:
if x==result3[i][j]:
result4[i]={j:x}
print(result4)
return result4
#3 获取21年数据
def test_data():
result4=xgx()
ts_code=[]
for i in result4:
for j in result4[i]:
ts_code.append(j)
df = pd.DataFrame()
for i in ts_code:
df1 = pro.daily(ts_code=i, start_date='20210101', end_date='20210331')
df = pd.concat([df, df1], axis=0)
df.to_excel('股票数据1.xlsx', index=False)
test_data()

#4 买股方案
def mgfa():
timetime=list(set(timeseries))
timetime1=sorted(timetime)
result4=xgx()
ts1=[] #昨天
ts2=[] #今天
for i in result4:
ts2.append(i)
for j in result4[i]:
ts1.append(j)

result1={}
for i in range(len(df)):
time=df.iloc[i,1]
if result1.get(time,False):
aa.append(df.iloc[i,-3])
else:
aa=[]
aa.append(df.iloc[i,-3])
result1[time]=aa

result2={}
for i in result1:
if i!=20210331:
aaa=[]
for j in result1[i]:
if j >0:
aaa.append(ts2[result1[i].index(j)])
result2[timetime1[timetime1.index(i)+1]]=aaa
print(result2)
return result2
mgfa()
#5 获取测试数据
def cssj():
result4=xgx()
ts_code=[]
for i in result4:
ts_code.append(i)
df = pd.DataFrame()
for i in ts_code:
df1 = pro.daily(ts_code=i, start_date='20210101', end_date='20210331')
df = pd.concat([df, df1], axis=0)
df.to_excel('股票数据2.xlsx', index=False)
cssj()

#6 评估策略
def jssy():
result2=mgfa()
result4=xgx()
zdf=[]
for i in result2:
if len(result2[i]) == 1:
for j in result2[i]:
for x in range(len(df)):
if df.iloc[x, 0] == j and df.iloc[x, 1] == i:
zdf.append(df.iloc[x, -3])
else:
zdf.append(0)
bbb=1
for i in zdf:
bbb=bbb*(1+i/100)
bb=(bbb-1)*100
print('总收益率/%:',bb)
print('夏普率：', np.mean(zdf)/np.std(zdf,ddof=1))
ccc=1
hc=1
max_hc=[]
for i in zdf:
kk=ccc*(1+i/100)
if kk<ccc:
hc=hc*(1+i/100)
else:
hc=(hc-1)*100
max_hc.append(hc)
hc=1
ccc=copy.deepcopy(kk)
print('最大回撤/%:',abs(min(max_hc)))
jssy()

``````

THE END

)">