def get_atm_ivol(s, ndays=30): #Need to fix for divs, borrow etc to find atm symbol = s.ticker expiry_dict = get_expiries_bracket(symbol, ndays) #First Shorter One x = expiry_dict['shorter_expiry'] shorter_call = Call(symbol, d=int(x[0:2]), m=int(x[3:5]), y=int(x[6:10])) strike_dict = get_strike_bracket(shorter_call.strikes, s.price) shorter_call.set_strike(strike_dict['lower_strike']) lower_vol = shorter_call.implied_volatility() shorter_call.set_strike(strike_dict['higher_strike']) higher_vol = shorter_call.implied_volatility() shorter_ivol = lower_vol * strike_dict['lower_weight'] + higher_vol * ( 1 - strike_dict['lower_weight']) #Now longer One x = expiry_dict['longer_expiry'] longer_call = Call(symbol, d=int(x[0:2]), m=int(x[3:5]), y=int(x[6:10])) strike_dict = get_strike_bracket(longer_call.strikes, s.price) longer_call.set_strike(strike_dict['lower_strike']) lower_vol = longer_call.implied_volatility() longer_call.set_strike(strike_dict['higher_strike']) higher_vol = longer_call.implied_volatility() longer_ivol = lower_vol * strike_dict['lower_weight'] + higher_vol * ( 1 - strike_dict['lower_weight']) implied_ivol = shorter_ivol * expiry_dict[ 'shorter_weight'] + longer_ivol * (1 - expiry_dict['shorter_weight']) one_sigma_move_ndays_day = implied_ivol * math.sqrt(ndays / 365) return (implied_ivol, one_sigma_move_ndays_day)
def opt_vol(self, type, symbol, option, underlying, day, month, year, strike): if type == "Equity": vol = 1 elif option == "CALL": call = Call(underlying, day, month, year, strike) vol = float(call.implied_volatility()) elif option == "PUT": put = Put(underlying, day, month, year, strike) vol = float(put.implied_volatility()) else: vol = 0 return vol
def get_atm_ivol(s, ndays=30): #Need to fix for divs, borrow etc to find atm symbol = s.ticker symbol = symbol.upper() if is_cache_good(f'{symbol}|getatmivol|{ndays}'): return ast.literal_eval(r.hget(f'{symbol}|getatmivol|{ndays}', 'value')) expiry_dict = get_expiries_bracket(symbol, ndays) #First Shorter One x = expiry_dict['shorter_expiry'] shorter_call = Call(symbol, d=int(x[0:2]), m=int(x[3:5]), y=int(x[6:10])) strike_dict = get_strike_bracket(shorter_call.strikes, s.price) shorter_call.set_strike(strike_dict['lower_strike']) lower_vol = shorter_call.implied_volatility() shorter_call.set_strike(strike_dict['higher_strike']) higher_vol = shorter_call.implied_volatility() shorter_ivol = lower_vol * strike_dict['lower_weight'] + higher_vol * ( 1 - strike_dict['lower_weight']) #Now longer One x = expiry_dict['longer_expiry'] longer_call = Call(symbol, d=int(x[0:2]), m=int(x[3:5]), y=int(x[6:10])) strike_dict = get_strike_bracket(longer_call.strikes, s.price) longer_call.set_strike(strike_dict['lower_strike']) lower_vol = longer_call.implied_volatility() longer_call.set_strike(strike_dict['higher_strike']) higher_vol = longer_call.implied_volatility() longer_ivol = lower_vol * strike_dict['lower_weight'] + higher_vol * ( 1 - strike_dict['lower_weight']) implied_ivol = shorter_ivol * expiry_dict[ 'shorter_weight'] + longer_ivol * (1 - expiry_dict['shorter_weight']) one_sigma_move_ndays_day = implied_ivol * math.sqrt(ndays / 365) return_dict = (implied_ivol, one_sigma_move_ndays_day) r.hset(f'{symbol}|getatmivol|{ndays}', 'time', datetime.utcnow().strftime('%s')) r.hset(f'{symbol}|getatmivol|{ndays}', 'value', str(return_dict)) return return_dict
def infos(udlying, day, month, year, stockprice, offset): """ Group information :param udlying: underlying stock object :param day: int digits :param month: int digits :param year: :param stockprice: stock price :param offset: strike offset :return: Tuple of all data """ u = Call(udlying, d=day, m=month, y=year, strike=stockprice + offset) price = u.price IV = u.implied_volatility() v = u.vega() g = u.gamma() strike = u.strike return (IV, v, g, price, strike)
def opt_vol_r_T(self, type, symbol, option, underlying, day, month, year, strike): if type == "Equity": time = 1 rate = 1 vol = 1 elif option == "CALL": call = Call(underlying, day, month, year, strike) time = call.BandS.T rate = float(call.BandS.r) vol = float(call.implied_volatility()) elif option == "PUT": put = Put(underlying, day, month, year, strike) time = put.BandS.T rate = float(put.BandS.r) vol = float(put.implied_volatility()) else: time = 0; rate = 0; vol = 0 return time, rate, vol
symbol = args[2] day = int(args[3]) month = int(args[4]) year = int(args[5]) min_strike = int(args[6]) max_strike = int(args[7]) step = int(args[8]) options = [] price = min_strike while price <= max_strike: option = Call(symbol, d=day, m=month, y=year, strike=price) if method == 'call' else Put( symbol, d=day, m=month, y=year, strike=price) options.append([ price, option.price, option.implied_volatility(), option.volume, option.underlying.price, option.delta(), option.gamma(), option.theta(), option.expiration ]) price += step df = pd.DataFrame(options, columns=[ 'Strike', 'Price', 'Implied Vol', 'Volume', 'Underlying', 'Delta', 'Gamma', 'Theta', 'Expiration' ]) print(df)
def main(): parser = argparse.ArgumentParser( description="Find best trading strategies") group = parser.add_mutually_exclusive_group() parser.add_argument("ticker", type=str, help="stock ticker") # group.add_argument("-t", "--ticker", action="store_true") group.add_argument("-d", "--date", action="store_true") parser.add_argument("-s", "--strategy", help="the strategy") # parser.add_argument("y", type=int, help="the exponent") args = parser.parse_args() ticker = yf.Ticker(args.ticker) # get stock info print('****** Info **********') print(ticker.info) # input("Press Enter to continue...") # get historical market data print('****** History **********') hist = ticker.history(period="max") print(hist) # input("Press Enter to continue...") print('****** Actions **********') # show actions (dividends, splits) print(ticker.actions) # input("Press Enter to continue...") print('****** dividends **********') # show dividends print(ticker.dividends) # input("Press Enter to continue...") # show splits ticker.splits # show financials print('****** financials **********') print(ticker.financials) print(ticker.quarterly_financials) # input("Press Enter to continue...") # show major holders print(ticker.major_holders) # show institutional holders print(ticker.institutional_holders) # input("Press Enter to continue...") # show balance heet print(ticker.balance_sheet) print(ticker.quarterly_balance_sheet) # show cashflow ticker.cashflow ticker.quarterly_cashflow # show earnings print(ticker.earnings) print(ticker.quarterly_earnings) # show sustainability print(ticker.sustainability) # show analysts recommendations print(ticker.recommendations) # show next event (earnings, etc) print('****** calendars **********') print(ticker.calendar) # input("Press Enter to continue...") # show ISIN code - *experimental* # ISIN = International Securities Identification Number print(ticker.isin) # show options expirations print('****** calendars **********') print(ticker.options) # input("Press Enter to continue...") # get option chain for specific expiration opt = ticker.option_chain(ticker.options[0]) # data available via: opt.calls, opt.puts print(opt.calls) # input("Press Enter to continue...") print(opt.puts) # input("Press Enter to continue...") history = ticker.history() last_quote = (history.tail(1)['Close'].iloc[0]) last_price = int(last_quote) # calls for opt in ticker.options: try: data = [] dt = datetime.fromisoformat(opt) option = Call(args.ticker ) # d=dt.day, m=dt.month, y=dt.year, strike=ticker.) for strike in option.strikes: if strike < last_price - 40 or strike > last_price + 25: continue print(f'strike = {strike}') option.set_strike(strike) item = {} item['strike'] = strike item['price'] = option.price item['iv'] = option.implied_volatility() item['delta'] = option.delta() item['vega'] = option.vega() item['gamma'] = option.gamma() # print(f'theta = {option.theta()}') # print(f'vega = {option.vega()}') data.append(item) dataframe = pd.DataFrame(data) dataframe.to_csv(f'call-{args.ticker}-{dt}') print(dataframe.to_csv()) except Exception as e: print(f'{type(e)}: {str(e)} ') continue # put for opt in ticker.options: try: data = [] dt = datetime.fromisoformat(opt) option = Put( args.ticker ) # d=dt.day, m=dt.month, y=dt.year, strike=ticker.) for strike in option.strikes: if strike < last_price - 40 or strike > last_price + 25: continue print(f'strike = {strike}') option.set_strike(strike) item = {} item['strike'] = strike item['price'] = option.price item['iv'] = option.implied_volatility() item['delta'] = option.delta() item['vega'] = option.vega() item['gamma'] = option.gamma() # print(f'Rho = {option.rho()}') # print(f'type = {option.Option_type}') # print(f'theta = {option.theta()}') # print(f'vega = {option.vega()}') data.append(item) dataframe = pd.DataFrame(data) dataframe.to_csv(f'put-{args.ticker}-{dt}') print(dataframe.to_csv()) except Exception as e: print(f'{type(e)}: {str(e)} ') continue
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Wallstreet package can be found in the following link https://pypi.python.org/pypi/wallstreet/0.1.5 @author: chenkai """ from wallstreet import Stock, Call, Put import pandas as pd import numpy as np import matplotlib.pyplot as plt g = Call('SPX', d=20, m=7, y=2018, source='yahoo') x = g.strikes y = np.zeros(len(x)) for i in range(len(x)): g.set_strike(x[i]) y[i] = g.implied_volatility() plt.plot(x, y) plt.scatter(x, y)