Exemple #1
0
def defineForwordVolatilityStatergy(underlyinglist,
                                    strikeprice,
                                    nofdayslist,
                                    callorputlist,
                                    callorputflag,
                                    symbol,
                                    expieryDaysList,
                                    date,
                                    checkExit=False):

    m = range(0, 3)
    noofdaysVarienceDir = dict()
    name = ''
    for i in m:
        underlying = underlyinglist[i]
        noofdays = nofdayslist[i]
        callorputprice = callorputlist[i]
        flag = callorputflag
        if flag == 'P':
            name = 'Put'
            price = mibian.Me([underlying, strikeprice, 0, 0, noofdays],
                              putPrice=callorputprice)
        else:
            name = 'Call'
            #print("values are ",underlying,strikeprice,noofdays,callorputprice)
            price = mibian.Me([underlying, strikeprice, 0, 0, noofdays],
                              callPrice=callorputprice)
    # price = mibian.Me([underlying,strikeprice,0,0,noofdays],name = callorputprice)
        varience = calculatendayVarience(price.impliedVolatility, noofdays)
        noofdaysVarienceDir.update({i: (noofdays, varience)})

    firstVarince = noofdaysVarienceDir[0]
    secondVarince = noofdaysVarienceDir[1]
    thridVarience = noofdaysVarienceDir[2]

    firstandsecondVol = calculateForwordVolatility(firstVarince, secondVarince)
    secondandthridVol = calculateForwordVolatility(secondVarince,
                                                   thridVarience)
    if checkExit:
        statergy, statergyDF = makeExitStatergy(firstandsecondVol,
                                                secondandthridVol, strikeprice,
                                                symbol, name, expieryDaysList,
                                                callorputlist, date)
    else:
        statergy, statergyDF = makeFvStatergy(firstandsecondVol,
                                              secondandthridVol, strikeprice,
                                              symbol, name, expieryDaysList,
                                              callorputlist, date)

    return statergy, statergyDF, noofdaysVarienceDir, firstandsecondVol, secondandthridVol
Exemple #2
0
    def testMe(self):
        '''Merton model tests'''
        test = mibian.Me([52, 50, 1, 1, 30], volatility=30)
        self.assertEqual([test.callPrice, test.putPrice],
                         [2.8984579845404852, 0.93950583663422549])
        self.assertEqual([test.callDelta, test.putDelta],
                         [0.68691662012467536, -0.31150401721361859])
        #self.assertEqual([test.callDelta2, test.putDelta2],
        #					[-0.54332493698317152, 0.4468605293205825])
        self.assertEqual([test.callTheta, test.putTheta],
                         [-0.025346097581119695, -0.026712759026055157])
        self.assertEqual([test.callRho, test.putRho],
                         [0.026976333913925447, -0.014085792930199226])
        self.assertEqual(test.vega, 0.052657699586925684)
        self.assertEqual(test.gamma, 0.07897789426868787)

        test = mibian.Me([52, 50, 1, 1, 30], callPrice=3)
        self.assertEqual(test.impliedVolatility, 31.25)
def calc_pnl(spot, dte, opt_df, r, div):

    l_pnl = []

    for i in opt_df.iterrows():

        if i[1]['Contract'] == 'STK':

            l_pnl.append((spot - i[1]['Avg px']) * i[1]['pos'])

        else:
            c = mibian.Me([spot, i[1]['Contract'][-2], r, div * 100, dte],
                          volatility=i[1]['IV'] * 100)

            if i[1]['Contract'][-1] == 'C':
                l_pnl.append(
                    ((c.callPrice - i[1]['Avg px']) * i[1]['pos']) * 100)
            else:
                l_pnl.append(
                    ((c.putPrice - i[1]['Avg px']) * i[1]['pos']) * 100)

    pnl = sum(l_pnl)

    return {'spot': spot, 'dte': dte, 'pnl': pnl}
        def getDateStrike(i,dbq,con,x=0):
            strlist = []
            temp_Close = Df_F.loc[Df_F[date] == i][close].tolist()[x]
            exp_date = Df_F.loc[Df_F[close] == temp_Close]['EXPIRY_DT'].tolist()[0]

            temp_OI = DF_O.loc[DF_O[date] == i]['STRIKE_PR'].tolist()[-2:]

            diff, Strike_High, Strike_Low = getStrikes.getStrikes(temp_Close,temp_OI)

            # diff = abs(temp_OI[0] - temp_OI[1])
            # Strike_High = temp_Close + (diff - (temp_Close % diff))  # Get smallest no from larger no then Close
            # Strike_Low = temp_Close + - (temp_Close % diff)  # Get largest no from smaller then Close
            Strike_High_mask_CE = (DF_O[date] == i)\
                                  & (DF_O['STRIKE_PR'] == Strike_High)\
                                  & (DF_O['EXPIRY_DT'] == exp_date)\
                                  & (DF_O['OPTION_TYP'] == 'CE')

            Strike_High_mask_PE = (DF_O[date] == i) \
                                  & (DF_O['STRIKE_PR'] == Strike_High) \
                                  & (DF_O['EXPIRY_DT'] == exp_date) \
                                  & (DF_O['OPTION_TYP'] == 'PE')

            Strike_Low_mask_CE = (DF_O[date] == i) \
                                  & (DF_O['STRIKE_PR'] == Strike_Low) \
                                  & (DF_O['EXPIRY_DT'] == exp_date) \
                                  & (DF_O['OPTION_TYP'] == 'CE')

            Strike_Low_mask_PE = (DF_O[date] == i) \
                                  & (DF_O['STRIKE_PR'] == Strike_Low) \
                                  & (DF_O['EXPIRY_DT'] == exp_date) \
                                  & (DF_O['OPTION_TYP'] == 'PE')

            CE_High = DF_O.loc[Strike_High_mask_CE][close].tolist()[0]
            CE_Low = DF_O.loc[Strike_Low_mask_CE][close].tolist()[0]
            PE_High = DF_O.loc[Strike_High_mask_PE][close].tolist()[0]
            PE_Low = DF_O.loc[Strike_Low_mask_PE][close].tolist()[0]

            days_to_expire = int(get_tradingDay(i,exp_date,False))

            CE_H_IV = mibian.Me([temp_Close, Strike_High, 7, 0, days_to_expire], callPrice=CE_High).impliedVolatility
            CE_L_IV = mibian.Me([temp_Close, Strike_Low, 7, 0, days_to_expire], callPrice=CE_Low).impliedVolatility
            PE_H_IV = mibian.Me([temp_Close, Strike_High, 7, 0, days_to_expire], putPrice=PE_High).impliedVolatility
            PE_L_IV = mibian.Me([temp_Close, Strike_Low, 7, 0, days_to_expire], putPrice=PE_Low).impliedVolatility


            DF_test = DF_O.loc[(DF_O[date] == i) & (DF_O['EXPIRY_DT'] == exp_date)]

            mp_strike_pr,mp,r1 = OIMAXPAIN.findmaxpain(symbol,DF_test)
            ce_maxpain, pe_maxpain, maxpain = mp['CE'],mp['PE'],mp['totalpain']

            CE_OI_Max2,CE_OI_Max1 = sorted(r1['CE'].tolist())[-2:]
            PE_OI_Max2,PE_OI_Max1 = sorted(r1['PE'].tolist())[-2:]

            CE_OI_Max2_St_Pr,CE_OI_Max2_CHG_OI = DF_test.loc[DF_test['OPEN_INT'] == CE_OI_Max2][['STRIKE_PR','CHG_IN_OI']].values[0][-2:]
            CE_OI_Max1_St_Pr,CE_OI_Max1_CHG_OI = DF_test.loc[DF_test['OPEN_INT'] == CE_OI_Max1][['STRIKE_PR','CHG_IN_OI']].values[0][-2:]
            PE_OI_Max2_St_Pr,PE_OI_Max2_CHG_OI = DF_test.loc[DF_test['OPEN_INT'] == PE_OI_Max2][['STRIKE_PR','CHG_IN_OI']].values[0][-2:]
            PE_OI_Max1_St_Pr,PE_OI_Max1_CHG_OI = DF_test.loc[DF_test['OPEN_INT'] == PE_OI_Max1][['STRIKE_PR','CHG_IN_OI']].values[0][-2:]

            #

            # OI_CE_High = DF_O.loc[Strike_High_mask_CE][close].tolist()[0]
            # OI_CE_Low = DF_O.loc[Strike_Low_mask_CE][close].tolist()[0]
            # OI_PE_High = DF_O.loc[Strike_High_mask_PE][close].tolist()[0]
            # OI_PE_Low = DF_O.loc[Strike_Low_mask_PE][close].tolist()[0]
            #
            # COI_CE_High = DF_O.loc[Strike_High_mask_CE][close].tolist()[0]
            # COI_CE_Low = DF_O.loc[Strike_Low_mask_CE][close].tolist()[0]
            # COI_PE_High = DF_O.loc[Strike_High_mask_PE][close].tolist()[0]
            # COI_PE_Low = DF_O.loc[Strike_Low_mask_PE][close].tolist()[0]
            #
            #
            strlist.append([i, symbol, exp_date, temp_Close, Strike_High,Strike_Low,
                            CE_H_IV, CE_L_IV, PE_H_IV, PE_L_IV, days_to_expire,
                            ce_maxpain, pe_maxpain, maxpain, mp_strike_pr,
                            CE_OI_Max2_St_Pr, CE_OI_Max2_CHG_OI,
                            CE_OI_Max1_St_Pr, CE_OI_Max1_CHG_OI,
                            PE_OI_Max2_St_Pr, PE_OI_Max2_CHG_OI,
                            PE_OI_Max1_St_Pr, PE_OI_Max1_CHG_OI])
            implobj = ImpliedVolatility(dbq = dbq, conn = con)
            implobj.save_data(strlist)
Exemple #5
0
    df['spots'] = range(int(s1), int(s2))

    if stockpos != None:
        i = 0
        for spot in range(int(s1), int(s2)):
            df['stk'][i] = stockpos * (spot - s)
            i += 1
    n = 1
    for o in opts:
        i = 0
        for spot in range(int(s1), int(s2)):
            df['spots'][i] = spot
            dtes = o[2] - d
            if dtes > 0:
                c = mibian.Me([
                    df['spots'].iloc[i], o[0]['strike'], r * 100, div * 100, d
                ],
                              volatility=o[1] * 100)

                if o[0]['kind'] == 'C':
                    df['pos' + str(n)][i] = (
                        (c.callPrice - o[0]['close']) * o[3]) * 100
                else:
                    df['pos' +
                       str(n)][i] = ((c.putPrice - o[0]['close']) * o[3]) * 100
            else:
                df['pos' + str(n)][i] = o[0]['close'] * o[3]

            df['dte'][i] = d

            i += 1
Exemple #6
0
@author: sanjotraibagkar
"""

#The formula for IV rank is simple, really. It is:

#100 x (the current IV level - the 52 week IV low) / (the 52 week IV high - 52 week IV low) = IV Rank

import mibian

from nsepy import get_history
from datetime import date
import pandas as pd
from matplotlib import pyplot as plt
import datetime

c = mibian.Me([10692, 10700, 7, 0, 30], callPrice=153)

print(c.impliedVolatility)

c = mibian.Me([10692, 10600, 7, 0, 21], volatility=13)

print(c.callPrice)

from nsepy.derivatives import get_expiry_date
expiry = get_expiry_date(year=2018, month=5)
print(expiry)

stock = 'SBIN'
start = date(2017, 3, 25)
end = date(2018, 4, 26)
end2 = date(2018, 4, 27)
cov_VIX_VXD = (1 - 0.94) * np.sum(lamda * log_VIX * log_VXD)

y = np.array([[var_SPX, cov_SPX_DJX, cov_SPX_VIX, cov_SPX_VXD],
              [cov_SPX_DJX, var_DJX, cov_DJX_VIX, cov_DJX_VXD],
              [cov_SPX_VIX, cov_DJX_VIX, var_VIX, cov_VIX_VXD],
              [cov_SPX_VXD, cov_DJX_VXD, cov_VIX_VXD, var_VXD]])
print('Covariance matrix')
print(y)
#Question 1-b
annual_var_SPX = np.sqrt(252) * np.sqrt(var_SPX)
annual_var_DJX = np.sqrt(252) * np.sqrt(var_DJX)
annual_var_VIX = np.sqrt(252) * np.sqrt(var_VIX)
annual_var_VXD = np.sqrt(252) * np.sqrt(var_VXD)

# Question 2
c_SPX = mibian.Me([SPX[0], 1865, 0.25, 2.22, 35], callPrice=(49.5 + 50.1) / 2)
p_SPX = mibian.Me([SPX[0], 1865, 0.25, 2.22, 35], putPrice=(55.5 + 56.1) / 2)
c_DJX = mibian.Me([DJX[0] / 100, 160, 0.25, 2.48, 35],
                  callPrice=(3.85 + 4.05) / 2)
p_DJX = mibian.Me([DJX[0] / 100, 160, 0.25, 2.48, 35],
                  putPrice=(4.7 + 4.9) / 2)
print('implied Volatility')
print('SPX call:', c_SPX.impliedVolatility)
print('SPX put:', p_SPX.impliedVolatility)
print('DJX call:', c_DJX.impliedVolatility)
print('DJX put:', p_DJX.impliedVolatility)

# Question 3 & 4
SPX_initial = mibian.Me(
    [SPX[0], 1865, 0.25, 2.22, 35],
    volatility=(c_SPX.impliedVolatility + p_SPX.impliedVolatility) / 2)
if corp in ["Call", "call"]:
    print("")
    print("Call Option Analytics")
    xpx = input("Strike Price = ")
    xpx_float = float(xpx)
    if xpx_float <= underpx:
         print("This option is in the money and should be exercised.")
    elif xpx_float > underpx:
        intrt = input("Interest Rate = ")
        adiv = input("Annual Dividend = ")
        dte = input("Days to Expiration = ")
        #vol = input("Volatility = ")
        cpx = input("Call Price = ")
        #ppx = input("Put Price = ")
        #import mibian
        c=mibian.Me([underpx, xpx, intrt, adiv, dte], callPrice = cpx)
        print ("")
        print ("Implied Vol ", round(c.impliedVolatility,4))
        ivol = c.impliedVolatility
        c=mibian.Me([underpx, xpx, intrt, adiv, dte], volatility = ivol)
        #print ("Call Price ",c.callPrice)
        print("")
        print ("Put Price ", round(c.putPrice, 4))
        print ("Call Delta ", round(c.callDelta, 4))
        print ("Put Delta ", round(c.putDelta, 4))
        print ("Call Theta ", round(c.callTheta, 4))
        print ("Put Theta ", round(c.putTheta, 4))
        print ("Call Rho ", round(c.callRho, 4))
        print ("Put Rho ", round(c.putRho, 4))
        print ("Vega ", round(c.vega, 4))
        print ("Gamma ", round(c.gamma, 4))
Exemple #9
0
def iv_bisection(target_value, call_put, S, K, r, q, daystoexpiry):
    if call_put == 'call':
        opt = mibian.Me([S, K, r, q, daystoexpiry], callPrice=target_value)
    else:
        opt = mibian.Me([S, K, r, q, daystoexpiry], putPrice=target_value)
    return opt.impliedVolatility
Exemple #10
0
def bs_price(call_put, v, S, K, r, q, daystoexpiry):
    opt = mibian.Me([S, K, r, q, daystoexpiry], volatility=v)
    if call_put == 'call':
        return opt.callPrice, opt.vega
    else:
        return opt.putPrice, opt.vega