def test_analytical_theta(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.theta('c', S, K, t, r, sigma), row['CT'] / 365.0, delta=0.000001) self.assertAlmostEqual(analytical.theta('p', S, K, t, r, sigma), row['PT'] / 365.0, delta=0.000001)
def test_analytical_theta(self): S = 49 K = 50 sigma = .2 r = .05 t = 0.3846 flag = 'p' c_put = c_analytical.theta(flag, S, K, t, r, sigma) py_put = py_analytical.theta(flag, S, K, t, r, sigma) self.assertTrue(almost_equal(c_put, py_put)) flag = 'c' c_call = c_analytical.theta(flag, S, K, t, r, sigma) py_call = py_analytical.theta(flag, S, K, t, r, sigma) self.assertTrue(almost_equal(c_call, py_call))
def test_theta(self): thetas = [ theta(flag, S, K, t, r, sigma) for flag, S, K, t, r, sigma in self.arg_combinations ] nthetas = [ ntheta(flag, S, K, t, r, sigma) for flag, S, K, t, r, sigma in self.arg_combinations ] self.assertTrue(self.diff_mean(thetas, nthetas) < self.epsilon)
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()
def Calculate_theta(each_row): if each_row['Implied_Volatility'] == 0: measure= 0 else: try: measure = bs_a.theta(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("Theta", end=" ") return measure
def theta(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 theta = vollib_greeks.theta(flag, S, K, t, r, sigma) return theta
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})
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
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()
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()