def __init__(self, df_index=None, df_future_c1=None, df_future_all=None): if df_index is not None: self.df_base = df_index self.base = BaseInstrument(df_index) else: self.df_base = df_future_c1 self.base = BaseFutureCoutinuous( df_future_c1=df_future_c1, df_futures_all_daily=df_future_all) self.base.init() self.account = BaseAccount(c.Util.BILLION * 10) self._prepare_data() self.leverage = 0.75 # Will be multiplied to delta equivalent position self.rf = 0.03 self.slippage_date = 1 / 1000.0 self.hedge_multiplier = 1 self.hold_unit = 0 self.target_option = None self.cd_model = 'ww' # Delta调仓模型 self.delta_criterian = 0.1 # 固定delta变化值调仓条件 self.delta_last_rebalanced = 0.0 self.ttm = 50 # 期权固定期限 self.k = 1.1 # 期权行权价比率 self.H = None self.delta_upper_bound = 0.99 self.flag_fix_ttm = True self.rho = 0.01
def __init__(self, df_metrics, df_baseindex=None, cd_strategy='naked_put', id_baseindex=c.Util.STR_INDEX_300SH, cd_marutity_days=3): self.start_date = df_metrics[c.Util.DT_DATE].values[0] self.end_date = df_metrics[c.Util.DT_DATE].values[-1] if df_baseindex is None: df_baseindex = get_data.get_index_mktdata(self.start_date, self.end_date, c.Util.STR_INDEX_300SH) self.min_holding = 20 self.init_fund = c.Util.BILLION self.slippage = 0 self.m = 1 # 期权notional倍数 if cd_strategy == 'short_straddle': self.m = 0.5 self.moneyness_rank = -4 self.nbr_maturity = 0 self.cd_trade_price = c.CdTradePrice.VOLUME_WEIGHTED self.account = BaseAccount(init_fund=c.Util.BILLION, leverage=1.0, rf=0.03) self.optionset = BaseOptionSet(df_metrics) self.optionset.init() self.index = BaseInstrument(df_baseindex) self.index.init() self.cd_strategy = cd_strategy self.cd_maturity_days = cd_marutity_days self.init_index = self.index.mktprice_close()
def init(self): df_future_histvol = self.df_f_c1.copy() df_future_histvol['amt_hv'] = histvol.hist_vol( df_future_histvol[c.Util.AMT_CLOSE], n=self.n_hv) self.dt_start = max(self.df_f_c1[c.Util.DT_DATE].values[0], self.df_metrics[c.Util.DT_DATE].values[0]) self.end_date = min(self.df_f_c1[c.Util.DT_DATE].values[-1], self.df_metrics[c.Util.DT_DATE].values[-1]) self.df_metrics = self.df_metrics[ self.df_metrics[c.Util.DT_DATE] >= self.dt_start].reset_index( drop=True) self.df_f_c1 = self.df_f_c1[ self.df_f_c1[c.Util.DT_DATE] >= self.dt_start].reset_index( drop=True) self.df_f_all = self.df_f_all[ self.df_f_all[c.Util.DT_DATE] >= self.dt_start].reset_index( drop=True) self.df_vol = pd.merge(self.df_vol, df_future_histvol[[c.Util.DT_DATE, 'amt_hv']], on=c.Util.DT_DATE).set_index(c.Util.DT_DATE) self.optionset = BaseOptionSet(self.df_metrics) self.optionset.init() self.hedging = SytheticOption(self.df_f_c1, rf=self.rf, df_futures_all_daily=self.df_f_all) self.hedging.init() self.hedging.amt_option = 1 / 1000 # 50ETF与IH点数之比 self.account = BaseAccount(init_fund=c.Util.BILLION, rf=self.rf) self.prepare_timing()
def setUpClass(cls): start_date = datetime.date(2017, 10, 1) end_date = datetime.date(2017, 11, 21) df_cf_minute = get_dzqh_cf_minute(start_date, end_date, 'if') df_cf = get_dzqh_cf_daily(start_date, end_date, 'if') cls.future = BaseFutureCoutinuous(df_cf_minute, df_cf, frequency=FrequentType.MINUTE) cls.future.init() cls.account = BaseAccount(Util.BILLION) cls.trading_desk = Trade()
def __init__(self,name_code, df_option, df_etf=None, df_future_all=None,df_index=None): self.name_code = name_code self.df_option = df_option self.df_etf = df_etf self.df_future_all = df_future_all self.df_index = df_index self.rf = 0.03 self.m = 0.9 self.account = BaseAccount(c.Util.BILLION / 10,rf=self.rf) self.unit = 50 self.min_holding = 6 # 50ETF与IH到期日相差5天 self.nbr_maturity = 0 self.rank = 3 self.slippage = 0 self.aggregate_costs = 0.5/100.0 self.cd_price = c.CdTradePrice.CLOSE self.df_arbitrage_window = pd.DataFrame()
def __init__(self, df_c1, df_all, df_baseindex): self.slippage = 0 self.cd_trade_price = c.CdTradePrice.VOLUME_WEIGHTED dt_start = max(df_baseindex[c.Util.DT_DATE].values[0], df_c1[c.Util.DT_DATE].values[0]) self.end_date = min(df_baseindex[c.Util.DT_DATE].values[-1], df_c1[c.Util.DT_DATE].values[-1]) df_baseindex = df_baseindex[ df_baseindex[c.Util.DT_DATE] >= dt_start].reset_index(drop=True) df_c1 = df_c1[df_c1[c.Util.DT_DATE] >= dt_start].reset_index(drop=True) df_all = df_all[df_all[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) self.invst_portfolio = BaseFutureCoutinuous( df_c1, df_futures_all_daily=df_all) # e.g., top 50 low volatility index self.invst_portfolio.init() self.index = BaseInstrument(df_baseindex) self.index.init() self.account = BaseAccount(init_fund=c.Util.BILLION, leverage=1.0, rf=0.03)
def __init__(self, start_date, end_date): self.ttm = 30 self.buywrite = BuyWrite.BUY self.fund = Util.BILLION self.invest_underlying_ratio = 0.7 # self.invest_underlying_ratio = 1 self.slippage = 2 self.start_date = start_date self.end_date = end_date hist_date = start_date - datetime.timedelta(days=40) df_future_c1 = get_dzqh_cf_c1_minute(start_date, end_date, 'if') df_future_c1_daily = get_dzqh_cf_c1_daily(hist_date, end_date, 'if') df_futures_all_daily = get_dzqh_cf_daily( start_date, end_date, 'if') # daily data of all future contracts df_index = get_index_mktdata( start_date, end_date, 'index_300sh') # daily data of underlying index df_index = df_index[df_index[Util.DT_DATE].isin( Util.DZQH_CF_DATA_MISSING_DATES) == False].reset_index(drop=True) # df_index.to_csv('df_index.csv') self.trade_dates = sorted(df_future_c1_daily[Util.DT_DATE].unique()) self.df_vol_1m = Histvol.hist_vol(df_future_c1_daily) # df_parkinson_1m = Histvol.parkinson_number(df_future_c1_daily) self.df_garman_klass = Histvol.garman_klass(df_future_c1_daily) # df_hist_vol = self.df_vol_1m.join(self.df_garman_klass, how='left') # df_hist_vol.to_csv('../../data/df_hist_vol.csv') self.underlying = BaseInstrument(df_data=df_index) self.underlying.init() self.synthetic_option = SytheticOption( df_c1_data=df_future_c1, # df_c1_daily=df_future_c1_daily, df_futures_all_daily=df_futures_all_daily, df_index_daily=df_index) self.synthetic_option.init() self.account = BaseAccount(self.fund, leverage=20.0, rf=0.0) self.trading_desk = Trade() self.init_spot = self.synthetic_option.underlying_state_daily[ Util.AMT_CLOSE] self.df_analysis = pd.DataFrame()
d = max(d1, d2) print(d1, d2, d) df_metrics = df_metrics[df_metrics[c.Util.DT_DATE] >= d].reset_index(drop=True) df_c1 = df_future_c1_daily[ df_future_c1_daily[c.Util.DT_DATE] >= d].reset_index(drop=True) optionset = BaseOptionSet(df_metrics) optionset.init() d1 = optionset.eval_date df_c1 = df_c1.rename(columns={c.Util.ID_INSTRUMENT: 'id_future'}) df_c1.loc[:, c.Util.ID_INSTRUMENT] = name_code hedging = SytheticOption(df_c1, frequency=c.FrequentType.DAILY) hedging.init() account = BaseAccount(init_fund=c.Util.BILLION, leverage=1.0, rf=0.03) maturity1 = optionset.select_maturity_date(nbr_maturity=0, min_holding=15) empty_position = True unit_p = None unit_c = None atm_strike = None buy_write = c.BuyWrite.WRITE print(optionset.eval_date, hedging.eval_date) while optionset.eval_date <= end_date: if account.cash <= 0: break if maturity1 > end_date: # Final close out all. close_out_orders = account.creat_close_out_order() for order in close_out_orders: execution_record = account.dict_holding[ order.id_instrument].execute_order( order,
for moneyness in [0, -1, -2, -3, -4]: # for moneyness in [-1, -2, -3]: # for moneyness in [-3]: dict_annualized_yield = {'m': moneyness} dict_annualized_volatility = {'m': moneyness} dict_max_drawdown = {'m': moneyness} dict_sharpe_ratio = {'m': moneyness} dict_pct_option_amt = {'m': moneyness} # for target_delta in [-0.1,-0.2,-0.3,-0.4]: for target_delta in [None]: option_amt = [] optionset = BaseOptionSet(df_metrics) optionset.init() underlying = BaseInstrument(df_underlying) underlying.init() account = BaseAccount(init_fund=10000000, leverage=1.0, rf=0.03) """ init open position """ unit_underlying = np.floor(pct_underlying_invest * account.cash / underlying.mktprice_close() / underlying.multiplier()) order_underlying = account.create_trade_order(underlying, c.LongShort.LONG, unit_underlying) record_underlying = underlying.execute_order(order_underlying, slippage=slippage) account.add_record(record_underlying, underlying) maturity1 = optionset.select_maturity_date(nbr_maturity=nbr_maturity, min_holding=min_holding) list_atm_call, list_atm_put = optionset.get_options_list_by_moneyness_mthd1( moneyness, maturity1) if list_atm_put is None:
df_vol_1m = Histvol.hist_vol(df_future_c1_daily) # df_parkinson_1m = Histvol.parkinson_number(df_future_c1_daily) # df_garman_klass = Histvol.garman_klass(df_future_c1_daily) # df_hist_vol = df_vol_1m.join(df_parkinson_1m, how='left') # df_hist_vol = df_hist_vol.join(df_garman_klass, how='left') df_future_c1_daily = df_future_c1_daily[ df_future_c1_daily[Util.DT_DATE] >= start_date].reset_index(drop=True) synthetic_option = SytheticOption(df_c1_minute=df_future_c1, df_c1_daily=df_future_c1_daily, df_futures_all_daily=df_futures_all_daily, df_index_daily=df_index) synthetic_option.init() underlying = BaseInstrument(df_data=df_index) underlying.init() account = BaseAccount(2 * Util.BILLION, leverage=10.0, rf=0.0) trading_desk = Trade() ##################################################################### # """ Init position """ strike = synthetic_option.underlying_index_state_daily[Util.AMT_CLOSE] dt_maturity = synthetic_option.eval_date + datetime.timedelta(days=30) vol = 0.2 Option = EuropeanOption(strike, dt_maturity, OptionType.PUT) delta = synthetic_option.get_black_delta(Option, vol) id_future = synthetic_option.current_state[Util.ID_INSTRUMENT] synthetic_unit = synthetic_option.get_synthetic_unit(delta) if synthetic_unit > 0: long_short = LongShort.LONG else: long_short = LongShort.SHORT
from back_test.model.base_future import BaseFuture from back_test.model.base_future_coutinuous import BaseFutureCoutinuous from back_test.model.constant import Util, FrequentType, LongShort import data_access.get_data as data start_date = datetime.date(2017, 6, 1) end_date = datetime.date(2017, 12, 1) df_cf = data.get_mktdata_future_daily(start_date, end_date, 'ih') df_cf1 = data.get_mktdata_future_c1_daily(start_date, end_date, 'ih') future = BaseFuture(df_cf1) future.init() futureset = BaseFutureSet(df_cf) futureset.init() account = BaseAccount(Util.MILLION * 10, rf=0) print('Future Set Test') contracts = futureset.eligible_futures c_1 = futureset.select_higher_volume(contracts) order = account.create_trade_order(c_1, LongShort.LONG, 10) record = c_1.execute_order(order) account.add_record(record, c_1) while futureset.has_next(): if not c_1.has_next(): print(futureset.eval_date) order = account.create_trade_order(c_1, LongShort.SHORT, 10) record = c_1.execute_order(order) account.add_record(record, c_1) contracts = futureset.eligible_futures
print(reg.rsquared_adj) # a_beta = reg.params['BETA_F'] # a_smb = reg.params['SMB_F'] # a_hc = reg.params['HC_F'] a_beta = 0.744710 a_smb = 0.399662 a_hc = 0.244484 init_stock = Util.BILLION / 100 data_hedge = data.iloc[1:,:].copy() # data_hedge = data_hedge[['index_top5', '000300.SH', '000905.SH', '000016.SH', 'HC.SHF']] data_hedge = data_hedge[['index_top5', 'IF.CFE', 'IC.CFE', 'IH.CFE', 'HC.SHF']] init_closes = np.array(data_hedge.iloc[0]) weights = np.array([1, -a_beta, -a_smb, a_smb, -a_hc]) init_mktvalues = weights*init_stock init_capital = sum(np.array([1, a_beta*0.2, a_smb*0.2, a_smb*0.2, a_hc*0.2])*init_stock) # 五倍杠杆 units = init_mktvalues/init_closes print(units) print(np.array(data_hedge.iloc[0])) print(np.array(data_hedge.iloc[1])) data_hedge['hedged_mkv'] = data_hedge.apply(lambda x:sum(x*units),axis=1) data_hedge['pnl'] = data_hedge['hedged_mkv'] -data_hedge.iloc[0]['hedged_mkv'] data_hedge['NPV'] = (data_hedge['pnl']+init_capital)/init_capital account = BaseAccount(init_capital,rf=0.0) res = account.get_netvalue_analysis(data_hedge['NPV']) print(res) data_hedge.to_csv('data/result_hedged_port.csv')
def __init__(self, df_baseindex, df_option_metrics, df_c1=None, df_all=None, cd_direction_timing='ma', cd_strategy='bull_spread', cd_volatility='close_std', cd_short_ma='ma_5', cd_long_ma='ma_60', cd_std='std_10'): self.min_holding = 20 self.slippage = 0 self.nbr_maturity = 0 self.moneyness_rank = 0 self.cd_trade_price = c.CdTradePrice.VOLUME_WEIGHTED # self.cd_trade_price = c.CdTradePrice.CLOSE if df_c1 is None: dt_start = max(df_option_metrics[c.Util.DT_DATE].values[0], df_baseindex[c.Util.DT_DATE].values[0]) self.end_date = min(df_option_metrics[c.Util.DT_DATE].values[-1], df_baseindex[c.Util.DT_DATE].values[-1]) df_metrics = df_option_metrics[ df_option_metrics[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) df_baseindex = df_baseindex[ df_baseindex[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) self.invst_portfolio = BaseInstrument( df_baseindex) # e.g., top 50 low volatility index self.invst_portfolio.init() else: dt_start = max(df_option_metrics[c.Util.DT_DATE].values[0], df_baseindex[c.Util.DT_DATE].values[0], df_c1[c.Util.DT_DATE].values[0]) self.end_date = min(df_option_metrics[c.Util.DT_DATE].values[-1], df_baseindex[c.Util.DT_DATE].values[-1], df_c1[c.Util.DT_DATE].values[-1]) df_metrics = df_option_metrics[ df_option_metrics[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) df_baseindex = df_baseindex[ df_baseindex[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) df_c1 = df_c1[df_c1[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) df_all = df_all[df_all[c.Util.DT_DATE] >= dt_start].reset_index( drop=True) self.invst_portfolio = BaseFutureCoutinuous( df_c1, df_futures_all_daily=df_all ) # e.g., top 50 low volatility index self.invst_portfolio.init() self.optionset = BaseOptionSet(df_metrics) self.index = BaseInstrument(df_baseindex) self.optionset.init() self.index.init() self.account = BaseAccount(init_fund=c.Util.BILLION, leverage=1.0, rf=0.03) self.prepare_timing(df_baseindex) self.cd_direction_timing = cd_direction_timing self.cd_strategy = cd_strategy self.cd_volatility = cd_volatility self.cd_short_ma = cd_short_ma self.cd_long_ma = cd_long_ma self.cd_std = cd_std self.dict_strategy = {} self.nbr_timing = 0 self.nbr_stop_loss = 0 self.nvp_adjustment = 0 self.sl_npv_high_point = 1.0 self.strategy_pause = False
start_date = datetime.date(2017, 10, 1) end_date = datetime.date(2017, 11, 21) # df_option_metrics = get_50option_mktdata(start_date, end_date) # df_index_metrics = get_index_mktdata(start_date, end_date, 'index_50etf') # option_set = BaseOptionSet(df_option_metrics) # option_set.init() # index = BaseInstrument(df_index_metrics) df_cf_minute = get_dzqh_cf_minute(start_date, end_date, 'if') df_cf = get_dzqh_cf_daily(start_date, end_date, 'if') future = BaseFutureCoutinuous(df_cf_minute, df_cf, frequency=FrequentType.MINUTE) future.init() account = BaseAccount(Util.BILLION) trading_desk = Trade() # while future.has_next(): # for option in option_set.eligible_options: # TODO: Create and execute order could be implemented in base_product class. order = account.create_trade_order(future, TradeType.OPEN_LONG, 10) execution_res = future.execute_order(order) account.add_record(execution_res, future) trading_desk.add_pending_order(order) future.next() order = account.create_trade_order(future, TradeType.OPEN_SHORT, 5) execution_res = future.execute_order(order) account.add_record(execution_res, future) trading_desk.add_pending_order(order) future.next()