-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbacktester_version_3
226 lines (176 loc) · 9.39 KB
/
backtester_version_3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 30 11:09:53 2019
@author: Alan
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import jqdatasdk as jq
import statsmodels.api as sm
import datetime
from strategy import double_ma
from jqdatasdk import *
def pick_stock():
'''Your pick stock strategy'''
return ['000352.XSHE']
class BacktestEngine(object):
"""
This class is used to read data,
process data to standard form.
"""
def __init__(self,start_date,end_date):
self.start_date = start_date
self.end_date = end_date
self.stock_list = pick_stock()
self.data = self.load_data()
self.close = self.data['close']
self.open = self.data['open']
self.len = np.size(self.close[self.stock_list[0]]) #len is the total trade day
'''it is cash (column=0) and balance (column = 1)'''
self.trade_log = np.empty([self.len,2])
self.trade_log[0] = [10000,10000]
'''it is record the share that we hold'''
self.share_log = pd.DataFrame(np.empty([self.len,len(self.stock_list)]),columns=self.stock_list)
for stock in self.stock_list:
self.share_log[stock][0]=0
#get risk_free rate
q = query(macro.MAC_LEND_RATE).filter(macro.MAC_LEND_RATE.currency_id==1,macro.MAC_LEND_RATE.market_id==5,macro.MAC_LEND_RATE.term_id==20,macro.MAC_LEND_RATE.day>=self.start_date,macro.MAC_LEND_RATE.day<=self.end_date)
tmp = macro.run_query(q)
tmp = tmp.sort_values(by='day')
i, j = 0, 0
self.rf = np.zeros(self.len-1)
'''while i < self.len-1:
print(i)
for j in range(len(tmp['day'])):
day = pd.to_datetime(tmp['day'].iloc[j])
if(day>=self.close.index[i]):
self.rf[i] = tmp['interest_rate'].iloc[j]/360
break
if(self.rf[i]==0):
print('ir too small')
break
i+=1'''
while i<self.len-1 and j<len(tmp['day']):
day = pd.to_datetime(tmp['day'].iloc[j])
if(day==self.close.index[i]):
self.rf[i] = tmp['interest_rate'].iloc[j]/360/100
i+=1
j+=1
last = tmp['interest_rate'].iloc[j]/360
elif(day<self.close.index[i]):
self.rf[i] = tmp['interest_rate'].iloc[j]/360/100
j+=1
elif(day>self.close.index[i]):
self.rf[i] = tmp['interest_rate'].iloc[j]/360/100
i+=1
if(i!=self.len):
while i < self.len-1:
self.rf[i] = last
i+=1
def load_data(self):
jq.auth("15825675534",'Programming123')
return jq.get_price(security=self.stock_list,start_date=self.start_date,end_date=self.end_date)
def load_strategy(self, strategy_name,parameters):
self.strategy_name = strategy_name
self.signal = strategy_name(self.data,self.stock_list,parameters[0],parameters[1])
def run(self,fee):
for i in range(0,self.len-1):
ts = 0 #record total cost in stock
if(self.trade_log[i][1]<0): #if the balance is less than 0, we bankrupt
self.trade_log[i+1]=self.trade_log[i]
self.share_log.iloc[i+1]=self.share_log.iloc[i]
continue;
self.trade_log[i+1]=self.trade_log[i] #first copy day i's situation
self.signal.iloc[0]=0
money_to_trade = (self.signal.iloc[i+1]-self.signal.iloc[i])*self.open.iloc[i+1]
money_to_trade[np.isnan(money_to_trade)]=0
transaction_fee = sum(abs(money_to_trade))*fee
total=sum(money_to_trade)
self.trade_log[i+1][0]=self.trade_log[i+1][0]-total-transaction_fee
'''for stock in self.stock_list:
self.share_log[stock][i+1]=self.signal[stock][i] #according to day i's signal, we will hold same share in day i+1
if(np.isnan(self.open[stock][i+1])):
continue
self.trade_log[i+1][0]=self.trade_log[i+1][0]-self.open[stock][i+1]*(self.share_log[stock][i+1]-self.share_log[stock][i]) #cash = cash - cost in stock
sum=sum+self.share_log[stock][i+1]*self.close[stock][i+1] #record the value of stock that we hold
'''
a=self.signal.iloc[i+1]
b=self.close.iloc[i+1]
c=a*b
c[np.isnan(c)]=0
ts = sum(c)
self.trade_log[i+1][1]=self.trade_log[i+1][0] + ts #balance = cash + value of stocks
'''if we have a signal in day i, then we will execute it at day i+1 '''
'''for i in range(0,self.len-1):
sum = 0 #record total cost in stock
if(self.trade_log[i][1]<0): #if the balance is less than 0, we bankrupt
self.trade_log[i+1]=self.trade_log[i]
self.share_log[i+1]=self.share_log[i]
continue;
self.trade_log[i+1]=self.trade_log[i] #first copy day i's situation
for stock in self.stock_list:
self.share_log[stock][i+1]=self.signal[stock][i] #according to day i's signal, we will hold same share in day i+1
self.trade_log[i+1][0]=self.trade_log[i+1][0]-self.open[stock][i+1]*(self.share_log[stock][i+1]-self.share_log[stock][i]) #cash = cash - cost in stock
sum=sum+self.share_log[stock][i+1]*self.close[stock][i+1] #record the value of stock that we hold
self.trade_log[i+1][1]=self.trade_log[i+1][0]+sum #balance = cash + value of stocks
'''
def prints(self):
r_strategy = np.log(np.array(self.trade_log[1:self.len,1])/np.array(self.trade_log[0:self.len-1,1])) #strategy return rate
hs300 = jq.get_price('000300.XSHG',start_date=self.start_date, end_date=self.end_date,fields = ('close','pre_close'))
r_m = np.log(np.array(hs300.close)/np.array(hs300.pre_close)) #market return rate
r_m = np.delete(r_m,0)
return_period = sum(r_strategy) #total return rate
x,y = r_m-self.rf,r_strategy-self.rf #excess return rate
x = x.reshape(len(x),1)
c = np.ones((len(x),1))
X = np.hstack((c,x))
'''CAPM model'''
res = (sm.OLS(y,X)).fit()
self.see = res
alpha, beta = res.params[0], res.params[1]
vol = np.std(r_strategy)
loss_rate = len(r_strategy[r_strategy<0])/len(r_strategy)
loss_ave = r_strategy[r_strategy<0].mean()
sharpe_ratio = (r_strategy.mean()-self.rf.mean())/vol*(360**0.5) #360 suitable?
#sotino_ratio = (return_period-self.rf.mean())/beta
#IR = (res.resid).mean()/(res.resid.std())*(360**0.5)
'''performance_strategy = {'阶段收益率:':return_period,'詹森系数(alpha):':alpha,'beta:':beta,'波动率:':vol,'亏损比例:':loss_rate,'平均亏损:':loss_ave,
'Sharpe比率:':sharpe_ratio,'Sotino比率:':sotino_ratio,'信息比:':IR}'''
performance_strategy = {'阶段收益率:':return_period,'詹森系数(alpha):':alpha,'beta:':beta,'波动率:':vol,'亏损比例:':loss_rate,'平均亏损:':loss_ave,
'Sharpe比率:':sharpe_ratio}
print(performance_strategy)
def c_sharpe(self):
r_strategy = np.log(np.array(self.trade_log[1:self.len,1])/np.array(self.trade_log[0:self.len-1,1]))
return_period = sum(r_strategy)
vol = np.std(r_strategy)
sr = (r_strategy.mean()-self.rf.mean())/vol*(360**0.5)
return sr
def show(self):
x = self.close.index
y = self.trade_log[:,1]
plt.plot(x,y)
plt.show()
'''parameter optimazation'''
def optimaze(self, p1_min, p1_max, p1_step, p2_min, p2_max, p2_step):
max_sr = 0
res = [p1_min,p2_min]
for i in range(p1_min,p1_max+1,p1_step):
for j in range(p2_min,p2_max+1,p2_step):
parameters = [i,j]
self.load_strategy(self.strategy_name,parameters)
self.run()
sr = self.c_sharpe()
if sr > max_sr:
res[0], res[1] = i, j
max_sr = sr
print("Optimazation Parameters are:",res)
if __name__ == '__main__':
start_date, end_date = '2007-01-01', '2018-12-31' #set start time and end time
Backtester = BacktestEngine(start_date,end_date)
parameters=[10,20]
Backtester.load_strategy(double_ma,parameters); #load strategy to create trade signal
fee = 0.0001
Backtester.run(fee); #using signal to create trade log
Backtester.prints(); #calculate statistics and print it
Backtester.show(); #draw our pnl curve