-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbacktester_version_2
162 lines (127 loc) · 6.41 KB
/
backtester_version_2
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
"""
Created on Wed Oct 30 11:09:53 2019
@author: Alan
"""
import pandas as pd
import numpy as np
import talib
import matplotlib.pyplot as plt
import jqdatasdk as jq
import statsmodels.api as sm
def double_ma(data,stock_list,fast_window,slow_window):
'''signal = [long=+1/short=-1,amount] '''
close=data['close']
signal = close.copy()
for stock in stock_list:
fm = talib.SMA(close[stock],fast_window)
sm = talib.SMA(close[stock],slow_window)
nan = np.isnan(sm)
for i in range(0,np.size(fm)):
if(nan[i]==True):
signal[stock][i]=0
else:
if(fm[i]>sm[i]):
signal[stock][i]=1
else:
signal[stock][i]=-1
return signal
def pick_stock():
'''Your pick stock strategy'''
return ['000300.XSHG', '000001.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
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):
'''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)
rf = np.ones(np.size(r_m))*0.03/360 #risk_Free rate
return_period = sum(r_strategy) #total return rate
x,y = r_m-rf,r_strategy-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()
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 = (return_period-rf.mean())/vol
sotino_ratio = (return_period-rf.mean())/beta
IR = (res.resid).mean()/(res.resid.std())
performance_strategy = {'阶段收益率:':return_period,'詹森系数(alpha):':alpha,'beta:':beta,'波动率:':vol,'亏损比例:':loss_rate,'平均亏损:':loss_ave,
'Sharpe比率:':sharpe_ratio,'Sotino比率:':sotino_ratio,'信息比:':IR}
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)
rf = np.ones(np.size(r_strategy))*0.03/360
vol = np.std(r_strategy)
sr = (return_period-rf.mean())/vol
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 = '2017-01-01', '2017-12-31' #set start time and end time
Backtester = BacktestEngine(start_date,end_date)
parameters=[12,21]
Backtester.load_strategy(double_ma,parameters); #load strategy to create trade signal
Backtester.run(); #using signal to create trade log
Backtester.prints(); #calculate statistics and print it
Backtester.show(); #draw our pnl curve