-
Notifications
You must be signed in to change notification settings - Fork 0
/
strategy_class.py
408 lines (342 loc) · 13.9 KB
/
strategy_class.py
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import concurrent.futures
import pandas as pd
import os
class EntrySetting():
def __init__(self, entry, exit):
self.entry = entry
self.exit = exit
class NseIndex():
def __init__(self, name):
self.name = name
class MoveCostSL():
def __init__(self, flag):
self.active = flag
class AddSimpleMomentum:
def __init__(self, name, val):
if name.upper() == 'STRIKE_POINTS_UP':
pass
elif name.upper() == 'STRIKE_POINTS_DOWN':
pass
elif name.upper() == 'STRIKE_PCT_UP':
pass
elif name.upper() == 'STRIKE_PCT_DOWN':
pass
elif name.upper() == 'UINDEX_POINTS_UP':
pass
elif name.upper() == 'UINDEX_POINTS_DOWN':
pass
elif name.upper() == 'UINDEX_PCT_UP':
pass
elif name.upper() == 'UINDEX_PCT_DOWN':
pass
class AddTarget:
def __init__(self, name, val):
if name.upper() == 'STRIKE_POINTS':
pass
elif name.upper() == 'STRIKE_PCT':
pass
elif name.upper() == 'UINDEX_POINTS':
pass
elif name.upper() == 'UINDEX_PCT':
pass
class AddStoploss:
def __init__(self, name, val):
if name.upper() == 'STRIKE_POINTS':
pass
elif name.upper() == 'STRIKE_PCT':
pass
elif name.upper() == 'UINDEX_POINTS':
pass
elif name.upper() == 'UINDEX_PCT':
pass
class AddTrailingStoploss:
def __init__(self, val1, val2):
pass
class AddLeg:
def __init__(self, lots = 1, position = 'sell', option_type = 'call', expiry = 'weekly',strike_criteria = 'strike_type', strike_type = 'ATM',
premium = 100, simple_momentum = [False, 0 , 0], target = [False, 0 , 0], stoploss = [False, 0, 0], trailing_stoploss = [False, 0, 0],
reentry_on_sl = False, reentry_on_target = False, entry_active = False, entry_time = None, entry_at = None,
exit_active = False, exit_time = None, exit_at = None):
self.lots = lots
self.position = position
self.option_type = option_type
self.expiry = expiry
self.strike_criteria = strike_criteria
self.strike_type = strike_type
self.premium = premium
self.simple_momentum_active = simple_momentum[0]
self.simple_momentum_name = simple_momentum[1]
self.simple_momentum_val = simple_momentum[2]
self.target_active = target[0]
self.target_name = target[1]
self.target_val = target[2]
self.stoploss_active = stoploss[0]
self.stoploss_name = stoploss[1]
self.stoploss_val = stoploss[2]
self.trailing_stoploss_active = trailing_stoploss[0]
self.trailing_stoploss_val1 = trailing_stoploss[1]
self.trailing_stoploss_val2 =trailing_stoploss[2]
self.reentry_on_sl = reentry_on_sl
self.reentry_on_target = reentry_on_target
self.entry_active = entry_active
self.entry_time = entry_time
self.entry_at = entry_at
self.exit_active = exit_active
self.exit_time = exit_time
self.exit_at = exit_at
self.factor = 1 if position == 'buy' else -1
class Strategy:
all_leg = {}
myid = 0
def __init__(self):
self.add_leg(option_type = 'call', position = 'buy', strike_criteria = 'closest_premium', premium = 100,
simple_momentum = [True, 'STRIKE_PCT_UP', 0.15], target = [False, 'POINTS', 50], stoploss = [True, 'PERCENTAGE', 0.25])
self.add_leg(option_type = 'put', position = 'buy', strike_criteria = 'closest_premium', premium = 100,
simple_momentum = [True, 'STRIKE_PCT_UP', 0.15], target = [False, 'POINTS', 50], stoploss = [True, 'PERCENTAGE', 0.25])
def add_leg(self,lots = 1, position = 'sell', option_type = 'call', expiry = 'weekly',strike_criteria = 'strike_type', strike_type = 'ATM',
premium = 100, simple_momentum = [False, 0 , 0], target = [False, 0 , 0], stoploss = [False, 0, 0], trailing_stoploss = [False, 0, 0],
reentry_on_sl = False, reentry_on_target = False):
Strategy.myid += 1
self.all_leg[Strategy.myid] = {}
self.all_leg[Strategy.myid] = AddLeg(option_type = option_type, position = position, strike_criteria = strike_criteria, premium = premium,
simple_momentum = simple_momentum, target = target, stoploss = stoploss)
def get_legs(self):
return Strategy.all_leg
class Execute:
def __init__(self, df):
# print("-------->",Strategy().all_leg[1].__dict__)
self.total_pnl = 0
# self.df_date = #'abc'
self.entry_setting = EntrySetting(entry = '09:35:00', exit = '15:15:00')
self.nse_index = NseIndex('Nifty Bank')
self.move_to_sl = MoveCostSL(1)
self.df = df['data'] #pd.read_csv(fr'C:\Users\zp2117\Work non ondrive\shoonya-v2\back_tester\BNF_201904_202204\BANKNIFTY-2022-06-{n}.csv')
self.df_date = ''#df['filename'] df['data']
# print(self.df)
self.spot, self.spot_atm = self.get_spot_and_atm(self.df)
self.legs = Strategy().get_legs()
self.get_legs()
self.get_ce_pe()
self.loop_over_time()
self.get_pnl()
self.return_pnl()
# print(self.df_date)
def get_legs(self):
m = Strategy().all_leg.copy()
self.legs = m
def return_pnl(self):
return self.df_date, self.total_pnl
def get_pnl(self):
pnl = 0
for k in self.legs:
myleg = self.legs[k]
if myleg.entry_active and myleg.exit_active:
pnl += (myleg.exit_price - myleg.entry_price) * myleg.factor
# self.
total_pnl = pnl * 25
self.total_pnl = total_pnl
# print(pnl)
# return self.df_date, total_pnl
# print(f"{self.df_date} : {total_pnl:.0f}")
def loop_over_time(self):
df2 = self.df.copy()
df2 = df2[(df2['time'] >= self.entry_setting.entry) & (df2['time'] <= self.entry_setting.exit)].copy()
for tmt in df2['time'].tolist():
self.enter(tmt)
self.stoploss(tmt)
self.end_of_day(tmt)
def end_of_day(self, mytmt):
if mytmt != self.entry_setting.exit:
return
# for k in self.legs:
for k, value in list(self.legs.items()):
myleg = self.legs[k]
if not myleg.exit_active and myleg.entry_active:
ltp = self.get_option_ltp(myleg.instrument, 'open', self.entry_setting.exit)
myleg.exit_price = ltp
myleg.exit_at = 'open'
myleg.exit_time = mytmt
myleg.exit_active = True
print('exit time')
def stoploss(self, mytmt):
# print('Hi', mytmt)
for k, value in list(self.legs.items()):
myleg = self.legs[k]
if myleg.exit_active:
return
# elif not myleg.entry_active:
# return
# print(mytmt,myleg.instrument, myleg.entry_active)
if myleg.entry_active:
ltp = self.get_option_ltp(myleg.instrument, 'open', mytmt)
# print(ltp, myleg.stoploss_price)
if myleg.stoploss_name.upper() == 'PERCENTAGE':
if ltp <= myleg.stoploss_price:
myleg.exit_price = ltp
myleg.exit_at = 'open'
myleg.exit_time = mytmt
myleg.exit_active = True
print('SL hit')
elif self.get_option_ltp(myleg.instrument, 'low', mytmt) <= myleg.stoploss_price:
print('SL hit at low')
myleg.exit_price = self.get_option_ltp(myleg.instrument, 'low', mytmt)
myleg.exit_at = 'low'
myleg.exit_time = mytmt
myleg.exit_active = True
def get_atm(self, price, ch = 100):
return round(price / ch) * ch
def get_spot_and_atm(self, df):
spot = df[df['time'] == self.entry_setting.entry].iloc[0]['open']
spot_atm = self.get_atm(spot)
return spot, spot_atm
def get_option_ltp(self, instrument, ohlc = 'open', tmt = None):
df = self.df
prc = df[df['time'] == tmt].iloc[0][f"{instrument}_{ohlc}"]
return prc
def get_ce_pe(self):
strikes = []
for k, value in list(self.legs.items()):
myleg = self.legs[k]
if myleg.strike_criteria == 'closest_premium':
myleg.instrument = self.find_closest_premium_strike(myleg.premium, myleg.option_type)
elif myleg.strike_criteria == 'strike_type':
if 'ATM' in myleg.strike_type:
myleg.instrument = str(self.spot_atm) + 'C' if myleg.option_type == 'call' else None
myleg.instrument = str(self.spot_atm) + 'P' if myleg.option_type == 'put' else None
elif 'ITM' in myleg.strike_type:
no = myleg.strike_type[-1]
myleg.instrument = str(self.spot_atm - no * 100) + 'C' if myleg.option_type == 'call' else None
myleg.instrument = str(self.spot_atm + no * 100) + 'P' if myleg.option_type == 'put' else None
elif 'OTM' in myleg.strike_type:
no = myleg.strike_type[-1]
myleg.instrument = str(self.spot_atm + no * 100) + 'C' if myleg.option_type == 'call' else None
myleg.instrument = str(self.spot_atm - no * 100) + 'P' if myleg.option_type == 'put' else None
myleg.price = self.get_option_ltp(myleg.instrument, 'open', self.entry_setting.entry)
def get_options_df():
dfg = self.df
cols = []
for ohlc in ['open', 'high', 'low', 'close']:
cols.append(col + '_' + ohlc)
cols.append('time');
cols.append('timestamp')
df = dfg[cols]
df.columns = ['open', 'high', 'low', 'close', 'time', 'timestamp']
df = df[(df['time'] >= entry_time) & (df['time'] <= exit_time)]
entry_open = df[df['time'] >= entry_time].iloc[0]['open']
try:
c = int(entry_open)
except Exception as e:
raise e
return df, entry_open
def find_closest_premium_strike(self, closestPremiumValue, C_P2):
C_P = 'C' if C_P2 == 'call' else 'P'
df2 = self.df.copy()
df2 = df2.loc[df2['time'] == self.entry_setting.entry]
df2 = df2.filter(regex=C_P + '_open')
df2 = dict(df2.T.iloc[:, -1] )
# print(df2)
df2 = pd.DataFrame(df2.items(), columns=['strike', 'ltp'])
df2['strike'] = df2['strike'].apply(lambda x: x[0:6])
df2['absolute'] = abs(df2['ltp'] - closestPremiumValue)
df2 = df2.sort_values(by=['absolute'], ascending=True)
return df2['strike'].tolist()[0]
def enter(self, mytmt):
for k, value in list(self.legs.items()):
myleg = self.legs[k]
# print(vars(myleg))
# print(vars(myleg))
ltp_open = self.get_option_ltp(myleg.instrument, 'open', mytmt)
ltp_high = self.get_option_ltp(myleg.instrument, 'high', mytmt)
ltp_low = self.get_option_ltp(myleg.instrument, 'low', mytmt)
if myleg.entry_active: return
if myleg.simple_momentum_active and not myleg.entry_active:
if myleg.simple_momentum_name == 'STRIKE_PCT_UP':
if ltp_open >= myleg.price * (1 + myleg.simple_momentum_val):
myleg.entry_price = ltp_open
myleg.entry_active = True
myleg.entry_time = mytmt
myleg.entry_at = 'open'
print(f"{self.df_date} Momentum achieved at Open")
elif self.get_option_ltp(myleg.instrument, 'high', mytmt) >= myleg.price * (1 + myleg.simple_momentum_val):
myleg.entry_price = ltp_high
myleg.entry_active = True
print(f"{self.df_date} Momentum achieved at High")
myleg.entry_time = mytmt
myleg.entry_at = 'high'
elif myleg.simple_momentum_name == 'STRIKE_PCT_DOWN':
if ltp <= myleg.price * (1 - myleg.simple_momentum_val):
myleg.entry_price = ltp_open
myleg.entry_active = True
print(f"{self.df_date} Momentum achieved at Open")
myleg.entry_time = mytmt
myleg.entry_at = 'open'
elif self.get_option_ltp(myleg.instrument, 'low', mytmt) >= myleg.price * (1 - myleg.simple_momentum_val):
myleg.entry_price = ltp_low
myleg.entry_active = True
print(f"{self.df_date} Momentum achieved at Low")
myleg.entry_time = mytmt
myleg.entry_at = 'low'
if myleg.stoploss_active and myleg.entry_active:
# print('Placing SL')
myleg.stoploss_price = myleg.entry_price * (1 - myleg.stoploss_val * myleg.factor)
# a = Execute()
# # print(vars(a))
# print(a.legs[1].__dict__)
# print(a.legs[2].__dict__)
# # for i in a.legs.keys():
# # print(vars(a.legs[i]))
# a = Execute(17)
# # print(vars(a))
# print(a.legs[1].__dict__)
# print(a.legs[2].__dict__)
all_files_path = r'C:\Users\zp2117\Work non ondrive\shoonya-v2\back_tester\BNF_201904_202204'
file_list = os.listdir(all_files_path)
banknifty_data = []
for filename in file_list[:5]:
filepath = all_files_path + '//' + filename
try:
df = pd.read_csv(filepath, parse_dates = ['date','ds','timestamp','expiry'])
df.sort_values('timestamp', inplace=True)
banknifty_data.append({'filename':filename,'data': df})
except:
print(f"issue with {filename}")
a = Execute(banknifty_data[0])
print(a.legs[1].__dict__)
print(a.legs[2].__dict__)
b = Execute(banknifty_data[1])
print(b.legs[1].__dict__)
print(b.legs[2].__dict__)
# abc = {}
# def check2(y2, mydf):
# abc[str(y2)] = Execute(mydf)
# b, c = abc[str(y2)].return_pnl()
# print(b,c)
# # print(a.legs[1].__dict__)
# # print(a.legs[2].__dict__)
# # del a
# # print(vars(a))
# # for x in banknifty_data:
# # check2(x)
# for x,y in enumerate(banknifty_data):
# # print(x)
# check2(x,y)
# print(abc)
# a = Execute()
# with concurrent.futures.ThreadPoolExecutor() as executor:
# results = executor.map(check2, banknifty_data)
# for f in results:
# print(f)
# results = executor.map(check2, banknifty_data)
# # x2 =
# results = executor.map(check2, [x for x in banknifty_data])
# # results2 = [res.df_dt for res in results]
# # print([x for x in results])
# # print("result_list: ", results)
# for result in results:
# print("Result ==========================>", str(result))
# # results2 = [(res.df_dt, res.total_pnl) for res in results]
# for i in results:
# print(i)
# print(results.__dict__)
# merged_list = [v for f in futures for v in f.result()]
# print(banknifty_data[0])