An image of python logo

Hey coder! Python’s a fun language right? I’ve heard someone calling it a language for lazy coders. Can’t agree more. Anyways, today we are going to see how to fetch real time stock market details using python.

Instructions:

  • This requires an Internet connection.
  • Any code editor can be used, e.g. (PyCharm, VS Code, IDLE)
  • Packages used: yahoo finance( yfinance) and lxml.

1. In the terminal of your code editor, install lxml first. To do so, type this:

pip install lxml

 

2. Then comes the real package ‘yfinance’ by yahoo . Go ahead and type in the terminal :

pip install yfinance

 

3.With this, The yahoo finance package and lxml should be installed in your Virtualenv.(or simply in your system.)

 

4.You can now create a python project, and in your project you must import yfinance (and provide a shorter name to it) :

import yfinance as yf

 

5.  here is a sample code to print HDFC Bank’s stock details:

import yfinance as yf

try:
    stock = yf.Ticker("HDB")

    # get stock info
    print(stock.info)

except Exception as e:
    print('Error:',e)

6. To show historical market data of a company, write this command :

import yfinance as yf

#MSFT stands for microsoft
stock = yf.Ticker("MSFT")

# get historical market data
hist = stock.history(period="max")

 

This might be great to make programming fun as well as useful at the same time.

Read documentation and other basic commands here

Click here to learn many more interesting python codes and packages.

We will be back very soon with an another interesting python package! thanks for hanging out.

 

 

You may also like

Leave a reply

Your email address will not be published. Required fields are marked *