Esempio n. 1
0
 def test_analytical_delta(self):
     while self.tdi.has_next():
         row = self.tdi.next_row()
         S, K, t, r, sigma = row['S'], row['K'], row['t'], row['R'], row[
             'v']
         self.assertAlmostEqual(analytical.delta('c', S, K, t, r, sigma),
                                row['CD'],
                                delta=0.000001)
         self.assertAlmostEqual(analytical.delta('p', S, K, t, r, sigma),
                                row['PD'],
                                delta=0.000001)
Esempio n. 2
0
    def test_analytical_delta(self):
        S = 49
        K = 50
        sigma = .2
        r = .05
        t = 0.3846

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

        flag = 'c'
        c_call = c_analytical.delta(flag, S, K, t, r, sigma)
        py_call = py_analytical.delta(flag, S, K, t, r, sigma)
        self.assertTrue(almost_equal(c_call, py_call))
Esempio n. 3
0
 def test_delta(self):
     deltas = [
         delta(flag, S, K, t, r, sigma)
         for flag, S, K, t, r, sigma in self.arg_combinations
     ]
     ndeltas = [
         ndelta(flag, S, K, t, r, sigma)
         for flag, S, K, t, r, sigma in self.arg_combinations
     ]
     self.assertTrue(self.diff_mean(deltas, ndeltas) < self.epsilon)
Esempio n. 4
0
def precompute(underlying):
    
    print "precompute: " + str(underlying)
    print 
    
    db = MySQLdb.connect(host="localhost", user=settings.db_username, passwd=settings.db_password, db="optiondata") 
    cur2 = db.cursor()
    
    query = "SELECT id, quote_date, underlying_bid_1545, underlying_ask_1545, bid_1545, ask_1545, expiration, strike, option_type FROM optiondata WHERE underlying_symbol = '" + underlying + "' AND iv IS NULL ORDER BY id asc" 
    cur2.execute(query)
    
    for row in cur2:
        rowid = row[0]
        quote_date = row[1]
        underlying_bid_1545 = row[2]
        underlying_ask_1545 = row[3]
        bid_1545 = row[4]
        ask_1545 = row[5]
        expiration = row[6]
        strike = float(row[7])
        option_type = row[8].lower()
        current_quote = float((underlying_bid_1545 + underlying_ask_1545) / 2)
        midprice = float((bid_1545 + ask_1545) / 2)
        
        expiration_time = datetime.combine(expiration, time(16, 00))
        remaining_time_in_years = util.remaining_time(quote_date, expiration_time)
            
        iv = 0.001
        delta = 0.001 
        theta = 0.001 
        
        if remaining_time_in_years > 0: 
            try:
                iv = implied_volatility.implied_volatility(midprice, current_quote, int(strike), remaining_time_in_years, util.interest, option_type)
            except: 
                iv = 0.001
                
            delta = analytical.delta(option_type, current_quote, strike, remaining_time_in_years, util.interest, iv) * 100
            theta = analytical.theta(option_type, current_quote, strike, remaining_time_in_years, util.interest, iv) * 100 
    
        updateQuery = "UPDATE optiondata SET iv=%s, delta=%s, theta=%s WHERE id=%s" % (iv, delta, theta, rowid)
        try: 
            cur2.execute(updateQuery)
            db.commit()
        except: 
            print rowid 
            print current_quote
            print midprice
            print iv 
            print delta 
            print theta 
            print updateQuery
    
    db.close()
Esempio n. 5
0
def Calculate_delta(each_row):
    if each_row['Implied_Volatility'] == 0:
        measure= 0
    else:
        try:
            measure = bs_a.delta(flag=each_row['CallOrPut'], S=each_row['Spot'], K=each_row['Strike_Price'],
                                 t=each_row['Days_to_Expiry']/365, r=.1,sigma=each_row['Implied_Volatility'])
        except:
            measure = 0

    print("Delta", end = " ")
    return measure
Esempio n. 6
0
 def calc_all(self, b):
     h = self.all_set(b)
     if not h: return False
     if not h.get("sigma"): self.civ(h)
     if not h.get("sigma"): return False
     a = (h["flag"], h["F"], h["K"], h["t"], h["r"], h["sigma"])
     r = self.rounding
     h["price"] = round(oprice(*a), r)
     h["delta"] = round(delta(*a), r)
     h["gamma"] = round(gamma(*a) * 100, r)
     h["vega"] = round(vega(*a), r)
     return h
Esempio n. 7
0
    def delta(self, option_obj, asset_price, timestamp, expiration,
              call_put_flag):
        flag = call_put_flag
        S = asset_price
        K = option_obj.strike
        t = self.time_2_expiration(timestamp, expiration)
        r = self.risk_free_rate
        sigma = option_obj.sigma

        delta = vollib_greeks.delta(flag, S, K, t, r, sigma)

        return delta
Esempio n. 8
0
 def update_delta(self, asset_code):
     flag = asset_code[0].lower()
     S = self.mid_dict['IDX#PHX']
     if len(asset_code) == 6:
         K = int(asset_code[1:3])
     elif len(asset_code) == 7:
         K = int(asset_code[1:4])
     t = (63 - (time.time() - self.start_time) /
          (900 / 21)) / 252  #time to expiration in years
     r = 0
     price = self.mid_dict[asset_code]
     sigma = IV(price, S, K, r, t, flag) * np.sqrt(252)
     return bsga.delta(flag, S, K, t, r, sigma)
Esempio n. 9
0
def calculateAllGreeks(ticker, date, type, strike):
        S = si.get_live_price(ticker)
        K = strike
        sigma = calculateAnnualizedVolatility(ticker)
        t = optionExpiration(date)
        r = calculateTreasuryYield(date)
        if type == 'Call' or type == "call" or type == "C" or type == 'c':
            flag = 'c'
        else:
            flag = 'p'
        dlta = delta(flag, S, K, t, r, sigma)
        gam = gamma(flag, S, K, t, r, sigma)
        thta = theta(flag, S, K, t, r, sigma)
        vga = vega(flag, S, K, t, r, sigma)
        rh = rho(flag, S, K, t, r, sigma)
        return ({"delta": dlta, "gamma": gam, "theta": thta, "vega": vga, "rho": rh})
Esempio n. 10
0
def calculate_portfolio_delta(tick, securities_data, orders_data):
    S = securities_data["SAC"].last
    K = 50
    t =((300 - tick) / 15)/252
    r = 0
    sigma = .15
    
    d = delta("c", S, K, t, r, sigma)
    sac50c_position = -200
    delta_from_options = sac50c_position * d * 100

    sac_position = securities_data["SAC"].position
    delta_from_stocks = sac_position

    portfolio_delta = delta_from_options + delta_from_stocks
    return portfolio_delta
Esempio n. 11
0
def calculateGreek(ticker, date, type, strike, greek):
        grk = 0
        S = si.get_live_price(ticker)
        K = strike
        sigma = calculateAnnualizedVolatility(ticker)
        t = optionExpiration(date)
        r = calculateTreasuryYield(date)
        flag = ''
        if type == 'Call' or type == "call" or type == "C" or type == 'c':
            flag = 'c'
        flag = 'p'
        if greek == "Delta" or greek == "delta":
            grk = delta(flag, S, K, t, r, sigma)
        elif greek == "Gamma" or greek == "gamma":
            grk = gamma(flag, S, K, t, r, sigma)
        elif greek == "Theta" or greek == "theta":
            grk = theta(flag, S, K, t, r, sigma)
        elif greek == "Vega" or greek == "vega":
            grk = vega(flag, S, K, t, r, sigma)
        else:
            grk = rho(flag, S, K, t, r, sigma)
        return grk
Esempio n. 12
0
def on_update(msg, order):
    now = time.time()
    global tick
    ms = msg['market_state']
    tck = ms['ticker']
    last_price = msg['market_state']['last_price']
    tickers[tck]['price'].append(last_price)

    tick += 1

    if tck == fut:
        return

    S = tickers[fut]['price'][-1] if len(tickers[fut]['price']) > 0 else None
    K = int(tck[1:4]) if len(tck) == 5 else int(tck[1:3])
    t = (450 - tick) / 450 * 1 / 12
    flag = 'c' if tck[-1] == 'C' else 'p'

    if S is not None:
        try:
            iv = implied_volatility.implied_volatility(last_price, S, K, t, r,
                                                       flag)
            theo_p = black_scholes.black_scholes(flag, S, K, t, r, iv)
            delta = analytical.delta(flag, S, K, t, r, iv)
            gamma = analytical.gamma(flag, S, K, t, r, iv)
            # vega = analytical.vega(flag,S,K,t,r,iv)
            tickers[tck]['vol'].append(vol)
            tickers[tck]['delta'].append(delta)
            tickers[tck]['gamma'].append(gamma)
            # tickers[tck]['vega'].append(vega)

            if len(tickers[tck]['vol']) > 5:
                vol_sma = np.mean(np.array(ticker[tck]['vol'][-6:-1]))
                if abs(iv - vol_sma) / vol_sma > .015:
                    if iv > vol_sma: order.addSell(tck, 10, last_price + dx)
                    else: order.addBuy(tck, 10, last_price - dx)

        except:
            print(S, K, last_price, flag)
def precompute(table, computedate, underlying, include_riskfree):

    db = psycopg2.connect(host="localhost",
                          user=settings.db_username,
                          password=settings.db_password,
                          database="optiondata")
    cur2 = db.cursor()

    underlying_fragment = ""
    if (underlying != "*"):
        underlying_fragment = "underlying_symbol = '" + underlying + "' AND "

    date_fragment = ""
    if (computedate != "*"):
        date_fragment = "quote_date = '" + str(computedate) + "' AND "

    query = "SELECT id, quote_date, underlying_mid_1545, mid_1545, expiration, strike, option_type FROM " + \
        table + " WHERE " + underlying_fragment + date_fragment + "iv IS NULL"

    cur2.execute(query)
    result = cur2.fetchall()

    print(
        str(computedate) + " " + str(underlying) + ": " + str(len(result)) +
        " results")

    bulkrows = []
    if (len(result) > 0):
        for row in result:

            rowid = row[0]
            quote_date = row[1]
            underlying_mid_1545 = float(row[2])
            mid_1545 = float(row[3])
            expiration = row[4]
            strike = float(row[5])
            option_type = row[6]

            expiration_time = datetime.datetime.combine(
                expiration, datetime.time(16, 0))
            remaining_time_in_years = util.remaining_time(
                quote_date, expiration_time)

            rf = util.interest
            if include_riskfree:
                rf = util.get_riskfree_libor(quote_date,
                                             remaining_time_in_years)

            try:
                iv = implied_volatility.implied_volatility(
                    mid_1545, underlying_mid_1545, int(strike),
                    remaining_time_in_years, rf, option_type)
            except:
                iv = 0.001

            try:
                bs_price_bid_ask = black_scholes(option_type,
                                                 underlying_mid_1545, strike,
                                                 remaining_time_in_years, rf,
                                                 iv)
            except:
                bs_price_bid_ask = 0.001

            try:
                delta = analytical.delta(option_type, underlying_mid_1545,
                                         strike, remaining_time_in_years, rf,
                                         iv) * 100
            except:
                delta = 0.001

            try:
                theta = analytical.theta(option_type, underlying_mid_1545,
                                         strike, remaining_time_in_years, rf,
                                         iv) * 100
            except:
                theta = 0.001

            try:
                vega = analytical.vega(option_type, underlying_mid_1545,
                                       strike, remaining_time_in_years, rf,
                                       iv) * 100
            except:
                vega = 0.001

            bulkrows.append({
                'iv': iv,
                'bs_price_bid_ask': bs_price_bid_ask,
                'delta': delta,
                'theta': theta,
                'vega': vega,
                'rowid': rowid
            })

        psycopg2.extras.execute_batch(
            cur2,
            """UPDATE """ + table +
            """ SET iv=%(iv)s, bs_price_bid_ask=%(bs_price_bid_ask)s, delta=%(delta)s, theta=%(theta)s, vega=%(vega)s WHERE id=%(rowid)s""",
            bulkrows,
            page_size=100)
        db.commit()

        db.close()
Esempio n. 14
0
from py_vollib.black_scholes.greeks import analytical
from py_vollib.black_scholes.greeks import numerical

x = 'c', 10186, 10400, 10 / 250, 7.5, 11.5
print(analytical.delta(*x))
print(numerical.delta(*x))
Esempio n. 15
0
def precompute(underlying, include_riskfree):

    done = False
    bulksize = 100000
    counter = 0

    print("precompute: " + str(underlying))
    print()

    while not done:

        db = psycopg2.connect(host="localhost",
                              user=settings.db_username,
                              password=settings.db_password,
                              database="optiondata")
        cur2 = db.cursor()

        print("Query for next " + str(bulksize) + " items to precompute ")
        query = "SELECT id, quote_date, underlying_mid_1545, mid_1545, expiration, strike, option_type FROM optiondata WHERE underlying_symbol = '" + underlying + "' AND iv IS NULL LIMIT " + str(
            bulksize)
        cur2.execute(query)
        result = cur2.fetchall()
        print(str(len(result)) + " items to precompute")
        if len(result) == 0:
            done = True
            print("Done precomputing")
            print()

        bulkrows = []
        for row in result:

            rowid = row[0]
            quote_date = row[1]
            underlying_mid_1545 = float(row[2])
            mid_1545 = float(row[3])
            expiration = row[4]
            strike = float(row[5])
            option_type = row[6]

            expiration_time = datetime.datetime.combine(
                expiration, datetime.time(16, 0))
            remaining_time_in_years = util.remaining_time(
                quote_date, expiration_time)

            rf = util.interest
            if include_riskfree:
                rf = util.get_riskfree_libor(quote_date,
                                             remaining_time_in_years)

            try:
                iv = implied_volatility.implied_volatility(
                    mid_1545, underlying_mid_1545, int(strike),
                    remaining_time_in_years, rf, option_type)
                delta = analytical.delta(option_type, underlying_mid_1545,
                                         strike, remaining_time_in_years, rf,
                                         iv) * 100
                theta = analytical.theta(option_type, underlying_mid_1545,
                                         strike, remaining_time_in_years, rf,
                                         iv) * 100
                vega = analytical.vega(option_type, underlying_mid_1545,
                                       strike, remaining_time_in_years, rf,
                                       iv) * 100

            except:
                iv = 0.001
                delta = 0.001
                theta = 0.001
                vega = 0.001

            bulkrows.append({
                'iv': iv,
                'delta': delta,
                'theta': theta,
                'vega': vega,
                'rowid': rowid
            })
            counter += 1

            if (((counter % 1000) == 0) or ((len(result) < bulksize) and
                                            (counter == len(result)))):
                try:
                    cur2.executemany(
                        """UPDATE optiondata SET iv=%(iv)s, delta=%(delta)s, theta=%(theta)s, vega=%(vega)s WHERE id=%(rowid)s""",
                        bulkrows)
                    db.commit()
                    print("inserted: " + str(counter))
                    bulkrows = []
                    time.sleep(1)

                except Exception as e:
                    print("an exception occurred")
                    print(e)

            if (len(result) < bulksize) and (counter == len(result)):
                done = True
                print("Done precomputing")
                print()

    db.close()