Subscribe

Downloading NSE Bhavcopy closing prices in golang

NSE has no free per-symbol price API, but it publishes one zipped CSV with every closing price each trading day. Here is how I download and parse it in golang: browser headers, a cookie jar, a size cap, columns by name, and a clean error for holidays.

Downloading NSE Bhavcopy closing prices in golang

We needed the closing price of NSE listed stocks once a day, to value the holdings users have. Broker APIs can give you quotes but they need a login per user, and paid data feeds are overkill for one number per stock per day. NSE itself publishes the Bhavcopy: one zipped CSV per trading day with the close of every security on the cash market. One download prices everything.

The file is public, but NSE doesn't make downloading it from a server easy. In this blog we will look at a small golang client that fetches the Bhavcopy, deals with NSE's browser checks, reads the zip in memory and picks the right rows. I also fetched the real file for 18 November 2026 while writing this, so the format notes below are from that file, not from memory.

The file

The URL has the date in it as YYYYMMDD:

https://nsearchives.nseindia.com/content/cm/BhavCopy_NSE_CM_0_0_0_20261118_F_0000.csv.zip

The zip I got was 207,047 bytes with one CSV inside, 3,703 lines including the header. The header starts like this (it goes on to 34 columns):

TradDt,BizDt,Sgmt,Src,FinInstrmTp,FinInstrmId,ISIN,TckrSymb,SctySrs,XpryDt,...,FinInstrmNm,OpnPric,HghPric,LwPric,ClsPric,LastPric,PrvsClsgPric,...

The columns we need are TckrSymb (symbol), SctySrs (series), ISIN, FinInstrmNm (name), ClsPric (close) and PrvsClsgPric (previous close). See, series is the one people skip. Most rows are EQ, normal equity, but the same file also has BE, SM, ST, government securities, gold bonds and more. On 18 November there were 2,756 EQ rows out of 3,702.

First try with curl

Before writing any Go I tried curl, and this is the whole reason the client looks the way it does:

UA="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0 Safari/537.36"

curl -s -o day.zip -w "%{http_code} %{size_download}\n" -A "$UA" \
  "https://nsearchives.nseindia.com/content/cm/BhavCopy_NSE_CM_0_0_0_20261118_F_0000.csv.zip"

curl -s -o /dev/null -w "%{http_code} %{size_download}\n" \
  "https://nsearchives.nseindia.com/content/cm/BhavCopy_NSE_CM_0_0_0_20261118_F_0000.csv.zip"
200 207047
000 0

Same URL, same machine, few seconds apart. With a browser User-Agent I got the file. With curl's default User-Agent the connection was just dropped, no status code at all. That is how NSE treats clients it thinks are bots. Go's default User-Agent is Go-http-client/1.1 and I would expect it to get the same treatment.

A Sunday date gave a plain 404. That's useful, it means "no file for this day" is easy to tell apart from "something broke".

The client

const (
    fileURL = "https://nsearchives.nseindia.com/content/cm/BhavCopy_NSE_CM_0_0_0_%s_F_0000.csv.zip"
    homeURL = "https://www.nseindia.com"

    // NSE drops connections from clients that don't look like a browser.
    userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " +
        "(KHTML, like Gecko) Chrome/140.0 Safari/537.36"

    // The zip is about 200 KB. The cap only protects us from a bad response.
    maxBody = 20 << 20
)

// ErrNotPublished means there is no file for that day: a weekend, a market
// holiday, or the file is not out yet.
var ErrNotPublished = errors.New("bhavcopy: not published")

type Client struct {
    HTTP    *http.Client
    FileURL string // format string with one %s for YYYYMMDD
    HomeURL string
}

func New() *Client {
    jar, _ := cookiejar.New(nil) // keeps the cookies the home page sets
    return &Client{
        HTTP:    &http.Client{Timeout: 30 * time.Second, Jar: jar},
        FileURL: fileURL,
        HomeURL: homeURL,
    }
}

The URLs are fields only so the tests can point client at a local server. The cookie jar is actually the part that is easy to miss. Sometimes NSE answers 403 and only serves the file after you have visited the home page and picked up its cookies. Without a jar, Go's http.Client throws those cookies away, and the retry gets 403 again. With a jar the client carries them along by itself.

// Day returns the closing prices for one trading day, keyed by symbol.
func (c *Client) Day(ctx context.Context, day time.Time) (map[string]Quote, error) {
    url := fmt.Sprintf(c.FileURL, day.Format("20060102"))

    body, status, err := c.get(ctx, url)
    if err != nil {
        return nil, err
    }

    // A 403 usually means "visit the home page first and bring its cookies".
    if status == http.StatusForbidden {
        if _, _, err := c.get(ctx, c.HomeURL); err != nil {
            return nil, err
        }
        if body, status, err = c.get(ctx, url); err != nil {
            return nil, err
        }
    }

    switch status {
    case http.StatusOK:
        return Parse(body)
    case http.StatusNotFound:
        return nil, ErrNotPublished
    default:
        return nil, fmt.Errorf("bhavcopy %s: HTTP %d", day.Format("2006-01-02"), status)
    }
}

One retry, not a loop. If the second try also fails, it fails loudly and the caller decides. My curl test today didn't need the cookie step at all, the User-Agent alone was enough. The retry is there because the service this came from does run into that 403, and one extra request is cheap.

The 30 second timeout per request is picked so the worst case (file, home page, file again) fits inside the 3 minutes the calling job waits. Make your timeouts add up like that, otherwise the outer job times out first and you never see the real error.

func (c *Client) get(ctx context.Context, url string) ([]byte, int, error) {
    req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
    if err != nil {
        return nil, 0, err
    }
    req.Header.Set("User-Agent", userAgent)
    req.Header.Set("Accept", "*/*")

    resp, err := c.HTTP.Do(req)
    if err != nil {
        return nil, 0, fmt.Errorf("bhavcopy: %w", err)
    }
    defer resp.Body.Close()

    body, err := io.ReadAll(io.LimitReader(resp.Body, maxBody+1))
    if err != nil {
        return nil, 0, fmt.Errorf("bhavcopy: read: %w", err)
    }
    if len(body) > maxBody {
        return nil, 0, fmt.Errorf("bhavcopy: response over %d bytes", maxBody)
    }
    return body, resp.StatusCode, nil
}

The maxBody+1 trick: read one byte more than the limit, and if you got it, the body was too big. A plain LimitReader(body, maxBody) would just cut the body quietly and you'd try to unzip half a file.

Parsing the zip in memory

The file is small, so there's no reason to touch the disk. archive/zip reads from any io.ReaderAt, and bytes.NewReader is one:

// Parse reads the zipped CSV in memory.
func Parse(zipped []byte) (map[string]Quote, error) {
    zr, err := zip.NewReader(bytes.NewReader(zipped), int64(len(zipped)))
    if err != nil {
        return nil, fmt.Errorf("bhavcopy: not a zip: %w", err)
    }
    if len(zr.File) == 0 {
        return nil, errors.New("bhavcopy: empty zip")
    }
    f, err := zr.File[0].Open()
    if err != nil {
        return nil, err
    }
    defer f.Close()

    r := csv.NewReader(io.LimitReader(f, maxBody))
    r.FieldsPerRecord = -1

    header, err := r.Read()
    if err != nil {
        return nil, fmt.Errorf("bhavcopy: header: %w", err)
    }
    col := map[string]int{}
    for i, h := range header {
        col[strings.TrimSpace(strings.TrimPrefix(h, ""))] = i
    }
    for _, need := range []string{"TckrSymb", "SctySrs", "ISIN", "FinInstrmNm", "ClsPric", "PrvsClsgPric"} {
        if _, ok := col[need]; !ok {
            return nil, fmt.Errorf("bhavcopy: no %s column", need)
        }
    }

    quotes := map[string]Quote{}
    for {
        rec, err := r.Read()
        if errors.Is(err, io.EOF) {
            break
        }
        if err != nil {
            return nil, fmt.Errorf("bhavcopy: row: %w", err)
        }
        q, ok := quoteFrom(rec, col)
        if !ok {
            continue // skip a row we can't price, don't fail the whole day
        }
        if prev, seen := quotes[q.Symbol]; seen && rank(prev.Series) <= rank(q.Series) {
            continue
        }
        quotes[q.Symbol] = q
    }
    if len(quotes) == 0 {
        return nil, errors.New("bhavcopy: no priced rows")
    }
    return quotes, nil
}

A few things in there are on purpose.

Columns are looked up by name, never by position. NSE has changed this file before. Around July 2024 the cash market Bhavcopy moved to the UDiFF format, with a new file name, new location and new column names, which is why the old Bhavcopy links in older blog posts don't work anymore. If they add or move a column, lookup by name keeps working, and if they rename one we need, we get a clear error instead of reading the volume column as a price.

The header is stripped of a byte order mark. The file I downloaded doesn't have one, it starts straight with TradDt. But CSVs from Windows tools often do, and now what happens is a BOM glued to the first column name makes that lookup fail in a way that is really confusing to debug. One TrimPrefix and it's never a problem.

FieldsPerRecord = -1 lets rows have a different number of fields. A bad row is skipped instead of killing the whole day's prices. For our use, 3,701 prices and one missing is a lot better than none.

And the series preference. If a symbol appears in more than one series on the same day, we keep the EQ line first, then BE, and so on:

var seriesRank = map[string]int{"EQ": 0, "BE": 1, "BZ": 2, "SM": 3, "ST": 4}

I checked the 18 November file and no symbol were in two series that day, so honestly this didn't matter for that file. It's cheap insurance and I'd keep it.

Running it

The small command in the repo can read a saved zip, so I could test against the real file without downloading it again and again:

go run ./cmd/bhav -file day.zip RELIANCE INFY TCS NOSUCH
3702 symbols
RELIANCE   EQ     1363.00  prev    1367.00  -0.29%
INFY       EQ     1108.80  prev    1130.00  -1.88%
TCS        EQ     2379.50  prev    2406.60  -1.13%
NOSUCH     not found

3,702 rows went in and 3,702 symbols came out, so on that day every row had a usable close and no symbol was repeated.

Testing the download path

I didn't want tests that hit NSE itself. The download logic is tested against an httptest server that behaves like the awkward version of NSE: it answers 403 until the request carries a cookie that only the home page sets, and 404 for any date it doesn't know.

mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    http.SetCookie(w, &http.Cookie{Name: "nsit", Value: "ok", Path: "/"})
})
mux.HandleFunc("/content/cm/{name}", func(w http.ResponseWriter, r *http.Request) {
    if c, err := r.Cookie("nsit"); err != nil || c.Value != "ok" {
        w.WriteHeader(http.StatusForbidden)
        return
    }
    if r.PathValue("name") != "BhavCopy_20261118.csv.zip" {
        http.NotFound(w, r)
        return
    }
    w.Write(file)
})

There are three tests on top of it. The normal case gets 403, visits the home page, retries and gets prices. A Sunday gets ErrNotPublished. And one test sets c.HTTP.Jar = nil and checks that the call fails with HTTP 403, which shows the jar really is what makes the retry work. All tests pass with -race on Go 1.27.3.

When to run it

The file for a day only exists after the market closes and NSE has published it. The CSV inside the 18 November zip has a 16:30 timestamp, but I wouldn't count on it being up right at that time. We run the job in the evening IST and treat ErrNotPublished as "try again later", not as an error. Weekends and holidays return the same 404, so the job doesn't need its own holiday calendar. If you need the price as of a holiday, walk back one day at a time until you find a file, with a limit of a week or so.

Keep it to one download a day per job. It's one small file, and there's no reason to give NSE more traffic than that. If you want something to do with the prices, the Zerodha charges calculator in Go and the paper trader backtesting post are the other trading posts in Go on this blog.