Python for finance: automated analysis of the financial markets | by Riccardo Poli | Towards Data Science

The Python script presented in this article has been used to analyse the impact of COVID-19 on the various business sectors of the S&P 500 index, but can also be easily adapted to any other analysis of financial markets.
The code has been developed in Python programming language, and can be found in my GitHub repository (link below) as a Jupyter notebook.
github.com
The script makes use of standard Python packages (i.e. pandas, bokeh, math) as well as the yfinance API (Application Programming Interface), that is used to download the S&P 500 stock prices. The API is free to use and it is public, meaning that the user does not need an individual API key.
# Import librariesimport yfinance as yfimport pandas as pdfrom bokeh.plotting import figureimport bokeh.models as bmofrom bokeh.palettes import Paired11from bokeh.io import showfrom bokeh.models import ColumnDataSource, HoverToolimport math
In the first section of the script, the user needs to define the variable called “depth” to defines the level of detail of the analysis. This can either be set to “sector” or “sub_sector”. Choosing “sector” will produce a plot such as the one in Figure 1, whereas “sub_sector” will produce a plots similar to the ones in Figure 2 and Figure 3. In this last case, the user has to also specify the “filter”, that is the sector of interest. The available values of filter are: Communication Services, Consumer Discretionary, Consumer Staples, Energy, Financials, Health Care, Industrials, Information Technology, Materials, Real Estate and Utilities.
# Example of input definitiondepth = 'sub_sector'filter = 'Information Technology'
All the other inputs such as the list of S&P 500 stocks, and the date to compare current market performance against (beginning of 2020) are automatically set.
index_name = 'SP_500'companies = pd.read_html('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies', flavor='bs4')[0]
At this point, the data are downloaded and all the calculations are performed. As anticipated, the yfinance API is used to gather the financial data.
df_all = pd.DataFrame()color_df = pd.DataFrame({0})for stock in companies_codes:  stock_data = yf.Ticker(stock.replace(".",""))  stock_name = companies[company_label].loc[companies[code_label] == stock].values[0]  df_all[stock_name] = stock_data.history(start="2020-01-01")['Close']
The last section is where all plots are created.
if depth == 'sector':df_sector = df_summary.groupby(['Sector']).mean()    df_sector = df_sector.sort_values(by=['YTD_performance'], ascending=False)source2 = ColumnDataSource(data=dict(cum_sum_ytd=df_sector.YTD_performance.to_list(), sector=df_sector.index.to_list()))p = figure(plot_height=700, plot_width=1200, x_range=df_sector.index.to_list(), toolbar_location='right', y_range=[-50, 50],               title='Year-to-date performance of individual sectors (S&P 500 stocks)', tools="save")color_map = bmo.CategoricalColorMapper(factors=df_summary['Sector'].unique(), palette=Paired11)p.vbar(x='sector', top='cum_sum_ytd', width=0.9, source=source2, fill_color={'field': 'sector', 'transform': color_map},            legend='sector', line_width=0)p.xaxis.major_label_orientation = math.pi/3    p.yaxis.axis_label = 'Year to date average performance (%)'p.title.text_font_size = '12pt'    p.yaxis.axis_label_text_font_size = '12pt'show(p)
You can find further comments to the code and additional details in the notebook on the GitHub page.
In this section, the outputs of the code presented above are summarised in Figures 1, 2 and 3.
COVID-19 has had an unprecedented impact on our lives, our habits, on the real economy and on the financial markets. The financial shock caused by the pandemic has not been uniform, and the various business sectors have responded differently to the crisis.
It can be seen from Figure 1 that all sectors, as an average, have been negatively impacted by the pandemic, with the highest losses in the energy sector. In fact, due to a large portion of the world population being in lockdown, the demand for oil and gas has significantly dropped. The industrial sector has experienced significant losses as well, especially in the “aerospace and defence” and “airlines” sub-sectors. The main reason is the reduced demand for these services, due to the restrictions in place and the fear of COVID-19 spread.
Health Care
Health care is the business sector that has suffered the least, with some companies in the biotechnology sub-sector gaining an average+16% in stock price, Figure 2. This is because many companies are investing resources on the COVID-19 vaccine. The company to win the race could have stellar profits.
Communication Services
Smart working and the desire of people to speak and to see their loved ones have increased demand for video conferencing apps and software in these unprecedented times. As people are quarantined in many countries, they tend to spend more time on streaming services. As a consequence, home entertainment and telecom services have performed well during the pandemic (+12% and +23%, respectively), Figure 3.
If you want to read more on the topic, please refer to this article I have written a few weeks ago (May 2020) to explain the effects of COVID-19 on each business sector and sub-sector.
Stay safe, and happy trading!
Riccardo Polihttps://www.linkedin.com/in/riccardopoli/
Disclaimer: investing in the stock market involves risk and can lead to monetary loss. The content of this article is not to be taken as financial advice.