-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdolar.py
126 lines (102 loc) · 4.26 KB
/
dolar.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
from datetime import date
import enum
from workalendar.america.brazil import BrazilSaoPauloCity
import requests
class ModosDeConsulta(enum.Enum):
PorDia = 1
PorPeriodo = 2
Error = 3
class BancoCentralException(BaseException):
pass
class Dolar:
def __init__(self, mode: ModosDeConsulta, data: date = None, periodo: dict = None):
if (mode == ModosDeConsulta.PorDia):
if self.is_weekend(data):
raise BancoCentralException('Sábado e Domingo não há cotações')
if self.is_holiday(data):
raise BancoCentralException('Feriados não há cotações')
self.setUrl(_mode=mode, _data=data)
elif (mode == ModosDeConsulta.PorPeriodo):
self.setUrl(_mode=mode, _periodo=periodo)
else:
raise BancoCentralException('Tipo de consulta inválida')
req = self.getURL()
resp = req.content.decode("utf-8")
self.json_string = json.loads(resp)
def setUrl(self, _mode: ModosDeConsulta, _data: date = None, _periodo: dict = None):
self.URL_BASE = 'https://olinda.bcb.gov.br/olinda/servico/PTAX/versao/v1/odata/'
if (_mode == ModosDeConsulta.PorDia):
d = _data.strftime('%m-%d-%Y')
self.URL_RESOURCE = 'CotacaoDolarDia(dataCotacao=@dataCotacao)?'
self.URL_PARAM = f'@dataCotacao=%27{d}%27&$format=json'
elif (_mode == ModosDeConsulta.PorPeriodo):
i = _periodo["inicio"].strftime('%m-%d-%Y')
f = _periodo["final"].strftime('%m-%d-%Y')
self.URL_RESOURCE = 'CotacaoDolarPeriodo(dataInicial=@dataInicial,dataFinalCotacao=@dataFinalCotacao)?'
self.URL_PARAM = f'@dataInicial=%27{i}%27&@dataFinalCotacao=%27{f}%27&$top=100&$format=json'
self.URL = f'{self.URL_BASE}{self.URL_RESOURCE}{self.URL_PARAM}'
def getURL(self):
headers = {
"Host": "olinda.bcb.gov.br",
"Connection": "keep-alive",
"Cache-Control": "max-age=0",
"User-Agent": "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Mobile Safari/537.36",
"DNT": "1",
"Content-Type": "application/json;charset=UTF-8;odata.metadata=minimal",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "pt-BR,pt;q=0.9,en-US;q=0.8,en;q=0.7,mt;q=0.6,gl;q=0.5,he;q=0.4,ru;q=0.3,pl;q=0.2,la;q=0.1,es;q=0.1,fr;q=0.1,de;q=0.1,cy;q=0.1,und;q=0.1",
}
try:
req = requests.get(self.URL, headers=headers, timeout=None)
except requests.exceptions.ConnectionError:
raise BancoCentralException('Erro na conexão')
return req
@staticmethod
def is_holiday(day) -> bool:
"""
Retorna True se o dia for feriado
:param day: date
:return: bool
"""
cal = BrazilSaoPauloCity()
if cal.is_working_day(day):
return False
return True
@staticmethod
def is_weekend(day) -> bool:
"""
Retorna True se o dia for um dia de final de semana
:param day: date
:return: bool
"""
if date.weekday(day) in [5, 6]: # 5=saturday or 6=sunday
return True
return False
def dolar_compra_ptax(self) -> float:
"""
Retorna o valor do dólar ptax no momento da compra em real
:return: float
"""
if self.json_string["value"] == []:
return 0
return self.json_string["value"][0]["cotacaoCompra"]
def dolar_venda_ptax(self) -> float:
"""
Retorna o valor do dólar ptax no momento da venda em real
:return: float
"""
if self.json_string["value"] == []:
return 0
return self.json_string["value"][0]["cotacaoVenda"]
def dolar_ultimacotacao(self) -> float:
"""
Retorna a última cotação do dólar
:return: float
"""
if self.json_string["value"] == []:
return 0
return self.json_string["value"][0]["dataHoraCotacao"]