def High_IV_diff_flag_ratio(udlying): callIV = get_volatility(udlying, is_put=False)[-1]['value'] putIV = get_volatility(udlying, is_put=True)[-1]['value'] if callIV > 2 * putIV: s = Stock(udlying) if get_volume(udlying) > 1000000 and s.price > 10: High_IV_diff_list.append(udlying) print(udlying, "has call side skewed IV with req. met, ratio", callIV / putIV) elif putIV > 2 * callIV: s = Stock(udlying) if get_volume(udlying) > 1000000 and s.price > 10: High_IV_diff_list.append(udlying) print(udlying, "has put side skewed IV with req. met, ratio", putIV / callIV)
def detect_volatility_increase(ticker="AAPL"): """ Calculate avg volatiliy :param ticker: ticker name :param lookahead: lookahead :return: """ print(ticker) s = Stock(ticker) global abrupt_increase_list if get_volume(ticker) > 5000000 and s.price > 10: ivput_json = get_volatility(ticker, is_put=True) ivcall_json = get_volatility(ticker, is_put=False) ivput_now, ivput_past = ivput_json[-1]["value"], ivput_json[-2][ "value"] ivcall_now, ivcall_past = ivcall_json[-1]["value"], ivcall_json[-2][ "value"] # get the most recent values if ivput_now > 1.3 * ivput_past and ivput_now > 0.3: # s = Stock(ticker) # if get_volume(ticker) > 1000000 and s.price>10: print(ticker, "has abrupt increase in volatility") abrupt_increase_list.append(ticker) elif ivcall_now > 1.3 * ivcall_past and ivcall_now > 0.3: # s = Stock(ticker) # if get_volume(ticker) > 1000000 and s.price>10: print(ticker, "has abrupt increase in volatility") abrupt_increase_list.append(ticker)
def __store(): if not request.json or not 'objective' in request.json or not 'stockExchange' in request.json or not 'expectedValue' in request.json or database.count_documents( { 'stockExchange': request.json['stockExchange'], 'objective': request.json['objective'] }) > 0: abort(400) stock = Stock(request.json['stockExchange']) price = stock.price last_trade = pytz.timezone('UTC').localize( datetime.strptime(stock.last_trade, '%d %b %Y %H:%M:%S')).astimezone( pytz.timezone('Brazil/East')).strftime('%d/%m/%Y %H:%M:%S') database.insert_one({ 'objective': request.json['objective'], 'stockExchange': request.json['stockExchange'], 'expectedValue': request.json['expectedValue'], 'last_trade': last_trade, 'value': price, 'last_notification': last_trade }) data = database.find_one({'stockExchange': request.json['stockExchange']}) data['_id'] = str(data['_id']) objective = {'buy': 'comprar', 'sell': 'vender'} __sendNotification( 'Ativo adicionado.\nObjetivo: %s\nAtivo: %s\nValor esperado: R$%.2f' % (objective[data['objective']], data['stockExchange'], data['expectedValue'])) return data
def do_GET(self): s = self.path dic = dict(parse.parse_qsl(parse.urlsplit(s).query)) self.send_response(200) self.send_header('Content-type', 'text/plain') self.end_headers() curr_date = str(datetime.date(datetime.now())) if "sym" in dic: if dic["sym"] == 'WTF': message = "r/Wsb eTF?\nH🥚dl." else: try: my_stock = Stock(dic["sym"]) my_tuple = get_atm_ivol(my_stock, 7) curr_price = my_stock.price low = curr_price - 1.15 * my_tuple[1] * curr_price high = curr_price + 1.15 * my_tuple[1] * curr_price message = f'{{"symbol":"{my_stock.ticker}","price":"{round(my_stock.price)}","low":"{round(low)}","high":"{round(high)}"}}' except: message = '{"symbol":"invalid_symbol"}' else: message = "Hello, stranger!" self.wfile.write(message.encode()) return
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
def range_data_from_symbol(symbol, ndays=7, sigma=1.15): symbol = symbol.upper() return_dict = {"symbol": "Error", "desc": "No Data found for %s" % symbol} try: if is_cache_good(f'{symbol}|range|{ndays}|{sigma}'): return ast.literal_eval( r.hget(f'{symbol}|range|{ndays}|{sigma}', 'value')) r.hset(f'{symbol}|range|{ndays}|{sigma}', 'time', datetime.utcnow().strftime('%s')) s = Stock(symbol) prob = prob_move_pct(symbol, ndays, 0) if "error" in prob: return {"error": "no options"} my_tuple = get_atm_ivol(s, ndays) volume = stock_volume(symbol, ndays) return_dict["symbol"] = symbol return_dict["desc"] = s.name return_dict["price"] = s.price return_dict["ivol"] = my_tuple[0] return_dict["low_range"] = s.price - s.price * my_tuple[1] * sigma return_dict["high_range"] = s.price + s.price * my_tuple[1] * sigma return_dict["volume_pct"] = volume["percentile"] return_dict["today_volume"] = volume["volume"] return_dict["avg_10d_volume"] = volume["avg_10d_volume"] return_dict["prob_up"] = prob["prob_up"] r.hset(f'{symbol}|range|{ndays}|{sigma}', 'time', datetime.utcnow().strftime('%s')) r.hset(f'{symbol}|range|{ndays}|{sigma}', 'value', str(return_dict)) return return_dict except: return return_dict
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}
def group_exp(self, df): ticker = df.iloc[0,2] stock_px = float(Stock(ticker).price) inc = max(round(stock_px / 100),0.25) price = round(stock_px + (inc * 5)) for i in range(10): df[f'$ {price}'] = df.apply(lambda x: self.eqty_exp(x['Type'], price, x['Option Type'], x['Quantity'], x['Strike Price'], x['Rate'], x['Time'], x['Vol']), axis = 1) price = price - inc return df
def stock(bot, update, args): if len(args) < 1: update.message.reply_text("Usage: /stock <ticker>") return ticker = args[0] stk = Stock(ticker, source="yahoo") name = stk.name name = name.replace("&", "&") update.message.reply_text( "{}({}) 最近交易价格为{:.2f}, 最近交易日变动{:.2f}({:.1f}%)".format( name, stk.ticker, stk.price, stk.change, stk.cp))
def opt_prices(self, type, symbol, option, underlying, day, month, year, strike): if type == "Equity": price = Stock(symbol).price elif option == "CALL": call = Call(underlying, day, month, year, strike) price = call.price elif option == "PUT": put = Put(underlying, day, month, year, strike) price = put.price else: price = 0 return price
def price_filter(udlying, min_price=30, max_price=200): """ filter price between min and max add filtered price to filtered_list :param udlying: stock :param min_price: min price default 30 :param max_price: max price dafult 200 :return: None """ global filtered_list s = Stock(udlying) if min_price < s.price < max_price: filtered_list.append(udlying)
def get_quotes_from_yahoo(reload_weekly=False): if reload_weekly: tickers = save_weekly_earnings() else: with open("saveweekly.pickle", "rb") as f: tickers = pickle.load(f) for ticker in tickers: print(ticker) g = Stock(ticker, source='yahoo') price = g.price PutATM = Put(ticker, strike=price, source='yahoo') b = PutATM.price CallATM = Call(ticker, strike=price, source='yahoo') a = CallATM.price print("Put ATM:", a, "Call ATM:", b) iv = (a + b) poms = PutATM.strike pom = poms - iv coms = CallATM.strike com = coms + iv PutIV = Put(ticker, strike=pom, source='yahoo') PutIV2 = Put(ticker, strike=pom - 3, source='yahoo') pl = PutIV.price pl2 = PutIV2.price pis = PutIV.strike pis2 = PutIV2.strike CallIV = Call(ticker, strike=com, source='yahoo') CallIV2 = Call(ticker, strike=com + 3, source='yahoo') cl = CallIV.price cl2 = CallIV2.price cis = CallIV.strike cis2 = CallIV2.strike MaxLossP = pis - pis2 MaxLossC = cis - cis2 ProfitP = 100 * (pl - pl2) / (MaxLossP + 0.00001) ProfitC = 100 * (cl2 - cl) / (MaxLossC + 0.00001) print("Implied Volatility:", iv, "Puts Outside of IV:", pl, "Calls Outside of IV:", cl) print("Profit from selling puts at", pis, "and buying at", pis2, ":", ProfitP, "%") print("Profit from selling calls at", cis, "and buying at", cis2, ":", ProfitC, "%")
def prob_move_sigma(symbol: str, n_days: int, sigma_fraction_to_use: float): symbol = symbol.upper() if is_cache_good(f'{symbol}|pmovesigma|{n_days}|{sigma_fraction_to_use}'): return ast.literal_eval( r.hget(f'{symbol}|pmovesigma|{n_days}|{sigma_fraction_to_use}', 'value')) return_dict = {"error": "no options"} try: c = Call(symbol) expiries = c.expirations curr_date = str(datetime.date(datetime.now())) expiry_to_use = expiries[0] my_n_days = 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 my_n_days = days_to_exp if days_to_exp >= n_days: break my_tuple = get_atm_ivol(Stock(symbol), my_n_days) my_percent = my_tuple[1] * 100 * sigma_fraction_to_use my_delta = get_delta(symbol, my_percent, expiry_to_use) prob_down = my_delta['delta_down'] prob_up = my_delta['delta_up'] norm_prob_down = 0 norm_prob_up = 0 if prob_up > prob_down: norm_prob_down = 0.5 norm_prob_up = prob_up * 0.5 / prob_down else: norm_prob_up = 0.5 norm_prob_down = prob_down * 0.5 / prob_up return_dict = { "symbol": symbol, "move_percent": my_percent, 'expiry': expiry_to_use, "prob_down": prob_down, "norm_prob_down": norm_prob_down, "prob_up": prob_up, "norm_prob_up": norm_prob_up } r.hset(f'{symbol}|pmovesigma|{n_days}|{sigma_fraction_to_use}', 'time', datetime.utcnow().strftime('%s')) r.hset(f'{symbol}|pmovesigma|{n_days}|{sigma_fraction_to_use}', 'value', str(return_dict)) return return_dict except: return return_dict
def High_IV_diff_flag(udlying): callIV = get_volatility(udlying, is_put=False)[-1]['value'] putIV = get_volatility(udlying, is_put=True)[-1]['value'] if abs(callIV - putIV) > 0.5: print(udlying, "has large IV diff") s = Stock(udlying) if get_volume(udlying) > 1000000 and s.price > 10: High_IV_diff_list.append(udlying) if callIV > putIV: print(udlying, "has call side skewed IV with req. met, diff", abs(callIV - putIV)) elif putIV > callIV: print(udlying, "has put side skewed IV with req. met, diff", abs(callIV - putIV))
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
def implied_forward(symbol, n_days): s = Stock(symbol) c = Call(symbol) curr_date = str(datetime.date(datetime.now())) expiries = c.expirations expiry_to_use = expiries[0] my_n_days = 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 my_n_days = days_to_exp if days_to_exp >= n_days: break call = Call(symbol, d=int(expiry_to_use[0:2]), m=int(expiry_to_use[3:5]), y=int(expiry_to_use[6:10])) put = Put(symbol, d=int(expiry_to_use[0:2]), m=int(expiry_to_use[3:5]), y=int(expiry_to_use[6:10])) bracket_dict = get_strike_bracket(call.strikes, s.price) forward = s.price if bracket_dict['lower_weight'] > 0.5: call.set_strike(bracket_dict['lower_strike']) put.set_strike(bracket_dict['lower_strike']) forward = bracket_dict['lower_strike'] - put.price + call.price else: call.set_strike(bracket_dict['higher_strike']) put.set_strike(bracket_dict['higher_strike']) forward = bracket_dict['higher_strike'] - put.price + call.price return { "symbol": symbol, "forward_price": forward, "current_price": s.price, "expiry": expiry_to_use }
def group_vol_exp(self, df): ticker = df.iloc[0, 2] stock_px = float(Stock(ticker).price) tup = df.shape x = tup[0] y= tup[1] z = 0 vol = 0 ; avgvol = 0 for i in range (x): if df.iloc[i, 1] == "Option": vol = df.iloc[i, 12] + vol z = z + 1 avgvol = vol / z inc = avgvol * 0.1 vol = avgvol - inc * 5 temp = round(vol*100) for i in range (10): temp = round(vol*100,2) df[f'{temp}%'] = df.apply(lambda x: self.vol_exp(x['Type'], stock_px, x['Option Type'], x['Quantity'], x['Strike Price'], x['Rate'], x['Time'], vol, avgvol), axis=1) vol = vol + inc return df
def get_options(sym, strike_date): put = Put(sym, d=strike_date.day, m=strike_date.month, y=strike_date.year, strict=True, source='yahoo') call = Call(sym, d=strike_date.day, m=strike_date.month, y=strike_date.year, strict=True, source='yahoo') stock = Stock(sym) price = get_closest(stock.price, put.strikes) put.set_strike(price) call.set_strike(price) return [ stock.price, price, put.price, put.volume, call.price, call.volume, format_date(put.expiration), format_date(call.expiration) ]
newData = {'Returns': portRet, 'Volatility': portVol} for counter, symbol in enumerate(prices.columns.tolist()): newData[symbol] = [w[counter] for w in portWeights] #get results for ideal portfolio rf = 0.01 portfolios = pd.DataFrame(newData) optimalPort = portfolios.iloc[((portfolios['Returns'] - rf) / portfolios['Volatility']).idxmax()] newKeysList = optimalPort.keys() #print results and metrics print("\nPortfolio Size = $" + str(portfolioSize)) count = 0 for key in newKeysList: if (count < 2): print(str(key) + ": " + str(round(optimalPort[key] * 100, 2)) + "%") count += 1 else: percentPort = portfolioSize * optimalPort[key] currentPrice = Stock(key).price sharesNum = math.floor(percentPort / currentPrice) if (count == 2): print("") count += 1 print(str(key) + " has a stock price of $" + str(currentPrice)) print("Buy " + str(sharesNum) + " shares of " + str(key))
symbol = values['__symbol'] price = 0 if values['__price'] == '' else Decimal(values['__price']) expdate = None if values['__expdate'] == '' else date.fromisoformat( values['__expdate']) target1 = 0 if values['__target1'] == '' else Decimal( values['__target1']) target2 = 0 if values['__target2'] == '' else Decimal( values['__target2']) #strike1 = 0 if values['__strike_price'] == '' else Decimal(values['__strike_price']) #strike_inc = 0 if values['__strike_price_inc'] == '' else Decimal(values['__strike_price_inc']) #if not is_call: # strike_inc *= -1 errors = False if symbol is not None and len(symbol) > 0: try: s = Stock(symbol) window['__price'].update(s.price) except requests.exceptions.ConnectionError as ConnectionError: window['__price'].update("ERROR") errors = True # Get strikes and populate. # TODO: Wait for the price to update if expdate is not None and not errors: o = None # This is our option object. if is_call: o = Call(symbol, d=expdate.day, m=expdate.month, y=expdate.year) print("CALLS") else:
def best_put_protection(symbol, num_of_days): symbol = symbol.upper() if is_cache_good(f'{symbol}|putprotection|{num_of_days}'): return ast.literal_eval( r.hget(f'{symbol}|putprotection|{num_of_days}', 'value')) try: p = Put(symbol) s = Stock(symbol) curr_date = str(datetime.date(datetime.now())) expiries = p.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 p = Put(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 = p.strikes for i in reversed(strikes): if i <= s.price and counter < 10: counter = counter + 1 p.set_strike(i) spread_list.append({ 'strike': i, 'bid': p.bid, 'ask': p.ask, 'last': p.price, 'using_last': 'false', 'delta': -p.delta() }) min_put_strength = 100000 best_put = {} spread_list.reverse() for i in spread_list: #for put prob_in_the_money_put = i['delta'] i['using_last'] = 'false' if i['bid'] == 0 or i['ask'] == 0: i['bid'] = i['last'] i['ask'] = i['last'] i['using_last'] = 'true' premium_put = i['ask'] put_cost_per_money = premium_put / prob_in_the_money_put if put_cost_per_money < min_put_strength: min_put_strength = put_cost_per_money best_put = i best_put['expiry'] = expiry_to_use return_dict = {"symbol": symbol, 'best_put': best_put} if best_put: r.hset(f'{symbol}|putprotection|{num_of_days}', 'time', datetime.utcnow().strftime('%s')) r.hset(f'{symbol}|putprotection|{num_of_days}', 'value', str(return_dict)) return return_dict except: return {"error": "No options were found"}
# https://github.com/mcdallas/wallstreet from wallstreet import Stock, Call, Put import numpy as mp s = Stock('AAPL') print(s.change) apple = Stock('AAPL', source='yahoo') print(apple) call = Call('AAPL', strike=apple.price, source='yahoo') p = Stock('BTC-USD') print(p) r = Call('RACE', d=10, m=7, y=2020) print(r.strikes) print(r.underlying.price)
def __notificate(): notificateText = '' out = [] for data in database.find(): stock = Stock(data['stockExchange']) price = stock.price last_trade = stock.last_trade objective = { 'buy': [price <= data['expectedValue'], 'COMPRA'], 'sell': [price >= data['expectedValue'], 'VENDA'] } if data['last_trade'] != pytz.timezone('UTC').localize( datetime.strptime(last_trade, '%d %b %Y %H:%M:%S')).astimezone( pytz.timezone('Brazil/East')).strftime( '%d/%m/%Y %H:%M:%S'): if objective[data['objective']][0] and ( datetime.utcnow() - pytz.timezone('Brazil/East').localize( datetime.strptime(data['last_notification'], '%d/%m/%Y %H:%M:%S')).astimezone( pytz.timezone('UTC')). replace(tzinfo=None)).total_seconds() / 60 > 5: database.update_one({'_id': data['_id']}, { '$set': { 'last_notification': pytz.timezone('UTC').localize( datetime.utcnow()).astimezone( pytz.timezone('Brazil/East')).strftime( '%d/%m/%Y %H:%M:%S') } }) notificateText = notificateText + '[%s] %s: R$%.2f | %s\n' % ( objective[data['objective']][1], data['stockExchange'], price, pytz.timezone('UTC').localize( datetime.strptime(last_trade, '%d %b %Y %H:%M:%S') ).astimezone(pytz.timezone('Brazil/East')).strftime( '%d/%m/%Y às %H:%M:%S')) database.update_one({'_id': data['_id']}, { '$set': { 'last_trade': pytz.timezone('UTC').localize( datetime.strptime( last_trade, '%d %b %Y %H:%M:%S')).astimezone( pytz.timezone('Brazil/East')).strftime( '%d/%m/%Y %H:%M:%S'), 'value': price } }) data = database.find_one({'_id': data['_id']}) out.append({ '_id': str(data['_id']), 'objective': data['objective'], 'stockExchange': data['stockExchange'], 'expectedValue': data['expectedValue'], 'last_notification': data['last_notification'], 'value': price, 'last_trade': pytz.timezone('UTC').localize( datetime.strptime(last_trade, '%d %b %Y %H:%M:%S')).astimezone( pytz.timezone('Brazil/East')).strftime('%d/%m/%Y %H:%M:%S') }) if notificateText != '': __sendNotification(notificateText) return jsonify(out)
def updatePrice(self): try: self.price = Stock(self.getTick(), source='yahoo').price except: self.price = "Price Error"
def getStockPrice(tickerSymbol): s = Stock(tickerSymbol, source="yahoo") return s.price
def putCreditSpread(tick, minDays, maxDays, strikeSpread, minPoP): s = Stock(tick) stockPrice = s.price validExpirations = expirationsOfInterest(tick, minDays, maxDays) print('List of valid expirations:\n') print(validExpirations) print('\n') my_columns = ['Expiry', 'PoP', 'Premium', 'Long Strike', 'Short Strike'] #spread_dataframe = pd.DataFrame(columns = my_columns) frames = [] for expDate in validExpirations[:1]: print('Current expiration being analyzed\n') print(expDate) expir = expDate.split('-') day = int(expir[0]) month = int(expir[1]) year = int(expir[2]) if day == 3: blah = 5 day = 5 month = 3 year = 2021 temp = Put(tick, d=day, m=month, y=year) spread_dataframe = pd.DataFrame(columns=my_columns) strikes = [] strike1 = [] strike2 = [] longStrike = [] shortStrike = [] longPremium = [] shortPremium = [] strikes = (temp.strikes) strikes = [ strike for strike in strikes if (strike / stockPrice > 1 - strikeSpread and strike / stockPrice < 1 + strikeSpread) ] strike1 = [a for (a, b) in itertools.product(strikes, strikes)] strike2 = [b for (a, b) in itertools.product(strikes, strikes)] for i in range(0, len(strike1)): if strike1[i] < strike2[i]: longStrike.append(strike1[i]) shortStrike.append(strike2[i]) temp.set_strike(strike1[i]) price = (temp.bid + temp.ask) / 2 longPremium.append(price) temp.set_strike(strike2[i]) price = (temp.bid + temp.ask) / 2 shortPremium.append(price) elif strike1[i] > strike2[i]: longStrike.append(strike2[i]) shortStrike.append(strike1[i]) temp.set_strike(strike1[i]) price = (temp.bid + temp.ask) / 2 shortPremium.append(price) temp.set_strike(strike2[i]) price = (temp.bid + temp.ask) / 2 longPremium.append(price) else: continue for i in range(0, len(shortStrike)): credit = shortPremium[i] - longPremium[i] strikeWidth = shortStrike[i] - longStrike[i] spread_dataframe = spread_dataframe.append(pd.Series( [ expir, 100 - credit / strikeWidth * 100, credit, longStrike[i], shortStrike[i] ], index=my_columns), ignore_index=True) frames.append(spread_dataframe) result = pd.concat(frames) spread_dataframe.sort_values('PoP', ascending=False, inplace=True) spread_dataframe.reset_index(drop=True, inplace=True) spread_dataframe = spread_dataframe[spread_dataframe['PoP'] >= minPoP] result.sort_values('PoP', ascending=False, inplace=True) result.reset_index(drop=True, inplace=True) result = result[spread_dataframe['PoP'] >= minPoP] return result
spread_dataframe = spread_dataframe[spread_dataframe['PoP'] >= minPoP] result.sort_values('PoP', ascending=False, inplace=True) result.reset_index(drop=True, inplace=True) result = result[spread_dataframe['PoP'] >= minPoP] return result #%% tick = 'PLTR' minDays = 15 maxDays = 45 strikeSpread = 0.2 # percentage to vary around underlying stock price minPoP = 60 #%% spread_dataframe = putCreditSpread(tick, minDays, maxDays, strikeSpread, minPoP) #%% s = Stock(tick) stockPrice = s.price print( f'Credit Spread Table for {tick} at the current trading price of {stockPrice}' ) print(spread_dataframe)
pickle.dump(tickers, f) return tickers tickers = save_sp500_tickers() tickers = [x.split()[0] for x in tickers] tickers.remove('BRK.B') tickers.remove('BF.B') main_df = pd.DataFrame() for i in range(len(tickers)): item = tickers[i] print(i, item) s = Stock(item) f = s.historical(days_back=1035, frequency='d') f.index = f['Date'] f.drop('Date', axis=1, inplace=True) f.columns = [x + '_' + item for x in f.columns] if main_df.empty: main_df = f else: main_df = pd.merge(main_df, f, left_index=True, right_index=True, how='outer') main_df.to_csv('STOCK_S&P500.csv')
from wallstreet import Stock, Call, Put s = Stock('AAPL') print(s.price)
def findPrice(self,ticker): stock = Stock(ticker,source='yahoo') return(str(stock.price))