Skip to content

Instantly share code, notes, and snippets.

@turicas
Last active July 20, 2020 15:15
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save turicas/a46eaea2a9fe11fdde96 to your computer and use it in GitHub Desktop.
Save turicas/a46eaea2a9fe11fdde96 to your computer and use it in GitHub Desktop.
Get stock prices from BMF Bovespa API (not working anymore)
# coding: utf-8
# WARNING: as far as I checked, this script is not working anymore.
# B3 moved to use TradingView in their own website, but there's a way
# to download daily data at:
# <http://www.b3.com.br/pt_br/market-data-e-indices/servicos-de-dados/market-data/cotacoes/cotacoes/>.
# Copyright 2015 Álvaro Justen <https://github.com/turicas/rows/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# requirements:
# pip install requests
# Other useful URLs:
# http://www.bmfbovespa.com.br/cotacoes2000/FormConsultaCotacoes.asp?strListaCodigos=BBPO11|PETR4
# http://www.bmfbovespa.com.br/Pregao-Online/ExecutaAcaoAjax.asp?CodigoPapel=BBPO11|PETR4
# http://www.bmfbovespa.com.br/cotacoes2000/formCotacoesMobile.asp?codsocemi=BBPO11
import datetime
from collections import namedtuple
from decimal import Decimal
import requests
URL = 'http://www.bmfbovespa.com.br/Pregao-Online/executaacaocarregardadosPapeis.asp?CodDado={symbol}'
MONTHS = {'Jan': '01', 'Fev': '02', 'Mar': '03', 'Abr': '04', 'Mai': '05',
'Jun': '06', 'Jul': '07', 'Ago': '08', 'Set': '09', 'Out': '10',
'Nov': '11', 'Dez': '12',}
StockQuote = namedtuple('StockQuote', ['timestamp', 'price', 'oscilation'])
def create_date(date, time):
year, month, day = date.split('/')
month = MONTHS[month]
hour, minute, second = time.split(':')
return datetime.datetime(int(year), int(month), int(day), int(hour),
int(minute), int(second))
def create_stock_quote(date, value):
return StockQuote(create_date(date, value[0]),
Decimal(value[1]),
Decimal(value[2]))
def parse_intraday_data(data):
"""Parse BMF API data into a list of `StockQuote` objects"""
data_dict = dict([x.split('=') for x in data.split('&')])
date = data_dict['D']
values = [value.split('@') for value in data_dict['V'].split('|') if value]
return [create_stock_quote(date, value) for value in values]
def get_quote(symbol):
"""Get data from BMF Bovespa API (used by its Android app)"""
response = requests.get(URL.format(symbol=symbol))
return parse_intraday_data(response.content)
def test_parse_intraday_data():
data = 'D=2015/Mai/28&V=10:00:00@103.15@-0.02|16:47:04@103@-0.17|&CE=0&ME='
expected_response = [
StockQuote(timestamp=datetime.datetime(2015, 5, 28, 10, 0, 0),
price=Decimal('103.15'),
oscilation=Decimal('-0.02')),
StockQuote(timestamp=datetime.datetime(2015, 5, 28, 16, 47, 04),
price=Decimal('103.0'),
oscilation=Decimal('-0.17')), ]
assert parse_intraday_data(data) == expected_response
if __name__ == '__main__':
print 'Quotes for BBPO11 today:'
for quote in get_quote('BBPO11'):
print ' {} {}'.format(quote.timestamp, quote.price)
@embatbr
Copy link

embatbr commented May 19, 2017

Justen, no WebSockets?

@pliniosilveira
Copy link

Not worked for me. They probably had changed the API.

@Frederico-Pacheco
Copy link

Frederico-Pacheco commented Feb 21, 2018

Here works, just changing the domain from "www.bmfbovespa.com.br" to "bvmf.bmfbovespa.com.br"

@filipefiedler
Copy link

I tried what you suggested, Frederico, but it didn't work.

@leonardoauer
Copy link

Any idea which is the correct url? It didn't work for me also.

@elirodrigues
Copy link

If anyone knows a way to get historical data, it'll be already useful for me.

@andresmafra
Copy link

Dont Work!

@rpsjr
Copy link

rpsjr commented Apr 15, 2020

If anyone knows a way to get historical data, it'll be already useful for me.

Did u find anything?

@turicas
Copy link
Author

turicas commented Apr 16, 2020

WARNING: as far as I checked, this script is not working anymore. B3 moved to use TradingView in their own website, but there's a way to download daily data at: http://www.b3.com.br/pt_br/market-data-e-indices/servicos-de-dados/market-data/cotacoes/cotacoes/.

@marcelometal
Copy link

marcelometal commented May 1, 2020

try: https://mfinance.com.br/swagger/index.html

curl -X GET "https://mfinance.com.br/api/v1/stocks/petr4"
curl -X GET "https://mfinance.com.br/api/v1/stocks/historicals/petr4"

@juvebianco
Copy link

This mfinance is cool, but just shows the last 3-months of historical data, i need data since 2010.

I was using this: http://cotacoes.economia.uol.com.br/ws/asset/2391/interday?callback=uolfinancecallback1&replicate=true&page=1&fields=date,close&end=1589392800000&begin=1262368800000

But for some tickers (e.g. COGN3) doesn't work.

Someone knows another free API with full historic data?

@marcelometal
Copy link

hi @juvebianco,

for historical data, default is the last 3 months, but you can try: 60 (5*12); mfinance stores the last 5 years data.

https://mfinance.com.br/api/v1/stocks/historicals/COGN3?months=60

I will change the API to store and show the last 15 years.

Thanks for the feedback

@juvebianco
Copy link

Hi @marcelometal,
I will try your suggestion, thanks for reply. It will be great to show the last 15 years.

All the best

@juvebianco
Copy link

@marcelometal,
I have a new doubt. Does your api gets the adjusted price like alphadvantage api example?

https://www.alphavantage.co/documentation/#monthlyadj

Thanks for your contribution!

@marcelometal
Copy link

@juvebianco, not yet... maybe someday...

If you have any doubts don't hesitate to open an issue at:
https://github.com/mfinancecombr/site/issues

This way we don't make noise in this gist =)

Thank you!

@juvebianco
Copy link

@marcelometal, ah you're right. Done! =)

Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment