コード例 #1
0
ファイル: compass.py プロジェクト: chenzhenhu-yeah/nature
def implied_dist(date, basic, gap):
    try:
        fn = get_dss() + 'opt/' + date[:7] + '_greeks.csv'
        df = pd.read_csv(fn)
        df['date'] = df.Localtime.str.slice(0, 10)
        df = df[df.date == date]
        df = df[df.Instrument.str.slice(0, len(basic)) == basic]

        strike_list = []
        for i, row in df.iterrows():
            strike_list.append(get_contract(row.Instrument).strike)

        atm = int(
            round(
                round(min(strike_list) * (100 / gap) / 1E4, 2) * 1E4 /
                (100 / gap), 0))  # 获得平值

        strike_list = range(atm, max(strike_list) + 1, gap)
        # print( [*strike_list] )

        if basic[:2] == 'IO':
            symbol_obj = 'IF' + basic[2:]
        else:
            symbol_obj = basic

        fn = get_dss() + 'fut/bar/min5_' + symbol_obj + '.csv'
        df = pd.read_csv(fn)
        df = df[(df.date == date) & (df.time == '14:54:00')]
        obj_close = df.iat[0, 5]
        # print(obj_close)

        c_list = []
        p_list = []
        for strike in strike_list:
            # print(strike)
            symbol_c = basic + get_contract(basic).opt_flag_C + str(strike)
            fn = get_dss() + 'fut/bar/min5_' + symbol_c + '.csv'
            df = pd.read_csv(fn)
            df = df[(df.date == date) & (df.time == '14:54:00')]
            c_list.append(df.iat[0, 5])

            symbol_p = basic + get_contract(basic).opt_flag_P + str(strike)
            fn = get_dss() + 'fut/bar/min5_' + symbol_p + '.csv'
            df = pd.read_csv(fn)
            df = df[(df.date == date) & (df.time == '14:54:00')]
            # print(date, symbol_p, df.tail())
            p_list.append(df.iat[0, 5])

        prop_list = []
        n = len(strike_list)
        for i in range(1, n - 1):
            if strike_list[i] < obj_close:
                prop_list.append(
                    int(100 * (p_list[i - 1] - 2 * p_list[i] + p_list[i + 1]) /
                        gap))
            else:
                prop_list.append(
                    int(100 * (c_list[i - 1] - 2 * c_list[i] + c_list[i + 1]) /
                        gap))

        df = pd.DataFrame([])
        df['strike'] = strike_list[1:n - 1]
        df['strike'] = df['strike'].astype('str')
        df['value'] = prop_list
        df = df.set_index('strike')
        df.index.name = basic + '_implied_dist'

        return df
    except Exception as e:
        s = traceback.format_exc()
        # to_log(s)
        to_log(date + ' ' + basic +
               ' 数据缺失 in implied_dist from file compass.py')

        return None
コード例 #2
0
ファイル: compass.py プロジェクト: chenzhenhu-yeah/nature
def df_atm_plus_obj_min5(basic, date, gap, shift=0):
    """
    选取每天的平值合约,按要求组装包含close_obj的df
    返回的df包括以下字段:dt, symbol, close, close_obj
    """
    try:
        r_c = []
        r_p = []

        if basic[:2] == 'IO':
            symbol_obj = 'IF' + basic[2:]
        else:
            symbol_obj = basic

        fn = get_dss() + 'fut/bar/min5_' + symbol_obj + '.csv'
        df_obj = pd.read_csv(fn)
        df_obj = df_obj[(df_obj.date == date) & (df_obj.time <= '14:54:00')]
        df_obj = df_obj.reset_index()
        # print(df_obj.head())

        if df_obj.empty:
            pass
        else:
            close_obj = df_obj.iloc[-1, :].close
            atm = int(
                round(
                    round(close_obj * (100 / gap) / 1E4, 2) * 1E4 /
                    (100 / gap), 0))  # 获得平值
            # if date == '2020-11-10':
            #     print(basic, '-------------------------', close_obj, atm )

            symbol_c = basic + get_contract(basic).opt_flag_C + str(
                atm + shift * gap)
            fn = get_dss() + 'fut/bar/min5_' + symbol_c + '.csv'
            df_atm_c = pd.read_csv(fn)
            df_atm_c = df_atm_c[(df_atm_c.date == date)
                                & (df_atm_c.time <= '14:54:00')]

            symbol_p = basic + get_contract(basic).opt_flag_P + str(
                atm + shift * gap)
            fn = get_dss() + 'fut/bar/min5_' + symbol_p + '.csv'
            df_atm_p = pd.read_csv(fn)
            df_atm_p = df_atm_p[(df_atm_p.date == date)
                                & (df_atm_p.time <= '14:54:00')]

            if df_atm_c.empty or df_atm_p.empty:
                pass
            else:
                for i, row in df_obj.iterrows():
                    rec = df_atm_c.iloc[i, :]
                    r_c.append([
                        row.date + ' ' + row.time, symbol_c, rec.close,
                        row.close
                    ])
                    rec = df_atm_p.iloc[i, :]
                    r_p.append([
                        row.date + ' ' + row.time, symbol_p, rec.close,
                        row.close
                    ])

        cols = ['dt', 'symbol', 'close', 'close_obj']
        df_c = pd.DataFrame(r_c, columns=cols)
        df_p = pd.DataFrame(r_p, columns=cols)
        df_c.index.name = basic + '_iv_c'
        df_p.index.name = basic + '_iv_p'
        # print(df_c.tail())
        # print(df_p.tail())

        return df_c, df_p
    except Exception as e:
        s = traceback.format_exc()
        to_log(s)

        return None, None
コード例 #3
0
ファイル: compass.py プロジェクト: chenzhenhu-yeah/nature
def df_smile(date, basic):
    try:
        fn = get_dss() + 'opt/' + date[:7] + '_greeks.csv'
        df = pd.read_csv(fn)
        df['date'] = df.Localtime.str.slice(0, 10)
        df = df[df.date == date]
        df = df[df.Instrument.str.slice(0, len(basic)) == basic]

        strike_list = []
        for i, row in df.iterrows():
            strike_list.append(get_contract(row.Instrument).strike)
        strike_list = sorted(list(set(strike_list)))
        # print(strike_list)

        if basic[:2] == 'IO':
            symbol_obj = 'IF' + basic[2:]
        else:
            symbol_obj = basic

        fn = get_dss() + 'fut/bar/min5_' + symbol_obj + '.csv'
        df = pd.read_csv(fn)
        df = df[(df.date == date) & (df.time == '14:54:00')]
        close_obj = df.iat[0, 5]
        # print(obj_close)

        r_c = []
        r_p = []
        strike_c = []
        strike_p = []
        for strike in strike_list:
            # print(strike)
            symbol_c = basic + get_contract(basic).opt_flag_C + str(strike)
            fn = get_dss() + 'fut/bar/min5_' + symbol_c + '.csv'
            df = pd.read_csv(fn)
            df = df[(df.date == date) & (df.time == '14:54:00')]
            if df.empty:
                continue
            r_c.append([date, symbol_c, df.iat[0, 5], close_obj])
            strike_c.append(str(strike))

            symbol_p = basic + get_contract(basic).opt_flag_P + str(strike)
            fn = get_dss() + 'fut/bar/min5_' + symbol_p + '.csv'
            df = pd.read_csv(fn)
            df = df[(df.date == date) & (df.time == '14:54:00')]
            # print(date, symbol_p, df.tail())
            if df.empty:
                continue
            r_p.append([date, symbol_p, df.iat[0, 5], close_obj])
            strike_p.append(str(strike))

        df_c = pd.DataFrame(r_c,
                            columns=['dt', 'symbol', 'close', 'close_obj'])
        df_p = pd.DataFrame(r_p,
                            columns=['dt', 'symbol', 'close', 'close_obj'])
        # print(df_c)
        # print(df_p)

        df_c = df_iv(basic, df_c)
        df_p = df_iv(basic, df_p)

        # 去掉深度虚值的干扰项
        for i in [0, 1, 2]:
            df_c.iat[i, 0] = np.nan
            df_p.iat[-i - 1, 0] = np.nan

        df_c.index = strike_c
        df_c.index.name = date + '_smile_c'
        df_p.index = strike_p
        df_p.index.name = date + '_smile_p'

        # print(df_c)
        # print(df_p)
        return df_c, df_p

    except Exception as e:
        s = traceback.format_exc()
        to_log(s)

        return None, None
コード例 #4
0
def pandian_dali(today):
    dss = get_dss()

    # 加载品种
    config = open(dss + 'fut/cfg/config.json')
    setting = json.load(config)
    symbols = setting['symbols_dali']
    dali_symbol_list = symbols.split(',')

    # 读取value_dali文件
    fn_value = dss + 'fut/engine/value_dali.csv'
    if os.path.exists(fn_value):
        df_value = pd.read_csv(fn_value)
    else:
        return

    fn_param = dss + 'fut/engine/dali/signal_dali_param.csv'
    df_param = pd.read_csv(fn_param)
    df_param = df_param.set_index('pz')
    # print(df_param)

    r = []
    for symbol in dali_symbol_list:
        c = get_contract(symbol)
        pz = str(c.pz)
        df = df_value[df_value.pz == pz]
        # 获得该品种最近日期的一条记录,新品种必须事先维护一条记录!!!
        if len(df) > 0:
            rec = df.iloc[-1, :]
            capital = rec.capital
            date = rec.date
            # 跨年了
            if today[:4] == date[:4]:
                newyear_value = rec.newyear_value
            else:
                newyear_value = rec.cur_value  # 换年

        else:
            continue

        # 更新该品种的最新数据
        fn_signal = dss + 'fut/engine/dali/signal_dali_' + 'multi' + '_var_' + pz + '.csv'
        if os.path.exists(fn_signal):
            df = pd.read_csv(fn_signal)
            df = df[df.vtSymbol == symbol]
            rec = df.iloc[-1, :]
            # print(rec)

            cur_value = int(capital + rec.pnl_net)
            year_ratio = round(100 * (cur_value / newyear_value - 1), 2)
            net_pos = rec.unit
            multi_duo_list = eval(rec.price_duo_list)
            multi_kong_list = eval(rec.price_kong_list)

            active_price = (int(multi_duo_list[0]) +
                            int(multi_kong_list[0])) * 0.5

            margin = df_param.at[pz, 'fixed_size'] * active_price * float(
                c.size) * float(
                    c.margin) * (len(multi_duo_list) + len(multi_kong_list))
            risk = round(100 * (margin / capital), 2)

            r.append([
                today, pz, capital, cur_value, newyear_value, year_ratio,
                margin, risk, net_pos, multi_duo_list, multi_kong_list
            ])
            #print(r)
            #return

    df = pd.DataFrame(r)
    df.to_csv(fn_value, index=False, mode='a', header=None)
コード例 #5
0
ファイル: compass.py プロジェクト: chenzhenhu-yeah/nature
def df_atm_plus_obj_day(basic, date, gap, shift=0):
    """
    选取每天的平值合约,按要求组装包含close_obj的df
    返回的df包括以下字段:dt, symbol, close, close_obj
    """
    try:

        if basic[:2] == 'IO':
            symbol_obj = 'IF' + basic[2:]
        else:
            symbol_obj = basic

        fn = get_dss() + 'fut/bar/min5_' + symbol_obj + '.csv'
        df_obj = pd.read_csv(fn)
        date_list = sorted(list(set(df_obj.date)))
        date_list = [d for d in date_list if d <= date]
        # print(date_list)

        r_c = []
        r_p = []
        for date in date_list:
            df2 = df_obj[(df_obj.date == date) & (df_obj.time <= '14:54:00')]
            if df2.empty:
                print('df empty: ', basic, date)
                continue
            close_obj = df2.iloc[-1, :].close
            atm = int(
                round(
                    round(close_obj * (100 / gap) / 1E4, 2) * 1E4 /
                    (100 / gap), 0))  # 获得平值
            # if date == '2020-11-10':
            #     print(basic, '-------------------------', close_obj, atm )

            symbol_c = basic + get_contract(basic).opt_flag_C + str(
                atm + shift * gap)
            fn = get_dss() + 'fut/bar/min5_' + symbol_c + '.csv'
            df_atm_c = pd.read_csv(fn)
            df_atm_c = df_atm_c[(df_atm_c.date == date)
                                & (df_atm_c.time == '14:54:00')]

            symbol_p = basic + get_contract(basic).opt_flag_P + str(
                atm + shift * gap)
            fn = get_dss() + 'fut/bar/min5_' + symbol_p + '.csv'
            df_atm_p = pd.read_csv(fn)
            df_atm_p = df_atm_p[(df_atm_p.date == date)
                                & (df_atm_p.time == '14:54:00')]

            if df_atm_c.empty or df_atm_p.empty:
                pass
                # print('df empty: ', basic, date)
            else:
                rec = df_atm_c.iloc[0, :]
                r_c.append([date, symbol_c, rec.close, close_obj])
                rec = df_atm_p.iloc[0, :]
                r_p.append([date, symbol_p, rec.close, close_obj])

        cols = ['dt', 'symbol', 'close', 'close_obj']
        df_c = pd.DataFrame(r_c, columns=cols)
        df_p = pd.DataFrame(r_p, columns=cols)
        df_c.index.name = basic + '_iv_c'
        df_p.index.name = basic + '_iv_p'
        # print(df_c.tail())
        # print(df_p.tail())

        return df_c, df_p
    except Exception as e:
        s = traceback.format_exc()
        to_log(s)

        return None, None
コード例 #6
0
ファイル: iv_atm.py プロジェクト: chenzhenhu-yeah/nature
def calc_iv_atm():
    ''' 计算IO合约min5的iv值,保存在文件中'''

    now = datetime.now()
    # today = now.strftime('%Y-%m-%d %H:%M:%S')
    today = now.strftime('%Y-%m-%d')
    # today = '2020-07-09'

    fn = get_dss() + 'fut/cfg/opt_mature.csv'
    df2 = pd.read_csv(fn)
    df2 = df2[df2.pz == 'IO']
    df2 = df2[df2.flag == df2.flag]  # 筛选出不为空的记录
    df2 = df2[df2.mature >= today]  # 过期的合约就不要了
    df2 = df2.set_index('symbol')
    mature_dict = dict(df2.mature)
    print(mature_dict)
    # for symbol in mature_dict.keys():
    #     if mature_dict[symbol] < today:
    #         mature_dict.pop(symbol)
    #         break
    # print(mature_dict)

    cur_io = min(mature_dict.keys())
    cur_if = 'IF' + cur_io[2:]
    # print(cur_if)
    fn = get_dss() + 'fut/bar/day_' + cur_if + '.csv'
    df = pd.read_csv(fn)
    df = df[df.date == today]
    # print(df)
    if len(df) > 0:
        row = df.iloc[0, :]
        strike = row.open * 0.5 + row.close * 0.5
        strike = int(round(strike / 1E4, 2) * 1E4)
    else:
        return

    atm = str(strike)  # 获得平值
    print(atm)

    # for symbol in ['IO2007']:
    for symbol in mature_dict.keys():
        # print(symbol)
        # 取IF min5数据
        fn = get_dss() + 'fut/bar/min5_IF' + symbol[2:] + '.csv'
        if os.path.exists(fn) == False:
            continue
        df = pd.read_csv(fn)
        df = df[df.date == today]
        if len(df) == 0:
            continue

        df['obj'] = df['close']
        df = df.set_index(['date', 'time'])
        df_IF = df[['obj']]
        # print(df_IF.head())

        for flag in ['C', 'P']:
            fn = get_dss(
            ) + 'fut/bar/min5_' + symbol + '-' + flag + '-' + atm + '.csv'
            df = pd.read_csv(fn)
            df = df[df.date == today]
            df = df.set_index(['date', 'time'])
            df['close' + '_' + flag] = df['close']
            df_IO = df[['close' + '_' + flag]]
            # print(df_IO.head())

            # 与IF 数据进行join
            df_IF = df_IF.join(df_IO)
            # print(df_IF.head())

        df_IF = df_IF.reset_index()
        # print(df_IF.head())
        df_IF['pz'] = str(get_contract(symbol).pz)
        df_IF['symbol'] = symbol
        df_IF['atm'] = atm
        date_mature = datetime.strptime(mature_dict[symbol], '%Y-%m-%d')
        td = datetime.strptime(today, '%Y-%m-%d')
        T = float((date_mature - td).days) / 365  # 剩余期限,已做年化处理
        T = 0.0015 if T == 0 else T  # 最后一天特殊处理
        df = proc_iv(df_IF, T)
        # print(df.head())
        fn = get_dss() + 'opt/iv_atm_' + today[:4] + '.csv'
        if os.path.exists(fn):
            df.to_csv(fn, index=False, header=None, mode='a')
        else:
            df.to_csv(fn, index=False)
コード例 #7
0
ファイル: skew.py プロジェクト: chenzhenhu-yeah/nature
def calc_skew():
    now = datetime.now()
    date = now.strftime('%Y-%m-%d')
    # date = '2020-09-02'

    # 数据基于greeks文件,该文件中已计算好合约的iv
    fn = get_dss() + 'opt/' + date[:7] + '_greeks.csv'
    if os.path.exists(fn) == False:
        return

    r = []
    basic_list = []                                           # 提取当日的basic
    df = pd.read_csv(fn)
    df = df[df.Localtime.str.slice(0,10) == date]
    for i, row in df.iterrows():
        basic_list.append( get_contract(row.Instrument).basic )
    basic_list = list(set(basic_list))
    for basic in basic_list:
        try:
            df1 = df[df.Instrument.str.slice(0,len(basic)) == basic]
            df1 = df1.drop_duplicates(subset=['Instrument'],keep='last')
            # df1 = df1.sort_values('Instrument')
            # print(df1.tail())

            if len(df1) > 0:
                rec = df1.iloc[0, :]
                obj = int(rec.obj)
                pz = str(get_contract(rec.Instrument).pz)
                gap = 50
                if pz == 'CF':
                    gap = 200
                if pz == 'm':
                    gap = 50
                if pz in ['RM', 'MA']:
                    gap = 25

                atm = int(round(round(obj*(100/gap)/1E4,2) * 1E4/(100/gap), 0))     # 获得平值
                # print(gap)
                # print(obj)
                # print(atm)

                exchangeID = str(get_contract(rec.Instrument).exchangeID)
                if exchangeID in ['CFFEX', 'DCE']:
                    atm_c = basic + '-C-' + str(atm)
                    atm_p = basic + '-P-' + str(atm)
                    otm_right_c = basic + '-C-' + str(atm+2*gap)
                    otm_right_p = basic + '-P-' + str(atm+2*gap)
                    otm_left_c = basic + '-C-' + str(atm-2*gap)
                    otm_left_p = basic + '-P-' + str(atm-2*gap)
                else:
                    atm_c = basic + 'C' + str(atm)
                    atm_p = basic + 'P' + str(atm)
                    otm_right_c = basic + 'C' + str(atm+2*gap)
                    otm_right_p = basic + 'P' + str(atm+2*gap)
                    otm_left_c = basic + 'C' + str(atm-2*gap)
                    otm_left_p = basic + 'P' + str(atm-2*gap)

                df1 = df1.set_index('Instrument')
                skew_c = round( 100*(df1.at[otm_right_c,'iv']-df1.at[atm_c,'iv']) / df1.at[atm_c,'iv'], 2)
                skew_p = round( 100*(df1.at[otm_left_p,'iv']-df1.at[atm_p,'iv']) / df1.at[atm_p,'iv'], 2)

                # skew_mean_c = round( 100*( df1.at[otm_right_c,'iv'] + df1.at[otm_right_p,'iv'] - df1.at[atm_c,'iv'] - df1.at[atm_p,'iv'] ) / (df1.at[atm_c,'iv'] + df1.at[atm_p,'iv']), 2)
                # skew_mean_p = round( 100*( df1.at[otm_left_c,'iv'] + df1.at[otm_left_p,'iv'] - df1.at[atm_c,'iv'] - df1.at[atm_p,'iv'] ) / (df1.at[atm_c,'iv'] + df1.at[atm_p,'iv']), 2)
                skew_mean = round( 100*( df1.at[otm_right_c,'iv'] + df1.at[otm_right_p,'iv'] - df1.at[otm_left_c,'iv'] - df1.at[otm_left_p,'iv'] ) / (df1.at[otm_left_c,'iv'] + df1.at[otm_left_p,'iv']), 2)

                r.append([date, pz, basic, obj, atm, atm+2*gap, atm-2*gap, skew_c, skew_p, skew_mean])

        except:
            pass

    df = pd.DataFrame(r, columns=['date', 'pz', 'basic', 'obj', 'atm', 'otm_c', 'otm_p', 'skew_c', 'skew_p', 'skew_mean'])
    fn = get_dss() + 'opt/skew.csv'
    if os.path.exists(fn):
        df.to_csv(fn, index=False, header=None, mode='a')
    else:
        df.to_csv(fn, index=False)
コード例 #8
0
    def save_var(self):
        try:
            # 按照新逻辑,收盘不再调整队列
            self.adjust_price_head()
            self.price_duo_list  = sorted( self.price_duo_list )
            self.price_kong_list = sorted( self.price_kong_list, reverse=True )

            pnl_trade = 0
            commission = 0
            slippage = 0
            pz = str(get_contract(self.vtSymbol).pz)
            filename = get_dss() + 'fut/engine/dali/signal_dali_'+self.type+ '_deal_' + pz + '.csv'
            if os.path.exists(filename):
                df = pd.read_csv(filename)
                pnl_trade = df.pnl.sum()
                commission = df.commission.sum()
                slippage = df.slippage.sum()

            settle = self.bar.close
            pnl_hold = 0
            ct = get_contract(self.vtSymbol)
            size = ct.size

            d_list = [2,2,2,2,2] + self.size_duo_list
            k_list = [2,2,2,2,2] + self.size_kong_list
            # print(self.vtSymbol)
            # print(d_list)
            # print(k_list)

            for d, item in zip( d_list, sorted(self.price_duo_list,reverse=True) ):
                pnl_hold += (settle - item) * d * size
                # print(d, pnl_hold)

            for k, item in zip( k_list, sorted(self.price_kong_list) ):
                pnl_hold += (item - settle) * k * size
                # print(k, pnl_hold)

            # print(pnl_hold)

            self.unit = len(self.price_duo_list) - len(self.price_kong_list)
            print(self.unit)

            r = [ [self.portfolio.result.date,self.vtSymbol, settle, self.unit, \
                   pnl_trade+pnl_hold-commission-slippage, pnl_trade, pnl_hold, \
                   commission, slippage, str(self.price_duo_list), str(self.price_kong_list), \
                   str(self.size_duo_list), str(self.size_kong_list)] ]

            df = pd.DataFrame(r, columns=['datetime','vtSymbol','price','unit', \
                                          'pnl_net','pnl_trade','pnl_hold', \
                                          'commission','slippage','price_duo_list','price_kong_list', \
                                          'size_duo_list', 'size_kong_list'])
            filename = get_dss() +  'fut/engine/dali/signal_dali_'+self.type+ '_var_' + pz + '.csv'
            if os.path.exists(filename):
                df.to_csv(filename, index=False, mode='a', header=False)
            else:
                df.to_csv(filename, index=False)

            assert self.unit == len(self.size_duo_list) - len(self.size_kong_list)
            assert len(self.size_duo_list) == 0 or len(self.size_kong_list) == 0

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
コード例 #9
0
    def pcp(self):
        """
        将行情切片整理成k_dict,其以basic+strike为键,
        以[basic, strike, c_ask_price, c_bid_price, p_ask_price, p_bid_price, obj_ask_price, obj_bid_price, tm]为值
        """
        k_dict = {}
        tm = '00:00:00'
        now = datetime.now()
        today = now.strftime('%Y-%m-%d')

        # 获取期权的到期日
        fn = get_dss() + 'fut/cfg/opt_mature.csv'
        df2 = pd.read_csv(fn)
        df2 = df2[df2.flag == df2.flag]  # 筛选出不为空的记录
        df2 = df2.set_index('symbol')
        mature_dict = dict(df2.mature)

        for pz in self.slice_dict.keys():
            # print(pz)
            v = self.slice_dict[pz]
            for row in v:
                # print(row)
                symbol = row[0]
                tm = row[1]
                ask_price = row[2]
                bid_price = row[3]
                opt_flag = get_contract(symbol).opt_flag
                basic = get_contract(symbol).basic
                strike = get_contract(symbol).strike
                if basic[:2] == 'IO':
                    symbol_obj = 'IF' + basic[2:]
                else:
                    symbol_obj = basic

                # 当键值出现时,一次性将认购和认沽合约都处理了
                if basic + str(strike) not in k_dict.keys():
                    if opt_flag == 'C':
                        symbol_p = basic + get_contract(
                            symbol).opt_flag_P + str(strike)
                        rec_p = self.get_rec_from_slice(symbol_p)
                        rec_obj = self.get_rec_from_slice(symbol_obj)
                        if rec_p is not None and rec_obj is not None:
                            k_dict[basic + str(strike)] = [
                                basic, strike, ask_price, bid_price, rec_p[2],
                                rec_p[3], rec_obj[2], rec_obj[3], tm
                            ]
                    if opt_flag == 'P':
                        symbol_c = basic + get_contract(
                            symbol).opt_flag_C + str(strike)
                        rec_c = self.get_rec_from_slice(symbol_c)
                        rec_obj = self.get_rec_from_slice(symbol_obj)
                        if rec_c is not None and rec_obj is not None:
                            k_dict[basic + str(strike)] = [
                                basic, strike, rec_c[2], rec_c[3], ask_price,
                                bid_price, rec_obj[2], rec_obj[3], tm
                            ]

        r = []
        # 逐条记录验证pcp规则
        for k in k_dict.keys():
            rec = k_dict[k]
            term = rec[0]
            x = rec[1]
            tm = rec[8]
            date_mature = mature_dict[term]
            date_mature = datetime.strptime(date_mature, '%Y-%m-%d')
            td = datetime.strptime(today, '%Y-%m-%d')
            T = round(float((date_mature - td).days) / 365, 4)  # 剩余期限
            if T == 0 or T >= 0.3:
                continue

            # 正向套利
            S = rec[6]
            cb = rec[3]
            pa = rec[4]
            if cb > 1E8 or cb == 0 or cb != cb or pa > 1E8 or pa == 0 or pa != pa:
                pass
            else:
                pSc_forward = int(pa + S - cb)
                diff_forward = float(x) - pSc_forward
                rt_forward = round(diff_forward / (S * 2 * 0.15) / T, 2)

                if rt_forward >= 0.12 and diff_forward >= 3:
                    self.id += 1
                    seq = today[-5:-3] + today[-2:] + str(self.id)
                    r.append([
                        seq, today, tm, 'pcp',
                        [
                            'forward', term, S, cb, pa, T, x, pSc_forward,
                            diff_forward, rt_forward
                        ]
                    ])
                    # to_log( 'pcp: ' + str([today, 'forward', term, x, S, cb, pa, pSc_forward, T, diff_forward, rt_forward]) )

            # 反向套利
            S = rec[7]
            ca = rec[2]
            pb = rec[5]
            if ca > 1E8 or ca == 0 or ca != ca or pb > 1E8 or pb == 0 or pb != pb:
                pass
            else:
                pSc_back = int(pb + S - ca)
                diff_back = pSc_back - float(x)
                rt_back = round(diff_back / (S * 2 * 0.15) / T, 2)

                if rt_back >= 0.12 and diff_back >= 3:
                    self.id += 1
                    seq = today[-5:-3] + today[-2:] + str(self.id)
                    r.append([
                        seq, today, tm, 'pcp',
                        [
                            'back', term, S, ca, pb, T, x, pSc_back, diff_back,
                            rt_back
                        ]
                    ])
                    # to_log( 'pcp: ' + str([today, 'back', term, x, S, ca, pb, pSc_back, T, diff_back, rt_back]) )

        df = pd.DataFrame(r,
                          columns=['seq', 'date', 'time', 'type', 'content'])
        fn = get_dss() + 'fut/engine/arbitrage/portfolio_arbitrage_chance.csv'
        if os.path.exists(fn):
            df.to_csv(fn, index=False, mode='a', header=False)
        else:
            df.to_csv(fn, index=False)

        if tm > '09:00:00' and tm < '15:00:00' and r != []:
            pass
コード例 #10
0
def get_exchangeID(symbol):
    c = get_contract(symbol)
    return c.exchangeID
コード例 #11
0
    def _bc_sendOrder(self, dt, code, direction, offset, price, volume,
                      portfolio):
        filename = get_dss() + 'gateway_closed.csv'
        if os.path.exists(filename):
            return

        if self.state == 'CLOSE':
            print('gateway closed')
            return

        pz = get_contract(code).pz
        if portfolio in self.pf_dict:
            pz_list = self.pf_dict[portfolio].split(',')
            if (pz in pz_list) or ('*' in pz_list):
                print(portfolio, ' ', pz, ' send order here!')
            else:
                print(portfolio, ' ', pz, ' just test order here!')
                return
        else:
            print(portfolio, ' ', pz, ' just test order here!')
            return

        exchangeID = get_exchangeID(code)
        if exchangeID == '':
            return

        try:
            now = datetime.now()
            now = now.strftime('%H:%M')
            if now in ['10:14', '10:15', '10:16'
                       ] and code[:2] not in ['IF', 'IO']:
                time.sleep(960)

            self.lock.acquire()

            # 对价格四舍五入
            priceTick = get_contract(code).price_tick
            price = int(round(price / priceTick, 0)) * priceTick

            r = [[dt, code, direction, offset, price, volume]]
            print(str(r))
            c = [
                'datetime', 'symbol', 'direction', 'offset', 'price', 'volume'
            ]
            df = pd.DataFrame(r, columns=c)
            filename = get_dss() + 'fut/engine/gateway_order.csv'
            if os.path.exists(filename):
                df.to_csv(filename, index=False, mode='a', header=False)
            else:
                df.to_csv(filename, index=False)

            if direction == DIRECTION_LONG and offset == 'Open':
                self.t.ReqOrderInsert(code, DirectType.Buy, OffsetType.Open,
                                      price, volume, exchangeID)
            if direction == DIRECTION_SHORT and offset == 'Open':
                self.t.ReqOrderInsert(code, DirectType.Sell, OffsetType.Open,
                                      price, volume, exchangeID)
            if direction == DIRECTION_LONG and offset == 'Close':
                self.t.ReqOrderInsert(code, DirectType.Buy, OffsetType.Close,
                                      price, volume, exchangeID)
            if direction == DIRECTION_SHORT and offset == 'Close':
                self.t.ReqOrderInsert(code, DirectType.Sell, OffsetType.Close,
                                      price, volume, exchangeID)
            send_email(
                get_dss(),
                '引擎下单:' + code + ' ' + str(direction) + ' ' + str(offset), '')

        except Exception as e:
            s = traceback.format_exc()
            to_log(s)
            send_email(get_dss(), '交易路由出错', s)

        # 流控
        time.sleep(0.5)
        print('流控')
        self.lock.release()
コード例 #12
0
    def control_in_p(self, bar):
        if (bar.time > '09:31:00' and bar.time < '11:27:00' and bar.vtSymbol[:2] in ['IF','IO']) or \
           (bar.time > '13:01:00' and bar.time < '14:57:00' and bar.vtSymbol[:2] in ['IF','IO']) or \
           (bar.time > '21:01:00' and bar.time < '24:00:00' and bar.vtSymbol[:2] in ['al']) or \
           (bar.time > '00:00:00' and bar.time < '01:00:00' and bar.vtSymbol[:2] in ['al']) or \
           (bar.time > '09:01:00' and bar.time < '11:27:00' and bar.vtSymbol[:2] not in ['IF','IO']) or \
           (bar.time > '13:31:00' and bar.time < '14:57:00' and bar.vtSymbol[:2] not in ['IF','IO']) or \
           (bar.time > '21:01:00' and bar.time < '22:57:00' and bar.vtSymbol[:2] not in ['IF','IO']) :    # 因第一根K线的价格为0

            symbol_got_list = []
            fn = get_dss() + 'fut/engine/straddle/portfolio_straddle_param.csv'
            # while get_file_lock(fn) == False:
            #     time.sleep(0.01)

            df = pd.read_csv(fn)  # 加载最新参数
            for i, row in df.iterrows():
                try:
                    if row.state == 'stop':
                        continue

                    exchangeID = str(get_contract(row.basic_c).exchangeID)
                    if exchangeID in ['CFFEX', 'DCE']:
                        symbol_c = row.basic_c + '-C-' + str(row.strike_c)
                        symbol_p = row.basic_p + '-P-' + str(row.strike_p)
                    else:
                        symbol_c = row.basic_c + 'C' + str(row.strike_c)
                        symbol_p = row.basic_p + 'P' + str(row.strike_p)

                    if symbol_c not in self.got_dict or symbol_p not in self.got_dict:
                        continue

                    if self.got_dict[symbol_c] == False or self.got_dict[
                            symbol_p] == False:
                        continue
                    else:
                        df.at[i, 'tm'] = bar.time

                        symbol_got_list.append(symbol_c)
                        symbol_got_list.append(symbol_p)

                        s_c = self.signalDict[symbol_c][0]
                        s_p = self.signalDict[symbol_p][0]

                        # 开仓
                        if row.hold_c == 0 and row.hold_p == 0:
                            # print('come here ')
                            if row.direction == 'duo':
                                if self.engine.type == 'backtest':
                                    s_c.buy(s_c.bar.close, row.num_c)
                                    s_p.buy(s_p.bar.close, row.num_p)
                                    df.at[i, 'price_c'] = s_c.bar.close
                                    df.at[i, 'price_p'] = s_p.bar.close
                                else:
                                    s_c.buy(s_c.bar.AskPrice, row.num_c)  # 挂卖价
                                    s_p.buy(s_p.bar.AskPrice, row.num_p)  # 挂卖价
                                    df.at[i, 'price_c'] = round(
                                        s_c.bar.AskPrice, 2)
                                    df.at[i, 'price_p'] = round(
                                        s_p.bar.AskPrice, 2)
                                df.at[i, 'hold_c'] = row.num_c
                                df.at[i, 'hold_p'] = row.num_p

                            if row.direction == 'kong':
                                if self.engine.type == 'backtest':
                                    s_c.short(s_c.bar.close, row.num_c)
                                    s_p.short(s_p.bar.close, row.num_p)
                                    df.at[i, 'price_c'] = s_c.bar.close
                                    df.at[i, 'price_p'] = s_p.bar.close
                                else:
                                    s_c.short(s_c.bar.BidPrice,
                                              row.num_c)  # 挂买价
                                    s_p.short(s_p.bar.BidPrice,
                                              row.num_p)  # 挂买价
                                    df.at[i, 'price_c'] = round(
                                        s_c.bar.BidPrice, 2)
                                    df.at[i, 'price_p'] = round(
                                        s_p.bar.BidPrice, 2)
                                df.at[i, 'hold_c'] = -row.num_c
                                df.at[i, 'hold_p'] = -row.num_p

                        # 多单获利平仓
                        if row.hold_c >= 1 and row.hold_p >= 1:
                            if self.engine.type == 'backtest':
                                df.at[i,
                                      'profit_c'] = (s_c.bar.close -
                                                     row.price_c) * row.hold_c
                                df.at[i,
                                      'profit_p'] = (s_p.bar.close -
                                                     row.price_p) * row.hold_p
                                df.at[i, 'profit_o'] = df.at[
                                    i, 'profit_c'] + df.at[i, 'profit_p']

                                if row.profit_o >= row.profit:
                                    s_c.sell(s_c.bar.close, abs(row.hold_c))
                                    s_p.sell(s_p.bar.close, abs(row.hold_p))
                                    df.at[i, 'hold_c'] = 0
                                    df.at[i, 'hold_p'] = 0
                                    df.at[i, 'state'] = 'stop'
                            else:
                                df.at[i, 'profit_c'] = round(
                                    (s_c.bar.BidPrice - row.price_c) *
                                    row.hold_c, 2)
                                df.at[i, 'profit_p'] = round(
                                    (s_p.bar.BidPrice - row.price_p) *
                                    row.hold_p, 2)
                                df.at[i, 'profit_o'] = round(
                                    df.at[i, 'profit_c'] +
                                    df.at[i, 'profit_p'], 2)

                                if row.profit_o >= row.profit:
                                    s_c.sell(s_c.bar.BidPrice, abs(row.hold_c))
                                    s_p.sell(s_p.bar.BidPrice, abs(row.hold_p))
                                    df.at[i, 'hold_c'] = 0
                                    df.at[i, 'hold_p'] = 0
                                    df.at[i, 'state'] = 'stop'

                        # 空单获利平仓
                        if row.hold_c <= -1 and row.hold_p <= -1:
                            if self.engine.type == 'backtest':
                                df.at[i,
                                      'profit_c'] = (s_c.bar.close -
                                                     row.price_c) * row.hold_c
                                df.at[i,
                                      'profit_p'] = (s_p.bar.close -
                                                     row.price_p) * row.hold_p
                                df.at[i, 'profit_o'] = df.at[
                                    i, 'profit_c'] + df.at[i, 'profit_p']

                                if row.profit_o >= row.profit:
                                    s_c.cover(s_c.bar.close, abs(row.hold_c))
                                    s_p.cover(s_p.bar.close, abs(row.hold_p))
                                    df.at[i, 'hold_c'] = 0
                                    df.at[i, 'hold_p'] = 0
                                    df.at[i, 'state'] = 'stop'
                            else:
                                df.at[i, 'profit_c'] = round(
                                    (s_c.bar.AskPrice - row.price_c) *
                                    row.hold_c, 2)
                                df.at[i, 'profit_p'] = round(
                                    (s_p.bar.AskPrice - row.price_p) *
                                    row.hold_p, 2)
                                df.at[i, 'profit_o'] = round(
                                    df.at[i, 'profit_c'] +
                                    df.at[i, 'profit_p'], 2)

                                if row.profit_o >= row.profit:
                                    s_c.cover(s_c.bar.AskPrice,
                                              abs(row.hold_c))
                                    s_p.cover(s_p.bar.AskPrice,
                                              abs(row.hold_p))
                                    df.at[i, 'hold_c'] = 0
                                    df.at[i, 'hold_p'] = 0
                                    df.at[i, 'state'] = 'stop'

                except Exception as e:
                    s = traceback.format_exc()
                    to_log(s)

            df.to_csv(fn, index=False)  # 回写文件
            # release_file_lock(fn)
            for symbol in symbol_got_list:
                self.got_dict[symbol] = False
コード例 #13
0
def open_interest_show_distribution(basic, type, date):
    now = datetime.now()
    # 本月第一天
    first_day = datetime(now.year, now.month, 1)
    #前一个月最后一天
    pre_month = first_day - timedelta(days=1)
    today = now.strftime('%Y-%m-%d')
    pre = pre_month.strftime('%Y-%m-%d')

    fn = get_dss() + 'opt/' + pre[:7] + '_greeks.csv'
    df_pre = pd.read_csv(fn)
    fn = get_dss() + 'opt/' + today[:7] + '_greeks.csv'
    df_today = pd.read_csv(fn)
    df = pd.concat([df_pre, df_today])

    df = df[df.Instrument.str.slice(0, len(basic)) == basic]
    df['date'] = df.Localtime.str.slice(0, 10)
    date_list = sorted(list(set(list(df.date))), reverse=True)
    print(date_list)
    if len(date_list) < 10:
        return ''

    plt.figure(figsize=(12, 7))
    plt.title(' ')

    for i in [0, 1, 9]:
        # for i in [0]:
        df1 = df[df.date == date_list[i]]
        df1 = df1.sort_values('Instrument')
        n = len(df1)
        assert n % 2 == 0
        n = int(n / 2)
        df_c = df1.iloc[:n, :]
        df_p = df1.iloc[n:, :]
        # print(df_c)
        # print(df_p)
        if type == 'call':
            df2 = df_c
        else:
            df2 = df_p

        strike_list = []
        for j, row in df2.iterrows():
            strike_list.append(get_contract(row.Instrument).strike)
        df2['strike'] = strike_list
        df2 = df2.set_index('strike')
        if i == 0:
            plt.plot(df2.OpenInterest, label=date_list[i])
        else:
            plt.plot(df2.OpenInterest, '--', label=date_list[i])
        # print(df2.OpenInterest)

    plt.xticks(rotation=90)
    plt.legend()
    fn = 'static/open_interest.jpg'
    plt.savefig(fn)
    plt.cla()

    fn = 'open_interest.jpg'
    now = str(int(time.time()))
    r = '<img src=\"static/' + fn + '?rand=' + now + '\" />'
    return r
コード例 #14
0
def iv_min5_show(symbol_list, date):
    plt.figure(figsize=(13, 7))
    plt.title(date)

    for symbol in symbol_list:
        basic = get_contract(symbol).basic
        strike = get_contract(symbol).strike
        opt_flag = get_contract(symbol).opt_flag

        if basic[:2] == 'IO':
            symbol_obj = 'IF' + basic[2:]
        else:
            symbol_obj = basic

        fn = get_dss() + 'fut/put/rec/min5_' + symbol_obj + '.csv'
        df_obj = pd.read_csv(fn)
        df_obj = df_obj.set_index(['date', 'time'])
        df_obj['close_obj'] = df_obj['close']
        df_obj = df_obj[['close_obj']]
        # print(df_obj.tail())

        fn = get_dss() + 'fut/put/rec/min5_' + symbol + '.csv'
        df = pd.read_csv(fn)
        df = df[df.date == date]
        df = df.set_index(['date', 'time'])
        # print(df.tail())

        df = df.join(df_obj)
        df = df.dropna()
        df = df.reset_index()
        df = df.set_index('time')
        # print(df.tail())

        r = 0.03
        fn = get_dss() + 'fut/cfg/opt_mature.csv'
        df2 = pd.read_csv(fn)
        df2 = df2[df2.flag == df2.flag]  # 筛选出不为空的记录
        df2 = df2.set_index('symbol')
        mature_dict = dict(df2.mature)
        date_mature = mature_dict[basic]
        date_mature = datetime.strptime(date_mature, '%Y-%m-%d')
        td = datetime.strptime(date, '%Y-%m-%d')
        T = float((date_mature - td).days) / 365  # 剩余期限

        iv_list = []
        for i, row in df.iterrows():
            try:
                if opt_flag == 'C':
                    iv = bsm_call_imp_vol(row.close_obj, strike, T, r,
                                          row.close)
                else:
                    iv = bsm_put_imp_vol(row.close_obj, strike, T, r,
                                         row.close)
                iv_list.append(round(100 * iv, 2))
            except:
                break
        df['iv'] = iv_list
        plt.plot(df.iv, label=symbol)

    plt.xticks(rotation=90)
    plt.legend()

    fn = 'static/iv_min5_show.jpg'
    plt.savefig(fn)
    plt.cla()

    rr = ''
    fn = 'iv_min5_show.jpg'
    now = str(int(time.time()))
    rr = '<img src=\"static/' + fn + '?rand=' + now + '\" />'
    return rr