Thursday, April 23, 2020

Python - How to get the NSE daily data feed?



These are days when trading decisions are taken more by a software, and people write algorithms to get their trades executed. For all this to happen, you need to have the stock data feed with you. Data is nothing but the daily open,close,high, low and volume for the stocks. Once you have the feed, the kind of things you can do with that data is endless.  In this article, we will see how to download the data feed through a Python program.

Pre-requisites:
1. Install pandas if not present already:
pip install pandas
2. Alpha Vantage has exposed free API's for downloading data feed. Install the alpha vantage package:
pip install alpha-vantage
3. You need to register yourself in Alpha vantage and get an API key.

Program:
Below is the Python program, alpha_data.py, to get the feed:

Changes you should do in the script:
1. In Line 1, replace the she-bang line with the appropriate one as present in your system.
2. In Line 7, replace the path in stock_dir to that location in which you want to save your feed files.
3. In Line 8, replace the file nifty50list.dat along with path with a file which contains the list of stock names for which you want to get the data feed. One stock per line. Sample below:
$ head -3 /home/guru/history/config/nifty50list.dat
ADANIPORTS
ASIANPAINT
AXISBANK
$ 
4. In Line 10, replace the value of key with the value you got during registration with alpha-vantage.

Execute the Python script:
Lets run the program, to begin with you can just have one or two stocks in the config file.
$ python alpha_data.py
Fetching for the stock NSE:ADANIPORTS
Completed for the stock NSE:ADANIPORTS in /home/guru/history/stock/adaniports.csv
Fetching for the stock NSE:ASIANPAINT
Completed for the stock NSE:ASIANPAINT in /home/guru/history/stock/asianpaint.csv
Fetching for the stock NSE:AXISBANK
Completed for the stock NSE:AXISBANK in /home/guru/history/stock/axisbank.csv
$
Checking the content of one of the feed files:
$ head -3 /home/guru/history/stock/axisbank.csv
Date,Open,High,Low,Close,Volume
2000-01-03,5.4394,5.4527,5.3779,5.4,521349.0
2000-01-04,5.4,5.51,5.08,5.38,494000.0
$ 
$ tail -3 /home/guru/history/stock/axisbank.csv
2020-04-20,482.0,483.45,451.25,455.95,42163627.0
2020-04-21,436.0,439.95,412.95,420.65,33572119.0
2020-04-22,418.55,434.55,412.0,431.15,36619611.0
$ 
Start playing with your data!!!

 Note:  A sleep of 20 seconds is given because alpha vantage allows only 3 API calls per minute.

No comments:

Post a Comment