AlirezaX2 commited on
Commit
25f14bb
·
1 Parent(s): 9b69e78

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +150 -0
main.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import yfinance as yf
2
+ import os
3
+ import pandas as pd
4
+ import requests
5
+ import json
6
+ import datetime
7
+
8
+
9
+ #calculating columns how many days to expiration dates
10
+ def daysleft(inputdate):
11
+ import datetime
12
+ previous_date = datetime.datetime.strptime(inputdate, '%Y-%m-%d')
13
+ today = datetime.datetime.today()
14
+ ndays = (previous_date - today).days +1
15
+ return ndays
16
+
17
+ #get All Option Chain for a ticker, calculate additional columns and retun as a dataframe from Yahoo finance
18
+ def get_DF_optionchain(ticker):
19
+ import requests_cache
20
+ session = requests_cache.CachedSession('yfinance.cache')
21
+ session.headers['User-agent'] = 'my-program/1.0'
22
+ # ticker = yf.Ticker('msft', session=session)
23
+
24
+ tkobj = yf.Ticker(ticker, session=session)
25
+ exps = tkobj.options
26
+
27
+ # Current Price in Market Session
28
+ # lastprice = tkobj.info['currentPrice']
29
+ lastprice = tkobj.history().iloc[-1]['Close']
30
+
31
+
32
+ #base price for additional column
33
+ bias_price = 'mark'
34
+ # bias_price = 'lastPrice'
35
+ options = pd.DataFrame()
36
+ for e in exps:
37
+ try:
38
+ print(e)
39
+ opt = tkobj.option_chain(e)
40
+ # opt_calls = pd.DataFrame().append(opt.calls)
41
+ opt_calls = opt.calls
42
+ opt_calls['Type'] = 'CALL'
43
+ # opt_puts = pd.DataFrame().append(opt.puts)
44
+ opt_puts = opt.puts
45
+ opt_puts['Type'] = 'PUT'
46
+ opt = opt_calls._append(opt_puts)
47
+ opt['expirationDate'] = e
48
+ opt['daysleft'] = daysleft(e)
49
+
50
+ opt[['bid', 'ask', 'strike']] = opt[['bid', 'ask', 'strike']].apply(pd.to_numeric)
51
+ opt['mark'] = (opt['bid'] + opt['ask']) / 2
52
+ opt['pricepercent'] = 100 * opt['mark'] / lastprice
53
+
54
+ opt[['bid', 'ask', 'strike']] = opt[['bid', 'ask', 'strike']].apply(pd.to_numeric)
55
+ opt['mark'] = (opt['bid'] + opt['ask']) / 2
56
+
57
+ opt['interinsicvalue'] = opt.apply(lambda row: abs(lastprice - row['strike']) if row['inTheMoney'] else 0, axis=1)
58
+ opt['timevalue'] = opt.apply(lambda row: row[bias_price] - row['interinsicvalue'], axis=1)
59
+ opt['breakevenprice'] = opt.apply(lambda row: row[bias_price]+ row['strike'] if row['Type']=='CALL' else row['strike'] - row['lastPrice'], axis=1)
60
+ options = options._append(opt, ignore_index=True)
61
+ except:
62
+ print('ERROR')
63
+ pass
64
+ return options
65
+
66
+
67
+
68
+ pathdatafolder = os.path.join('data' , datetime.datetime.today().strftime("%Y%m%d"))
69
+ if not os.path.exists(fr"./{pathdatafolder}"):
70
+ os.mkdir(fr"./{pathdatafolder}")
71
+
72
+ tickers = ['TSLA', 'META', 'GOOG', 'IBM', 'MSFT','NKE','DLTR','DG']
73
+
74
+ for ticker in tickers:
75
+ print(ticker)
76
+ try:
77
+ options = get_DF_optionchain(ticker)
78
+ options = options.drop(['contractSize','currency'] , axis=1)
79
+ options.to_csv(fr"./{pathdatafolder}/{ticker}.csv",index=False)
80
+ except:
81
+ pass
82
+
83
+
84
+ # df = pd.read_csv(r"\\PERSIA\New Volume\storage\premarket\america_2022-04-14.csv")
85
+
86
+ # df2 = df.query("`Market Capitalization`>10e9")
87
+
88
+ # import timeit
89
+ # start = timeit.default_timer()
90
+
91
+
92
+ # for index,row in df2.iterrows():
93
+ # ticker = row.Ticker
94
+ # print(ticker)
95
+ # try:
96
+ # options = get_DF_optionchain(ticker)
97
+ # options.to_csv(fr"./{pathdatafolder}/{ticker}.csv")
98
+ # except:
99
+ # pass
100
+
101
+
102
+
103
+ # stop = timeit.default_timer()
104
+ # print('Time: ', stop - start)
105
+
106
+
107
+
108
+
109
+ # import os
110
+ # import glob
111
+
112
+ # DFtotal = pd.DataFrame()
113
+ # for csvfile in glob.glob(r'./data/*.csv'):
114
+ # DF = pd.read_csv(csvfile)
115
+ # DF['Ticker'] = os.path.basename(csvfile).split('.')[0]
116
+ # DFtotal = DFtotal.append(DF)
117
+ # DFtotal.shape
118
+ # DFtotal.columns
119
+
120
+
121
+ # DFtotal.sort_values(by='impliedVolatility')[-10:].T
122
+ # DFtotal.sort_values(by='impliedVolatility')[-10:].T
123
+
124
+
125
+ # DFtotal.query('volume>100').sort_values(by='impliedVolatility')[-10:].T
126
+ # DFtotal.query('daysleft>7 & daysleft<60 & not inTheMoney & Type=="CALL" & openInterest>1000').sort_values(by='pricepercent')[-5:].T
127
+
128
+ # dftest = DFtotal.query('daysleft>7 & daysleft<60 & inTheMoney!=1 & Type=="CALL" &openInterest>100').sort_values(by='pricepercent')
129
+ # dftest['lasttradedate']=dftest['lastTradeDate'].str.split(' ', 0, expand=False).str[0]
130
+ # dftest.to_csv('test.csv')
131
+ # # dftest['lasttradedate']=pd.to_datetime(dftest['lastTradeDate'])
132
+ # dftest['lasttradedate2']=pd.to_datetime(dftest['lasttradedate'],format='%Y-%m-%d')
133
+ # dftest['year'] = pd.DatetimeIndex(dftest['lasttradedate']).year
134
+ # dftest['month'] = pd.DatetimeIndex(dftest['lasttradedate']).month
135
+ # dftest['day'] = pd.DatetimeIndex(dftest['lasttradedate']).day
136
+ # dftest.info()
137
+ # dftest.query('year==2022 & month==4 & day==14').sort_values(by='pricepercent')
138
+ # [-5:].T
139
+
140
+ # # dftest.query('lasttradedate>2022-04-14')
141
+
142
+ # df = pd.read_csv(r"./{pathdatafolder}/AAPL.csv")
143
+ # df.columns
144
+ # df.sort_values(by='impliedVolatility')[-5:].T
145
+
146
+ # df.query('impliedVolatility>1').sort_values(by='openInterest')[-5:].T
147
+
148
+ # df.query('daysleft>7 & daysleft<60 & not inTheMoney & Type=="CALL" & openInterest>10000').sort_values(by='bid')[-5:].T
149
+
150
+