def find_options_by_strike(inputSymbols, strikePrice, optionType=None, info=None): """Returns a list of all the option orders that match the seach parameters :param inputSymbols: The ticker of either a single stock or a list of stocks. :type inputSymbols: str :param strikePrice: Represents the strike price to filter for. :type strikePrice: str :param optionType: Can be either 'call' or 'put' or leave blank to get both. :type optionType: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all options of the stock that match the search parameters. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ try: symbols = helper.inputs_to_set(inputSymbols) if optionType: optionType = optionType.lower().strip() except AttributeError as message: print(message, file=helper.get_output()) return [None] data = [] for symbol in symbols: filteredOptions = find_tradable_options(symbol, None, strikePrice, optionType, None) for item in filteredOptions: marketData = get_option_market_data_by_id(item['id']) item.update(marketData) write_spinner() data.extend(filteredOptions) return(helper.filter(data, info))
def delete_symbols_from_watchlist(inputSymbols, name='Default'): """Deletes multiple stock tickers from a watchlist. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param name: The name of the watchlist to delete data from. :type name: Optional[str] :returns: Returns result of the delete request. """ symbols = helper.inputs_to_set(inputSymbols) symbols = stocks.get_fundamentals(symbols, info='instrument') watchlist = get_watchlist_by_name(name=name) items = [] data = None for symbol in symbols: for list_ in watchlist: if symbol == list_['instrument']: items.append(symbol[37:]) for item in items: url = urls.watchlists() + name + item data = helper.request_delete(url) return(data)
def get_quotes(inputSymbols, info=None): """Takes any number of stock tickers and returns information pertaining to its price. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. """ symbols = helper.inputs_to_set(inputSymbols) url = urls.quotes() payload = {'symbols': ','.join(symbols)} data = helper.request_get(url, 'results', payload) if (data == None or data == [None]): return data for count, item in enumerate(data): if item is None: print(helper.error_ticker_does_not_exist(symbols[count])) data = [item for item in data if item is not None] return (helper.filter(data, info))
def get_latest_price(inputSymbols, priceType=None, includeExtendedHours=True, access_token=None): """Takes any number of stock tickers and returns the latest price of each one as a string. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param priceType: Can either be 'ask_price' or 'bid_price'. If this parameter is set, then includeExtendedHours is ignored. :type priceType: str :param includeExtendedHours: Leave as True if you want to get extendedhours price if available. \ False if you only want regular hours price, even after hours. :type includeExtendedHours: bool :returns: [list] A list of prices as strings. """ symbols = helper.inputs_to_set(inputSymbols) quote = get_quotes(symbols, access_token=access_token) prices = [] for item in quote: if item: if priceType == 'ask_price': prices.append(item['ask_price']) elif priceType == 'bid_price': prices.append(item['bid_price']) else: if priceType: print('WARNING: priceType should be "ask_price" or "bid_price". You entered "{0}"'.format(priceType), file=helper.get_output()) if item['last_extended_hours_trade_price'] is None or not includeExtendedHours: prices.append(item['last_trade_price']) else: prices.append(item['last_extended_hours_trade_price']) else: prices.append(None) return(prices)
def get_instruments_by_symbols(inputSymbols, info=None): """Takes any number of stock tickers and returns information held by the market such as ticker name, bloomberg id, and listing date. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. """ symbols = helper.inputs_to_set(inputSymbols) url = urls.instruments() data = [] for item in symbols: payload = {'symbol': item} itemData = helper.request_get(url, 'indexzero', payload) if itemData: data.append(itemData) else: print(helper.error_ticker_does_not_exist(item)) return (helper.filter(data, info))
def get_list_market_data(inputSymbols,expirationDate,info=None): """Returns a list of option market data for several stock tickers. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all stock option market data. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ symbols = helper.inputs_to_set(inputSymbols) ids = [] data = [] url = urls.option_instruments() for symbol in symbols: payload = { 'chain_id' : helper.id_for_chain(symbol), 'expiration_date' : expirationDate, 'state' : 'active', 'tradability' : 'tradable'} otherData = helper.request_get(url,'pagination',payload) for item in otherData: ids.append(item['id']) for id in ids: url = urls.marketdata(id) otherData = helper.request_get(url) data.append(otherData) return(helper.filter(data,info))
def get_popularity_by_ids(inputIds, info=None, errors=True): """Returns the number of open positions. :param inputSymbols: The stock ids. :type symbol: str, list :param info: Will filter the results to be a string value. :type info: Optional[str] :returns: If the info parameter is provided, then the function will extract the value of the key \ that matches the info parameter. Otherwise, the whole dictionary is returned. """ ids = helper.inputs_to_set(inputIds) url = urls.popularity() payload = {'ids': ','.join(ids)} data = helper.request_get(url, payload=payload, errors=errors) if (data == None or data == [None]): return data for count, item in enumerate(data): if item is None: print(helper.error_ticker_does_not_exist(ids[count])) # data = [item for item in data if item is not None] return (helper.filter(data, info))
def delete_symbols_from_watchlist(inputSymbols, name="My First List"): """Deletes multiple stock tickers from a watchlist. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param name: The name of the watchlist to delete data from. :type name: Optional[str] :returns: Returns result of the delete request. """ symbols = helper.inputs_to_set(inputSymbols) ids = stocks.get_instruments_by_symbols(symbols, info='id') data = [] #Get id of requested watchlist all_watchlists = get_all_watchlists() watchlist_id = '' for wl in all_watchlists['results']: if wl['display_name'] == name: watchlist_id = wl['id'] for id in ids: payload = { watchlist_id: [{ "object_type": "instrument", "object_id": id, "operation": "delete" }] } url = urls.watchlists(name, True) data.append(helper.request_post(url, payload, json=True)) return (data)
def get_fundamentals(input_symbols, info=None): """Takes any number of stock tickers and returns fundamental information about the stock such as what sector it is in, a description of the company, dividend yield, and market cap. :param input_symbols: May be a single stock ticker or a list of stock tickers. :type input_symbols: str or list :param info: Will data_filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. """ symbols = helper.inputs_to_set(input_symbols) url = urls.fundamentals() payload = {'symbols': ','.join(symbols)} data = helper.request_get(url, 'results', payload) if data is None or data == [None]: return data for count, item in enumerate(data): if item is None: print(helper.error_ticker_does_not_exist(symbols[count])) data = [item for item in data if item is not None] return helper.data_filter(data, info)
def get_option_market_data(inputSymbols, expirationDate, strikePrice, optionType, info=None): """Returns the option market data for the stock option, including the greeks, open interest, change of profit, and adjusted mark price. :param inputSymbols: The ticker of the stock. :type inputSymbols: str :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param strikePrice: Represents the price of the option. :type strikePrice: str :param optionType: Can be either 'call' or 'put'. :type optionType: str :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a dictionary of key/value pairs for the stock. \ If info parameter is provided, the value of the key that matches info is extracted. """ try: symbols = helper.inputs_to_set(inputSymbols) if optionType: optionType = optionType.lower().strip() except AttributeError as message: print(message, file=helper.get_output()) return [None] data = [] for symbol in symbols: optionID = helper.id_for_option(symbol, expirationDate, strikePrice, optionType) marketData = get_option_market_data_by_id(optionID) data.append(marketData) return(helper.filter(data, info))
def get_historicals(*inputSymbols, span='week', bounds='regular'): """Represents the data that is used to make the graphs. :param inputSymbols: This is a variable length parameter that represents a stock ticker. \ May be several tickers seperated by commas or a list of tickers. :type inputSymbols: str or list :param span: Sets the range of the data to be either 'day', 'week', 'year', or '5year'. Default is 'week'. :type span: Optional[str] :param bounds: Represents if graph will include extended trading hours or just regular trading hours. Values are 'extended' or 'regular'. :type bounds: Optional[str] :returns: Returns a list of dictionaries where each dictionary is for a different time. If multiple stocks are provided \ the historical data is listed one after another. """ span_check = ['day', 'week', 'year', '5year'] bounds_check = ['extended', 'regular', 'trading'] if span not in span_check: print('ERROR: Span must be "day","week","year",or "5year"') return ([None]) if bounds not in bounds_check: print('ERROR: Bounds must be "extended","regular",or "trading"') return ([None]) if (bounds == 'extended' or bounds == 'trading') and span != 'day': print( 'ERROR: extended and trading bounds can only be used with a span of "day"' ) return ([None]) if span == 'day': interval = '5minute' elif span == 'week': interval = '10minute' elif span == 'year': interval = 'day' else: interval = 'week' symbols = helper.inputs_to_set(inputSymbols) url = urls.historicals() payload = { 'symbols': ','.join(symbols), 'interval': interval, 'span': span, 'bounds': bounds } data = helper.request_get(url, 'results', payload) if (data == None or data == [None]): return data histData = [] for count, item in enumerate(data): if (len(item['historicals']) == 0): print(helper.error_ticker_does_not_exist(symbols[count])) continue for subitem in item['historicals']: histData.append(subitem) return (histData)
def find_options_for_list_of_stocks_by_expiration_date(inputSymbols, expirationDate, optionType='both', info=None): """Returns a list of all the option orders that match the seach parameters :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param optionType: Can be either 'call' or 'put' or leave blank to get both. :type optionType: Optional[str] :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all options of the stock that match the search parameters. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ symbols = helper.inputs_to_set(inputSymbols) try: optionType = optionType.lower().strip() except AttributeError as message: print(message) return [None] data = [] url = urls.option_instruments() for symbol in symbols: if (optionType == 'put' or optionType == 'call'): payload = { 'chain_id': helper.id_for_chain(symbol), 'expiration_date': expirationDate, 'state': 'active', 'tradability': 'tradable', 'rhs_tradability': 'tradable', 'type': optionType } else: payload = { 'chain_id': helper.id_for_chain(symbol), 'expiration_date': expirationDate, 'state': 'active', 'tradability': 'tradable', 'rhs_tradability': 'tradable' } otherData = helper.request_get(url, 'pagination', payload) for item in otherData: if (item['expiration_date'] == expirationDate ): # and item['rhs_tradability'] == 'tradable' data.append(item) for item in data: marketData = get_option_market_data_by_id(item['id']) item.update(marketData) return (helper.filter(data, info))
def get_list_options_of_specific_profitability(inputSymbols,expirationDate,typeProfit="chance_of_profit_short",profitFloor=0.0, profitCeiling=1.0,info=None): """Returns a list of option market data for several stock tickers that match a range of profitability. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param typeProfit: Will either be "chance_of_profit_short" or "chance_of_profit_long". :type typeProfit: str :param profitFloor: The lower percentage on scale 0 to 1. :type profitFloor: int :param profitCeiling: The higher percentage on scale 0 to 1. :type profitCeiling: int :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all stock option market data. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ symbols = helper.inputs_to_set(inputSymbols) ids = [] data = [] returnData = [] url = urls.option_instruments() if (typeProfit != "chance_of_profit_short" and typeProfit != "chance_of_profit_long"): print("Invalid string for 'typeProfit'. Defaulting to 'chance_of_profit_short'.") typeProfit = "chance_of_profit_short" for symbol in symbols: payload = { 'chain_id' : helper.id_for_chain(symbol), 'expiration_date' : expirationDate, 'state' : 'active', 'tradability' : 'tradable', 'rhs_tradability' : 'tradable'} otherData = helper.request_get(url,'pagination',payload) for item in otherData: if (item['tradability'] == 'tradable'): ids.append(item['id']) for id in ids: url = urls.marketdata_options(id) otherData = helper.request_get(url) data.append(otherData) for item in data: try: floatValue = float(item[typeProfit]) if (floatValue > profitFloor and floatValue < profitCeiling): returnData.append(item) except: pass return(helper.filter(returnData,info))
def get_fundamentals(inputSymbols, info=None): """Takes any number of stock tickers and returns fundamental information about the stock such as what sector it is in, a description of the company, dividend yield, and market cap. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [list] If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. :Dictionary Keys: * open * high * low * volume * average_volume_2_weeks * average_volume * high_52_weeks * dividend_yield * float * low_52_weeks * market_cap * pb_ratio * pe_ratio * shares_outstanding * description * instrument * ceo * headquarters_city * headquarters_state * sector * industry * num_employees * year_founded * symbol """ symbols = helper.inputs_to_set(inputSymbols) url = urls.fundamentals() payload = {'symbols': ','.join(symbols)} data = helper.request_get(url, 'results', payload) if (data == None or data == [None]): return data for count, item in enumerate(data): if item is None: print(helper.error_ticker_does_not_exist(symbols[count]), file=helper.get_output()) else: item['symbol'] = symbols[count] data = [item for item in data if item is not None] return (helper.filter(data, info))
def find_options_by_specific_profitability(inputSymbols, expirationDate=None, strikePrice=None, optionType=None, typeProfit="chance_of_profit_short", profitFloor=0.0, profitCeiling=1.0, info=None): """Returns a list of option market data for several stock tickers that match a range of profitability. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. Leave as None to get all available dates. :type expirationDate: str :param strikePrice: Represents the price of the option. Leave as None to get all available strike prices. :type strikePrice: str :param optionType: Can be either 'call' or 'put' or leave blank to get both. :type optionType: Optional[str] :param typeProfit: Will either be "chance_of_profit_short" or "chance_of_profit_long". :type typeProfit: str :param profitFloor: The lower percentage on scale 0 to 1. :type profitFloor: int :param profitCeiling: The higher percentage on scale 0 to 1. :type profitCeiling: int :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all stock option market data. \ If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ symbols = helper.inputs_to_set(inputSymbols) data = [] if (typeProfit != "chance_of_profit_short" and typeProfit != "chance_of_profit_long"): print("Invalid string for 'typeProfit'. Defaulting to 'chance_of_profit_short'.", file=helper.get_output()) typeProfit = "chance_of_profit_short" for symbol in symbols: tempData = find_tradable_options(symbol, expirationDate, strikePrice, optionType, info=None) for option in tempData: if expirationDate and option.get("expiration_date") != expirationDate: continue market_data = get_option_market_data_by_id(option['id']) if len(market_data): option.update(market_data[0]) write_spinner() try: floatValue = float(option[typeProfit]) if (floatValue >= profitFloor and floatValue <= profitCeiling): data.append(option) except: pass return(helper.filter_data(data, info))
def get_instruments_by_symbols(inputSymbols, info=None): """Takes any number of stock tickers and returns information held by the market such as ticker name, bloomberg id, and listing date. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [list] If info parameter is left as None then the list will a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. :Dictionary Keys: * id * url * quote * fundamentals * splits * state * market * simple_name * name * tradeable * tradability * symbol * bloomberg_unique * margin_initial_ratio * maintenance_ratio * country * day_trade_ratio * list_date * min_tick_size * type * tradable_chain_id * rhs_tradability * fractional_tradability * default_collar_fraction """ symbols = helper.inputs_to_set(inputSymbols) url = urls.instruments() data = [] for item in symbols: payload = {'symbol': item} itemData = helper.request_get(url, 'indexzero', payload) if itemData: data.append(itemData) else: print(helper.error_ticker_does_not_exist(item), file=helper.get_output()) return (helper.filter(data, info))
def post_symbols_to_watchlist(inputSymbols, name='Default'): """Posts multiple stock tickers to a watchlist. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param name: The name of the watchlist to post data to. :type name: Optional[str] :returns: Returns result of the post request. """ symbols = helper.inputs_to_set(inputSymbols) payload = {'symbols': ','.join(symbols)} url = urls.watchlists(name, True) data = helper.request_post(url, payload) return (data)
def post_symbols_to_watchlist(*inputSymbols, name='Default'): """Posts multiple stock tickers to a watchlist. :param inputSymbols: This is a variable length parameter that represents a stock ticker. \ May be several tickers seperated by commas or a list of tickers. :type inputSymbols: str or list :param name: The name of the watchlist to post data to. :type name: Optional[str] :returns: Returns result of the post request. """ symbols = helper.inputs_to_set(inputSymbols) payload = {'symbols': ','.join(symbols)} url = urls.watchlists(name, True) data = helper.request_post(url, payload) return (data)
def get_latest_price(inputSymbols): """Takes any number of stock tickers and returns the latest price of each one as a string. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :returns: A list of prices as strings. """ symbols = helper.inputs_to_set(inputSymbols) quote = get_quotes(symbols) prices = [] for item in quote: if item['last_extended_hours_trade_price'] is None: prices.append(item['last_trade_price']) else: prices.append(item['last_extended_hours_trade_price']) return (prices)
def get_latest_price(*inputSymbols): """Takes any number of stock tickers and returns the latest price of each one as a string. :param inputSymbols: This is a variable length parameter that represents a stock ticker. \ May be several tickers seperated by commas or a list of tickers. :type inputSymbols: str or list :returns: A list of prices as strings. """ symbols = helper.inputs_to_set(inputSymbols) quote = get_quotes(symbols) prices = [] for item in quote: if item['last_extended_hours_trade_price'] is None: prices.append(item['last_trade_price']) else: prices.append(item['last_extended_hours_trade_price']) return (prices)
def delete_symbols_from_watchlist(inputSymbols, name='Default'): """Deletes multiple stock tickers from a watchlist. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param name: The name of the watchlist to delete data from. :type name: Optional[str] :returns: Returns result of the delete request. """ symbols = helper.inputs_to_set(inputSymbols) ids = stocks.get_instruments_by_symbols(symbols, info='id') data = [] for id in ids: url = urls.watchlist_delete(name, id) data.append(helper.request_delete(url)) return (data)
def day_prices(): print(' ~~ Full Day Prices ~~ ') PSQL = db_connection('psql') current, next_id = det_cur_day_prices(PSQL, 'day') id_sym = pg_query(PSQL.client, 'select rh_id, rh_sym from portfolio.stocks') total_stocks = len(id_sym) trader = rs() login_data = trader.login() for stock_num, (idx, sym) in enumerate(id_sym.values): # if idx == '1d4d0780-ba27-4adc-ab12-0c3062fdf365': # asdfasdf progress(stock_num, total_stocks, status = sym) symbols = helper.inputs_to_set(sym) url = urls.historicals() payload = { 'symbols' : ','.join(symbols), 'interval' : 'day', 'span' : '5year', 'bounds' : 'regular'} data = trader.request_get(url,'results',payload) if data == [None]: continue for day in data[0]['historicals']: beg_date = datetime.strptime(day['begins_at'].replace('Z', '').replace('T', ' '), '%Y-%m-%d %H:%M:%S') if idx in current.keys() and beg_date <= current[idx]: continue open_price = float(day['open_price']) close_price = float(day['close_price']) high_price = float(day['high_price']) low_price = float(day['low_price']) volume = int(day['volume']) script = "INSERT INTO portfolio.day_prices(day_price_id, rh_id, date, open_price, close_price, high_price, low_price, volume) VALUES ('%s', '%s', '%s', %.2f, %.2f, %.2f, %.2f, %i);" % (next_id, idx, beg_date, open_price, close_price, high_price, low_price, volume) pg_insert(PSQL.client, script) next_id += 1 open_price = None close_price = None high_price = None low_price = None volume = None trader.logout()
def get_quotes(inputSymbols, info=None): """Takes any number of stock tickers and returns information pertaining to its price. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [list] If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. :Dictionary Keys: * ask_price * ask_size * bid_price * bid_size * last_trade_price * last_extended_hours_trade_price * previous_close * adjusted_previous_close * previous_close_date * symbol * trading_halted * has_traded * last_trade_price_source * updated_at * instrument """ symbols = helper.inputs_to_set(inputSymbols) url = urls.quotes() payload = {'symbols': ','.join(symbols)} data = helper.request_get(url, 'results', payload) if (data == None or data == [None]): return data for count, item in enumerate(data): if item is None: print(helper.error_ticker_does_not_exist(symbols[count]), file=helper.get_output()) data = [item for item in data if item is not None] return (helper.filter(data, info))
def get_latest_price(inputSymbols, includeExtendedHours=True): """Takes any number of stock tickers and returns the latest price of each one as a string. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param includeExtendedHours: Leave as True if you want to get extendedhours price if available. \ False if you only want regular hours price, even after hours. :type includeExtendedHours: bool :returns: A list of prices as strings. """ symbols = helper.inputs_to_set(inputSymbols) quote = get_quotes(symbols) prices = [] for item in quote: if item['last_extended_hours_trade_price'] is None or not includeExtendedHours: prices.append(item['last_trade_price']) else: prices.append(item['last_extended_hours_trade_price']) return (prices)
def get_stock_historicals(inputSymbols, interval='hour', span='week', bounds='regular', info=None): """Represents the historicl data for a stock. :param inputSymbols: May be a single stock ticker or a list of stock tickers. :type inputSymbols: str or list :param interval: Interval to retrieve data for. Values are '5minute', '10minute', 'hour', 'day', 'week'. Default is 'hour'. :type interval: Optional[str] :param span: Sets the range of the data to be either 'day', 'week', 'month', '3month', 'year', or '5year'. Default is 'week'. :type span: Optional[str] :param bounds: Represents if graph will include extended trading hours or just regular trading hours. Values are 'extended', 'trading', or 'regular'. Default is 'regular' :type bounds: Optional[str] :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [list] Returns a list of dictionaries where each dictionary is for a different time. If multiple stocks are provided \ the historical data is listed one after another. :Dictionary Keys: * begins_at * open_price * close_price * high_price * low_price * volume * session * interpolated * symbol """ interval_check = ['5minute', '10minute', 'hour', 'day', 'week'] span_check = ['day', 'week', 'month', '3month', 'year', '5year'] bounds_check = ['extended', 'regular', 'trading'] if interval not in interval_check: print( 'ERROR: Interval must be "5minute","10minute","hour","day",or "week"', file=helper.get_output()) return ([None]) if span not in span_check: print( 'ERROR: Span must be "day","week","month","3month","year",or "5year"', file=helper.get_output()) return ([None]) if bounds not in bounds_check: print('ERROR: Bounds must be "extended","regular",or "trading"', file=helper.get_output()) return ([None]) if (bounds == 'extended' or bounds == 'trading') and span != 'day': print( 'ERROR: extended and trading bounds can only be used with a span of "day"', file=helper.get_output()) return ([None]) symbols = helper.inputs_to_set(inputSymbols) url = urls.historicals() payload = { 'symbols': ','.join(symbols), 'interval': interval, 'span': span, 'bounds': bounds } data = helper.request_get(url, 'results', payload) if (data == None or data == [None]): return data histData = [] for count, item in enumerate(data): histData_single = [] if (len(item['historicals']) == 0): print(helper.error_ticker_does_not_exist(symbols[count]), file=helper.get_output()) continue stockSymbol = item['symbol'] for subitem in item['historicals']: subitem['symbol'] = stockSymbol histData_single.append(subitem) histData.append(histData_single) return (helper.filter(histData, info))
def find_options_by_expiration_and_strike_count(inputSymbols, expirationDate, strikeCount, optionType=None, info=None): """Returns a list of all the option orders that match the search parameters :param inputSymbols: The ticker of either a single stock or a list of stocks. :type inputSymbols: str :param expirationDate: Represents the expiration date in the format YYYY-MM-DD. :type expirationDate: str :param optionType: Can be either 'call' or 'put' or leave blank to get both. :type optionType: Optional[str] :param strikeCount: Number of strikes to return above and below ATM price :type strikeCount: intd :param info: Will filter the results to get a specific value. :type info: Optional[str] :returns: Returns a list of dictionaries of key/value pairs for all options of the stock that match the search parameters. If info parameter is provided, a list of strings is returned where the strings are the value of the key that matches info. """ try: symbols = helper.inputs_to_set(inputSymbols) if optionType: optionType = optionType.lower().strip() except AttributeError as message: print(message) return [None] data = [] for symbol in symbols: underlying = float(stocks.get_latest_price(symbol)[0]) allOptions = find_tradable_options(symbol, expirationDate, None, optionType, None) strikes = [] for each in allOptions: strikePrice = each['strike_price'] strikes.append( strikePrice) if strikePrice not in strikes else strikes sortedStrikes = list(map(float, strikes)) sortedStrikes.sort() filteredStrikes = find_strikes(sortedStrikes, strikeCount, underlying) for x in range(0, len(filteredStrikes)): filteredStrikes[x] = '%.4f' % filteredStrikes[ x] # DO NOT CHANGE ROUNDING x = 0 while x < len(allOptions): if allOptions[x]['strike_price'] not in filteredStrikes: allOptions.remove(allOptions[x]) else: x = x + 1 for item in allOptions: marketData = get_option_market_data_by_id(item['id']) item.update(marketData) # write_spinner() data.extend(allOptions) return (helper.filter(data, info))
def get_crypto_historicals(symbol, interval='hour', span='week', bounds='24_7', info=None): """Gets historical information about a crypto including open price, close price, high price, and low price. :param symbol: The crypto ticker. :type symbol: str :param interval: The time between data points. Can be '15second', '5minute', '10minute', 'hour', 'day', or 'week'. Default is 'hour'. :type interval: str :param span: The entire time frame to collect data points. Can be 'hour', 'day', 'week', 'month', '3month', 'year', or '5year'. Default is 'week' :type span: str :param bound: The times of day to collect data points. 'Regular' is 6 hours a day, 'trading' is 9 hours a day, \ 'extended' is 16 hours a day, '24_7' is 24 hours a day. Default is '24_7' :type bound: str :param info: Will filter the results to have a list of the values that correspond to key that matches info. :type info: Optional[str] :returns: [list] If info parameter is left as None then the list will contain a dictionary of key/value pairs for each ticker. \ Otherwise, it will be a list of strings where the strings are the values of the key that corresponds to info. :Dictionary Keys: * begins_at * open_price * close_price * high_price * low_price * volume * session * interpolated * symbol """ interval_check = ['15second', '5minute', '10minute', 'hour', 'day', 'week'] span_check = ['hour', 'day', 'week', 'month', '3month', 'year', '5year'] bounds_check = ['24_7', 'extended', 'regular', 'trading'] if interval not in interval_check: print( 'ERROR: Interval must be "15second","5minute","10minute","hour","day",or "week"', file=helper.get_output()) return ([None]) if span not in span_check: print( 'ERROR: Span must be "hour","day","week","month","3month","year",or "5year"', file=helper.get_output()) return ([None]) if bounds not in bounds_check: print('ERROR: Bounds must be "24_7","extended","regular",or "trading"', file=helper.get_output()) return ([None]) if (bounds == 'extended' or bounds == 'trading') and span != 'day': print( 'ERROR: extended and trading bounds can only be used with a span of "day"', file=helper.get_output()) return ([None]) symbol = helper.inputs_to_set(symbol) id = get_crypto_info(symbol[0], info='id') url = urls.crypto_historical(id) payload = {'interval': interval, 'span': span, 'bounds': bounds} data = helper.request_get(url, 'regular', payload) histData = [] cryptoSymbol = data['symbol'] for subitem in data['data_points']: subitem['symbol'] = cryptoSymbol histData.append(subitem) return (helper.filter_data(histData, info))