def getOptions(ticker): dates = options.get_expiration_dates( ticker) # get available expiration dates calls = {} puts = {} for date in dates: # pull and format data if (parse(date) - datetime.now()).days > 60 and ( parse(date) - datetime.now()).days < 150: print(date) calls[date] = options.get_options_chain(ticker)['calls'].set_index( 'Strike') puts[date] = options.get_options_chain(ticker)['puts'].set_index( 'Strike') return {'calls': calls, 'puts': puts}
def update_options_strike_dropdown(clicks, date, option_type): if examined_stock.ticker!='': strike_prices = options.get_options_chain(examined_stock.ticker,date)[option_type.lower()+'s'].Strike.to_numpy() return [{'label':float(i), 'value':float(i)} for i in strike_prices] else: return [{'label':'', 'value':''}]
def check_iv(ticka): puts = pd.DataFrame() tries = 0 while puts.empty: if tries > 3: return 'yahoo' try: puts = opt.get_options_chain(ticka)['puts'] except: print('FAILED') time.sleep(random() + 1) tries += 1 if 'Implied Volatility' not in puts.columns: return 'yahoo' puts['Implied Volatility'] = puts['Implied Volatility'].apply( lambda x: float(x.replace('%', '').replace(',', '')) / 100) expiry = get_expiry_from_name(puts['Contract Name'][0], ticka) puts = puts[puts['Implied Volatility'] >= 1] puts['Bid'] = puts['Bid'].apply(lambda x: 0 if type(x) == str else x) puts = puts[puts['Bid'] > 0] puts = puts[puts['Strike'] <= 20] puts['Ticka'] = ticka puts['Exp'] = expiry puts = puts.rename(columns={ 'Implied Volatility': 'IV', 'Open Interest': 'OI', 'Volume': 'Vol' }) return puts.drop(columns=[ 'Last Price', 'Change', 'Last Trade Date', '% Change', 'Contract Name' ])
def get_opt_chain(ticker, exp_date): date = None if exp_date is not None: date = exp_date opt_chain = options.get_options_chain(ticker, date) # print(opt_chain) return opt_chain
def main2(): m = stockMongo() prices = [] try: dates = options.get_expiration_dates('AAPL') try: prices = options.get_options_chain('AAPL', dates[14]) price_calls = pd.DataFrame.from_dict(prices['calls']) price_puts = pd.DataFrame.from_dict(prices['puts']) strike_date = datetime.datetime.strptime(dates[14], '%B %d, %Y') price_calls['strike-date'] = strike_date price_puts['strike-date'] = strike_date now = datetime.datetime.now() #now = datetime.datetime.strptime(now.strftime("%m/%d/%Y"),"%m/%d/%Y") price_puts['date'] = now price_calls['date'] = now price_calls['type'] = 'call' price_puts['type'] = 'put' m = stockMongo() m.update_options('AAPL', price_calls, now, 'call') m.update_options('AAPL', price_puts, now, 'put') print("Options updated and stored") except: print("no prices") except: print("No date")
def get_options_chain(self, expiry_date=None): """ Extracts call / put option tables for input ticker and expiration date. If no date is input, the default result will be the earliest expiring option chain from the current date. @param: date """ return options.get_options_chain(self.ticker, expiry_date)
def DataExtraction(a,p): dates = options.get_expiration_dates(a) date = dates[p] newdate = DateConvert(date) data_chain1 = options.get_options_chain(a, newdate) for i in (data_chain1["calls"]["Contract Name"]): xlist.append("20"+i[4:10]) for i in (data_chain1["calls"]["Implied Volatility"]): ylist.append(i) for i in (data_chain1["calls"]["Strike"]): zlist.append(i)
def check(): for stock, premium in premium_stock.items(): period = 3 price = si.get_live_price(stock) print("Stock %s, price = %.2f, premium= %.2f " % (stock, price, premium)) expire_dates = ops.get_expiration_dates(stock) for date in expire_dates: period -= 1 if period < 0: break options = ops.get_options_chain(stock, date) start = price * 1.05 print( "Checking Call option for %s premium %f for range from %0.1f" % (date, premium, start)) calls = options["calls"] selected = calls.loc[(calls['Last Price'] > premium) & (calls['Strike'] > start) & (calls['Strike'] < start * 1.5)] for ind in selected.index: print( " Strike: %s %s Last: %s Bid: %s Ask: %s Volume: %s OI: %s " % (selected['Strike'][ind], selected['Contract Name'][ind], selected['Last Price'][ind], selected['Bid'][ind], selected['Ask'][ind], selected['Volume'][ind], selected['Open Interest'][ind])) start = price * 0.95 print( "Checking Put option for %s premium %f for range from %0.1f " % (date, premium, start)) puts = options["puts"] selected = puts.loc[(puts['Last Price'] > premium) & (puts['Strike'] < start) & (puts['Strike'] > start * .5)] for ind in selected.index: print( " Strike: %s %s Last: %s Bid: %s Ask: %s Volume: %s OI: %s " % (selected['Strike'][ind], selected['Contract Name'][ind], selected['Last Price'][ind], selected['Bid'][ind], selected['Ask'][ind], selected['Volume'][ind], selected['Open Interest'][ind]))
def search(): data = clean(options.get_options_chain(txt.get())) calls = data[0] puts = data[1] last_put_date = puts['Last Trade Date'].iloc[-1] last_call_date = calls['Last Trade Date'].iloc[-1] last_put_price = puts['Strike'].iloc[-1] last_call_price = calls['Strike'].iloc[-1] total_put_volume_three_days = sum( puts['Volume'][puts['Last Trade Date'] >= puts['Last Trade Date'][0] - timedelta(days=3)]) total_call_volume_three_days = sum(calls['Volume'][ calls['Last Trade Date'] >= calls['Last Trade Date'][0] - timedelta(days=3)]) average_put_implied_volatility_three_days = str( round( np.mean(puts['implied volatility'][ puts['Last Trade Date'] >= puts['Last Trade Date'][0] - timedelta(days=3)]), 2)) + "%" average_call_implied_volatility_three_days = str( round( np.mean(calls['implied volatility'][ calls['Last Trade Date'] >= calls['Last Trade Date'][0] - timedelta(days=3)]), 2)) + "%" indexs = [ 'Last Put Date', 'Last Call Date', 'Last Put Price', 'Last Call Price', 'Total Put Volume in Last Three days', 'Total Call Volume in Last Three days', 'Average Put Implied Volatility in Last Three days', 'Average Call Implied Volatility in Last Three days' ] values = [ last_put_date, last_call_date, last_put_price, last_call_price, total_put_volume_three_days, total_call_volume_three_days, average_put_implied_volatility_three_days, average_call_implied_volatility_three_days ] summary = pd.DataFrame() summary['Indexes'] = indexs summary['Values'] = values frame = tk.Text(self) frame.delete(1.0, tk.END) frame.insert(tk.END, summary) frame.grid(column=1, row=2)
def display_calls_table(clicks, date): if date is None: return[{'Contract Name':'', 'Last Trade Date': '', 'Strike':'', 'Last Price': '','Bid': '','Ask':'','Change':'', '% Change':'','Volume':'','Open Interest':'', 'Implied Volatility': ''}], [{'Contract Name':'', 'Last Trade Date': '', 'Strike':'', 'Last Price': '', 'Bid': '', 'Ask':'', 'Change':'', '% Change':'', 'Volume':'', 'Open Interest':'', 'Implied Volatility': ''}] else: return options.get_options_chain(examined_stock.ticker,date)['calls'].to_dict('records'), options.get_options_chain(examined_stock.ticker,date)['puts'].to_dict('records')
def collect_options(tick, day): try: prices = options.get_options_chain(tick, day) price_calls = pd.DataFrame.from_dict(prices['calls']) price_puts = pd.DataFrame.from_dict(prices['puts']) strike_date = datetime.datetime.strptime(day, '%B %d, %Y') price_calls['strike-date'] = strike_date price_puts['strike-date'] = strike_date now = datetime.datetime.now() now = datetime.datetime.strptime(now.strftime("%m/%d/%Y"), "%m/%d/%Y") price_puts['date'] = now price_calls['date'] = now price_calls['type'] = 'call' price_puts['type'] = 'put' m = stockMongo() m.update_options(tick, price_calls, now, 'call') m.update_options(tick, price_puts, now, 'put') except: pass
def get_calls_and_puts_formated(self, expiry_date=None): if not self.live_prices_released(): chain = self.get_calls_and_puts_formated_old_prices(expiry_date) else: chain = options.get_options_chain(self.ticker, expiry_date) calls = chain['calls'] c_strike_idx = self.get_closests(calls, "Strike", self.underlying) print("c_idx: ", c_strike_idx, "len: ", len(calls)) c_range_lower = max(0, c_strike_idx - (len(calls) - c_strike_idx)) calls = calls[c_range_lower:] calls.reset_index(inplace=True, drop=True) calls = calls[[ "Strike", "Change", "% Change", "Bid", "Ask", "Last Price", "Implied Volatility" ]] call_deltas = self.get_deltas(calls, "call", expiry_date) calls['delta'] = call_deltas #calls = calls[max(0,c_strike_idx-10):min(len(calls),c_strike_idx+11)] puts = chain['puts'] p_strike_idx = self.get_closests(puts, "Strike", self.underlying) print("p_idx: ", p_strike_idx, "len: ", len(puts)) p_range_lower = max(0, p_strike_idx - (len(puts) - p_strike_idx)) puts = puts[p_range_lower:].reset_index() puts = puts[[ "Strike", "Change", "% Change", "Bid", "Ask", "Implied Volatility" ]] put_deltas = self.get_deltas(puts, "put", expiry_date) puts['delta'] = put_deltas print("Underlying Check", self.underlying) new_c_strike_index, new_p_strike_index = self.get_closests( calls, "Strike", self.underlying), self.get_closests(puts, "Strike", self.underlying) #puts = puts[max(0,p_strike_idx-10):min(len(puts),p_strike_idx+11)] self.calls_formatted = calls.copy() self.puts_formatted = puts.copy() return calls, puts, new_c_strike_index, new_p_strike_index
def existing_dates_calc(existing_dates, stock_price, date_today, rate,historical_loc, t): writer = pd.ExcelWriter(historical_loc + t + '.xlsx', engine = 'openpyxl') writer.book = load_workbook(historical_loc + t + '.xlsx') writer.sheets = dict((ws.title, ws) for ws in writer.book.worksheets) reader = pd.read_excel(r''+historical_loc+t+'.xlsx') for d in existing_dates: print('updating date tab {} for {}'.format(d, t)) years_to_maturity = stock_options.years_to_maturity_calc(d) #get list of contract values previously collected contracts = get_options_stored(historical_loc+t+'.xlsx', d) #should include both calls and puts header1 = ['Date', 'Price Today', 'Rate'] header2 = ['', '', ''] row = [date_today, stock_price, rate] print('updating existing contract values') header1, header2, row = calc_existing_contracts(t, d, contracts, years_to_maturity, rate, stock_price, header1, header2, row) #look through contracts not already listed; if any new contracts for the given date, calculate greeks for the new contracts and expand 'contract names' list all_contracts = options.get_options_chain(t, d) lst1 = all_contracts['calls']['Contract Name'].to_list() lst2 = all_contracts['puts']['Contract Name'].to_list() all_contracts = lst1+lst2 new_contracts = [c for c in all_contracts if c not in contracts] print('adding {} new contracts to existing date {} for {}'.format(len(new_contracts), d, t)) header1, header2, row = calc_existing_contracts(t, d, new_contracts, years_to_maturity, rate, stock_price, header1, header2, row) col_names = pd.MultiIndex.from_tuples(list(zip(*[header1, header2]))) df = pd.DataFrame( data = [row], columns = col_names) df = df.set_index('Date') # #new row added df.to_excel(writer,d, header = False, startrow = len(reader) + 1) #update header writer.save() return
def calc_existing_contracts(t, d, contracts,years_to_maturity, rate, stock_price,header1, header2, row): all_contracts= options.get_options_chain(t, d) for c in contracts: if stock_options.option_breakdown(c)['option']=='C': iv = all_contracts['calls'].loc[all_contracts['calls']['Contract Name']==c]['Implied Volatility'].to_list()[0][0:-1] if ',' in iv: iv = iv.replace(',', '') implied_volatility = float(iv)/100 strike_price = all_contracts['calls'].loc[all_contracts['calls']['Contract Name']==c]['Strike'].to_list()[0] calc = stock_options.option_greeks(stock_price, strike_price, years_to_maturity, implied_volatility, rate)['call'] calculated_price = stock_options.option_price(stock_price, strike_price, years_to_maturity, implied_volatility, rate)['call'] else: iv = all_contracts['puts'].loc[all_contracts['puts']['Contract Name']==c]['Implied Volatility'].to_list()[0][0:-1] if ',' in iv: iv = iv.replace(',', '') implied_volatility = float(iv)/100 strike_price = all_contracts['puts'].loc[all_contracts['puts']['Contract Name']==c]['Strike'].to_list()[0] calc = stock_options.option_greeks(stock_price, strike_price, years_to_maturity, implied_volatility, rate)['put'] calculated_price = stock_options.option_price(stock_price, strike_price, years_to_maturity, implied_volatility, rate)['put'] delta = calc['delta'] gamma = calc['gamma'] theta = calc['theta'] vega = calc['vega'] rho = calc['rho'] row.append(calculated_price) row.append(implied_volatility) row.append(delta) row.append(gamma) row.append(theta) row.append(vega) row.append(rho) #extend header header1 = header1 + [c] * 7 header2 = header2 + ['Option Price', 'Implied Volatility', 'Delta', 'Gamma', 'Theta', 'Vega', 'Rho'] return header1, header2, row
def new_dates_calc(new_dates, stock_price, date_today, rate,historical_loc, t): #creates new file if ticker hasnt been tracked yet writer = pd.ExcelWriter(historical_loc + t+'.xlsx', engine = 'openpyxl') for d in new_dates: print('creating new date tab for {}, date {}'.format(t, d)) years_to_maturity = stock_options.years_to_maturity_calc(d) #get list of contract values previously collected #contracts = get_options_stored(historical_loc+t+'.xlsx', d) #should include both calls and puts header1 = ['Date', 'Price Today', 'Rate'] header2 = ['', '', ''] row = [date_today, stock_price, rate] #header1, header2, row = calc_existing_contracts(t, d, contracts, # years_to_maturity, rate, stock_price, header1, header2, row) #look through contracts not already listed; if any new contracts for the given date, calculate greeks for the new contracts and expand 'contract names' list try: all_contracts = options.get_options_chain(t, d) lst1 = all_contracts['calls']['Contract Name'].to_list() lst2 = all_contracts['puts']['Contract Name'].to_list() all_contracts = lst1+lst2 header1, header2, row = calc_existing_contracts(t, d, all_contracts, years_to_maturity, rate, stock_price, header1, header2, row) except ValueError: all_contracts = [] print('no current contracts for {}'.format(d)) col_names = pd.MultiIndex.from_tuples(list(zip(*[header1, header2]))) df = pd.DataFrame( data = [row], columns = col_names) df = df.set_index('Date') df.to_excel(writer, d) writer.save() #for each date, create new tab and write df to historical_loc + t return
def GetPrice(ticker, date, strike, type='calls'): chain = options.get_options_chain(ticker, date)[type] return (float)(chain[chain['Strike'] == strike]['Last Price'])
def optimal_options_combination(ticker, date, price_today, risk_free_rate): all_options = options.get_options_chain(ticker, date) calls = all_options['calls'].to_dict('record') puts = all_options['puts'].to_dict('record') years_to_maturity = years_to_maturity_calc(date) good_combinations = [] for c in calls: for p in puts: ##### call_iv = float(c['Implied Volatility'][0:-1].replace(',', '')) / 100 put_iv = float(p['Implied Volatility'][0:-1].replace(',', '')) / 100 call_strike_price = c['Strike'] put_strike_price = p['Strike'] call_option_price = round( option_price(price_today, call_strike_price, years_to_maturity, call_iv, risk_free_rate)['call'], 2) #call_option_price = np.max([c['Last Price'], c['Bid'], c['Ask']]) put_option_price = round( option_price(price_today, put_strike_price, years_to_maturity, put_iv, risk_free_rate)['put'], 2) #put_option_price = np.max([p['Last Price'], p['Bid'], p['Ask']]) if (c == 20) & (p == 25): print([call_option_price, put_option_price]) total_option_cost = call_option_price + put_option_price # c_xval = [0, call_strike_price, call_strike_price + call_option_price, call_strike_price * 1.5] # p_xval = [0, max(0, put_strike_price - put_option_price), put_strike_price, put_strike_price*1.5] combined_xval = np.sort( np.unique([ 0, call_strike_price, call_strike_price + call_option_price, max(call_strike_price * 1.5, (call_strike_price + call_option_price) * 1.2), max(0, put_strike_price - put_option_price), put_strike_price, put_strike_price * 1.5 ])) # combined_xval = np.sort(np.unique(np.array(c_xval+p_xval))) overall_profit = [] for v in combined_xval: temp_prof = 0 if v <= call_strike_price: temp_prof -= call_strike_price else: temp_prof += (v - call_strike_price) if v >= put_strike_price: temp_prof -= put_strike_price else: temp_prof += (put_strike_price - v) overall_profit.append( max(v - call_strike_price, 0) + max(put_strike_price - v, 0) - total_option_cost) if np.min(overall_profit) > 1: good_combinations.append({ 'profit': [combined_xval, overall_profit], 'call': c, 'put': p }) return good_combinations
import yahoo_fin.options as ops import pandas #expiration_dates = ops.get_expiration_dates("aapl") #print(expiration_dates) stocks = ["sq", "amd", "dis", "v"] for s in stocks: options = ops.get_options_chain(s) call_file_name = s + "_call.csv" put_file_name = s + "_put.csv" options["calls"].to_csv(call_file_name) options["puts"].to_csv(put_file_name) #chain = pandas.read_csv(file_name) #print(chain.columns) #['Strike'], d['Last Price']
import requests import requests_html import ssl import numpy as np from yahoo_fin import options from yahoo_fin import stock_info as si import matplotlib.pyplot as plt import py_vollib.black_scholes as vol import yfinance as yf tickers = ["aapl", "nflx"] dow_data = {} for ticker in tickers: try: dow_data[ticker] = options.get_options_chain(ticker) except Exception: print(ticker + " failed") print(dow_data["aapl"]["calls"].keys()) for ticker in tickers: iv_dec = [] calls = dow_data[ticker]['calls'] volatility = calls["Implied Volatility"] for ii in range(len(volatility)): x = volatility[ii] dec = float(x.strip('%').replace(',', '')) / 100 iv_dec.append(dec) dow_data[ticker]['calls']["iv_dec"] = iv_dec
# get option chain first l = options.get_expiration_dates(symbol) count = 0 df = pd.DataFrame() # extract option chains by expiration dates for x in l: count = count + 1 if count >= 0 and count <= 100: df_calls = pd.DataFrame() df_puts = pd.DataFrame() try: expiration = datetime.strptime(x, "%B %d, %Y").strftime('%d/%m/%Y') da = options.get_options_chain(symbol, expiration) df_calls = df_calls.append(pd.DataFrame(da['calls']), ignore_index=True) df_puts = df_puts.append(pd.DataFrame(da['puts']), ignore_index=True) df_calls = df_calls.loc[(df_calls['Bid'] != 0) & (df_calls['Ask'] != 0)] df_calls = df_calls.loc[(df_calls['Bid'] != '-') & (df_calls['Ask'] != '-')] df_puts = df_puts.loc[(df_puts['Bid'] != 0) & (df_puts['Ask'] != 0)] df_puts = df_puts.loc[(df_puts['Bid'] != '-') & (df_puts['Ask'] != '-')] df = df.append(df_calls, ignore_index=True) df = df.append(df_puts, ignore_index=True)
from yahoo_fin import options import pandas as pd import sys if __name__ == '__main__': STOCK = sys.argv[1] with pd.ExcelWriter(STOCK + ".xlsx") as writer: for date in options.get_expiration_dates(STOCK): options_at_expiry = options.get_options_chain(STOCK, date) options_at_expiry["calls"].to_excel(writer, sheet_name=date + " calls") options_at_expiry["puts"].to_excel(writer, sheet_name=date + " puts")
def getOptTable(_type, _ticker, _date): try: return op.get_options_chain(_ticker, _date)[_type].to_numpy() except: return "Unable to load options chain for the requested data, please check your inputs"
# CALL Option: Right but not obligation to BUY a certain asset up to a certain date. # PUT Option: Right but not obligation to SELL a certain asset up to a certain date. from yahoo_fin import options import pandas as pd stock = 'MSFT' # Selected Stock Ticker print(f'All Expiration Dates for {stock}: ') print(options.get_expiration_dates(stock)) # Get all possible expiration dates print('\n') pd.set_option('display.max_columns', None) # View all columns chain = options.get_options_chain( stock, 'August 20, 2021') # Give all options that expire before a particular date #print(chain) # All Options #print('\n') print('CALL Options: \n') print(chain['calls']) # CALL Options print('\n') print('PUT Options: \n') print(chain['puts']) # PUT Options print('\n') # Another way to get call and put options directly chain = options.get_calls(stock, 'August 20, 2021') #print(chain) # Strike value depends on Stock's price, so modify as per requirement. print('CALL Options: Strike <=150 \n')
DB_PASS = os.getenv("DB_PASS") DB_USER = os.getenv("DB_USER") DB_HOST = os.getenv("DB_HOST") engine = create_engine(f"mysql://{DB_USER}:{DB_PASS}@{DB_HOST}/options") conn = engine.connect() table_name = 'options_data' hour = str(datetime.now().time().hour) base_dir = '/home/pi/options/' # change as needed tickers = pd.read_csv(base_dir + 'tickers_csv.csv')['TICKER'] #tickers=['AAL'] for ticker in tickers: try: chain = get_options_chain(ticker) puts = chain['puts'] calls = chain['calls'] except ValueError: file = open(base_dir + 'errors/error ' + str(date.today()) + '.txt', 'a') file.write(ticker + ' ' + hour + '\n') file.close() puts['contract'] = 'P' calls['contract'] = 'C' data = pd.concat([puts, calls]) data.reset_index(drop=True, inplace=True) data['pull_timestamp'] = str(datetime.now())
def GetChain(ticker, dates, idx, type='calls'): chain = options.get_options_chain(ticker, GetDate(dates, idx)) return chain[type]
#stocks = ["sq", "amd", "dis", "v"] stocks = ["aapl", "nflx", "nvda", "tsla", "sq", "intc", "arkk", "tsm", "v"] for s in stocks: period = 2 p = si.get_live_price(s) print ("Stock %s, price = %.2f"%(s,p)) expire_dates = ops.get_expiration_dates(s) for date in expire_dates: period -= 1 if period < 0: break premium = int (p/100) + 0.5 options = ops.get_options_chain(s, date) start = p*1.05 end = p*1.3 print ("Checking Call option for %s premium %f for range %0.1f - %0.1f"%(date, premium, start,end )) calls = options["calls"] selected = calls.loc[(calls['Last Price']> premium ) & (calls['Strike']> start) & (calls['Strike']< end) ] for ind in selected.index: print( " Strike: %s %s Last: %s Volume: %s OI: %s " % (selected['Strike'][ind], selected['Contract Name'][ind], selected['Last Price'][ind], selected['Volume'][ind], selected['Open Interest'][ind]) ) start = p*0.7 end = p*0.95 print ("Checking Put option for %s premium %f for range %0.1f - %0.1f"%(date, premium, start,end )) puts = options["puts"]
import datetime as dt import matplotlib.pyplot as plt from matplotlib import style import pandas as pd import pandas_datareader.data as web import robin_stocks as rh import json import userFunctions as uf import rhorders as rho from yahoo_fin import options from yahoo_fin import stock_info as si spy_tickers = si.tickers_sp500() spy_tickers.append('SPY') spy_tickers.append('TLT') print(spy_tickers) # scrape the options data for each Dow ticker spy_data = {} for ticker in spy_tickers: ticker_dates = options.get_expiration_dates(ticker) info = {} for date in ticker_dates: info[date] = options.get_options_chain(ticker) pd.DataFrame.to_csv('{}{}.csv'.format(ticker, date))
def extract_save_option_data(ticker): """ Imports and saves from the yahoo finance database a company's option data. The option data is split per type (call or put), expiration date, and day. It does: 1. Checks for nested directories: <ticker>\options_data_<ticker>\<expiration_date>_<ticker>_<options> Creates it if non-existent. 2. Checks in the folder for a file named: <expiration_date>_<ticker>_<calls/puts>_as-at_<date_extract> If so: merges the existing and newly extracted data. 3. Saves the data (merged when applicable) in the folder under the company's ticker. -------- :param <ticker>: String ; ticker of a company traded on the financial markets """ extract_dates = options.get_expiration_dates(ticker) today = datetime.today().strftime("%Y-%m-%d") for expiration_date in extract_dates: format_date = arrow.get(expiration_date, 'MMMM D, YYYY').format('YYYY-MM-DD') extract_date = arrow.get(expiration_date, 'MMMM D, YYYY').format('MM/DD/YYYY') try: extract = options.get_options_chain(ticker, extract_date) path = ticker + "\\options_data_" + ticker + "\\" + format_date + "_" + ticker + "_options" option_types = ["calls", "puts"] for option in option_types: extract_chain = extract[option] extract_chain = extract_chain.to_dict(orient="index") data_file_name = format_date + "_" + ticker + "_" + option + "_as-at_" + today # Step 1 if not os.path.exists(path): os.makedirs(path) # Step 2 if os.path.isfile(os.path.join(path, data_file_name)) == True: try: with open(os.path.join(path, data_file_name), 'r') as file: existing_data_in_file = json.load(file) for item in existing_data_in_file: extract_chain[item] = existing_data_in_file[ item] except Exception as e: print(f"{ticker}: {e}") #Step 3 with open(os.path.join(path, data_file_name), 'w') as f: json.dump(extract_chain, f) print( f"{ticker}: {format_date} {option} options data retrieved successfully!\n" ) except Exception as e: print( f"{ticker}: {format_date} options data could not be retrieved.\n" )
#bestExpDates = find_closed_exp_dates(int(hedgeDay), int(hedgeMonth), int(hedgeYear), expDates, 3) currentStr = "Select hedge date: " #actualHedgeDate = st.radio(currentStr, bestExpDates) actualHedgeDate = st.radio(currentStr, expDates) # 4: correct option type for stock in list: if (reqDelta < 0): optionType = 'puts' elif (reqDelta > 0): optionType = 'calls' else: optionType = 'None' # 5: corresponding delta, strike prices options_chain = options.get_options_chain(benchmark, actualHedgeDate) options_chain = options_chain[optionType] options_delta = pd.DataFrame() options_delta['Strike'] = options_chain['Strike'] options_delta['Delta'] = np.NaN if (optionType == 'calls'): for strike in range(0, len(options_delta)): d1 = Call(benchmark, d=int(hedgeDay), m=int(hedgeMonth), y=int(hedgeYear), strike=options_delta['Strike'][strike]) options_delta.iloc[strike, 1] = d1.delta() else: for strike in range(0, len(options_delta)): d1 = Put(benchmark,