├── .env
├── Procfile
├── .gitignore
├── requirements.txt
├── src
├── connections_db
│ ├── create_database.py
│ ├── connections_cryptocurrencies.py
│ └── get_data_local.py
├── updateValues.py
├── get_price_cryptocurrencies.py
├── lists.py
└── get_data_internet.py
├── main.py
├── LICENSE
└── README.md
/.env:
--------------------------------------------------------------------------------
1 | API_KEY=''
--------------------------------------------------------------------------------
/Procfile:
--------------------------------------------------------------------------------
1 | web: uvicorn main:app --host=0.0.0.0 --port=${PORT:-5000}
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Folders
2 | venv/
3 | database/
4 | assets/
5 |
6 | /**/.idea/
7 | /**/__pycache__/
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | deep-translator==1.5.4
2 | fastapi==0.68.1
3 | firebase-admin==5.0.2
4 | uvicorn==0.15.0
5 | wikipedia==1.4.0
6 | pandas==1.3.2
7 | beautifulsoup4==4.10.0
8 | html5lib==1.1
9 | python-dotenv==0.19.0
--------------------------------------------------------------------------------
/src/connections_db/create_database.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | from connections_db.connections_cryptocurrencies import ConnectionDBCryptoCurrencies
3 |
4 | dbTickers = sqlite3.connect("database/tickers.db")
5 | dbTickers.execute("create table dataStock(nome text, logo text, info text, ticker text, dy number, precoMinimoCotaEmUmAno number, precoMaximoCotaEmUmAno number, dividendoEmUmAno number, oscilacaoCota number, valorCota number ,linkSiteRi text, valorizacaoCotaUmAno number, cnpj text);")
6 | dbTickers.commit()
7 |
8 | ConnectionDBCryptoCurrencies().createTable()
--------------------------------------------------------------------------------
/main.py:
--------------------------------------------------------------------------------
1 | from fastapi import FastAPI
2 | import uvicorn
3 | from src.get_data_local import DataLocal
4 | from src.get_price_cryptocurrencies import getValueCryptos
5 |
6 | app = FastAPI(debug=False)
7 |
8 | infoAction = {"data": {}}
9 |
10 | @app.get("/get-ticker/{ticker}")
11 | async def getTicker(ticker: str):
12 | dataLocal = DataLocal()
13 | infoAction["data"] = dataLocal.getData(ticker)
14 | return infoAction
15 |
16 | @app.get("/get-tickers")
17 | async def getTickers():
18 | dataLocal = DataLocal()
19 | return dataLocal.getOrderDatas("oscilacaoCota")
20 |
21 | @app.get("/get-stocks-by-order/{order}")
22 | async def getStocksByOrder(order: str):
23 | dataLocal = DataLocal()
24 | return dataLocal.getOrderDatas(order)
25 |
26 | @app.get("/get-values-cryptos")
27 | async def getCryptos():
28 | return {"result": getValueCryptos()}
29 |
30 | uvicorn.run(app, host="localhost", port=8000)
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Ramon Paolo Maran
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/connections_db/connections_cryptocurrencies.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 | class ConnectionDBCryptoCurrencies():
4 | def __init__(self):
5 | self.db = sqlite3.connect("database/cryptos.db")
6 |
7 | def createTable(self):
8 | self.db.execute("create table cryptos(uuid text, symbol text, name text, color text, iconUrl text, marketCap number, price number, change number, rank number, lowVolume number, coinrankingUrl text, volume number, btcPrice number);")
9 | self.db.commit()
10 |
11 | def updateValues(self, x: object):
12 | self.db.execute(f"update cryptos set marketCap={float(x['marketCap'])}, price={float(x['price'])}, change={float(x['change'])}, rank={x['rank']}, lowVolume={float(x['lowVolume'])}, volume={float(x['24hVolume'])}, btcPrice={float(x['btcPrice'])} where name='{x['name']}';")
13 |
14 | def addValues(self, x: object):
15 | self.db.execute(f"""insert into cryptos values('{x['uuid']}','{x['symbol']}','{x['name']}', '{x['color']}','{x['iconUrl']}', {float(x['marketCap'])} , {float(x['price'])}, {float(x['change'])}, {x['rank']}, {float(x['lowVolume'])},'{x['coinrankingUrl']}', {float(x['24hVolume'])},{float(x['btcPrice'])});""")
16 |
17 | def getValues(self):
18 | return self.db.execute("select * from cryptos;")
--------------------------------------------------------------------------------
/src/connections_db/get_data_local.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 |
3 | class DataLocal():
4 | def getData(self, ticker: str):
5 | db = sqlite3.connect("./database/tickers.db")
6 | data = db.execute(f"select * from dataStock where ticker='{ticker.upper()}'").fetchall()
7 | # print(data[0])
8 | return {
9 | "nome": data[0][0],
10 | "logo": data[0][1],
11 | "info": data[0][2],
12 | "ticker": data[0][3],
13 | "dy": data[0][4],
14 | "preco_min_cota": data[0][5],
15 | "preco_max_cota": data[0][6],
16 | "ultimo_pagamento": data[0][7],
17 | "oscilacao_cota": data[0][8],
18 | "valor_cota": data[0][9],
19 | "linkSiteRi": data[0][10],
20 | "valorizacaoCota": data[0][11],
21 | "cnpj": data[0][12],
22 | }
23 |
24 | def getOrderDatas(self, order: str):
25 | db = sqlite3.connect("./database/tickers.db")
26 | datas = db.execute(f"select * from dataStock order by {order}").fetchall()
27 | datasInJson = []
28 | for x in datas:
29 | if x[0] != "":
30 | datasInJson.append({"data": {
31 | "nome": x[0],
32 | "logo": x[1],
33 | "info": x[2],
34 | "ticker": x[3],
35 | "dy": x[4],
36 | "preco_min_cota": x[5],
37 | "preco_max_cota": x[6],
38 | "ultimo_pagamento": x[7],
39 | "oscilacao_cota": x[8],
40 | "valor_cota": x[9],
41 | "linkSiteRi": x[10],
42 | "valorizacaoCota": x[11],
43 | "cnpj": x[12]}
44 | })
45 | return {"result": datasInJson}
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # API Ações
2 | ### API simples que retorna: Preço, DY, ultimo valor em dividendos, logo, preço mínimo em 12 meses, preço maxímo em 12 meses, oscilação diária, oscilação anual, cnpj e link do site de RI.
3 |
4 | ### Libs Utilizadas:
5 | - Fast API
6 | - numpy
7 | - sqlite3
8 | - beautifulSoup4
9 |
10 | ### Descrição do Funcionamento:
11 | Ao executar: python main.py, Fast API irá executar localmente na porta 8000(no debug), abrindo as seguintes rotas:
12 | - docs (rota padrão do Fast API)
13 | - get-tickers
14 | - get-ticker/{nome da ação. exemplo: petr4}
15 | - get-tickers-by-order/{exemplo: valor_cota}
16 | - get-values-cryptos
17 |
18 | Ao executar: python updateValues.py, será feito web-scraping com bs4(Beautiful Soup) no site Status Invest, onde irá atualizar os tickers(FIIs, BDRs, ETFs e Ações) e os valores das Crypto Moedas no site Coin Ranking
19 |
20 | Ao clocar o projeto, o dev deverá criar uma conta de desenvolvedor no site Coin Ranking Developers, para gerar sua API de cotação das Crypto Moedas, e colocar no arquivo:
21 |
22 | * get_price_cryptocurrencies.py
23 |
24 | Substituindo API_KEY pela chave gerada anteriormente.
25 |
26 | Projeto com deploy no Heroku, na url: https://api-b3-python.herokuapp.com
27 |
28 |
29 |   
30 |
--------------------------------------------------------------------------------
/src/updateValues.py:
--------------------------------------------------------------------------------
1 | import numpy
2 | from get_price_cryptocurrencies import updateCryptos
3 | from lists import fiis, bdrs, stocks, etfs
4 | import requests
5 | from bs4 import BeautifulSoup
6 | from get_data_internet import getAllValuesFiis, getAllValuesStocks, getAllValuesEtfs, getAllValuesBdrs
7 |
8 | totalLengthStocks = len(stocks) + len(fiis) + len(bdrs) + len(etfs)
9 | totalStocks = stocks
10 | totalStocks = numpy.append(totalStocks, fiis)
11 | totalStocks = numpy.append(totalStocks, bdrs)
12 | totalStocks = numpy.append(totalStocks, etfs)
13 |
14 | print("Rodando dnv")
15 | updateCryptos()
16 | for x in range(1, totalLengthStocks):
17 | typeStock = totalStocks[x]
18 | if typeStock in stocks:
19 |
20 | url = requests.get(
21 | f"https://statusinvest.com.br/acoes/{typeStock}")
22 | nav = BeautifulSoup(url.text, "html5lib")
23 |
24 | infoAction = getAllValuesStocks(nav, stocks[x].upper())
25 | print(f"Atualizando a ação: {typeStock}")
26 |
27 | elif typeStock in fiis:
28 |
29 | url = requests.get(
30 | f"https://statusinvest.com.br/fundos-imobiliarios/{typeStock}")
31 | nav = BeautifulSoup(url.text, "html5lib")
32 |
33 | infoAction = getAllValuesFiis(nav, typeStock.upper())
34 | print(f"Atualizando o fundo: {typeStock}")
35 |
36 | elif typeStock in etfs:
37 | url = requests.get(
38 | f"https://statusinvest.com.br/etfs/{typeStock}")
39 | nav = BeautifulSoup(url.text, "html5lib")
40 |
41 | infoAction = getAllValuesEtfs(nav, typeStock.upper())
42 | print(f"Atualizando o ETF: {typeStock}")
43 |
44 | else:
45 | url = requests.get(
46 | f"https://statusinvest.com.br/bdrs/{typeStock}")
47 | nav = BeautifulSoup(url.text, "html5lib")
48 |
49 | infoAction = getAllValuesBdrs(nav, typeStock.upper())
50 | print(f"Atualizando o BDR: {typeStock}")
--------------------------------------------------------------------------------
/src/get_price_cryptocurrencies.py:
--------------------------------------------------------------------------------
1 | import json
2 | import requests
3 | from connections_db.connections_cryptocurrencies import ConnectionDBCryptoCurrencies
4 | from dotenv import load_dotenv
5 | import os
6 |
7 | load_dotenv(".env")
8 |
9 | def updateCryptos():
10 | connectionCrypto = ConnectionDBCryptoCurrencies()
11 |
12 | # Troque a chave de acesso pela sua. https://developers.coinranking.com/account/
13 | response = requests.get("https://api.coinranking.com/v2/coins", params={'x-access-token': os.getenv("API_KEY")})
14 | parsed = json.loads(response.text)
15 | coins = parsed["data"]["coins"]
16 |
17 | for x in coins:
18 | print(f"uuid: {x['uuid']}")
19 | print(f"symbol: {x['symbol']}")
20 | print(f"name: {x['name']}")
21 | print(f"iconUrl: {x['iconUrl']}")
22 | print(f"price: {x['price']}")
23 | print(f"rank: {x['rank']}")
24 | print(f"btcPrice: {x['btcPrice']} \n")
25 | connectionCrypto.updateValues(x)
26 | #Se for sua primeira vez executando, execute primeiro a inserção de dados na tabela
27 | #connectionCrypto.addValues(x)
28 |
29 | connectionCrypto.db.commit()
30 | connectionCrypto.db.close()
31 |
32 | def getValueCryptos():
33 | coins = ConnectionDBCryptoCurrencies().getValues()
34 | coinsInJson = []
35 | for x in coins:
36 | coinsInJson.append({'uuid': x[0],
37 | "symbol": x[1],
38 | "name": x[2],
39 | "color": x[3],
40 | "iconUrl": x[4],
41 | "marketCap": x[5],
42 | "price": x[6],
43 | "change": x[7],
44 | "rank": x[8],
45 | "lowVolume": x[9],
46 | "coinrankingUrl": x[10],
47 | "24hVolume": x[11],
48 | "btcPrice": x[12]
49 | })
50 | return coinsInJson
51 | #Code to Download crypto images
52 | # r = requests.get(x['iconUrl'], stream=True)
53 | # if r.status_code == 200:
54 | # r.raw.decode_content = True
55 | # Abrir arquivo com permissão de escrita binária
56 | # with open(f"assets/crypto/{x['name']}.svg", 'wb') as f:
57 | # shutil.copyfileobj(r.raw, f)
58 | # print('Downloaded Image: ', f"{x['name']}.svg")
59 | # else:
60 | # print('Não conseguiu salvar a imagem')
61 |
--------------------------------------------------------------------------------
/src/lists.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | fiis = np.array(["bcff11", "bpff11", "hctr11", "hfof11", "btal11"])
3 | stocks = np.array(["itub4", "itsa4", "taee4", "taee11", "taee3", "wizs3", "sapr4",
4 | "sapr3", "egie3", "enbr3", "klbn4", "klbn3", "klbn11", "cyre3",
5 | "sula4", "sula3", "sula11", "bbse3", "mdia3", "whrl4", "bidi4",
6 | "bidi11", "bbas3", "aesb3", "itub3", "itub4", "cple3", "cple5",
7 | "cple6", "amer3", "bbdc3", "bbdc4", "azul4", "embr3", "alpa4",
8 | "alup11", "abev3", "bmgb4", "bkbr3", "brfs3", "cepe3", "cmig3",
9 | "cmig4", "raiz4", "irbr3", "petr4", "petr3", "epar3", "mmaq3",
10 | "wlmm3", "azev3", "sond3", "tcno3", "alpk3", "atmp3", "bbml3",
11 | "dtcy3", "flex3", "ggps3", "mils3", "prnr3", "seql3", "vlid3",
12 | "aeri3", "arml3", "bdll3", "ealt3", "romi3", "inep3", "kepl3",
13 | "frio3", "nord3", "ptca3", "shul3", "wege3", "fras3", "pomo3",
14 | "rsul3", "rapt3", "rcsl3", "tupy3", "mwet3", "ccro3", "stbp3",
15 | "goll4", "vspt3", "rail3", "hbsa3", "logn3", "jslg3", "aheb6",
16 | "tgma3", "elmd3", "mypk3", "leve3", "plas3", "alld3", "mglu3",
17 | "viia3", "sbfg3", "lame3", "lame4", "ljqq3", "petz3", "sled3",
18 | "sled4", "arzz3", "ceab3", "cgra3", "soma3", "guar3", "lren3",
19 | "amar3", "llis3", "lcam3", "rent3", "msro3", "show3", "cvcb3",
20 | "movi3", "vamo3", "bahi3", "cogn3", "csed3", "yduq3", "hoot3",
21 | "hoot4", "meal3", "mndl3", "tecn3", "viva3", "camb3", "grnd3",
22 | "cedo3", "cedo4", "cata3", "cata4", "ctnm3", "ctnm4", "ctsa3",
23 | "ctsa4", "dohl3", "ecpr3", "ctka3", "ctka4", "ptnt3", "ptnt4",
24 | "sgps3", "teka3", "teka4", "txrx3", "txrx4", "hgtx3", "tfco4",
25 | "ucas3", "heta3", "heta4", "smft3", "bmks3", "estr3", "estr4",
26 | "aheb3", "aheb5", "vulc3"
27 | ])
28 | bdrs = np.array(["nvdc34", "csco34", "aapl34", "mmmc34", "a1bb34", "abtt34", "atvi34", "adbe34"])
29 | etfs = np.array(["ivvb11", "smal11", "bova11"])
30 |
--------------------------------------------------------------------------------
/src/get_data_internet.py:
--------------------------------------------------------------------------------
1 | import sqlite3
2 | import wikipedia
3 | from deep_translator import GoogleTranslator
4 |
5 | infoAction = {}
6 | dataJson = {}
7 |
8 | class BasicData():
9 | def __init__(self, soup, ticker: str):
10 | self.soup = soup
11 | self.ticker = ticker
12 |
13 | def getValuesLocal(self):
14 | return None
15 |
16 | def getInfoWikipedia(self):
17 | try:
18 | text = wikipedia.summary("Empresa: " + infoAction["nome"], 3)
19 | return GoogleTranslator(
20 | source="auto", target="pt").translate(text)
21 | except:
22 | #print("Não conseguiu pegar da Wikipédia/traduzir")
23 | return "Nada encontrado...."
24 |
25 | def getDatasInternet(self):
26 | try:
27 | infoAction["nome"] = self.soup.find("small").text
28 | except AttributeError:
29 | pass
30 | infoAction["logo"] = self.getImage()
31 | infoAction["info"] = self.getInfoWikipedia()
32 | infoAction["ticker"] = self.ticker.upper()
33 |
34 | return infoAction
35 |
36 | def getImage(self):
37 | #print(str(self.soup.find_all("div")[338]).split("(")[1].split(")")[0])
38 | if self.soup.find("div", title="Logotipo da empresa '"+infoAction["nome"].upper()+"'") != None:
39 | getImagee = self.soup.find("div", title="Logotipo da empresa '"+infoAction["nome"].upper()+"'")
40 | print(f"Site da image: {getImagee} do ticker: {self.ticker} com o nome: {infoAction['nome']}")
41 | return "https://statusinvest.com.br" +getImagee.__str__().split("(")[1].split(")")[0]
42 | #elif str(self.soup.find_all("div")[338]).split("(")[1].split(")")[0] != None:
43 | #return "https://statusinvest.com.br" + str(self.soup.find_all("div")[338]).split("(")[1].split(")")[0]
44 | else:
45 | for x in self.soup.find_all("div"):
46 | if str(x).__contains__("data-img"):
47 | try:
48 | print(str(x).split("(")[1].split(")")[0])
49 | return "https://statusinvest.com.br" + str(x).split("(")[1].split(")")[0]
50 | except:
51 | return "https://ik.imagekit.io/9t3dbkxrtl/image_not_work_bkTPWw2iO.png"
52 | return "https://ik.imagekit.io/9t3dbkxrtl/image_not_work_bkTPWw2iO.png"
53 |
54 | def getTagAlong(self):
55 | self.tagAlong = self.soup.find_all("strong", attrs={"class": "value"})[6].text
56 | return self.tagAlong
57 |
58 | def getLiquidezDiaria(self):
59 | self.liquidezMediaDiaria = self.soup.find_all("strong", attrs={"class": "value"})[7].text
60 | return self.liquidezMediaDiaria
61 |
62 |
63 | def writeData(self, infoAction):
64 | db = sqlite3.connect("./database/tickers.db")
65 | try:
66 | infoAction["dy"] = float(str(infoAction["dy"]).replace(",", "."))
67 | except:
68 | infoAction["dy"] = 0.0
69 |
70 | try:
71 | infoAction["valorizacaoCota"] = float(str(infoAction["valorizacaoCota"]).replace(",", ".").replace("%", ""))
72 | except:
73 | infoAction["valorizacaoCota"] = 0.0
74 |
75 | try:
76 | infoAction['preco_min_cota'] = float(str(infoAction["preco_min_cota"]).replace(",", "."))
77 | infoAction['preco_max_cota'] = float(str(infoAction["preco_max_cota"]).replace(",", "."))
78 |
79 | except:
80 | infoAction["preco_min_cota"] = 0.0
81 | infoAction["preco_max_cota"] = 0.0
82 |
83 | try:
84 | infoAction['ultimo_pagamento'] = float(str(infoAction["ultimo_pagamento"]).replace(",", ".").replace("R$ ", ""))
85 | except:
86 | infoAction['ultimo_pagamento'] = 0.0
87 |
88 | try:
89 | infoAction['oscilacao_cota'] = float(str(infoAction["oscilacao_cota"]).replace(",", ".").replace("%", ""))
90 | except:
91 | infoAction['oscilacao_cota'] = 0.0
92 |
93 | try:
94 | infoAction['valor_cota'] = float(str(infoAction["valor_cota"]).replace(",", "."))
95 | except:
96 | infoAction['valor_cota'] = 0.0
97 |
98 | if len(db.execute(f"select * from dataStock where ticker='{self.ticker}'").fetchall()) >= 1:
99 | db.execute(f"update dataStock SET dy={infoAction['dy']}, precoMinimoCotaEmUmAno={infoAction['preco_min_cota']}, precoMaximoCotaEmUmAno={infoAction['preco_max_cota']}, dividendoEmUmAno={infoAction['ultimo_pagamento']}, oscilacaoCota={infoAction['oscilacao_cota']}, valorCota={infoAction['valor_cota']}, logo='{infoAction['logo']}', cnpj='{infoAction['cnpj']}', linkSiteRi='{infoAction['linkSiteRi']}', valorizacaoCotaUmAno={infoAction['valorizacaoCota']} where ticker='{infoAction['ticker']}'")
100 | #print("Ação atualizada")
101 | else:
102 | db.execute(f"insert into dataStock values('{infoAction['nome']}','{infoAction['logo']}','Nada sobre....','{infoAction['ticker']}',{infoAction['dy']},{infoAction['preco_min_cota']},{infoAction['preco_max_cota']}, {infoAction['ultimo_pagamento']}, {infoAction['oscilacao_cota']},{infoAction['valor_cota']}, '{infoAction['linkSiteRi']}', {infoAction['valorizacaoCota']}, '{infoAction['cnpj']}');")
103 | #print("Ação inserida")
104 | db.commit()
105 | return infoAction
106 |
107 | #------------------------------------------
108 |
109 | def getValuesMoneyBdrs(soup):
110 | infoAction["preco_min_cota"] = soup.find_all("strong")[1].text
111 | infoAction["preco_max_cota"] = soup.find_all("strong")[2].text
112 | infoAction["ultimo_pagamento"] = soup.find_all("span")[33].text
113 | infoAction["valor_cota"] = soup.find('strong').text
114 | infoAction["dy"] = soup.find_all("strong")[3].text
115 | infoAction["valorizacaoCota"] = soup.find_all("strong")[4].text
116 | infoAction["oscilacao_cota"] = soup.find_all('b')[11].text.strip("\n").lstrip().rstrip()
117 | infoAction["cnpj"] = "none"
118 | infoAction["linkSiteRi"] = "none"
119 |
120 | return infoAction
121 |
122 | def getAllValuesBdrs(soup, ticker: str):
123 | comandBasics = BasicData(soup, ticker)
124 | comandBasics.getDatasInternet()
125 | infoAction = getValuesMoneyBdrs(soup)
126 | comandBasics.writeData(infoAction)
127 | return infoAction
128 |
129 | #----------------------------------------
130 |
131 | def getValuesMoneyEtfs(soup):
132 | infoAction["valor_cota"] = soup.find('strong').text
133 | infoAction["dy"] = None
134 | infoAction["oscilacao_cota"] = soup.find_all('b')[11].text.strip("\n").lstrip().rstrip()
135 | infoAction["preco_min_cota"] = soup.find_all("strong")[1].text
136 | infoAction["preco_max_cota"] = soup.find_all("strong")[2].text
137 | infoAction["ultimo_pagamento"] = None
138 | infoAction["cnpj"] = "none"
139 | infoAction["linkSiteRi"] = "none"
140 |
141 | return infoAction
142 |
143 | def getAllValuesEtfs(soup, ticker: str):
144 | comandBasics = BasicData(soup, ticker)
145 | comandBasics.getDatasInternet()
146 | infoAction = getValuesMoneyEtfs(soup)
147 | comandBasics.writeData(infoAction)
148 | return infoAction
149 |
150 | #-----------------------
151 |
152 | def getValuesMoneyStocks(soup):
153 | try:
154 | infoAction["dy"] = soup.find_all("strong")[3].text
155 | except IndexError:
156 | infoAction["dy"] = soup.find("strong")
157 | except:
158 | infoAction["dy"] = 0
159 | infoAction["preco_min_cota"] = soup.find_all("strong")[1].text
160 | infoAction["preco_max_cota"] = soup.find_all("strong")[2].text
161 | infoAction["ultimo_pagamento"] = soup.find_all("span")[32].text
162 | infoAction["valor_cota"] = soup.find('strong').text
163 | infoAction["oscilacao_cota"] = soup.find_all('b')[11].text.strip("\n").lstrip().rstrip()
164 | try:
165 | infoAction["valorizacaoCota"] = soup.find_all("strong", attrs={"class": "value"})[4].text
166 | except:
167 | print(soup.find_all("strong", attrs={"class": "value"}))
168 | infoAction["valorizacaoCota"] = 0.0
169 | try:
170 | infoAction["cnpj"] = soup.find_all("small", attrs={"class": "d-block fs-4 fw-100 lh-4"})[0].text
171 | except:
172 | print(soup.find_all("small", attrs={"class": "d-block fs-4 fw-100 lh-4"}))
173 | infoAction["cnpj"] = None
174 | try:
175 | infoAction["linkSiteRi"] = soup.find_all("a", attrs={"rel": "noopener noreferrer nofollow", "class": "waves-effect waves-light btn btn-small btn-secondary"})[0]["href"]
176 | except:
177 | print(soup.find_all("a", attrs={"rel": "noopener noreferrer nofollow", "class": "waves-effect waves-light btn btn-small btn-secondary"}))
178 | infoAction["linkSiteRi"] = None
179 |
180 | return infoAction
181 |
182 |
183 | def getAllValuesStocks(soup, ticker: str):
184 | comandBasics = BasicData(soup, ticker)
185 | comandBasics.getDatasInternet()
186 | infoAction = getValuesMoneyStocks(soup)
187 | comandBasics.writeData(infoAction)
188 | return infoAction
189 |
190 | #-----------------------
191 |
192 | def getValuesMoneyFiis(soup):
193 | infoAction["preco_min_cota"] = soup.find_all("strong")[1].text
194 | infoAction["preco_max_cota"] = soup.find_all("strong")[2].text
195 | infoAction["ultimo_pagamento"] = soup.find_all("span")[33].text
196 | infoAction["valor_cota"] = soup.find('strong').text
197 | infoAction["dy"] = soup.find_all("strong")[3].text
198 | infoAction["oscilacao_cota"] = soup.find_all('b')[11].text.strip("\n").lstrip().rstrip()
199 | infoAction["valorizacaoCota"] = soup.find_all("strong", attrs={"class": "value"})[4].text
200 | infoAction["cnpj"] = soup.find_all("strong", attrs={"class": "value"})[28].text
201 | a = soup.find_all("strong", attrs={"class": "value"})
202 | i = 0
203 | for x in a:
204 | #print(f"{x} no index: {i}")
205 | i = i+1
206 | infoAction["linkSiteRi"] = "none"
207 |
208 | return infoAction
209 |
210 | def getAllValuesFiis(soup, ticker: str):
211 | comandBasics = BasicData(soup, ticker)
212 | comandBasics.getDatasInternet()
213 | infoAction = getValuesMoneyFiis(soup)
214 | comandBasics.writeData(infoAction)
215 | return infoAction
--------------------------------------------------------------------------------