This file contains hidden or 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 requests | |
| from base64 import b64encode | |
| # Função para buscar o trading name | |
| def get_trading_name(ticker): | |
| # cria os parâmetros | |
| params = {"language":"pt-br","pageNumber":1,"pageSize":20,"company":ticker} | |
| #params = '{"language":"pt-br","pageNumber":1,"pageSize":20,"company":"' + ticker + '"}' | |
| # para codificar em base64 é preciso fazer a conversão dos parâmetros em bytes |
This file contains hidden or 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 pandas as pd | |
| import requests | |
| from io import BytesIO | |
| from zipfile import ZipFile | |
| # le um arquivo csv ou txt dentro de um zip na internet e retorna um dataframe | |
| def read_csv_from_zip(url, file, sep=';'): | |
| # Requisição do arquivo | |
| r=requests.get(url) |
This file contains hidden or 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
| ativo = 'BBAS3' | |
| vencimento = '2022-12-16' | |
| K = 36.55 | |
| df = cotacoes(ativo, 365) | |
| S = df['Adj Close'][-1] | |
| df['Returns'] = np.log(df['Adj Close']/df['Adj Close'].shift(1)) |
This file contains hidden or 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
| ativo = 'BBAS3' | |
| vencimento = '2022-12-16' | |
| K = 45.05 | |
| # A data que está sendo executado é 17/09/2022 | |
| # em outro dia os parâmetros serão diferentes, portanto os resultados serão diferentes | |
| # Série histórica, usaremos os últimos 365 dias. O parâmetro dias irá afetar diretamente a volatildiade (sigma) | |
| df = cotacoes(ativo, 365) |
This file contains hidden or 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
| from scipy.stats import norm | |
| import numpy as np | |
| def d1(S, K, r, sigma, T): | |
| return (np.log(S/K) + (r + sigma ** 2 / 2) * T) / (sigma * np.sqrt(T)) | |
| def d2(S, K, r, sigma, T): | |
| return (np.log(S/K) + (r - sigma ** 2 / 2) * T) / (sigma * np.sqrt(T)) | |
| def bsm_call(S, K, r, sigma, T): |
This file contains hidden or 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 pandas as pd | |
| from datetime import datetime, timedelta | |
| from functools import cache | |
| # Busca a lista de feriados no site da anbima | |
| # O decorador salva a lista para não precisar fazer a requisição a todo momento | |
| @cache | |
| def feriados(): | |
| df = pd.read_excel('http://www.anbima.com.br/feriados/arqs/feriados_nacionais.xls') | |
| return [i for i in df['Data'] if isinstance(i, datetime)] |
This file contains hidden or 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 requests | |
| import pandas as pd | |
| def selic(): | |
| # busca o histórico diário da selic | |
| r=requests.get('https://api.bcb.gov.br/dados/serie/bcdata.sgs.11/dados?formato=json').json() | |
| df = pd.DataFrame(r).set_index('data') | |
| df['valor'] = df['valor'].astype(float) | |
| # anualiza as taxas, considerando 252 dias úteis no ano |
This file contains hidden or 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 requests | |
| import pandas as pd | |
| # Obtem os vencimentos | |
| def vencimentos(ticker): | |
| url = f'https://opcoes.net.br/listaopcoes/completa?au=False&uinhc=0&idLista=ML&idAcao={ticker}&listarVencimentos=true&cotacoes=true' | |
| response = requests.get(url, verify=False).json() | |
| vctos = [[i['value'], i['text']] for i in response['data']['vencimentos']] | |
| return vctos |
This file contains hidden or 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 yfinance as yf | |
| from datetime import datetime, timedelta | |
| def cotacoes(ticker, dias): | |
| # formata o nome do ticker | |
| start = (datetime.today()-timedelta(dias)).strftime('%Y-%m-%d') | |
| ticker=ticker+'.SA' if ticker[-3:] != '.SA' else ticker | |
| # busca o ticker no yahoo finance | |
| df = yf.download(ticker, start) |