Go package to fetch index composition from B3, the
Brazilian stock exchange. Given an index symbol (e.g. IBOV), it returns the
constituent securities and their theoretical weights.
Each call makes a live HTTP request to B3's public
IndexCompositionendpoint, so it needs network access and can fail with network, status, or decoding errors.
go get github.com/cesarvspr/brmarket/v2package main
import (
"fmt"
"log"
"github.com/cesarvspr/brmarket/v2"
)
func main() {
info, err := brmarket.GetSharesForIndex(brmarket.IBOV.String())
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s (%s): %d constituents\n",
info.Index.Symbol, info.Index.Description, len(info.UnderlyingList))
for _, c := range info.UnderlyingList {
fmt.Printf(" %-6s %.3f%%\n", c.Symb, c.IndxCmpnPctg)
}
}Use GetSharesForIndexContext to control the request lifetime:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
info, err := brmarket.GetSharesForIndexContext(ctx, brmarket.IBOV.String())GetSharesForIndex is a thin wrapper that calls this with context.Background()
and a default 15s client timeout.
Errors are wrapped and can be matched with errors.Is:
_, err := brmarket.GetSharesForIndex("NOPE")
if errors.Is(err, brmarket.ErrIndexNotFound) {
// unsupported symbol
}| Sentinel | Meaning |
|---|---|
ErrIndexNotFound |
the symbol is not a supported B3 index |
ErrUnexpectedStatus |
B3 returned a non-200 HTTP status |
ErrUnexpectedResponse |
B3 returned 200 but the body was not a valid index composition |
idx, err := brmarket.ParseIndexType("IBOV") // brmarket.IBOV, nil
sym := brmarket.IBOV.String() // "IBOV"IBOV IBXX IBXL IBRA IGCX ITAG IGNM IGCT
IDIV MLCX SMLL IVBX ICO2 ISEE ICON IEEX
IFNC IMOB INDX IMAT UTIL IFIX IFIL BDRX
GPTW IDVR IBLV IBSD IBHB