Exemplo n.º 1
0
def get_delta(symbol: str, percent_move: float, expiry: str):
    s = Stock(symbol)
    up_px = s.price * (1 + percent_move / 100)
    down_px = s.price * (1 - percent_move / 100)
    call = Call(symbol,
                d=int(expiry[0:2]),
                m=int(expiry[3:5]),
                y=int(expiry[6:10]))
    up_delta_dict = get_strike_bracket(call.strikes, up_px)
    call.set_strike(up_delta_dict['lower_strike'])
    delta1 = call.delta() * up_delta_dict['lower_weight']
    call.set_strike(up_delta_dict['higher_strike'])
    delta2 = call.delta() * (1 - up_delta_dict['lower_weight'])
    delta_up_move = delta1 + delta2

    put = Put(symbol,
              d=int(expiry[0:2]),
              m=int(expiry[3:5]),
              y=int(expiry[6:10]))
    down_delta_dict = get_strike_bracket(put.strikes, down_px)
    put.set_strike(down_delta_dict['lower_strike'])
    delta1 = -put.delta() * down_delta_dict['lower_weight']
    put.set_strike(down_delta_dict['higher_strike'])
    delta2 = -put.delta() * (1 - down_delta_dict['lower_weight'])
    delta_down_move = delta1 + delta2
    return {'delta_up': delta_up_move, 'delta_down': delta_down_move}
Exemplo n.º 2
0
def get_delta(symbol: str, percent_move: float, expiry: str):
    symbol = symbol.upper()
    if is_cache_good(f'{symbol}|getdelta|{percent_move:.2f}|{expiry}'):
        return ast.literal_eval(
            r.hget(f'{symbol}|getdelta|{percent_move:.2f}|{expiry}', 'value'))
    s = Stock(symbol)
    up_px = s.price * (1 + percent_move / 100)
    down_px = s.price * (1 - percent_move / 100)
    call = Call(symbol,
                d=int(expiry[0:2]),
                m=int(expiry[3:5]),
                y=int(expiry[6:10]))
    up_delta_dict = get_strike_bracket(call.strikes, up_px)
    call.set_strike(up_delta_dict['lower_strike'])
    delta1 = call.delta() * up_delta_dict['lower_weight']
    call.set_strike(up_delta_dict['higher_strike'])
    delta2 = call.delta() * (1 - up_delta_dict['lower_weight'])
    delta_up_move = delta1 + delta2

    put = Put(symbol,
              d=int(expiry[0:2]),
              m=int(expiry[3:5]),
              y=int(expiry[6:10]))
    down_delta_dict = get_strike_bracket(put.strikes, down_px)
    put.set_strike(down_delta_dict['lower_strike'])
    delta1 = -put.delta() * down_delta_dict['lower_weight']
    put.set_strike(down_delta_dict['higher_strike'])
    delta2 = -put.delta() * (1 - down_delta_dict['lower_weight'])
    delta_down_move = delta1 + delta2
    return_dict = {'delta_up': delta_up_move, 'delta_down': delta_down_move}
    r.hset(f'{symbol}|getdelta|{percent_move:.2f}|{expiry}', 'time',
           datetime.utcnow().strftime('%s'))
    r.hset(f'{symbol}|getdelta|{percent_move:.2f}|{expiry}', 'value',
           str(return_dict))
    return return_dict
Exemplo n.º 3
0
 def opt_values(self, type, symbol, option, underlying, day, month, year, strike):
     if type == "Equity":
         price = Stock(symbol).price
         delta = 1
     elif option == "CALL":
         call = Call(underlying, day, month, year, strike)
         price = call.price
         delta = call.delta()
     elif option == "PUT":
         put = Put(underlying, day, month, year, strike)
         price = put.price
         delta = put.delta()
     else:
         price = 0
         delta = 0
     return price, delta
Exemplo n.º 4
0
    def get_data(self, df):
        tup = df.shape
        x = tup[0]
        y = tup[1]
        prices = []
        deltas = []
        for i in range(x):
            if df.iloc[i, 1] == "Equity":
                price = Stock(df.iloc[i, 0]).price
                delta = 1
                df.iloc[i, 2] = df.iloc[i, 0]

            elif df.iloc[i, 3] == "CALL":
                ticker = df.iloc[i, 2]
                strike = float(df.iloc[i, 5])
                date = datetime.strptime(df.iloc[i, 6], '%m/%d/%Y')
                month = date.month
                day = date.day
                year = date.year
                call = Call(ticker, day, month, year, strike)
                price = call.price
                delta = call.delta()

            elif df.iloc[i, 3] == "PUT":
                ticker = df.iloc[i, 2]
                strike = float(df.iloc[i, 5])
                date = datetime.strptime(df.iloc[i, 6], '%m/%d/%Y')
                month = date.month
                day = date.day
                year = date.year
                put = Put(ticker, day, month, year, strike)
                price = put.price
                delta = put.delta()

            else:
                price = 0
            prices.append(price)
            deltas.append(delta)
            print(prices, deltas)

        df["Prices"] = prices
        df["Deltas"] = deltas
        return df
Exemplo n.º 5
0
def best_call_trades(symbol, num_of_days):
    symbol = symbol.upper()
    if is_cache_good(f'{symbol}|calltrade|{num_of_days}'):
        return ast.literal_eval(
            r.hget(f'{symbol}|calltrade|{num_of_days}', 'value'))
    return_dict = {"error": "no options"}
    try:
        c = Call(symbol)
        range_dict = range_data_from_symbol(symbol, num_of_days)
        curr_date = str(datetime.date(datetime.now()))
        expiries = c.expirations
        expiry_to_use = expiries[0]
        for i in expiries:
            days_to_exp = abs(
                datetime.strptime(i, '%d-%m-%Y') -
                datetime.strptime(curr_date, '%Y-%m-%d')).days
            expiry_to_use = i
            if days_to_exp >= num_of_days:
                break
        c = Call(symbol,
                 d=int(expiry_to_use[0:2]),
                 m=int(expiry_to_use[3:5]),
                 y=int(expiry_to_use[6:10]))
        counter = 0
        spread_list = []
        strikes = c.strikes
        for i in strikes:
            if i >= range_dict["high_range"] and counter < 10:
                counter = counter + 1
                c.set_strike(i)
                spread_list.append({
                    'strike': i,
                    'bid': c.bid,
                    'ask': c.ask,
                    'last': c.price,
                    'using_last': 'false',
                    'delta': c.delta()
                })
        max_amt = 0
        max_call_amt = 0
        best_spread = {}
        best_call_written = {}

        for i in spread_list:
            #for call
            prob_winning_call = 1 - i['delta']  # Not expiring in the money
            i['using_last'] = 'false'
            if i['bid'] == 0 and i['ask'] == 0:
                i['bid'] = i['last']
                i['ask'] = i['last']
                i['using_last'] = 'true'
            premium_call = i['bid']
            call_win_amt = premium_call * prob_winning_call
            if call_win_amt > max_call_amt:
                max_call_amt = call_win_amt
                best_call_written = i
            for j in spread_list:
                if i['strike'] < j['strike']:
                    #for spread
                    premium_per_dollar = (i['bid'] - j['ask']) / (j['strike'] -
                                                                  i['strike'])
                    spread_using_last = 'false'
                    if i['using_last'] == 'true' or j[
                            'using_last'] == 'true':  #If any leg uses last mark spread as last
                        spread_using_last = 'true'
                    prob_winning_spread = 1 - j['delta']
                    win_amt = premium_per_dollar * prob_winning_spread
                    if win_amt > max_amt:
                        max_amt = win_amt
                        if spread_using_last == 'true':
                            best_spread = {
                                'strike_to_sell': i['strike'],
                                'strike_to_buy': j['strike'],
                                'premium_received': i['last'],
                                'premium_paid': j['last'],
                                'expiry': expiry_to_use,
                                'spread_using_last': spread_using_last
                            }
                        else:
                            best_spread = {
                                'strike_to_sell': i['strike'],
                                'strike_to_buy': j['strike'],
                                'premium_received': i['bid'],
                                'premium_paid': j['ask'],
                                'expiry': expiry_to_use,
                                'spread_using_last': spread_using_last
                            }

        best_call_written['expiry'] = expiry_to_use
        return_dict = {
            "symbol": symbol,
            'best_spread': best_spread,
            'best_call': best_call_written
        }
        if best_spread and best_call_written:
            r.hset(f'{symbol}|calltrade|{num_of_days}', 'time',
                   datetime.utcnow().strftime('%s'))
            r.hset(f'{symbol}|calltrade|{num_of_days}', 'value',
                   str(return_dict))
            return return_dict
    except:
        return return_dict
Exemplo n.º 6
0
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)
Exemplo n.º 7
0
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
Exemplo n.º 8
0
        optionType = 'None'

# 5: corresponding delta, strike prices
options_chain = options.get_options_chain(benchmark, actualHedgeDate)
options_chain = options_chain[optionType]
options_delta = pd.DataFrame()
options_delta['Strike'] = options_chain['Strike']
options_delta['Delta'] = np.NaN
if (optionType == 'calls'):
    for strike in range(0, len(options_delta)):
        d1 = Call(benchmark,
                  d=int(hedgeDay),
                  m=int(hedgeMonth),
                  y=int(hedgeYear),
                  strike=options_delta['Strike'][strike])
        options_delta.iloc[strike, 1] = d1.delta()
else:
    for strike in range(0, len(options_delta)):
        d1 = Put(benchmark,
                 d=int(hedgeDay),
                 m=int(hedgeMonth),
                 y=int(hedgeYear),
                 strike=options_delta['Strike'][strike])
        options_delta.iloc[strike, 1] = d1.delta()
st.write(options_delta)

# 6: strike prices for delta range
strike_range = 0
if reqDelta > 0:
    strike_range = options_delta[(0.35 <= options_delta['Delta'])
                                 & (options_delta['Delta'] <= 0.65)]