Creating a Financial Dashboard Using Python and Streamlit

Using the Streamlit library to display financial data from Yahoo Finance

Julian Marx
Towards Data Science

--

Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.

Recent anecdotes of day traders tripling their net worth with OTM call options after “in-depth” price chart analysis have led to a somewhat distorted view on investing in general and stocks in particular. It is in times of such optimism (or exuberance) that turning to great investors like Joel Greenblatt might allow for a more grounded understanding of what exactly it is that investors are ultimately betting on when trading options or buying or selling shares.

“Stocks are […] not pieces of paper that bounce around that you put Sharpe ratios and Sortinos on […], they’re ownership shares of businesses that you value and try to buy at a discount.” — Joel Greenblatt [1]

What this suggests is that investors who want to outperform the market for a sustained period of time should not approach this goal by recklessly trading in the options market. Rather, Greenblatt suggests that any approach to active investing should be informed by an analysis of fundamental company data.

At this point it is important to mention that there has long been a more fundamental debate regarding the capacity of markets to adequately price securities (see, for instance, Fama [2] and Shiller [3]). The ultimate outcome of this debate, in turn, has major implications on the merits of engaging in active portfolio management in the first place. This concern, however, should not be topic of this article and I will make the (potentially inaccurate) assumption that there is value in active portfolio management.

With the insight that successful active investing demands a detailed understanding of company financials, the central question that remains is where to get this information from and how to interpret it. While great sources of information like the Bloomberg Terminal exist, most retail investors lack the urge to bankrupt themselves by purchasing an annual subscription to such services. In case of preliminary research, I personally use free offerings like Yahoo Finance, which aggregate financial information, eliminating the need to dig through lengthy annual and quarterly reports.

While I think that Yahoo Finance does a great job of providing an initial understanding of a company’s fundamentals, certain important metrics are not provided and others can be difficult to find.

In an attempt to get a concise, easy to interpret snapshot of publicly traded companies, I therefore used some Python automation to write a financial dashboard application. Here it might be important to note that my programming skills are definitely subpar and I am sure that there is a more elegant way of finding a solution to my problem. The following passages should therefore serve as a testimonial to the potency of Python and Streamlit and by no means as a programming tutorial.

The Financial Dashboard Application

Streamlit is a Python package that makes it very easy to create dashboards and data applications, without the need for any front-end programming expertise. The library can be used to create applications like the one shown below, which allows users to enter a company stock ticker and get financial ratios based on the company’s most recent financial data:

Preview of the final dashboard

Collecting the Data

To collect the data that serve as an input to the application, using the yahoo_fin package is very helpful. The package scrapes information from Yahoo Finance and returns it in the form of pandas DataFrames, which in turn integrate very nicely with Streamlit.

class Company:
def __init__(self, ticker):
price_df = si.get_data(ticker, dt.datetime.now()- dt.timedelta(days=2*365), dt.datetime.date(dt.datetime.now()))
overview_df = si.get_stats(ticker)
overview_df = overview_df.set_index('Attribute')
overview_dict = si.get_quote_table(ticker)
income_statement = si.get_income_statement(ticker)
balance_sheet = si.get_balance_sheet(ticker)
cash_flows = si.get_cash_flow(ticker)

The resulting DataFrames can then be used to extract required information like company market capitalization or income statement measures like EBIT or net income.

self.year_end = overview_df.loc['Fiscal Year Ends'][0]
self.market_cap = get_integer(overview_dict['Market Cap'])
self.market_cap_cs = '{:,d}'.format(int(self.market_cap))
self.prices = price_df['adjclose']

self.sales = income_statement.loc['totalRevenue'][0]
self.gross_profit = income_statement.loc['grossProfit'][0]
self.ebit = income_statement.loc['ebit'][0]
self.interest = - income_statement.loc['interestExpense'][0]
self.net_profit = income_statement.loc['netIncome'][0]

Finally, these data can be used to calculate measures like valuation multiples or profit margins. Further, I calculated liquidity, leverage, and efficiency ratios for my application.

def get_overview(self):
self.price_earnings_ratio = self.market_cap/self.net_profit
self.ev_sales_ratio = self.ev/self.sales
self.overview_dict = {
'Values' : [self.ev_cs, self.market_cap_cs, self.ev_sales_ratio, self.price_earnings_ratio]
}

def get_profit_margins(self):
self.gross_margin = self.gross_profit/self.sales
self.operating_margin = self.ebit/self.sales
self.net_margin = self.net_profit/self.sales
self.profit_margin_dict = {
'Values' : [self.gross_margin, self.operating_margin, self.net_margin]
}

Displaying the Data

As mentioned earlier, Streamlit makes it very easy to display this information in a structured way, with very little additional effort. In my case, I simply added the title of the application and a text field which allows the user to enter a company ticker. Through the click of the “Search” button, the lines of code displayed above are executed and the data are collected.

st.title('Financial Dashboard')
ticker_input = st.text_input('Please enter your company ticker:')
search_button = st.button('Search')

if search_button:
company = Company(ticker_input)
company.get_overview()
company.get_profit_margins()
company.get_liquidity_ratios()
company.get_leverage_ratios()
company.get_efficiency_ratios()

Streamlit provides great functionality that helps display the data through means like line charts, tables, or bar charts.

st.header('Company overview')
overview_index = ['Enterprise value', 'Market cap', 'EV/sales ratio', 'P/E ratio']
overview_df = pd.DataFrame(company.overview_dict, index = overview_index)
st.line_chart(company.prices)
st.table(overview_df)

with st.beta_expander('Profit margins (as of {})'.format(company.year_end)):
profit_margin_index = ['Gross margin', 'Operating margin', 'Net margin']
profit_margin_df = pd.DataFrame(company.profit_margin_dict, index = profit_margin_index)
st.table(profit_margin_df)
st.bar_chart(profit_margin_df)

In my case, the result looks like the following:

Final dashboard with a general company overview on the left and further metrics on the right

Concluding Remarks

In my opinion Streamlit is very easy to work with and well documented, making displaying and interpreting data straightforward. I admit that my application is still rather limited and there is a lot of additional functionality that a more proficient programmer could integrate.

Overall, I believe that increasing the availability of and accessibility to basic metrics like profit margins or leverage ratios can yield a better understanding of company financials. This in turn is likely to lead to more informed investment decisions, which might help investors outperform the market in the long run.

Disclaimer

The code provided above is simply an exercise in applying Python programming to the field of finance. The information included in this article should not be used to make investment decisions. Further, information collected from Yahoo Finance should not be used for any commercial purposes.

[1] https://www.youtube.com/watch?v=V8Zuw8Mnc-I
[2] Fama, E. F. (1970). Efficient Capital Markets: A Review of Theory and Empirical Work. The Journal of Finance, 25(2), 383–417.
[3] Shiller, R.J. (1981). Do Stock Prices Move Too Much to be Justified by Subsequent Changes in Dividends? The American Economic Review, 71(3), 421–436.

--

--