-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trading_test.py
351 lines (286 loc) · 13.9 KB
/
Trading_test.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
import pandas as pd
import numpy as np
from datetime import timezone
from datetime import datetime
import time
from time import strptime
strptime('Feb','%b').tm_mon
def convertMonth(value):
month = strptime(value,'%b').tm_mon
return str(month)
def convertYear(year):
year = str(20) + year
return str(year)
def utcConvert(value):
exp = data["Expiry Date"].str.split("-", expand = True)
exp1 = exp.iloc[i]
expiry = datetime(int(exp1.iloc[2]), int(exp1.iloc[1]), int(exp1.iloc[0]))
timestamp = int(expiry.replace(tzinfo=timezone.utc).timestamp())
timestamp = str(timestamp)
return timestamp
def naked():
if(data.iloc[i,10] == "CALL"):
if(data.iloc[i,13] != '-'):
data.iloc[i,17] = float(data.iloc[i,13]) + float(data.iloc[i,11])
elif(data.iloc[i,14] != '-'):
data.iloc[i,17] = float(data.iloc[i,14]) + float(data.iloc[i,11])
elif(data.iloc[i,10] == "PUT"):
if(data.iloc[i,15] != '-'):
data.iloc[i,18] = float(data.iloc[i,15]) - float(data.iloc[i,11])
if(data.iloc[i,16] != '-'):
data.iloc[i,18] = float(data.iloc[i,16]) - float(data.iloc[i,11])
def vertical():
if(data.iloc[i,10] == "CALL"):
data.iloc[i,17] = float(data.iloc[i,13]) + float(data.iloc[i,11])
elif(data.iloc[i,10] == "PUT"):
data.iloc[i,18] = float(data.iloc[i,15]) - float(data.iloc[i,11])
def ironcondor():
data.iloc[i,17] = float(data.iloc[i,14]) + float(data.iloc[i,11])
data.iloc[i,18] = float(data.iloc[i,15]) - float(data.iloc[i,11])
# Using for loop
start = time.time()
#load data and remove un-neccesary fields and make data column string due to date format incosistency in csv file
data = pd.read_csv("2021-01-05-AccountStatement.csv",dtype={'DATE': str})
# data = pd.read_csv("2020-09-27-AccountStatement.csv",dtype={'DATE': str})
# rename columns
data = data.rename(columns=data.iloc[2])
data = data.iloc[5:, 0:9]
#filter data based on BOT/SOLD, PUT/CALL
data = data[data["DESCRIPTION"].str.contains("BOT|SOLD", na = False)]
data = data[data["DESCRIPTION"].str.contains("PUT|CALL", na = False)]
#Remove unnecassary columns
data = data.drop(columns=["REF #","TYPE","Misc Fees","Commissions & Fees","AMOUNT","BALANCE"])
#split data according to fields required and length of descrition column
try:
data[["BOT/SOLD","Quantity","Strategy","Strategy1","Ticker","Total Stocks","Weekly/Monthly","Expiry Date","Month","Year","AM/PM","Strike Price","Call/Put","Premium","Trade"]] = data["DESCRIPTION"].str.split(" ", expand = True)
data = data.drop("DESCRIPTION", axis=1)
except ValueError:
data[["BOT/SOLD","Quantity","Strategy","Strategy1","Ticker","Total Stocks","Weekly/Monthly","Expiry Date","Month","Year","Strike Price","Call/Put","Premium","Trade"]] = data["DESCRIPTION"].str.split(" ", expand = True)
data = data.drop("DESCRIPTION", axis=1)
data["AM/PM"] = None
data.columns = ["DATE","TIME","BOT/SOLD","Quantity","Strategy","Strategy1","Ticker","Total Stocks","Weekly/Monthly","Expiry Date","Month","Year","AM/PM","Strike Price","Call/Put","Premium","Trade"]
#remove unncessary values
data["BOT/SOLD"] = data["BOT/SOLD"].replace('WEB:API_TDAM:iPhone', np.nan)
data["BOT/SOLD"] = data["BOT/SOLD"].replace('tIP', np.nan)
#shift data to left 1 column to fill nan with BOT/SOLD data
mask = data["BOT/SOLD"].isna()
data.loc[mask, "BOT/SOLD":] = data.loc[mask, "BOT/SOLD":].shift(-1, axis=1)
#loop through strategy and strategy1 column to combine related values
for i in range(len(data)):
if (data.iloc[i,5] == "CONDOR" or data.iloc[i,5] == "ROLL"):
data.iloc[i,4] = data.iloc[i,4] + '-' + data.iloc[i,5]
#remove unnecessary values
data["Strategy1"] = data["Strategy1"].replace('CONDOR', np.nan)
data["Strategy1"] = data["Strategy1"].replace('ROLL', np.nan)
##################
mask = data["Strategy1"].isna()
data.loc[mask, "Strategy1":] = data.loc[mask, "Strategy1":].shift(-1, axis=1)
data["Strategy1"] = data["Strategy1"].replace("100", np.nan)
mask = data["Strategy1"].isna()
data.loc[mask, "Strategy":] = data.loc[mask, "Strategy":].shift(1, axis=1)
otherStrategy = data[data["Strategy"].str.contains("VERT-ROLL|DIAGONAL|CALENDAR|COMBO|COVERED|STRADDLE|STRANGLE", na = False)]
data = data[~data["Strategy"].str.contains("VERT-ROLL|DIAGONAL|CALENDAR|COMBO|COVERED|STRADDLE|STRANGLE", na = False)]
mask = data["Trade"].isna()
data.loc[mask, "Strategy1":] = data.loc[mask, "Strategy1":].shift(1, axis=1)
data["Strategy"] = data["Strategy"].fillna("NAKED")
data["Call/Put"] = data["Call/Put"].fillna("-")
truthTable = data["Call/Put"].str.contains('@')
for i in range(len(truthTable)):
if (truthTable.iloc[i] == True):
if (data.iloc[i,15] == np.nan):
data.iloc[i,15] = "-"
mask = data["Premium"].isna()
data.loc[mask, "Weekly/Monthly":] = data.loc[mask, "Weekly/Monthly":].shift(1, axis=1)
for i in range(len(data)):
if (data.iloc[i,9] == "(Weeklys)"):
data.iloc[i,8] = data.iloc[i,9]
data.iloc[i,9] = np.nan
mask = data["Expiry Date"].isna()
data.loc[mask, "Expiry Date":] = data.loc[mask, "Expiry Date":].shift(-1, axis=1)
truthTable = data["Premium"].str.contains('@')
for i in range(len(data)):
if (truthTable.iloc[i,] == False):
data.iloc[i,16] = data.iloc[i,15]
data.iloc[i,15] = np.nan
mask = data["Premium"].isna()
data.loc[mask, "AM/PM":"Premium"] = data.loc[mask, "AM/PM":"Premium"].shift(1, axis=1)
for i in range(len(data)):
if (data.iloc[i,11] == '[AM]'):
data.iloc[i,12] = data.iloc[i,11]
data.iloc[i,11] = np.nan
data["AM/PM"] = data["AM/PM"].fillna("[PM]")
mask = data["Year"].isna()
data.loc[mask, "Weekly/Monthly":"Year"] = data.loc[mask, "Weekly/Monthly":"Year"].shift(1, axis=1)
data["Weekly/Monthly"] = data["Weekly/Monthly"].fillna("Monthly")
data["Trade"] = data["Trade"].fillna("-")
for i in range(len(data)):
month = convertMonth(data.iloc[i,10])
year = convertYear(data.iloc[i,11])
date = data.iloc[i,9]
data.iloc[i,9] = date + '-' + month + '-' + year
data = data.drop(columns = ["Strategy1", "Total Stocks", "Month", "Year"])
data[["Junk","Premium"]] = data["Premium"].str.split("@", expand = True)
data = data.drop(columns = ["Junk"])
data["Call Buy"] = None
data["Call Sell"] = None
data["Put Sell"] = None
data["Put Buy"] = None
data["Temp"] = data["Strike Price"].str.contains("/", na = False)
for i in range(len(data)):
if (data.iloc[i,2] == 'BOT'):
if (data.iloc[i,10] == 'CALL'):
if(data.iloc[i,17] == False):
data.iloc[i,13] = data.iloc[i,9]
elif (data.iloc[i,10] == 'PUT'):
if(data.iloc[i,17] == False):
data.iloc[i,16] = data.iloc[i,9]
elif (data.iloc[i,2] == 'SOLD'):
if (data.iloc[i,10] == 'CALL'):
if(data.iloc[i,17] == False):
data.iloc[i,14] = data.iloc[i,9]
elif (data.iloc[i,10] == 'PUT'):
if(data.iloc[i,17] == False):
data.iloc[i,15] = data.iloc[i,9]
data["Temp1"] = None
data["Temp2"] = None
data["Temp3"] = None
data["Temp4"] = None
data[["Temp1","Temp2","Temp3","Temp4"]] = data["Strike Price"].str.split("/", expand = True)
for i in range(len(data)):
if (data.iloc[i,19] != None):
if (data.iloc[i,20] == None and data.iloc[i,21] == None):
if (data.iloc[i,2] == 'BOT'):
if (data.iloc[i,10] == 'CALL'):
data.iloc[i,13] = data.iloc[i,18]
data.iloc[i,14] = data.iloc[i,19]
elif (data.iloc[i,10] == 'PUT'):
data.iloc[i,16] = data.iloc[i,18]
data.iloc[i,15] = data.iloc[i,19]
else:
if (data.iloc[i,10] == 'CALL'):
data.iloc[i,14] = data.iloc[i,18]
data.iloc[i,13] = data.iloc[i,19]
elif (data.iloc[i,10] == 'PUT'):
data.iloc[i,15] = data.iloc[i,18]
data.iloc[i,16] = data.iloc[i,19]
for i in range(len(data)):
if (data.iloc[i,18] != None and data.iloc[i,19] != None and data.iloc[i,20] != None and data.iloc[i,21] != None):
if (data.iloc[i,2] == 'BOT'):
data.iloc[i,13] = data.iloc[i,18]
data.iloc[i,14] = data.iloc[i,19]
data.iloc[i,16] = data.iloc[i,20]
data.iloc[i,15] = data.iloc[i,21]
if (data.iloc[i,2] == 'SOLD'):
data.iloc[i,13] = data.iloc[i,19]
data.iloc[i,14] = data.iloc[i,18]
data.iloc[i,16] = data.iloc[i,21]
data.iloc[i,15] = data.iloc[i,20]
data = data.drop(columns = ["Temp","Temp1","Temp2","Temp3","Temp4"])
data["Call + Premium"] = np.nan
data["Put - Premium"] = np.nan
data['Call Buy'] = data['Call Buy'].fillna('-')
data['Call Sell'] = data['Call Sell'].fillna('-')
data['Put Buy'] = data['Put Buy'].fillna('-')
data['Put Sell'] = data['Put Sell'].fillna('-')
data['Strike Price'] = data['Strike Price'].fillna('-')
data = data.sort_values(by=['Strategy'])
# for naked
for i in range(len(data)):
if(data.iloc[i,13] != '-' and data.iloc[i,14] == '-' and data.iloc[i,15] == '-' and data.iloc[i,16] == '-'):
naked()
elif(data.iloc[i,13] == '-' and data.iloc[i,14] != '-' and data.iloc[i,15] == '-' and data.iloc[i,16] == '-'):
naked()
if(data.iloc[i,13] == '-' and data.iloc[i,14] == '-' and data.iloc[i,15] != '-' and data.iloc[i,16] == '-'):
naked()
elif(data.iloc[i,13] == '-' and data.iloc[i,14] == '-' and data.iloc[i,15] == '-' and data.iloc[i,16] != '-'):
naked()
# for vertical
for i in range(len(data)):
if(data.iloc[i,13] != '-' and data.iloc[i,14] != '-' and data.iloc[i,15] == '-' and data.iloc[i,16] == '-'):
vertical()
elif(data.iloc[i,13] == '-' and data.iloc[i,14] == '-' and data.iloc[i,15] != '-' and data.iloc[i,16]!= '-'):
vertical()
# for ironcondor
for i in range(len(data)):
if(data.iloc[i,13] != '-' and data.iloc[i,14] != '-' and data.iloc[i,15] != '-' and data.iloc[i,16] != '-'):
ironcondor()
elif(data.iloc[i,13] != '-' and data.iloc[i,14] != '-' and data.iloc[i,15] != '-' and data.iloc[i,16]!= '-'):
ironcondor()
data["Current Premium"] = None
for i in range(len(data)):
ticker = data.iloc[i,5]
try:
timestamp = utcConvert(i)
temp = pd.read_html("https://finance.yahoo.com/quote/"+ticker+"/options?date="+timestamp+"&p="+ticker+"&straddle=true")
temp = temp[0]
if(data.iloc[i,10] == "CALL"):
if(data.iloc[i,13] != '-' and data.iloc[i,14] == '-' and data.iloc[i,15] == '-' and data.iloc[i,16] == '-'):
call = data.iloc[i,13]
elif(data.iloc[i,13] == '-' and data.iloc[i,14] != '-' and data.iloc[i,15] == '-' and data.iloc[i,16] == '-'):
call = data.iloc[i,14]
if(data.iloc[i,13] != '-' and data.iloc[i,14] != '-' and data.iloc[i,15] == '-' and data.iloc[i,16] == '-'):
if(data.iloc[i,2]=='BOT'):
call = data.iloc[i,13]
else:
call = data.iloc[i,14]
for x in range(len(temp)):
if (float(temp.iloc[x,5]) == float(call)):
data.iloc[i,19] = temp.iloc[x,0]
elif(data.iloc[i,10] == "PUT"):
if(data.iloc[i,13] == '-' and data.iloc[i,14] == '-' and data.iloc[i,15] != '-' and data.iloc[i,16] == '-'):
put = data.iloc[i,15]
elif(data.iloc[i,13] == '-' and data.iloc[i,14] == '-' and data.iloc[i,15] == '-' and data.iloc[i,16] != '-'):
put = data.iloc[i,16]
elif(data.iloc[i,13] == '-' and data.iloc[i,14] == '-' and data.iloc[i,15] != '-' and data.iloc[i,16]!= '-'):
if(data.iloc[i,2]=='BOT'):
put = data.iloc[i,16]
else:
put = data.iloc[i,15]
for x in range(len(temp)):
if (float(temp.iloc[x,5]) == float(put)):
data.iloc[i,19] = temp.iloc[x,6]
if(data.iloc[i,10] == "CALL/PUT"):
if data.iloc[i,2] == 'BOT':
call = data.iloc[i,15]
for x in range(len(temp)):
if (float(temp.iloc[x,5]) == float(call)):
data.iloc[i,19] = temp.iloc[x,0]
elif data.iloc[i,2] == 'SOLD':
put = data.iloc[i,15]
for x in range(len(temp)):
if (float(temp.iloc[x,5]) == float(call)):
data.iloc[i,19] = temp.iloc[x,0]
except:
data.iloc[i,19] = 0
data["Current Premium"] = data["Current Premium"].fillna(0)
data[["Temp1","Temp2"]] = data["Quantity"].str.split("+", expand = True)
data[["Temp1","Temp3"]] = data["Quantity"].str.split("-", expand = True)
data["PnL"] = None
for i in range(len(data)):
if(data.iloc[i,21] == None):
data.iloc[i,21] = data.iloc[i,22]
for i in range(len(data)):
try:
if (data.iloc[i,19] != 0):
data.iloc[i,23] = float(data.iloc[i,11]) - float(data.iloc[i,19])
else:
data.iloc[i,23] = 0
except:
data.iloc[i,23] = 0
data["PL_Amount"] = None
for i in range(len(data)):
if data.iloc[i,20] != 0:
data.iloc[i,24] = data.iloc[i,23]*100
data["Profit/Loss"] = None
for i in range(len(data)):
try:
if(data.iloc[i,24] < 0):
data.iloc[i,25] = "Loss"
elif(data.iloc[i,24] > 0):
data.iloc[i,25] = "Profit"
else:
data.iloc[i,25] = "NA"
except:
data.iloc[i,21] = "NA"
data = data.drop(columns = ["Temp1","Temp2","Temp3","Strike Price"])
data.to_csv("options.csv", index=None)