Created
October 29, 2022 18:13
-
-
Save carlosdelfino/3e47158bf6a99adb2816d7fd40eb2548 to your computer and use it in GitHub Desktop.
Códigos para uso nos dados históricos da B3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
from pathlib import Path | |
import requests as req | |
def get_cotacoes(ano, mes=None, dia=None, overwrite=True): | |
if dia and mes: | |
zip_file_name = "COTAHIST_D{:02d}{:02d}{}.ZIP".format(dia,mes,ano); | |
elif mes: | |
zip_file_name = "COTAHIST_M{:02d}{}.ZIP".format(mes,dia); | |
else: | |
zip_file_name = "COTAHIST_A{}.ZIP".format(ano); | |
dest_path_file = Path("cotacoes/" + zip_file_name) | |
if dest_path_file.is_file() and not overwrite: | |
print("Arquivo {} já existe, não será baixado!".format(zip_file_name)) | |
return | |
print("Obtendo histórico {}".format(zip_file_name)) | |
url = "https://bvmf.bmfbovespa.com.br/InstDados/SerHist/"+zip_file_name | |
headers = { 'accept': '*/*', | |
'accept-language': 'en-US,en;q=0.9,pt-BR;q=0.8,pt;q=0.7,es-MX;q=0.6,es;q=0.5', | |
'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', | |
'x-requested-with': 'XMLHttpRequest', | |
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"', | |
'sec-ch-ua-mobile': '?0', | |
'sec-ch-ua-platform': '"macOS"', | |
'sec-fetch-dest': 'empty', | |
'sec-fetch-mode': 'cors', | |
'sec-fetch-site': 'same-origin', | |
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko)'} | |
get_response = req.get(url,stream=True, headers = headers) | |
print('#', end='') | |
file_name = "./cotacoes/" + zip_file_name | |
os.makedirs("./cotacoes", exist_ok=True) | |
with open(file_name, 'wb') as f: | |
print('#', end='') | |
for chunk in get_response.iter_content(chunk_size=1024): | |
if chunk: # filter out keep-alive new chunks | |
print('.', end='') | |
f.write(chunk) | |
f.close() | |
print('#') | |
if __name__ == "__main__": | |
#for ano in reversed(range(1986, 2023)): | |
# get_cotacoes(ano=ano, overwrite=False) | |
for dia in reversed(range(1,28)): | |
get_cotacoes(ano=2022, mes=10, dia=dia) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment