<jupyter_start><jupyter_text>Python package to collect financial metrics and ratios data Dr. <NAME>, Fremont, CA, June 2020We wrote a simple Python class script for interfacing with a [financial data microservice](https://financialmodelingprep.com/).You can pull data about and build a Pandas DataFrame with almost all important financial metrics and ratios by invoking a simple method.We also provide simple charting methods (bar chart and scatter plots) for analyzing the data graphically.Note that you need to obtain your own secret API key (free) from the website and register it after instantiating the class object.<jupyter_code># Main script
from financeAPI import *
# Other libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
from urllib.request import urlopen<jupyter_output><empty_output><jupyter_text>Read the secret API key from a file and register itNote that you need to have a file called `Secret_Key.txt` in the same directory as the code files. Without it, you cannot progress.**Register here: https://financialmodelingprep.com/login**<jupyter_code>with open('Secret_Key.txt') as f:
    key = f.read()
f = FinanceAPI()<jupyter_output><empty_output><jupyter_text>Description of the class<jupyter_code>print(f)<jupyter_output>This is a finance API class.<jupyter_text>Cannot build a data dictionary without registering the secret key<jupyter_code>f.build_dict('AAPL')<jupyter_output>API key not registered yet.<jupyter_text>Register the key<jupyter_code>f.registerKey_(key)<jupyter_output><empty_output><jupyter_text>Build a data dictionary for the ticker symbol 'AAPL' (Apple Inc.)<jupyter_code>apple_dict=f.build_dict('AAPL')<jupyter_output><empty_output><jupyter_text>Browse through the dictionary<jupyter_code>for k,v in apple_dict.items():
    print("{}: {}".format(k,v))<jupyter_output>symbol: AAPL
price: 331.5
beta: 1.228499
volAvg: 46216714
mktCap: 1.4368304E12
lastDiv: 3.08
range: 185.77-331.75
changes: 9.18
changesPercentage: (+2.85%)
companyName: Apple Inc.
exchange: Nasdaq Global Select
exchangeShortName: NASDAQ
industry: Computer Hardware
website: http://www.apple.com
description: Apple Inc designs, manufactures and markets mobile communication and media devices and personal computers, and sells a variety of related software, services, accessories, networking solutions and third-party digital content and applications.
ceo: <NAME>
sector: Technology
image: https://financialmodelingprep.com/images-New-jpg/AAPL.jpg
date: 2019-09-28
Revenue per Share: 56.34113309400035
Net Income per Share: 11.965783092246278
Operating Cash Flow per Share: 15.026741974700693
Free Cash Flow per Share: 12.75403143551717
Cash per Share: 10.577253318330628
Book Value per Share: 19.59533408953202
Tangible Book Value per Share: 73.30622971722241
Shareholders Equity per Share: 1[...]<jupyter_text>Build a DataFrame by passing a list of ticker symbols<jupyter_code>df=f.build_dataframe(['TWTR','FB','MSFT','NVDA','AAPL','CRM'])<jupyter_output>C:\Users\tirth\Documents\Personal\Data Science related\Python and other Notebooks\Finance\financeAPI.py:200: FutureWarning: The pandas.np module is deprecated and will be removed from pandas in a future version. Import numpy directly instead
  self.df.fillna(value=pd.np.nan, inplace=True)<jupyter_text>What kind of profile data are available?<jupyter_code>f.available_data('profile')<jupyter_output>Following data are available for profile
============================================================
price, beta, volAvg, mktCap, lastDiv, range, changes, changesPercentage, companyName, exchange, exchangeShortName, industry, website, description, ceo, sector, image.<jupyter_text>What kind of metrics data are available?<jupyter_code>f.available_data('metrics')<jupyter_output>Following data are available for metrics
============================================================
date, Revenue per Share, Net Income per Share, Operating Cash Flow per Share, Free Cash Flow per Share, Cash per Share, Book Value per Share, Tangible Book Value per Share, Shareholders Equity per Share, Interest Debt per Share, Market Cap, Enterprise Value, PE ratio, Price to Sales Ratio, POCF ratio, PFCF ratio, PB ratio, PTB ratio, EV to Sales, Enterprise Value over EBITDA, EV to Operating cash flow, EV to Free cash flow, Earnings Yield, Free Cash Flow Yield, Debt to Equity, Debt to Assets, Net Debt to EBITDA, Current ratio, Interest Coverage, Income Quality, Dividend Yield, Payout Ratio, SG&A to Revenue, R&D to Revenue, Intangibles to Total Assets, Capex to Operating Cash Flow, Capex to Revenue, Capex to Depreciation, Stock-based compensation to Revenue, Graham Number, ROIC, Return on Tangible Assets, Graham Net-Net, Working Capital, Tangible Asset Value, Net Current Asset Value, In[...]<jupyter_text>What kind of financial ratios data are available?<jupyter_code>f.available_data('ratios')<jupyter_output>Following data are available for ratios
============================================================
currentRatio, quickRatio, cashRatio, daysOfSalesOutstanding, daysOfInventoryOutstanding, operatingCycle, daysOfPayablesOutstanding, cashConversionCycle, grossProfitMargin, operatingProfitMargin, pretaxProfitMargin, netProfitMargin, effectiveTaxRate, returnOnAssets, returnOnEquity, returnOnCapitalEmployed, netIncomePerEBT, ebtPerEbit, ebitPerRevenue, debtRatio, debtEquityRatio, longTermDebtToCapitalization, totalDebtToCapitalization, cashFlowToDebtRatio, companyEquityMultiplier, receivablesTurnover, payablesTurnover, fixedAssetTurnover, assetTurnover, payoutRatio, operatingCashFlowSalesRatio, freeCashFlowOperatingCashFlowRatio, cashFlowCoverageRatios, shortTermCoverageRatios, capitalExpenditureCoverageRatio, priceToFreeCashFlowsRatio, enterpriseValueMultiple.<jupyter_text>Simple bar charts<jupyter_code>f.bar_chart('Book Value per Share',color='orange',edgecolor='k')
f.bar_chart('debtEquityRatio')<jupyter_output><empty_output><jupyter_text>Scatter plots<jupyter_code>f.scatter('quickRatio','Book Value per Share',color='blue')
f.scatter(varX='debtEquityRatio',
          varY='Enterprise Value over EBITDA',
         sizeZ='price',
         color='red',alpha=0.6)<jupyter_output><empty_output><jupyter_text>You can work with the underlying DataFrame to create your own filterOften, investors may want to create their own filters and investment logic with the available data. For example, we may want to consider only those companies with market capitalization > 200 billion USD and then look at the metric of _Enterprise value over EBIDTA_.We can access the underlying DataFrame, create a custom DataFrame, and then assign this custom DataFrame to a new `financeAPI()` object to take advantage of the ready-made charting methods. In this way, we won't need to request data from the API again. **We should avoid the data read as much as possible because of the limitation of the number of data read with the free API key.**Example code is shown below.<jupyter_code># Only companies with market cap > 200 billion USD
df = f.df
df_large_cap = df[df['Market Cap']>200e9]
df_large_cap[['companyName','Market Cap']]
# A fresh class declration
f2 = FinanceAPI()
# Assigning the custom DataFrame to the `df` attribute of this new class object
# Note we did not need to request data from the API again.
f2.df = df_large_cap
f2.bar_chart('Enterprise Value over EBITDA',color='red',edgecolor='k')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10061877858488028, 'fraction_numerical': 0.026096314231907454, 'mean_word_length': 7.037837837837838, 'pattern_counts': {'":': 0, '<': 52, '<?xml version=': 0, '>': 55, 'https://': 3, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '537143', 'license': 'MIT', 'n_tokens_mistral': 2337, 'n_tokens_neox': 2129, 'n_words': 766, 'path': 'financeAPI/Test_FinanceAPI.ipynb', 'repo_name': 'StengerP/StockScreenerGui', 'size': '7455'}