Exemplo n.º 1
0
        price = barrier_option.NPV()
        prices.append(price)
        # vol2 = black_var_surface.blackVol(daycounter.yearFraction(evalDate, maturitydt),spot+0.1)
        # process2 = evaluation.get_bsmprocess_cnstvol(daycounter,calendar,underlying,vol2)
        # barrier_option.setPricingEngine(ql.BinomialBarrierEngine(process2, 'crr', 800))
        # price2 = barrier_option.NPV()
        # vega = (price2-price)/(vol2-vol)
        # dsigma_ds = (vol2-vol)/0.1
        # print(vol,vol2,vega,dsigma_ds)
        # vegas.append(vega)
        # tdeltas.append(delta+vega*dsigma_ds)
    # delta_maturities.update({maturitydt:deltas})
    t = daycounter.yearFraction(evalDate, maturitydt)
    # pu.plot_line(axx,cont,list(spot_range),deltas,lgds[cont],'spot','Delta')
    # pu.plot_line(axx1,cont,list(spot_range),gammas,lgds[cont],'spot','Gamma')
    pu.plot_line(axx2, cont, list(spot_range), prices, lgds[cont], 'spot',
                 'Price')
    # pu.plot_line(axx3,cont,list(spot_range),tdeltas,lgds[cont],'spot','Total Delta')
# axx = pu.set_frame([axx])[0]
# pu.plot_line(axx,cont+1,[barrier*1.01]*len(spot_range),np.arange(-2,10,12/len(spot_range)),'','spot','Delta')
# maxd = 10
# mind = -2
# maxd = 8.5
# mind = 0
# rate = -0.01
# x = np.arange(barrier*(1+rate),barrier,-barrier*rate/100)
# axx.plot([barrier*(1+rate)]*len(spot_range),np.arange(mind,maxd,(maxd-mind)/len(spot_range)), color=pu.c6, linestyle='--', linewidth=1)
# axx.plot([barrier+0.001]*len(spot_range),np.arange(mind,maxd,(maxd-mind)/len(spot_range)), color=pu.c6, linestyle='--', linewidth=1)
# axx.plot(x,[mind]*len(x), color=pu.c6, linestyle='--', linewidth=1)
# axx.plot(x,[maxd]*len(x), color=pu.c6, linestyle='--', linewidth=1)

plt.show()
        float(index300sh_df_c['histvol_60']),
        float(index300sh_df_c['histvol_20']),
        float(index300sh_df_c['histvol_10']),
        float(index300sh_df_c['histvol_5'])
    ]
    print(indexid, ' current_vols : ', current_vols)
    histvolcone = [
        current_vols, max_vols, min_vols, median_vols, p75_vols, p25_vols
    ]
    x = [120, 60, 20, 10, 5]
    x_labels = ['1W', '2W', '1M', '3M', '6M']

    f2, ax2 = plt.subplots()
    ldgs = ['当前水平', '最大值', '最小值', '中位数', '75分位数', '25分位数']
    for cont2, y in enumerate(histvolcone):
        pu.plot_line(ax2, cont2, x, y, ldgs[cont2], '时间窗口', '波动率(%)')
    ax2.legend(bbox_to_anchor=(0., 1.02, 1., .202),
               loc=3,
               ncol=4,
               mode="expand",
               borderaxespad=0.)
    ax2.set_xticks([5, 10, 20, 60, 120])
    ax2.set_xticklabels(x_labels)
    f2.set_size_inches((8, 6))
    f2.savefig('../save_figure/otc_histvols_' + indexid + '_' +
               str(hist_date) + ' - ' + str(evalDate) + '.png',
               dpi=300,
               format='png')

plt.show()
def implied_vol_analysis(evalDate, w, nameCode, exchangeCode):

    pu = PlotUtil()
    engine1 = create_engine(
        'mysql+pymysql://readonly:[email protected]/mktdata',
        echo=False)
    Session1 = sessionmaker(bind=engine1)
    sess1 = Session1()
    engine2 = create_engine(
        'mysql+pymysql://readonly:[email protected]/metrics',
        echo=False)
    Session2 = sessionmaker(bind=engine2)
    sess2 = Session2()

    optionMetrics = dbt.OptionMetrics

    dt_1w = w.tdaysoffset(-1, evalDate,
                          "Period=W").Data[0][0].strftime("%Y-%m-%d")
    dt_2w = w.tdaysoffset(-2, evalDate,
                          "Period=W").Data[0][0].strftime("%Y-%m-%d")
    dt_3w = w.tdaysoffset(-3, evalDate,
                          "Period=W").Data[0][0].strftime("%Y-%m-%d")
    dt_4w = w.tdaysoffset(-4, evalDate,
                          "Period=W").Data[0][0].strftime("%Y-%m-%d")
    dt_5w = w.tdaysoffset(-5, evalDate,
                          "Period=W").Data[0][0].strftime("%Y-%m-%d")
    plt.rcParams['font.sans-serif'] = ['STKaiti']
    plt.rcParams.update({'font.size': 15})
    """波动率期限结构"""
    dates = [evalDate, dt_1w, dt_2w, dt_3w, dt_4w, dt_5w]

    query_f = sess1.query(futureMkt.dt_date, futureMkt.id_instrument.label('id_underlying'),
                            futureMkt.amt_settlement,futureMkt.flag_night,futureMkt.name_code) \
        .filter(or_(futureMkt.dt_date==evalDate,futureMkt.dt_date==dt_1w,futureMkt.dt_date==dt_2w,
                    futureMkt.dt_date==dt_3w,futureMkt.dt_date==dt_4w,futureMkt.dt_date==dt_5w))\
        .filter(futureMkt.name_code == nameCode)\
        .filter(futureMkt.flag_night != 1)

    query_metrics = sess2.query(optionMetrics.dt_date,optionMetrics.id_instrument,optionMetrics.cd_option_type,
                                optionMetrics.pct_implied_vol,optionMetrics.amt_option_price) \
        .filter(or_(optionMetrics.dt_date == evalDate, optionMetrics.dt_date == dt_1w, optionMetrics.dt_date == dt_2w,
                    optionMetrics.dt_date == dt_3w, optionMetrics.dt_date == dt_4w, optionMetrics.dt_date == dt_5w)) \
        .filter(optionMetrics.name_code == nameCode)

    df_future = pd.read_sql(query_f.statement, query_f.session.bind)
    df_metrics = pd.read_sql(query_metrics.statement,
                             query_metrics.session.bind)
    for (idx, row) in df_metrics.iterrows():
        id_option = row['id_instrument']

        if id_option[0] == nameCode or id_option[0:2] == nameCode:
            dt_date = row['dt_date']
            option_price = row['amt_option_price']
            strike = float(id_option[-4:])
            if nameCode == 'm':
                id_underlying = id_option[:6]
            elif nameCode == 'sr':
                id_underlying = id_option[:7]
            else:
                id_underlying = None
            contract_month = id_underlying[-4:]
            if int(contract_month[-2:]) in [1, 5, 9]:
                df_metrics.loc[idx, 'flag'] = 1
                underlying_price = df_future[
                    (df_future['dt_date'] == dt_date)
                    & (df_future['id_underlying'] == id_underlying
                       )]['amt_settlement'].values[0]
                df_metrics.loc[idx, 'dt_date'] = dt_date.strftime("%Y-%m-%d")
                df_metrics.loc[idx, 'id_underlying'] = id_underlying
                df_metrics.loc[idx, 'underlying_price'] = underlying_price
                df_metrics.loc[idx, 'contract_month'] = id_underlying[-4:]
                df_metrics.loc[idx, 'diff'] = abs(strike - underlying_price)
            else:
                df_metrics.loc[idx, 'flag'] = 0
        else:
            df_metrics.loc[idx, 'flag'] = 0

    df_metrics = df_metrics[df_metrics['flag'] == 1].reset_index()
    idx = df_metrics.groupby(['dt_date', 'id_underlying', 'cd_option_type'
                              ])['diff'].transform(min) == df_metrics['diff']

    df_iv = df_metrics[idx]
    df_call_iv = df_iv[df_iv['cd_option_type'] == 'call'].sort_values(
        by=['dt_date',
            'id_underlying'], ascending=False).reset_index()  # 选取认购平值合约
    df_put_iv = df_iv[df_iv['cd_option_type'] == 'put'].sort_values(
        by=['dt_date',
            'id_underlying'], ascending=False).reset_index()  # 选取认沽平值合约
    df_call_iv = df_call_iv.drop_duplicates(['dt_date', 'id_underlying'])
    df_put_iv = df_put_iv.drop_duplicates(['dt_date', 'id_underlying'])

    optiondata_atm_df = df_put_iv[['dt_date', 'contract_month']]
    optiondata_atm_df.loc[:, 'implied_vol'] = 100 * (
        df_call_iv.loc[:, 'pct_implied_vol'] +
        df_put_iv.loc[:, 'pct_implied_vol']) / 2.0

    f1, ax1 = plt.subplots()
    cont = 0
    contracts = []
    for d in dates:
        df = optiondata_atm_df[optiondata_atm_df['dt_date'] == d]
        df = df.sort_values(by=['contract_month'], ascending=True)
        pu.plot_line(ax1, cont, range(len(df)), df['implied_vol'], d, '合约月份',
                     '波动率(%)')
        if len(contracts) == 0: contracts = df['contract_month'].tolist()
        cont += 1
    ax1.legend(bbox_to_anchor=(0., 1.02, 1., .202),
               loc=3,
               ncol=6,
               mode="expand",
               borderaxespad=0.,
               frameon=False)
    ax1.set_xticks(range(len(contracts)))
    ax1.set_xticklabels(contracts)
    f1.set_size_inches((12, 6))
    optiondata_atm_df.to_csv('../data/' + nameCode +
                             '_implied_vol_term_structure.csv')
    f1.savefig('../data/' + nameCode + '_iv_term_structure_' + str(evalDate) +
               '.png',
               dpi=300,
               format='png')
a = pd.merge(rb_data, i_data, on='dt_date')
earningsdata = pd.merge(a, j_data, on='dt_date')
earningsdata[
    'amt_earning'] = earningsdata['amt_close_x'] - 1.65 * earningsdata[
        'amt_close_y'] - 0.5 * earningsdata['amt_close']

print(earningsdata)

pu = PlotUtil()

f, ax = plt.subplots()

count = 0
pu.plot_line(ax,
             0,
             earningsdata['dt_date'],
             earningsdata['amt_earning'],
             lgd='钢厂利润指数')
pu.plot_line(ax,
             1,
             earningsdata['dt_date'],
             earningsdata['amt_close_x'],
             lgd='螺纹钢')
pu.plot_line(ax,
             2,
             earningsdata['dt_date'],
             earningsdata['amt_close_y'],
             lgd='铁矿石')
pu.plot_line(ax,
             3,
             earningsdata['dt_date'],
    for cm1 in contract_months:
        c = optiondata_df['contract_month'].map(lambda x: x == cm1)
        c1 = optiondata_df['date'].map(lambda x: x == date)
        critiron = c & c1
        df = optiondata_df[critiron]
        idx = df['atm_dif'].idxmin()
        optiondata_atm_df = optiondata_atm_df.append(df.loc[idx],
                                                     ignore_index=True)
print('atm_implied_vols')
print(optiondata_atm_df)
f1, ax1 = plt.subplots()
cont = 0
for d in dates:
    c2 = optiondata_atm_df['date'].map(lambda a: a == d)
    df = optiondata_atm_df[c2]
    pu.plot_line(ax1, cont, df['contract_month'], df['implied_vol'], d, '合约月份',
                 '波动率(%)')
    cont += 1
ax1.legend(bbox_to_anchor=(0., 1.02, 1., .202),
           loc=3,
           ncol=3,
           mode="expand",
           borderaxespad=0.,
           frameon=False)
f1.savefig('../save_figure/implied_vols_' + str(evalDate) + '.png',
           dpi=300,
           format='png')

#################### Futures and Realised Vol
# Get core contract mktdata
data = w.wsd("SR.CZC", "trade_hiscode", hist_date, evalDate, "")
underlying_df = pd.DataFrame({'date': data.Times, 'code_core': data.Data[0]})
    mergedvix_df = rv_df.join(cvix_df.set_index('dt_date'), on='dt_date')

    print(merged_df)

    dates = merged_df['dt_date'].tolist()
    vol_set = [merged_df['intraday_vol'].tolist(),
               merged_df['histvol_120'].tolist(),
               merged_df['histvol_60'].tolist(),
               merged_df['histvol_20'].tolist(),
               mergedvix_df['amt_close'].tolist()
               ]
    print(indexid,' histvol_60 : ',merged_df['histvol_60'].tolist()[-1])
    f2, ax2 = plt.subplots()
    ldgs = ['已实现波动率RV', '历史波动率6M', '历史波动率3M', '历史波动率1M', '中国波指IVIX']
    for cont2, y in enumerate(vol_set):
        pu.plot_line(ax2, cont2, dates, y, ldgs[cont2], '日期', '波动率(%)')
    ax2.legend(bbox_to_anchor=(0., 1.02, 1., .202), loc=3,
               ncol=5, mode="expand", borderaxespad=0.)
    f2.set_size_inches((12, 5))

    f2.savefig('../save_figure/otc_realizedvol_' + indexid + '_' + str(startDate) + ' - ' + str(evalDate) + '.png',
               dpi=300, format='png')
    histvols_3M.append(merged_df['histvol_60'].tolist())
    realizedvols.append(merged_df['intraday_vol'].tolist())
    merged_df.to_csv('../save_figure/index_vols'+indexid+'.csv')

f3, ax3 = plt.subplots()
ldgs = ['沪深300指数历史波动率3M','上证50指数历史波动率3M','中证500指数历史波动率3M']
for cont2, y in enumerate(histvols_3M):
    pu.plot_line(ax3, cont2, dates, y, ldgs[cont2], '日期', '波动率(%)')
ax3.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,