☰
Current Page
Main Menu
Home
Home
Editing Fundamental Analysis of Stocks using Python
Edit
Preview
H1
H2
H3
default
Set your preferred keybinding
default
vim
emacs
markdown
Set this page's format to
AsciiDoc
Creole
Markdown
MediaWiki
Org-mode
Plain Text
RDoc
Textile
Rendering unavailable for
BibTeX
Pod
reStructuredText
Help 1
Help 1
Help 1
Help 2
Help 3
Help 4
Help 5
Help 6
Help 7
Help 8
Autosaved text is available. Click the button to restore it.
Restore Text
https://medium.com/geekculture/fundamental-analysis-of-stocks-using-python-d5ad050e6372 # Fundamental Analysis of Stocks using Python | by Lakshmi Ajay | Geek Culture | Medium  [Lakshmi Ajay](https://medium.com/@lakshmi1212)  [Geek Culture](https://medium.com/geekculture) **Fundamental Analysis using Python** (Image by Author) Technical analysis and fundamental analysis are the two main techniques to analyse any financial market. Technical analysis looks at the trends and patterns in the past data whereas the fundamental analysis looks at the economic and financial factors of a company. In this article we shall be performing the fundamental analysis of some of the stocks programmatically. To check out on the technical analysis, refer to this blog: [Beginners Guide to Technical Analysis in Python for Algorithmic Trading](https://medium.com/geekculture/beginners-guide-to-technical-analysis-in-python-for-algorithmic-trading-19164fb6149) Before jumping into the Python code let us first touch upon the basics of fundamental analysis and web scraping. WHAT IS FUNDAMENTAL ANALYSIS? ----------------------------- Fundamental analysis guides us in reaching a decision point on whether a particular company’s stock is worth buying or not and if its stock price has the right valuation. To perform this analysis it uses the company level factors such as the company’s market capitalization, balance sheet, profit/loss statement, shareholder pattern, cash flow etc Most of the information required for the fundamental analysis is directly available on various websites. In this article, we will be picking one such webpage from where this information shall be scraped and used to perform the fundamental analysis. WEB SCRAPING ------------ Copying the data manually from the website is a cumbersome task. Web scraping is a technique that automates this process by extracting data from a website or an online source. Once the required data is pulled from the website it can then be used to perform any kind of data analysis or data manipulation activity. In this article we will be using ‘Beautiful Soup’ which is a Python package for pulling data from HTML and XML files. It creates a parse tree of the complex HTML document which is then used to read the data. Refer to [this page](https://www.crummy.com/software/BeautifulSoup/bs4/doc/) to get an overview of Beautiful Soup. **Steps involved in web scraping** ---------------------------------- **STEP 1:** Identify the url to pull the data **STEP 2:** Inspect the page to understand its HTML structure **STEP 3:** Write the code to pull the required data from the HTML Scraping data from other websites --------------------------------- A note of caution on using other websites for web scraping. Please ensure that only publicly available data is scraped. In order to control the traffic, some websites define the robots.txt file. This gives an indication on the urls that should not be used for web scraping from that particular website. For more details on robots.txt, refer [here](https://developers.google.com/search/docs/advanced/robots/intro). LET’S SCRAPE IT!! ----------------- With most of the data required for fundamental analysis directly available on the web, it is easer to scrape this information and use it for further analysis. In this article we will be considering stocks from the NSE and using the webpage from [screener.in](https://www.screener.in/) to extract the fundamental details of a particular stock. Same logic can be applied for any of the other webpages as well. The code might require minor changes to align with the html structure of that webpage. The intention of this article is to provide the starter code for someone to quickly get onboard with their own analysis strategy. Hence the scope is limited to fetching some of the basic information and on applying a simple BUY/WAIT strategy. FETCHING THE FUNDAMENTAL DATA ----------------------------- For this analysis we will be considering the following IT stocks from the National Stock Exchange (NSE): INFY, HCLTECH, LTI, TCS, LTTS, WIPRO Infosys — Fetch the market cap using web scraping ------------------------------------------------- As an example let us try to extract the market cap for the Infosys stock from the screener webpage using the 3 steps outlined earlier. **STEP 1: Identify the url to pull the data** URL: [https://www.screener.in/company/INFY](https://www.screener.in/company/INFY/consolidated/)  **STEP 2: Inspect the page to understand its HTML structure** Using the browser inspect the page (right click on the page and choose inspect option). The HTML structure of the page can be studied here. For this example, the HTML page looks like below.  As seen in the HTML structure, the market cap is present within the div class “company-ratios”. Inside this class, it is inside an ul-element (Unordered List Element) with id “top-ratios”. Inside this the market cap is available as a simple span element. **STEP 3: Write the code to pull the required data from the HTML** Using the beautiful soup package, the contents of the given url can be read into a tree object. It can then be traversed till we reach the required data. Using the below code, the market cap of the Infy stock can be extracted from screener’s webpage. ```python from bs4 import BeautifulSoup from urllib.request import urlopen, Request SCRIP = 'INFY' link = f'https://www.screener.in/company/{SCRIP}' hdr = {'User-Agent':'Mozilla/5.0'} req = Request(link,headers=hdr) try: page=urlopen(req) soup = BeautifulSoup(page) div_html = soup.find('div',{'class': 'company-ratios'}) ul_html = div_html.find('ul',{'id': 'top-ratios'}) market_cap = 0.0 for li in ul_html.find_all("li"): name_span = li.find('span',{'class':'name'}) if 'Market Cap' in name_span.text: num_span = li.find('span',{'class':'number'}) num_span = num_span.text.replace(',', '') market_cap = float(num_span) if (num_span != '') else 0.0 break print(f'MARKET CAPITILIZATION - {SCRIP}: {market_cap} Cr') except: print(f'EXCEPTION THROWN: UNABLE TO FETCH DATA FOR {SCRIP}') ``` **Output:**  Fetching other fundamental details of stocks -------------------------------------------- The other parameters of the stock can also be fetched with a similar approach. This can be repeated for any number of stocks. Here we have fetched the data for 6 different IT stocks. Adding the complete code here will make the article too verbose. Please refer to the repository mentioned at the end of the article to get the access to the complete code. Below table is a summary of the fundamental data extracted for the 6 IT stocks.  **Summary of extracted stock data** Here is a quick guide on the extracted data: * Market\_Cap — the total market value of the company’s outstanding shares * Price — the current market price of the share * High — 52-week high of the share * Low — 52-week low of the share * PE — Price to Earnings ratio * ROE — Return on Equity * ROCE — Return on Capital Employed * Dividend — Dividend yield of the company ANALYSING THE STOCKS -------------------- Once the data is fetched, it is time to explore the data. As an example, the market capitalization of the different IT stocks are compared.  The market cap of Infy is almost half of TCS. L&T Technology Services (LTTS) has the lowest market cap amongst the 6 stocks under consideration. COMPARING STOCKS OF THE SAME SECTOR ----------------------------------- Fundamental analysis is normally used to compare the stocks of the same sector. The PE ratio, ROE and ROCE are some of the common parameters used for comparison.  **Comparison of PE-ROE-ROCE parameters** (Image by Author) **PE — Price-to-Earnings Ratio:** It measures the current share price relative to its earnings per share **ROE — Return on Equity:** It is the ratio of net income to the shareholder equity. **ROCE — Return on Capital Employment:** ROCE is the ratio of the operating profits of a company to its total capital employed. **PE + ROE + ROCE:** * PE ratio is normally not used in isolation. It is either compared with other companies from the same industry (Eg: PE of INFY is compared with the PE of HCL, LTI, TCS etc) or compared with the industry PE (PE of Infy is compared with PE of IT sector) * Higher PE indicates that the stock is priced highly. Lower PE indicates a good investment opportunity (provided the other fundamentals of the company is good) * High ROE indicates that the company is good in converting its earnings into profits. * A higher ROCE indicates that the company is generating higher returns for the debt holders than for the equity holders. The higher the value of the ROCE ratio, the better are the chances of profits. * ROE considers the returns from equity shareholder’s point of view only whereas ROCE considers the debt and other liabilities as well. This provides a better indication of financial performance for companies with significant debt. * If the ROCE value is higher than the ROE value, it implies that the company is efficiently using its debts to reduce the cost of capital. * [_Mr. Warren Buffet_](https://en.wikipedia.org/wiki/Warren_Buffett), one of the most successful investors of the 20th century_, prefers companies where the ROE and ROCE values are almost close to each other and both are above 20%_ CREATING CUSTOM-MADE STRATEGIES ------------------------------- It is also possible to apply our own strategies on the fundamental data to decide whether to buy a stock or not. Profit-Loss Strategy -------------------- This is one of the strategies in which the profit/loss data from the past ‘n’ years of a company’s is used along with its current market price to check whether it is a worthy stock to buy now or not. This is how the strategy works _BUY if:_ * _Net profit for the company has been increasing consistently in the last few years_ * _Current market price is atleast 10% below the 52-week high (stock is not trading around its all time high)_ Applying this strategy by considering the net profit in the last 3 years gives the below recommendations for the 6 IT stocks under consideration.  **PROFIT-LOSS STRATEGY — IT STOCKS**  **VISUALIZING PROFIT-LOSS STRATEGY — IT STOCKS** Below are the details of the net profit in the last 3 years along with the stock’s current price and 52-week high for INFY and HCLTECH  **Details of strategy applied on Infy and HCL stocks** By applying this strategy, there is a buy recommendation for Infy, LTI and Wipro stocks, which implies that they have shown a consistent raise in their net profits in the last 3 years. PUTTING THEM TOGETHER --------------------- Refer to the following github repo to get access to the complete code used to scrape the web and perform the fundamental analysis, : [**_Fundamental Analyzer_**](https://github.com/Lakshmi-1212/FundamentalAnalyzer) This is only the starter code to help you get on-board quickly. Use it at your own discretion to experiment with other stocks, to fetch more data and apply your own strategies on them. Final Words…. ------------- In this article, we covered only one strategy to make the BUY/WAIT recommendation. Similarly other strategies (fundamental or technical) can be implemented for a particular stock. The consolidated results from all the strategies can be used to make the final BUY/WAIT/SELL decision. Hope this article helped you in getting a basic understanding on performing the fundamental analysis of a stock and to implement it in Python. Do try it out with other stocks and other strategies. **_Happy Learning & Happy Trading!!_** IF “PYTHON+TRADING” FASCINATES YOU THEN CHECK THESE OUT… -------------------------------------------------------- * [_Beginner’s Guide to Technical Analysis in Python for Algorithmic Trading_](https://medium.com/geekculture/beginners-guide-to-technical-analysis-in-python-for-algorithmic-trading-19164fb6149) * [_Building a Basic Crypto Trading Bot in Python_](https://medium.com/geekculture/building-a-basic-crypto-trading-bot-in-python-4f272693c375) * [_Automated Triangular Arbitrage of Cryptos in 4 steps_](https://medium.com/geekculture/automated-triangular-arbitrage-of-cryptos-in-4-steps-a678f7b01ce7) * [_Identifying Trading Patterns — Behavioural Analysis of Traders_](https://medium.com/geekculture/identifying-trading-patterns-behavioural-analysis-of-traders-5184dfa0350b) * _Fundamental Analysis of Stocks using Python \[you are here\]_ * [_Crypto & Stock: Daily Price Prediction using ML algorithms_](https://medium.com/geekculture/crypto-stock-daily-price-prediction-using-ml-algorithms-b7e815fcb06c)
Uploading file...
Edit message:
Cancel