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)
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)
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 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 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 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)
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)
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 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 response = urlopen(url) data = response.read().decode("utf-8") return safe_read_json(data)
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 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 historical_stock_data(ticker, period = None, dailytype = None, last = None, start = None, end = None): """Historical stock data API for . From https://fmpcloud.io/documentation#historicalStockData Input: ticker - fx for which you want the historical data 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 price or daily change and volume. Do not use with period. last - fx 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 -- fx stock 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 + "×eries=" + 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
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 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 response = urlopen(url) data = response.read().decode("utf-8") return safe_read_json(data)
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)