signature:
def keyStatsDF ( symbol , token = '' , version = '' ) :
    '''Key Stats about company
 https : / / iexcloud . io / docs / api / # key - stats
 8am , 9am ET
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
s = keyStats ( symbol , token , version )
df = _statsToDF ( s )
return df


signature:
def largestTrades ( symbol , token = '' , version = '' ) :
    '''This returns 15 minute delayed , last sale eligible trades .
 https : / / iexcloud . io / docs / api / # largest - trades
 9:30-4pm ET M - F during regular market hours
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/largest-trades' , token , version )


signature:
def largestTradesDF ( symbol , token = '' , version = '' ) :
    '''This returns 15 minute delayed , last sale eligible trades .
 https : / / iexcloud . io / docs / api / # largest - trades
 9:30-4pm ET M - F during regular market hours
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( largestTrades ( symbol , token , version ) )
_toDatetime ( df )
_reindex ( df , 'time' )
return df


signature:
def list ( option = 'mostactive' , token = '' , version = '' ) :
    '''Returns an array of quotes for the top 10 symbols in a specified list .
 https : / / iexcloud . io / docs / api / # list
 Updated intraday
 Args :
 option ( string ) ; Option to query
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
if option not in _LIST_OPTIONS :
    raise PyEXception ( 'Option must be in %s' % str ( _LIST_OPTIONS ) )
return _getJson ( 'stock/market/list/' + option , token , version )


signature:
def listDF ( option = 'mostactive' , token = '' , version = '' ) :
    '''Returns an array of quotes for the top 10 symbols in a specified list .
 https : / / iexcloud . io / docs / api / # list
 Updated intraday
 Args :
 option ( string ) ; Option to query
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( list ( option , token , version ) )
_toDatetime ( df )
_reindex ( df , 'symbol' )
return df


signature:
def logo ( symbol , token = '' , version = '' ) :
    '''This is a helper function , but the google APIs url is standardized .
 https : / / iexcloud . io / docs / api / # logo
 8am UTC daily
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/logo' , token , version )


signature:
def logoPNG ( symbol , token = '' , version = '' ) :
    '''This is a helper function , but the google APIs url is standardized .
 https : / / iexcloud . io / docs / api / # logo
 8am UTC daily
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 image : result as png'''

implementation:
_raiseIfNotStr ( symbol )
response = requests . get ( logo ( symbol , token , version ) [ 'url' ] )
return ImageP . open ( BytesIO ( response . content ) )


signature:
def logoNotebook ( symbol , token = '' , version = '' ) :
    '''This is a helper function , but the google APIs url is standardized .
 https : / / iexcloud . io / docs / api / # logo
 8am UTC daily
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 image : result'''

implementation:
_raiseIfNotStr ( symbol )
url = logo ( symbol , token , version ) [ 'url' ]
return ImageI ( url = url )


signature:
def news ( symbol , count = 10 , token = '' , version = '' ) :
    '''News about company
 https : / / iexcloud . io / docs / api / # news
 Continuous
 Args :
 symbol ( string ) ; Ticker to request
 count ( int ) : limit number of results
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/news/last/' + str ( count ) , token , version )


signature:
def _newsToDF ( n ) :
    '''internal'''

implementation:
df = pd . DataFrame ( n )
_toDatetime ( df )
_reindex ( df , 'datetime' )
return df


signature:
def newsDF ( symbol , count = 10 , token = '' , version = '' ) :
    '''News about company
 https : / / iexcloud . io / docs / api / # news
 Continuous
 Args :
 symbol ( string ) ; Ticker to request
 count ( int ) : limit number of results
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
n = news ( symbol , count , token , version )
df = _newsToDF ( n )
return df


signature:
def marketNewsDF ( count = 10 , token = '' , version = '' ) :
    '''News about market
 https : / / iexcloud . io / docs / api / # news
 Continuous
 Args :
 count ( int ) : limit number of results
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( marketNews ( count , token , version ) )
_toDatetime ( df )
_reindex ( df , 'datetime' )
return df


signature:
def ohlc ( symbol , token = '' , version = '' ) :
    '''Returns the official open and close for a give symbol .
 https : / / iexcloud . io / docs / api / # news
 9:30am - 5pm ET Mon - Fri
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/ohlc' , token , version )


signature:
def ohlcDF ( symbol , token = '' , version = '' ) :
    '''Returns the official open and close for a give symbol .
 https : / / iexcloud . io / docs / api / # news
 9:30am - 5pm ET Mon - Fri
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
o = ohlc ( symbol , token , version )
if o :
    df = pd . io . json . json_normalize ( o )
    _toDatetime ( df )
else :
    df = pd . DataFrame ( )
return df


signature:
def marketOhlcDF ( token = '' , version = '' ) :
    '''Returns the official open and close for whole market .
 https : / / iexcloud . io / docs / api / # news
 9:30am - 5pm ET Mon - Fri
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = marketOhlc ( token , version )
data = [ ]
for key in x :
    data . append ( x [ key ] )
    data [ - 1 ] [ 'symbol' ] = key
df = pd . io . json . json_normalize ( data )
_toDatetime ( df )
_reindex ( df , 'symbol' )
return df


signature:
def peers ( symbol , token = '' , version = '' ) :
    '''Peers of ticker
 https : / / iexcloud . io / docs / api / # peers
 8am UTC daily
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/peers' , token , version )


signature:
def _peersToDF ( p ) :
    '''internal'''

implementation:
df = pd . DataFrame ( p , columns = [ 'symbol' ] )
_toDatetime ( df )
_reindex ( df , 'symbol' )
df [ 'peer' ] = df . index
return df


signature:
def peersDF ( symbol , token = '' , version = '' ) :
    '''Peers of ticker
 https : / / iexcloud . io / docs / api / # peers
 8am UTC daily
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
p = peers ( symbol , token , version )
df = _peersToDF ( p )
return df


signature:
def yesterday ( symbol , token = '' , version = '' ) :
    '''This returns previous day adjusted price data for one or more stocks
 https : / / iexcloud . io / docs / api / # previous - day - prices
 Available after 4am ET Tue - Sat
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/previous' , token , version )


signature:
def yesterdayDF ( symbol , token = '' , version = '' ) :
    '''This returns previous day adjusted price data for one or more stocks
 https : / / iexcloud . io / docs / api / # previous - day - prices
 Available after 4am ET Tue - Sat
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
y = yesterday ( symbol , token , version )
if y :
    df = pd . io . json . json_normalize ( y )
    _toDatetime ( df )
    _reindex ( df , 'symbol' )
else :
    df = pd . DataFrame ( )
return df


signature:
def marketYesterdayDF ( token = '' , version = '' ) :
    '''This returns previous day adjusted price data for whole market
 https : / / iexcloud . io / docs / api / # previous - day - prices
 Available after 4am ET Tue - Sat
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = marketYesterday ( token , version )
data = [ ]
for key in x :
    data . append ( x [ key ] )
    data [ - 1 ] [ 'symbol' ] = key
df = pd . DataFrame ( data )
_toDatetime ( df )
_reindex ( df , 'symbol' )
return df


signature:
def price ( symbol , token = '' , version = '' ) :
    '''Price of ticker
 https : / / iexcloud . io / docs / api / # price
 4:30am - 8pm ET Mon - Fri
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/price' , token , version )


signature:
def priceDF ( symbol , token = '' , version = '' ) :
    '''Price of ticker
 https : / / iexcloud . io / docs / api / # price
 4:30am - 8pm ET Mon - Fri
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( { 'price' : price ( symbol , token , version ) } )
_toDatetime ( df )
return df


signature:
def priceTarget ( symbol , token = '' , version = '' ) :
    '''Provides the latest avg , high , and low analyst price target for a symbol .
 https : / / iexcloud . io / docs / api / # price - target
 Updates at 10am , 11am , 12pm UTC every day
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/price-target' , token , version )


signature:
def priceTargetDF ( symbol , token = '' , version = '' ) :
    '''Provides the latest avg , high , and low analyst price target for a symbol .
 https : / / iexcloud . io / docs / api / # price - target
 Updates at 10am , 11am , 12pm UTC every day
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( priceTarget ( symbol , token , version ) )
_toDatetime ( df )
return df


signature:
def quote ( symbol , token = '' , version = '' ) :
    '''Get quote for ticker
 https : / / iexcloud . io / docs / api / # quote
 4:30am - 8pm ET Mon - Fri
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/quote' , token , version )


signature:
def quoteDF ( symbol , token = '' , version = '' ) :
    '''Get quote for ticker
 https : / / iexcloud . io / docs / api / # quote
 4:30am - 8pm ET Mon - Fri
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
q = quote ( symbol , token , version )
if q :
    df = pd . io . json . json_normalize ( q )
    _toDatetime ( df )
    _reindex ( df , 'symbol' )
else :
    df = pd . DataFrame ( )
return df


signature:
def relevant ( symbol , token = '' , version = '' ) :
    '''Same as peers
 https : / / iexcloud . io / docs / api / # relevant
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/relevant' , token , version )


signature:
def relevantDF ( symbol , token = '' , version = '' ) :
    '''Same as peers
 https : / / iexcloud . io / docs / api / # relevant
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( relevant ( symbol , token , version ) )
_toDatetime ( df )
return df


signature:
def sectorPerformanceDF ( token = '' , version = '' ) :
    '''This returns an array of each sector and performance for the current trading day . Performance is based on each sector ETF .
 https : / / iexcloud . io / docs / api / # sector - performance
 8am - 5pm ET Mon - Fri
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( sectorPerformance ( token , version ) )
_toDatetime ( df )
_reindex ( df , 'name' )
return df


signature:
def _splitsToDF ( s ) :
    '''internal'''

implementation:
df = pd . DataFrame ( s )
_toDatetime ( df )
_reindex ( df , 'exDate' )
return df


signature:
def splitsDF ( symbol , timeframe = 'ytd' , token = '' , version = '' ) :
    '''Stock split history
 https : / / iexcloud . io / docs / api / # splits
 Updated at 9am UTC every day
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
s = splits ( symbol , timeframe , token , version )
df = _splitsToDF ( s )
return df


signature:
def volumeByVenue ( symbol , token = '' , version = '' ) :
    '''This returns 15 minute delayed and 30 day average consolidated volume percentage of a stock , by market .
 This call will always return 13 values , and will be sorted in ascending order by current day trading volume percentage .
 https : / / iexcloud . io / docs / api / # volume - by - venue
 Updated during regular market hours 9:30am - 4pm ET
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
return _getJson ( 'stock/' + symbol + '/volume-by-venue' , token , version )


signature:
def volumeByVenueDF ( symbol , token = '' , version = '' ) :
    '''This returns 15 minute delayed and 30 day average consolidated volume percentage of a stock , by market .
 This call will always return 13 values , and will be sorted in ascending order by current day trading volume percentage .
 https : / / iexcloud . io / docs / api / # volume - by - venue
 Updated during regular market hours 9:30am - 4pm ET
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( volumeByVenue ( symbol , token , version ) )
_toDatetime ( df )
_reindex ( df , 'venue' )
return df


signature:
def threshold ( date = None , token = '' , version = '' ) :
    '''The following are IEX - listed securities that have an aggregate fail to deliver position for five consecutive settlement days at a registered clearing agency , totaling 10,000 shares or more and equal to at least 0.5 % of the issuer ’ s total shares outstanding ( i . e . , “ threshold securities ” ) .
 The report data will be published to the IEX website daily at 8:30 p . m . ET with data for that trading day .
 https : / / iexcloud . io / docs / api / # listed - regulation - sho - threshold - securities - list - in - dev
 Args :
 date ( datetime ) ; Effective Datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
if date :
    date = _strOrDate ( date )
    return _getJson ( 'stock/market/threshold-securities/' + date , token , version )
return _getJson ( 'stock/market/threshold-securities' , token , version )


signature:
def thresholdDF ( date = None , token = '' , version = '' ) :
    '''The following are IEX - listed securities that have an aggregate fail to deliver position for five consecutive settlement days at a registered clearing agency , totaling 10,000 shares or more and equal to at least 0.5 % of the issuer ’ s total shares outstanding ( i . e . , “ threshold securities ” ) .
 The report data will be published to the IEX website daily at 8:30 p . m . ET with data for that trading day .
 https : / / iexcloud . io / docs / api / # listed - regulation - sho - threshold - securities - list - in - dev
 Args :
 date ( datetime ) ; Effective Datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( threshold ( date , token , version ) )
_toDatetime ( df )
return df


signature:
def shortInterest ( symbol , date = None , token = '' , version = '' ) :
    '''The consolidated market short interest positions in all IEX - listed securities are included in the IEX Short Interest Report .
 The report data will be published daily at 4:00pm ET .
 https : / / iexcloud . io / docs / api / # listed - short - interest - list - in - dev
 Args :
 symbol ( string ) ; Ticker to request
 date ( datetime ) ; Effective Datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if date :
    date = _strOrDate ( date )
    return _getJson ( 'stock/' + symbol + '/short-interest/' + date , token , version )
return _getJson ( 'stock/' + symbol + '/short-interest' , token , version )


signature:
def shortInterestDF ( symbol , date = None , token = '' , version = '' ) :
    '''The consolidated market short interest positions in all IEX - listed securities are included in the IEX Short Interest Report .
 The report data will be published daily at 4:00pm ET .
 https : / / iexcloud . io / docs / api / # listed - short - interest - list - in - dev
 Args :
 symbol ( string ) ; Ticker to request
 date ( datetime ) ; Effective Datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( shortInterest ( symbol , date , token , version ) )
_toDatetime ( df )
return df


signature:
def marketShortInterest ( date = None , token = '' , version = '' ) :
    '''The consolidated market short interest positions in all IEX - listed securities are included in the IEX Short Interest Report .
 The report data will be published daily at 4:00pm ET .
 https : / / iexcloud . io / docs / api / # listed - short - interest - list - in - dev
 Args :
 date ( datetime ) ; Effective Datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
if date :
    date = _strOrDate ( date )
    return _getJson ( 'stock/market/short-interest/' + date , token , version )
return _getJson ( 'stock/market/short-interest' , token , version )


signature:
def marketShortInterestDF ( date = None , token = '' , version = '' ) :
    '''The consolidated market short interest positions in all IEX - listed securities are included in the IEX Short Interest Report .
 The report data will be published daily at 4:00pm ET .
 https : / / iexcloud . io / docs / api / # listed - short - interest - list - in - dev
 Args :
 date ( datetime ) ; Effective Datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( marketShortInterest ( date , token , version ) )
_toDatetime ( df )
return df


signature:
def topsSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''TOPS provides IEX ’ s aggregated best quoted bid and offer position in near real time for all securities on IEX ’ s displayed limit order book .
 TOPS is ideal for developers needing both quote and trade data .
 https : / / iexcloud . io / docs / api / # tops
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'tops' , symbols , on_data , token , version )


signature:
def lastSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''Last provides trade data for executions on IEX . It is a near real time , intraday API that provides IEX last sale price , size and time .
 Last is ideal for developers that need a lightweight stock quote .
 https : / / iexcloud . io / docs / api / # last
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'last' , symbols , on_data , token , version )


signature:
def deepSSE ( symbols = None , channels = None , on_data = None , token = '' , version = '' ) :
    '''DEEP is used to receive real - time depth of book quotations direct from IEX .
 The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side ,
 and do not indicate the size or number of individual orders at any price level .
 Non - displayed orders and non - displayed portions of reserve orders are not represented in DEEP .
 DEEP also provides last trade price and size information . Trades resulting from either displayed or non - displayed orders matching on IEX will be reported . Routed executions will not be reported .
 https : / / iexcloud . io / docs / api / # deep
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation:
symbols = _strCommaSeparatedString ( symbols )
channels = channels or [ ]
if isinstance ( channels , str ) :
    if channels not in DeepChannelsSSE . options ( ) :
        raise PyEXception ( 'Channel not recognized: %s' , type ( channels ) )
    channels = [ channels ]
elif isinstance ( channels , DeepChannelsSSE ) :
    channels = [ channels . value ]
elif isinstance ( channels , list ) :
    for i , c in enumerate ( channels ) :
        if isinstance ( c , DeepChannelsSSE ) :
            channels [ i ] = c . value
        elif not isinstance ( c , str ) or isinstance ( c , str ) and c not in DeepChannelsSSE . options ( ) :
            raise PyEXception ( 'Channel not recognized: %s' , c )
channels = _strCommaSeparatedString ( channels )
return _streamSSE ( _SSE_DEEP_URL_PREFIX . format ( symbols = symbols , channels = channels , token = token , version = version ) , on_data )


signature:
def tradesSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part . DEEP sends a Trade report message for every individual fill .
 https : / / iexcloud . io / docs / api / # deep - trades
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation:
symbols = _strCommaSeparatedString ( symbols )
return _streamSSE ( _SSE_DEEP_URL_PREFIX . format ( symbols = symbols , channels = 'trades' , token = token , version = version ) , on_data )


signature:
def auctionSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''DEEP broadcasts an Auction Information Message every one second between the Lock - in Time and the auction match for Opening and Closing Auctions ,
 and during the Display Only Period for IPO , Halt , and Volatility Auctions . Only IEX listed securities are eligible for IEX Auctions .
 https : / / iexcloud . io / docs / api / # deep - auction
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'auction' , symbols , on_data , token , version )


signature:
def bookSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''Book shows IEX ’ s bids and asks for given symbols .
 https : / / iexcloud . io / docs / api / # deep - book
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'book' , symbols , on_data , token , version )


signature:
def opHaltStatusSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message .
 IEX disseminates a full pre - market spin of Operational halt status messages indicating the operational halt status of all securities .
 In the spin , IEX will send out an Operational Halt Message with “ N ” ( Not operationally halted on IEX ) for all securities that are eligible for trading at the start of the Pre - Market Session .
 If a security is absent from the dissemination , firms should assume that the security is being treated as operationally halted in the IEX Trading System at the start of the Pre - Market Session .
 After the pre - market spin , IEX will use the Operational halt status message to relay changes in operational halt status for an individual security .
 https : / / iexcloud . io / docs / api / # deep - operational - halt - status
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'op-halt-status' , symbols , on_data , token , version )


signature:
def officialPriceSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''The Official Price message is used to disseminate the IEX Official Opening and Closing Prices .
 These messages will be provided only for IEX Listed Securities .
 https : / / iexcloud . io / docs / api / # deep - official - price
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'official-price' , symbols , on_data , token , version )


signature:
def securityEventSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''The Security event message is used to indicate events that apply to a security . A Security event message will be sent whenever such event occurs
 https : / / iexcloud . io / docs / api / # deep - security - event
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'security-event' , symbols , on_data , token , version )


signature:
def ssrStatusSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''In association with Rule 201 of Regulation SHO , the Short Sale Price Test Message is used to indicate when a short sale price test restriction is in effect for a security .
 IEX disseminates a full pre - market spin of Short sale price test status messages indicating the Rule 201 status of all securities . After the pre - market spin , IEX will use the Short sale price test status message in the event of an intraday status change .
 The IEX Trading System will process orders based on the latest short sale price test restriction status .
 https : / / iexcloud . io / docs / api / # deep - short - sale - price - test - status
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'ssr-status' , symbols , on_data , token , version )


signature:
def systemEventSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''The System event message is used to indicate events that apply to the market or the data feed .
 There will be a single message disseminated per channel for each System Event type within a given trading session .
 https : / / iexcloud . io / docs / api / # deep - system - event
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'system-event' , symbols , on_data , token , version )


signature:
def tradeBreaksSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part . DEEP sends a Trade report message for every individual fill .
 https : / / iexcloud . io / docs / api / # deep - trades
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'trade-breaks' , symbols , on_data , token , version )


signature:
def tradingStatusSSE ( symbols = None , on_data = None , token = '' , version = '' ) :
    '''The Trading status message is used to indicate the current trading status of a security .
 For IEX - listed securities , IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons .
 For non - IEX - listed securities , IEX abides by any regulatory trading halts and trading pauses instituted by the primary or listing market , as applicable .
 IEX disseminates a full pre - market spin of Trading status messages indicating the trading status of all securities .
 In the spin , IEX will send out a Trading status message with “ T ” ( Trading ) for all securities that are eligible for trading at the start of the Pre - Market Session .
 If a security is absent from the dissemination , firms should assume that the security is being treated as operationally halted in the IEX Trading System .
 After the pre - market spin , IEX will use the Trading status message to relay changes in trading status for an individual security . Messages will be sent when a security is :
 Halted
 Paused *
 Released into an Order Acceptance Period *
 Released for trading
 * The paused and released into an Order Acceptance Period status will be disseminated for IEX - listed securities only . Trading pauses on non - IEX - listed securities will be treated simply as a halt .
 https : / / iexcloud . io / docs / api / # deep - trading - status
 Args :
 symbols ( string ) ; Tickers to request
 on _ data ( function ) : Callback on data
 token ( string ) ; Access token
 version ( string ) ; API version'''

implementation: return _runSSE ( 'trading-status' , symbols , on_data , token , version )


signature:
def cryptoDF ( token = '' , version = '' ) :
    '''This will return an array of quotes for all Cryptocurrencies supported by the IEX API . Each element is a standard quote object with four additional keys .
 https : / / iexcloud . io / docs / api / # crypto
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( crypto ( token , version ) )
_toDatetime ( df )
_reindex ( df , 'symbol' )
return df


signature:
def sentiment ( symbol , type = 'daily' , date = None , token = '' , version = '' ) :
    '''This endpoint provides social sentiment data from StockTwits . Data can be viewed as a daily value , or by minute for a given date .
 https : / / iexcloud . io / docs / api / # social - sentiment
 Continuous
 Args :
 symbol ( string ) ; Ticker to request
 type ( string ) ; ' daily ' or ' minute '
 date ( string ) ; date in YYYYMMDD or datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if date :
    date = _strOrDate ( date )
    return _getJson ( 'stock/{symbol}/sentiment/{type}/{date}' . format ( symbol = symbol , type = type , date = date ) , token , version )
return _getJson ( 'stock/{symbol}/sentiment/{type}/' . format ( symbol = symbol , type = type ) , token , version )


signature:
def sentimentDF ( symbol , type = 'daily' , date = None , token = '' , version = '' ) :
    '''This endpoint provides social sentiment data from StockTwits . Data can be viewed as a daily value , or by minute for a given date .
 https : / / iexcloud . io / docs / api / # social - sentiment
 Continuous
 Args :
 symbol ( string ) ; Ticker to request
 type ( string ) ; ' daily ' or ' minute '
 date ( string ) ; date in YYYYMMDD or datetime
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
ret = sentiment ( symbol , type , date , token , version )
if type == 'daiy' :
    ret = [ ret ]
df = pd . DataFrame ( ret )
_toDatetime ( df )
return df


signature:
def statsDF ( token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - intraday
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( stats ( token , version ) )
_toDatetime ( df )
return df


signature:
def recentDF ( token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - recent
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( recent ( token , version ) )
_toDatetime ( df )
_reindex ( df , 'date' )
return df


signature:
def recordsDF ( token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - records
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( records ( token , version ) )
_toDatetime ( df )
return df


signature:
def summary ( date = None , token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - historical - summary
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
if date :
    if isinstance ( date , str ) :
        return _getJson ( 'stats/historical?date=' + date , token , version )
    elif isinstance ( date , datetime ) :
        return _getJson ( 'stats/historical?date=' + date . strftime ( '%Y%m' ) , token , version )
    else :
        raise PyEXception ( "Can't handle type : %s" % str ( type ( date ) ) , token , version )
return _getJson ( 'stats/historical' , token , version )


signature:
def summaryDF ( date = None , token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - historical - summary
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( summary ( date , token , version ) )
_toDatetime ( df )
return df


signature:
def daily ( date = None , last = '' , token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - historical - daily
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
if date :
    date = _strOrDate ( date )
    return _getJson ( 'stats/historical/daily?date=' + date , token , version )
elif last :
    return _getJson ( 'stats/historical/daily?last=' + last , token , version )
return _getJson ( 'stats/historical/daily' , token , version )


signature:
def dailyDF ( date = None , last = '' , token = '' , version = '' ) :
    '''https : / / iexcloud . io / docs / api / # stats - historical - daily
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . DataFrame ( daily ( date , last , token , version ) )
_toDatetime ( df )
return df


signature:
def topsWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # tops'''

implementation:
symbols = _strToList ( symbols )
if symbols :
    sendinit = ( 'subscribe' , ',' . join ( symbols ) )
    return _stream ( _wsURL ( 'tops' ) , sendinit , on_data )
return _stream ( _wsURL ( 'tops' ) , on_data = on_data )


signature:
def lastWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # last'''

implementation:
symbols = _strToList ( symbols )
if symbols :
    sendinit = ( 'subscribe' , ',' . join ( symbols ) )
    return _stream ( _wsURL ( 'last' ) , sendinit , on_data )
return _stream ( _wsURL ( 'last' ) , on_data = on_data )


signature:
def deepWS ( symbols = None , channels = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # deep'''

implementation:
symbols = _strToList ( symbols )
channels = channels or [ ]
if isinstance ( channels , str ) :
    if channels not in DeepChannels . options ( ) :
        raise PyEXception ( 'Channel not recognized: %s' , type ( channels ) )
    channels = [ channels ]
elif isinstance ( channels , DeepChannels ) :
    channels = [ channels . value ]
elif isinstance ( channels , list ) :
    for i , c in enumerate ( channels ) :
        if isinstance ( c , DeepChannels ) :
            channels [ i ] = c . value
        elif not isinstance ( c , str ) or isinstance ( c , str ) and c not in DeepChannels . options ( ) :
            raise PyEXception ( 'Channel not recognized: %s' , c )
sendinit = ( { 'symbols' : symbols , 'channels' : channels } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def bookWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # book51'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'book' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def tradesWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # trades'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'trades' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def tradingStatusWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # trading - status'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'tradingstatus' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def opHaltStatusWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # operational - halt - status'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'ophaltstatus' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def ssrStatusWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # short - sale - price - test - status'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'ssr' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def securityEventWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # security - event'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'securityevent' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def tradeBreakWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # trade - break'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'tradebreaks' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def auctionWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # auction'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'auction' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def officialPriceWS ( symbols = None , on_data = None ) :
    '''https : / / iextrading . com / developer / docs / # official - price'''

implementation:
symbols = _strToList ( symbols )
sendinit = ( { 'symbols' : symbols , 'channels' : [ 'official-price' ] } , )
return _stream ( _wsURL ( 'deep' ) , sendinit , on_data )


signature:
def tops ( symbols = None , token = '' , version = '' ) :
    '''TOPS provides IEX ’ s aggregated best quoted bid and offer position in near real time for all securities on IEX ’ s displayed limit order book .
 TOPS is ideal for developers needing both quote and trade data .
 https : / / iexcloud . io / docs / api / # tops
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
symbols = _strToList ( symbols )
if symbols :
    return _getJson ( 'tops?symbols=' + ',' . join ( symbols ) + '%2b' , token , version )
return _getJson ( 'tops' , token , version )


signature:
def topsDF ( symbols = None , token = '' , version = '' ) :
    '''TOPS provides IEX ’ s aggregated best quoted bid and offer position in near real time for all securities on IEX ’ s displayed limit order book .
 TOPS is ideal for developers needing both quote and trade data .
 https : / / iexcloud . io / docs / api / # tops
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( tops ( symbols , token , version ) )
_toDatetime ( df )
_reindex ( df , 'symbol' )
return df


signature:
def last ( symbols = None , token = '' , version = '' ) :
    '''Last provides trade data for executions on IEX . It is a near real time , intraday API that provides IEX last sale price , size and time .
 Last is ideal for developers that need a lightweight stock quote .
 https : / / iexcloud . io / docs / api / # last
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
symbols = _strToList ( symbols )
if symbols :
    return _getJson ( 'tops/last?symbols=' + ',' . join ( symbols ) + '%2b' , token , version )
return _getJson ( 'tops/last' , token , version )


signature:
def lastDF ( symbols = None , token = '' , version = '' ) :
    '''Last provides trade data for executions on IEX . It is a near real time , intraday API that provides IEX last sale price , size and time .
 Last is ideal for developers that need a lightweight stock quote .
 https : / / iexcloud . io / docs / api / # last
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( last ( symbols , token , version ) )
_toDatetime ( df )
_reindex ( df , 'symbol' )
return df


signature:
def deep ( symbol = None , token = '' , version = '' ) :
    '''DEEP is used to receive real - time depth of book quotations direct from IEX .
 The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side ,
 and do not indicate the size or number of individual orders at any price level .
 Non - displayed orders and non - displayed portions of reserve orders are not represented in DEEP .
 DEEP also provides last trade price and size information . Trades resulting from either displayed or non - displayed orders matching on IEX will be reported . Routed executions will not be reported .
 https : / / iexcloud . io / docs / api / # deep
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep?symbols=' + symbol , token , version )
return _getJson ( 'deep' , token , version )


signature:
def deepDF ( symbol = None , token = '' , version = '' ) :
    '''DEEP is used to receive real - time depth of book quotations direct from IEX .
 The depth of book quotations received via DEEP provide an aggregated size of resting displayed orders at a price and side ,
 and do not indicate the size or number of individual orders at any price level .
 Non - displayed orders and non - displayed portions of reserve orders are not represented in DEEP .
 DEEP also provides last trade price and size information . Trades resulting from either displayed or non - displayed orders matching on IEX will be reported . Routed executions will not be reported .
 https : / / iexcloud . io / docs / api / # deep
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( deep ( symbol , token , version ) )
_toDatetime ( df )
return df


signature:
def auction ( symbol = None , token = '' , version = '' ) :
    '''DEEP broadcasts an Auction Information Message every one second between the Lock - in Time and the auction match for Opening and Closing Auctions ,
 and during the Display Only Period for IPO , Halt , and Volatility Auctions . Only IEX listed securities are eligible for IEX Auctions .
 https : / / iexcloud . io / docs / api / # deep - auction
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/auction?symbols=' + symbol , token , version )
return _getJson ( 'deep/auction' , token , version )


signature:
def auctionDF ( symbol = None , token = '' , version = '' ) :
    '''DEEP broadcasts an Auction Information Message every one second between the Lock - in Time and the auction match for Opening and Closing Auctions ,
 and during the Display Only Period for IPO , Halt , and Volatility Auctions . Only IEX listed securities are eligible for IEX Auctions .
 https : / / iexcloud . io / docs / api / # deep - auction
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( auction ( symbol , token , version ) )
_toDatetime ( df )
return df


signature:
def book ( symbol = None , token = '' , version = '' ) :
    '''Book shows IEX ’ s bids and asks for given symbols .
 https : / / iexcloud . io / docs / api / # deep - book
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/book?symbols=' + symbol , token , version )
return _getJson ( 'deep/book' , token , version )


signature:
def bookDF ( symbol = None , token = '' , version = '' ) :
    '''Book shows IEX ’ s bids and asks for given symbols .
 https : / / iexcloud . io / docs / api / # deep - book
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = book ( symbol , token , version )
data = [ ]
for key in x :
    d = x [ key ]
    d [ 'symbol' ] = key
    data . append ( d )
df = pd . io . json . json_normalize ( data )
_toDatetime ( df )
return df


signature:
def opHaltStatus ( symbol = None , token = '' , version = '' ) :
    '''The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message .
 IEX disseminates a full pre - market spin of Operational halt status messages indicating the operational halt status of all securities .
 In the spin , IEX will send out an Operational Halt Message with “ N ” ( Not operationally halted on IEX ) for all securities that are eligible for trading at the start of the Pre - Market Session .
 If a security is absent from the dissemination , firms should assume that the security is being treated as operationally halted in the IEX Trading System at the start of the Pre - Market Session .
 After the pre - market spin , IEX will use the Operational halt status message to relay changes in operational halt status for an individual security .
 https : / / iexcloud . io / docs / api / # deep - operational - halt - status
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/op-halt-status?symbols=' + symbol , token , version )
return _getJson ( 'deep/op-halt-status' , token , version )


signature:
def opHaltStatusDF ( symbol = None , token = '' , version = '' ) :
    '''The Exchange may suspend trading of one or more securities on IEX for operational reasons and indicates such operational halt using the Operational halt status message .
 IEX disseminates a full pre - market spin of Operational halt status messages indicating the operational halt status of all securities .
 In the spin , IEX will send out an Operational Halt Message with “ N ” ( Not operationally halted on IEX ) for all securities that are eligible for trading at the start of the Pre - Market Session .
 If a security is absent from the dissemination , firms should assume that the security is being treated as operationally halted in the IEX Trading System at the start of the Pre - Market Session .
 After the pre - market spin , IEX will use the Operational halt status message to relay changes in operational halt status for an individual security .
 https : / / iexcloud . io / docs / api / # deep - operational - halt - status
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = opHaltStatus ( symbol , token , version )
data = [ ]
for key in x :
    d = x [ key ]
    d [ 'symbol' ] = key
    data . append ( d )
df = pd . DataFrame ( data )
_toDatetime ( df )
return df


signature:
def officialPrice ( symbol = None , token = '' , version = '' ) :
    '''The Official Price message is used to disseminate the IEX Official Opening and Closing Prices .
 These messages will be provided only for IEX Listed Securities .
 https : / / iexcloud . io / docs / api / # deep - official - price
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/official-price?symbols=' + symbol , token , version )
return _getJson ( 'deep/official-price' , token , version )


signature:
def officialPriceDF ( symbol = None , token = '' , version = '' ) :
    '''The Official Price message is used to disseminate the IEX Official Opening and Closing Prices .
 These messages will be provided only for IEX Listed Securities .
 https : / / iexcloud . io / docs / api / # deep - official - price
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( officialPrice ( symbol , token , version ) )
_toDatetime ( df )
return df


signature:
def securityEvent ( symbol = None , token = '' , version = '' ) :
    '''The Security event message is used to indicate events that apply to a security . A Security event message will be sent whenever such event occurs
 https : / / iexcloud . io / docs / api / # deep - security - event
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/security-event?symbols=' + symbol , token , version )
return _getJson ( 'deep/security-event' , token , version )


signature:
def securityEventDF ( symbol = None , token = '' , version = '' ) :
    '''The Security event message is used to indicate events that apply to a security . A Security event message will be sent whenever such event occurs
 https : / / iexcloud . io / docs / api / # deep - security - event
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = securityEvent ( symbol , token , version )
data = [ ]
for key in x :
    d = x [ key ]
    d [ 'symbol' ] = key
    data . append ( d )
df = pd . DataFrame ( data )
_toDatetime ( df )
return df


signature:
def ssrStatus ( symbol = None , token = '' , version = '' ) :
    '''In association with Rule 201 of Regulation SHO , the Short Sale Price Test Message is used to indicate when a short sale price test restriction is in effect for a security .
 IEX disseminates a full pre - market spin of Short sale price test status messages indicating the Rule 201 status of all securities .
 After the pre - market spin , IEX will use the Short sale price test status message in the event of an intraday status change .
 The IEX Trading System will process orders based on the latest short sale price test restriction status .
 https : / / iexcloud . io / docs / api / # deep - short - sale - price - test - status
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/ssr-status?symbols=' + symbol , token , version )
return _getJson ( 'deep/ssr-status' , token , version )


signature:
def ssrStatusDF ( symbol = None , token = '' , version = '' ) :
    '''In association with Rule 201 of Regulation SHO , the Short Sale Price Test Message is used to indicate when a short sale price test restriction is in effect for a security .
 IEX disseminates a full pre - market spin of Short sale price test status messages indicating the Rule 201 status of all securities .
 After the pre - market spin , IEX will use the Short sale price test status message in the event of an intraday status change .
 The IEX Trading System will process orders based on the latest short sale price test restriction status .
 https : / / iexcloud . io / docs / api / # deep - short - sale - price - test - status
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = ssrStatus ( symbol , token , version )
data = [ ]
for key in x :
    d = x [ key ]
    d [ 'symbol' ] = key
    data . append ( d )
df = pd . DataFrame ( data )
_toDatetime ( df )
return df


signature:
def systemEventDF ( token = '' , version = '' ) :
    '''The System event message is used to indicate events that apply to the market or the data feed .
 There will be a single message disseminated per channel for each System Event type within a given trading session .
 https : / / iexcloud . io / docs / api / # deep - system - event
 Args :
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( systemEvent ( token , version ) )
_toDatetime ( df )
return df


signature:
def trades ( symbol = None , token = '' , version = '' ) :
    '''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part . DEEP sends a Trade report message for every individual fill .
 https : / / iexcloud . io / docs / api / # deep - trades
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/trades?symbols=' + symbol , token , version )
return _getJson ( 'deep/trades' , token , version )


signature:
def tradesDF ( symbol = None , token = '' , version = '' ) :
    '''Trade report messages are sent when an order on the IEX Order Book is executed in whole or in part . DEEP sends a Trade report message for every individual fill .
 https : / / iexcloud . io / docs / api / # deep - trades
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = trades ( symbol , token , version )
data = [ ]
for key in x :
    dat = x [ key ]
    for d in dat :
        d [ 'symbol' ] = key
        data . append ( d )
df = pd . DataFrame ( data )
_toDatetime ( df )
return df


signature:
def tradeBreak ( symbol = None , token = '' , version = '' ) :
    '''Trade break messages are sent when an execution on IEX is broken on that same trading day . Trade breaks are rare and only affect applications that rely upon IEX execution based data .
 https : / / iexcloud . io / docs / api / # deep - trade - break
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/trade-breaks?symbols=' + symbol , token , version )
return _getJson ( 'deep/trade-breaks' , token , version )


signature:
def tradeBreakDF ( symbol = None , token = '' , version = '' ) :
    '''Trade break messages are sent when an execution on IEX is broken on that same trading day . Trade breaks are rare and only affect applications that rely upon IEX execution based data .
 https : / / iexcloud . io / docs / api / # deep - trade - break
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
df = pd . io . json . json_normalize ( tradeBreak ( symbol , token , version ) )
_toDatetime ( df )
return df


signature:
def tradingStatus ( symbol = None , token = '' , version = '' ) :
    '''The Trading status message is used to indicate the current trading status of a security .
 For IEX - listed securities , IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons .
 For non - IEX - listed securities , IEX abides by any regulatory trading halts and trading pauses instituted by the primary or listing market , as applicable .
 IEX disseminates a full pre - market spin of Trading status messages indicating the trading status of all securities .
 In the spin , IEX will send out a Trading status message with “ T ” ( Trading ) for all securities that are eligible for trading at the start of the Pre - Market Session .
 If a security is absent from the dissemination , firms should assume that the security is being treated as operationally halted in the IEX Trading System .
 After the pre - market spin , IEX will use the Trading status message to relay changes in trading status for an individual security . Messages will be sent when a security is :
 Halted
 Paused *
 Released into an Order Acceptance Period *
 Released for trading
 * The paused and released into an Order Acceptance Period status will be disseminated for IEX - listed securities only . Trading pauses on non - IEX - listed securities will be treated simply as a halt .
 https : / / iexcloud . io / docs / api / # deep - trading - status
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 dict : result'''

implementation:
_raiseIfNotStr ( symbol )
if symbol :
    return _getJson ( 'deep/trading-status?symbols=' + symbol , token , version )
return _getJson ( 'deep/trading-status' , token , version )


signature:
def tradingStatusDF ( symbol = None , token = '' , version = '' ) :
    '''The Trading status message is used to indicate the current trading status of a security .
 For IEX - listed securities , IEX acts as the primary market and has the authority to institute a trading halt or trading pause in a security due to news dissemination or regulatory reasons .
 For non - IEX - listed securities , IEX abides by any regulatory trading halts and trading pauses instituted by the primary or listing market , as applicable .
 IEX disseminates a full pre - market spin of Trading status messages indicating the trading status of all securities .
 In the spin , IEX will send out a Trading status message with “ T ” ( Trading ) for all securities that are eligible for trading at the start of the Pre - Market Session .
 If a security is absent from the dissemination , firms should assume that the security is being treated as operationally halted in the IEX Trading System .
 After the pre - market spin , IEX will use the Trading status message to relay changes in trading status for an individual security . Messages will be sent when a security is :
 Halted
 Paused *
 Released into an Order Acceptance Period *
 Released for trading
 * The paused and released into an Order Acceptance Period status will be disseminated for IEX - listed securities only . Trading pauses on non - IEX - listed securities will be treated simply as a halt .
 https : / / iexcloud . io / docs / api / # deep - trading - status
 Args :
 symbol ( string ) ; Ticker to request
 token ( string ) ; Access token
 version ( string ) ; API version
 Returns :
 DataFrame : result'''

implementation:
x = tradingStatus ( symbol , token , version )
data = [ ]
for key in x :
    d = x [ key ]
    d [ 'symbol' ] = key
    data . append ( d )
df = pd . DataFrame ( data )
_toDatetime ( df )
return df


signature:
def histDF ( date = None , token = '' , version = '' ) :
    '''https : / / iextrading . com / developer / docs / # hist'''

implementation:
x = hist ( date , token , version )
data = [ ]
for key in x :
    dat = x [ key ]
    for item in dat :
        item [ 'date' ] = key
        data . append ( item )
df = pd . DataFrame ( data )
_toDatetime ( df )
_reindex ( df , 'date' )
return df


signature:
def look ( self , i = 0 ) :
    """Look ahead of the iterable by some number of values with advancing
 past them .
 If the requested look ahead is past the end of the iterable then None is
 returned ."""

implementation:
length = len ( self . look_ahead )
if length <= i :
    try :
        self . look_ahead . extend ( [ next ( self . iterable ) for _ in range ( length , i + 1 ) ] )
    except StopIteration :
        return self . default
self . value = self . look_ahead [ i ]
return self . value


signature:
def pop_marker ( self , reset ) :
    """Pop a marker off of the marker stack . If reset is True then the
 iterator will be returned to the state it was in before the
 corresponding call to push _ marker ( ) ."""

implementation:
marker = self . markers . pop ( )
if reset : # Make the values available to be read again
    marker . extend ( self . look_ahead )
    self . look_ahead = marker
elif self . markers : # Otherwise , reassign the values to the top marker
    self . markers [ - 1 ] . extend ( marker )
else : # If there are not more markers in the stack then discard the values
    pass


implementation:
try :
    self . value = self . list [ self . marker + i ]
except IndexError :
    return self . default
return self . value


implementation:
saved = self . saved_markers . pop ( )
if reset :
    self . marker = saved
elif self . saved_markers :
    self . saved_markers [ - 1 ] = saved


signature:
def is_annotation ( self , i = 0 ) :
    """Returns true if the position is the start of an annotation application
 ( as opposed to an annotation declaration )"""

implementation: return ( isinstance ( self . tokens . look ( i ) , Annotation ) and not self . tokens . look ( i + 1 ) . value == 'interface' )


signature:
def is_annotation_declaration ( self , i = 0 ) :
    """Returns true if the position is the start of an annotation application
 ( as opposed to an annotation declaration )"""

implementation: return ( isinstance ( self . tokens . look ( i ) , Annotation ) and self . tokens . look ( i + 1 ) . value == 'interface' )


signature:
def parse_command_line ( self , argv = None ) :
    """Overriden to check for conflicting flags
 Since notebook version doesn ' t do it well ( or , indeed , at all )"""

implementation:
conflicting_flags = set ( [ '--user' , '--system' , '--sys-prefix' ] )
if len ( conflicting_flags . intersection ( set ( argv ) ) ) > 1 :
    raise serverextensions . ArgumentConflict ( 'cannot specify more than one of user, sys_prefix, or system' )
return super ( ToggleJupyterTensorboardApp , self ) . parse_command_line ( argv )


signature:
def start ( self ) :
    """Perform the App ' s actions as configured ."""

implementation:
if self . extra_args :
    sys . exit ( '{} takes no extra arguments' . format ( self . name ) )
else :
    if self . _toggle_value :
        nbextensions . install_nbextension_python ( _pkg_name , overwrite = True , symlink = False , user = self . user , sys_prefix = self . sys_prefix , prefix = None , nbextensions_dir = None , logger = None )
    else :
        nbextensions . uninstall_nbextension_python ( _pkg_name , user = self . user , sys_prefix = self . sys_prefix , prefix = None , nbextensions_dir = None , logger = None )
    self . toggle_nbextension_python ( _pkg_name )
    self . toggle_server_extension_python ( _pkg_name )


signature:
def start ( self ) :
    """Perform the App ' s actions as configured"""

implementation:
super ( JupyterTensorboardApp , self ) . start ( )
# The above should have called a subcommand and raised NoStart ; if we
# get here , it didn ' t , so we should self . log . info a message .
subcmds = ", " . join ( sorted ( self . subcommands ) )
sys . exit ( "Please supply at least one subcommand: %s" % subcmds )


signature:
def _load_client_secrets ( filename ) :
    """Loads client secrets from the given filename .
 Args :
 filename : The name of the file containing the JSON secret key .
 Returns :
 A 2 - tuple , the first item containing the client id , and the second
 item containing a client secret ."""

implementation:
client_type , client_info = clientsecrets . loadfile ( filename )
if client_type != clientsecrets . TYPE_WEB :
    raise ValueError ( 'The flow specified in {} is not supported, only the WEB flow ' 'type  is supported.' . format ( client_type ) )
return client_info [ 'client_id' ] , client_info [ 'client_secret' ]


signature:
def _get_oauth2_client_id_and_secret ( settings_instance ) :
    """Initializes client id and client secret based on the settings .
 Args :
 settings _ instance : An instance of ` ` django . conf . settings ` ` .
 Returns :
 A 2 - tuple , the first item is the client id and the second
 item is the client secret ."""

implementation:
secret_json = getattr ( settings_instance , 'GOOGLE_OAUTH2_CLIENT_SECRETS_JSON' , None )
if secret_json is not None :
    return _load_client_secrets ( secret_json )
else :
    client_id = getattr ( settings_instance , "GOOGLE_OAUTH2_CLIENT_ID" , None )
    client_secret = getattr ( settings_instance , "GOOGLE_OAUTH2_CLIENT_SECRET" , None )
    if client_id is not None and client_secret is not None :
        return client_id , client_secret
    else :
        raise exceptions . ImproperlyConfigured ( "Must specify either GOOGLE_OAUTH2_CLIENT_SECRETS_JSON, or " "both GOOGLE_OAUTH2_CLIENT_ID and " "GOOGLE_OAUTH2_CLIENT_SECRET in settings.py" )


signature:
def _get_storage_model ( ) :
    """This configures whether the credentials will be stored in the session
 or the Django ORM based on the settings . By default , the credentials
 will be stored in the session , unless ` GOOGLE _ OAUTH2 _ STORAGE _ MODEL `
 is found in the settings . Usually , the ORM storage is used to integrate
 credentials into an existing Django user system .
 Returns :
 A tuple containing three strings , or None . If
 ` ` GOOGLE _ OAUTH2 _ STORAGE _ MODEL ` ` is configured , the tuple
 will contain the fully qualifed path of the ` django . db . model ` ,
 the name of the ` ` django . contrib . auth . models . User ` ` field on the
 model , and the name of the
 : class : ` oauth2client . contrib . django _ util . models . CredentialsField `
 field on the model . If Django ORM storage is not configured ,
 this function returns None ."""

implementation:
storage_model_settings = getattr ( django . conf . settings , 'GOOGLE_OAUTH2_STORAGE_MODEL' , None )
if storage_model_settings is not None :
    return ( storage_model_settings [ 'model' ] , storage_model_settings [ 'user_property' ] , storage_model_settings [ 'credentials_property' ] )
else :
    return None , None , None


signature:
def get_storage ( request ) :
    """Gets a Credentials storage object provided by the Django OAuth2 Helper
 object .
 Args :
 request : Reference to the current request object .
 Returns :
 An : class : ` oauth2 . client . Storage ` object ."""

implementation:
storage_model = oauth2_settings . storage_model
user_property = oauth2_settings . storage_model_user_property
credentials_property = oauth2_settings . storage_model_credentials_property
if storage_model :
    module_name , class_name = storage_model . rsplit ( '.' , 1 )
    module = importlib . import_module ( module_name )
    storage_model_class = getattr ( module , class_name )
    return storage . DjangoORMStorage ( storage_model_class , user_property , request . user , credentials_property )
else : # use session
    return dictionary_storage . DictionaryStorage ( request . session , key = _CREDENTIALS_KEY )


signature:
def _redirect_with_params ( url_name , * args , ** kwargs ) :
    """Helper method to create a redirect response with URL params .
 This builds a redirect string that converts kwargs into a
 query string .
 Args :
 url _ name : The name of the url to redirect to .
 kwargs : the query string param and their values to build .
 Returns :
 A properly formatted redirect string ."""

implementation:
url = urlresolvers . reverse ( url_name , args = args )
params = parse . urlencode ( kwargs , True )
return "{0}?{1}" . format ( url , params )


signature:
def _credentials_from_request ( request ) :
    """Gets the authorized credentials for this flow , if they exist ."""

implementation:
# ORM storage requires a logged in user
if ( oauth2_settings . storage_model is None or request . user . is_authenticated ( ) ) :
    return get_storage ( request ) . get ( )
else :
    return None


signature:
def has_credentials ( self ) :
    """Returns True if there are valid credentials for the current user
 and required scopes ."""

implementation:
credentials = _credentials_from_request ( self . request )
return ( credentials and not credentials . invalid and credentials . has_scopes ( self . _get_scopes ( ) ) )


signature:
def _get_scopes ( self ) :
    """Returns the scopes associated with this object , kept up to
 date for incremental auth ."""

implementation:
if _credentials_from_request ( self . request ) :
    return ( self . _scopes | _credentials_from_request ( self . request ) . scopes )
else :
    return self . _scopes


signature:
def locked_get ( self ) :
    """Retrieve stored credential .
 Returns :
 A : class : ` oauth2client . Credentials ` instance or ` None ` ."""

implementation:
filters = { self . key_name : self . key_value }
query = self . session . query ( self . model_class ) . filter_by ( ** filters )
entity = query . first ( )
if entity :
    credential = getattr ( entity , self . property_name )
    if credential and hasattr ( credential , 'set_store' ) :
        credential . set_store ( self )
    return credential
else :
    return None


signature:
def locked_put ( self , credentials ) :
    """Write a credentials to the SQLAlchemy datastore .
 Args :
 credentials : : class : ` oauth2client . Credentials `"""

implementation:
filters = { self . key_name : self . key_value }
query = self . session . query ( self . model_class ) . filter_by ( ** filters )
entity = query . first ( )
if not entity :
    entity = self . model_class ( ** filters )
setattr ( entity , self . property_name , credentials )
self . session . add ( entity )


signature:
def locked_delete ( self ) :
    """Delete credentials from the SQLAlchemy datastore ."""

implementation:
filters = { self . key_name : self . key_value }
self . session . query ( self . model_class ) . filter_by ( ** filters ) . delete ( )


signature:
def _to_json ( self , strip , to_serialize = None ) :
    """Utility function that creates JSON repr . of a credentials object .
 Over - ride is needed since PKCS # 12 keys will not in general be JSON
 serializable .
 Args :
 strip : array , An array of names of members to exclude from the
 JSON .
 to _ serialize : dict , ( Optional ) The properties for this object
 that will be serialized . This allows callers to
 modify before serializing .
 Returns :
 string , a JSON representation of this instance , suitable to pass to
 from _ json ( ) ."""

implementation:
if to_serialize is None :
    to_serialize = copy . copy ( self . __dict__ )
pkcs12_val = to_serialize . get ( _PKCS12_KEY )
if pkcs12_val is not None :
    to_serialize [ _PKCS12_KEY ] = base64 . b64encode ( pkcs12_val )
return super ( ServiceAccountCredentials , self ) . _to_json ( strip , to_serialize = to_serialize )


signature:
def _from_parsed_json_keyfile ( cls , keyfile_dict , scopes , token_uri = None , revoke_uri = None ) :
    """Helper for factory constructors from JSON keyfile .
 Args :
 keyfile _ dict : dict - like object , The parsed dictionary - like object
 containing the contents of the JSON keyfile .
 scopes : List or string , Scopes to use when acquiring an
 access token .
 token _ uri : string , URI for OAuth 2.0 provider token endpoint .
 If unset and not present in keyfile _ dict , defaults
 to Google ' s endpoints .
 revoke _ uri : string , URI for OAuth 2.0 provider revoke endpoint .
 If unset and not present in keyfile _ dict , defaults
 to Google ' s endpoints .
 Returns :
 ServiceAccountCredentials , a credentials object created from
 the keyfile contents .
 Raises :
 ValueError , if the credential type is not : data : ` SERVICE _ ACCOUNT ` .
 KeyError , if one of the expected keys is not present in
 the keyfile ."""

implementation:
creds_type = keyfile_dict . get ( 'type' )
if creds_type != client . SERVICE_ACCOUNT :
    raise ValueError ( 'Unexpected credentials type' , creds_type , 'Expected' , client . SERVICE_ACCOUNT )
service_account_email = keyfile_dict [ 'client_email' ]
private_key_pkcs8_pem = keyfile_dict [ 'private_key' ]
private_key_id = keyfile_dict [ 'private_key_id' ]
client_id = keyfile_dict [ 'client_id' ]
if not token_uri :
    token_uri = keyfile_dict . get ( 'token_uri' , oauth2client . GOOGLE_TOKEN_URI )
if not revoke_uri :
    revoke_uri = keyfile_dict . get ( 'revoke_uri' , oauth2client . GOOGLE_REVOKE_URI )
signer = crypt . Signer . from_string ( private_key_pkcs8_pem )
credentials = cls ( service_account_email , signer , scopes = scopes , private_key_id = private_key_id , client_id = client_id , token_uri = token_uri , revoke_uri = revoke_uri )
credentials . _private_key_pkcs8_pem = private_key_pkcs8_pem
return credentials


signature:
def from_json_keyfile_name ( cls , filename , scopes = '' , token_uri = None , revoke_uri = None ) :
    """Factory constructor from JSON keyfile by name .
 Args :
 filename : string , The location of the keyfile .
 scopes : List or string , ( Optional ) Scopes to use when acquiring an
 access token .
 token _ uri : string , URI for OAuth 2.0 provider token endpoint .
 If unset and not present in the key file , defaults
 to Google ' s endpoints .
 revoke _ uri : string , URI for OAuth 2.0 provider revoke endpoint .
 If unset and not present in the key file , defaults
 to Google ' s endpoints .
 Returns :
 ServiceAccountCredentials , a credentials object created from
 the keyfile .
 Raises :
 ValueError , if the credential type is not : data : ` SERVICE _ ACCOUNT ` .
 KeyError , if one of the expected keys is not present in
 the keyfile ."""

implementation:
with open ( filename , 'r' ) as file_obj :
    client_credentials = json . load ( file_obj )
return cls . _from_parsed_json_keyfile ( client_credentials , scopes , token_uri = token_uri , revoke_uri = revoke_uri )


signature:
def from_json_keyfile_dict ( cls , keyfile_dict , scopes = '' , token_uri = None , revoke_uri = None ) :
    """Factory constructor from parsed JSON keyfile .
 Args :
 keyfile _ dict : dict - like object , The parsed dictionary - like object
 containing the contents of the JSON keyfile .
 scopes : List or string , ( Optional ) Scopes to use when acquiring an
 access token .
 token _ uri : string , URI for OAuth 2.0 provider token endpoint .
 If unset and not present in keyfile _ dict , defaults
 to Google ' s endpoints .
 revoke _ uri : string , URI for OAuth 2.0 provider revoke endpoint .
 If unset and not present in keyfile _ dict , defaults
 to Google ' s endpoints .
 Returns :
 ServiceAccountCredentials , a credentials object created from
 the keyfile .
 Raises :
 ValueError , if the credential type is not : data : ` SERVICE _ ACCOUNT ` .
 KeyError , if one of the expected keys is not present in
 the keyfile ."""

implementation: return cls . _from_parsed_json_keyfile ( keyfile_dict , scopes , token_uri = token_uri , revoke_uri = revoke_uri )


signature:
def _from_p12_keyfile_contents ( cls , service_account_email , private_key_pkcs12 , private_key_password = None , scopes = '' , token_uri = oauth2client . GOOGLE_TOKEN_URI , revoke_uri = oauth2client . GOOGLE_REVOKE_URI ) :
    """Factory constructor from JSON keyfile .
 Args :
 service _ account _ email : string , The email associated with the
 service account .
 private _ key _ pkcs12 : string , The contents of a PKCS # 12 keyfile .
 private _ key _ password : string , ( Optional ) Password for PKCS # 12
 private key . Defaults to ` ` notasecret ` ` .
 scopes : List or string , ( Optional ) Scopes to use when acquiring an
 access token .
 token _ uri : string , URI for token endpoint . For convenience defaults
 to Google ' s endpoints but any OAuth 2.0 provider can be
 used .
 revoke _ uri : string , URI for revoke endpoint . For convenience
 defaults to Google ' s endpoints but any OAuth 2.0
 provider can be used .
 Returns :
 ServiceAccountCredentials , a credentials object created from
 the keyfile .
 Raises :
 NotImplementedError if pyOpenSSL is not installed / not the
 active crypto library ."""

implementation:
if private_key_password is None :
    private_key_password = _PASSWORD_DEFAULT
if crypt . Signer is not crypt . OpenSSLSigner :
    raise NotImplementedError ( _PKCS12_ERROR )
signer = crypt . Signer . from_string ( private_key_pkcs12 , private_key_password )
credentials = cls ( service_account_email , signer , scopes = scopes , token_uri = token_uri , revoke_uri = revoke_uri )
credentials . _private_key_pkcs12 = private_key_pkcs12
credentials . _private_key_password = private_key_password
return credentials


signature:
def from_p12_keyfile ( cls , service_account_email , filename , private_key_password = None , scopes = '' , token_uri = oauth2client . GOOGLE_TOKEN_URI , revoke_uri = oauth2client . GOOGLE_REVOKE_URI ) :
    """Factory constructor from JSON keyfile .
 Args :
 service _ account _ email : string , The email associated with the
 service account .
 filename : string , The location of the PKCS # 12 keyfile .
 private _ key _ password : string , ( Optional ) Password for PKCS # 12
 private key . Defaults to ` ` notasecret ` ` .
 scopes : List or string , ( Optional ) Scopes to use when acquiring an
 access token .
 token _ uri : string , URI for token endpoint . For convenience defaults
 to Google ' s endpoints but any OAuth 2.0 provider can be
 used .
 revoke _ uri : string , URI for revoke endpoint . For convenience
 defaults to Google ' s endpoints but any OAuth 2.0
 provider can be used .
 Returns :
 ServiceAccountCredentials , a credentials object created from
 the keyfile .
 Raises :
 NotImplementedError if pyOpenSSL is not installed / not the
 active crypto library ."""

implementation:
with open ( filename , 'rb' ) as file_obj :
    private_key_pkcs12 = file_obj . read ( )
return cls . _from_p12_keyfile_contents ( service_account_email , private_key_pkcs12 , private_key_password = private_key_password , scopes = scopes , token_uri = token_uri , revoke_uri = revoke_uri )


signature:
def from_p12_keyfile_buffer ( cls , service_account_email , file_buffer , private_key_password = None , scopes = '' , token_uri = oauth2client . GOOGLE_TOKEN_URI , revoke_uri = oauth2client . GOOGLE_REVOKE_URI ) :
    """Factory constructor from JSON keyfile .
 Args :
 service _ account _ email : string , The email associated with the
 service account .
 file _ buffer : stream , A buffer that implements ` ` read ( ) ` `
 and contains the PKCS # 12 key contents .
 private _ key _ password : string , ( Optional ) Password for PKCS # 12
 private key . Defaults to ` ` notasecret ` ` .
 scopes : List or string , ( Optional ) Scopes to use when acquiring an
 access token .
 token _ uri : string , URI for token endpoint . For convenience defaults
 to Google ' s endpoints but any OAuth 2.0 provider can be
 used .
 revoke _ uri : string , URI for revoke endpoint . For convenience
 defaults to Google ' s endpoints but any OAuth 2.0
 provider can be used .
 Returns :
 ServiceAccountCredentials , a credentials object created from
 the keyfile .
 Raises :
 NotImplementedError if pyOpenSSL is not installed / not the
 active crypto library ."""

implementation:
private_key_pkcs12 = file_buffer . read ( )
return cls . _from_p12_keyfile_contents ( service_account_email , private_key_pkcs12 , private_key_password = private_key_password , scopes = scopes , token_uri = token_uri , revoke_uri = revoke_uri )


signature:
def _generate_assertion ( self ) :
    """Generate the assertion that will be used in the request ."""

implementation:
now = int ( time . time ( ) )
payload = { 'aud' : self . token_uri , 'scope' : self . _scopes , 'iat' : now , 'exp' : now + self . MAX_TOKEN_LIFETIME_SECS , 'iss' : self . _service_account_email , }
payload . update ( self . _kwargs )
return crypt . make_signed_jwt ( self . _signer , payload , key_id = self . _private_key_id )


signature:
def from_json ( cls , json_data ) :
    """Deserialize a JSON - serialized instance .
 Inverse to : meth : ` to _ json ` .
 Args :
 json _ data : dict or string , Serialized JSON ( as a string or an
 already parsed dictionary ) representing a credential .
 Returns :
 ServiceAccountCredentials from the serialized data ."""

implementation:
if not isinstance ( json_data , dict ) :
    json_data = json . loads ( _helpers . _from_bytes ( json_data ) )
private_key_pkcs8_pem = None
pkcs12_val = json_data . get ( _PKCS12_KEY )
password = None
if pkcs12_val is None :
    private_key_pkcs8_pem = json_data [ '_private_key_pkcs8_pem' ]
    signer = crypt . Signer . from_string ( private_key_pkcs8_pem )
else : # NOTE : This assumes that private _ key _ pkcs8 _ pem is not also
# in the serialized data . This would be very incorrect
# state .
    pkcs12_val = base64 . b64decode ( pkcs12_val )
    password = json_data [ '_private_key_password' ]
    signer = crypt . Signer . from_string ( pkcs12_val , password )
credentials = cls ( json_data [ '_service_account_email' ] , signer , scopes = json_data [ '_scopes' ] , private_key_id = json_data [ '_private_key_id' ] , client_id = json_data [ 'client_id' ] , user_agent = json_data [ '_user_agent' ] , ** json_data [ '_kwargs' ] )
if private_key_pkcs8_pem is not None :
    credentials . _private_key_pkcs8_pem = private_key_pkcs8_pem
if pkcs12_val is not None :
    credentials . _private_key_pkcs12 = pkcs12_val
if password is not None :
    credentials . _private_key_password = password
credentials . invalid = json_data [ 'invalid' ]
credentials . access_token = json_data [ 'access_token' ]
credentials . token_uri = json_data [ 'token_uri' ]
credentials . revoke_uri = json_data [ 'revoke_uri' ]
token_expiry = json_data . get ( 'token_expiry' , None )
if token_expiry is not None :
    credentials . token_expiry = datetime . datetime . strptime ( token_expiry , client . EXPIRY_FORMAT )
return credentials


signature:
def create_with_claims ( self , claims ) :
    """Create credentials that specify additional claims .
 Args :
 claims : dict , key - value pairs for claims .
 Returns :
 ServiceAccountCredentials , a copy of the current service account
 credentials with updated claims to use when obtaining access
 tokens ."""

implementation:
new_kwargs = dict ( self . _kwargs )
new_kwargs . update ( claims )
result = self . __class__ ( self . _service_account_email , self . _signer , scopes = self . _scopes , private_key_id = self . _private_key_id , client_id = self . client_id , user_agent = self . _user_agent , ** new_kwargs )
result . token_uri = self . token_uri
result . revoke_uri = self . revoke_uri
result . _private_key_pkcs8_pem = self . _private_key_pkcs8_pem
result . _private_key_pkcs12 = self . _private_key_pkcs12
result . _private_key_password = self . _private_key_password
return result


signature:
def get_access_token ( self , http = None , additional_claims = None ) :
    """Create a signed jwt .
 Args :
 http : unused
 additional _ claims : dict , additional claims to add to
 the payload of the JWT .
 Returns :
 An AccessTokenInfo with the signed jwt"""

implementation:
if additional_claims is None :
    if self . access_token is None or self . access_token_expired :
        self . refresh ( None )
    return client . AccessTokenInfo ( access_token = self . access_token , expires_in = self . _expires_in ( ) )
else : # Create a 1 time token
    token , unused_expiry = self . _create_token ( additional_claims )
    return client . AccessTokenInfo ( access_token = token , expires_in = self . _MAX_TOKEN_LIFETIME_SECS )


signature:
def _detect_gce_environment ( ) :
    """Determine if the current environment is Compute Engine .
 Returns :
 Boolean indicating whether or not the current environment is Google
 Compute Engine ."""

implementation:
# NOTE : The explicit ` ` timeout ` ` is a workaround . The underlying
# issue is that resolving an unknown host on some networks will take
# 20-30 seconds ; making this timeout short fixes the issue , but
# could lead to false negatives in the event that we are on GCE , but
# the metadata resolution was particularly slow . The latter case is
# " unlikely " .
http = transport . get_http_object ( timeout = GCE_METADATA_TIMEOUT )
try :
    response , _ = transport . request ( http , _GCE_METADATA_URI , headers = _GCE_HEADERS )
    return ( response . status == http_client . OK and response . get ( _METADATA_FLAVOR_HEADER ) == _DESIRED_METADATA_FLAVOR )
except socket . error : # socket . timeout or socket . error ( 64 , ' Host is down ' )
    logger . info ( 'Timeout attempting to reach GCE metadata service.' )
    return False


signature:
def _in_gae_environment ( ) :
    """Detects if the code is running in the App Engine environment .
 Returns :
 True if running in the GAE environment , False otherwise ."""

implementation:
if SETTINGS . env_name is not None :
    return SETTINGS . env_name in ( 'GAE_PRODUCTION' , 'GAE_LOCAL' )
try :
    import google . appengine
    # noqa : unused import
except ImportError :
    pass
else :
    server_software = os . environ . get ( _SERVER_SOFTWARE , '' )
    if server_software . startswith ( 'Google App Engine/' ) :
        SETTINGS . env_name = 'GAE_PRODUCTION'
        return True
    elif server_software . startswith ( 'Development/' ) :
        SETTINGS . env_name = 'GAE_LOCAL'
        return True
return False


signature:
def _in_gce_environment ( ) :
    """Detect if the code is running in the Compute Engine environment .
 Returns :
 True if running in the GCE environment , False otherwise ."""

implementation:
if SETTINGS . env_name is not None :
    return SETTINGS . env_name == 'GCE_PRODUCTION'
if NO_GCE_CHECK != 'True' and _detect_gce_environment ( ) :
    SETTINGS . env_name = 'GCE_PRODUCTION'
    return True
return False


signature:
def _save_private_file ( filename , json_contents ) :
    """Saves a file with read - write permissions on for the owner .
 Args :
 filename : String . Absolute path to file .
 json _ contents : JSON serializable object to be saved ."""

implementation:
temp_filename = tempfile . mktemp ( )
file_desc = os . open ( temp_filename , os . O_WRONLY | os . O_CREAT , 0o600 )
with os . fdopen ( file_desc , 'w' ) as file_handle :
    json . dump ( json_contents , file_handle , sort_keys = True , indent = 2 , separators = ( ',' , ': ' ) )
shutil . move ( temp_filename , filename )


signature:
def save_to_well_known_file ( credentials , well_known_file = None ) :
    """Save the provided GoogleCredentials to the well known file .
 Args :
 credentials : the credentials to be saved to the well known file ;
 it should be an instance of GoogleCredentials
 well _ known _ file : the name of the file where the credentials are to be
 saved ; this parameter is supposed to be used for
 testing only"""

implementation:
# TODO ( orestica ) : move this method to tools . py
# once the argparse import gets fixed ( it is not present in Python 2.6)
if well_known_file is None :
    well_known_file = _get_well_known_file ( )
config_dir = os . path . dirname ( well_known_file )
if not os . path . isdir ( config_dir ) :
    raise OSError ( 'Config directory does not exist: {0}' . format ( config_dir ) )
credentials_data = credentials . serialization_data
_save_private_file ( well_known_file , credentials_data )


signature:
def _get_well_known_file ( ) :
    """Get the well known file produced by command ' gcloud auth login ' ."""

implementation:
# TODO ( orestica ) : Revisit this method once gcloud provides a better way
# of pinpointing the exact location of the file .
default_config_dir = os . getenv ( _CLOUDSDK_CONFIG_ENV_VAR )
if default_config_dir is None :
    if os . name == 'nt' :
        try :
            default_config_dir = os . path . join ( os . environ [ 'APPDATA' ] , _CLOUDSDK_CONFIG_DIRECTORY )
        except KeyError : # This should never happen unless someone is really
        # messing with things .
            drive = os . environ . get ( 'SystemDrive' , 'C:' )
            default_config_dir = os . path . join ( drive , '\\' , _CLOUDSDK_CONFIG_DIRECTORY )
    else :
        default_config_dir = os . path . join ( os . path . expanduser ( '~' ) , '.config' , _CLOUDSDK_CONFIG_DIRECTORY )
return os . path . join ( default_config_dir , _WELL_KNOWN_CREDENTIALS_FILE )


signature:
def _get_application_default_credential_from_file ( filename ) :
    """Build the Application Default Credentials from file ."""

implementation:
# read the credentials from the file
with open ( filename ) as file_obj :
    client_credentials = json . load ( file_obj )
credentials_type = client_credentials . get ( 'type' )
if credentials_type == AUTHORIZED_USER :
    required_fields = set ( [ 'client_id' , 'client_secret' , 'refresh_token' ] )
elif credentials_type == SERVICE_ACCOUNT :
    required_fields = set ( [ 'client_id' , 'client_email' , 'private_key_id' , 'private_key' ] )
else :
    raise ApplicationDefaultCredentialsError ( "'type' field should be defined (and have one of the '" + AUTHORIZED_USER + "' or '" + SERVICE_ACCOUNT + "' values)" )
missing_fields = required_fields . difference ( client_credentials . keys ( ) )
if missing_fields :
    _raise_exception_for_missing_fields ( missing_fields )
if client_credentials [ 'type' ] == AUTHORIZED_USER :
    return GoogleCredentials ( access_token = None , client_id = client_credentials [ 'client_id' ] , client_secret = client_credentials [ 'client_secret' ] , refresh_token = client_credentials [ 'refresh_token' ] , token_expiry = None , token_uri = oauth2client . GOOGLE_TOKEN_URI , user_agent = 'Python client library' )
else : # client _ credentials [ ' type ' ] = = SERVICE _ ACCOUNT
    from oauth2client import service_account
    return service_account . _JWTAccessCredentials . from_json_keyfile_dict ( client_credentials )


signature:
def verify_id_token ( id_token , audience , http = None , cert_uri = ID_TOKEN_VERIFICATION_CERTS ) :
    """Verifies a signed JWT id _ token .
 This function requires PyOpenSSL and because of that it does not work on
 App Engine .
 Args :
 id _ token : string , A Signed JWT .
 audience : string , The audience ' aud ' that the token should be for .
 http : httplib2 . Http , instance to use to make the HTTP request . Callers
 should supply an instance that has caching enabled .
 cert _ uri : string , URI of the certificates in JSON format to
 verify the JWT against .
 Returns :
 The deserialized JSON in the JWT .
 Raises :
 oauth2client . crypt . AppIdentityError : if the JWT fails to verify .
 CryptoUnavailableError : if no crypto library is available ."""

implementation:
_require_crypto_or_die ( )
if http is None :
    http = transport . get_cached_http ( )
resp , content = transport . request ( http , cert_uri )
if resp . status == http_client . OK :
    certs = json . loads ( _helpers . _from_bytes ( content ) )
    return crypt . verify_signed_jwt_with_certs ( id_token , certs , audience )
else :
    raise VerifyJwtTokenError ( 'Status code: {0}' . format ( resp . status ) )


signature:
def _extract_id_token ( id_token ) :
    """Extract the JSON payload from a JWT .
 Does the extraction w / o checking the signature .
 Args :
 id _ token : string or bytestring , OAuth 2.0 id _ token .
 Returns :
 object , The deserialized JSON payload ."""

implementation:
if type ( id_token ) == bytes :
    segments = id_token . split ( b'.' )
else :
    segments = id_token . split ( u'.' )
if len ( segments ) != 3 :
    raise VerifyJwtTokenError ( 'Wrong number of segments in token: {0}' . format ( id_token ) )
return json . loads ( _helpers . _from_bytes ( _helpers . _urlsafe_b64decode ( segments [ 1 ] ) ) )


signature:
def _parse_exchange_token_response ( content ) :
    """Parses response of an exchange token request .
 Most providers return JSON but some ( e . g . Facebook ) return a
 url - encoded string .
 Args :
 content : The body of a response
 Returns :
 Content as a dictionary object . Note that the dict could be empty ,
 i . e . { } . That basically indicates a failure ."""

implementation:
resp = { }
content = _helpers . _from_bytes ( content )
try :
    resp = json . loads ( content )
except Exception : # different JSON libs raise different exceptions ,
# so we just do a catch - all here
    resp = _helpers . parse_unique_urlencoded ( content )
# some providers respond with ' expires ' , others with ' expires _ in '
if resp and 'expires' in resp :
    resp [ 'expires_in' ] = resp . pop ( 'expires' )
return resp


signature:
def credentials_from_code ( client_id , client_secret , scope , code , redirect_uri = 'postmessage' , http = None , user_agent = None , token_uri = oauth2client . GOOGLE_TOKEN_URI , auth_uri = oauth2client . GOOGLE_AUTH_URI , revoke_uri = oauth2client . GOOGLE_REVOKE_URI , device_uri = oauth2client . GOOGLE_DEVICE_URI , token_info_uri = oauth2client . GOOGLE_TOKEN_INFO_URI , pkce = False , code_verifier = None ) :
    """Exchanges an authorization code for an OAuth2Credentials object .
 Args :
 client _ id : string , client identifier .
 client _ secret : string , client secret .
 scope : string or iterable of strings , scope ( s ) to request .
 code : string , An authorization code , most likely passed down from
 the client
 redirect _ uri : string , this is generally set to ' postmessage ' to match
 the redirect _ uri that the client specified
 http : httplib2 . Http , optional http instance to use to do the fetch
 token _ uri : string , URI for token endpoint . For convenience defaults
 to Google ' s endpoints but any OAuth 2.0 provider can be
 used .
 auth _ uri : string , URI for authorization endpoint . For convenience
 defaults to Google ' s endpoints but any OAuth 2.0 provider
 can be used .
 revoke _ uri : string , URI for revoke endpoint . For convenience
 defaults to Google ' s endpoints but any OAuth 2.0 provider
 can be used .
 device _ uri : string , URI for device authorization endpoint . For
 convenience defaults to Google ' s endpoints but any OAuth
 2.0 provider can be used .
 pkce : boolean , default : False , Generate and include a " Proof Key
 for Code Exchange " ( PKCE ) with your authorization and token
 requests . This adds security for installed applications that
 cannot protect a client _ secret . See RFC 7636 for details .
 code _ verifier : bytestring or None , default : None , parameter passed
 as part of the code exchange when pkce = True . If
 None , a code _ verifier will automatically be
 generated as part of step1 _ get _ authorize _ url ( ) . See
 RFC 7636 for details .
 Returns :
 An OAuth2Credentials object .
 Raises :
 FlowExchangeError if the authorization code cannot be exchanged for an
 access token"""

implementation:
flow = OAuth2WebServerFlow ( client_id , client_secret , scope , redirect_uri = redirect_uri , user_agent = user_agent , auth_uri = auth_uri , token_uri = token_uri , revoke_uri = revoke_uri , device_uri = device_uri , token_info_uri = token_info_uri , pkce = pkce , code_verifier = code_verifier )
credentials = flow . step2_exchange ( code , http = http )
return credentials