def pcr_etf_option(dt_start, dt_end, name_code, df_res): optionMkt = admin.table_options_mktdata() Index_mkt = admin.table_indexes_mktdata() query_pcr = admin.session_gc().query(optionMkt.c.dt_date, optionMkt.c.cd_option_type, optionMkt.c.id_underlying, func.sum(optionMkt.c.amt_holding_volume).label('total_holding_volume'), func.sum(optionMkt.c.amt_trading_volume).label('total_trading_volume') ) \ .filter(optionMkt.c.dt_date >= dt_start) \ .filter(optionMkt.c.dt_date <= dt_end) \ .filter(optionMkt.c.name_code == name_code) \ .group_by(optionMkt.c.cd_option_type, optionMkt.c.dt_date, optionMkt.c.id_underlying) df_pcr = pd.read_sql(query_pcr.statement, query_pcr.session.bind) query_etf = admin.session_gc().query(Index_mkt.c.dt_date, Index_mkt.c.amt_close, Index_mkt.c.amt_open, Index_mkt.c.id_instrument.label(c.Util.ID_UNDERLYING)) \ .filter(Index_mkt.c.dt_date >= dt_start).filter(Index_mkt.c.dt_date <= dt_end) \ .filter(Index_mkt.c.id_instrument == 'index_50etf') df_50etf = pd.read_sql(query_etf.statement, query_etf.session.bind) df = df_pcr.groupby(['dt_date', 'cd_option_type' ])['total_holding_volume', 'total_trading_volume'].sum().reset_index() df_call = df[df['cd_option_type'] == 'call'].reset_index() df_put = df[df['cd_option_type'] == 'put'].reset_index() pc_ratio = [] for idx, row in df_call.iterrows(): row_put = df_put[df_put['dt_date'] == row['dt_date']] pcr_trading = row_put['total_trading_volume'].values[0] / row[ 'total_trading_volume'] pcr_holding = row_put['total_holding_volume'].values[0] / row[ 'total_holding_volume'] pc_ratio.append({ 'dt_date': row['dt_date'], 'tv_c': row['total_trading_volume'], 'tv_p': row_put['total_trading_volume'].values[0], 'hv_c': row['total_holding_volume'], 'hv_p': row_put['total_holding_volume'].values[0], 'tv_pcr': pcr_trading, 'hv_pcr': pcr_holding, }) df_pcr = pd.DataFrame(pc_ratio) df_pcr = pd.merge(df_pcr, df_50etf[['dt_date', 'amt_close']], how='left', on=['dt_date'], suffixes=['', '_r']) df_pcr = df_pcr.sort_values(by='dt_date', ascending=False).reset_index(drop=True) df_res.loc[:, name_code + ':A:date'] = df_pcr['dt_date'] df_res.loc[:, name_code + ':B:tv_c'] = df_pcr['tv_c'] df_res.loc[:, name_code + ':C:tv_p'] = df_pcr['tv_p'] df_res.loc[:, name_code + ':E:date'] = df_pcr['dt_date'] df_res.loc[:, name_code + ':F:hv_c'] = df_pcr['hv_c'] df_res.loc[:, name_code + ':G:hv_p'] = df_pcr['hv_p'] df_res.loc[:, name_code + ':I:date'] = df_pcr['dt_date'] df_res.loc[:, name_code + ':J:tv_pcr'] = df_pcr['tv_pcr'] df_res.loc[:, name_code + ':K:hv_pcr'] = df_pcr['hv_pcr'] df_res.loc[:, name_code + ':L:amt_close'] = df_pcr['amt_close'] return df_res
def pcr(dt_start, dt_end, name_code, df_res): optionMkt = admin.table_options_mktdata() futureMkt = admin.table_futures_mktdata() query_pcr = admin.session_mktdata().query(optionMkt.c.dt_date, optionMkt.c.cd_option_type, optionMkt.c.id_underlying, func.sum(optionMkt.c.amt_holding_volume).label('total_holding_volume'), func.sum(optionMkt.c.amt_trading_volume).label('total_trading_volume') ) \ .filter(optionMkt.c.dt_date >= dt_start) \ .filter(optionMkt.c.dt_date <= dt_end) \ .filter(optionMkt.c.name_code == name_code) \ .group_by(optionMkt.c.cd_option_type, optionMkt.c.dt_date, optionMkt.c.id_underlying) query_srf = admin.session_mktdata().query(futureMkt.c.dt_date, futureMkt.c.id_instrument, futureMkt.c.amt_close, futureMkt.c.amt_trading_volume, futureMkt.c.amt_settlement) \ .filter(futureMkt.c.dt_date >= dt_start) \ .filter(futureMkt.c.dt_date <= dt_end) \ .filter(futureMkt.c.name_code == name_code) \ .filter(futureMkt.c.flag_night != 1) df_pcr = pd.read_sql(query_pcr.statement, query_pcr.session.bind) df_srf = pd.read_sql(query_srf.statement, query_srf.session.bind) # 按期权合约持仓量最大选取主力合约 df = df_pcr[df_pcr.groupby(['dt_date', 'cd_option_type'])['total_holding_volume'].transform(max) == df_pcr[ 'total_holding_volume']] df_call = df[df['cd_option_type'] == 'call'].reset_index() df_put = df[df['cd_option_type'] == 'put'].reset_index() pc_ratio = [] for idx, row in df_call.iterrows(): row_put = df_put[df_put['dt_date'] == row['dt_date']] pcr_trading = row_put['total_trading_volume'].values[0] / row['total_trading_volume'] pcr_holding = row_put['total_holding_volume'].values[0] / row['total_holding_volume'] pc_ratio.append({'dt_date': row['dt_date'], 'tv_c': row['total_trading_volume'], 'tv_p': row_put['total_trading_volume'].values[0], 'hv_c': row['total_holding_volume'], 'hv_p': row_put['total_holding_volume'].values[0], 'tv_pcr': pcr_trading, 'hv_pcr': pcr_holding, 'id_instrument': row['id_underlying'], }) df_pcr = pd.DataFrame(pc_ratio) df_pcr = pd.merge(df_pcr, df_srf[['dt_date', 'id_instrument', 'amt_settlement']], how='left', on=['dt_date', 'id_instrument'], suffixes=['', '_r']) df_pcr = df_pcr.sort_values(by='dt_date', ascending=False).reset_index(drop=True) df_res.loc[:, 'A:date'] = df_pcr['dt_date'] df_res.loc[:, 'B:tv_c'] = df_pcr['tv_c'] df_res.loc[:, 'C:tv_p'] = df_pcr['tv_p'] df_res.loc[:, 'D'] = None df_res.loc[:, 'E:date'] = df_pcr['dt_date'] df_res.loc[:, 'F:hv_c'] = df_pcr['hv_c'] df_res.loc[:, 'G:hv_p'] = df_pcr['hv_p'] df_res.loc[:, 'H'] = None df_res.loc[:, 'I:date'] = df_pcr['dt_date'] df_res.loc[:, 'J:tv_pcr'] = df_pcr['tv_pcr'] df_res.loc[:, 'K:hv_pcr'] = df_pcr['hv_pcr'] df_res.loc[:, 'L:amt_settlement'] = df_pcr['amt_settlement'] df_res.loc[:, 'M'] = None return df_res
def df_iv_at_the_money(dt_date, dt_start, namecode, df_srf): optionMetrics = dbt.OptionMetrics query_sro = admin.session_metrics().query(optionMetrics.dt_date, optionMetrics.id_instrument, optionMetrics.id_underlying, optionMetrics.amt_strike, optionMetrics.cd_option_type, optionMetrics.pct_implied_vol) \ .filter(optionMetrics.dt_date >= dt_start) \ .filter(optionMetrics.dt_date <= dt_date)\ .filter(optionMetrics.name_code == namecode) df_sro = pd.read_sql(query_sro.statement, query_sro.session.bind) dates = df_sro['dt_date'].unique() dict_iv_call = [] dict_iv_put = [] for date in dates: df_volume_groupby = get_volume_groupby_id_option(admin.table_options_mktdata(), namecode, dt_start=date, dt_end=date). \ sort_values(by='total_trading_volume', ascending=False).reset_index(drop=True) id_c1 = df_volume_groupby.loc[0, 'id_underlying'] df0 = df_sro[(df_sro['dt_date'] == date) & (df_sro['id_underlying'] == id_c1)] df1 = df0[(df0['cd_option_type'] == 'call')] amt_settle = \ df_srf[(df_srf['dt_date'] == date) & (df_srf['id_instrument'] == id_c1)]['amt_settlement'].values[0] df1['diff'] = abs(df1['amt_strike'] - amt_settle) df1 = df1.sort_values(by='diff', ascending=True) k = df1.iloc[0]['amt_strike'] iv_call_c1 = df1.iloc[0]['pct_implied_vol'] * 100 iv_put_c1 = df0[(df0['cd_option_type'] == 'put') & ( df0['amt_strike'] == k)]['pct_implied_vol'].values[0] * 100 id_c2 = df_volume_groupby.loc[1, 'id_underlying'] df0 = df_sro[(df_sro['dt_date'] == date) & (df_sro['id_underlying'] == id_c2)] df1 = df0[(df0['cd_option_type'] == 'call')] amt_settle = \ df_srf[(df_srf['dt_date'] == date) & (df_srf['id_instrument'] == id_c1)]['amt_settlement'].values[0] df1['diff'] = abs(df1['amt_strike'] - amt_settle) df1 = df1.sort_values(by='diff', ascending=True) k = df1.iloc[0]['amt_strike'] iv_call_c2 = df1.iloc[0]['pct_implied_vol'] * 100 iv_put_c2 = df0[(df0['cd_option_type'] == 'put') & ( df0['amt_strike'] == k)]['pct_implied_vol'].values[0] * 100 dict_iv_call.append({ 'dt_date': date, 'iv_c1': iv_call_c1, 'iv_c2': iv_call_c2, 'underlying_c1': id_c1, 'underlying_c2': id_c2, }) dict_iv_put.append({ 'dt_date': date, 'iv_c1': iv_put_c1, 'iv_c2': iv_put_c2, 'underlying_c1': id_c1, 'underlying_c2': id_c2, }) df_call = pd.DataFrame(dict_iv_call) df_put = pd.DataFrame(dict_iv_put) return df_call, df_put
def commodity_option_market_overview_by_month(start_date, end_date, name_code): optionMkt = admin.table_options_mktdata() futureMkt = admin.table_futures_mktdata() query = admin.session_gc().query(optionMkt.c.dt_date,optionMkt.c.id_underlying, func.sum(optionMkt.c.amt_trading_volume).label('option_trading_volume'), func.sum(optionMkt.c.amt_trading_value).label('option_trading_value') ) \ .filter(optionMkt.c.dt_date >= start_date) \ .filter(optionMkt.c.dt_date <= end_date) \ .filter(optionMkt.c.name_code == name_code) \ .group_by(optionMkt.c.dt_date, optionMkt.c.id_underlying) df_option_trading = pd.read_sql(query.statement, query.session.bind) query_future = admin.session_gc().query(futureMkt.c.dt_date,futureMkt.c.id_instrument, func.sum(futureMkt.c.amt_trading_volume).label('future_trading_volume') ) \ .filter(futureMkt.c.dt_date >= start_date) \ .filter(futureMkt.c.dt_date <= end_date) \ .filter(futureMkt.c.name_code == name_code) \ .group_by(futureMkt.c.dt_date, futureMkt.c.id_instrument) df_future_trading = pd.read_sql(query_future.statement, query_future.session.bind) query_option_holding = admin.session_gc().query(optionMkt.c.dt_date, optionMkt.c.id_underlying, func.sum(optionMkt.c.amt_holding_volume).label('option_holding_volume')) \ .filter(optionMkt.c.dt_date >= start_date) \ .filter(optionMkt.c.dt_date <= end_date) \ .filter(optionMkt.c.name_code == name_code)\ .group_by(optionMkt.c.dt_date, optionMkt.c.id_underlying) #每日日盘收盘持仓数据 df_option_holding = pd.read_sql(query_option_holding.statement, query_option_holding.session.bind) query_future_holding = admin.session_gc().query(futureMkt.c.dt_date,futureMkt.c.id_instrument, func.sum(futureMkt.c.amt_holding_volume).label('future_holding_volume')) \ .filter(futureMkt.c.dt_date >= start_date) \ .filter(futureMkt.c.dt_date <= end_date) \ .filter(futureMkt.c.name_code == name_code) \ .group_by(futureMkt.c.dt_date, futureMkt.c.id_instrument) #每日日盘收盘持仓数据 df_future_holding = pd.read_sql(query_future_holding.statement, query_future_holding.session.bind) # new_df = pd.merge(A_df, B_df, how='left', left_on=['A_c1', 'c2'], right_on=['B_c1', 'c2']) df_future = pd.merge(df_future_holding, df_future_trading, on=[c.Util.DT_DATE, c.Util.ID_INSTRUMENT]) df_option = pd.merge(df_option_holding, df_option_trading, on=[c.Util.DT_DATE, c.Util.ID_UNDERLYING]) df = pd.merge(df_option, df_future, left_on=[c.Util.DT_DATE, c.Util.ID_UNDERLYING], right_on=[c.Util.DT_DATE, c.Util.ID_INSTRUMENT]) # df = df.groupby([c.Util.DT_DATE,c.Util.ID_UNDERLYING,c.Util.ID_INSTRUMENT])['col3'].sum() return df
def commodity_option_market_overview(start_date, end_date, name_code): optionMkt = admin.table_options_mktdata() futureMkt = admin.table_futures_mktdata() query = admin.session_gc().query(optionMkt.c.dt_date, func.sum(optionMkt.c.amt_trading_volume).label('option_trading_volume'), func.sum(optionMkt.c.amt_trading_value).label('option_trading_value') ) \ .filter(optionMkt.c.dt_date >= start_date) \ .filter(optionMkt.c.dt_date <= end_date) \ .filter(optionMkt.c.name_code == name_code) \ .group_by(optionMkt.c.dt_date) df_option_trading = pd.read_sql(query.statement, query.session.bind) query_future = admin.session_gc().query(futureMkt.c.dt_date, func.sum(futureMkt.c.amt_trading_volume).label('future_trading_volume') ) \ .filter(futureMkt.c.dt_date >= start_date) \ .filter(futureMkt.c.dt_date <= end_date) \ .filter(futureMkt.c.name_code == name_code) \ .group_by(futureMkt.c.dt_date) df_future_trading = pd.read_sql(query_future.statement, query_future.session.bind) query_option_holding = admin.session_gc().query(optionMkt.c.dt_date, func.sum(optionMkt.c.amt_holding_volume).label('option_holding_volume')) \ .filter(optionMkt.c.dt_date >= start_date) \ .filter(optionMkt.c.dt_date <= end_date) \ .filter(optionMkt.c.name_code == name_code) \ .group_by(optionMkt.c.dt_date) #每日日盘收盘持仓数据 df_option_holding = pd.read_sql(query_option_holding.statement, query_option_holding.session.bind) query_future_holding = admin.session_gc().query(futureMkt.c.dt_date, func.sum(futureMkt.c.amt_holding_volume).label('future_holding_volume')) \ .filter(futureMkt.c.dt_date >= start_date) \ .filter(futureMkt.c.dt_date <= end_date) \ .filter(futureMkt.c.name_code == name_code) \ .group_by(futureMkt.c.dt_date) #每日日盘收盘持仓数据 df_future_holding = pd.read_sql(query_future_holding.statement, query_future_holding.session.bind) # df = pd.merge(df_option_trading,df_future_trading[[c.Util.DT_DATE,'future_trading_volume']],on=c.Util.DT_DATE) # df = pd.merge(df,df_option_holding,on=c.Util.DT_DATE) # df = pd.merge(df,df_future_holding,on=c.Util.DT_DATE) df_future = pd.merge(df_future_holding, df_future_trading, on=[c.Util.DT_DATE]) df_option = pd.merge(df_option_holding, df_option_trading, on=[c.Util.DT_DATE]) df = pd.merge(df_option, df_future, on=[c.Util.DT_DATE]) return df
def get_comoption_mktdata(start_date, end_date, name_code): # Future_mkt = dbt.FutureMkt table_mktdata = admin.table_futures_mktdata_gc() Option_mkt = admin.table_options_mktdata() options = dbt.Options query_mkt = admin.session_gc(). \ query(Option_mkt.c.dt_date, Option_mkt.c.id_instrument, Option_mkt.c.id_underlying, Option_mkt.c.code_instrument, Option_mkt.c.amt_close, Option_mkt.c.amt_open, Option_mkt.c.amt_settlement, Option_mkt.c.amt_last_settlement, Option_mkt.c.amt_trading_volume,Option_mkt.c.amt_trading_value, Option_mkt.c.pct_implied_vol, Option_mkt.c.amt_holding_volume, Option_mkt.c.amt_trading_volume ) \ .filter(Option_mkt.c.dt_date >= start_date).filter(Option_mkt.c.dt_date <= end_date) \ .filter(Option_mkt.c.name_code == name_code).filter(Option_mkt.c.flag_night != 1) query_option = admin.session_mktdata(). \ query(options.id_instrument, options.cd_option_type, options.amt_strike, options.name_contract_month, options.dt_maturity, options.nbr_multiplier) \ .filter(and_(options.dt_listed <= end_date, options.dt_maturity >= start_date)) query_srf = admin.session_gc(). \ query(table_mktdata.c.dt_date, table_mktdata.c.id_instrument.label(c.Util.ID_UNDERLYING), table_mktdata.c.amt_settlement.label(c.Util.AMT_UNDERLYING_CLOSE), table_mktdata.c.amt_open.label(c.Util.AMT_UNDERLYING_OPEN_PRICE)) \ .filter(table_mktdata.c.dt_date >= start_date).filter(table_mktdata.c.dt_date <= end_date) \ .filter(table_mktdata.c.name_code == name_code) df_srf = pd.read_sql(query_srf.statement, query_srf.session.bind) df_mkt = pd.read_sql(query_mkt.statement, query_mkt.session.bind) df_contract = pd.read_sql(query_option.statement, query_option.session.bind) df_option = df_mkt.join(df_contract.set_index('id_instrument'), how='left', on='id_instrument') df_option_metrics = pd.merge(df_option, df_srf, how='left', on=['dt_date', 'id_underlying'], suffixes=['', '_r']) return df_option_metrics
def get_50option_mktdata(start_date, end_date): Index_mkt = dbt.IndexMkt Option_mkt = admin.table_options_mktdata() options = dbt.Options util = c.Util query_mkt = admin.session_gc().query(Option_mkt.c.dt_date, Option_mkt.c.id_instrument, Option_mkt.c.code_instrument, Option_mkt.c.amt_open, Option_mkt.c.amt_close, Option_mkt.c.amt_settlement, Option_mkt.c.amt_last_settlement,Option_mkt.c.amt_trading_value, Option_mkt.c.amt_trading_volume, Option_mkt.c.amt_holding_volume, Option_mkt.c.pct_implied_vol ) \ .filter(Option_mkt.c.dt_date >= start_date).filter(Option_mkt.c.dt_date <= end_date) \ .filter(Option_mkt.c.datasource == 'wind').filter(Option_mkt.c.name_code == '50etf') query_option = admin.session_mktdata().query(options.id_instrument, options.cd_option_type, options.amt_strike, options.name_contract_month, options.dt_maturity, options.nbr_multiplier) \ .filter(and_(options.dt_listed <= end_date, options.dt_maturity >= start_date)) query_etf = admin.session_gc().query(Index_mkt.dt_date, Index_mkt.amt_close, Index_mkt.amt_open, Index_mkt.id_instrument.label(util.ID_UNDERLYING)) \ .filter(Index_mkt.dt_date >= start_date).filter(Index_mkt.dt_date <= end_date) \ .filter(Index_mkt.id_instrument == 'index_50etf') df_mkt = pd.read_sql(query_mkt.statement, query_mkt.session.bind) df_contract = pd.read_sql(query_option.statement, query_option.session.bind) df_50etf = pd.read_sql(query_etf.statement, query_etf.session.bind).rename( columns={ 'amt_close': util.AMT_UNDERLYING_CLOSE, 'amt_open': util.AMT_UNDERLYING_OPEN_PRICE }) df_option = df_mkt.join(df_contract.set_index('id_instrument'), how='left', on='id_instrument') df_option_metrics = df_option.join(df_50etf.set_index('dt_date'), how='left', on='dt_date') return df_option_metrics
def trade_volume(dt_date, dt_last_week, w, nameCode, core_instrumentid): pu = PlotUtil() options_mkt = admin.table_options_mktdata() evalDate = dt_date.strftime("%Y-%m-%d") # Set as Friday plt.rcParams['font.sans-serif'] = ['STKaiti'] plt.rcParams.update({'font.size': 15}) """当日成交持仓量 """ query_volume = admin.session_mktdata().query(options_mkt.c.dt_date, options_mkt.c.cd_option_type, options_mkt.c.amt_strike, options_mkt.c.amt_holding_volume, options_mkt.c.amt_trading_volume, options_mkt.c.amt_close, options_mkt.c.pct_implied_vol ) \ .filter(or_(options_mkt.c.dt_date == evalDate,options_mkt.c.dt_date == dt_last_week)) \ .filter(options_mkt.c.id_underlying == core_instrumentid)\ .filter(options_mkt.c.flag_night != 1) df_2d = pd.read_sql(query_volume.statement, query_volume.session.bind) df = df_2d[df_2d['dt_date'] == dt_date].reset_index() df_lw = df_2d[df_2d['dt_date'] == dt_last_week].reset_index() df_call = df[df['cd_option_type'] == 'call'].reset_index() df_put = df[df['cd_option_type'] == 'put'].reset_index() dflw_call = df_lw[df_lw['cd_option_type'] == 'call'].reset_index() dflw_put = df_lw[df_lw['cd_option_type'] == 'put'].reset_index() call_deltas = [] put_deltas = [] for idx, row in df_call.iterrows(): row_put = df_put.loc[idx] strike = row['amt_strike'] rowlw_call = dflw_call[dflw_call['amt_strike'] == strike] rowlw_put = dflw_put[dflw_put['amt_strike'] == strike] last_holding_call = 0.0 last_holding_put = 0.0 try: last_holding_call = rowlw_call['amt_holding_volume'].values[0] except: pass try: last_holding_put = rowlw_put['amt_holding_volume'].values[0] except: pass call_delta = row['amt_holding_volume'] - last_holding_call put_delta = row_put['amt_holding_volume'] - last_holding_put call_deltas.append(call_delta) put_deltas.append(put_delta) if nameCode == 'sr': wt = 25 else: wt = 15 strikes = df_call['amt_strike'].tolist() strikes1 = df_call['amt_strike'] + wt holding_call = df_call['amt_holding_volume'].tolist() holding_put = df_put['amt_holding_volume'].tolist() trading_call = df_call['amt_trading_volume'].tolist() trading_put = df_put['amt_trading_volume'].tolist() df_results = pd.DataFrame({ '0 call iv': df_call['pct_implied_vol'].tolist(), '1 call delta_holding': call_deltas, '2 call holding': df_call['amt_holding_volume'].tolist(), '3 call trading': df_call['amt_trading_volume'].tolist(), '4 call price': df_call['amt_close'].tolist(), '5 strikes': df_put['amt_strike'].tolist(), '6 put price': df_put['amt_close'].tolist(), '7 put trading': df_put['amt_trading_volume'].tolist(), '8 put holding': df_put['amt_holding_volume'].tolist(), '9 put delta_holding': put_deltas, '91 put iv': df_put['pct_implied_vol'].tolist() }) df_results.to_csv('../data/' + nameCode + '_holdings_' + evalDate + '.csv') ldgs = ['持仓量(看涨)', '持仓量(看跌)', '成交量(看涨)', '成交量(看跌)'] f3, ax3 = plt.subplots() p1 = ax3.bar(strikes, holding_call, width=wt, color=pu.colors[0]) p2 = ax3.bar(strikes1, holding_put, width=wt, color=pu.colors[1]) p3, = ax3.plot(strikes, trading_call, color=pu.colors[2], linestyle=pu.lines[2], linewidth=2) p4, = ax3.plot(strikes, trading_put, color=pu.colors[3], linestyle=pu.lines[3], linewidth=2) ax3.legend([p1, p2, p3, p4], ldgs, bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=4, mode="expand", borderaxespad=0., frameon=False) ax3.spines['top'].set_visible(False) ax3.spines['right'].set_visible(False) ax3.yaxis.set_ticks_position('left') ax3.xaxis.set_ticks_position('bottom') f3.set_size_inches((12, 8)) f3.savefig('../data/' + nameCode + '_holdings_' + evalDate + '.png', dpi=300, format='png', bbox_inches='tight')