Tuesday, 17 April 2012

Indian Market Data Download (NSE & BSE)

Recently while browsing the Indian stock market web sites (NSE and BSE), a thought came by to build a automated data downloader for the historical equity prices to be analyzed in excel.

Henceforth the following tool was built to do the same. This tool extracts the data from the exchanges (NSE and BSE) website (Historical Data Section) for the equity and the time period requested (Currently the tool downloads the daily data only but easily configurable via code to monthly/yearly).

The data downloaded via tool is placed on separate sheets for both NSE and BSE, upon which any post download analysis can be conducted..

Hope this tool helps you in outperform the markets better. Happy trading..

 


modNse.bas
Option Explicit

Private Const NSE_URL As String = "http://www.nseindia.com/products/dynaContent/common/productsSymbolMapping.jsp?symbol={0}&segmentLink=3&symbolCount=1&series=EQ&dateRange=+&fromDate={1}&toDate={2}&dataType=PRICEVOLUME"

Public Sub GetNseData()

    Dim request As WinHttp.WinHttpRequest
    Dim htmlDocument As MSHTML.htmlDocument
    Dim rowCollection As Variant
    Dim htmlRow As Variant
    Dim rowSubContent As Variant
    Dim rowSubData As Variant
    Dim rowCount As Integer, colCount As Integer
    Dim anchorRange As Range
    Dim prepUrl As String
    Dim timeOut As Long

    On Error GoTo errHandler
    
    timeOut = 10000
    DataDumpNse.Cells.Clear
    Set anchorRange = DataDumpNse.Range("A1")

    Set htmlDocument = New MSHTML.htmlDocument

    Set request = New WinHttp.WinHttpRequest

    prepUrl = Replace(NSE_URL, "{0}", modCommonFunctions.URLEncode(ThisWorkbook.Names("NSE_TICKER").RefersToRange.Value))
    prepUrl = Replace(prepUrl, "{1}", Format(ThisWorkbook.Names("NSE_FROM_DATE").RefersToRange.Value, "dd-mm-yyyy"))
    prepUrl = Replace(prepUrl, "{2}", Format(ThisWorkbook.Names("NSE_TO_DATE").RefersToRange.Value, "dd-mm-yyyy"))
    request.Open "GET", prepUrl
    request.SetTimeouts timeOut, timeOut, timeOut, timeOut
    request.Send
    htmlDocument.body.innerHTML = request.ResponseText

    rowCount = 0
    colCount = 0

    Set rowCollection = htmlDocument.getElementsByTagName("tr")
    For Each htmlRow In rowCollection
        Set rowSubContent = htmlRow.getElementsByTagName("th")
        If rowSubContent.Length <> 0 Then
            For Each rowSubData In rowSubContent
                anchorRange.Offset(rowCount, colCount).Value = rowSubData.innerText
                colCount = colCount + 1
            Next rowSubData
        Else
            Set rowSubContent = htmlRow.getElementsByTagName("td")
            For Each rowSubData In rowSubContent
                anchorRange.Offset(rowCount, colCount).Value = rowSubData.innerText
                colCount = colCount + 1
            Next rowSubData
        End If

        colCount = 0
        rowCount = rowCount + 1
    Next htmlRow
    
    Exit Sub
    
errHandler:
    MsgBox Err.Description, vbExclamation, "Download Error"
    On Error GoTo 0
    Err.Clear
End Sub



modBse.bas
Option Explicit

Private Const BSE_URL As String = "http://www.bseindia.com/stockinfo/stockprc2_excel.aspx?scripcd={0}&FromDate={1}&ToDate={2}&OldDMY=D"

Public Sub GetBseData()

    Dim request As WinHttp.WinHttpRequest
    Dim lineSplit As Variant
    Dim rowCount As Long
    Dim line As Variant
    Dim anchorRange As Range
    Dim url As String
    
    DataDumpBse.Cells.Clear
    Set anchorRange = DataDumpBse.Range("A1")
    
    Set request = New WinHttp.WinHttpRequest
    
    url = Replace(BSE_URL, "{0}", ThisWorkbook.Names("BSE_TICKER").RefersToRange.Value)
    url = Replace(url, "{1}", Format(ThisWorkbook.Names("BSE_FROM_DATE").RefersToRange.Value, "mm/dd/yyyy"))
    url = Replace(url, "{2}", Format(ThisWorkbook.Names("BSE_TO_DATE").RefersToRange.Value, "mm/dd/yyyy"))
    
    request.Open "GET", url
    request.Send
    lineSplit = Split(request.ResponseText, vbCrLf)
    
    rowCount = 0
    For Each line In lineSplit
        anchorRange.Offset(rowCount, 0).Value = line
        rowCount = rowCount + 1
    Next line
    
    DataDumpBse.Range("A:A").TextToColumns DataDumpBse.Range("A1"), xlDelimited, Comma:=True
    
End Sub



Download Solution
Download solution


References:
Link1: http://www.nseindia.com/
Link2: http://www.bseindia.com/

14 comments:

Bagwan Zeeshan Ali Akbar said...

Hey the code is giving an error of operation timed out.
can u help resolve the it

Anonymous said...

too good man........very useful...super like...can u provide me for nifty futures , mcx and currency..plz help

Anonymous said...

FEDERALBN.NS
APOLLOTYRE.NS
JINDALSTEL.NS
INDUSINDBK.NS
JUSTDIAL.NS
MCDOWELL-N.NS
ORIENTBANK.NS

Anonymous said...

FEDERALBN.NS
APOLLOTYRE.NS
JINDALSTEL.NS
INDUSINDBK.NS
JUSTDIAL.NS
MCDOWELL-N.NS
ORIENTBANK.NS


getting error data unavailable i tried with -eq.ns also plz help us

Anonymous said...

Dear Amol,

Many Thanks for this Useful Program.
Is it possible to create such program for multiple stocks per day basis?

For Eg. If i have a list of stocks Like A,B,C,D & If i enter a date Shall we capture a data for that specific date in Date Column (One worksheet for price & other for volume?


Regards,
Kedar N

Dinesh said...

Dear Amol,

You are an amazing programmer.
Thank you.

But there is an issue here... the data is downloading only till 28th May 2015.

Could you pls help resolve this.

Warm Regards
Dinesh

Dinesh said...

Dear Amol,

When I put in a script "ACC", data of script "ACCELYA" is collected.
Also how do we get data for indexes?

Thanks
Warm Regards
Dinesh

somayaji said...

BSE downloading error due to change in downloading location, can you please updated it please

Boom said...

There is an error for the BSE data as the data source is changed, so please change the code and provide is the modified file.

seema said...


Thank you for another great article. Where else could anyone get that kind of information in such a perfect way of writing? I have a presentation next week, and I am on the look for such information.



NSE ACCOUNT

FlyHigh said...

For this, I had been using this and it's great.
It has instructions which can help you.
Historical Stock Data in Excel
Just visit the site for more info.
They also have a live support and a forum to help you with your questions/concerns.

Anonymous said...

Hi.. The macro code was working fine till yesterday. However, I am not sure what has happened. The code is not working. Please assist. I believe some thing wrong with the URL. whether the nse url is changed?

seema said...



Thank you so much for taking time to read my blog. I read all my comments and appreciate each and every one!


Nifty Trading

Pareesh Ratan Kundu said...

Facing Problem!!
https://nsebsegrowthfreetips.blogspot.in