-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyfinance-dolar-to-real.py
87 lines (71 loc) · 2.71 KB
/
yfinance-dolar-to-real.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
import yfinance as yf
import locale
import pywhatkit as kit
from datetime import datetime
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Set the locale to Brazilian Portuguese for currency formatting
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')
# WhatsApp contact information
account_sid = os.getenv('TWILIO_ACCOUNT_SID')
auth_token = os.getenv('TWILIO_AUTH_TOKEN')
twilio_whatsapp_number = os.getenv('TWILIO_WHATSAPP_NUMBER')
recipient_whatsapp_number = os.getenv('RECIPIENT_WHATSAPP_NUMBER')
# Function to get exchange rate from yfinance
def get_exchange_rate_yfinance(ticker):
ticker_data = yf.Ticker(ticker)
exchange_rate = ticker_data.history(period='1d')
if not exchange_rate.empty:
rate = exchange_rate['Close'].iloc[-1]
return rate
else:
print(f"No data available for {ticker}")
return None
# Function to convert and format the rate
def convert_and_format(rate, currency_name, usd_to_brl):
if currency_name == 'USD to BRL':
converted_rate = rate
else:
converted_rate = rate * usd_to_brl
# Format the number with commas and decimal points
formatted_rate = locale.format_string("%.2f", converted_rate, grouping=True)
return f"R$ {formatted_rate}", print("yFinance converter is done.")
# Function to fetch and format exchange rates
def fetch_exchange_rates():
# Tickers for exchange rates
tickers = {
'USD to BRL': 'USDBRL=X',
'BTC to USD': 'BTC-USD',
'EUR to USD': 'EURUSD=X',
'ETH to USD': 'ETH-USD'
}
rates = {}
usd_to_brl = get_exchange_rate_yfinance('USDBRL=X')
if usd_to_brl is None:
return "Failed to fetch USD to BRL exchange rate."
messages = []
for name, ticker in tickers.items():
rate = get_exchange_rate_yfinance(ticker)
if rate is not None:
formatted_rate = convert_and_format(rate, name, usd_to_brl)
rates[name] = formatted_rate
messages.append(f"Current {name} exchange rate in BRL: {formatted_rate}")
print(f"Current {name} exchange rate in BRL: {formatted_rate}")
return "\n".join(messages)
# Function to send message to WhatsApp
def send_to_whatsapp(message: str):
try:
# Send message via WhatsApp Web
kit.sendwhatmsg_instantly(f"+{recipient_whatsapp_number}", message)
print(f"Sent message to WhatsApp: {message}")
except Exception as e:
print(f"Failed to send message to WhatsApp: {str(e)}")
# Main function
def main():
exchange_rates_message = fetch_exchange_rates()
return exchange_rates_message
send_to_whatsapp(exchange_rates_message)
if __name__ == '__main__':
main()