-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathasync_usage.py
More file actions
92 lines (71 loc) · 2.77 KB
/
Copy pathasync_usage.py
File metadata and controls
92 lines (71 loc) · 2.77 KB
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
"""
Exemplo: Usando APIs Assíncronas
Este exemplo demonstra como usar as versões assíncronas das APIs
para busca de dados concorrente (útil para buscar múltiplas séries).
"""
import asyncio
from bcb import http, sgs, currency
from bcb.odata.api import Expectativas
async def fetch_multiple_sgs_series():
"""Buscar múltiplas séries temporais do SGS concorrentemente."""
print("Exemplo 1: Buscando múltiplas séries do SGS concorrentemente")
# Buscar SELIC, CDI e IPCA concorrentemente
codes = [1, 12, 433] # SELIC, CDI, IPCA
df = await sgs.async_get(codes, start="2023-01-01", end="2024-12-31", multi=True)
print("Busca concorrente do SGS concluída")
print(df.head())
print()
async def fetch_multiple_currencies():
"""Buscar taxas de câmbio concorrentemente."""
print("Exemplo 2: Buscando taxas de câmbio concorrentemente")
# Buscar múltiplos símbolos em paralelo
df = await currency.async_get(
["USD", "EUR"],
start="2024-01-01",
end="2024-12-31",
side="both",
)
print("Busca de câmbio assíncrona concluída")
print(df.head())
print()
async def fetch_odata_async():
"""Buscar resultados OData de forma assíncrona."""
print("Exemplo 3: Buscando resultados OData de forma assíncrona")
api = Expectativas()
endpoint = api.get_endpoint("ExpectativasMercadoAnuais")
# Construir e executar consulta de forma assíncrona
query = endpoint.query().filter(endpoint.Indicador == "IPCA").limit(5)
df = await query.async_collect()
print("Busca OData assíncrona concluída")
print(df)
print()
async def concurrent_operations():
"""Executar múltiplas operações assíncronas concorrentemente."""
print("Exemplo 4: Múltiplas operações concorrentes")
# Criar tarefas para execução concorrente
tasks = [
sgs.async_get(1, start="2024-01-01", end="2024-12-31"), # SELIC
sgs.async_get(11, start="2024-01-01", end="2024-12-31"), # CDI
sgs.async_get(433, start="2024-01-01", end="2024-12-31"), # IPCA
]
# Aguardar conclusão de todas as tarefas
results = await asyncio.gather(*tasks)
print(f"Buscadas {len(results)} séries concorrentes")
print("Amostra da primeira série:")
print(results[0].head())
print()
async def main():
"""Executar todos os exemplos assíncronos."""
try:
await fetch_multiple_sgs_series()
await fetch_multiple_currencies()
await fetch_odata_async()
await concurrent_operations()
except Exception as e:
print(f"Erro: {type(e).__name__}: {e}")
finally:
await http.aclose_async_client()
if __name__ == "__main__":
# Executar os exemplos assíncronos
# Nota: o pacote requer Python 3.10+
asyncio.run(main())