def test_option_models(**kwargs):

    test_data_dir = dn.get_directory_name(ext='option_model_test_data')

    engine_name = kwargs['engine_name']

    if os.path.isfile(test_data_dir + '/' + engine_name + '.pkl'):
        data_frame_test = pd.read_pickle(test_data_dir + '/' + engine_name + '.pkl')
        return data_frame_test

    data_frame_test = generate_test_cases_from_aligned_option_data()
    data_frame_test = data_frame_test[data_frame_test['strike'].notnull()]

    if 'num_cases' in kwargs.keys():
        data_frame_test = data_frame_test.iloc[0:kwargs['num_cases']]

    model_wrapper_output = []

    #return data_frame_test['settleDates'].iloc[no]

    for no in range(len(data_frame_test.index)):

        #print('true vol: ' + str(data_frame_test['impVol'].iloc[no]))
        #print('int rate: ' + str(data_frame_test['rate2OptExp'].iloc[no]))
        print(no)

        model_wrapper_output.append(omu.option_model_wrapper(ticker=data_frame_test['ticker'].iloc[no],
                                                        calculation_date=int(data_frame_test['settleDates'].iloc[no]),
                                                        underlying=data_frame_test['underlying'].iloc[no],
                                                        strike = data_frame_test['strike'].iloc[no],
                                                        option_price=data_frame_test['theoValue'].iloc[no],
                                                        exercise_type = data_frame_test['exercise_type'].iloc[no],
                                                        option_type=data_frame_test['option_type'].iloc[no],
                                                        engine_name=engine_name))

    #return model_wrapper_output

    data_frame_test['vol_deviation'] = [100*(model_wrapper_output[no]['implied_vol']-data_frame_test['impVol'].iloc[no])/data_frame_test['impVol'].iloc[no] for no in range(len(data_frame_test.index))]
    data_frame_test['dollar_gamma_deviation'] = [100*(model_wrapper_output[no]['dollar_gamma']-data_frame_test['dollarGamma'].iloc[no])/data_frame_test['dollarGamma'].iloc[no] for no in range(len(data_frame_test.index))]
    data_frame_test['gamma_deviation'] = [100*(model_wrapper_output[no]['gamma']-data_frame_test['gamma'].iloc[no])/data_frame_test['gamma'].iloc[no] for no in range(len(data_frame_test.index))]
    data_frame_test['delta_deviation'] = [100*(model_wrapper_output[no]['delta']-data_frame_test['delta'].iloc[no]) for no in range(len(data_frame_test.index))]
    data_frame_test['dollar_vega_deviation'] = [100*(model_wrapper_output[no]['dollar_vega']-data_frame_test['dollarVega'].iloc[no])/data_frame_test['dollarVega'].iloc[no] for no in range(len(data_frame_test.index))]
    data_frame_test['dollar_theta_deviation'] = [100*(model_wrapper_output[no]['dollar_theta']-data_frame_test['dollarTheta'].iloc[no])/data_frame_test['dollarTheta'].iloc[no] for no in range(len(data_frame_test.index))]
    data_frame_test['interest_rate_deviation'] = [100*(model_wrapper_output[no]['interest_rate']-data_frame_test['rate2OptExp'].iloc[no]) for no in range(len(data_frame_test.index))]
    data_frame_test['cal_dte_deviation'] = [model_wrapper_output[no]['cal_dte']-data_frame_test['calDTE'].iloc[no] for no in range(len(data_frame_test.index))]

    data_frame_test.to_pickle(test_data_dir + '/' + engine_name + '.pkl')
    return data_frame_test
def generate_csv_file(**kwargs):

    output_dir = dn.get_directory_name(ext='test_data')
    engine_name = kwargs['engine_name']

    data_frame_test = generate_test_cases_from_aligned_option_data()
    data_frame_test = data_frame_test[data_frame_test['strike'].notnull()]

    if 'num_cases' in kwargs.keys():
        data_frame_test = data_frame_test.iloc[0:kwargs['num_cases']]

    model_wrapper_output = []
    for no in range(len(data_frame_test.index)):

        #print('true vol: ' + str(data_frame_test['impVol'].iloc[no]))
        #print('int rate: ' + str(data_frame_test['rate2OptExp'].iloc[no]))
        print(no)

        model_wrapper_output.append(omu.option_model_wrapper(ticker=data_frame_test['ticker'].iloc[no],
                                                        calculation_date=int(data_frame_test['settleDates'].iloc[no]),
                                                        underlying=data_frame_test['underlying'].iloc[no],
                                                        strike = data_frame_test['strike'].iloc[no],
                                                        option_price=data_frame_test['theoValue'].iloc[no],
                                                        exercise_type = data_frame_test['exercise_type'].iloc[no],
                                                        option_type=data_frame_test['option_type'].iloc[no],
                                                        engine_name=engine_name))

    #return model_wrapper_output

    data_frame_test['impVol'] = [model_wrapper_output[no]['implied_vol'] for no in range(len(data_frame_test.index))]
    data_frame_test['dollarGamma'] = [model_wrapper_output[no]['dollar_gamma'] for no in range(len(data_frame_test.index))]
    data_frame_test['gamma'] = [model_wrapper_output[no]['gamma'] for no in range(len(data_frame_test.index))]
    data_frame_test['delta'] = [model_wrapper_output[no]['delta'] for no in range(len(data_frame_test.index))]
    data_frame_test['dollarVega'] = [model_wrapper_output[no]['dollar_vega']for no in range(len(data_frame_test.index))]
    data_frame_test['dollarTheta'] = [model_wrapper_output[no]['dollar_theta'] for no in range(len(data_frame_test.index))]
    data_frame_test['rate2OptExp'] = [model_wrapper_output[no]['interest_rate'] for no in range(len(data_frame_test.index))]
    data_frame_test['calDTE'] = [model_wrapper_output[no]['cal_dte'] for no in range(len(data_frame_test.index))]

    data_frame_test = data_frame_test[data_frame_test['impVol'].notnull()]
    data_frame_test = data_frame_test[~data_frame_test['tickerHead'].isin(['ED','E0','E1','E2','E3','E4','E5'])]

    data_frame_test = data_frame_test[['settleDates','ticker','option_type','strike','underlying','theoValue',
                                       'impVol','delta','dollarVega','dollarTheta','dollarGamma','rate2OptExp']]

    data_frame_test.reset_index(drop=True, inplace=True)

    writer = pd.ExcelWriter(output_dir + '/' + 'option_model_test' + '.xlsx', engine='xlsxwriter')
    data_frame_test.to_excel(writer, sheet_name='all')
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
Пример #4
0
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