def calc_realized_vol_4options_ticker(**kwargs): ticker = kwargs['ticker'] contract_specs_output = cmi.get_contract_specs(ticker) if contract_specs_output['ticker_class'] in ['Index', 'FX', 'Metal']: use_proxy_contract = True else: use_proxy_contract = False if use_proxy_contract: if 'futures_data_dictionary' in kwargs.keys(): futures_data_input = { 'ticker_head': contract_specs_output['ticker_head'], 'settle_date': kwargs['settle_date'] } futures_data_input['futures_data_dictionary'] = kwargs[ 'futures_data_dictionary'] data_out = gfp.get_futures_price_preloaded(**futures_data_input) data_out = data_out.reset_index() kwargs['ticker'] = data_out['ticker'].loc[ data_out['volume'].idxmax()] else: kwargs['ticker'] = omu.get_option_underlying(**kwargs) return calc_realized_vol_4futures_ticker(**kwargs)
def cal_greeks_4option_maturity(**kwargs): option_prices = gop.get_options_price_from_db(**kwargs) if option_prices.empty: return pd.DataFrame() option_prices = option_prices[option_prices['strike'] > 0] option_prices.reset_index(drop=True, inplace=True) contract_specs_out = cmi.get_contract_specs(kwargs['ticker']) exercise_type = cmi.get_option_exercise_type(**contract_specs_out) underlying_ticker = oput.get_option_underlying(**kwargs) futures_price_output = gfp.get_futures_price_preloaded( ticker=underlying_ticker, settle_date=kwargs['settle_date']) if futures_price_output.empty: return pd.DataFrame() underlying_price = futures_price_output['close_price'].iloc[0] expiration_datetime = exp.get_expiration_from_db(instrument='options', **kwargs) expiration_date = int(expiration_datetime.strftime('%Y%m%d')) interest_rate = grfs.get_simple_rate( as_of_date=kwargs['settle_date'], date_to=expiration_date)['rate_output'] option_greeks = [ qom.get_option_greeks(underlying=underlying_price, option_price=float( option_prices['close_price'].iloc[x]), strike=float(option_prices['strike'].iloc[x]), risk_free_rate=interest_rate, expiration_date=expiration_date, calculation_date=kwargs['settle_date'], option_type=option_prices['option_type'].iloc[x], exercise_type=exercise_type) for x in range(len(option_prices.index)) ] greek_frame = pd.DataFrame(option_greeks) return pd.concat([ greek_frame[['delta', 'gamma', 'implied_vol', 'theta', 'vega']], option_prices ], axis=1)
def calc_intraday_structure_pnl_from_prices(**kwargs): if 'as_of_date' in kwargs.keys(): as_of_date = kwargs['as_of_date'] else: as_of_date = exp.doubledate_shift_bus_days() con = msu.get_my_sql_connection(**kwargs) structure_type = kwargs['structure_type'] structure_price = kwargs['structure_price'] ticker_list = kwargs['ticker_list'] strike_list = kwargs['strike_list'] underlying_price_list = kwargs['underlying_price_list'] qty = kwargs['qty'] if structure_type == 'straddle_spread': option_frame = pd.DataFrame.from_items([('ticker', [ticker_list[0], ticker_list[0], ticker_list[1], ticker_list[1]]), ('option_type', ['C', 'P', 'C', 'P']), ('strike_price', [strike_list[0], strike_list[0], strike_list[1],strike_list[1]]), ('qty', [-1, -1, 1, 1])]) option_price_output = [gop.get_options_price_from_db(ticker=option_frame['ticker'].iloc[x], strike=option_frame['strike_price'].iloc[x], option_type=option_frame['option_type'].iloc[x], con=con,settle_date=as_of_date,column_names=['close_price','delta']) for x in range(len(option_frame.index))] option_frame['delta'] = [option_price_output[x]['delta'][0] for x in range(len(option_frame.index))] option_frame['close_price'] = [option_price_output[x]['close_price'][0] for x in range(len(option_frame.index))] option_frame['PQ'] = option_frame['close_price']*option_frame['qty'] option_frame['signed_delta'] = option_frame['delta']*option_frame['qty'] delta_list = [option_frame[option_frame['ticker'] == x]['signed_delta'].sum() for x in ticker_list] ticker_head = cmi.get_contract_specs(ticker_list[0])['ticker_head'] contract_multiplier = cmi.contract_multiplier[ticker_head] structure_price_yesterday = option_frame['PQ'].sum() structure_pnl = qty*(structure_price-structure_price_yesterday)*contract_multiplier underlying_ticker_list = [oputil.get_option_underlying(ticker=x) for x in ticker_list] underlying_price_list_yesterday = [gfp.get_futures_price_preloaded(ticker=x, settle_date=as_of_date)['close_price'].iloc[0] for x in underlying_ticker_list] delta_pnl = contract_multiplier*sum([-delta_list[x]*qty*(underlying_price_list[x]-underlying_price_list_yesterday[x]) for x in range(len(delta_list))]) return {'total_pnl': structure_pnl+delta_pnl, 'structure_pnl': structure_pnl, 'delta_pnl': delta_pnl, 'structure_price_yesterday': structure_price_yesterday }
def calc_realized_vol_4options_ticker(**kwargs): ticker = kwargs['ticker'] contract_specs_output = cmi.get_contract_specs(ticker) if contract_specs_output['ticker_class'] in ['Index', 'FX', 'Metal']: use_proxy_contract = True else: use_proxy_contract = False if use_proxy_contract: if 'futures_data_dictionary' in kwargs.keys(): futures_data_input = {'ticker_head': contract_specs_output['ticker_head'],'settle_date': kwargs['settle_date']} futures_data_input['futures_data_dictionary'] = kwargs['futures_data_dictionary'] data_out = gfp.get_futures_price_preloaded(**futures_data_input) data_out = data_out.reset_index() kwargs['ticker'] = data_out['ticker'].loc[data_out['volume'].idxmax()] else: kwargs['ticker'] = omu.get_option_underlying(**kwargs) return calc_realized_vol_4futures_ticker(**kwargs)
def cal_greeks_4option_maturity(**kwargs): option_prices = gop.get_options_price_from_db(**kwargs) if option_prices.empty: return pd.DataFrame() contract_specs_out = cmi.get_contract_specs(kwargs['ticker']) exercise_type = cmi.get_option_exercise_type(**contract_specs_out) underlying_ticker = oput.get_option_underlying(**kwargs) futures_price_output = gfp.get_futures_price_preloaded(ticker=underlying_ticker, settle_date=kwargs['settle_date']) if futures_price_output.empty: return pd.DataFrame() underlying_price = futures_price_output['close_price'].iloc[0] expiration_datetime = exp.get_expiration_from_db(instrument='options', **kwargs) expiration_date = int(expiration_datetime.strftime('%Y%m%d')) interest_rate = grfs.get_simple_rate(as_of_date=kwargs['settle_date'], date_to=expiration_date)['rate_output'] #print(kwargs['settle_date']) #print(expiration_date) option_greeks = [qom.get_option_greeks(underlying=underlying_price, option_price=float(option_prices['close_price'].iloc[x]), strike=float(option_prices['strike'].iloc[x]), risk_free_rate=interest_rate, expiration_date=expiration_date, calculation_date=kwargs['settle_date'], option_type=option_prices['option_type'].iloc[x], exercise_type=exercise_type) for x in range(len(option_prices.index))] greek_frame = pd.DataFrame(option_greeks) return pd.concat([greek_frame[['delta', 'gamma', 'implied_vol', 'theta', 'vega']], option_prices], axis=1)
def main(): app = algo.Algo() report_date = exp.doubledate_shift_bus_days() todays_date = cu.get_doubledate() con = msu.get_my_sql_connection() vcs_output = vcs.generate_vcs_sheet_4date(date_to=report_date) vcs_pairs = vcs_output['vcs_pairs'] filter_out = of.get_vcs_filters(data_frame_input=vcs_pairs, filter_list=['long2', 'short2']) vcs_pairs = filter_out['selected_frame'] vcs_pairs = vcs_pairs[vcs_pairs['downside'].notnull() & vcs_pairs['upside'].notnull()] # &(vcs_pairs.tickerClass!='Energy') vcs_pairs = vcs_pairs[(vcs_pairs['trDte1'] >= 50) & (vcs_pairs.tickerClass != 'Metal') & (vcs_pairs.tickerClass != 'FX') & (vcs_pairs.tickerClass != 'Energy')] vcs_pairs = vcs_pairs[((vcs_pairs['Q'] <= 30) & (vcs_pairs['fwdVolQ'] >= 30)) | ((vcs_pairs['Q'] >= 70) & (vcs_pairs['fwdVolQ'] <= 70))] vcs_pairs.reset_index(drop=True, inplace=True) vcs_pairs['underlying_ticker1'] = [ omu.get_option_underlying(ticker=x) for x in vcs_pairs['ticker1'] ] vcs_pairs['underlying_ticker2'] = [ omu.get_option_underlying(ticker=x) for x in vcs_pairs['ticker2'] ] vcs_pairs['underlying_tickerhead'] = [ cmi.get_contract_specs(x)['ticker_head'] for x in vcs_pairs['underlying_ticker1'] ] futures_data_dictionary = { x: gfp.get_futures_price_preloaded(ticker_head=x) for x in vcs_pairs['underlying_tickerhead'].unique() } proxy_output_list1 = [ up.get_underlying_proxy_ticker( ticker=x, settle_date=report_date, futures_data_dictionary=futures_data_dictionary) for x in vcs_pairs['underlying_ticker1'] ] vcs_pairs['proxy_ticker1'] = [x['ticker'] for x in proxy_output_list1] vcs_pairs['add_2_proxy1'] = [x['add_2_proxy'] for x in proxy_output_list1] proxy_output_list2 = [ up.get_underlying_proxy_ticker( ticker=x, settle_date=report_date, futures_data_dictionary=futures_data_dictionary) for x in vcs_pairs['underlying_ticker2'] ] vcs_pairs['proxy_ticker2'] = [x['ticker'] for x in proxy_output_list2] vcs_pairs['add_2_proxy2'] = [x['add_2_proxy'] for x in proxy_output_list2] vcs_pairs['expiration_date1'] = [ int( exp.get_expiration_from_db(instrument='options', ticker=x, con=con).strftime('%Y%m%d')) for x in vcs_pairs['ticker1'] ] vcs_pairs['expiration_date2'] = [ int( exp.get_expiration_from_db(instrument='options', ticker=x, con=con).strftime('%Y%m%d')) for x in vcs_pairs['ticker2'] ] vcs_pairs['interest_date1'] = [ grfs.get_simple_rate(as_of_date=report_date, date_to=x)['rate_output'] for x in vcs_pairs['expiration_date1'] ] vcs_pairs['interest_date2'] = [ grfs.get_simple_rate(as_of_date=report_date, date_to=x)['rate_output'] for x in vcs_pairs['expiration_date2'] ] vcs_pairs['exercise_type'] = [ cmi.get_option_exercise_type(ticker_head=x) for x in vcs_pairs['tickerHead'] ] admin_dir = dna.get_directory_name(ext='admin') risk_file_out = su.read_text_file(file_name=admin_dir + '/RiskParameter.txt') vcs_risk_parameter = 5 * 2 * float(risk_file_out[0]) vcs_pairs['long_quantity'] = vcs_risk_parameter / abs( vcs_pairs['downside']) vcs_pairs['short_quantity'] = vcs_risk_parameter / vcs_pairs['upside'] vcs_pairs['long_quantity'] = vcs_pairs['long_quantity'].round() vcs_pairs['short_quantity'] = vcs_pairs['short_quantity'].round() vcs_pairs['alias'] = [ generate_vcs_alias(vcs_row=vcs_pairs.iloc[x]) for x in range(len(vcs_pairs.index)) ] vcs_pairs['call_mid_price1'] = np.nan vcs_pairs['put_mid_price1'] = np.nan vcs_pairs['call_mid_price2'] = np.nan vcs_pairs['put_mid_price2'] = np.nan vcs_pairs['call_iv1'] = np.nan vcs_pairs['put_iv1'] = np.nan vcs_pairs['call_iv2'] = np.nan vcs_pairs['put_iv2'] = np.nan vcs_pairs['underlying_mid_price1'] = np.nan vcs_pairs['underlying_mid_price2'] = np.nan vcs_pairs['proxy_mid_price1'] = np.nan vcs_pairs['proxy_mid_price2'] = np.nan vcs_pairs['current_strike1'] = np.nan vcs_pairs['current_strike2'] = np.nan ta_folder = dn.get_dated_directory_extension(folder_date=todays_date, ext='ta') app.vcs_pairs = vcs_pairs app.con = con app.futures_data_dictionary = futures_data_dictionary app.report_date = report_date app.todays_date = todays_date app.log = lg.get_logger(file_identifier='vcs', log_level='INFO') app.trade_file = ta_folder + '/trade_dir.csv' app.vcs_risk_parameter = vcs_risk_parameter app.connect(client_id=3) app.run()
def get_hedge_4strategy(**kwargs): con = msu.get_my_sql_connection(**kwargs) current_date = cu.get_doubledate() settle_price_date = exp.doubledate_shift_bus_days(double_date=current_date, shift_in_days=1) position_frame = tas.get_net_position_4strategy_alias(alias=kwargs['alias'],as_of_date=current_date,con=con) intraday_price_frame = gip.get_cme_direct_prices() intraday_price_frame.rename(columns={'ticker': 'underlying_ticker'},inplace=True) intraday_price_frame['ticker_head'] = [cmi.get_contract_specs(x)['ticker_head'] for x in intraday_price_frame['underlying_ticker']] intraday_price_frame['mid_price'] = (intraday_price_frame['bid_price'] + intraday_price_frame['ask_price'])/2 intraday_price_frame['mid_price'] = [tfl.convert_trade_price_from_cme_direct(ticker_head=intraday_price_frame['ticker_head'].iloc[x], price=intraday_price_frame['mid_price'].iloc[x]) for x in range(len(intraday_price_frame.index))] options_frame = position_frame[position_frame['instrument'] == 'O'] futures_frame = position_frame[position_frame['instrument'] == 'F'] if options_frame.empty: futures_frame.rename(columns={'ticker': 'underlying_ticker', 'qty': 'underlying_delta'},inplace=True) futures_frame = futures_frame[['underlying_ticker', 'underlying_delta']] net_position = pd.merge(futures_frame, intraday_price_frame, how='left', on='underlying_ticker') net_position['hedge_price'] = net_position['mid_price'] net_position['hedge'] = -net_position['underlying_delta'] return net_position imp_vol_list = [gop.get_options_price_from_db(ticker=options_frame['ticker'].iloc[x], settle_date=settle_price_date, strike=options_frame['strike_price'].iloc[x], column_names=['imp_vol'], con=con)['imp_vol'] for x in range(len(options_frame.index))] options_frame['imp_vol'] = [imp_vol_list[x][1] if (np.isnan(imp_vol_list[x][0]) and len(imp_vol_list[x]) > 1) else imp_vol_list[x][0] for x in range(len(options_frame.index))] options_frame['underlying_ticker'] = [omu.get_option_underlying(ticker=x) for x in options_frame['ticker']] options_frame = pd.merge(options_frame, intraday_price_frame, how='left', on='underlying_ticker') options_frame['ticker_head'] = [cmi.get_contract_specs(x)['ticker_head'] for x in options_frame['ticker']] options_frame['exercise_type'] = [cmi.get_option_exercise_type(ticker_head=x) for x in options_frame['ticker_head']] options_frame['strike_price'] = options_frame['strike_price'].astype('float64') options_frame['delta'] = [omu.option_model_wrapper(ticker=options_frame['ticker'].iloc[x], calculation_date=current_date, interest_rate_date=settle_price_date, underlying=options_frame['mid_price'].iloc[x], strike=options_frame['strike_price'].iloc[x], implied_vol=options_frame['imp_vol'].iloc[x], option_type=options_frame['option_type'].iloc[x], exercise_type=options_frame['exercise_type'].iloc[x], con=con)['delta'] for x in range(len(options_frame.index))] options_frame['total_delta'] = options_frame['qty']*options_frame['delta'] grouped = options_frame.groupby('underlying_ticker') net_position = pd.DataFrame() net_position['underlying_ticker'] = (grouped['underlying_ticker'].first()).values net_position['hedge_price'] = (grouped['mid_price'].first()).values net_position['option_delta'] = (grouped['total_delta'].sum()).values net_position['option_delta'] = net_position['option_delta'].round(2) if futures_frame.empty: net_position['total_delta'] = net_position['option_delta'] else: futures_frame.rename(columns={'ticker': 'underlying_ticker', 'qty': 'underlying_delta'},inplace=True) futures_frame = futures_frame[['underlying_ticker', 'underlying_delta']] isinOptions = futures_frame['underlying_ticker'].isin(net_position['underlying_ticker']) futures_frame_w_options = futures_frame[isinOptions] futures_frame_wo_options = futures_frame[~isinOptions] if futures_frame_w_options.empty: net_position['underlying_delta'] = 0 net_position['total_delta'] = net_position['option_delta'] else: net_position = pd.merge(net_position, futures_frame_w_options, how='outer', on='underlying_ticker') net_position['total_delta'] = net_position['option_delta']+net_position['underlying_delta'] if not futures_frame_wo_options.empty: net_position_futures = pd.merge(futures_frame_wo_options, intraday_price_frame, how='left', on='underlying_ticker') net_position_futures['hedge_price'] = net_position_futures['mid_price'] net_position_futures['option_delta'] = 0 net_position_futures['total_delta'] = net_position_futures['underlying_delta'] net_position = pd.concat([net_position,net_position_futures[['underlying_ticker','hedge_price','option_delta','underlying_delta','total_delta']]]) net_position['hedge'] = -net_position['total_delta'] if 'con' not in kwargs.keys(): con.close() return net_position
def calc_intraday_structure_pnl_from_prices(**kwargs): if 'as_of_date' in kwargs.keys(): as_of_date = kwargs['as_of_date'] else: as_of_date = exp.doubledate_shift_bus_days() con = msu.get_my_sql_connection(**kwargs) structure_type = kwargs['structure_type'] structure_price = kwargs['structure_price'] ticker_list = kwargs['ticker_list'] strike_list = kwargs['strike_list'] underlying_price_list = kwargs['underlying_price_list'] qty = kwargs['qty'] if structure_type == 'straddle_spread': option_frame = pd.DataFrame.from_dict({ 'ticker': [ticker_list[0], ticker_list[0], ticker_list[1], ticker_list[1]], 'option_type': ['C', 'P', 'C', 'P'], 'strike_price': [strike_list[0], strike_list[0], strike_list[1], strike_list[1]], 'qty': [-1, -1, 1, 1] }) elif structure_type == 'straddle': option_frame = pd.DataFrame.from_dict({ 'ticker': [ticker_list[0], ticker_list[0]], 'option_type': ['C', 'P'], 'strike_price': [strike_list[0], strike_list[0]], 'qty': [1, 1] }) option_price_output = [ gop.get_options_price_from_db( ticker=option_frame['ticker'].iloc[x], strike=option_frame['strike_price'].iloc[x], option_type=option_frame['option_type'].iloc[x], con=con, settle_date=as_of_date, column_names=['close_price', 'delta']) for x in range(len(option_frame.index)) ] option_frame['delta'] = [ option_price_output[x]['delta'][0] for x in range(len(option_frame.index)) ] option_frame['close_price'] = [ option_price_output[x]['close_price'][0] for x in range(len(option_frame.index)) ] option_frame['PQ'] = option_frame['close_price'] * option_frame['qty'] option_frame['signed_delta'] = option_frame['delta'] * option_frame['qty'] delta_list = [ option_frame[option_frame['ticker'] == x]['signed_delta'].sum() for x in ticker_list ] ticker_head = cmi.get_contract_specs(ticker_list[0])['ticker_head'] contract_multiplier = cmi.contract_multiplier[ticker_head] structure_price_yesterday = option_frame['PQ'].sum() structure_pnl = qty * (structure_price - structure_price_yesterday) * contract_multiplier underlying_ticker_list = [ oputil.get_option_underlying(ticker=x) for x in ticker_list ] underlying_price_list_yesterday = [ gfp.get_futures_price_preloaded( ticker=x, settle_date=as_of_date)['close_price'].iloc[0] for x in underlying_ticker_list ] delta_pnl = contract_multiplier * sum([ -delta_list[x] * qty * (underlying_price_list[x] - underlying_price_list_yesterday[x]) for x in range(len(delta_list)) ]) return { 'total_pnl': structure_pnl + delta_pnl, 'structure_pnl': structure_pnl, 'delta_pnl': delta_pnl, 'structure_price_yesterday': structure_price_yesterday }
def get_intraday_data_contract_frame(**kwargs): current_date = cu.get_doubledate() con = msu.get_my_sql_connection(**kwargs) strategy_frame = tas.get_open_strategies(as_of_date=current_date, con=con) strategy_class_list = [ sc.convert_from_string_to_dictionary( string_input=strategy_frame['description_string'][x]) ['strategy_class'] for x in range(len(strategy_frame.index)) ] hedge_indx = [ x in ['vcs', 'scv', 'optionInventory'] for x in strategy_class_list ] hedge_frame = strategy_frame[hedge_indx] options_frame_list = [] for i in range(len(hedge_frame.index)): position_frame = tas.get_net_position_4strategy_alias( alias=hedge_frame['alias'].iloc[i], as_of_date=current_date, con=con) options_frame = position_frame[position_frame['instrument'] == 'O'] options_frame['underlying_ticker'] = [ omu.get_option_underlying(ticker=x) for x in options_frame['ticker'] ] options_frame_list.append(options_frame) merged_frame = pd.concat(options_frame_list) underlying_ticker_list = list(merged_frame['underlying_ticker'].unique()) delta_alias = get_delta_strategy_alias(con=con) delta_position_frame = tas.get_net_position_4strategy_alias( alias=delta_alias, as_of_date=current_date, con=con) contract_frame = pd.DataFrame() contract_frame['ticker'] = list( set(delta_position_frame['ticker'].unique()) | set(underlying_ticker_list)) contract_specs_output_list = [ cmi.get_contract_specs(x) for x in contract_frame['ticker'] ] contract_frame['ticker_head'] = [ x['ticker_head'] for x in contract_specs_output_list ] contract_frame['ticker_class'] = [ x['ticker_class'] for x in contract_specs_output_list ] contract_frame['cont_indx'] = [ x['cont_indx'] for x in contract_specs_output_list ] contract_frame['is_spread_q'] = False contract_frame.sort_values(['ticker_head', 'cont_indx'], ascending=[True, True], inplace=True) contract_frame.reset_index(drop=True, inplace=True) non_flat_frame = contract_frame[~contract_frame['ticker_class']. isin(flat_curve_ticker_class_list)] unique_ticker_head_list = non_flat_frame['ticker_head'].unique() for i in range(len(unique_ticker_head_list)): ticker_head_frame = non_flat_frame[non_flat_frame['ticker_head'] == unique_ticker_head_list[i]] if len(ticker_head_frame.index) > 1: for j in range(len(ticker_head_frame.index) - 1): for k in range(j + 1, len(ticker_head_frame.index)): spread_ticker = ticker_head_frame['ticker'].iloc[ j] + '-' + ticker_head_frame['ticker'].iloc[k] contract_frame.loc[len(contract_frame.index)] = [ spread_ticker, ticker_head_frame['ticker_head'].iloc[j], ticker_head_frame['ticker_class'].iloc[j], ticker_head_frame['cont_indx'].iloc[j], True ] if 'con' not in kwargs.keys(): con.close() return contract_frame
def get_hedge_4strategy(**kwargs): con = msu.get_my_sql_connection(**kwargs) current_date = cu.get_doubledate() settle_price_date = exp.doubledate_shift_bus_days(double_date=current_date, shift_in_days=1) position_frame = tas.get_net_position_4strategy_alias( alias=kwargs['alias'], as_of_date=current_date, con=con) if 'intraday_price_frame' in kwargs.keys(): intraday_price_frame = kwargs['intraday_price_frame'] else: intraday_price_frame = gip.get_cme_direct_prices() intraday_price_frame.rename(columns={'ticker': 'underlying_ticker'}, inplace=True) intraday_price_frame['ticker_head'] = [ cmi.get_contract_specs(x)['ticker_head'] for x in intraday_price_frame['underlying_ticker'] ] intraday_price_frame['mid_price'] = ( intraday_price_frame['bid_price'] + intraday_price_frame['ask_price']) / 2 intraday_price_frame['mid_price'] = [ tfl.convert_trade_price_from_cme_direct( ticker_head=intraday_price_frame['ticker_head'].iloc[x], price=intraday_price_frame['mid_price'].iloc[x]) for x in range(len(intraday_price_frame.index)) ] options_frame = position_frame[position_frame['instrument'] == 'O'] futures_frame = position_frame[position_frame['instrument'] == 'F'] if options_frame.empty: futures_frame.rename(columns={ 'ticker': 'underlying_ticker', 'qty': 'underlying_delta' }, inplace=True) futures_frame = futures_frame[[ 'underlying_ticker', 'underlying_delta' ]] net_position = pd.merge(futures_frame, intraday_price_frame, how='left', on='underlying_ticker') net_position['hedge_price'] = net_position['mid_price'] net_position['hedge'] = -net_position['underlying_delta'] return net_position imp_vol_list = [ gop.get_options_price_from_db( ticker=options_frame['ticker'].iloc[x], settle_date=settle_price_date, strike=options_frame['strike_price'].iloc[x], column_names=['imp_vol'], con=con)['imp_vol'] for x in range(len(options_frame.index)) ] options_frame['imp_vol'] = [ imp_vol_list[x][1] if (np.isnan(imp_vol_list[x][0]) and len(imp_vol_list[x]) > 1) else imp_vol_list[x][0] for x in range(len(options_frame.index)) ] options_frame['underlying_ticker'] = [ omu.get_option_underlying(ticker=x) for x in options_frame['ticker'] ] #print(intraday_price_frame) options_frame = pd.merge(options_frame, intraday_price_frame, how='left', on='underlying_ticker') options_frame['ticker_head'] = [ cmi.get_contract_specs(x)['ticker_head'] for x in options_frame['ticker'] ] options_frame['exercise_type'] = [ cmi.get_option_exercise_type(ticker_head=x) for x in options_frame['ticker_head'] ] options_frame['strike_price'] = options_frame['strike_price'].astype( 'float64') options_frame['delta'] = [ omu.option_model_wrapper( ticker=options_frame['ticker'].iloc[x], calculation_date=current_date, interest_rate_date=settle_price_date, underlying=options_frame['mid_price'].iloc[x], strike=options_frame['strike_price'].iloc[x], implied_vol=options_frame['imp_vol'].iloc[x], option_type=options_frame['option_type'].iloc[x], exercise_type=options_frame['exercise_type'].iloc[x], con=con)['delta'] for x in range(len(options_frame.index)) ] options_frame[ 'total_delta'] = options_frame['qty'] * options_frame['delta'] grouped = options_frame.groupby('underlying_ticker') net_position = pd.DataFrame() net_position['underlying_ticker'] = ( grouped['underlying_ticker'].first()).values net_position['hedge_price'] = (grouped['mid_price'].first()).values net_position['option_delta'] = (grouped['total_delta'].sum()).values net_position['option_delta'] = net_position['option_delta'].round(2) if futures_frame.empty: net_position['total_delta'] = net_position['option_delta'] else: futures_frame.rename(columns={ 'ticker': 'underlying_ticker', 'qty': 'underlying_delta' }, inplace=True) futures_frame = futures_frame[[ 'underlying_ticker', 'underlying_delta' ]] isinOptions = futures_frame['underlying_ticker'].isin( net_position['underlying_ticker']) futures_frame_w_options = futures_frame[isinOptions] futures_frame_wo_options = futures_frame[~isinOptions] if futures_frame_w_options.empty: net_position['underlying_delta'] = 0 net_position['total_delta'] = net_position['option_delta'] else: net_position = pd.merge(net_position, futures_frame_w_options, how='outer', on='underlying_ticker') net_position[['underlying_delta' ]] = net_position[['underlying_delta' ]].fillna(value=0, inplace=False) net_position['total_delta'] = net_position[ 'option_delta'] + net_position['underlying_delta'] if not futures_frame_wo_options.empty: net_position_futures = pd.merge(futures_frame_wo_options, intraday_price_frame, how='left', on='underlying_ticker') net_position_futures['hedge_price'] = net_position_futures[ 'mid_price'] net_position_futures['option_delta'] = 0 net_position_futures['total_delta'] = net_position_futures[ 'underlying_delta'] net_position = pd.concat([ net_position, net_position_futures[[ 'underlying_ticker', 'hedge_price', 'option_delta', 'underlying_delta', 'total_delta' ]] ]) net_position['hedge'] = -net_position['total_delta'] if 'con' not in kwargs.keys(): con.close() return net_position