Exemplo n.º 1
0
    def test_analytical_vega(self):
        F = 100
        K = 90
        sigma = .2
        r = .02
        t = .5

        flag = 'p'
        c_put = c_analytical.vega(flag, F, K, t, r, sigma)
        py_put = py_analytical.vega(flag, F, K, t, r, sigma)
        self.assertTrue(almost_equal(c_put, py_put))

        flag = 'c'
        c_call = c_analytical.vega(flag, F, K, t, r, sigma)
        py_call = py_analytical.vega(flag, F, K, t, r, sigma)
        self.assertTrue(almost_equal(c_call, py_call))
Exemplo n.º 2
0
def main_fun(now_date, now_time, percent):
    vol_sr = pd.Series()
    try:
        vol_sr['percent'] = percent
        part_result_dict = deal_fun(now_date=now_date, now_time=now_time, percent=percent)
        F = part_result_dict['spot_px']
        vol_sr['S'] = F
        r = part_result_dict['rate_weight']
        vol_sr['r'] = r

        tran_dict = {1: 'first', 2: 'second'}
        for i in range(1, 3):
            t = part_result_dict['opt_ttm_1'] / 365
            for ii in range(1, 3):
                K = part_result_dict[f'opt_k_{i}_{ii}']
                vol_sr[f'{tran_dict[i]}_K_{ii}'] = K
                # 计算 vol
                # if F >= K:
                #     flag = 'call'
                #     price = part_result_dict[f'{flag}_px_{i}_{ii}']
                #     vol_sr[f'{tran_dict[i]}_{flag}_px_{ii}'] = price
                #     sigma = implied_volatility(price, F, K, t, r, flag[0])
                #     vol_sr[f'{tran_dict[i]}_{flag}_vol_{ii}'] = sigma
                #     vol_sr[f'{tran_dict[i]}_vol_{ii}'] = vol_sr[f'{tran_dict[i]}_call_vol_{ii}']
                # else:
                #     flag = 'put'
                #     price = part_result_dict[f'{flag}_px_{i}_{ii}']
                #     vol_sr[f'{tran_dict[i]}_{flag}_px_{ii}'] = price
                #     sigma = implied_volatility(price, F, K, t, r, flag[0])
                #     vol_sr[f'{tran_dict[i]}_{flag}_vol_{ii}'] = sigma
                #     vol_sr[f'{tran_dict[i]}_vol_{ii}'] = vol_sr[f'{tran_dict[i]}_put_vol_{ii}']

                # 计算希腊字母
                for flag in ['call', 'put']:
                    price = result_dict[now_date][f'{flag}_px_{i}_{ii}']
                    vol_sr[f'{tran_dict[i]}_{flag}_px_{ii}'] = price
                    sigma = implied_volatility(price, F, K, t, r, flag[0])
                    vol_sr[f'{tran_dict[i]}_{flag}_vol_{ii}'] = sigma
                    vol_sr[f'{tran_dict[i]}_{flag}_delta_{ii}'] = delta(flag[0], F, K, t, r, sigma)
                    vol_sr[f'{tran_dict[i]}_{flag}_gamma_{ii}'] = gamma(flag[0], F, K, t, r, sigma)
                    vol_sr[f'{tran_dict[i]}_{flag}_rho_{ii}'] = rho(flag[0], F, K, t, r, sigma)
                    vol_sr[f'{tran_dict[i]}_{flag}_theta_{ii}'] = theta(flag[0], F, K, t, r, sigma)
                    vol_sr[f'{tran_dict[i]}_{flag}_vega_{ii}'] = vega(flag[0], F, K, t, r, sigma)

            vol_sr[f'{tran_dict[i]}_K_weight'] = (F - vol_sr[f'{tran_dict[i]}_K_2']) / \
                                                 (vol_sr[f'{tran_dict[i]}_K_1'] - vol_sr[f'{tran_dict[i]}_K_2'])
            vol_sr[f'{tran_dict[i]}_vol'] = vol_sr[f'{tran_dict[i]}_K_weight'] * \
                                            vol_sr[f'{tran_dict[i]}_vol_1'] + \
                                            (1 - vol_sr[f'{tran_dict[i]}_K_weight']) * \
                                            vol_sr[f'{tran_dict[i]}_vol_2']
        x = (30 - part_result_dict['opt_ttm_2']) / \
            (part_result_dict['opt_ttm_1'] - part_result_dict['opt_ttm_2'])
        vol_sr[f'opt_ttm_1'] = part_result_dict['opt_ttm_1']
        vol_sr[f'opt_ttm_2'] = part_result_dict['opt_ttm_2']
        vol_sr[f'time_weight'] = x
        vol_sr[f'target_vol'] = x * vol_sr[f'first_vol'] + (1 - x) * vol_sr[f'second_vol']
    except Exception as error:
        print(error)
    vol_sr.name = pd.to_datetime(f'{now_date} {now_time}')
    return vol_sr
Exemplo n.º 3
0
def get_greeks(OPTION_DICT):
    delta_dict = {}
    vega_dict = {}
    for security in OPTION_DICT.keys():
        flag = OPTION_DICT[security]['opt_type']
        F = OPTION_DICT[security]['und_price']
        K = OPTION_DICT[security]['strike']
        t = OPTION_DICT[security]['ttm']
        r = 0
        sigma = OPTION_DICT[security]['implied_vol']
        d1 = delta(flag, F, K, t, r, sigma)
        v1 = vega(flag, F, K, t, r, sigma)
        delta_dict[security] = d1
        vega_dict[security] = v1
    '''
    delta = re.compile(r'T(\d*)([CP])_delta$')
    vega = re.compile(r'T(\d*)([CP])_vega$')
    for security in SECURITIES:
        delta_groups = delta.search(security)
        vega_groups = vega.search(security)

        if bool(delta_groups):
            delta_dict[security] = SECURITIES[security]
        if bool(vega_groups):
            vega_dict[security] = SECURITIES[security]
    '''
    return delta_dict, vega_dict
Exemplo n.º 4
0
def f_greeks(t):
    iv = bk.implied_volatility.implied_volatility_of_discounted_option_price(
        P0, F, K, r, t, flag='c')
    gammaC = greek.gamma('c', F, K, t, r, iv)
    # gammaP = greek.gamma('p', F, K, t, r, iv) # should be equal to gammaC
    vegaC = greek.vega('c', F, K, t, r, iv)
    # vegaP  = greek.vega ('p', F, K, t, r, iv) # should be equal to vegaP C
    thetaC = greek.theta('c', F, K, t, r, iv)
    thetaP = greek.theta('p', F, K, t, r, iv)
    deltaC = greek.delta('c', F, K, t, r, iv)
    deltaP = greek.delta('p', F, K, t, r, iv)
    return gammaC, vegaC, thetaC, thetaP, deltaC, deltaP
Exemplo n.º 5
0
def get_greeks(OPTION_DICT):
    delta_dict = {}
    vega_dict = {}
    for security in OPTION_DICT.keys():
        flag = OPTION_DICT[security]['opt_type']
        F = OPTION_DICT[security]['und_price']
        K = OPTION_DICT[security]['strike']
        t = OPTION_DICT[security]['ttm']
        r = 0
        sigma = OPTION_DICT[security]['implied_vol']
        d1 = delta(flag, F, K, t, r, sigma)
        v1 = vega(flag, F, K, t, r, sigma)
        delta_dict[security] = d1
        vega_dict[security] = v1

    return delta_dict, vega_dict
Exemplo n.º 6
0
def calcVol(mercFilter='DOL', opcMercFilter=None):
    if opcMercFilter is None:
        opcMercFilter = mercFilter
    opclst = mds.find({'$regex': '^{}'.format(opcMercFilter)},
                      ds.freqHelper.bday,
                      mds.b3VS,
                      False,
                      type='option')
    futlst = mds.find({'$regex': '^{}'.format(mercFilter)},
                      ds.freqHelper.bday,
                      mds.b3VS,
                      False,
                      type='future')
    opclst = [o[1].replace('_1BDay', '') for o in opclst]
    futlst = [o[1].replace('_1BDay', '') for o in futlst]

    df_fut = mds.read(futlst, library=mds.b3VS)
    df_fut = {f.md.name: f for f in df_fut}
    #df_opc=

    for i, nm in enumerate(opclst):
        df = mds.read(nm, ds.freqHelper.bday, mds.b3VS)
        df0 = df.copy()
        underlying1 = mercFilter + uu.futCodeFromDate(df.md.maturity)
        #df.md.underlying
        try:
            df_fut1 = df_fut[underlying1 + '_b3']
        except:
            try:
                df_fut1 = df_fut[underlying1.replace('0', '') + '_b3']
            except:
                warn('future not found {}'.format(underlying1))
                continue

        df_fut1 = df_fut1.reindex(df.index)
        du = uu.networkdays(df.index, df.md.maturity)
        dc = (df.md.maturity - df.index).days / 365
        rf = uu.rCont(uu.getRates(df.index, du))
        vol = empty_like(df.close)
        vol1 = empty_like(df.close)
        df['vol'] = nan
        df['delta'] = nan
        df['gamma'] = nan
        df['theta'] = nan
        df['vega'] = nan

        px = df.close * exp(rf * ((du + 1) / 252))
        for t, px1 in enumerate(px):
            if du[t] > 0:
                #            vol[t] = implied_volatility(px,df_fut1.close[t],df.md.strike,rf[t],du[t]/252,df.md.cp)
                try:
                    df['vol'].values[
                        t] = implied_volatility_of_undiscounted_option_price(
                            px1, df_fut1.close[t], df.md.strike, dc[t],
                            df.md.cp)
                    df.gamma.values[t] = analytical.gamma(
                        df.md.cp, df_fut1.close[t], df.md.strike, dc[t], rf[t],
                        df['vol'][t])
                    df.theta.values[t] = analytical.theta(
                        df.md.cp, df_fut1.close[t], df.md.strike, dc[t], rf[t],
                        df['vol'][t])
                    df.vega.values[t] = analytical.vega(
                        df.md.cp, df_fut1.close[t], df.md.strike, dc[t], rf[t],
                        df['vol'][t])

                    df.delta.values[t] = analytical.delta(
                        df.md.cp, df_fut1.close[t], df.md.strike, dc[t], rf[t],
                        df['vol'][t])
                except:
                    warn('invalid vol (prob below intrinsic)')
            else:
                df['vol'].values[t] = 0

        print('{} i: {}/{}'.format(nm, i, len(opclst)))
        if not df0.equals(df):
            mds.write(df,
                      library=mds.b3VS,
                      check_metadata=False,
                      prune_previous_version=True)