-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathkeyIndicatorAnalyzer.py
More file actions
254 lines (218 loc) · 7.1 KB
/
Copy pathkeyIndicatorAnalyzer.py
File metadata and controls
254 lines (218 loc) · 7.1 KB
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
import backtrader as bt
import numpy as np
import pandas as pd
pd.set_option("display.max_columns", None)
class KeyIndicatorAnalyzer(bt.Analyzer):
""" """
def __init__(self):
super(KeyIndicatorAnalyzer, self).__init__()
# period
self.year_period = 252
# period
self.month_period = 21
# period
self.week_period = 5
#
self.daily_details = []
#
self.commission = 0
#
self.win_list = []
#
self.loss_list = []
#
self.key_indicators_df = pd.DataFrame(
columns=["", "", "", "", "", "", "", "7", "30", "", ""]
)
# ,,{:DataFrame, :DataFrame},,
self.daily_chart_dict = dict()
def get_analysis_data(self, benchmark_df, benchmark_name):
"""
,,。
@param benchmark_df:
@param benchmark_name:
"""
self._calculate_benchmark_indicators(benchmark_df, benchmark_name)
return self.key_indicators_df, self.daily_chart_dict
def _calculate_benchmark_indicators(self, benchmark_df, benchmark_name):
""" """
series = benchmark_df["close"]
total_return = self.total_return(series)
annual_return = self.annual_return(series)
period = self.week_period
recent_7_days_return = self.recent_period_return(series, period)
period = self.month_period
recent_30_days_return = self.recent_period_return(series, period)
max_drawdown = self.max_drawdown(series)
sharp_ratio = self.sharp_ratio(series)
self.key_indicators_df.loc[len(self.key_indicators_df)] = [
benchmark_name,
total_return,
annual_return,
max_drawdown,
None,
sharp_ratio,
None,
recent_7_days_return,
recent_30_days_return,
None,
None,
]
#
df = pd.DataFrame(index=benchmark_df.index)
s = self.yield_curve(series)
#
df.insert(0, "", s)
df.index.name = ""
self.daily_chart_dict[benchmark_name] = df
def next(self):
super(KeyIndicatorAnalyzer, self).next()
#
current_date = self.strategy.data.datetime.date(0)
#
total_value = self.strategy.broker.getvalue()
#
cash = self.strategy.broker.getcash()
self.daily_details.append({"": current_date, "": total_value, "": cash})
def notify_trade(self, trade):
#
if trade.isclosed:
#
self.commission += trade.commission
#
if trade.pnlcomm >= 0:
# , 0
self.win_list.append(trade.pnlcomm)
else:
#
self.loss_list.append(trade.pnlcomm)
def stop(self):
#
if self._win_times() + self._loss_times() == 0:
win_rate = 0
else:
win_percent = self._win_times() / (self._win_times() + self._loss_times())
win_rate = f"{round(win_percent * 100, 2)}%"
df = pd.DataFrame(self.daily_details)
#
total_return = self.total_return(df[""])
#
annual_return = self.annual_return(df[""])
# 7
period = self.week_period
recent_7_days_return = self.recent_period_return(df[""], period)
# 30
period = self.month_period
recent_30_days_return = self.recent_period_return(df[""], period)
#
max_drawdown = self.max_drawdown(df[""])
#
sharp_ratio = self.sharp_ratio(df[""])
#
kelly_percent = self.kelly_percent()
#
commission_percent = self.commission_percent(df[""])
#
trade_times = self._win_times() + self._loss_times()
#
self.key_indicators_df.loc[len(self.key_indicators_df)] = [
"",
total_return,
annual_return,
max_drawdown,
win_rate,
sharp_ratio,
kelly_percent,
recent_7_days_return,
recent_30_days_return,
commission_percent,
trade_times,
]
#
df[""] = self.yield_curve(df[""])
df.set_index("", inplace=True)
#
self.daily_chart_dict[""] = df
def commission_percent(self, series) -> str:
""" """
percent = self.commission / series.iloc[0]
return f"{round(percent * 100, 2)}%"
def yield_curve(self, series) -> pd.Series:
""" """
percent = (series - series.iloc[0]) / series.iloc[0]
return round(percent * 100, 2)
def total_return(self, series) -> str:
""" """
percent = (series.iloc[-1] - series.iloc[0]) / series.iloc[0]
return f"{round(percent * 100, 2)}%"
def annual_return(self, series) -> str:
""" """
percent = (
(series.iloc[-1] - series.iloc[0])
/ series.iloc[0]
/ len(series)
* self.year_period
)
return f"{round(percent * 100, 2)}%"
def recent_period_return(self, series, period) -> str:
""" """
percent = (series.iloc[-1] - series.iloc[-period]) / series.iloc[-period]
return f"{round(percent * 100, 2)}%"
def max_drawdown(self, series) -> str:
""" """
s = (series - series.expanding().max()) / series.expanding().max()
percent = s.min()
return f"{round(percent * 100, 2)}%"
def sharp_ratio(self, series) -> float:
"""
:,()
,,。
,,。
,,。
,,。
,,1.0。
:(Rp-Rf)/σp
,Rp,Rf,σp。
3%
:sharpe = ( - ) /
"""
ret_s = series.pct_change().fillna(0)
avg_ret_s = ret_s.mean()
avg_risk_free = 0.03 / self.year_period
sd_ret_s = ret_s.std()
sharp = (avg_ret_s - avg_risk_free) / sd_ret_s
sharp_year = round(np.sqrt(self.year_period) * sharp, 3)
return sharp_year
def kelly_percent(self) -> str:
"""
:,,
,。
:K = W - [(1 - W) / R]
,K,W,R,。
:,,;,
kelly_percent = 0.2,20%。
,
"""
win_times = self._win_times()
loss_times = self._loss_times()
if win_times > 0 and loss_times > 0:
avg_win = np.average(self.win_list) #
avg_loss = abs(np.average(self.loss_list)) # ,
win_loss_ratio = avg_win / avg_loss #
if win_loss_ratio == 0:
kelly_percent = None
else:
sum_trades = win_times + loss_times
win_percent = win_times / sum_trades #
#
#
kelly_percent = win_percent - ((1 - win_percent) / win_loss_ratio)
else:
kelly_percent = None #
return f"{round(kelly_percent * 100, 2)}%" if kelly_percent else None
def _win_times(self):
""" """
return len(self.win_list)
def _loss_times(self):
""" """
return len(self.loss_list)