def get_strategy_class_historical_pnls(**kwargs):

    con = msu.get_my_sql_connection(**kwargs)

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()

    strategy_frame = ts.select_strategies(con=con,open_date_to=as_of_date)

    strategy_frame['strategy_class'] = [sc.convert_from_string_to_dictionary(string_input=strategy_frame['description_string'][x])['strategy_class']
                           for x in range(len(strategy_frame.index))]

    unique_strategy_class_list = strategy_frame['strategy_class'].unique()
    time_series_list = [None]*len(unique_strategy_class_list)

    for i in range(len(unique_strategy_class_list)):
        strategy_frame_selected = strategy_frame[strategy_frame['strategy_class'] == unique_strategy_class_list[i]]
        pnl_out = [tpnl.get_strategy_pnl(alias=x,as_of_date=as_of_date,con=con)['pnl_frame'][['settle_date','total_pnl']] for x in strategy_frame_selected['alias']]
        [x.set_index('settle_date',drop=True, inplace=True) for x in pnl_out]
        time_series_list[i] = pd.concat(pnl_out,axis=1).fillna(0).sum(axis=1)

    if 'con' not in kwargs.keys():
        con.close()

    merged_pnl = pd.concat(time_series_list,axis=1,keys=unique_strategy_class_list).fillna(0)
    merged_pnl['total'] = merged_pnl.sum(axis=1)

    output_dir = dn.get_directory_name(ext='daily')
    writer = pd.ExcelWriter(output_dir + '/historical_performance_' + str(as_of_date) + '.xlsx', engine='xlsxwriter')
    merged_pnl.to_excel(writer, sheet_name='timeSeries')
    writer.save()

    return merged_pnl
Пример #2
0
def get_delta_strategy_alias(**kwargs):

    # inputs:
    # as_of_date

    strategy_frame = tas.get_open_strategies(**kwargs)
    strategy_frame.sort_values('open_date', ascending=True, inplace=True)

    strategy_class_list = [
        sc.convert_from_string_to_dictionary(
            string_input=strategy_frame['description_string'].iloc[x])
        ['strategy_class'] for x in range(len(strategy_frame.index))
    ]

    if ('delta' not in strategy_class_list):
        datetime_now = dt.datetime.now()
        delta_strategy_alias = 'delta_' + datetime_now.strftime('%b%y')
        generate_strategy_output = tas.generate_db_strategy_from_alias(
            alias=delta_strategy_alias,
            description_string='strategy_class=delta')
        delta_alias_final = generate_strategy_output['alias']
    else:
        strategy_frame['class'] = strategy_class_list
        delta_frame = strategy_frame[strategy_frame['class'] == 'delta']
        delta_alias_final = delta_frame['alias'].iloc[-1]

    return delta_alias_final
Пример #3
0
def get_filtered_open_strategies(**kwargs):


    open_strategy_frame = get_open_strategies(**kwargs)
    open_strategy_frame['strategy_class'] = [conv.convert_from_string_to_dictionary(string_input=x)['strategy_class'] for
                                             x in open_strategy_frame['description_string']]

    return open_strategy_frame[open_strategy_frame['strategy_class'].isin(kwargs['strategy_class_list'])]
Пример #4
0
def generate_spread_carry_followup_report(**kwargs):

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    con = msu.get_my_sql_connection(**kwargs)

    ta_output_dir = dn.get_dated_directory_extension(folder_date=as_of_date,
                                                     ext='ta')

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx',
                                engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))
    ]

    spread_carry_indx = [x == 'spread_carry' for x in strategy_class_list]
    spread_carry_frame = strategy_frame[spread_carry_indx]

    if spread_carry_frame.empty:
        return writer

    results = [
        sf.get_results_4strategy(
            alias=spread_carry_frame['alias'].iloc[x],
            strategy_info_output=spread_carry_frame.iloc[x],
            con=con) for x in range(len(spread_carry_frame.index))
    ]

    results_frame_list = [
        results[x]['results_frame'] for x in range(len(results))
        if results[x]['success']
    ]
    spread_carry_followup_frame = pd.concat(results_frame_list)

    spread_carry_followup_frame.to_excel(writer, sheet_name='sc')
    worksheet_sc = writer.sheets['sc']
    worksheet_sc.freeze_panes(1, 0)

    worksheet_sc.autofilter(0, 0, len(spread_carry_followup_frame.index),
                            len(spread_carry_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    return writer
Пример #5
0
def get_strategy_class_historical_pnls(**kwargs):

    con = msu.get_my_sql_connection(**kwargs)

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()

    strategy_frame = ts.select_strategies(con=con, open_date_to=as_of_date)

    strategy_frame['strategy_class'] = [
        sc.convert_from_string_to_dictionary(
            string_input=strategy_frame['description_string'][x])
        ['strategy_class'] for x in range(len(strategy_frame.index))
    ]

    unique_strategy_class_list = strategy_frame['strategy_class'].unique()
    time_series_list = [None] * len(unique_strategy_class_list)

    for i in range(len(unique_strategy_class_list)):
        strategy_frame_selected = strategy_frame[
            strategy_frame['strategy_class'] == unique_strategy_class_list[i]]
        pnl_out = [
            tpnl.get_strategy_pnl(
                alias=x, as_of_date=as_of_date,
                con=con)['pnl_frame'][['settle_date', 'total_pnl']]
            for x in strategy_frame_selected['alias']
        ]
        [x.set_index('settle_date', drop=True, inplace=True) for x in pnl_out]
        time_series_list[i] = pd.concat(pnl_out, axis=1).fillna(0).sum(axis=1)

    if 'con' not in kwargs.keys():
        con.close()

    merged_pnl = pd.concat(time_series_list,
                           axis=1,
                           keys=unique_strategy_class_list).fillna(0)
    merged_pnl['total'] = merged_pnl.sum(axis=1)

    output_dir = dn.get_directory_name(ext='daily')
    writer = pd.ExcelWriter(output_dir + '/historical_performance_' +
                            str(as_of_date) + '.xlsx',
                            engine='xlsxwriter')
    merged_pnl.to_excel(writer, sheet_name='timeSeries')
    writer.save()

    return merged_pnl
def generate_spread_carry_followup_report(**kwargs):

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    con = msu.get_my_sql_connection(**kwargs)

    ta_output_dir = dn.get_dated_directory_extension(folder_date=as_of_date, ext='ta')

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx', engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))]

    spread_carry_indx = [x == 'spread_carry' for x in strategy_class_list]
    spread_carry_frame = strategy_frame[spread_carry_indx]

    results = [sf.get_results_4strategy(alias=spread_carry_frame['alias'].iloc[x],
                                        strategy_info_output=spread_carry_frame.iloc[x],
                                        con=con)
               for x in range(len(spread_carry_frame.index))]

    results_frame_list = [results[x]['results_frame'] for x in range(len(results)) if results[x]['success']]
    spread_carry_followup_frame = pd.concat(results_frame_list)

    spread_carry_followup_frame.to_excel(writer, sheet_name='sc')
    worksheet_sc = writer.sheets['sc']
    worksheet_sc.freeze_panes(1, 0)

    worksheet_sc.autofilter(0, 0, len(spread_carry_followup_frame.index),
                              len(spread_carry_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    return writer
def strategy_hedge_report(**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]

    #hedge_frame = hedge_frame[hedge_frame['alias'] != 'LNZ16V16VCS']
    [hedge_strategy_against_delta(alias=x, con=con) for x in hedge_frame['alias']]

    if 'con' not in kwargs.keys():
        con.close()
Пример #8
0
def strategy_hedge_report(**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]

    #hedge_frame = hedge_frame[(hedge_frame['alias'] == 'BPX2018_short_scv')]
    #hedge_frame = hedge_frame[(hedge_frame['alias'] != 'CLZ17H18VCS')]

    if 'intraday_price_frame' in kwargs.keys():
        [
            hedge_strategy_against_delta(
                alias=x,
                intraday_price_frame=kwargs['intraday_price_frame'],
                delta_alias=kwargs['delta_alias'],
                con=con) for x in hedge_frame['alias']
        ]
    else:
        [
            hedge_strategy_against_delta(alias=x,
                                         delta_alias=kwargs['delta_alias'],
                                         con=con) for x in hedge_frame['alias']
        ]

    if 'con' not in kwargs.keys():
        con.close()
def generate_futures_butterfly_followup_report(**kwargs):

    con = msu.get_my_sql_connection(**kwargs)

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        ta_output_dir = dn.get_dated_directory_extension(folder_date=as_of_date, ext='ta')
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx', engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))]

    futures_butterfly_indx = [x == 'futures_butterfly' for x in strategy_class_list]

    futures_butterfly_frame = strategy_frame[futures_butterfly_indx]

    results = [sf.get_results_4strategy(alias=futures_butterfly_frame['alias'].iloc[x],
                                        strategy_info_output=futures_butterfly_frame.iloc[x])
               for x in range(len(futures_butterfly_frame.index))]

    butterfly_followup_frame = pd.DataFrame(results)
    butterfly_followup_frame['alias'] = futures_butterfly_frame['alias'].values

    pnl_frame = pm.get_daily_pnl_snapshot(as_of_date=as_of_date, con=con)
    risk_output = hr.get_historical_risk_4open_strategies(as_of_date=as_of_date, con=con)

    merged_frame1 = pd.merge(butterfly_followup_frame,pnl_frame, how='left', on='alias')
    merged_frame2 = pd.merge(merged_frame1, risk_output['strategy_risk_frame'], how='left', on='alias')

    butterfly_followup_frame = merged_frame2[['alias', 'ticker_head', 'holding_tr_dte', 'short_tr_dte',
                                                         'z1_initial', 'z1', 'QF_initial', 'QF',
                                                         'total_pnl', 'downside','recommendation']]

    butterfly_followup_frame.rename(columns={'alias': 'Alias', 'ticker_head': 'TickerHead',
                                             'holding_tr_dte': 'HoldingTrDte', 'short_tr_dte': 'ShortTrDte',
                                             'z1_initial': 'Z1Initial', 'z1': 'Z1',
                                             'QF_initial': 'QFInitial','total_pnl': 'TotalPnl',
                                             'downside': 'Downside','recommendation':'Recommendation'}, inplace=True)

    butterfly_followup_frame.sort('QF', ascending=False,inplace=True)

    butterfly_followup_frame['Z1'] = butterfly_followup_frame['Z1'].round(2)

    butterfly_followup_frame.to_excel(writer, sheet_name='butterflies')
    worksheet_butterflies = writer.sheets['butterflies']

    worksheet_butterflies.set_column('B:B', 26)
    worksheet_butterflies.freeze_panes(1, 0)

    worksheet_butterflies.autofilter(0, 0, len(butterfly_followup_frame.index),
                              len(butterfly_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    return writer
def generate_vcs_followup_report(**kwargs):

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    ta_output_dir = dn.get_dated_directory_extension(folder_date=as_of_date, ext='ta')

    con = msu.get_my_sql_connection(**kwargs)

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx', engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))]

    vcs_indx = [x == 'vcs' for x in strategy_class_list]
    vcs_frame = strategy_frame[vcs_indx]

    results = [sf.get_results_4strategy(alias=vcs_frame['alias'].iloc[x],
                                        strategy_info_output=vcs_frame.iloc[x])
               for x in range(len(vcs_frame.index))]

    vcs_followup_frame = pd.DataFrame(results)
    vcs_followup_frame['alias'] = vcs_frame['alias'].values

    pnl_frame = pm.get_daily_pnl_snapshot(**kwargs)
    merged_frame1 = pd.merge(vcs_followup_frame,pnl_frame, how='left', on='alias')

    vcs_followup_frame = merged_frame1[['alias', 'last_adjustment_days_ago','min_tr_dte', 'long_short_ratio',
                   'net_oev', 'net_theta', 'long_oev', 'short_oev', 'favQMove', 'total_pnl','recommendation']]

    vcs_followup_frame['long_short_ratio'] = vcs_followup_frame['long_short_ratio'].round()
    vcs_followup_frame['net_oev'] = vcs_followup_frame['net_oev'].round(1)
    vcs_followup_frame['long_oev'] = vcs_followup_frame['long_oev'].round(1)
    vcs_followup_frame['short_oev'] = vcs_followup_frame['short_oev'].round(1)
    vcs_followup_frame['net_theta'] = vcs_followup_frame['net_theta'].round(1)

    vcs_followup_frame.sort('total_pnl', ascending=False, inplace=True)
    vcs_followup_frame.reset_index(drop=True,inplace=True)
    vcs_followup_frame.loc[len(vcs_followup_frame.index)] = ['TOTAL', None, None, None, None, vcs_followup_frame['net_theta'].sum(),
                                                             None, None, None, vcs_followup_frame['total_pnl'].sum(), None]

    vcs_followup_frame.to_excel(writer, sheet_name='vcs')
    worksheet_vcs = writer.sheets['vcs']
    worksheet_vcs.set_column('B:B', 18)
    worksheet_vcs.freeze_panes(1, 0)

    worksheet_vcs.autofilter(0, 0, len(vcs_followup_frame.index),
                              len(vcs_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    writer.save()
Пример #11
0
def generate_ocs_followup_report(**kwargs):

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    broker = kwargs['broker']

    ta_output_dir = dn.get_dated_directory_extension(folder_date=as_of_date,
                                                     ext='ta')

    con = msu.get_my_sql_connection(**kwargs)

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx',
                                engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))
    ]

    ocs_indx = [x == 'ocs' for x in strategy_class_list]
    ocs_frame = strategy_frame[ocs_indx]

    if ocs_frame.empty:
        writer.save()
        return

    results = [
        sf.get_results_4strategy(alias=ocs_frame['alias'].iloc[x],
                                 strategy_info_output=ocs_frame.iloc[x],
                                 con=con,
                                 broker=broker,
                                 date_to=as_of_date)
        for x in range(len(ocs_frame.index))
    ]

    ocs_followup_frame = pd.DataFrame(results)
    ocs_followup_frame['alias'] = ocs_frame['alias'].values

    kwargs['name'] = 'final'
    pnl_frame = pm.get_daily_pnl_snapshot(**kwargs)
    merged_frame1 = pd.merge(ocs_followup_frame,
                             pnl_frame,
                             how='left',
                             on='alias')
    ocs_followup_frame = merged_frame1[[
        'alias', 'dollar_noise', 'time_held', 'daily_pnl', 'total_pnl', 'notes'
    ]]
    ocs_followup_frame.reset_index(drop=True, inplace=True)
    ocs_followup_frame.loc[max(ocs_followup_frame.index) + 1] = [
        'TOTAL', np.nan, np.nan, ocs_followup_frame['daily_pnl'].sum(),
        ocs_followup_frame['total_pnl'].sum(), ''
    ]

    date_from30 = cu.doubledate_shift(as_of_date, 30)
    history_frame = ts.select_strategies(close_date_from=date_from30,
                                         close_date_to=as_of_date,
                                         con=con)
    strategy_class_list = [
        sc.convert_from_string_to_dictionary(
            string_input=history_frame['description_string'][x])
        ['strategy_class'] for x in range(len(history_frame.index))
    ]

    ocs_indx = [x == 'ocs' for x in strategy_class_list]

    ocs_history_frame = history_frame[ocs_indx]
    pnl_past_month = ocs_history_frame['pnl'].sum()

    as_of_datetime = cu.convert_doubledate_2datetime(as_of_date)
    date_from7 = as_of_datetime + dt.timedelta(days=-7)
    ocs_short_history_frame = ocs_history_frame[
        ocs_history_frame['close_date'] >= date_from7]
    pnl_past_week = ocs_short_history_frame['pnl'].sum()

    ocs_followup_frame.loc[max(ocs_followup_frame.index) + 1] = [
        'WEEKLY PERFORMANCE', np.nan, np.nan, np.nan, pnl_past_week, ''
    ]
    ocs_followup_frame.loc[max(ocs_followup_frame.index) + 1] = [
        'MONTHLY PERFORMANCE', np.nan, np.nan, np.nan, pnl_past_month, ''
    ]

    ocs_followup_frame['total_pnl'] = ocs_followup_frame['total_pnl'].astype(
        int)

    ocs_followup_frame.to_excel(writer, sheet_name='ocs')
    worksheet_ocs = writer.sheets['ocs']
    worksheet_ocs.freeze_panes(1, 0)
    worksheet_ocs.set_column('B:B', 26)

    worksheet_ocs.autofilter(0, 0, len(ocs_followup_frame.index),
                             len(ocs_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    writer.save()
Пример #12
0
def generate_vcs_followup_report(**kwargs):

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    ta_output_dir = dn.get_dated_directory_extension(folder_date=as_of_date,
                                                     ext='ta')

    con = msu.get_my_sql_connection(**kwargs)

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx',
                                engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))
    ]

    vcs_indx = [x == 'vcs' for x in strategy_class_list]
    vcs_frame = strategy_frame[vcs_indx]

    if len(vcs_frame.index) == 0:
        return writer

    results = [
        sf.get_results_4strategy(alias=vcs_frame['alias'].iloc[x],
                                 strategy_info_output=vcs_frame.iloc[x])
        for x in range(len(vcs_frame.index))
    ]

    vcs_followup_frame = pd.DataFrame(results)
    vcs_followup_frame['alias'] = vcs_frame['alias'].values

    kwargs['name'] = 'final'
    pnl_frame = pm.get_daily_pnl_snapshot(**kwargs)
    merged_frame1 = pd.merge(vcs_followup_frame,
                             pnl_frame,
                             how='left',
                             on='alias')

    vcs_followup_frame = merged_frame1[[
        'alias', 'last_adjustment_days_ago', 'min_tr_dte', 'long_short_ratio',
        'net_oev', 'net_theta', 'long_oev', 'short_oev', 'favQMove',
        'total_pnl', 'recommendation'
    ]]

    vcs_followup_frame['long_short_ratio'] = vcs_followup_frame[
        'long_short_ratio'].round()
    vcs_followup_frame['net_oev'] = vcs_followup_frame['net_oev'].round(1)
    vcs_followup_frame['long_oev'] = vcs_followup_frame['long_oev'].round(1)
    vcs_followup_frame['short_oev'] = vcs_followup_frame['short_oev'].round(1)
    vcs_followup_frame['net_theta'] = vcs_followup_frame['net_theta'].round(1)

    vcs_followup_frame.sort_values('total_pnl', ascending=False, inplace=True)
    vcs_followup_frame.reset_index(drop=True, inplace=True)
    vcs_followup_frame.loc[len(vcs_followup_frame.index)] = [
        'TOTAL', None, None, None, None, vcs_followup_frame['net_theta'].sum(),
        None, None, None, vcs_followup_frame['total_pnl'].sum(), None
    ]

    vcs_followup_frame.to_excel(writer, sheet_name='vcs')
    worksheet_vcs = writer.sheets['vcs']
    worksheet_vcs.set_column('B:B', 18)
    worksheet_vcs.freeze_panes(1, 0)

    worksheet_vcs.autofilter(0, 0, len(vcs_followup_frame.index),
                             len(vcs_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    return writer
Пример #13
0
def generate_futures_butterfly_followup_report(**kwargs):

    con = msu.get_my_sql_connection(**kwargs)

    if 'as_of_date' in kwargs.keys():
        as_of_date = kwargs['as_of_date']
    else:
        as_of_date = exp.doubledate_shift_bus_days()
        kwargs['as_of_date'] = as_of_date

    if 'writer' in kwargs.keys():
        writer = kwargs['writer']
    else:
        ta_output_dir = dn.get_dated_directory_extension(
            folder_date=as_of_date, ext='ta')
        writer = pd.ExcelWriter(ta_output_dir + '/followup.xlsx',
                                engine='xlsxwriter')

    strategy_frame = ts.get_open_strategies(**kwargs)

    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))
    ]

    futures_butterfly_indx = [
        x == 'futures_butterfly' for x in strategy_class_list
    ]

    futures_butterfly_frame = strategy_frame[futures_butterfly_indx]

    results = [
        sf.get_results_4strategy(
            alias=futures_butterfly_frame['alias'].iloc[x],
            strategy_info_output=futures_butterfly_frame.iloc[x])
        for x in range(len(futures_butterfly_frame.index))
    ]

    butterfly_followup_frame = pd.DataFrame(results)
    butterfly_followup_frame['alias'] = futures_butterfly_frame['alias'].values

    pnl_frame = pm.get_daily_pnl_snapshot(as_of_date=as_of_date,
                                          con=con,
                                          name='final')
    risk_output = hr.get_historical_risk_4open_strategies(
        as_of_date=as_of_date, con=con)

    merged_frame1 = pd.merge(butterfly_followup_frame,
                             pnl_frame,
                             how='left',
                             on='alias')
    merged_frame2 = pd.merge(merged_frame1,
                             risk_output['strategy_risk_frame'],
                             how='left',
                             on='alias')

    butterfly_followup_frame = merged_frame2[[
        'alias', 'ticker_head', 'holding_tr_dte', 'short_tr_dte', 'z1_initial',
        'z1', 'QF_initial', 'QF', 'total_pnl', 'downside', 'recommendation'
    ]]

    butterfly_followup_frame.rename(columns={
        'alias': 'Alias',
        'ticker_head': 'TickerHead',
        'holding_tr_dte': 'HoldingTrDte',
        'short_tr_dte': 'ShortTrDte',
        'z1_initial': 'Z1Initial',
        'z1': 'Z1',
        'QF_initial': 'QFInitial',
        'total_pnl': 'TotalPnl',
        'downside': 'Downside',
        'recommendation': 'Recommendation'
    },
                                    inplace=True)

    butterfly_followup_frame.sort_values('QF', ascending=False, inplace=True)

    butterfly_followup_frame['Z1'] = butterfly_followup_frame['Z1'].round(2)

    butterfly_followup_frame.to_excel(writer, sheet_name='butterflies')
    worksheet_butterflies = writer.sheets['butterflies']

    worksheet_butterflies.set_column('B:B', 26)
    worksheet_butterflies.freeze_panes(1, 0)

    worksheet_butterflies.autofilter(0, 0, len(butterfly_followup_frame.index),
                                     len(butterfly_followup_frame.columns))

    if 'con' not in kwargs.keys():
        con.close()

    return writer
Пример #14
0
def get_results_4strategy(**kwargs):

    signal_input = dict()

    if 'futures_data_dictionary' in kwargs.keys():
        signal_input['futures_data_dictionary'] = kwargs[
            'futures_data_dictionary']

    if 'date_to' in kwargs.keys():
        date_to = kwargs['date_to']
    else:
        date_to = exp.doubledate_shift_bus_days()

    if 'datetime5_years_ago' in kwargs.keys():
        signal_input['datetime5_years_ago'] = kwargs['datetime5_years_ago']

    if 'strategy_info_output' in kwargs.keys():
        strategy_info_output = kwargs['strategy_info_output']
    else:
        strategy_info_output = ts.get_strategy_info_from_alias(**kwargs)

    if 'broker' in kwargs.keys():
        broker = kwargs['broker']
    else:
        broker = 'abn'

    con = msu.get_my_sql_connection(**kwargs)

    strategy_info_dict = sc.convert_from_string_to_dictionary(
        string_input=strategy_info_output['description_string'])

    strategy_class = strategy_info_dict['strategy_class']

    pnl_frame = tpm.get_daily_pnl_snapshot(as_of_date=date_to, broker=broker)
    pnl_frame = pnl_frame[pnl_frame['alias'] == kwargs['alias']]
    strategy_position = ts.get_net_position_4strategy_alias(
        alias=kwargs['alias'], as_of_date=date_to)

    if strategy_class == 'futures_butterfly':

        ticker_head = cmi.get_contract_specs(
            strategy_info_dict['ticker1'])['ticker_head']
        if not strategy_position.empty:
            total_contracts2trade = strategy_position['qty'].abs().sum()
            t_cost = cmi.t_cost[ticker_head]
        QF_initial = float(strategy_info_dict['QF'])
        z1_initial = float(strategy_info_dict['z1'])

        bf_signals_output = fs.get_futures_butterfly_signals(
            ticker_list=[
                strategy_info_dict['ticker1'], strategy_info_dict['ticker2'],
                strategy_info_dict['ticker3']
            ],
            aggregation_method=int(strategy_info_dict['agg']),
            contracts_back=int(strategy_info_dict['cBack']),
            date_to=date_to,
            **signal_input)

        if bf_signals_output['success']:
            aligned_output = bf_signals_output['aligned_output']
            current_data = aligned_output['current_data']
            holding_tr_dte = int(
                strategy_info_dict['trDte1']) - current_data['c1']['tr_dte']
            success_status = True
            QF = bf_signals_output['qf']
            z1 = bf_signals_output['zscore1']
            short_tr_dte = current_data['c1']['tr_dte']
            second_spread_weight = bf_signals_output['second_spread_weight_1']

            if strategy_position.empty:
                recommendation = 'CLOSE'
            elif (z1_initial>0)&(holding_tr_dte > 5) &\
                    (bf_signals_output['qf']<QF_initial-20)&\
                    (pnl_frame['total_pnl'].iloc[0] > 3*t_cost*total_contracts2trade):
                recommendation = 'STOP'
            elif (z1_initial<0)&(holding_tr_dte > 5) &\
                    (bf_signals_output['qf']>QF_initial+20)&\
                    (pnl_frame['total_pnl'].iloc[0] > 3*t_cost*total_contracts2trade):
                recommendation = 'STOP'
            elif (current_data['c1']['tr_dte'] < 35)&\
                (pnl_frame['total_pnl'].iloc[0] > 3*t_cost*total_contracts2trade):
                recommendation = 'STOP'
            elif (current_data['c1']['tr_dte'] < 35)&\
                (pnl_frame['total_pnl'].iloc[0] < 3*t_cost*total_contracts2trade):
                recommendation = 'WINDDOWN'
            else:
                recommendation = 'HOLD'
        else:
            success_status = False
            QF = np.nan
            z1 = np.nan
            short_tr_dte = np.nan
            holding_tr_dte = np.nan
            second_spread_weight = np.nan
            recommendation = 'MISSING DATA'

        result_output = {
            'success': success_status,
            'ticker_head': ticker_head,
            'QF_initial': QF_initial,
            'z1_initial': z1_initial,
            'QF': QF,
            'z1': z1,
            'short_tr_dte': short_tr_dte,
            'holding_tr_dte': holding_tr_dte,
            'second_spread_weight': second_spread_weight,
            'recommendation': recommendation
        }

    elif strategy_class == 'spread_carry':
        trades4_strategy = ts.get_trades_4strategy_alias(**kwargs)
        grouped = trades4_strategy.groupby('ticker')
        net_position = pd.DataFrame()
        net_position['ticker'] = (grouped['ticker'].first()).values
        net_position['qty'] = (grouped['trade_quantity'].sum()).values
        net_position = net_position[net_position['qty'] != 0]

        net_position['ticker_head'] = [
            cmi.get_contract_specs(x)['ticker_head']
            for x in net_position['ticker']
        ]
        price_output = [
            gfp.get_futures_price_preloaded(ticker=x, settle_date=date_to)
            for x in net_position['ticker']
        ]
        net_position['tr_dte'] = [
            np.nan if x.empty else x['tr_dte'].values[0] for x in price_output
        ]

        results_frame = pd.DataFrame()
        unique_tickerhead_list = net_position['ticker_head'].unique()
        results_frame['tickerHead'] = unique_tickerhead_list
        results_frame['ticker1'] = [None] * len(unique_tickerhead_list)
        results_frame['ticker2'] = [None] * len(unique_tickerhead_list)
        results_frame['qty'] = [None] * len(unique_tickerhead_list)
        results_frame['pnl'] = [None] * len(unique_tickerhead_list)
        results_frame['downside'] = [None] * len(unique_tickerhead_list)
        results_frame['indicator'] = [None] * len(unique_tickerhead_list)
        results_frame['timeHeld'] = [None] * len(unique_tickerhead_list)
        results_frame['recommendation'] = [None] * len(unique_tickerhead_list)

        spread_carry_output = osc.generate_spread_carry_sheet_4date(
            report_date=date_to)
        spread_report = spread_carry_output['spread_report']

        pnl_output = tpnl.get_strategy_pnl(**kwargs)
        pnl_per_tickerhead = pnl_output['pnl_per_tickerhead']

        for i in range(len(unique_tickerhead_list)):
            net_position_per_tickerhead = net_position[
                net_position['ticker_head'] == unique_tickerhead_list[i]]
            net_position_per_tickerhead.sort_values('tr_dte',
                                                    ascending=True,
                                                    inplace=True)

            selected_spread = spread_report[
                (spread_report['ticker1'] ==
                 net_position_per_tickerhead['ticker'].values[0])
                & (spread_report['ticker2'] ==
                   net_position_per_tickerhead['ticker'].values[1])]

            results_frame['qty'][i] = net_position_per_tickerhead[
                'qty'].values[0]

            if selected_spread.empty:
                results_frame['ticker1'][i] = net_position_per_tickerhead[
                    'ticker'].values[0]
                results_frame['ticker2'][i] = net_position_per_tickerhead[
                    'ticker'].values[1]
            else:
                results_frame['ticker1'][i] = selected_spread[
                    'ticker1'].values[0]
                results_frame['ticker2'][i] = selected_spread[
                    'ticker2'].values[0]

                selected_trades = trades4_strategy[
                    trades4_strategy['ticker'] ==
                    results_frame['ticker1'].values[i]]

                price_output = gfp.get_futures_price_preloaded(
                    ticker=results_frame['ticker1'].values[i],
                    settle_date=pd.to_datetime(
                        selected_trades['trade_date'].values[0]))

                results_frame['timeHeld'][i] = price_output['tr_dte'].values[
                    0] - net_position_per_tickerhead['tr_dte'].values[0]
                results_frame['pnl'][i] = pnl_per_tickerhead[
                    unique_tickerhead_list[i]].sum()

                if unique_tickerhead_list[i] in ['CL', 'B', 'ED']:
                    results_frame['indicator'][i] = selected_spread[
                        'reward_risk'].values[0]

                    if results_frame['qty'][i] > 0:
                        results_frame['recommendation'][i] = 'STOP'
                    elif results_frame['qty'][i] < 0:
                        if results_frame['indicator'][i] > -0.06:
                            results_frame['recommendation'][i] = 'STOP'
                        else:
                            results_frame['recommendation'][i] = 'HOLD'
                else:

                    results_frame['indicator'][i] = selected_spread[
                        'q_carry'].values[0]

                    if results_frame['qty'][i] > 0:
                        if results_frame['indicator'][i] < 19:
                            results_frame['recommendation'][i] = 'STOP'
                        else:
                            results_frame['recommendation'][i] = 'HOLD'

                    elif results_frame['qty'][i] < 0:
                        if results_frame['indicator'][i] > -9:
                            results_frame['recommendation'][i] = 'STOP'
                        else:
                            results_frame['recommendation'][i] = 'HOLD'

                if results_frame['qty'][i] > 0:
                    results_frame['downside'][i] = selected_spread[
                        'downside'].values[0] * results_frame['qty'][i]
                else:
                    results_frame['downside'][i] = selected_spread[
                        'upside'].values[0] * results_frame['qty'][i]

        return {'success': True, 'results_frame': results_frame}

    elif strategy_class == 'vcs':

        greeks_out = sg.get_greeks_4strategy_4date(alias=kwargs['alias'],
                                                   as_of_date=date_to)
        ticker_portfolio = greeks_out['ticker_portfolio']
        options_position = greeks_out['options_position']

        if ticker_portfolio.empty and not options_position.empty:
            result_output = {
                'success': False,
                'net_oev': np.NaN,
                'net_theta': np.NaN,
                'long_short_ratio': np.NaN,
                'recommendation': 'MISSING DATA',
                'last_adjustment_days_ago': np.NaN,
                'min_tr_dte': np.NaN,
                'long_oev': np.NaN,
                'short_oev': np.NaN,
                'favQMove': np.NaN
            }
        elif ticker_portfolio.empty and options_position.empty:
            result_output = {
                'success': False,
                'net_oev': np.NaN,
                'net_theta': np.NaN,
                'long_short_ratio': np.NaN,
                'recommendation': 'EMPTY',
                'last_adjustment_days_ago': np.NaN,
                'min_tr_dte': np.NaN,
                'long_oev': np.NaN,
                'short_oev': np.NaN,
                'favQMove': np.NaN
            }

        else:
            min_tr_dte = min([
                exp.get_days2_expiration(ticker=x,
                                         date_to=date_to,
                                         instrument='options',
                                         con=con)['tr_dte']
                for x in ticker_portfolio['ticker']
            ])

            net_oev = ticker_portfolio['total_oev'].sum()
            net_theta = ticker_portfolio['theta'].sum()

            long_portfolio = ticker_portfolio[
                ticker_portfolio['total_oev'] > 0]
            short_portfolio = ticker_portfolio[
                ticker_portfolio['total_oev'] < 0]
            short_portfolio['total_oev'] = abs(short_portfolio['total_oev'])

            long_oev = long_portfolio['total_oev'].sum()
            short_oev = short_portfolio['total_oev'].sum()

            if (not short_portfolio.empty) & (not long_portfolio.empty):
                long_short_ratio = 100 * long_oev / short_oev

                long_portfolio.sort_values('total_oev',
                                           ascending=False,
                                           inplace=True)
                short_portfolio.sort_values('total_oev',
                                            ascending=False,
                                            inplace=True)

                long_ticker = long_portfolio['ticker'].iloc[0]
                short_ticker = short_portfolio['ticker'].iloc[0]

                long_contract_specs = cmi.get_contract_specs(long_ticker)
                short_contract_specs = cmi.get_contract_specs(short_ticker)

                if 12*long_contract_specs['ticker_year']+long_contract_specs['ticker_month_num'] < \
                                        12*short_contract_specs['ticker_year']+short_contract_specs['ticker_month_num']:
                    front_ticker = long_ticker
                    back_ticker = short_ticker
                    direction = 'long'
                else:
                    front_ticker = short_ticker
                    back_ticker = long_ticker
                    direction = 'short'

                if 'vcs_output' in kwargs.keys():
                    vcs_output = kwargs['vcs_output']
                else:
                    vcs_output = ovcs.generate_vcs_sheet_4date(date_to=date_to)

                vcs_pairs = vcs_output['vcs_pairs']
                selected_result = vcs_pairs[
                    (vcs_pairs['ticker1'] == front_ticker)
                    & (vcs_pairs['ticker2'] == back_ticker)]

                if selected_result.empty:
                    favQMove = np.NaN
                else:
                    current_Q = selected_result['Q'].iloc[0]
                    q_limit = of.get_vcs_filter_values(
                        product_group=long_contract_specs['ticker_head'],
                        filter_type='tickerHead',
                        direction=direction,
                        indicator='Q')
                    if direction == 'long':
                        favQMove = current_Q - q_limit
                    elif direction == 'short':
                        favQMove = q_limit - current_Q
            else:
                long_short_ratio = np.NaN
                favQMove = np.NaN

            trades_frame = ts.get_trades_4strategy_alias(**kwargs)
            trades_frame_options = trades_frame[trades_frame['instrument'] ==
                                                'O']
            last_adjustment_days_ago = len(
                exp.get_bus_day_list(
                    date_to=date_to,
                    datetime_from=max(
                        trades_frame_options['trade_date']).to_pydatetime()))

            if favQMove >= 10 and last_adjustment_days_ago > 10:
                recommendation = 'STOP-ratio normalized'
            elif min_tr_dte < 25:
                recommendation = 'STOP-close to expiration'
            elif np.isnan(long_short_ratio):
                recommendation = 'STOP-not a proper calendar'
            else:
                if long_short_ratio < 80:
                    if favQMove < 0:
                        recommendation = 'buy_options_to_grow'
                    else:
                        recommendation = 'buy_options_to_shrink'
                elif long_short_ratio > 120:
                    if favQMove < 0:
                        recommendation = 'sell_options_to_grow'
                    else:
                        recommendation = 'sell_options_to_shrink'
                else:
                    recommendation = 'HOLD'

            result_output = {
                'success': True,
                'net_oev': net_oev,
                'net_theta': net_theta,
                'long_short_ratio': long_short_ratio,
                'recommendation': recommendation,
                'last_adjustment_days_ago': last_adjustment_days_ago,
                'min_tr_dte': min_tr_dte,
                'long_oev': long_oev,
                'short_oev': short_oev,
                'favQMove': favQMove
            }

    elif strategy_class == 'ocs':

        datetime_to = cu.convert_doubledate_2datetime(date_to)
        time_held = (datetime_to.date() -
                     strategy_info_output['created_date'].date()).days
        notes = ''

        strategy_position = ts.get_net_position_4strategy_alias(
            alias=kwargs['alias'], as_of_date=date_to, con=con)

        if len(strategy_position.index) == 0:
            tpnl.close_strategy(alias=kwargs['alias'],
                                close_date=date_to,
                                broker=broker,
                                con=con)
            result_output = {
                'success': True,
                'time_held': time_held,
                'dollar_noise': np.nan,
                'notes': 'closed'
            }
        elif strategy_position['qty'].sum() != 0:
            result_output = {
                'success': True,
                'time_held': time_held,
                'dollar_noise': np.nan,
                'notes': 'check position'
            }
        else:
            strategy_position['cont_indx'] = [
                cmi.get_contract_specs(x)['cont_indx']
                for x in strategy_position['ticker']
            ]
            strategy_position.sort_values('cont_indx',
                                          ascending=True,
                                          inplace=True)

            ocs_output = ocs.generate_overnight_spreads_sheet_4date(
                date_to=date_to)
            overnight_calendars = ocs_output['overnight_calendars']

            selection_indx = (overnight_calendars['ticker1'] == strategy_position['ticker'].iloc[0])&\
                             (overnight_calendars['ticker2'] == strategy_position['ticker'].iloc[1])

            if sum(selection_indx) > 0:
                dollar_noise = (overnight_calendars.loc[
                    selection_indx, 'dollarNoise100'].values[0]) * abs(
                        strategy_position['qty'].iloc[0])
            else:
                dollar_noise = np.nan

            result_output = {
                'success': True,
                'time_held': time_held,
                'dollar_noise': dollar_noise,
                'notes': 'hold'
            }

    elif strategy_class == 'skpt':

        long_ticker = strategy_position.loc[strategy_position['qty'] > 0,
                                            'ticker'].iloc[0]
        short_ticker = strategy_position.loc[strategy_position['qty'] < 0,
                                             'ticker'].iloc[0]

        long_data = gsp.get_stock_price_preloaded(ticker=long_ticker,
                                                  data_source='iex',
                                                  settle_date_to=date_to)
        short_data = gsp.get_stock_price_preloaded(ticker=short_ticker,
                                                   data_source='iex',
                                                   settle_date_to=date_to)
        merged_data = pd.merge(long_data[['close', 'settle_datetime']],
                               short_data[['close', 'settle_datetime']],
                               how='inner',
                               on='settle_datetime')
        merged_data.set_index('settle_datetime', drop=True, inplace=True)

        intaday_output_long = pweb.DataReader(long_ticker, 'iex-tops')
        intaday_output_short = pweb.DataReader(short_ticker, 'iex-tops')
        merged_data = merged_data.append(
            pd.DataFrame(
                {
                    'close_x': intaday_output_long.iloc[4].values[0],
                    'close_y': intaday_output_short.iloc[4].values[0]
                },
                index=[dt.datetime.now()]))

        signal_output = spt.backtest(merged_data, 'close_x', 'close_y')

        return {
            'long_ticker': long_ticker,
            'short_ticker': short_ticker,
            'zScoreC': signal_output['data_frame']['zScore'].iloc[-1],
            'zScore': signal_output['data_frame']['zScore'].iloc[-2]
        }

    else:
        result_output = {'success': False}

    if 'con' not in kwargs.keys():
        con.close()

    return result_output
def get_results_4strategy(**kwargs):

    signal_input = dict()

    if 'futures_data_dictionary' in kwargs.keys():
        signal_input['futures_data_dictionary'] = kwargs['futures_data_dictionary']

    if 'date_to' in kwargs.keys():
        date_to = kwargs['date_to']
    else:
        date_to = exp.doubledate_shift_bus_days()

    if 'datetime5_years_ago' in kwargs.keys():
        signal_input['datetime5_years_ago'] = kwargs['datetime5_years_ago']

    if 'strategy_info_output' in kwargs.keys():
        strategy_info_output = kwargs['strategy_info_output']
    else:
        strategy_info_output = ts.get_strategy_info_from_alias(**kwargs)

    con = msu.get_my_sql_connection(**kwargs)

    strategy_info_dict = sc.convert_from_string_to_dictionary(string_input=strategy_info_output['description_string'])
    #print(kwargs['alias'])

    strategy_class = strategy_info_dict['strategy_class']

    pnl_frame = tpm.get_daily_pnl_snapshot(as_of_date=date_to)
    pnl_frame = pnl_frame[pnl_frame['alias']==kwargs['alias']]
    strategy_position = ts.get_net_position_4strategy_alias(alias=kwargs['alias'],as_of_date=date_to)

    if strategy_class == 'futures_butterfly':

        ticker_head = cmi.get_contract_specs(strategy_info_dict['ticker1'])['ticker_head']
        if not strategy_position.empty:
            total_contracts2trade = strategy_position['qty'].abs().sum()
            t_cost = cmi.t_cost[ticker_head]
        QF_initial = float(strategy_info_dict['QF'])
        z1_initial = float(strategy_info_dict['z1'])

        bf_signals_output = fs.get_futures_butterfly_signals(ticker_list=[strategy_info_dict['ticker1'],
                                                                          strategy_info_dict['ticker2'],
                                                                          strategy_info_dict['ticker3']],
                                          aggregation_method=int(strategy_info_dict['agg']),
                                          contracts_back=int(strategy_info_dict['cBack']),
                                          date_to=date_to,**signal_input)

        aligned_output = bf_signals_output['aligned_output']
        current_data = aligned_output['current_data']
        holding_tr_dte = int(strategy_info_dict['trDte1'])-current_data['c1']['tr_dte']

        if strategy_position.empty:
            recommendation = 'CLOSE'
        elif (z1_initial>0)&(holding_tr_dte > 5) &\
                (bf_signals_output['qf']<QF_initial-20)&\
                (pnl_frame['total_pnl'].iloc[0] > 3*t_cost*total_contracts2trade):
            recommendation = 'STOP'
        elif (z1_initial<0)&(holding_tr_dte > 5) &\
                (bf_signals_output['qf']>QF_initial+20)&\
                (pnl_frame['total_pnl'].iloc[0] > 3*t_cost*total_contracts2trade):
            recommendation = 'STOP'
        elif (current_data['c1']['tr_dte'] < 35)&\
            (pnl_frame['total_pnl'].iloc[0] > 3*t_cost*total_contracts2trade):
            recommendation = 'STOP'
        elif (current_data['c1']['tr_dte'] < 35)&\
            (pnl_frame['total_pnl'].iloc[0] < 3*t_cost*total_contracts2trade):
            recommendation = 'WINDDOWN'
        else:
            recommendation = 'HOLD'

        result_output = {'success': True,'ticker_head': ticker_head,
                        'QF_initial':QF_initial,'z1_initial': z1_initial,
                        'QF': bf_signals_output['qf'],'z1': bf_signals_output['zscore1'],
                        'short_tr_dte': current_data['c1']['tr_dte'],
                        'holding_tr_dte': holding_tr_dte,
                        'second_spread_weight': bf_signals_output['second_spread_weight_1'],'recommendation': recommendation}

    elif strategy_class == 'spread_carry':
        trades4_strategy = ts.get_trades_4strategy_alias(**kwargs)
        grouped = trades4_strategy.groupby('ticker')
        net_position = pd.DataFrame()
        net_position['ticker'] = (grouped['ticker'].first()).values
        net_position['qty'] = (grouped['trade_quantity'].sum()).values
        net_position = net_position[net_position['qty'] != 0]

        net_position['ticker_head'] = [cmi.get_contract_specs(x)['ticker_head'] for x in net_position['ticker']]
        price_output = [gfp.get_futures_price_preloaded(ticker=x, settle_date=date_to) for x in net_position['ticker']]
        net_position['tr_dte'] = [x['tr_dte'].values[0] for x in price_output]

        results_frame = pd.DataFrame()
        unique_tickerhead_list = net_position['ticker_head'].unique()
        results_frame['tickerHead'] = unique_tickerhead_list
        results_frame['ticker1'] = [None]*len(unique_tickerhead_list)
        results_frame['ticker2'] = [None]*len(unique_tickerhead_list)
        results_frame['qty'] = [None]*len(unique_tickerhead_list)
        results_frame['pnl'] = [None]*len(unique_tickerhead_list)
        results_frame['downside'] = [None]*len(unique_tickerhead_list)
        results_frame['indicator'] = [None]*len(unique_tickerhead_list)
        results_frame['timeHeld'] = [None]*len(unique_tickerhead_list)
        results_frame['recommendation'] = [None]*len(unique_tickerhead_list)

        spread_carry_output = osc.generate_spread_carry_sheet_4date(report_date=date_to)
        spread_report = spread_carry_output['spread_report']

        pnl_output = tpnl.get_strategy_pnl(**kwargs)
        pnl_per_tickerhead = pnl_output['pnl_per_tickerhead']

        for i in range(len(unique_tickerhead_list)):

            net_position_per_tickerhead = net_position[net_position['ticker_head'] == unique_tickerhead_list[i]]
            net_position_per_tickerhead.sort('tr_dte',ascending=True,inplace=True)

            selected_spread = spread_report[(spread_report['ticker1'] == net_position_per_tickerhead['ticker'].values[0]) &
                             (spread_report['ticker2'] == net_position_per_tickerhead['ticker'].values[1])]

            results_frame['ticker1'][i] = selected_spread['ticker1'].values[0]
            results_frame['ticker2'][i] = selected_spread['ticker2'].values[0]
            results_frame['qty'][i] = net_position_per_tickerhead['qty'].values[0]

            selected_trades = trades4_strategy[trades4_strategy['ticker'] == results_frame['ticker1'].values[i]]

            price_output = gfp.get_futures_price_preloaded(ticker=results_frame['ticker1'].values[i],
                                                           settle_date=pd.to_datetime(selected_trades['trade_date'].values[0]))

            results_frame['timeHeld'][i] = price_output['tr_dte'].values[0]-net_position_per_tickerhead['tr_dte'].values[0]
            results_frame['pnl'][i] = pnl_per_tickerhead[unique_tickerhead_list[i]].sum()

            if unique_tickerhead_list[i] in ['CL', 'B', 'ED']:
                results_frame['indicator'][i] = selected_spread['reward_risk'].values[0]

                if results_frame['qty'][i] > 0:
                    results_frame['recommendation'][i] = 'STOP'
                elif results_frame['qty'][i] < 0:
                    if results_frame['indicator'][i] > -0.06:
                        results_frame['recommendation'][i] = 'STOP'
                    else:
                        results_frame['recommendation'][i] = 'HOLD'
            else:

                results_frame['indicator'][i] = selected_spread['q_carry'].values[0]

                if results_frame['qty'][i] > 0:
                    if results_frame['indicator'][i] < 19:
                        results_frame['recommendation'][i] = 'STOP'
                    else:
                        results_frame['recommendation'][i] = 'HOLD'

                elif results_frame['qty'][i] < 0:
                    if results_frame['indicator'][i] > -9:
                        results_frame['recommendation'][i] = 'STOP'
                    else:
                        results_frame['recommendation'][i] = 'HOLD'

            if results_frame['qty'][i] > 0:
                results_frame['downside'][i] = selected_spread['downside'].values[0]*results_frame['qty'][i]
            else:
                results_frame['downside'][i] = selected_spread['upside'].values[0]*results_frame['qty'][i]

        return {'success': True, 'results_frame': results_frame}

    elif strategy_class == 'vcs':

        greeks_out = sg.get_greeks_4strategy_4date(alias=kwargs['alias'], as_of_date=date_to)
        ticker_portfolio = greeks_out['ticker_portfolio']

        if ticker_portfolio.empty:
            min_tr_dte = np.NaN
            result_output = {'success': False, 'net_oev': np.NaN, 'net_theta': np.NaN, 'long_short_ratio': np.NaN,
                         'recommendation': 'EMPTY', 'last_adjustment_days_ago': np.NaN,
                         'min_tr_dte': np.NaN, 'long_oev': np.NaN, 'short_oev': np.NaN, 'favQMove': np.NaN}
        else:
            min_tr_dte = min([exp.get_days2_expiration(ticker=x,date_to=date_to,instrument='options',con=con)['tr_dte'] for x in ticker_portfolio['ticker']])

            net_oev = ticker_portfolio['total_oev'].sum()
            net_theta = ticker_portfolio['theta'].sum()

            long_portfolio = ticker_portfolio[ticker_portfolio['total_oev'] > 0]
            short_portfolio = ticker_portfolio[ticker_portfolio['total_oev'] < 0]
            short_portfolio['total_oev']=abs(short_portfolio['total_oev'])

            long_oev = long_portfolio['total_oev'].sum()
            short_oev = short_portfolio['total_oev'].sum()

            if (not short_portfolio.empty) & (not long_portfolio.empty):
                long_short_ratio = 100*long_oev/short_oev

                long_portfolio.sort('total_oev', ascending=False, inplace=True)
                short_portfolio.sort('total_oev', ascending=False, inplace=True)

                long_ticker = long_portfolio['ticker'].iloc[0]
                short_ticker = short_portfolio['ticker'].iloc[0]

                long_contract_specs = cmi.get_contract_specs(long_ticker)
                short_contract_specs = cmi.get_contract_specs(short_ticker)

                if 12*long_contract_specs['ticker_year']+long_contract_specs['ticker_month_num'] < \
                                        12*short_contract_specs['ticker_year']+short_contract_specs['ticker_month_num']:
                    front_ticker = long_ticker
                    back_ticker = short_ticker
                    direction = 'long'
                else:
                    front_ticker = short_ticker
                    back_ticker = long_ticker
                    direction = 'short'

                if 'vcs_output' in kwargs.keys():
                    vcs_output = kwargs['vcs_output']
                else:
                    vcs_output = ovcs.generate_vcs_sheet_4date(date_to=date_to)

                vcs_pairs = vcs_output['vcs_pairs']
                selected_result = vcs_pairs[(vcs_pairs['ticker1'] == front_ticker) & (vcs_pairs['ticker2'] == back_ticker)]

                if selected_result.empty:
                    favQMove = np.NaN
                else:
                    current_Q = selected_result['Q'].iloc[0]
                    q_limit = of.get_vcs_filter_values(product_group=long_contract_specs['ticker_head'],
                                                   filter_type='tickerHead',direction=direction,indicator='Q')
                    if direction == 'long':
                        favQMove = current_Q-q_limit
                    elif direction == 'short':
                        favQMove = q_limit-current_Q
            else:
                long_short_ratio = np.NaN
                favQMove = np.NaN

            trades_frame = ts.get_trades_4strategy_alias(**kwargs)
            trades_frame_options = trades_frame[trades_frame['instrument'] == 'O']
            last_adjustment_days_ago = len(exp.get_bus_day_list(date_to=date_to,datetime_from=max(trades_frame_options['trade_date']).to_datetime()))

            if favQMove >= 10 and last_adjustment_days_ago > 10:
                recommendation = 'STOP-ratio normalized'
            elif min_tr_dte<25:
                recommendation = 'STOP-close to expiration'
            elif np.isnan(long_short_ratio):
                recommendation = 'STOP-not a proper calendar'
            else:
                if long_short_ratio < 80:
                    if favQMove < 0:
                        recommendation = 'buy_options_to_grow'
                    else:
                        recommendation = 'buy_options_to_shrink'
                elif long_short_ratio > 120:
                    if favQMove < 0:
                        recommendation = 'sell_options_to_grow'
                    else:
                        recommendation = 'sell_options_to_shrink'
                else:
                    recommendation = 'HOLD'

            result_output = {'success': True, 'net_oev': net_oev, 'net_theta': net_theta, 'long_short_ratio': long_short_ratio,
                         'recommendation': recommendation, 'last_adjustment_days_ago': last_adjustment_days_ago,
                         'min_tr_dte': min_tr_dte, 'long_oev': long_oev, 'short_oev': short_oev, 'favQMove': favQMove}

    else:
        result_output = {'success': False}

    if 'con' not in kwargs.keys():
        con.close()

    return result_output
Пример #16
0
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