コード例 #1
0
 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()
コード例 #2
0
    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()
コード例 #3
0
# end_date = datetime.date(2016, 12, 31)
# start_date = datetime.date(2017, 1, 1)
# end_date = datetime.date(2017, 12, 31)
start_date = datetime.date(2016, 2, 1)
end_date = datetime.date(2017, 1, 31)
# start_date = datetime.date(2015, 3, 1)
# end_date = datetime.date(2018, 8, 20)
close_out_date = end_date
min_holding = 15
nbr_maturity = 1
# nbr_maturity = 0
slippage = 0
pct_underlying_invest = 0.7
res = {}
df_metrics = get_data.get_50option_mktdata(start_date, end_date)
df_underlying = get_data.get_index_mktdata(start_date, end_date,
                                           c.Util.STR_INDEX_50ETF)
# df_underlying.to_csv('../accounts_data/df_underlying.csv')


def get_option_unit(option_put: BaseOption, underlying_value: float,
                    target_delta):
    if target_delta is None:
        unit = np.floor(underlying_value / option_put.strike() /
                        option_put.multiplier())  # 期权名义本金等于标的市值
    else:
        delta = option_put.get_delta(option_put.get_implied_vol())
        unit = np.floor(target_delta * underlying_value / delta /
                        option_put.multiplier())  # 根据目标delta值
    return unit

コード例 #4
0
end_date = datetime.date(2018, 8, 8)
dt_histvol = start_date - datetime.timedelta(days=40)
min_holding = 18

""" commodity option """
# name_code = name_code_option = c.Util.STR_M
# df_metrics = get_data.get_comoption_mktdata(start_date, end_date,name_code)
# df_future_c1_daily = get_data.get_future_c1_by_option_daily(dt_histvol, end_date, name_code, min_holding)

""" 50ETF option """
name_code = c.Util.STR_IH
name_code_option = c.Util.STR_50ETF
df_metrics = get_data.get_50option_mktdata(start_date, end_date)
df_future_c1_daily = get_data.get_dzqh_cf_c1_daily(dt_histvol, end_date, name_code)
name_code_index = c.Util.STR_INDEX_50SH
df_index = get_data.get_index_mktdata(dt_histvol,end_date,name_code_index)
""" 历史波动率 """
# df_vol_1m = Histvol.hist_vol(df_index)
# df_parkinson_1m = Histvol.parkinson_number(df_future_c1_daily)
# df_garman_klass = Histvol.garman_klass(df_future_c1_daily)
# df_data = df_future_c1_daily.join(df_vol_1m,on=c.Util.DT_DATE,how='left')
# df_data = df_data.join(df_garman_klass,on=c.Util.DT_DATE,how='left')
# df_data = df_data.join(df_parkinson_1m,on=c.Util.DT_DATE,how='left')
# df_data = df_data.dropna()

# df_data = df_future_c1_daily
""" iv premium """
# df_iv = get_data.get_iv_by_moneyness(start_date,end_date,name_code_option)
#
# df_iv['selected_date'] = df_iv[c.Util.DT_MATURITY].apply(lambda x:x-datetime.timedelta(days=30))
# df_iv = df_iv[df_iv['selected_date']==df_iv[c.Util.DT_DATE]]
コード例 #5
0
        res = am.fit(disp='off')
        print(res.summary())
        forecasts = res.forecast(horizon=5)
        print(forecasts.variance.iloc[-3:]**0.5 * math.sqrt(252) / 100)
        print(self.df_data.iloc[-3:])

    def recursive_forecast_generation(self):
        am = arch_model(self.returns, vol='Garch', p=1, q=1, dist='t')
        end_loc = 100  # 基于一百个数据预测
        max_loc = len(self.returns.index) - 1
        forecasts = {}
        for i in range(max_loc - end_loc):
            # sys.stdout.write('.')
            sys.stdout.flush()
            res = am.fit(last_obs=i + end_loc, disp='off')
            temp = res.forecast(horizon=3).variance**0.5 * math.sqrt(252) / 100
            fcast = temp.iloc[i + end_loc - 1]
            fcast['hv_20'] = self.df_data.iloc[i + end_loc]['hv_20']
            fcast['iv'] = self.df_data.iloc[i + end_loc][Util.PCT_IMPLIED_VOL]
            forecasts[fcast.name] = fcast
        print()
        print(pd.DataFrame(forecasts).T)


df_c1 = get_index_mktdata(datetime.date(2018, 1,
                                        1), datetime.date(2018, 12, 31),
                          Util.STR_INDEX_300SH)[[Util.DT_DATE, Util.AMT_CLOSE]]
arch = Arch(df_c1)

arch.recursive_forecast_generation()
コード例 #6
0
            """按当日价格调整保证金,计算投资组合盯市价值"""
            bkt_account.mkm_update_portfolio(evalDate,self.portfolio)
            # print(evalDate, bkt_optionset.eval_date, ' , ', bkt_account.npv, bkt_account.mtm_long_positions)



"""Back Test Settings"""
# start_date = datetime.date(2015, 3, 1)
start_date = datetime.date(2017, 10, 1)
end_date = datetime.date(2018, 1, 21)


"""Collect Mkt Date"""

df_option_metrics = get_50option_mktdata(start_date, end_date)
df_index_metrics = get_index_mktdata(start_date,end_date,'index_50etf')
"""Run Backtest"""


bkt_strategy = BktStrategyCollar(df_option_metrics, df_index_metrics)
bkt_strategy.set_min_holding_days(8)


df_index_ma = bkt_strategy.get_moving_average_signal(get_index_ma(start_date,end_date,'index_50etf'))
df_vix_boll = bkt_strategy.get_bollinger_signal(get_index_ma(start_date,end_date,'index_cvix'),cd_long='60')
df_index_boll = bkt_strategy.get_bollinger_signal(get_index_ma(start_date,end_date,'index_50etf'),cd_long='60')
df_iv = bkt_strategy.get_bollinger_signal_calculate(get_pciv_ratio(end_date),start_date)
# df_iv = bkt_strategy.get_percentile_signal(get_put_call_iv(end_date),start_date)

bkt_strategy.set_index_ma(df_index_ma)
bkt_strategy.set_index_boll(df_index_boll)
コード例 #7
0
from back_test.model.base_account import BaseAccount
from back_test.model.base_instrument import BaseInstrument
from back_test.model.constant import Util, OptionType, LongShort, ExecuteType
from back_test.model.trade import Trade
from data_access.get_data import get_dzqh_cf_daily, get_dzqh_cf_c1_daily, \
    get_dzqh_cf_c1_minute, get_index_mktdata
from OptionStrategyLib.VolatilityModel.historical_volatility import historical_volatility_model as Histvol

start_date = datetime.date(2018, 4, 1)
end_date = datetime.date(2018, 6, 1)
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_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()
コード例 #8
0
import numpy as np
from OptionStrategyLib.VolatilityModel.kernel_density import kde_sklearn
from Utilities.PlotUtil import PlotUtil
from scipy import stats

pu = PlotUtil()
start_date = datetime.date(2010, 1, 1)
end_date = datetime.date.today()
dt_histvol = start_date
""" 50ETF option """
name_code = c.Util.STR_CU
name_code_index = c.Util.STR_INDEX_50SH
# df_future_c1_daily = get_data.get_dzqh_cf_c1_daily(dt_histvol, end_date, name_code)
df_future_c1_daily = get_data.get_mktdata_future_c1_daily(
    dt_histvol, end_date, name_code)
df_index = get_data.get_index_mktdata(start_date, end_date, name_code_index)

df_future_c1_daily[c.Util.AMT_YIELD] = np.log(
    df_future_c1_daily[c.Util.AMT_CLOSE]).diff(periods=20)
df_index[c.Util.AMT_YIELD] = np.log(
    df_index[c.Util.AMT_CLOSE]).diff(periods=20)
df_future_c1_daily = df_future_c1_daily.dropna()
df_index = df_index.dropna()

r_future = np.array(df_future_c1_daily[c.Util.AMT_YIELD])
r_index = np.array(df_index[c.Util.AMT_YIELD])
s = np.random.normal(0, 0.15, 1000)

m1 = np.mean(r_future)
sk1 = stats.skew(r_future)
std1 = np.std(r_future)
コード例 #9
0
from OptionStrategyLib.OptionStrategy.protective_put.HedgeIndexByOptions import HedgeIndexByOptions
import back_test.model.constant as c
import datetime
import pandas as pd
from data_access import get_data
from Utilities.PlotUtil import PlotUtil
import matplotlib.pyplot as plt

start_date = datetime.date(2015, 4, 16)
end_date = datetime.date(2018, 11, 1)
dt_histvol = start_date - datetime.timedelta(days=500)

df_metrics = get_data.get_50option_mktdata(start_date, end_date)
df_index = get_data.get_index_mktdata(dt_histvol, end_date,
                                      c.Util.STR_INDEX_50ETF)
df_1 = get_data.get_index_mktdata(dt_histvol, end_date, c.Util.STR_INDEX_50SH)
df_c1 = get_data.get_mktdata_future_c1_daily(dt_histvol, end_date,
                                             c.Util.STR_IH)
df_all = get_data.get_mktdata_future_daily(dt_histvol, end_date, c.Util.STR_IH)
df_1.to_csv('50sh.csv')
df_c1.to_csv('ih.csv')
cd_direction_timing = 'ma'
cd_strategy = 'bull_spread'
cd_volatility = 'close_std'
cd_short_ma = 'ma_3'
cd_long_ma = 'ma_20'
cd_std = 'std_10'

df_res = pd.DataFrame()

hedging1 = HedgeIndexByOptions(df_index,
コード例 #10
0
start_date = datetime.date(2015, 2, 1)
# start_date = datetime.date(2017, 2, 1)
end_date = datetime.date(2018, 8, 31)
d1 = start_date
min_holding = 15
nbr_maturity = 1
slippage = 0
pct_underlying_invest = 1.0

##############
alpha = 0.0
moneyness = -5
#################

df_metrics = get_data.get_50option_mktdata(start_date, end_date)
df_option_underlying = get_data.get_index_mktdata(start_date, end_date,
                                                  c.Util.STR_INDEX_50ETF)
df_underlying = get_data.get_index_mktdata(start_date, end_date,
                                           c.Util.STR_INDEX_300SH_TOTAL_RETURN)

calendar = c.Calendar(sorted(df_underlying[c.Util.DT_DATE].unique()))
pu = PlotUtil()

df = pd.DataFrame()
#
d1 = calendar.firstBusinessDayNextMonth(d1)
d2 = d1 + datetime.timedelta(days=365)
while d2 <= end_date:
    print(d1)
    df_metrics_1 = df_metrics[(df_metrics[c.Util.DT_DATE] >= d1) & (
        df_metrics[c.Util.DT_DATE] <= d2)].reset_index(drop=True)
    df_underlying_1 = df_underlying[(df_underlying[c.Util.DT_DATE] >= d1) & (
コード例 #11
0
# df_res = pd.DataFrame()
# for cd_strategy in ['short_call','short_put','short_straddle']:
#     naked_short = NakedShort(df_metrics,df_baseindex,cd_strategy=cd_strategy,cd_marutity_days=5)
#     naked_short.moneyness_rank=-2
#     naked_short.back_test()
#     naked_short.account.account.to_csv('../../accounts_data/naked_short_account_'+ str(cd_strategy) +'_' + str(naked_short.moneyness_rank) + '_2015.csv')
#     naked_short.account.trade_records.to_csv('../../accounts_data/naked_short_records_' + str(cd_strategy) +'_' + str(naked_short.moneyness_rank) + '_2015.csv')
#     res = naked_short.account.analysis()
#     print(res)
#     df_res[cd_strategy] = res
# df_res.to_csv('../../accounts_data/res_cd_strategy_' + str(naked_short.moneyness_rank) + '_2015.csv')

df_metrics = get_data.get_50option_mktdata(datetime.date(2015, 2, 9),
                                           datetime.date(2018, 11, 20))
df_baseindex = get_data.get_index_mktdata(datetime.date(2015, 2, 9),
                                          datetime.date(2018, 11, 20),
                                          c.Util.STR_INDEX_50SH)

df_res = pd.DataFrame()
for cd_strategy in ['short_call', 'short_put', 'short_straddle']:
    naked_short = NakedShort(df_metrics,
                             df_baseindex,
                             cd_strategy=cd_strategy,
                             cd_marutity_days=0)
    naked_short.moneyness_rank = -4
    naked_short.back_test()
    naked_short.account.account.to_csv(
        '../../accounts_data/naked_short_account_' + str(cd_strategy) + '_' +
        str(naked_short.moneyness_rank) + '_2015.csv')
    naked_short.account.trade_records.to_csv(
        '../../accounts_data/naked_short_records_' + str(cd_strategy) + '_' +
コード例 #12
0
    df_res.to_excel(writer, name_code)
    dt_end = df_metrics[c.Util.DT_DATE].unique()[-1]
    dt_yesterday = df_metrics[c.Util.DT_DATE].unique()[-2]
    print('Finished ', name_code, dt_end, dt_yesterday)
    # df_holdings = trade_volume(dt_end, dt_yesterday, df_metrics, name_code, core_id,df_res)
    # df_holdings.to_excel(writer, 'holdings_'+name_code)

name_codes = [
    c.Util.STR_CF, c.Util.STR_C, c.Util.STR_RU, c.Util.STR_M, c.Util.STR_CU,
    c.Util.STR_SR
]

dt_start = datetime.date(2000, 1, 1)
for (idx1, name_code) in enumerate(name_codes):
    print(name_code)
    df_res = pd.DataFrame()
    df_future_c1_daily = get_data.get_gc_future_c1_daily(
        dt_start, end_date, name_code)
    df_future_c1_daily = hist_vol1(
        df_future_c1_daily[[c.Util.DT_DATE, c.Util.AMT_CLOSE]])
    df_future_c1_daily = df_future_c1_daily.sort_values(by=c.Util.DT_DATE,
                                                        ascending=False)
    df_future_c1_daily.to_excel(writer, name_code + '_hv')

df_50etf = get_data.get_index_mktdata(dt_start, end_date, 'index_50etf')
df_50etf = hist_vol1(df_50etf[[c.Util.DT_DATE, c.Util.AMT_CLOSE]])
df_50etf = df_50etf.sort_values(by=c.Util.DT_DATE, ascending=False)
df_50etf.to_excel(writer, 'index_50etf' + '_hv')

writer.save()