示例#1
0
def get_crypto_historical(symbol, interval, span, bound, 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.
    :type interval: str
    :param span: The entire time frame to collect data points.
    :type span: str
    :param bound: The times of dat to collect data points.
    :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: 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.

    """
    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"')
        return([None])
    if span not in span_check:
        print('ERROR: Span must be "hour","day","week","month","3month","year",or "5year"')
        return([None])
    if bound not in bounds_check:
        print('ERROR: Bounds must be "24_7","extended","regular",or "trading"')
        return([None])
    if (bound == 'extended' or bound == 'trading') and span != 'day':
        print('ERROR: extended and trading bounds can only be used with a span of "day"')
        return([None])

    id = get_crypto_info(symbol, info='id')
    url = urls.crypto_historical(id, interval, span, bound)
    data = helper.request_get(url)
    return(helper.filter(data, info))
示例#2
0
def load_phoenix_account(info=None):
    """Returns unified information about your account.

    :param info: Will filter the results to get a specific value.
    :type info: Optional[str]
    :returns: [list] Returns a list of dictionaries of key/value pairs. If info parameter is provided, \
    a list of strings is returned where the strings are the value of the key that matches info.
    :Dictionary Keys: * account_buying_power
                      * cash_available_from_instant_deposits
                      * cash_held_for_currency_orders
                      * cash_held_for_dividends
                      * cash_held_for_equity_orders
                      * cash_held_for_options_collateral
                      * cash_held_for_orders
                      * crypto
                      * crypto_buying_power
                      * equities
                      * extended_hours_portfolio_equity
                      * instant_allocated
                      * levered_amount
                      * near_margin_call
                      * options_buying_power
                      * portfolio_equity
                      * portfolio_previous_close
                      * previous_close
                      * regular_hours_portfolio_equity
                      * total_equity
                      * total_extended_hours_equity
                      * total_extended_hours_market_value
                      * total_market_value
                      * total_regular_hours_equity
                      * total_regular_hours_market_value
                      * uninvested_cash
                      * withdrawable_cash

    """
    url = urls.phoenix()
    data = helper.request_get(url, 'regular')
    return (helper.filter(data, info))
示例#3
0
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)
        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))
示例#4
0
def get_crypto_positions(info=None):
    """Returns crypto positions for the account.

    :param info: Will filter the results to get a specific value.
    :type info: Optional[str]
    :returns: [list] Returns a list of dictionaries of key/value pairs for each option. If info parameter is provided, \
    a list of strings is returned where the strings are the value of the key that matches info.
    :Dictionary Keys: * account_id
                      * cost_basis
                      * created_at
                      * currency
                      * id
                      * quantity
                      * quantity_available
                      * quantity_held_for_buy
                      * quantity_held_for_sell
                      * updated_at

    """
    url = urls.crypto_holdings()
    data = helper.request_get(url, 'pagination')
    return (helper.filter(data, info))
示例#5
0
文件: stocks.py 项目: gxdai/robinhood
def get_news(symbol,info=None):
    """Returns news stories for a stock.

    :param symbol: The stock ticker.
    :type symbol: str
    :param info: Will filter the results to get a specific value.
    :type info: Optional[str]
    :returns: Returns a list of dictionaries. If info parameter is provided, \
    a list of strings is returned where the strings are the value \
    of the key that matches info.

    """
    try:
        symbol = symbol.upper().strip()
    except AttributeError as message:
        print(message)
        return None

    url = urls.news(symbol)
    data = helper.request_get(url,'results')

    return(helper.filter(data,info))
示例#6
0
文件: stocks.py 项目: gxdai/robinhood
def get_splits(symbol,info=None):
    """Returns the date, divisor, and multiplier for when a stock split occureed.

    :param symbol: The stock ticker.
    :type symbol: str
    :param info: Will filter the results to get a specific value. Possible options are \
    url, instrument, execution_date, divsor, and multiplier.
    :type info: Optional[str]
    :returns: Returns a list of dictionaries. If info parameter is provided, \
    a list of strings is returned where the strings are the value \
    of the key that matches info.

    """
    try:
        symbol = symbol.upper().strip()
    except AttributeError as message:
        print(message)
        return None

    url = urls.splits(symbol)
    data = helper.request_get(url,'results')
    return(helper.filter(data,info))
示例#7
0
def get_markets(info=None):
    """Returns a list of available markets.

    :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 each market. If info parameter is provided, \
    a list of strings is returned where the strings are the value of the key that matches info.
    :Dictionary Keys: * url
                      * todays_hours
                      * mic
                      * operating_mic
                      * acronym
                      * name
                      * city
                      * country
                      * timezone
                      * website

    """
    url = urls.markets()
    data = helper.request_get(url, 'pagination')
    return (helper.filter(data, info))
示例#8
0
文件: stocks.py 项目: gxdai/robinhood
def get_events(symbol,info=None):
    """Returns the events related to a stock.

    :param symbol: The stock ticker.
    :type symbol: str
    :param info: Will filter the results to get a specific 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.

    """
    try:
        symbol = symbol.upper().strip()
    except AttributeError as message:
        print(message)
        return None

    payload = {'equity_instrument_id' : helper.id_for_stock(symbol)}
    url = urls.events()
    data = helper.request_get(url,'results',payload)

    return(helper.filter(data,info))
示例#9
0
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)
        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))
示例#10
0
def get_historical_portfolio(interval=None,
                             span='week',
                             bounds='regular',
                             info=None):
    interval_check = ['5minute', '10minute', 'hour', 'day', 'week']
    span_check = ['day', 'week', 'month', '3month', 'year', '5year', 'all']
    bounds_check = ['extended', 'regular', 'trading']

    if interval not in interval_check:
        if interval is None and (bounds != 'regular' and span != 'all'):
            print(
                'ERROR: Interval must be None for "all" span "regular" bounds',
                file=helper.get_output())
            return ([None])
        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"')
        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])

    account = profiles.load_account_profile('account_number')
    url = urls.portfolis_historicals(account)
    payload = {'interval': interval, 'span': span, 'bounds': bounds}
    data = helper.request_get(url, 'regular', payload)

    return (helper.filter(data, info))
示例#11
0
def get_popularity(symbol, info=None):
    """Returns the number of open positions.

    :param symbol: The stock ticker.
    :type symbol: str
    :param info: Will filter the results to be a string value.
    :type info: Optional[str]
    :returns: [dict] 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.
    :Dictionary Keys: * instrument
                      * num_open_positions

    """
    try:
        symbol = symbol.upper().strip()
    except AttributeError as message:
        print(message)
        return None

    url = urls.popularity(symbol)
    data = helper.request_get(url)

    return(helper.filter(data, info))
示例#12
0
def get_crypto_quote_from_id(id, info=None):
    """Gets information about a crypto including low price, high price, and open price. Uses the id instead of crypto ticker.

    :param id: The id of a crypto.
    :type id: 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: [dict] 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
                      * bid_price
                      * high_price
                      * id
                      * low_price
                      * mark_price
                      * open_price
                      * symbol
                      * volume

    """
    url = urls.crypto_quote(id)
    data = helper.request_get(url)
    return (helper.filter(data, info))
示例#13
0
def get_currency_pairs(info=None):
    """Returns currency pairs

    :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 each currency pair. If info parameter is provided, \
    a list of strings is returned where the strings are the value of the key that matches info.
    :Dictionary Keys: * asset_currency
                      * display_only
                      * id
                      * max_order_size
                      * min_order_size
                      * min_order_price_increment
                      * min_order_quantity_increment
                      * name
                      * quote_currency
                      * symbol
                      * tradability

    """
    url = urls.currency()
    data = helper.request_get(url, 'results')
    return(helper.filter(data, info))
示例#14
0
def get_earnings(symbol, info=None):
    """Returns the earnings for the differenct financial quarters.

    :param symbol: The stock ticker.
    :type symbol: str
    :param info: Will filter the results to get a specific value.
    :type info: Optional[str]
    :returns: Returns a list of dictionaries. If info parameter is provided, \
    a list of strings is returned where the strings are the value \
    of the key that matches info.

    """
    try:
        symbol = symbol.upper().strip()
    except AttributeError as message:
        print(message)
        return None

    url = urls.earnings()
    payload = {'symbol': symbol}
    data = helper.request_get(url, 'results', payload)

    return (helper.filter(data, info))
示例#15
0
def get_crypto_currency_pairs(info=None):
    """Gets a list of all the cypto currencies that you can trade.

    :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: * asset_currency
                      * display_only
                      * id
                      * max_order_size
                      * min_order_size
                      * min_order_price_increment
                      * min_order_quantity_increment
                      * name
                      * quote_currency
                      * symbol
                      * tradability

    """
    url = urls.crypto_currency_pairs()
    data = helper.request_get(url, 'results')
    return (helper.filter(data, info))
示例#16
0
def get_market_next_open_hours(market, info=None):
    """Returns the opening and closing hours for the next open trading day after today. Also will tell you if market is
    market is open on that date.

    :param market: The 'mic' value for the market. Can be found using get_markets().
    :type market: 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 specific market. If info parameter is provided, \
    the string value for the corresponding key will be provided.
    :Dictionary Keys: * date
                      * is_open
                      * opens_at
                      * closes_at
                      * extended_opens_at
                      * extended_closes_at
                      * previous_open_hours
                      * next_open_hours

    """
    url = get_market_today_hours(market, info='next_open_hours')
    data = helper.request_get(url, 'regular')
    return(helper.filter(data, info))
示例#17
0
def get_news(symbol, info=None):
    """Returns news stories for a stock.

    :param symbol: The stock ticker.
    :type symbol: str
    :param info: Will filter the results to get a specific value.
    :type info: Optional[str]
    :returns: [list] Returns a list of dictionaries. If info parameter is provided, \
    a list of strings is returned where the strings are the value \
    of the key that matches info.
    :Dictionary Keys: * api_source
                      * author
                      * num_clicks
                      * preview_image_url
                      * published_at
                      * relay_url
                      * source
                      * summary
                      * title
                      * updated_at
                      * url
                      * uuid
                      * related_instruments
                      * preview_text
                      * currency_id

    """
    try:
        symbol = symbol.upper().strip()
    except AttributeError as message:
        print(message, file=helper.get_output())
        return None

    url = urls.news(symbol)
    data = helper.request_get(url, 'results')

    return (helper.filter(data, info))
示例#18
0
def find_tradable_options_for_stock(symbol, optionType='both', info=None):
    """Returns a list of all available options for a stock.

    :param symbol: The ticker of the stock.
    :type symbol: str
    :param optionType: Can be either 'call' or 'put' or left 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 calls of the stock. If info parameter is provided, \
    a list of strings is returned where the strings are the value of the key that matches info.

    """
    try:
        symbol = symbol.upper().strip()
        optionType = optionType.lower().strip()
    except AttributeError as message:
        print(message)
        return [None]

    url = urls.option_instruments()
    if (optionType == 'call' or optionType == 'put'):
        payload = {
            'chain_id': helper.id_for_chain(symbol),
            'state': 'active',
            'tradability': 'tradable',
            'type': optionType
        }
    else:
        payload = {
            'chain_id': helper.id_for_chain(symbol),
            'state': 'active',
            'tradability': 'tradable'
        }

    data = helper.request_get(url, 'pagination', payload)
    return (helper.filter(data, info))
示例#19
0
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',
            'rhs_tradability': 'tradable'
        }
        otherData = helper.request_get(url, 'pagination', payload)
        for item in otherData:
            if (item['expiration_date'] == expirationDate
                ):  # and item['rhs_tradability'] == 'tradable'
                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))
示例#20
0
def find_options_for_stock_by_strike(symbol,
                                     strike,
                                     optionType='both',
                                     info=None):
    """Returns a list of all the option orders that match the seach parameters

    :param symbol: The ticker of the stock.
    :type symbol: str
    :param strike: Represents the price of the option.
    :type strike: 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:
        symbol = symbol.upper().strip()
        optionType = optionType.lower().strip()
    except AttributeError as message:
        print(message)
        return [None]

    allOptions = find_tradable_options_for_stock(symbol, optionType)
    filteredOptions = [
        item for item in allOptions
        if float(item["strike_price"]) == float(strike)
    ]
    # and item['rhs_tradability'] == 'tradable']

    for item in filteredOptions:
        marketData = get_option_market_data_by_id(item['id'])
        item.update(marketData)

    return (helper.filter(filteredOptions, info))
示例#21
0
def load_portfolio_profile(access_token, info=None):
    """Gets the information associated with the portfolios profile,
    such as withdrawable amount, market value of account, and excess margin.

    :param info: The name of the key whose value is to be returned from the function.
    :type info: Optional[str]
    :returns: The function returns a dictionary of key/value pairs. \
    If a string is passed in to the info parameter, then the function will return \
    a string corresponding to the value of the key whose name matches the info parameter.
    :Dictionary Keys: * url
                      * account
                      * start_date
                      * market_value
                      * equity
                      * extended_hours_market_value
                      * extended_hours_equity
                      * extended_hours_portfolio_equity
                      * last_core_market_value
                      * last_core_equity
                      * last_core_portfolio_equity
                      * excess_margin
                      * excess_maintenance
                      * excess_margin_with_uncleared_deposits
                      * excess_maintenance_with_uncleared_deposits
                      * equity_previous_close
                      * portfolio_equity_previous_close
                      * adjusted_equity_previous_close
                      * adjusted_portfolio_equity_previous_close
                      * withdrawable_amount
                      * unwithdrawable_deposits
                      * unwithdrawable_grants

    """
    url = urls.portfolio_profile()
    data = helper.request_get(url, 'indexzero', access_token=access_token)
    return (helper.filter(data, info))
示例#22
0
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))
示例#23
0
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['rhs_tradability'] == 'tradable'):
            ids.append(item['id'])

    for id in ids:
        url = urls.marketdata(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))
示例#24
0
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(histData, info))
示例#25
0
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))
示例#26
0
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'."
        )
        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'])
            option.update(market_data)
            write_spinner()

            try:
                floatValue = float(option[typeProfit])
                if (floatValue >= profitFloor and floatValue <= profitCeiling):
                    data.append(option)
            except:
                pass

    return (helper.filter(data, info))
示例#27
0
def get_option_historicals(symbol, expirationDate, strikePrice, optionType, interval='hour', span='week', bounds='regular', info=None):
    """Returns the data that is used to make the graphs.

    :param symbol: The ticker of the stock.
    :type symbol: 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 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', '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 'regular', 'trading', and 'extended'. \
    regular hours are 6 hours long, trading hours are 9 hours long, and extended hours are 16 hours long. 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: Returns a list that contains a list for each symbol. \
    Each list contains a dictionary where each dictionary is for a different time.

    """
    try:
        symbol = symbol.upper().strip()
        optionType = optionType.lower().strip()
    except AttributeError as message:
        print(message, file=helper.get_output())
        return [None]

    interval_check = ['5minute', '10minute', 'hour', 'day', 'week']
    span_check = ['day', 'week', '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", "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])

    optionID = helper.id_for_option(symbol, expirationDate, strikePrice, optionType)

    url = urls.option_historicals(optionID)
    payload = {'span': span,
               'interval': interval,
               'bounds': bounds}
    data = helper.request_get(url, 'regular', payload)
    if (data == None or data == [None]):
        return data

    histData = []
    for subitem in data['data_points']:
        subitem['symbol'] = symbol
        histData.append(subitem)

    return(helper.filter(histData, info))