Beispiel #1
0
def balance_sheet(ticker, period='annual', ftype='full'):
    """Balance sheet API from https://fmpcloud.io/documentation#balanceSheet
    
    Input:
        ticker : ticker for which we need the balance sheet values
        period : 'annual', 'quarter'. Periodicity of requested balance sheet. Defaults to annual
        ftype : 'full', 'growth'. Defines input sheet type. Defaults to full. 
    Returns:
        Balance sheet info for selected ticker
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    typeurl = ''
    try:
        if ftype == 'full':
            typeurl = 'balance-sheet-statement/'
        elif ftype == 'growth':
            typeurl = 'balance-sheet-statement-growth/'


#        elif ftype == 'short':
#            typeurl = 'balance-sheet-statement-shorten/'
#        elif ftype == 'growth-short':
#            typeurl = 'balance-sheet-statement-growth-shorten/'
    except KeyError:
        print('Balance sheet type not correct')

    url = urlroot + typeurl + ticker.upper(
    ) + "?" + "&period=" + period + "&apikey=" + apikey
    data = safe_read_json(url)
    return data
def batch_request_eod_prices(tickers = None, date = None):
    """Daily candle stick data API for all available or specified tickers. From https://fmpcloud.io/documentation#batchEndOfTheDay
    
    Input:
        tickers - a list of strings only. Will not work as expected if 'AAPL' is sent. Please send ['AAPL'] for single stock and ['AAPL','FB','MSFT'] for a batch. Default value returns data for all available stocks. If batch data for specific is requested, a date must also be provided.
    Returns:
        Dataframe -- batch request for daily candle information for all stocks.
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    if (tickers is None) and (date is None):
        url = urlroot + "batch-request-end-of-day-prices?apikey=" + apikey
    elif (tickers is not None) and (date is None):
        raise Exception('For batch query of specific stocks, please specify a date in the format yyyy-mm-dd')
    elif (tickers is None) and (date is not None):
        url = urlroot + "batch-request-end-of-day-prices?date=" + date + "&apikey=" + apikey
    elif (tickers is not None) and (date is not None):
        tick = ''
        for ticker in tickers:
            tick = tick + ticker.upper() + ','
        url = urlroot + "batch-request-end-of-day-prices/" + tick + "?date=" + date + "&apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    if pd.read_json(data).empty is True:
        raise ValueError("Data not found for " + str(tickers) + " on specified date " + date)
    return safe_read_json(data)
Beispiel #3
0
def dcf(ticker, history='today'):
    """Discounted Cash Flow Valuation API from https://fmpcloud.io/documentation#dcf
    
    Input:
        ticker : ticker for which we need the dcf 
        history: 'today','daily', 'quarter', 'annual'. Periodicity of requested DCF valuations. Defaults to single value of today
    Returns:
        Discounted Cash Flow Valuation info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    try:
        if history == 'today':
            typeurl = 'discounted-cash-flow/'
            url = urlroot + typeurl + ticker.upper() + "?" + "apikey=" + apikey
        elif history == 'daily':
            typeurl = 'historical-daily-discounted-cash-flow/'
            url = urlroot + typeurl + ticker.upper() + "?" + "apikey=" + apikey
        elif history == 'annual':
            typeurl = 'historical-discounted-cash-flow-statement/'
            url = urlroot + typeurl + ticker.upper() + "?" + "apikey=" + apikey
        elif history == 'quarter':
            typeurl = 'historical-discounted-cash-flow-statement/'
            url = urlroot + typeurl + ticker.upper(
            ) + "?" + "period=" + history + "&apikey=" + apikey
    except KeyError:
        raise KeyError('Discounted Cash Flow history requested not correct. ' +
                       history + ' is not an accepted key')
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #4
0
def cash_flow_statement(ticker, period='annual', ftype='full'):
    """Cash Flow Statement API from https://fmpcloud.io/documentation#cashFlowStatement
    
    Input:
        ticker : ticker for which we need the cash flow statement
        period : 'annual', 'quarter'. Periodicity of requested balance sheet. Defaults to annual
        ftype : 'full', 'growth'. Defines input sheet type. Defaults to full. 
    Returns:
        Income statement info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    typeurl = ''
    try:
        if ftype == 'full':
            typeurl = 'cash-flow-statement/'
        elif ftype == 'growth':
            typeurl = 'cash-flow-statement-growth/'


#        elif bstype == 'short':
#            typeurl = 'income-statement-shorten/'
#        elif bstype == 'growth-short':
#            typeurl = 'income-statement-growth-shorten/'
    except KeyError:
        raise KeyError('Cash Flow Statement type not correct')

    url = urlroot + typeurl + ticker.upper(
    ) + "?" + "period=" + period + "&apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def company_profile(ticker):
    """Company profile API from https://financialmodelingprep.com/developer/docs/#Symbols-List
    
    Returns:
        DataFrame -- Returns company profile
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + "company/profile/" + ticker.upper() + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def forex_historical_data(ticker,
                          period=None,
                          dailytype=None,
                          last=None,
                          start=None,
                          end=None):
    """Forex Historical data API for partial matching of stocks over specified exchange. From https://fmpcloud.io/documentation#historicalStockData
    
    Input:
        ticker - company for which you want the historical stock data. for complete list of fx, use forex.forex_realtime_quote(fxtype = 'list')
        period - tick periodicity - can be '1min', '5min', '15min', '30min', '1hour'. Defaults to '15min'. Do not use with daily type
        dailytype - can be 'line', 'change'. line chart info for daily stock or daily change and volume. Do not use with period.
        last - stock data for last x days. Only works with dailytype. Does not work with period 
        start - start date in the format yyyy-mm-dd. eg: '2018-01-01'
        end - end date in the format yyyy-mm-dd. eg: '2019-01-01'
    Returns:
        Dataframe -- historical fx data
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    if ((dailytype is not None) or
        (last is not None)) and (period is not None):
        raise Exception(
            " 'period' and 'dailytype' cannot be set on the same call. Please choose either, not both. 'last' can only be set with 'dailytype'"
        )
    if dailytype is not None:
        urlhist = urlroot + 'historical-price-full/' + ticker.upper() + '?'
    elif period is not None:
        urlhist = urlroot + 'historical-chart/' + period + '/' + ticker.upper(
        ) + '?'
    else:
        raise Exception(
            "'period' or 'dailytype' not set. Please set atleast one")
    if dailytype == 'line':
        urlhist = urlhist + "serietype=line"
    if last is not None:
        urlhist = urlhist + "&timeseries=" + str(last)
    if (last is None) and (start is not None):
        urlhist = urlhist + "&from=" + start
    if (last is None) and (end is not None):
        urlhist = urlhist + "&to" + end
    url = urlhist + "&apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    data = safe_read_json(data)
    if dailytype is not None:
        datatick = data['symbol']
        data_mod = pd.DataFrame.from_records(data['historical'])
        data_mod['symbol'] = datatick
        data = data_mod
    data['date'] = pd.to_datetime(data['date'], format='%Y-%m-%d %H:%M:%S')
    data = data.set_index('date')
    return data
Beispiel #7
0
def form_list():
    """Returns all names of companies and their CIK numbers. From https://fmpcloud.io/documentation#thirteenFormList
    
    Returns:
        list of available companies and their CIK numbers 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + "cik_list?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #8
0
def rss_feed():
    """RSS Feed API from https://fmpcloud.io/documentation#rssFeed

    Returns:
        Returns any filings of the day over the last week
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    localurl = "rss_feed?apikey="
    url = urlroot + localurl + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def stock_market_performances(performancetype):
    """Provides an overview of the market performance across specified performance type. https://fmpcloud.io/documentation#stockMarketPerformances
    
    Input:
        performancetype : type of performance for which data is sought. performance type can be "active", "gainers", "losers", "sector", "sector historical", "market hours". 
    Returns:
        Dataframe -- market performance data by specified performance type
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + map_performance(performancetype.lower()) + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def symbol_list():
    """Stocks list API from https://financialmodelingprep.com/developer/docs/#Company-Profile
    
    Input:
        ticker : ticker for which we need the company profile
    Returns:
        Dataframe -- Returns company profile of the requested company (ticker)
    """
    urlroot = settings.get_urlrootfmp()
    apikey = settings.get_apikey()
    url = urlroot + "company/stock/list?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return pd.DataFrame(json.loads(data)['symbolsList'])
Beispiel #11
0
def cusip_mapper(cusip):
    """Returns the company name for specified CUSIP number. From https://fmpcloud.io/documentation#cusipMapper
    
    Input:
        cusip : CUSIP number for which you'd like the company name
    Returns:
        company name for specified CUSIP number
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + "cusip/" + cusip + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #12
0
def form_ciktoname(cik):
    """Returns company name for specified CIK number. From https://fmpcloud.io/documentation#thirteenFormCik
    
    Input:
        cik : CIK number for which you'd like the company name
    Returns:
        Company name for specified company
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + "cik/" + cik + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #13
0
def form_nametocik(company):
    """Returns CIK number for specified company. Allows partial matching of names. From https://fmpcloud.io/documentation#thirteenFormName
    
    Input:
        company : Name of the company for which you'd like the CIK 
    Returns:
         CIK number for specified company
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + "cik-search/" + company + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def real_time_quote(ticker):
    """Real time quote API from https://fmpcloud.io/documentation#realtimeQuote
    
    Input:
        ticker : stock ticker of the company. eg: 'AAPL'
    Returns:
        Dataframe -- real-time quotes of the requested tickers
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    urlrtq = 'quote/'
    url = urlroot + urlrtq + ticker.upper() + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #15
0
def form(cik, year):
    """Returns form 13F for specified CIK number. From https://fmpcloud.io/documentation#thirteenForm
    
    Input:
        cik : CIK number for which you'd like the 13F form
        year = year for which you'd like the 13F form.
    Returns:
        Form 13F for specified company
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    url = urlroot + "form-thirteen/" + cik + "?year=" + year + "&apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def financial_statements_growth(ticker, period='annual'):
    """Financial Statements Growth API from https://fmpcloud.io/documentation#financialStatementGrowth
    
    Input:
        ticker : ticker for which we need the financial growth
        period : 'annual', 'quarter'. Periodicity of requested balance sheet. Defaults to annual
    Returns:
        Financial Statements Growth info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    typeurl = "financial-growth/"

    url = urlroot + typeurl + ticker.upper(
    ) + "?" + "period=" + period + "&apikey=" + apikey
    return safe_read_json(url)
def enterprise_value(ticker, period='annual'):
    """Enterprise value API from https://fmpcloud.io/documentation#enterpriseValue
    
    Input:
        ticker : ticker for which we need the enterprise value
        period : 'annual', 'quarter'. Periodicity of requested balance sheet. Defaults to annual
    Returns:
        Enterprise value info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    typeurl = "enterprise-values/"

    url = urlroot + typeurl + ticker.upper(
    ) + "?" + "period=" + period + "&apikey=" + apikey
    return safe_read_json(url)
def ticker_search(match = None, limit = 100, exchange = 'NASDAQ'):
    """Ticker search API for partial matching of stocks over specified exchange. From https://fmpcloud.io/documentation#tickerSearch
    
    Input:
        match - string to match tickers. eg: 'AA' will return AAPL, AAON etc.
        limit - number of search results to return. Defaults to 100
        exchange - the exchange to perform the search on. Possible values 'NASDAQ', 'AEX', 'NYSE'. Will publish a complete list later
    Returns:
        Dataframe -- matching tickers, upto 'limit' number of values, found on the specified exchange
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    if match is not None:
        url = urlroot + 'search?query=' + match.upper() + '&limit=' + str(limit) + "&exchange=" + exchange.lower() + '&apikey=' + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #19
0
def key_metrics(ticker, period='annual'):
    """Key Metrics API from https://fmpcloud.io/documentation#keyMetrics
    
    Input:
        ticker : ticker for which we need the key metrics
        period : 'annual', 'quarter'. Periodicity of requested balance sheet. Defaults to annual
    Returns:
        Key metrics info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    typeurl = "key-metrics/"

    url = urlroot + typeurl + ticker.upper(
    ) + "?" + "period=" + period + "&apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def available_markets_and_tickers(markettype = None, marketprices = False):
    """List of available tickers per specified market, and their prices. From https://fmpcloud.io/documentation#availableMarketandTickers
    
    Input:
        marketType : type of market for which we need the available tickers/prices. marketType can be "ETF", "Commodities", "Euronext", "NYSE", "AMEX", "TSX", "Mutual Funds", "Index", "Nasdaq". 
        marketprices : Boolean to indicate if you want the prices of the tickers for the specified markettype.
    Returns:
        Dataframe -- Returns list of available tickers per specified market, and their prices if marketPrices = True
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    
    if markettype is None:
        raise Exception("Please provide marketType. For a list of available options, see function documentation or visit https://fmpcloud.io/documentation#availableMarketandTickers")
    urlmarket = map_markets(markettype.lower(), marketprices)
    url = urlroot + urlmarket + "?apikey=" + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def financial_ratios(ticker, period='annual', ttm=False):
    """Financial Ratios API from https://fmpcloud.io/documentation#financialRatios
    
    Input:
        ticker : ticker for which we need the financial ratios
        period : 'annual', 'quarter'. Periodicity of requested balance sheet. Defaults to annual
        ttm: trailing twelve months financial ratios. Default is False
    Returns:
        Financial ratios info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    if ttm:
        typeurl = "ratios-ttm/"
    else:
        typeurl = "ratios/"

    url = urlroot + typeurl + ticker.upper(
    ) + "?" + "period=" + period + "&apikey=" + apikey
    return safe_read_json(url)
def rating(ticker, history='today'):
    """Rating API from https://fmpcloud.io/documentation#rating
    
    Input:
        ticker : ticker for which we need the rating info 
        history: 'today','daily'. Periodicity of requested ratings. Defaults to single value of today
    Returns:
        rating info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    try:
        if history == 'today':
            typeurl = 'rating/'
        elif history == 'daily':
            typeurl = 'historical-rating/'
    except KeyError:
        print('Rating history requested not correct')
    url = urlroot + typeurl + ticker.upper() + "?" + "apikey=" + apikey
    return safe_read_json(url)
def market_capitalization(ticker, history='today'):
    """Market Capitalization API from https://fmpcloud.io/documentation#marketCapitalization
    
    Input:
        ticker : ticker for which we need the Market Cap 
        history: 'today','daily'. Periodicity of requested Market Caps. Defaults to single value of today
    Returns:
        Market Cap info for selected ticker 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    try:
        if history == 'today':
            typeurl = 'market-capitalization/'
        elif history == 'daily':
            typeurl = 'historical-market-capitalization/'
    except KeyError:
        print('Market Cap history requested not correct')
    url = urlroot + typeurl + ticker.upper() + "?" + "apikey=" + apikey
    return safe_read_json(url)
Beispiel #24
0
def crypto_realtime_quote(cryptotype):
    """Crypto Real time quotes including list of available cryptos, and their prices. From https://fmpcloud.io/documentation#crypto
    
    Input:
        cryptotype : can be 'list', 'price'
    Returns:
        list of available crypto trading pairs, and their prices 
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    if cryptotype == 'list':
        urlc = "symbol/available-cryptocurrencies?apikey="
    elif cryptotype == 'price':
        urlc = "quotes/crypto?apikey="
    else:
        raise KeyError("Invalid cryptotype " + cryptotype +
                       " Allowed values are 'list' and 'price'.")
    url = urlroot + urlc + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
def forex_realtime_quote(fxtype):
    """Forex Real time quotes including list of available fx, their prices and a combination function to return both. From https://fmpcloud.io/documentation#forex
    
    Input:
        fxtype : can be 'list', 'price' or 'both'
    Returns:
        list of available fx, their prices or both
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    if fxtype == 'both':
        urlfx = "fx?apikey="
    elif fxtype == 'list':
        urlfx = "symbol/available-forex-currency-pairs?apikey="
    elif fxtype == 'price':
        urlfx = "quotes/forex?apikey="
    else:
        raise KeyError("Invalid fxtype " + fxtype)
    url = urlroot + urlfx + apikey
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)
Beispiel #26
0
def stock_screener(mcgt=None,
                   mclt=None,
                   bgt=None,
                   blt=None,
                   divgt=None,
                   divlt=None,
                   volgt=None,
                   vollt=None,
                   sector=None,
                   limit=100):
    """Stock Screener API from https://fmpcloud.io/documentation#rating
    
    Input:
        mcgt: stocks with market cap greater than this value
        mclt: stocks with market cap less than this value
        bgt: stocks with beta greater than this value
        blt: stocks with beta less than this value
        divgt: stock with dividends per share greater than this value
        divlt: stocks with dividends per share less than this value
        volgt: stocks with average trading volume greater than this value
        vollt: stocks with average trading volume less than this value
        sector: stocks within this 
        limit: number of return results
    Returns:
        List of stocks meeting the screening criteria
    """
    urlroot = settings.get_urlroot()
    apikey = settings.get_apikey()
    urlss = 'stock-screener?'
    urlbase = urlroot + urlss
    url = urlroot + urlss
    if sector is not None:
        urlsector = 'sector=' + sector  #API call adds the %20 automatically
        url = url + urlsector
    if mcgt is not None:
        urlmcgt = "marketCapMoreThan=" + str(mcgt)
        if url == urlbase:
            url = url + urlmcgt
        else:
            url = url + '&' + urlmcgt
    if mclt is not None:
        urlmclt = "marketCapLowerThan=" + str(mclt)
        if url == urlbase:
            url = url + urlmclt
        else:
            url = url + '&' + urlmclt
    if bgt is not None:
        urlbgt = "betaMoreThan=" + str(bgt)
        if url == urlbase:
            url = url + urlbgt
        else:
            url = url + '&' + urlbgt
    if blt is not None:
        urlblt = "betaLowerThan=" + str(blt)
        if url == urlbase:
            url = url + urlblt
        else:
            url = url + '&' + urlblt
    if divgt is not None:
        urldivgt = "dividendMoreThan=" + str(divgt)
        if url == urlbase:
            url = url + urldivgt
        else:
            url = url + '&' + urldivgt
    if divlt is not None:
        urldivlt = "dividendLowerThan=" + str(divlt)
        if url == urlbase:
            url = url + urldivlt
        else:
            url = url + '&' + urldivlt
    if volgt is not None:
        urlvolgt = "volumeMoreThan=" + str(volgt)
        if url == urlbase:
            url = url + urlvolgt
        else:
            url = url + '&' + urlvolgt
    if vollt is not None:
        urlvollt = "volumeLowerThan=" + str(vollt)
        if url == urlbase:
            url = url + urlvollt
        else:
            url = url + '&' + urlvollt
    try:
        if url != urlbase:
            url = url + '&limit=' + str(limit) + '&apikey=' + apikey
    except ValueError('Please check screening values provided'):
        print('Exiting')
    url = "20%".join(url.split(" "))
    response = urlopen(url)
    data = response.read().decode("utf-8")
    return safe_read_json(data)